repo_name
string
path
string
language
string
license
string
size
int64
score
float64
prefix
string
middle
string
suffix
string
klmitch/nova
nova/conf/novnc.py
Python
apache-2.0
2,021
0
# Copyright (c) 2016 OpenStack Foundation # 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 ...
quired 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 # License for the specific lan
guage governing permissions and limitations # under the License. from oslo_config import cfg novnc_opts = [ cfg.StrOpt('record', help=""" Filename that will be used for storing websocket frames received and sent by a proxy service (like VNC, spice, serial) running on this host. If this is not se...
sodzawic/tk
doc/extcap_example.py
Python
gpl-2.0
9,150
0.036066
#!/usr/bin/env python # Copyright 2014 Roland Knall <rknall [AT] gmail.com> # # Wireshark - Network traffic analyzer # By Gerald Combs <gerald@wireshark.org> # Copyright 1998 Gerald Combs # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # a...
h the following content: ------- @echo off <Path to python interpreter>
<Path to script file> $* ------- Windows is not able to execute Python scripts directly, which also goes for all other script-based formates beside VBScript } """ import os import sys import signal import re import argparse import time import struct import binascii from threading import Thread ERROR_USAGE = 0 ERR...
googleapis/python-dialogflow
samples/generated_samples/dialogflow_generated_dialogflow_v2_session_entity_types_create_session_entity_type_async.py
Python
apache-2.0
1,957
0.002555
# -*- coding: utf-8 -*- # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
ue = "value_value" session_entity_type.entities.synonyms = ['synonyms_value_1', 'synonyms_value_2'] request = dialogflow_v2.CreateSessionEntityTypeRequest(
parent="parent_value", session_entity_type=session_entity_type, ) # Make the request response = await client.create_session_entity_type(request=request) # Handle the response print(response) # [END dialogflow_generated_dialogflow_v2_SessionEntityTypes_CreateSessionEntityType_asyn...
cctaylor/googleads-python-lib
examples/dfp/v201502/activity_group_service/get_active_activity_groups.py
Python
apache-2.0
2,353
0.008075
#!/usr/bin/python # # 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 b...
# Get activity groups by statement. while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) if 'results' in response: # Display results. for activity_group in response['results']:
print ('Activity group with ID \'%s\' and name \'%s\' was found.' % (activity_group['id'], activity_group['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize...
bidossessi/brss
brss/view.py
Python
gpl-2.0
7,267
0.004679
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # # view.py # # Copyright 2011 Bidossessi Sodonon <bidossessi.sodonon@yahoo.fr> # # 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...
, None, (GObject.TYPE_STRING,)), "link-hovered-in" : ( GObject.SignalFlags.RUN_FIRST,
None, (GObject.TYPE_STRING,)), "link-hovered-out" : ( GObject.SignalFlags.RUN_FIRST, None, ()), } def __init__(self, logger): self.log = logger Gtk.VBox.__init__(self, spacing=3) GObject.GObject.__init__(self) # top n...
tensorflow/probability
tensorflow_probability/python/distributions/beta_quotient_test.py
Python
apache-2.0
8,738
0.003319
# Copyright 2020 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
dtype=self.dtype) d = tf.random.uniform( shape=[1, 1, 1, 7], minval=1., maxval=5., seed=test_util.test_seed(), dtype=self.dtype) beta_quotient = tfd.BetaQuotient(a, b, c, d, validate_args=True) # TODO(b/179283344): Increase this to 3e5 when CPU-only gamma s
ampler is # fixed. n = int(3e4) samples = beta_quotient.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(sample_values.shape, (n, 2, 3, 5, 7)) self.assertFalse(np.any(sample_values < 0.0)) self.evaluate( st.assert_true_mean_equal_by_dkwm( ...
Elyjax/Snake
main.py
Python
gpl-2.0
2,389
0.002093
# Importe la biblioteque pygame import pygame # La syntaxe from x import y permet de ne pas devoir ecrire x.y mais juste y # L'etoile indique que l'on importe tout from constantes import * from Sauvegarde import * from jouer import * from options import * pygame.init() sauvegarde = Sauvegarde() try: sauvegarde = ...
("Fonts/font1.ttf", 80) selectionActuelle = 0 menu = ["Jouer", "Options", "Quitter"] nbMenu = len(menu) ouvert = True while ouvert: for event in pygame.event.get(): if event.type == QUIT: ouvert = False if event.type == KEYDOWN:
if event.key == K_ESCAPE: ouvert = False if event.key == K_RETURN: if menu[selectionActuelle] == "Jouer": jouer(fenetre) if menu[selectionActuelle] == "Options": options(fenetre) if menu[selectionAct...
strin/yaotalk
yaoTalkSpeech/yaoTalkSpeech/lm/make_dic.py
Python
gpl-3.0
1,489
0.030893
import jieba # cmu = file('cmu.dic').readlines() # cmu_dict = dict() # for line in cmu: # line = line.decode('utf-8') # line = line[:len(line)-1] # pos = line.find(u' ') # keyword = line[:pos].lower() # content = line[pos:].lower() # cmu_dict[keyword] = content chinese = file('zh_broadcastnews_utf8.dic').readli...
nese_dict[line[0]]+'\n').encode('utf-8')) elif line[0][0]
>= u'\u4e00' and line[0][0] <=u'\u9fa5' : # is chinese words = list(jieba.cut(line[0])) res = list() for word in words: if chinese_dict.has_key(word): res.append(chinese_dict[word]) else: res = None break if res != None: output.write((line[0]+' '.join(res)+'\n').encode('utf-8')) else: ...
nesl/LabSense
Devices/LabSenseModbus/common/modbus.py
Python
bsd-3-clause
4,834
0.004344
import argparse # For reading command line arguments import socket # For TCP Socket: create_connection and htons() import struct # For reading/writing binary data import crc16 # For calculating crc-16 for modbus msgs import logging # For logging events import sys ...
= start + (reg_qty/2) data = data[start:end] #sys.stdout.write("Response: ") #for num in data:
#sys.stdout.write(str(num) + " " ) print "\n" return data """ Channel-level calls for getting data from meters """ # Checks if channels given are valid def checkValidChannel(self, channels): if not all([channel in self.Valid_channels for channel in channels]): ...
christabor-archive/DjangoKonstrukt
konstrukt/konstrukt/forms.py
Python
mit
940
0
from django.db import models as _models from django import forms import models import inspect # Hax, inspect ftw # Get the args and varargs of a given module # for use in the form. DJANGO_FIELD_ARGS = ( (str(name), str(inspect.getargspec(obj.__init__))) for name, obj in inspect.getmembers(_models) if name...
s.ModelForm): class Meta: model = models.View class FieldValueForm(forms.ModelForm): ref_name = _models.CharField( help_text='A reference name for this key', max_length=500) blank = _models.BooleanField() null = _models.BooleanField() class Meta:
model = models.FieldValue class AttachModelsViewForm(forms.Form): pass
LaurentClaessens/phystricks
testing/demonstration/phystricksQEPZooNndwiS.py
Python
gpl-3.0
671
0.059613
# -*- coding: utf8 -*- from phystricks import * def QEPZooNndwiS(): pspict,fig = SinglePicture("QEPZooNndwiS") pspict.dilatation_X(1) pspict.dilatation_Y(1) h=2 A=Point(0,0) B=Point(4,0) C=Point(1,-h) D=Point(6,-h) d1=Segment(A,B).dilatation(1.5) d2=Segment(D,C).dilatatio
n(1.5) I=d1
.midpoint() J=d2.midpoint() seg=Segment(I,J).dilatation(1.3) a1=AngleAOB(A,I,J) a2=AngleAOB(D,J,I) a1.put_mark(0.2,angle=None,text="\( a\)",pspict=pspict) a2.put_mark(0.2,angle=None,text="\( q\)",pspict=pspict) pspict.DrawGraphs(d1,d2,seg,a1,a2) fig.no_figure() fig.conclude() ...
eladnoor/optslope
src/html_writer.py
Python
mit
9,669
0.006412
#!/usr/bin/python """ html_writer.py - Construct HTML pages """ import datetime import os import types import numpy as np import xml.dom.minidom class BaseHtmlWriter: def __init__(self): self.div_counter = 0 pass def relative_to_full_path(self, relpath): raise Exception("class not i...
vg+xml" width="%dpt" height="%dpt" name="%s" frameborder="0" marginwidth="0" marginheight="0"/></object>' # % (fig_fname, width, height, name)) def embed_matplotlib_figure(self, fig, width=None, height=None, name=None): """ Adds a matplotlib figure into the HTML as an inli...
ure in pixels height - the desired height of the figure in pixels name - if not None, the SVG will be written to a file with that name will be linked to from the inline figure """ if name: svg_filename = self.relati...
Pink-Silver/PyDoom
resourcezip/scripts/doom2/__init__.py
Python
bsd-3-clause
410
0.007317
# Cop
yright (c) 2016, Kate Fox # All rights reserved. # # This file is covered by the 3-clause BSD license. # See the LICENSE file in this program's distribution for details. """Game Library for DOOM II: Hell on Earth (doom2.exe, or close to it, maybe)""" game_shortname = "doom2" game_title = "DOOM II: Hell on Earth" game...
ad" ]
mrkiwi-nz/django-helpdesk
helpdesk/urls.py
Python
bsd-3-clause
5,961
0.001174
""" django-helpdesk - A Django powered ticket tracker for small enterprise. (c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details. urls.py - Mapping of URL's to our various views. Note we always used NAMED views for simplicity in linking later on. """ from django.conf.urls import url from ...
value() else: context[key] = value return context app_name = 'helpdesk' urlpatterns = [ url(r'^dashboard/$', staff.dashboard, name='dashboard'), url(r'^tickets/$', staff.ticket_list, name='list'), url(r'^tickets/update/$', ...
ket_id>[0-9]+)/$', staff.view_ticket, name='view'), url(r'^tickets/(?P<ticket_id>[0-9]+)/followup_edit/(?P<followup_id>[0-9]+)/$', staff.followup_edit, name='followup_edit'), url(r'^tickets/(?P<ticket_id>[0-9]+)/followup_delete/(?P<followup_id>[0-9]+)/$', staff.followup...
ijat/Hotspot-PUTRA-Auto-login
PyInstaller-3.2/tests/functional/modules/pyi_get_datadir.py
Python
gpl-3.0
1,315
0.003042
#----------------------------------------------------------------------------- # Copyright (c) 2015-2016, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this s...
by # Pyinstaller or simply run from the Python interpreter.
def get_data_dir(): # Some tests need input files to operate on. There are two cases: if getattr(sys, 'frozen', False): # 1. Frozen: rely on gettemp to find the correct directory both in # onefile and in onedir modes. return gettemp('data') else: # 2. Not frozen: rely on ...
Sutto/cloud-custodian
c7n/resources/iam.py
Python
apache-2.0
66,755
0.000599
# Copyright 2016-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
'remove': client.remove_user_from_group } for r in resources: try: op_map[state](GroupName=group_name, UserName=r['UserName']) except client.exceptions.NoSuchEntityException: continue @resources.regist
er('iam-policy') class Policy(QueryResourceManager): class resource_type(TypeInfo): service = 'iam' arn_type = 'policy' enum_spec = ('list_policies', 'Policies', None) id = 'PolicyId' name = 'PolicyName' date = 'CreateDate' config_type = "AWS::IAM::Policy" ...
uniite/pyirc
gcm/gcm.py
Python
mit
4,198
0.005002
import urllib import urllib2 import json GCM_URL = 'https://android.googleapis.com/gcm/send' class GCMException(Exception): pass class GCMMalformedJsonException(GCMException): pass class GCMConnectionException(GCMException): pass class GCMAuthenticationException(GCMException): pass class GCMTooManyRegIdsException(GC...
e(data) if time_to_live: payload['time_to_live'] = time_to_live payload['collapse_key'] = collapse_key if json: payload = json.dumps(payload) return payload def make_request(self, data, is_json=True): headers = { 'Authorization': 'k...
if is_json: headers['Content-Type'] = 'application/json' if not is_json: data = urllib.quote_plus(data) req = urllib2.Request(GCM_URL, data, headers) try: response = urllib2.urlopen(req).read() except urllib2.HTTPError as e: if e...
atados/atados-ovp
api/channels/default/tests/test_tasks.py
Python
agpl-3.0
4,585
0.002621
from django.test import TestCase from django.test.utils import override_settings from django.utils import timezone from django.core import mail from ovp.apps.users.tests.fixture import UserFactory from ovp.apps.organizations.tests.fixture import OrganizationFactory from ovp.apps.projects.models import Project, Apply...
start_date=timezone.now(), end_date=timezone.now(), project=self.project, object_channel='default' ) Apply.objects.create(user=self.user, project=self.project, object_channel='default')
self.assertEqual(mail.outbox[2].subject, 'Conta pra gente como foi sua experiência?') self.assertIn('>test project<', mail.outbox[2].alternatives[0][0]) def test_publishing_project_schedules_ask_about_experience_to_organization(self): """ Assert cellery task to ask organization about...
pypingou/pagure
pagure/hooks/pagure_hook.py
Python
gpl-2.0
8,617
0
# -*- coding: utf-8 -*- """ (c) 2014-2018 - Copyright Red Hat Inc Authors: Pierre-Yves Chibon <pingou@pingoured.fr> """ from __future__ import unicode_literals, absolute_import import logging import pygit2 import sqlalchemy as sa import wtforms try: from flask_wtf import FlaskForm except ImportError: ...
e.lib.query import pagure.lib.git from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project _log = logging.getLogger(__name__) pagure_config = pagure.config.reload_config() class PagureTable(BASE): """ Stores information about the pagure hook deployed on a project. Table -- h...
n( sa.Integer, sa.ForeignKey("projects.id", onupdate="CASCADE", ondelete="CASCADE"), nullable=False, unique=True, index=True, ) active = sa.Column(sa.Boolean, nullable=False, default=False) project = relation( "Project", remote_side=[Project.id], ...
balloob/netdisco
netdisco/discoverables/cambridgeaudio.py
Python
mit
473
0
""" Discover Cambridge Audio StreamMagic devices. """ from . import SSDPDiscover
able class Discoverable(
SSDPDiscoverable): """Add support for discovering Cambridge Audio StreamMagic devices.""" def get_entries(self): """Get all Cambridge Audio MediaRenderer uPnP entries.""" return self.find_by_device_description({ "manufacturer": "Cambridge Audio", "deviceType": "urn:schem...
thomasmauerhofer/search-engine
src/setup/check_for_currupt_references.py
Python
mit
2,124
0.000942
from engine.api import API from engine.utils.printing_utils import progressBar from setup.utils.datastore_utils import repair_corrupt_reference, link_references_to_paper def remove_duplicates_from_cited_by(): print("\nRemove Duplicates") api = API() papers = api.get_all_paper() for i, paper in enumer...
id) api.client.update_paper(paper) continue cited_paper = api.get_paper(cited_paper_id) cited_paper_refs = [ref.get_paper_id() for ref
in cited_paper.references if ref.get_paper_id()] if cited_paper_refs.count(paper.id) == 0: print() paper.cited_by.remove(cited_paper_id) api.client.update_paper(paper) link_references_to_paper(cited_paper, paper, api) def perform_checks(): ...
Madpilot0/EVE-Farm
app.py
Python
gpl-3.0
14,554
0.032431
#!/usr/bin/env python from flask import Flask, render_template, request, jsonify, session, redirect, escape, url_for import MySQLdb import bcrypt from esipy import App from esipy import EsiClient from esipy import EsiSecurity from esipy.exceptions import APIException import time import json import requests import datet...
(plexPricen * 500))/1000000,2) return "<a href='https://market.madpilot.nl/static/graph/farm-month.png'>Projected pro
fits: (min)"+str(nonoptimal)+"mil - (max)"+str(profit)+"mil </a>" except: return "<a href='https://market.madpilot.nl/static/graph/farm-month.png'>Projected profits: (min)"+str(0)+"mil - (max)"+str(0)+"mil </a>" def isk(extractors): extractorID = "40519" injectorID = "40520" plexID = "44992" priceList = [] url...
Brickstertwo/pretty-markdown
utils/whitespace_utils.py
Python
mit
542
0.005535
import re def trim_nonbreaking_whitespace(text): """Trims non-breaking whitespace from the end of eac
h line in the given text. Non-breaking whitespace refers to the markdown syntax of places two spaces at the end of a line to signify a break. """ pattern = re.compile(r'^.*\S $') text = text.split('\n') # use split(...) since splitlines() doesn't keep trailing blank lines if any are present te...
text = '\n'.join(text) return text
loandy/billy
billy/tests/importers/test_merge.py
Python
bsd-3-clause
1,328
0
from __future__ import print_function from billy.importers.utils import merge_legislators import json import os def _load_test_data(test_name): test_data = os.path.join(os.path.dirname(os.path.dirname(__file__)), "leg_merge_test_data") folder = "%s/%s/" % (test_data, test_name) ...
test_vanishing_photo(): _test_logic("vanishing_photo_url") def test_order(): _test_logic("
test_legi_order")
NonVolatileComputing/arrow
python/pyarrow/filesystem.py
Python
apache-2.0
8,926
0
# 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 # "License"); you may not u...
f.pathsep.join(args) def stat(self, path): """ Returns ------- stat : dict """ raise NotImplementedError('FileSystem.stat') def rm(self, path, recursive=False): """ Alias for FileSystem.delete """ retur
n self.delete(path, recursive=recursive) def mv(self, path, new_path): """ Alias for FileSystem.rename """ return self.rename(path, new_path) def rename(self, path, new_path): """ Rename file, like UNIX mv command Parameters ---------- p...
Architektor/PySnip
venv/lib/python2.7/site-packages/twisted/internet/_dumbwin32proc.py
Python
gpl-3.0
12,502
0.00272
# -*- test-case-name: twisted.test.test_process -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ http://isometri.cc/strips/gates_in_the_head """ import os # Win32 imports import win32api import win32con import win32event import win32file import win32pipe import win32process import win3...
vironment to the current environment - this is # necessary because certain
operations are only supported on Windows # if certain environment variables are present. env = os.environ.copy() env.update(environment or {}) cmdline = quoteArguments(args) # TODO: error detection here. See #2787 and #4184. def doCreate(): self.hProcess, ...
nburn42/tensorflow
tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py
Python
apache-2.0
5,248
0.002668
# Copyright 2017 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...
eForClassifier(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2
learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() classifier = estimator.GradientBoostedDecisionTreeClassifier( learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, confi...
rfleschenberg/django-shop
shop/admin/order.py
Python
bsd-3-clause
8,117
0.002957
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import patterns, url from django.contrib import admin from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models.fields import Field, FieldDoesNotExist from django.forms import...
ount") def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False def get_customer_link(self, obj): try: url = reverse('admin:shop_customerproxy_change', args=(obj.customer.pk,)) return format_html('...
except NoReverseMatch: return format_html('<strong>{0}</strong>', obj.customer.get_username()) get_customer_link.short_description = pgettext_lazy('admin', "Customer") get_customer_link.allow_tags = True def get_search_fields(self, request): fields = super(BaseOrderAdmin, self).get_sear...
Southpaw-TACTIC/TACTIC
src/pyasm/biz/clipboard.py
Python
epl-1.0
4,282
0.003503
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
item.set_value("category", "select") item.commit() add_to_selected = classmethod(add_to_selected)
def clear_selected(cls): # make sure the sobjects exist search = Search("sthpw/clipboard") search.add_filter("category", "select") search.add_user_filter() items = search.get_sobjects() for item in items: item.delete() clear_selected = classmethod(cl...
Agent007/deepchem
contrib/dragonn/models.py
Python
mit
16,267
0.001967
from __future__ import absolute_import, division, print_function import matplotlib import numpy as np import os import subprocess import sys import tempfile matplotlib.use('pdf') import matplotlib.pyplot as plt from dragonn.metrics import ClassificationResult from keras.layers.core import (Activation, Dense, Dropout, F...
# input_references_list=input_references) # return deeplift_scores # # def in_silico_mutagenesis(self, X): # """ # Returns (num_task, num_samples, 1, num_bases, sequence_length) ISM score array. # """ # mutagenesis_scores = np.empty(X.shape + (self.num_tasks,), dtype=np.float32) # wild_type_...
np.newaxis] # for sequence_index, (sequence, wild_type_prediction) in enumerate( # zip(X, wild_type_predictions)): # mutated_sequences = np.repeat( # sequence[np.newaxis], np.prod(sequence.shape), axis=0) # # remove wild-type # arange = np.arange(len(mut...
simeonf/sfpython
sfpython/flatpage_admin_override/admin.py
Python
apache-2.0
783
0.005109
from django.contrib import admin from django import forms from django.core.urlresolvers import reverse from django.contrib.flatpages.admin import FlatPageAdmin from django.contrib.flatpages.models import FlatPage from tinymce.widgets import
TinyMCE class TinyMCEFlatPageAdmin(FlatPageAdmin): def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'content': return db_field.formfield(widget=TinyMCE( attrs={'cols': 80, 'rows': 30}, mce_attrs={'external
_link_list_url': reverse('tinymce.views.flatpages_link_list')}, )) return super(TinyMCEFlatPageAdmin, self).formfield_for_dbfield(db_field, **kwargs) admin.site.unregister(FlatPage) admin.site.register(FlatPage, TinyMCEFlatPageAdmin)
jeffrobots/senseRF
app/add_data.py
Python
bsd-2-clause
2,377
0.002524
from datetime import datetime import peewee import itertools import random from time import sleep from models import Sensor, SensorData, init_db sensors = [{"id": 1, "location": "Living Room", "late_updated": datetime.now(), "name": "greenpi", "refresh_rate": 30} ...
, sensor_type): if sensor_type is "temperature": value = self.get_rand_temperature() elif sensor_type is "humidity": value = self.get_rand_humidity() elif sensor_type is "light": value
= self.get_rand_light() updated_at = datetime.now() data = {"sensor_type": sensor_type, "sensor": self.record, "sensor_val": value, "updated_at": datetime.now()} record = SensorData(**data) record.save() @staticmethod def get_rand_temperature(): return r...
scieloorg/access_stats
setup.py
Python
bsd-2-clause
1,792
0.001116
#!/usr/bin/env python import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.rst')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() install_requires = [ 'requests>=2.8.1', ...
"Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Programming Language :: Python", "Operating System :: POSIX :: Linux", "Topic :: System", "Topic :: Services", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: ...
"git+https://github.com/scieloorg/thriftpy-wrap@0.1.1#egg=thriftpywrap" ], include_package_data=True, zip_safe=False, setup_requires=["nose>=1.0", "coverage"], tests_require=test_requires, install_requires=install_requires, test_suite="nose.collector", entry_points="""\ [paste.ap...
DavidTingley/ephys-processing-pipeline
installation/klustaviewa-0.3.0/klustaviewa/stats/tests/test_indexed_matrix.py
Python
gpl-3.0
7,015
0.010549
"""Unit tests for stats.cache module.""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- from nose.tools import raises import numpy as np from klustaviewa.stats.indexed_matrix import Index...
x[:, 7] == 30) matrix[[2, 3], 5] = 40 assert np.all(matrix[[2, 3], 5] == 40) matrix[[2, 3], [5, 7]] = 5
0 assert np.all(matrix[[2, 3], [5, 7]] == 50) def test_indexed_matrix_8(): indices = [2, 3, 5, 7] matrix = IndexedMatrix(indices=indices, shape=(4, 4, 10)) x = np.random.rand(10) matrix[7, 7] = x assert np.array_equal(matrix[7, 7], x) assert np.array_equal(matrix[7,...
vnsofthe/odoo
addons/base_geolocalize/models/res_partner.py
Python
agpl-3.0
3,783
0.002379
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013_Today OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms ...
cept Exception, e: raise osv.except_osv(_('Network error'), _('Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).') % e) if result['status'] != 'OK': return None
try: geo = result['results'][0]['geometry']['location'] return float(geo['lat']), float(geo['lng']) except (KeyError, ValueError): return None def geo_query_address(street=None, zip=None, city=None, state=None, country=None): if country and ',' in country and (country.endswith(' of') o...
srounet/pystormlib
pystormlib/structure.py
Python
mit
485
0
import ctypes class MPQFileData(ctypes.Structure): _fields_ = [ ('filename',
ctypes.c_char * 1024), ('plainpath', ctypes.c_char_p), ('hashindex', ctypes.c_int, 32), ('blockindex', ctypes.c_int, 32), ('filesize', ctypes.c_int, 32), ('fileflags', ctypes.c_int, 32), ('compsize', ctypes.c_int, 32), ('filetimelo', ctypes.c_int, 32), ('...
', ctypes.c_int, 32), ('locale', ctypes.c_int, 32) ]
ernitron/radio-server
radio-server/server.py
Python
mit
26,943
0.008165
#!/usr/bin/env python3 """ My radio server application For my eyes only """ #CREATE TABLE Radio(id integer primary key autoincrement, radio text, genre text, ur
l text); uuid='56ty66ba-6kld-9opb-ak29-0t7f5d294686' # Import CherryPy global namespace import os import sys import time import socket import cherrypy import sqlite3 as lite import re import subprocess from random import shuffle # Globals version = "4.2.1" database = "database.db" player = 'omxplayer' header = '''<!...
> <html lang="en"> <head> <title>My Radio Web Server</title> <meta name="generator" content="Vim"> <meta charset="UTF-8"> <link rel="icon" type="image/png" href="/static/css/icon.png" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="/static/js/jquery-2.0.3.min.js"></scrip...
databuild/databuild
databuild/operations/columns.py
Python
bsd-3-clause
1,932
0.003623
from decimal import Decimal from dateutil import parser as date_parser import six def update_column(context, sheet, column, facets=None, values=None, expression=None): assert values or expression workbook = context['workbook'] callable_or_values = expression and expression or values sheet = workbook...
rkbook'] sheet = workbook.sheets[sheet] expression = lambda row: row[old_name] add_column(context, sheet, new_nam
e, expression) sheet.remove_column(old_name) def to_float(context, sheet, column, facets=None): expression = lambda x: float(x[column]) update_column(context, sheet, column, facets, expression=expression) def to_integer(context, sheet, column, facets=None): expression = lambda x: int(x[column]) ...
jaswal72/hacker-rank
Python/Basic Data Types/List Comprehensions.py
Python
mit
226
0.030973
if __name__ == '__main__': x = int(raw_input()) y = int(raw_input()) z = int(raw_input()) n = int(raw_inp
ut()) print ( [ [i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k != n]
)
atomic83/youtube-dl
youtube_dl/extractor/npr.py
Python
unlicense
2,966
0.001349
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_urllib_parse from ..utils import ( int_or_none, qualities, ) class NprIE(InfoExtractor): _VALID_URL = r'http://(?:www\.)?npr\.org/player/v2/mediaPlayer\.html\?.*\bid=(?P<id>\d+)' _TESTS = [{ ...
9930', 'ext': 'mp3', 'title': 'Your Mercy is Boundless (Bazum en Qo gtutyunqd)', 'duration': 402,
}, }], }] def _real_extract(self, url): playlist_id = self._match_id(url) config = self._download_json( 'http://api.npr.org/query?%s' % compat_urllib_parse.urlencode({ 'id': playlist_id, 'fields': 'titles,audio,show', 'format'...
Patola/Cura
plugins/VersionUpgrade/VersionUpgrade34to35/__init__.py
Python
lgpl-3.0
2,372
0.004637
# 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 VersionUpgrade34to35 if TYPE_CHECKING: from UM.Application import Application upgrade = VersionUpgrade34to35.VersionUpgrade34to35() def getMetaData() -> Dict...
gVersion, "location": {"./extruders"} }, "definiti
on_changes": { "get_version": upgrade.getCfgVersion, "location": {"./definition_changes"} }, "quality_changes": { "get_version": upgrade.getCfgVersion, "location": {"./quality_changes"} }, "quality": { ...
mathLab/RBniCS
rbnics/reduction_methods/base/nonlinear_time_dependent_rb_reduction.py
Python
lgpl-3.0
786
0.005089
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later from rbnics.reduction_methods.base.nonlinear_rb_reduction import NonlinearRBReduction from rbnics.reduction_methods.base.time_dependent_rb_reduction import TimeDependen
tRBReduction from rbnics.utils.decorators import PreserveClassName, RequiredBaseDecorators @RequiredBaseDecorators(NonlinearRBReductio
n, TimeDependentRBReduction) def NonlinearTimeDependentRBReduction(DifferentialProblemReductionMethod_DerivedClass): @PreserveClassName class NonlinearTimeDependentRBReduction_Class(DifferentialProblemReductionMethod_DerivedClass): pass # return value (a class) for the decorator return Nonline...
pjdelport/feincms
feincms/module/medialibrary/forms.py
Python
bsd-3-clause
2,901
0.005171
# ------------------------------------------------------------------------ # coding=utf-8 # ------------------------------------------------------------------------ from __future__ import absolute_import import os from django import forms from django.utils.translation import ugettext_lazy as _ from feincms import s...
__init__(*args, **kwargs) self.fie
lds['parent'].queryset = self.fields['parent'].queryset.exclude(pk=self.instance.pk) # ------------------------------------------------------------------------ class MediaFileAdminForm(forms.ModelForm): class Meta: model = MediaFile widgets = { 'file': AdminFileWithPreviewWidget } def __init__...
amdouglas/OpenPNM
test/unit/Geometry/models/PoreSeedTest.py
Python
mit
1,410
0
import OpenPNM import scipy as sp class PoreSeedTest: def setup_class(self): self.net = OpenPNM.Network.Cubic(shape=[5, 5, 5]) self.geo = OpenPNM.Geometry.GenericGeometry(network=self.net, pores=self.net.Ps, ...
(self): f = OpenPNM.Geometry.models.pore_seed.random self.geo.models.add(propname='pore.seed', model=f, seed=0, num_range=[0.1, 2]) assert sp.amax(sel
f.geo['pore.seed']) > 1.9 assert sp.amin(self.geo['pore.seed']) > 0.1 def test_spatially_correlated(self): f = OpenPNM.Geometry.models.pore_seed.spatially_correlated self.geo.models.add(propname='pore.seed', model=f, weights=[2, 2, 2])...
effigies/mne-python
examples/plot_read_forward.py
Python
bsd-3-clause
2,405
0.004158
""" ==================================================== Read a forward operator and display sensitivity maps ==================================================== """ # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) p...
size=14) for ax, picks, ch_type in zip(axes, [picks_meg, picks_eeg], ['meg', 'eeg']): im = ax.imshow(leadfield[picks, :500], origin='lower', aspect='auto', cmap='RdBu_r') ax.set_title(ch_type.upper()) ax.set_xlabel('sources') ax.set_ylabel('sensors') plt.colorbar(im, ax=ax, cmap='RdBu...
# Show sensitivity of each sensor type to dipoles in the source space grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed') mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed') eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed') plt.figure() plt.hist([grad_map.data.ravel(), mag_map...
freedesktop-unofficial-mirror/telepathy__telepathy-idle
tests/twisted/channels/join-muc-channel-bouncer.py
Python
lgpl-2.1
1,912
0.002615
""" Test connecting to a IRC channel when prompted by a bouncer """ from idletest import exec_test from servicetest import ( EventPattern, assertEquals, call_async, make_channel_proxy ) from constants import * def test_join_bouncer(q, conn, stream, room): stream.sendJoin(room) new_channels = EventPatter...
) return path def test(q, bus, conn, stream): conn.Connect() q.expect_many( EventPattern('dbus-signal', signal='StatusChanged', args=[1, 1]), EventPattern('irc-connected')) q.expect('dbus-signal', signal='SelfHandleChanged', args=[1L]) q.expect('dbus-signal', signal=...
a JOIN. path = test_join_bouncer(q, conn, stream, CHANNEL_NAME) # We PART. chan = make_channel_proxy(conn, path, 'Channel') chan.RemoveMembers([self_handle], "bye bye cruel world", dbus_interface=CHANNEL_IFACE_GROUP) q.expect('dbus-signal', signal='MembersChanged') # The bouncer initia...
MCLConsortium/mcl-site
src/jpl.mcl.site.knowledge/src/jpl/mcl/site/knowledge/publicationfolder.py
Python
apache-2.0
575
0.001745
# encoding: utf-8 u'''MCL — Publication Folder''' from ._base import IIngestableFolder, Ingestor, IngestableFolderView from .interfaces import IPublication from five import grok class IPublicationFolder(IIngestableFolder): u'''Folder containing publications.''' class PublicationIngestor(Ingestor): u'''RDF...
ion.''' grok.context(IPublicationFolder)
def getContainedObjectInterface(self): return IPublication class View(IngestableFolderView): u'''View for an publication folder''' grok.context(IPublicationFolder)
rfarley3/Kibana
kibana/mapping.py
Python
mit
17,896
0.000056
#!/usr/bin/env python from __future__ import absolute_import, unicode_literals, print_function import re try: from urllib2 import urlopen, HTTPError except ImportError: # Python 3 from urllib.request import urlopen from urllib.error import HTTPError import json import requests import time import sys ...
return self._index_pattern @index_pattern.setter def index_pattern_setter(self, index_pattern): self._index_pattern = index_pattern self.update_urls() @property def host(self): return self._host @host.setter def host_setter(self, host): self._host = host ...
ibana': try: search_results = urlopen(self.get_url).read().decode('utf-8') except HTTPError: # as e: # self.pr_err("get_field_cache(kibana), HTTPError: %s" % e) return [] index_pattern = json.loads(search_results) # Results...
wettenhj/mytardis
tardis/urls/download.py
Python
gpl-3.0
1,724
0.00058
''' Download URLs ''' from django.conf.urls import url from tardis.tardis_portal.download import ( download_datafile, streaming_download_datafiles, streaming_download_experiment, streaming_download_dataset, download_api_key ) download_urls = [ url(r'^datafile/(?P<datafile_id>\d+)/$', down
load_datafile, name='tardis
.tardis_portal.download.download_datafile'), url(r'^datafiles/$', streaming_download_datafiles, name='tardis.tardis_portal.download.streaming_download_datafiles'), url(r'^experiment/(?P<experiment_id>\d+)/$', streaming_download_experiment, name='tardis.tardis_portal.download.streaming_do...
pombredanne/python-cdb
setup.py
Python
gpl-2.0
1,203
0.029925
#! /usr/bin/env python SRCDIR = "src" SRCFILES = map(lambda f: SRCDIR + '/' + f + '.c', ["cdbmodule","cdb","cdb_make","cdb_hash", "uint32_pack","uint32_unpack"]) from distutils.core import setup, Extension setup (# Distribution meta-data name = "python-cdb", version = "...
"cdbmodule", SRCFILES, include_dirs=[ SRCDIR + '/' ], extra_compile_args=['-fPIC'], )
], url = "http://pilcrow.madison.wi.us/", )
xhqu1981/pymatgen
dev_scripts/chemenv/view_environment.py
Python
mit
5,095
0.002159
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals """ Script to visualize the model coordination environments """ __author__ = "David Waroquiers" __copyright__ = "Copyright 2012, The Materials Project" __vers...
print('Point #{:d} : {} {} {}'.format(ipoint, repr(point[0]), repr(point[1]), repr(point[2]))) print('Algorithms used :') for ialgo, algo in enumerate(cg.algorithms): print('Algorithm #{:d} :'.format(ialgo)) print(algo) print('') # Visualize the separatio...
hms]): test = raw_input('Enter index of the algorithm for which you want to visualize the plane : ') if test != '': try: ialgo = int(test) algo = cg.algorithms[ialgo] sepplane = True except: ...
iansprice/wagtail
wagtail/tests/snippets/models.py
Python
bsd-3-clause
2,344
0.000853
from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from w...
ecorator(mo
dels.Model): pass # A snippet model that inherits from index.Indexed can be searched on @register_snippet class SearchableSnippet(index.Indexed, models.Model): text = models.CharField(max_length=255) search_fields = [ index.SearchField('text'), ] def __str__(self): return self.t...
badjr/pysal
pysal/core/IOHandlers/tests/test_arcgis_swm.py
Python
bsd-3-clause
1,219
0.00082
import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(se...
88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self):
w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct...
Imperat/SSU-Courses
ssu-formal-languages/pda/pda_exceptions.py
Python
apache-2.0
91
0.043956
class UnknownSymbolExcep
tion(Exception): pass class PD
ACrashException(Exception): pass
gtaylor/btmux_battlesnake
battlesnake/plugins/contrib/pg_db/dict_conn.py
Python
bsd-3-clause
319
0
import psycopg2 import psyco
pg2.extras from txpostgres import txpostgres def dict_connect(*args, **kwargs): kwargs['connection_factory'] = psycopg2.extras.DictConnection return psycopg2.connect(*args, **kwargs) class DictConnection(txpostgres.Connection): connectio
nFactory = staticmethod(dict_connect)
massmutual/py4jdbc
tests/test_Cursor.py
Python
bsd-3-clause
3,513
0.000569
import pytest from py4jdbc.dbapi2 import connect, Connection from py4jdbc.resultset import ResultSet from py4jdbc.exceptions.dbapi2 import Error def test_connect(gateway): url = "jdbc:derby:memory:testdb;create=true" conn = connect(url, gateway=gateway) cur = conn.cursor() rs = cur.execute("select * ...
ows of result set have the correct class. ''' cur = derby.cursor() rs = cur.execute("select * from SYS.SYSTABLES") assert all({isinstance(row, rs.Row) for row in rs.fetchall()}) def test_Cursor__iter__(derby): cur = der
by.cursor() rs = cur.execute("select * from SYS.SYSTABLES") assert all({isinstance(row, rs.Row) for row in rs}) def test_Cursor__iter__(derby): cur = derby.cursor() rs = cur.execute("select * from SYS.SYSTABLES") # Exhaust all rows. list(rs) assert rs.fetchone() == None def test_close_an...
francois-a/fastqtl
python/run_FastQTL_threaded.py
Python
gpl-3.0
5,608
0.005171
#!/usr/bin/env python3 # Author: Francois Aguet import argparse import os import numpy as np import subprocess import gzip import multiprocessing as mp import contextlib from datetime import datetime import tempfile import glob @contextlib.contextmanager def cd(cd_path): saved_path = os.getcwd() os.chdir(cd_pa...
--fdr {} -o .'.format(chunk_list_file.name, log_list_file.name, args.prefix, args.fdr) if args.qvalue_lambda: cmd += ' --qvalue_lambda {}'.format(args.qvalue_lambda) if args.permute: cmd += ' --permute' subprocess.check_call(cmd
, shell=True) # remove chunk files for f in chunk_files + log_files: os.remove(f)
obi-two/Rebelion
data/scripts/templates/object/tangible/lair/structure/exterior/shared_lair_cave_giant_exterior_krayt_dragon.py
Python
mit
504
0.043651
#### 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/lair/structure/exterior/shared_lair_cave_giant_exterior_krayt_dragon.iff" result.attr...
#### END MODIFICATIONS #### return result
meejah/AutobahnPython
examples/twisted/websocket/echo_endpoints/client.py
Python
mit
3,397
0.001178
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software with...
ater(1, self.sendHello) class EchoClientFactory(WebSocketClientFactory): """ Example WebSocket client factory. This creates a new instance of our protocol when the client connects to the server. """ protocol = EchoClientProtocol if __name__ == '__main__': import sys
import argparse from twisted.python import log from twisted.internet.endpoints import clientFromString # parse command line arguments ## parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true", help="Enable debug output.") pars...
migueln/PySQM
config.py
Python
gpl-3.0
3,526
0.005672
#!/usr/bin/env python ''' PySQM configuration File. ____________________________ Copyright (c) Mireia Nievas <mnievas[at]ucm[dot]es> This file is part of PySQM. PySQM 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 Founda...
itude = 680 _observatory_horizon = 10 # If Sun is below this altitude, the program will take data _device_shorttype = 'SQM' # Device STR in t
he file _device_type = 'SQM_LU' # Device type in the Header _device_id = _device_type + '-' + _observatory_name # Long Device lame _device_locationname = 'Villalbilla/Spain - Observatorio GURUGU' # Device location in the world _data_supplier = 'Mireia Nievas / Universidad Complutense de Madrid' # Data suppli...
sebaxtian/raspberrypi3
lighting_led/gpio_button.py
Python
mit
478
0.002092
''' Ejemplo de imprimir un mensaje c
uando un boton es presionado. Fuente: https://www.raspberrypi.org/learning/physical-computing-with-python/worksheet/ Fecha: mar dic 6 20:11:21 COT 2016 Version: 1.0 ''' from gpiozero import Button # Usando el GP2 controlamos el boton button
= Button(2) # El programa espera hasta que el boton sea presionado button.wait_for_press() # El programa imprime un mensaje print('Se Presiona El Boton') ''' Ejecutar: python gpio_button.py '''
green-latte/geopy.jp
info.py
Python
mit
401
0.044888
# package information. INFO = dict( name = "geopy.jp", description = "Geocoding library for Python.", author = "Green Latte", author_email = "k.takeuchi@war
rantee.co.jp", license = "MIT License", url = "https://github.com/green-latte/geopy.jp", classifiers = [ "Program
ming Language :: Python :: 3.4", "License :: OSI Approved :: MIT License" ] )
rleigh-dundee/openmicroscopy
components/tools/OmeroPy/src/omero/install/logs_library.py
Python
gpl-2.0
6,637
0.011903
#!/usr/bin/env python """ Function for parsing OMERO log files. The format expected is defined for Python in omero.util.configure_logging. Copyright 2010 Glencoe Software, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt :author: Josh Moore <josh@glencoesoftware.co...
ut import logging import sys import os import re def parse_time(value): """ parse the time format used by log4j into seconds (float) since the epoch """ parts = value.split(",") value = part
s[0] millis = float(parts[1]) / 1000.0 t = mktime(strptime(value, "%Y-%m-%d %H:%M:%S")) t = float(t) t += millis return t class log_line(object): """ 2009-04-09 15:11:58,029 INFO [ ome.services.util.ServiceHandler] (l.Server-6) Meth: interface ome.api.IQuery.findByQuery 0123...
GoogleCloudPlatform/datacatalog-connectors-bi
google-datacatalog-tableau-connector/src/google/datacatalog_connectors/tableau/scrape/metadata_api_helper.py
Python
apache-2.0
5,757
0
#!/usr/bin/python # # 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 o
btain 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 distribut
ed 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 requests from google.datacatalog_connectors.tableau.scrape import \ authenticator, constants, metadata_ap...
ruishihan/R7-with-notes
src/host/python/GSM/SB.py
Python
apache-2.0
1,203
0.099751
from Burst import Burst import numpy as np class SB(Burst): def __init__(self): self.syncbits = [ 0x01, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01...
st( s
elf, frame, osr ): return Burst.channelEst( self, frame, self.training_seq, osr )
mitodl/ccxcon
webhooks/migrations/0001_initial.py
Python
agpl-3.0
624
0.003205
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Webhook', fields=[ ('id', models.Au...
('secret', m
odels.CharField(default=uuid.uuid4, max_length=32)), ('enabled', models.BooleanField(default=True)), ], ), ]
orashi/PaintsPytorch
models/base_model.py
Python
mit
9,627
0.002493
import numpy as np import torch import os import sys import functools import torch.nn as nn from torch.autograd import Variable from torch.nn import init import torch.nn.functional as F import torchvision.models as M class GANLoss(nn.Module): def __init__(self, target_real_label=1.0, target_fake_label=0.0, ...
norm_layer(ngf * 2)] self.up3 = nn.Sequential(*up) up = [nn.ConvTranspose2d(ngf * 3, ngf, kernel_size=4, stride=2, padding=1), norm_layer(ngf)] self.up2 = nn.Sequential(*up) self.up1 = nn.ConvTranspose2d(int(ngf * 1.5), 3
, kernel_size=4, stride=2, padding=1) self.linear = nn.Linear(4096, 2048) U_weight_init(self) def forward(self, input, VGG): x1 = F.leaky_relu(self.down1(input), 0.2, True) x2 = F.leaky_relu(self.down2(x1), 0.2, True) x3 = F.leaky_relu(self.down3(x2), 0.2, True) x4...
dsiddharth/access-keys
keystone/contrib/kds/cli/manage.py
Python
apache-2.0
1,896
0.001582
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 ...
st if necessary. """ retur
n migration.db_sync(CONF.command.version) def add_command_parsers(subparsers): parser = subparsers.add_parser('db_version') parser.set_defaults(func=do_db_version) parser = subparsers.add_parser('db_sync') parser.set_defaults(func=do_db_sync) parser.add_argument('version', nargs='?') command_op...
dodobas/osm-export-tool2
core/wsgi.py
Python
bsd-3-clause
402
0
""" WSGI config for osm-export-tool2 project. It exposes the WSGI callable as a module-level variable named ``appl
ication``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.s
ettings.prod") application = get_wsgi_application()
tobes/munge
munge/cli.py
Python
agpl-3.0
6,778
0.000148
import argparse import os.path import config import definitions import sa_util import csv_util def import_module(args): from dependencies import dependencies_manager tables = [] for module in args.module: if not args.updateonly: definitions.get_importer(module)(verbose=args.verbose) ...
create_views', ] parser
= argparse.ArgumentParser( description='Command line interface for munge' ) parser.add_argument('-v', '--verbose', action='count', default=0) subparsers = parser.add_subparsers(help='commands', dest='command') for command in commands: subparsers.add_parser(command) import_csv_parse...
rgommers/statsmodels
statsmodels/stats/multitest.py
Python
bsd-3-clause
16,540
0.00266
'''Multiple Testing and P-Value Correction Author: Josef Perktold License: BSD-3 ''' from statsmodels.compat.python import range from statsmodels.compat.collections import OrderedDict import numpy as np #============================================== # # Part 1: Multiple Tests and P-Value Correction # #=========...
ct = a <= alphaf elif method.lower() in ['fdr_bh', 'fdr_i', 'fdr_p', 'fdri', 'fdrp']: # delegate, call with sorted pvals reject, pvals_corrected = fdrcorrection(pvals, alpha=alpha, method='indep', is_s...
pvals_cor
zero-os/0-orchestrator
pyclient/zeroos/orchestrator/client/EnumClusterStatus.py
Python
apache-2.0
143
0
from enum import Enum class EnumClusterStatus(Enum): empty =
"empty" deploying = "deploying" ready = "ready" er
ror = "error"
myles/django-issues
src/issues/models.py
Python
bsd-3-clause
3,687
0.033903
from django.db import models from django.conf import settings from django.db.models import permalink from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from django.contrib.comments.models import Comment from django.contrib.contenttypes.generic import GenericRelation class Ve...
_('Assigned')), (3, _('Resolved')
), (4, _('Feedback')), (5, _('Closed')), (6, _('Rejected')), ) ISSUE_PRIORITIES = ( (1, _('Low')), (2, _('Normal')), (3, _('High')), (4, _('Urgent')), (5, _('Immediate')), ) # TODO I want this it first check the `settings.py` file for customization. ISSUE_STATUS_CHOICES = ISSUE_STATUSES ISSUE_PRIORITIY_CHOICE...
TamiaLab/PySkCode
skcode/utility/smileys.py
Python
agpl-3.0
9,460
0.001375
""" SkCode smileys replacement utility code. """ import re from html import escape as escape_html from urllib.parse import urljoin # Default emoticons map DEFAULT_EMOTICONS_MAP = ( ('<3', 'heart.png'), (':heart:', 'heart.png'), (":')", 'joy.png'), (':")', 'joy.png'), (":'-)", 'joy.png'), ('...
ons base URL EMOTICONS_BAS
E_URL_ATTR_NAME = 'EMOTICONS_BASE_URL' # Document attribute name for storing the emoticons HTML class EMOTICONS_HTML_CLASS_ATTR_NAME = 'EMOTICONS_HTML_CLASS' def setup_smileys_replacement(document_tree, base_url, emoticons_map=DEFAULT_EMOTICONS_MAP, html_class='emoticons'): """ Setup the document for emotico...
vsilent/smarty-bot
alembic/versions/3734300868bc_add_account_id.py
Python
mit
391
0.005115
"""add accoun
t id Revision ID: 3734300868bc Revises: 3772e5bcb34d Create Date: 2013-09-30 18:07:21.729288 """ # revision identifiers, used by Alembic. revision = '3734300868bc' down_revision = '3772e5bcb34d' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('account_profile', sa.Column('account_i...
ef downgrade(): pass
kdebrab/pandas
asv_bench/benchmarks/index_object.py
Python
bsd-3-clause
5,080
0
import numpy as np import pandas.util.testing as tm from pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex, Float64Index) from .pandas_vb_common import setup # noqa class SetOperations(object): goal_time = 0.2 params = (['datetime', 'date_string', 'int', 'strings'], ...
) def time_append_int_list(self): self.int_idx.append(self.int_idxs) def time_append_obj_list(self): self.obj_idx.append(self.object_idxs) class Indexing(object):
goal_time = 0.2 params = ['String', 'Float', 'Int'] param_names = ['dtype'] def setup(self, dtype): N = 10**6 self.idx = getattr(tm, 'make{}Index'.format(dtype))(N) self.array_mask = (np.arange(N) % 3) == 0 self.series_mask = Series(self.array_mask) self.sorted = se...
fangxingli/hue
desktop/libs/liboozie/src/liboozie/submittion2_tests.py
Python
apache-2.0
12,471
0.010424
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
licable 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 logging from django.contrib.auth.models import User from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_true, assert_not_equal from hadoop import cluster, pse...
jhermann/cookiecutter
setup.py
Python
bsd-3-clause
3,212
0.001868
#!/usr/bin/env python import os import sys try: from setuptools import setup, Command except ImportError: from distutils.core import setup, Command version = "1.0.1" if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit()...
ments = ['binaryornot>=0.2.0', 'jinja2>=2.7', 'PyYAML>=3.10', 'click<4.0'] test_requirements = ['pytest'] # Add Python 2.6-specific dependencies if sys.version_info[:2] < (2, 7): requirements.append('ordereddict') requirements.append('simplejson') test_requirements.append('unittest2') # Add Python 2.6 and...
e no Python 3-specific dependencies to add long_description = readme + '\n\n' + history if sys.argv[-1] == 'readme': print(long_description) sys.exit() class PyTest(Command): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): self.pytest_args...
tombstone/models
official/recommendation/ncf_keras_main.py
Python
apache-2.0
19,975
0.00766
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(tf.keras.layers.Layer): """Custom layer of metrics for NCF model.""" def __init__
(self, match_mlperf): super(MetricLayer, self).__init__() self.match_mlperf = match_mlperf def get_config(self): return {"match_mlperf": self.match_mlperf} @classmethod def from_config(cls, config, custom_objects=None): return cls(**config) def call(self, inputs, training=False): logits, ...
dongsenfo/pymatgen
pymatgen/analysis/chemenv/coordination_environments/tests/test_structure_environments.py
Python
mit
12,696
0.005986
#!/usr/bin/env python __author__ = 'waroquiers' import unittest import os import json import numpy as np import shutil from monty.tempfile import ScratchDir from pymatgen.util.testing import PymatgenTest from pymatgen.analysis.chemenv.coordination_environments.structure_environments import StructureEnvironments fr...
ot.patches[0].get_xy()), [[1., 1.], [1., 0.99301365], [1.00179228, 0.99301365], [1.00179228, 1.], ...
[[1., 0.99301365], [1., 0.], [1.00179228, 0.], [1.00179228, 0.99301365], [1., 0.99301365]]) np.testin...
samsam2310/LINE
line/api.py
Python
bsd-3-clause
11,264
0.003107
# -*- coding: utf-8 -*- """ line.client ~~~~~~~~~~~ LineClient for sending and receiving message from LINE server. :copyright: (c) 2014 by Taehoon Kim. :license: BSD, see LICENSE for more details. """ import rsa import requests try: import simplejson as json except ImportError: import json...
ncoding("utf-8") #from curve import CurveThrift from curve import CurveThrift from curve.ttypes import TalkException from curve.ttypes import ToType, ContentType class LineAPI(object): """This class is a wrapper of LINE API """ LINE_DOMAIN = "http://gd2.line.naver.jp" LINE_HTTP_URL = LINE_D...
LINE_DOMAIN + "/P4" LINE_CERTIFICATE_URL = LINE_DOMAIN + "/Q" LINE_SESSION_LINE_URL = LINE_DOMAIN + "/authct/v1/keys/line" LINE_SESSION_NAVER_URL = LINE_DOMAIN + "/authct/v1/keys/naver" CERT_FILE = ".line.crt" ip = "127.0.0.1" version = "5.1.2" com_name = "" rev...
Prototype-X/Zabbix-Network-Weathermap
mapping.py
Python
gpl-3.0
14,264
0.002384
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # __author__ = 'maximus' from PIL import Image, ImageDraw, ImageFont from datetime import datetime import math import os import logging log = logging.getLogger(__name__) class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls ...
tangle((self.x, self.y, self.rect_xy[8][2] + 60, self.rect_xy[8][3] + 5), outline='black', fill='white') draw.text((self.x + 5, self.y + 5), self.text_label, fill='black', font=self.font) for i in range(0, 9): draw.rectangle(self.rect_xy[i], fill=self.palette[i], outline=self.palette[i]) ...
, font=self.font) if self.dt: self.draw_datetime(draw) def draw_datetime(self, draw): self.dt_obj = datetime.now() self.date_now = datetime.strftime(self.dt_obj, "%d.%m.%Y") self.time_now = datetime.strftime(self.dt_obj, "%H:%M:%S") draw.rectangle((self.x, self.r...
VadimMalykh/courses
deeplearning1/nbs/vgg16.py
Python
apache-2.0
4,286
0.008866
from __future__ import division, print_function import os, json from glob import glob import numpy as np from scipy import misc, ndi
mage from scipy.ndimage.interpolation import zoom import keras from
keras import backend as K from keras.layers.normalization import BatchNormalization from keras.utils.data_utils import get_file from keras.models import Sequential from keras.layers.core import Flatten, Dense, Dropout, Lambda from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D from keras.layers.p...
kingctan/django-health-check
health_check/__init__.py
Python
mit
1,966
0.002035
# This file is heavily inspired from the django admin autodiscover __version_info__ = { 'major': 1, 'minor': 0, 'micro': 2, 'releaselevel': 'final', 'serial': 0 } def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an i...
if module_has_submodule(mod, 'plugin_health_check'): raise def get_
version(short=False): assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final') vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final' and not short: vers.ap...
tensorflow/lingvo
lingvo/core/gshard_layers_test.py
Python
apache-2.0
8,710
0.007577
# Lint as: python3 # Copyright 2021 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 ...
s_t = tf.reshape(inputs, (b, beam, seq_len, dim1, dim2))[:, :, i] # Copies state to theta. theta_t = gshard_layers.StateLayer.UpdateTheta(l, thet
a_t, state_t, t=i) tf.logging.info(f'theta_{i}: {repr(theta_t)}') # Updates theta inplace. out_t = l.FProp(theta_t, inputs_t) # Copies theta to state. state_t = gshard_layers.StateLayer.UpdateState(l, theta_t, state_t) tf.logging.info(f'state_{i}: {repr(state_t)}') decode_ou...
ganga-devs/ganga
ganga/GangaCore/test/GPI/TestExceptions.py
Python
gpl-3.0
2,047
0.00342
from
GangaCore.testlib.decorators import add_config @add_config([('TestingFramework', 'AutoCleanup', False)]) def test_all_exceptions(gpi): """Create all exceptions and make sure they behave correctly""" import GangaCore.Core.exceptions test_str = "My Test Error" def exception_test(err_name
): """Run tests on the given exception""" err_type = getattr(GangaCore.Core.exceptions, err_name) err_obj = err_type(test_str) assert test_str in str(err_obj) err_list = ["GangaException", "GangaFileError", "PluginError", "ApplicationConfigurationError", "Application...
mrmrwat/pylsner
pylsner/gui.py
Python
mit
2,624
0.001143
import cairo from gi.repository import Gtk from gi.repository import Gdk from pylsner import plugin class Window(Gtk.Window): def __init__(self): super(Window, self).__init__(skip_pager_hint=True, skip_taskbar_hint=True, ) ...
rea = Gtk.DrawingArea() drawing_area.
connect('draw', self.redraw) self.refresh_cnt = 0 self.add(drawing_area) self.connect('destroy', lambda q: Gtk.main_quit()) self.widgets = [] self.show_all() def refresh(self, force=False): self.refresh_cnt += 1 if self.refresh_cnt >= 60000: se...
apache/libcloud
libcloud/common/gandi_live.py
Python
apache-2.0
7,334
0
# 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 "License"); you may not use ...
" Determine if our request was successful. For the Gandi Live response class, tag all responses as successful and raise appropriate Exceptions from parse_body. :return: C
{True} """ return True def parse_body(self): """ Parse the JSON response body, or raise exceptions as appropriate. :return: JSON dictionary :rtype: ``dict`` """ json_error = False try: body = json.loads(self.body) exce...
ChawalitK/odoo
addons/event_sale/models/sale_order.py
Python
gpl-3.0
3,419
0.004095
# -*- coding: utf-8 -*- from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" @api.multi def action_confirm(self): self.ensure_one() res = super(SaleOrder, self).action_confirm() self.order_line._update_registrations(confirm=True) if ...
om_qty attribute that will be the number of registrations linked to
this line. This method update existing registrations and create new one for missing one. """ Registration = self.env['event.registration'] registrations = Registration.search([('sale_order_line_id', 'in', self.ids)]) for so_line in self.filtered('event_id'): existing_registra...
tingletech/md5s3stash
md5s3stash.py
Python
bsd-3-clause
13,467
0.001188
#!/usr/bin/env python """ md5s3stash content addressable storage in AWS S3 """ from __future__ import unicode_literals import sys import os import argparse import tempfile import urllib2 import urllib import urlparse import base64 import logging import hashlib import basin import boto import magic from PIL import I...
se.ArgumentParser( description='content addressable storage in AWS S3') parser.add_argument('url
', nargs='+', help='URL or path of source file to stash') parser.add_argument('-b', '--bucket_base', nargs="?", help='this must be a unique name in all of AWS S3') parser.add_argument('-s', '--bucket_scheme', nargs="?", default="simple", ch...
jawilson/home-assistant
homeassistant/components/stream/__init__.py
Python
apache-2.0
13,852
0.001083
"""Provide functionality to stream video source. Components use create_stream with a stream source (e.g. an rtsp url) to create a new Stream object. Stream manages: - Background work to fetch and decode a stream - Desired output formats - Home Assistant URLs for viewing a stream - Access tokens for URLs for vi...
bc import Mapping import logging import re import secrets import threading import time from types import MappingProxyType from typing import cast import voluptuous as vol from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import Event, HomeAssistant, callback from homeass
istant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType from .const import ( ATTR_ENDPOINTS, ATTR_SETTINGS, ATTR_STREAMS, CONF_LL_HLS, CONF_PART_DURATION, CONF_SEGMENT_DURATION, DOMAIN, HLS_PROV...
diablo-rewriter/diablo
obfuscation/diversity_engine/iterative_diablo/compare_and_evaluate.py
Python
gpl-2.0
9,057
0.036215
#!/usr/bin/python # This research is supported by the European Union Seventh Framework Programme (FP7/2007-2013), project ASPIRE (Advanced Software Protection: Integration, Research, and Exploitation), under grant agreement no. 609734; on-line at https://aspire-fp7.eu/. */ # The development of portions of the code co...
efix="") config_simple.extend_IDA_analysis = False config_simple.experiment_dir = "" config_extended = diablo_normalization.NormalizationConf(trace_prefix="") config_extended.extend_IDA_analysis = True config_extended.experiment_dir = "" def get_traces(vs): experiment = experiments.Experiment(config_simple, tmp_b...
diablo_normalization.generate_dynamic_info(experiment, unnormalized_filename( experiment, v )) # get_traces([1,2]) # For now, we just experiment with different normalizations on fixed 2 soplex binaries name = "" smallname = "" binary_pair = 0 only_do = None #only_do = [ 15 ] #only_do = [ 11, 12, 13, 14, 15, 16, 17 ]...
zxtstarry/src
book/cwp/geo2008IsotropicAngleDomainElasticRTM/marm2allA/marm2.py
Python
gpl-2.0
4,919
0.038219
from rsf.proj import * from math import * import fdmod,pcsutil,wefd def data(par): # ----------------------------------------------------------
-- Fetch('vp_marmousi-ii.segy',"marm2") Fetch('vs_marmousi-ii.segy',"marm2") Fetch('density_marmousi-ii.segy',"marm2") # ------------------------------------------------------------ for file in ('vp','vs','ro'): if(file=='ro'): ifile='density_marmousi-ii.segy' ...
b'+file],ifile, ''' segyread tape=$SOURCE tfile=${TARGETS[1]} hfile=${TARGETS[2]} bfile=${TARGETS[3]} ''',stdin=0) Flow('_'+file,'z'+file, ''' put o1=0 d1=0.001249 label1=%(lz)s unit1=%(...
edac-epscor/nmepscor-data-collection-form
application/builder/forms.py
Python
mit
2,579
0.001163
import warnings from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate UNMASKED_DIGITS_TO_SHOW = 6 mask_password = lambda p: "%s%s" % (p[:UNMASKED_DIGITS_TO_SHOW], "*" * max(len(p) - UNMASKED_DIGITS_TO_SHOW, 0)) # Originally from django.contr...
use authDrupal self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_log...
: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) return self.cleaned_data def check_for_test_cookie(self): warnings.warn("check_for_test_cookie is deprecated; ensure your login " ...
rynecarbone/Pokerly
Deck.py
Python
mit
2,273
0.036516
from random import shuffle from operator import attrgetter ### class Card: '''Class to define type of cards''' suits = {'H': '\u2661', 'D': '\u2662', 'S': '\u2660', 'C': '\u2663'} faces = {11: 'J', 12: 'Q', 13: 'K', 14: 'A'} #_________________...
q__(other) #______________________ def __gt__(self, other): return self.value > other.val
ue #_____________________ def __lt__(self, other): return self.value < other.value #_______________ def __repr__(self): return '[{0:>2}{1} ]'.format(self.name, self.symbol) #___________________ def dump_state(self): print('{0}{1} (value={2}, suit={3})'.format(self.name,self.symbol,self.value,sel...
funkyeah/tiddlyweb
tiddlyweb/serializations/__init__.py
Python
bsd-3-clause
3,732
0
""" Turn entities to and fro various representations. This is the base Class and interface Class used to transform strings of various forms to model objects and model objects to strings of various forms. """ from tiddlyweb.serializer import NoSerializationError from tiddlyweb.model.tiddler import string_to_tags_list ...
ialize a Bag into this serializer's form. """ raise NoSerializationError def as_tiddler(self, tiddler, input_string): """ Take input_string, which is a serialized tiddler and turn it into a Tiddler (if possible
). """ raise NoSerializationError def list_tiddlers(self, bag): """ Provided a bag, output the included tiddlers. """ raise NoSerializationError def list_recipes(self, recipes): """ Provided a List of RecipeS, make a serialized list of th...
FederatedAI/FATE
python/fate_arch/storage/hdfs/_table.py
Python
apache-2.0
5,051
0.000594
# # Copyright 2019 The FATE 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 appli...
tor(): yield line def _destroy(self): self._hdfs_client.delete_file(self.path) def _count(self): count = 0 if self._meta.get_count(): return self._meta.get_count() for _ in self._as_generator(): count += 1 return count def _save_...
ss, partitions=None, name=None, namespace=None, **kwargs ): self._hdfs_client.copy_file(src=self.path, dst=address.path) table = StorageTable( address=address, partitions=partitions, name=name, namespace=namespace, **kwargs, ) ...
magistral-io/MagistralPython
src/magistral/client/util/JksHandler.py
Python
mit
3,975
0.013082
''' Created on 16 Sep 2016 @author: rizarse ''' import jks, textwrap, base64 from os.path import expanduser import os.path import atexit import shutil from os import makedirs class JksHandler(object): def __init__(self, params): pass @staticmethod def writePkAndCerts(ks, token): ...
print("-----END %s-----" % _type_) for _, pk in ks.private_keys.items(): print("Private key: %s" % pk.alias) if pk.algorithm_oid == jks.util.RSA_ENCRYPTION_OID: print_pem(pk.pkey, "RSA PRIVATE KEY") else: print_pem(pk.pkey_pkcs8, "PRIVATE...
in ks.certs.items(): print("Certificate: %s" % c.alias) print_pem(c.cert, "CERTIFICATE") print() for _, sk in ks.secret_keys.items(): print("Secret key: %s" % sk.alias) print(" Algorithm: %s" % sk.algorithm) print(" Key size: %d ...
SophieBartmann/Faust-Bot
FaustBot/Communication/PingObservable.py
Python
gpl-3.0
831
0.003619
import _thread from FaustBot.Communication.Observable import Observable class PingObservable(Observable): def input(self, raw_data, connection): data = {'raw': raw_data, 'server': ''} if raw_data.find('PING') == 0: data['server'] = raw_data.split('PING ')[1] else:
return # hier kann noch gecheckt werden, ob data wirklich ein server ist, der ping haben will, oder sonstwas # finde heraus, w
er zurückgepingt werden muss, und ob das überhaupt ein ping-request ist oder ein user sich # einen spass erlaubt hat self.notify_observers(data, connection) def notify_observers(self, data, connection): for observer in self._observers: _thread.start_new_thread(observer.__class__...
jacyn/burst
webapp/userman/backends.py
Python
mit
1,074
0.004655
from django.contrib.auth.models import User #import advantage.iam import sys class CustomUserBackend(object): def authenticate(self, username=None, password=None): print >> sys.stderr, "starting to authenticate.. " try: user = User.objects.get(username=username) except User.o...
except User.DoesNotExist: user = User(username=username, password='') user.is_staff = False user.is_superuser = False user.save() return user return None def get_user(self, us
er_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None