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 |
|---|---|---|---|---|---|---|---|---|
m4ll0k/Spaghetti | lib/handler/attacks.py | Python | gpl-3.0 | 687 | 0.024745 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# @name: Wascan - Web Application Scanner
# @repo: https://github.com/m4ll0k/Wascan
# @author: Momo Outaadi (M4ll0k)
# @license: See the file 'LICENSE.txt
import os
import sys
from lib.utils.dirs import *
from lib.utils.printer import *
from importlib import impor... | th('.').split('lib')[0],'plugins/attacks/')
def Attacks(kwargs,url,data):
info('Starting attacks module...')
for file in dirs(path):
file = file.split('.py')[0]
__import__('plugins.attacks.%s'%(file))
module = sys.modul | es['plugins.attacks.%s'%(file)]
module = module.__dict__[file]
module(kwargs,url,data).run() |
burnpanck/chaco | chaco/abstract_colormap.py | Python | bsd-3-clause | 2,253 | 0.001775 | """ Defines the base class for color maps
"""
from traits.api import Enum, HasTraits, Instance
from data_range_1d import DataRange1D
class AbstractColormap(HasTraits):
"""
Abstract class for color maps, which map from scalar values to color values.
"""
# The data-space bounds of the mapper.
range... | = Enum('rgba', 'rgb')
def map_screen(self, val):
"""
map_screen(val) -> color
Maps an array of values to an array of colors. If the input array is
NxM, the returned array is NxMx3 or NxMx4, depending on the
**color_depth** setting.
"""
raise NotImplemented... | an array of values containing the colors mapping to the values
in *ary*. If the input array is NxM, the returned array is NxMx3 or
NxMx4, depending on the **color_depth** setting.
"""
# XXX this seems bogus: by analogy with AbstractMapper, this should map
# colors to data values... |
equalitie/vengeance | src/util/__init__.py | Python | agpl-3.0 | 38 | 0.026316 | #the file is | left | intentionally blank
|
frishberg/django | tests/view_tests/tests/test_specials.py | Python | bsd-3-clause | 880 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import SimpleTestCase, override_settings
@override_settings(ROOT_URLCONF='view_tests.generic_urls')
class URLHandling(SimpleTestCase):
"""
Tests for URL handling in view | s and responses.
"""
redirect_target = "/%E4%B8%AD%E6%96%87/target/"
def test_nonascii_redirect(self):
"""
A non-ASCII argument to HttpRedirect is handled properly.
"""
response = self.client.get('/nonascii_redirect/')
self.assertRedirects(response, self.redirect_tar... |
A non-ASCII argument to HttpPermanentRedirect is handled properly.
"""
response = self.client.get('/permanent_nonascii_redirect/')
self.assertRedirects(response, self.redirect_target, status_code=301)
|
watchdogpolska/django-mptt | mptt/fields.py | Python | mit | 1,592 | 0.004397 | """
Model fields for working with trees.
"""
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from mptt.forms import TreeNodeChoiceField, TreeNodeMultipleChoiceField
__all__ = ('TreeForeignKey', 'TreeOneToOneField', 'TreeManyToManyField')
class TreeForeignKey(mo... | mfield(**kwargs)
class TreeOneToOneField(models.OneToOneField):
def formfield(self, **kwargs):
kwargs.setdefault('form_class', TreeNodeChoiceField)
return | super(TreeOneToOneField, self).formfield(**kwargs)
class TreeManyToManyField(models.ManyToManyField):
def formfield(self, **kwargs):
kwargs.setdefault('form_class', TreeNodeMultipleChoiceField)
return super(TreeManyToManyField, self).formfield(**kwargs)
# South integration
if 'south' in settings... |
mfx9/molaris-tools | MolarisTools/Scripts/ParseScans.py | Python | gpl-3.0 | 8,470 | 0.016411 | #-------------------------------------------------------------------------------
# . File : ParseScans.py
# . Program : MolarisTools
# . Copyright : USC, Mikolaj Feliks (2015-2018)
# . License : GNU GPL v3.0 (http://www.gnu.org/licenses/gpl-3.0.en.html)
#--------------------------------------------------... | mumIndex=-1, logging=True):
"""Parse a potential energy surface scan."""
steps = []
file | s = glob.glob ("%s*.out" % pattern)
files.sort ()
for fn in files:
mof = MolarisOutputFile (filename=fn, logging=False)
if logging:
print ("# . Parsing file %s ..." % fn)
collect = []
for step in mof.qmmmComponentsI:
Eqmmm = step.Eqmmm
collect.... |
endlessm/chromium-browser | third_party/catapult/third_party/gsutil/gslib/tests/testcase/unit_testcase.py | Python | bsd-3-clause | 16,831 | 0.004872 | # -*- coding: utf-8 -*-
# Copyright 2013 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 require... | derr += ''.join(self.accumulated_stderr)
_AttemptToCloseSysFd(sys.stdout)
_AttemptToCloseSysFd(sys.stderr)
sys.stdout = self.stdout_sav | e
sys.stderr = self.stderr_save
os.unlink(self.stdout_file)
os.unlink(self.stderr_file)
_id = six.ensure_text(self.id())
if self.is_debugging and stdout:
print_to_fd('==== stdout {} ====\n'.format(_id), file=sys.stderr)
print_to_fd(stdout, file=sys.stderr)
print_to_fd('==== end st... |
bungoume/mecab-web-api | text_analysis/text_analysis/wsgi.py | Python | mit | 403 | 0 | """
WSGI config for text_analysis project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more informatio | n 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("DJAN | GO_SETTINGS_MODULE", "text_analysis.settings")
application = get_wsgi_application()
|
SINGROUP/pycp2k | inputparser.py | Python | lgpl-3.0 | 14,369 | 0.003549 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Provides functions for creating a python classes from the cp2k_input.xml
file.
"""
import xml.etree.cElementTree as cElementTree
import utilities
import textwrap
#===============================================================================
def validify_section(st... | keytype = keyname.get("type")
name = keyname.text
newname = validify_keyword(name)
if keytype == "default":
default_name = newname
if name.startswith("__"):
visible = False
# Now stor | e the keywords as class attributes
if visible:
for keyname in keyword.findall("NAME"):
name = keyname.text
newname = validify_keyword(name)
# Create original attribute for the default keyname
if newname == default_name:
... |
t3rm1n4l/ramcloud | bindings/python/ramcloud.py | Python | isc | 11,657 | 0.003174 | # Copyright (c) 2009-2010 Stanford University
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISC... | , POINTER(version),
buf, len, POINTER(len)]
so.rc_read.restype = status
so.rc_remove.argtypes = [client, table, id, rejectRules,
POINTER(v | ersion)]
so.rc_remove.restype = status
so.rc_write.argtypes = [client, table, id, buf, len, rejectRules,
POINTER(version)]
so.rc_write.restype = status
return so
def _ctype_copy(addr, var, width):
ctypes.memmove(addr, ctypes.addressof(var), width)
return addr + w... |
anhstudios/swganh | data/scripts/templates/object/building/poi/base/shared_base_poi_medium.py | Python | mit | 451 | 0.046563 | #### 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 = Building()
result.template = "object/building/poi/base/shared_base_poi_medium.iff"
result.attribute_template_id = -1
result.stfNam... |
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
bdevorem/GGNoRe | sort_fun.py | Python | gpl-3.0 | 1,009 | 0.005946 | #!/usr/bin/env python2.7
#naive implementation of a program that sorts function definitions alphabetically
import sys
import fileinput
DEBUG = False
function = ''
first_fun = None
output = []
funs = {}
bracket_count = 0
for line in f | ileinput.input():
bracket_count += line.count("{")
if bracket_count:
# we are in a function
if not function:
function = line.split("(")[0].split()[-1]
else:
function = None
if function:
if first_fun == None:
first_fun = len(output)
if func... | )
bracket_count -= line.count("}")
if DEBUG:
print(funs)
output_funs = []
for k in sorted(funs.keys()):
for l in funs[k]:
output_funs.append(l)
if first_fun != None:
output = output[:first_fun] + output_funs + output[first_fun:]
for l in output:
sys.stdout.write(l)
|
lahwaacz/qutebrowser | scripts/asciidoc2html.py | Python | gpl-3.0 | 10,901 | 0.000092 | #!/usr/bin/env python3
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2017 Florian Bruhin (The Compiler) <[email protected]>
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pub... | with open(modified_src, 'r', encoding='utf-8') as header_file:
header = header_file.read()
header += "\n\n"
with open(src, 'r', encoding='utf-8') as infp:
| outfp.write("\n\n")
hidden = False
found_title = False
title = ""
last_line = ""
for line in infp:
if line.strip() == '// QUTE_WEB_HIDE':
assert not hidden
hidden = True
elif line.str... |
fzenke/morla | scripts/compute_feature_vectors.py | Python | mit | 1,674 | 0.022103 | #!/usr/bin/python3
from __future__ import print_function
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import sys
import scipy
from tqdm import tqdm
import django
from django.utils imp... | end = min((k+1)*stride,features.shape[0])
A = scipy.sparse.coo_matrix(features[start:end])
Feature.objects.bulk_create( [ Feature( article=articles[int(i+k*stri | de)], index=int(j), value=float(v)) for i,j,v in zip(A.row, A.col, A.data) ] )
if __name__ == "__main__":
# Feature.objects.all().delete()
print("Finding articles without features...")
articles, data = get_articles_without_features()
if not len(data):
sys.exit()
print("Computing features... |
vacuus/kilonull | kilonull/templatetags/theming.py | Python | lgpl-3.0 | 901 | 0 | from django import template
# from kilonull.conf import BlogConf
from kilonull.models import Menu, MenuItem
from kilonull.settings import SETTINGS
import re
register = template.Library()
@register.simple_tag
def blog_title():
return SETT | INGS['BLOG_TITLE']
# Generate HTML for the header menu.
# Use a regex (path) to check if the current page is in the menu. If it is,
# apply the active class.
@register.simple_tag
def get_menu(menu_slug, curr_page):
html = ""
menu_items = MenuItem.objects.filter(menu__slug=menu_slug) \
.order_by("order... | += "<li"
match = path.match(item.link_url)
if match and match.group(1) == curr_page:
html += " class='active'"
html += "><a href='%s'>%s</a></li>" % (item.link_url, item.link_text)
return html
|
gnumdk/lollypop | lollypop/player_userplaylist.py | Python | gpl-3.0 | 4,223 | 0 | # Copyright (c) 2014-2017 Cedric Bellegarde <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | if force:
current_track = self._next_track
else:
current_track = self._current_track
if self._user_playlist and\
| current_track.id in self._user_playlist:
idx = self._user_playlist.index(current_track.id)
if idx + 1 >= len(self._user_playlist):
self._next_context = NextContext.STOP
idx = 0
else:
idx += 1
track = Track(self._us... |
divio/django-commontranslations | django_commontranslations/management/commands/makemessages_unique.py | Python | bsd-3-clause | 4,136 | 0.003627 | # -*- coding: utf-8 -*-
import glob
import os
import polib
from django import VERSION as DJANGO_VERSION
from django.core.management.commands.makemessages import (
Command as OriginalMakeMessagesCommand)
from django.utils import translation
from django.utils.translation.trans_real import CONTEXT_SEPARATOR
class Co... | _import_settings = True
def handle_noargs(self, *args, **options):
from django.conf import settings
super(Command, self).handle_noargs(*args, **options)
locale = options.get('locale')
domain = options.get('domain')
verbosity = int(options.get('verbosity') | )
process_all = options.get('all')
# now that we've built the regular po files, we mark any translations that are already translated elsewhere
# as obsolete. If there is already a translation in the local po file, we keep it.
localedir = os.path.abspath('locale')
locales = []
... |
anurag03/integration_tests | cfme/ansible/credentials.py | Python | gpl-2.0 | 18,975 | 0.002951 | # -*- coding: utf-8 -*-
"""Page model for Automation/Anisble/Credentials"""
import attr
from navmazing import NavigateToAttribute, NavigateToSibling
from widgetastic_patternfly import BootstrapSelect, Button, Dropdown, Input
from widgetastic_manageiq import ParametrizedSummaryTable, Table, PaginationPane
from widgetast... | .//input[@title="Vault password"][2]')
@credential_form.register("Amazon")
class CredentialFormAmazonView(View):
access_key = Input(locator='.//input[@title=" | AWS Access Key for this credential"]')
secret_key = Input(locator='.//input[@title="AWS Secret Key for this credential"][2]')
sts_token = Input(
locator='.//input[@title="Security Token Service(STS) Token for this credential"][2]')
@credential_form.register("VMware")
class Credentia... |
tpokorra/pykolab | pykolab/cli/cmd_list_user_subscriptions.py | Python | gpl-3.0 | 3,424 | 0.009638 | # -*- coding: utf-8 -*-
# Copyright 2010-2013 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.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 ... | ptions(*args, **kw):
my_option_group = conf.add_cli_parser_option_group(_("CLI Options"))
my_option_group.add_option( '--raw',
dest = "raw",
acti | on = "store_true",
default = False,
help = _("Display raw IMAP UTF-7 folder names"))
my_option_group.add_option( '--unsubscribed',
dest = "unsubscribed",
action = "store_true",
... |
RhubarbSin/arin-reg-rws | org_delete.py | Python | mit | 839 | 0 | #!/usr/bin/env python
import sys
import argparse
import regrws
import regrws.method.org
try:
from apikey import APIKEY
except ImportError:
APIKEY = None
epilog = 'API key can be omitted if APIKEY is defined in apikey.py'
parser = argparse.ArgumentParser(epilog=epilog)
pa | rser.add_argument('-k', '--key', help='ARIN API key',
required=False if APIKEY else True, dest='api_key')
parser.add_argument('-s', '--source-address', help='Source IP address')
parser.add_argument('org_handle', metavar='ORG_HANDLE')
args = parser.parse_args()
if args.api_key:
APIKEY = args.api_... | )
except regrws.restful.RegRwsError as exception:
print exception.args
|
Azure/azure-sdk-for-python | sdk/appplatform/azure-mgmt-appplatform/azure/mgmt/appplatform/v2021_09_01_preview/operations/_skus_operations.py | Python | mit | 5,833 | 0.004115 | # 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 ... | hould create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.appplatform.v2021_09_01_preview.models
:param client: Client for service re | quests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = s... |
jrwiegand/tdd-project | functional_tests/test_list_item_validation.py | Python | mit | 2,652 | 0 | from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def get_error_element(self):
return self.browser.find_element_by_css_selector('.has-error')
def test_cannot_add_empty_list_items(self):
# Edith goes to the home page and accidentally tries to submit
# an empty... | self.get_item_input_box().send_keys('Buy milk\n')
self.check_for_row_in_list_table('1: Buy milk')
# Perversely, she now decides to submit a second blank list item
self.get_item_input_box().send_keys('\n')
# She receives a similar warning on the list page
| self.check_for_row_in_list_table('1: Buy milk')
error = self.get_error_element()
self.assertEqual(error.text, "You can't have an empty list item")
# And she can correct it by filling some text in
self.get_item_input_box().send_keys('Make tea\n')
self.check_for_row_in_list... |
rascal999/qad | qad/__init__.py | Python | gpl-3.0 | 8,092 | 0.006179 | #!/usr/bin/env python
import re
import requests
import validators
import sys
import httplib2
import datetime
import socket
from urllib.parse import urlsplit, urljoin
from ipwhois import IPWhois
from pprint import pprint
from bs4 import BeautifulSoup, SoupStrainer
import pkg_resources
http_interface = httplib2.Http()
... | missing")
except httplib2.ServerNotFoundError as e:
print (e.message)
def getIPs(domain):
try:
ips = socket.gethostbyname_ex(domain)
except socket.gaierror:
ips=[]
print(timeStamp() + "Cannot resolve " + domain)
| sys.exit(1)
return ips
def checkQuickXSS(url):
url_xss = url + "/%3c%3eqadqad"
try:
print()
print(timeStamp() + "* Checking / for XSS (URL only)")
try:
response, content = http_interface.request(url_xss, method="GET")
except httplib2.HttpLib2Error as e:
... |
urlist/urlist | motherbrain/api_server/conf.py | Python | gpl-3.0 | 2,842 | 0.000352 | import os
import logging
import tornado.options as opt
from motherbrain.base import conf
from motherbrain.base.conf import get_config
SITE_CONF = conf.site_conf(os.getcwd())
DATADIR = SITE_CONF.get('env.motherbrain_data', '/tmp')
API_URL = SITE_CONF.get('env.api_url')
WEBCLIENT_URL = SITE_CONF.get('env.webclient_url... | ses'},
'datadir': {'default': os.path.join(DATADIR, 'motherbrain_data')}
}
_oauth_opts = {
'cookie_secret': {'default': 'XXX'},
'cookie_domain': {'default': SITE_CONF.get('oauth.cookie_domain')},
'facebook_secret': {'default': 'XXX'},
'facebook_api_key': {'default': 'XXX'},
'facebook_redi... | gin/facebook'.format(API_URL)},
'twitter_consumer_key': {'default': 'XXX'},
'twitter_consumer_secret': {'default': 'XXX'},
'urlist_salt': {'default': 'XXX'}
}
_db_opts = {
'dbname': {'default': 'urlist'},
'dbhost': {'default': 'mongo1'},
'dbport': {'default': 27017, 'type': int},
'dbus... |
Alcheri/Plugins | IMDb/plugin.py | Python | bsd-3-clause | 7,840 | 0.001531 | ###
# Copyright (c) 2015, butterscotchstallion
# Copyright (c) 2020, oddluck <[email protected]>
# 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... | bove copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither ... | c prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CO... |
shadow1dos/NASA | Run.py | Python | gpl-3.0 | 745 | 0.036242 | import serial #import serial module
import NASA_Conn
from NASA_Conn_ | TT import check
def read_rfid ():
ser = serial.Serial ("/dev/ttyAMA0") #Open named port
ser.baudrate = 9600 #Set baud rate to 9600
data = ser.read(12) #Read 12 characters from serial port to data
... |
print ("Reading,Type ctrl+z to exit: ")
id = read_rfid ()
id=int(id,16)
check(id) #Function call
|
Onderwaater/spacetime | lib/spacetime/modules/spec/subplots.py | Python | gpl-2.0 | 1,206 | 0.009121 | # This file is part of Spacetime.
#
# Copyright 2010-2014 Leiden University.
# Spec module written by Willem Onderwaater.
#
# Spacetime 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 L... | def set_normalization(self, factor, channel=None):
self.normalization_factor = factor
if channel:
self.normalization_channel = next(channel.iterchannels()).value
else:
self.normalization_channel = 1
def get_ydata(self, chandata): |
return chandata.value * self.normalization_factor / self.normalization_channel
|
mattjj/pyhawkes | test/test_sbm_gibbs.py | Python | mit | 2,521 | 0.005553 | import copy
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import adjusted_mutual_info_score, adjusted_rand_score
from pyhawkes.models import DiscreteTimeNetworkHawkesModelSpikeAndSlab
from pyhawkes.plotting.plotting import plot_network
def test_gibbs_sbm(seed=None):
"""
Create a di... | ngs
amis = []
arss = []
| for c in c_samples:
amis.append(adjusted_mutual_info_score(true_model.network.c, c))
arss.append(adjusted_rand_score(true_model.network.c, c))
plt.figure()
plt.plot(np.arange(N_samples), amis, '-r')
plt.plot(np.arange(N_samples), arss, '-b')
plt.xlabel("Iteration")
plt.ylabel("Clust... |
lautr3k/RepRap-iTopie | odmt/ezdxf/ac1009/tableentries.py | Python | gpl-3.0 | 8,896 | 0.00045 | # Purpose: ac1009 table entries
# Created: 16.03.2011
# Copyright (C) 2011, Manfred Moitzi
# License: MIT License
from __future__ import unicode_literals
__author__ = "mozman <[email protected]>"
from ..entity import GenericWrapper
from ..tags import DXFTag
from ..classifiedtags import ClassifiedTags
from ..dxfattr import... | 2, None),
'flags': DXFAttr(7 | 0, None),
'lower_left': DXFAttr(10, 'Point2D'),
'upper_right': DXFAttr(11, 'Point2D'),
'center_point': DXFAttr(12, 'Point2D'),
'snap_base': DXFAttr(13, 'Point2D'),
'snap_spacing': DXFAttr(14, 'Point2D'),
'grid_spacing': DXFAttr(15, 'Point2D'),
'direction_point': D... |
pcu4dros/pandora-core | workspace/lib/python3.5/site-packages/sqlalchemy/sql/type_api.py | Python | mit | 46,121 | 0.000022 | # sql/types_api.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Base types API.
"""
from .. import exc, util
from . import operators
from .vi... | owever,
it can be implemented by a user-defined type
where it can be consumed by schema comparison tools such as
Alembic autogenerate.
A future release of SQLAlchemy will potentially | impement this method
for builtin types as well.
The function should return True if this type is equivalent to the
given type; the type is typically reflected from the |
opengisch/QFieldSync | qfieldsync/core/cloud_transferrer.py | Python | lgpl-3.0 | 29,804 | 0.001409 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
QFieldSync
-------------------
begin : 2020-08-19
git sha : $Format:%H$
copyright : (C) 2020 by OPENGIS.ch
email ... | f
for f in sorted(
files_to_upload,
key=lambda f: f.path.suffix in (".qgs", ".qgz"),
)
]
# prepare the files to be uploaded, copy them in a temporary destination
for project_file in files_to_upload_sorted:
assert project_... | project_file.flush()
temp_filename = self.temp_dir.joinpath(
FileTransfer.Type.UPLOAD.value, project_file.name
)
temp_filename.parent.mkdir(parents=True, exist_ok=True)
copy_multifile(project_file.local_path, temp_filename)
self.total_upl... |
CoolCloud/taiga-back | tests/fixtures.py | Python | agpl-3.0 | 2,031 | 0.001972 | # Copyright (C) 2014 Andrey Antukh <[email protected]>
# Copyright (C) 2014 Jesús Espino <[email protected]>
# Copyright (C) 2014 David Barragán <[email protected]>
# Copyright (C) 2014 Anler Hernández <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | uthenticate') as authenticate:
user.backend = backend
authenticate.return_value = user
return super().login(**credentials)
@property
def json(self):
return PartialMethodCaller(obj=se | lf, content_type='application/json;charset="utf-8"')
return _Client()
@pytest.fixture
def outbox():
from django.core import mail
return mail.outbox
|
amrdraz/brython | www/src/Lib/encodings/mac_arabic.py | Python | bsd-3-clause | 37,165 | 0.018916 | """ Python Character Mapping Codec generated from 'VENDORS/APPLE/ARABIC.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='st... | 0x0661, # ARABIC-INDIC DIGIT ONE, right-left (need override)
0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO, right-left (need override)
0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE, right-left (need override)
0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR, right-left (need override)
0x00b5: 0... | x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX, right-left (need override)
0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN, right-left (need override)
0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT, right-left (need override)
0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE, right-left (need override)
... |
xcool/webtools | setup.py | Python | gpl-3.0 | 498 | 0.008032 | from distutils.core import setup
im | port py2exe
import sys
# this allows to run it with a simple double click.
sys.argv.append('py2exe')
py2exe_options = {
"includes": ["sip"],
"dll_excludes": ["MSVCP90.dll", ],
"compressed": 1,
"optimize": 2,
| "ascii": 0,
# "bundle_files": 1,
}
setup(
name='main',
version='1.0',
windows=[{"script":"main.py"}],
zipfile=None,
options={'py2exe': py2exe_options}
)
|
aterrel/dynd-python | dynd/tests/test_numpy_interop.py | Python | bsd-2-clause | 27,383 | 0.002922 | import sys
import unittest
from dynd import nd, ndt
import numpy as np
from datetime import date, datetime
from numpy.testing import *
class TestNumpyDTypeInterop(unittest.TestCase):
def setUp(self):
if sys.byteorder == 'little':
self.nonnative = '>'
else:
self.nonnative = '... | , align=True)
self.assertEqual(tp0, tp1)
# unaligned struct
tp0 = ndt.make_cstruct([ndt.make_unaligned(ndt.int32),
ndt.make_unaligned(ndt.int64)],
['x', 'y']).as_numpy()
tp1 = np.dtype([('x', np.int32), ('y', np.int64)])
self.assert... | self.assertRaises(TypeError, ndt.bytes.as_numpy)
self.assertRaises(TypeError, ndt.string.as_numpy)
class TestNumpyViewInterop(unittest.TestCase):
def setUp(self):
if sys.byteorder == 'little':
self.nonnative = '>'
else:
self.nonnative = '<'
def test_dynd_sca... |
MediaKraken/MediaKraken_Deployment | source/subprogram_match_anime_id.py | Python | gpl-3.0 | 3,312 | 0.000906 | """
Copyright (C) 2015 Quinn D Granfor <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
... | in common_metadata_scudlee.mk_scudlee_anime_list_parse():
common_logging_elasticsearch_httpx.com_es_httpx_post(message_type='info',
message_text={'row': 'row_data'})
if row_data is not None:
| # skip media with "no" match...rowdata2 is imdbid
# just check for non int then it's a non tvdb id
if type(row_data[1]) != int and row_data[2] is None:
pass
else:
# should be valid data, do the update
db_connection.db_meta_update_media_id_from_scudlee(r... |
CFIS-Octarine/octarine | planning/ph2.py | Python | gpl-3.0 | 5,099 | 0.001961 | import json
import argparse
import numpy
import sys
import copy
from astropy.coordinates import SkyCoord
from astropy import units
import operator
class Program(object):
def __init__(self, runid="16BP06", pi_login="gladman"):
self.config = {"runid": runid,
"pi_login": pi_login,
... | target_token},
"constraint_identifi | ers": [{"server_token": "C1"}],
"instrument_config_identifiers": [{"server_token": "I1"}]}
@property
def token(self):
return self.config["identifier"]["client_token"]
class ObservingGroup(object):
def __init__(self, client_token):
self.config = {"identifier": {"clie... |
atruberg/django-custom | tests/servers/tests.py | Python | bsd-3-clause | 5,773 | 0.000173 | # -*- encoding: utf-8 -*-
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import os
import socket
from django.core.exceptions import ImproperlyConfigured
from django.test import LiveServerTestCase
from django.test.utils import override_settings
from django.utils.http import urlencode
fr... | ket.error)
# The list of ports must be in a valid format
cls.raises_exception('localhost:8081,', ImproperlyConfigured)
cls.raises_exception('localhost:8081,blah', ImproperlyConfigured)
| cls.raises_exception('localhost:8081-', ImproperlyConfigured)
cls.raises_exception('localhost:8081-blah', ImproperlyConfigured)
cls.raises_exception('localhost:8081-8082-8083', ImproperlyConfigured)
# If contrib.staticfiles isn't configured properly, the exception
# should bubble up to... |
hacpai/show-me-the-code | Python/0002/main.py | Python | gpl-2.0 | 202 | 0.00495 | # -*- c | oding: utf-8 -*-
"""
Created on Tue Dec 9 11:10:56 2014
@author: MasterMac
"""
sec = int(raw_input())
hour = sec / 60**2
minute = sec / 60 % 60
second = sec % 60
print hour, minute, second
| |
maxwellgerber/ee122_final_proj | md1.py | Python | mit | 1,637 | 0.020159 | from src.discrete import Environment
from src.queue import Queue
from random import expovariate, seed
from tabulate import tabulate
from math import e
class MD1Queue | (Queue):
"""MD1 Queue discrete time simulator"""
def __init__(self, lamb, mu, env):
super().__init__(env)
self.lamb = lamb
self.mu = mu
@property
def arrival_rate(self):
return expovariate(self.lamb)
@property
def service_rate(self):
return 1/self.mu
|
def expected_dist(self, i):
if i == 0:
return 1 - 1/self.lamb
l = 1/self.lamb
return (1 - l) * (e**(i*l) - 1)
if __name__ == "__main__":
seed(122)
lamb = 130
mu = 200
N = int(1e5)
QueueSim = Environment(verbosity=True)
Q = MD1Queue(lamb, mu, QueueSim)
Q.generate_arrival_events(N)
... |
farooqsheikhpk/Aspose.BarCode-for-Cloud | Examples/Python/managing-recognition/without-cloud-storage/read-barcodes-with-checksum.py | Python | mit | 2,040 | 0.012745 | import asposebarcodecloud
from asposebarcodecloud.BarcodeApi import BarcodeApi
from asposebarcodecloud.BarcodeApi import ApiException
from asposebarcodecloud.models import BarcodeReader
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import Resp... | p_sid')
out_folder = config.get('AppConfig', 'out_folder')
data_folder = "../../data/" #resouece data folder
#ExStart:1
#Inst | antiate Aspose Storage API SDK
storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True)
storageApi = StorageApi(storage_apiClient)
#Instantiate Aspose Barcode API SDK
api_client = asposebarcodecloud.ApiClient.ApiClient(apiKey, appSid, True)
barcodeApi = BarcodeApi(api_client);
#Set input... |
w1ll1am23/home-assistant | homeassistant/scripts/__init__.py | Python | apache-2.0 | 2,358 | 0.000424 | """Home Assistant command line scripts."""
from __future__ import annotations
import argparse
import asyncio
import importlib
import logging
import os
import sys
from typing import Sequence
from homeassistant import runner
from homeassistant.bootstrap import async_mount_local_lib_path
from homeassistant.config import... | _":
| continue
if os.path.isdir(os.path.join(path, fil)):
scripts.append(fil)
elif fil != "__init__.py" and fil.endswith(".py"):
scripts.append(fil[:-3])
if not args:
print("Please specify a script to run.")
print("Available scripts:", ", ".join(scripts))
... |
waymao/SU-System | clubs/migrations/0002_auto_20170828_2330.py | Python | gpl-3.0 | 569 | 0 | # -*- coding: utf-8 -*-
# Generated by Django | 1.11.4 on 2017-08-28 15:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clubs', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='club',
name='time'... | ault=False,
),
]
|
abaumhauer/onie | test/lib/connection.py | Python | gpl-2.0 | 6,914 | 0.003182 | #
# DUT Connection classes
#
# Copyright (C) 2013 Curt Brune <[email protected]>
#
# SPDX-License-Identifier: GPL-2.0
'''
Defines a Connection object that the test fixture uses to communicate
with a DUT.
'''
#-------------------------------------------------------------------------------
#
# Imports
#
... | matically.
timeout -- how many seconds to wait for prompt. -1 is connection default.
'''
self._child.sendline(line)
try:
output = self.expect(self.prompt, timeout)
except pexpect.EOF, e:
logging.critical("pexpect received EOF while sending: " + line)
... |
logging.critical("pexpect received TIMEOUT (%d secs) while sending: >%s<" %
(to, line))
sys.exit(1)
# Return the output, split into lines. Also skip the first
# line as it is just an echo of the command sent.
return output.splitlines()[1:]
... |
rmvanhees/pys5p | examples/unit_test_s5p_plot.py | Python | bsd-3-clause | 11,888 | 0.000252 | """
This file is part of pyS5p
https://github.com/rmvanhees/pys5p.git
Performs unit-tests on S5Pplot methods: draw_signal, draw_quality,
draw_cmp_images, draw_trend1d and draw_lines (xarray version)
Copyright (c) 2020-2021 SRON - Netherlands Institute for Space Research
All Rights Reserved
License: BSD-3-Cla... | f = get_test_data(error=0.025)
nlines = 40 # 35
fig_info_in = FIGinfo('right')
for ii in range(nlines):
fig_info_in.add(f'line {ii:02d}', 5 * '0123456789')
plot.draw_si | gnal(msm,
title='Unit test of S5Pplot [draw_signal]',
sub_title='method=data; aspect=1; fig_pos=above')
plot.draw_signal(msm, zscale='diff',
title='Unit test of S5Pplot [draw_signal]',
sub_title='method=diff; aspect=1; fig_pos=above... |
serpilliere/miasm | test/os_dep/win_api_x86_32.py | Python | gpl-2.0 | 9,960 | 0.002309 | #! /usr/bin/env python2
#-*- coding:utf-8 -*-
from builtins import range
import unittest
import logging
from miasm.analysis.machine import Machine
import miasm.os_dep.win_api_x86_32 as winapi
from miasm.os_dep.win_api_x86_32 import get_win_str_a, get_win_str_w
from miasm.core.utils import pck32
from miasm.jitter.csts ... | jit.push_uint32_t(addr) # buf
jit.push_uint32_t | (5) # size
jit.push_uint32_t(0) # @return
winapi.kernel32_GetCurrentDirectoryA(jit)
size_ret = jit.cpu.EAX
self.assertEqual(len(dir_)+1, size_ret)
dir_short = get_win_str_a(jit, addr)
self.assertEqual(dir_short, dir_[:4])
def test_MemoryManagementFunctions(... |
vg/netsukuku | pyntk/ntk/sim/network/route.py | Python | gpl-2.0 | 29 | 0 | # TODO: thi | s must be a stub! | |
qrkourier/ansible | test/units/modules/network/nxos/test_nxos_feature.py | Python | gpl-3.0 | 2,591 | 0.000772 | # (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is dis... | def load_from_file(*args, **kwargs):
module, commands = args
| output = list()
for item in commands:
try:
obj = json.loads(item['command'])
command = obj['command']
except ValueError:
command = item['command']
filename = '%s.txt' % str(command).replace(' ... |
pierg75/pier-sosreport | sos/plugins/maas.py | Python | gpl-2.0 | 2,550 | 0 | # Copyright (C) 2013 Adam Stokes <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This prog... | out even the imp | lied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, ... |
danellecline/stoqs | stoqs/loaders/BEDS/__init__.py | Python | gpl-3.0 | 3,934 | 0.009151 | #!/usr/bin/env python
__author__ = 'Mike McCann'
__copyright__ = '2013'
__license__ = 'GPL v3'
__contact__ = 'mccann at mbari.org'
__doc__ = '''
Contains class for common routines for loading all BEDS data
Mike McCann
MBARI 13 May 2013
@undocumented: __doc__ parser
@status: production
@license: GPL
'''
imp... | ile, plotTimeSeriesDepth, fg) in zip(
[ a.split('/')[-1] + ' (stride=%d)' % stride for a in self.bed_files],
self.bed_platforms, self.bed_files, self.bed_depths, self.bed_framegrabs):
url = os.path.join(self.bed_base, file)
try:
... | the UI)
# assign a plotTimeSeriesDepth value of the starting depth in meters.
DAPloaders.runBEDTrajectoryLoader(url, self.campaignName, self.campaignDescription,
aName, pName, self.colors[pName.lower()], 'bed',
... |
KotiyaSenya/FlaskLearn | manage.py | Python | mit | 605 | 0 | from flask.ext.migrate import MigrateCom | mand
from flask.ext.script import Manager
from flask.ext.script.commands import ShowUrls, Clean
from commands.testcase_command import TestCommand
from flask_learn import create_app
manager = | Manager(create_app)
manager.add_option("-c", "--config", dest='config',
help="application config file",
required=False)
manager.add_command("test", TestCommand)
manager.add_command("showurls", ShowUrls())
manager.add_command("clean", Clean())
manager.add_command("db", MigrateCom... |
anhstudios/swganh | data/scripts/templates/object/tangible/component/weapon/shared_reinforcement_core.py | Python | mit | 484 | 0.045455 | #### 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 = "obj | ect/tangible/component/weapon/shared_reinforcement_core.iff"
result.attribute_template_id = -1
result.stfName("craft_weapon_ingredients_n","reinforcement_core")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
peterbraden/tensorflow | tensorflow/python/framework/framework_lib.py | Python | apache-2.0 | 3,634 | 0 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Shape
@@TensorShape
@@Dimension
@@op_scope
@@get_seed
## For libraries building on TensorFlow
@@register_tensor_conver | sion_function
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Classes used when building a Graph.
from tensorflow.python.framework.device import DeviceSpec
from tensorflow.python.framework.ops import Graph
from tensorflow.python.framework.ops import O... |
gaeun/open-event-orga-server | app/models/custom_placeholder.py | Python | gpl-3.0 | 1,176 | 0 | from . import db
class CustomPlaceholder(db.Model):
"""email notifications model class"""
__tablename__ = 'custom_placeholder'
id = db.Column(db.Integer,
primary_key=True)
name = db.Column(db.String)
url = db.Column(db.String)
thumbnail = db.Column(db.Str | ing)
copyright = db.Column(db.String)
origin = db.Column(db.String)
def __init__(self,
name=None,
url=None,
thumbnail=None,
copyright=None,
origin=None):
self.name = name
self.url = url
self.thumbna... | humbnail
self.copyright = copyright
self.origin = origin
def __str__(self):
return 'Name:' + unicode(self.name).encode('utf-8')
def __unicode__(self):
return unicode(self.id)
@property
def serialize(self):
"""Return object data in easily serializable format"""
... |
haad/ansible-modules-extras | cloud/profitbricks/profitbricks.py | Python | gpl-3.0 | 21,799 | 0.001973 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | on_added: '2.2'
ssh_keys:
description:
- Public SSH keys allowing access to the virtual machine.
required: false
version_added: '2.2'
datacenter:
| description:
- The datacenter to provision this virtual machine.
required: false
default: null
cores:
description:
- The number of CPU cores to allocate to the virtual machine.
required: false
default: 2
ram:
description:
- The amount of memory to allocate to the virtual... |
hbtech-ai/ARPS | report_spider/report_spider/spiders/USTC005.py | Python | mit | 3,781 | 0.024005 | # -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import time
import scrapy
from Global_function import get_localtime, print_new_number, save_messages
now_time = get_localtime(time.strftime("%Y-%m-%d", time.localtime()))
# now_time = 20170420
class USTC005_Spider(scrapy.Spider):
name = ... | yield scrapy.Request(report_url, callback=self.parse_pages, meta={'link': report_url, 'number': i + 1})
def parse_pages(self, response):
messages = response.xpath("//div[@class='TRS_Editor']").xpath(".//p")
sign = 0
title, speaker, time, addr | ess, content, person_introduce = '', '', '', '', '', ''
for message in messages:
text = self.get_text(message)
if u'欢迎大家' in text or u'联系人' in text or u'紫金山天文台学术委员会' in text:
continue
elif u'题目:' in text or 'Title:' in text or u'题目:' in text or 'Title:' in text:
title = self.connect_message(text, ':'... |
kernevil/samba | source4/torture/drs/python/drs_base.py | Python | gpl-3.0 | 24,898 | 0.001848 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Unix SMB/CIFS implementation.
# Copyright (C) Kamen Mazdrashki <[email protected]> 2011
# Copyright (C) Andrew Bartlett <[email protected]> 2016
# Copyright (C) Catalyst IT Ltd. 2016
#
# This program is free software; you can redistribute it and/or modify
# it under t... | """Sets which DC's LDB we perform operations on during the test"""
self.test_ldb_dc = ldb_dc
def _GUID_string(self, guid):
return get_string(self.test_ldb_dc.schema_format_value("objectGUID", guid))
def _ldap_schemaUpdateNow(self, sam_db):
rec = {"dn": "",
"schemaUpdateN... | sam_db.modify(m)
def _deleted_objects_dn(self, sam_ldb):
wkdn = "<WKGUID=18E2EA80684F11D2B9AA00C04F79F805,%s>" % self.domain_dn
res = sam_ldb.search(base=wkdn,
scope=SCOPE_BASE,
controls=["show_deleted:1"])
self.assertEqual(len(res... |
metakirby5/zenbu | setup.py | Python | mit | 1,288 | 0 | i | mport codecs
from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with codecs.open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='zenbu',
version='1.0.5',
descript... | han',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Natural ... |
BastilleResearch/gr-nordic | python/build_utils_codes.py | Python | gpl-3.0 | 1,289 | 0.013189 | '''
Copyright (C) 2016 Bastille Networks
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distribut... | See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
def i_code (code3):
return code3[0]
def o_code (code3):
if len (code3) >= 2:
return code3[1]
else... |
return code3[2]
else:
return code3[0]
def i_type (code3):
return char_to_type[i_code (code3)]
def o_type (code3):
return char_to_type[o_code (code3)]
def tap_type (code3):
return char_to_type[tap_code (code3)]
char_to_type = {}
char_to_type['s'] = 'short'
char_to_type['i'] = 'int'
... |
aemerick/galaxy_analysis | physics_data/UVB/grackle_tables/h5_in_memory.py | Python | mit | 2,620 | 0.002672 | """
HDF5 in memory object
Britton Smith <[email protected]>
"""
import h5py
import numpy as np
import sys
class H5InMemory(object):
def __init__(self, fh):
self.attrs = {}
if fh is None:
self.data = {}
return
if isinstance(fh, str):
fh = h... | d field
def keys(self):
if hasattr(self, "data"):
return self.data.keys()
return None
def save(self, fh):
top = False
if isinstance(fh, str):
top = True
fh = h5py.File(fh, "w")
for attr in self.attrs:
fh.attrs[attr] = sel... | e_group(field))
else:
dfh = fh.create_dataset(field,
data=self.data[field].value)
self.data[field].save(dfh)
if top:
fh.close()
|
favreau/RenderingResourceManager | rendering_resource_manager_service/session/management/slurm_job_manager.py | Python | lgpl-3.0 | 18,783 | 0.001757 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=W0403
# pylint: disable=R0915
# pylint: disable=W0613
# Copyright (c) 2014-2015, Human Brain Project
# Cyrille Favreau <[email protected]>
# Daniel Nachbaur <[email protected]>
#
# This file is... | stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stde | rr=subprocess.PIPE)
error = process.communicate()[1]
if len(re.findall('Granted', error)) != 0:
session.job_id = re.findall('\\d+', error)[0]
log.info(1, 'Allocated job ' + str(session.job_id) +
' on cluster node ' + c... |
zjuela/LapSRN-tensorflow | tensorlayer/prepro.py | Python | apache-2.0 | 62,978 | 0.005096 | #! /usr/bin/python
# -*- coding: utf8 -*-
import tensorflow as tf
import tensorlayer as tl
import numpy as np
import time
import numbers
import random
import os
import re
import sys
import threading
# import Queue # <-- donot work for py3
is_py2 = sys.version[0] == '2'
if is_py2:
import Queue as queue
else:
... | t’, ‘reflect’ or ‘wrap’
- `scipy ndimag | e affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
cval : scalar, optional
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0
- `scipy ndimage affine_transform <https://docs.s... |
miguelsdc/nao_robot | nao_driver/scripts/headscanTop.py | Python | bsd-3-clause | 5,281 | 0.013634 | #!/usr/bin/env python
import math
import time
import naoqi
import motion
from naoqi import ALProxy
import roslib
roslib.load_manifest('nao_driver')
import rospy
use_robot_state_publisher = False
if use_robot_state_publisher:
from robot_state.msg import RobotState
from scan_pose_bending import scanPoseBending
from... | 80.0
headPitchEnd = headPitchEnd * math.pi/180.0
headPitchInflectionPoint = headPitchEnd + (20.0*math.pi/180.0) # go further up than final scan pose
degreePerSecond = angularResolution* laserScanFreq*0.33
radiansPerSecond = degreePerSecond*math.pi/180.0
#print("Radians per second: " + str(radiansPer... | e)[0]
head_pitch_camera_learning = 22.0*math.pi/180.0
if use_scan_pose:
scanPoseBending(motionProxy,head_pitch_before_scan,0.0,2)
#motionProxy.stiffnessInterpolation('Body',1.0, 0.5)
# compute some times
t = abs(head_pitch_before_scan - headPitchStart)/radiansPerSecond
t2 = abs(headPit... |
ChantyTaguan/zds-site | zds/pages/models.py | Python | gpl-3.0 | 982 | 0.00611 | from django.contrib.auth.models import Group, User
from django.db import models
from django.utils.translation import gettext_lazy as _
class GroupContact(models.Model):
"""
Groups displayed in contact page and their informations.
| """
class Meta:
verbose_name = _("Groupe de la page de contact")
verbose_name_plural = _("Groupes de la page de contact")
group = models.OneToOneField(Group, verbose_name=_("Groupe d'utilisateur"), on_delete=models.CASCADE)
name = models.CharField(_("Nom (ex: Le staff)"), max_length=32, ... | ue=True)
description = models.TextField(_("Description (en markdown)"), blank=True, null=True)
email = models.EmailField(_("Adresse mail du groupe"), blank=True, null=True)
persons_in_charge = models.ManyToManyField(User, verbose_name=_("Responsables"), blank=True)
position = models.PositiveSmallInteger... |
muccg/rdrf | rdrf/explorer/migrations/0007_fieldvalue_column_name.py | Python | agpl-3.0 | 482 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-10-05 09:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('explorer', '0006_auto_201 | 81004_1159'),
]
operations = [
migrations. | AddField(
model_name='fieldvalue',
name='column_name',
field=models.CharField(blank=True, max_length=80, null=True),
),
]
|
JamesWo/cs194-16-data_manatees | precision_recall.py | Python | apache-2.0 | 4,204 | 0.002617 | import matplotlib.pyplot as plt
import numpy as np
import sklearn
from sklearn import svm, datasets
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
from sklearn.c | ross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
import pdb
from sklearn import ensemble
from sklearn import neighbors
from sklearn import tree
#import data
data_path = "joined_matrix_split.txt"
mat = np.loadtxt(data_path)
featur... | rize(output_raw)
# Split into training and test
random_state = np.random.RandomState(0)
X_train, X_test, y_train, y_test = train_test_split(features, output, test_size=.5,
random_state=random_state)
n_classes = 1
#run classifier
classifier = OneVsRestClassifier(svm.... |
stdweird/aquilon | tests/aqdb/aqdb_nose_plugin.py | Python | apache-2.0 | 2,638 | 0.003033 | #!/usr/bin/env python2.6
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2010,2013 Contributor
#
# 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... | eady exists)
if ENVIRONMENT_VARNAME in os.environ.keys():
log.info('found %s in the environment, skipping db rebuild ' % (
ENVIRONM | ENT_VARNAME))
return
if options.no_rebuild:
self.enabled = True
os.environ[ENVIRONMENT_VARNAME] = 'enabled'
log.debug("Plugin says don't rebuild the database")
else:
log.debug("Plugin says to rebuild the database")
def begin(self):
... |
multiplechoice/workplace | jobs/common.py | Python | apache-2.0 | 2,436 | 0.003284 | import datetime
import bleach
import re
months = {
1: "jan",
2: "feb",
3: "mars",
4: ["apr\u00edl", "apr"],
5: "ma\u00ed",
6: "j\u00fan\u00ed",
7: "j\u00fal\u00ed",
8: "\u00e1g\u00fast",
9: "sept",
10: "okt",
11: "n\u00f3v",
12: "des",
}
def decode_date_string(date_st... | month(month):
"""
Translates the month string into an integer value
Args:
month (unicode): month string parsed from the website listings.
Returns:
int: month index star | ting from 1
Examples:
>>> translate_month('jan')
1
"""
for key, values in months.items():
if month in values:
return key
def clean_html(input_html):
allowed_tags = bleach.sanitizer.ALLOWED_TAGS + ["br", "p"]
cleaner = bleach.sanitizer.Cleaner(
tags=... |
Epoptes/epoptes | epoptes-client/message.py | Python | gpl-3.0 | 2,401 | 0 | #!/usr/bin/python3
# This file is part of Epoptes, http://epoptes.org
# Copyright 2012-2018 the Epoptes team, see AUTHORS.
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Display a simple window with a message.
"""
import os
import sys
from _common import gettext as _
from gi.repository import Gtk
class MessageWindo... | text [title] [markup] [icon_name]").format(
os.path.basename(__file__)), file=sys.stderr)
exit(1)
text = sys.argv[1]
if len(sys.argv) > 2 and sys.argv[2]:
title = sys.argv[2]
else:
title = "Epoptes"
if len(sys.argv) > 3 and sys.argv[3]:
markup = sys.argv[3].lo... | :
icon_name = "dialog-information"
window = MessageWindow(text, title, markup, icon_name)
window.connect("destroy", Gtk.main_quit)
window.show_all()
Gtk.main()
if __name__ == '__main__':
main()
|
Ourinternet/website | commission/migrations/0001_initial.py | Python | mit | 10,354 | 0.003767 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(verbo... | blank=True)),
('website_display', models.CharField(max_length=256, null=True, blank=True)),
('description', models.TextField(null=True, blank=True)),
| ('press_description', models.TextField(null=True, blank=True)),
('logo', models.ImageField(null=True, upload_to=b'partner_logos', blank=True)),
('weight', models.IntegerField(default=0)),
],
options={
},
bases=(models.Model,)... |
isovic/marginAlign | src/margin/marginCaller.py | Python | mit | 2,779 | 0.020511 | import os
import sys
from optparse import OptionParser
from jobTree.src.bioio import logger, setLoggingFromOptions
from jobTree.scriptTree.stack import Stack
from jobTree.scriptTree.target import Target
from margin.utils import pathToBaseNanoporeDir
from margin.marginCallerLib import marginCallerTargetFn
def main(... | (pathToBaseNanoporeDir(),
"src", "margin", "mappers", "last_hmm_20.txt"),
| help="The model to use in calculating the difference between the predicted true reference and the reads.")
parser.add_option("--maxAlignmentLengthPerJob", default=7000000,
help="Maximum total alignment length of alignments to include in one posterior prob calculation job.",
... |
sunqm/pyscf | pyscf/tools/test/test_cubegen.py | Python | apache-2.0 | 2,994 | 0.007348 | #!/usr/bin/env python
# Copyright 2019 The PySCF Developers. 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... | .6539 | 95909548524, 9)
def test_orb(self):
ftmp = tempfile.NamedTemporaryFile()
orb = cubegen.orbital(mol, ftmp.name, mf.mo_coeff[:,0],
nx=10, ny=10, nz=10)
self.assertEqual(orb.shape, (10,10,10))
self.assertAlmostEqual(lib.finger(orb), -0.11804191128016768, 9... |
juhasch/polymode | examples/ex8_bragg_fiber.py | Python | gpl-3.0 | 1,327 | 0.019593 | ##
## Bragg fiber
##
from numpy import *
from pylab import *
from Polymode import *
from Polymode import LayeredSolver
ncore = 1.0
n1=1.4
n2=1.6
rcore = 5.0
Nlayer = 2 | 0
m = 0
neff_opt = 0.998
wl_opt = 1.0
d1 = wl_opt/(4*sqrt(n1**2 - neff_opt**2))
d2 = wl_opt/(4*sqrt(n2**2 - neff_opt**2))
dlayer = d1+d2
wlrange=[0.4,1.4]
print "Bragg layer widths d1=%.4g, d2=%.4g, rcore = %.5g " % (d1,d2, rcore)
mg = Material.Fixed(ncore)
m1 = Material.Fixed | (n1)
m2 = Material.Fixed(n2)
#create structure object with external substrate of m1
wg = Waveguide.Waveguide(material=m1, symmetry=1)
#Core
wg.add_shape(Waveguide.Circle(mg, center=(0,0), radius=rcore))
#Cladding
for ii in range(Nlayer):
ri = rcore+ii*dlayer
a1 = Waveguide.Annulus(m1, r=(ri,ri+d1))
a2 = ... |
Vagab0nd/SiCKRAGE | lib3/twilio/rest/ip_messaging/v1/service/channel/invite.py | Python | gpl-3.0 | 15,284 | 0.002225 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import... | thod='GET', uri=self._uri, params=data, )
return InvitePage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of InviteInstance records from the API.
Request is executed immediately
:param str target_url: API-generated UR... |
:returns: Page of InviteInstance
:rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return InvitePage(self._version, response, self._solution)
def get(self,... |
enthought/etsproxy | enthought/contexts/with_mask.py | Python | bsd-3-clause | 97 | 0 | # proxy module |
from __future__ import absolute_import
from codetools.contexts.with_mask import | *
|
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/sub_resource_py3.py | Python | mit | 823 | 0.00243 | # 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 ... | ------------------------------------------------
from msrest.serialization im | port Model
class SubResource(Model):
"""SubResource.
:param id: Resource ID.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(self, *, id: str=None, **kwargs) -> None:
super(SubResource, self).__init__(**kwargs)
self.id = id... |
asascience-open/paegan | paegan/cdm/dsg/member.py | Python | gpl-3.0 | 114 | 0.008772 | class M | ember(dict):
def __init__(self, *ar | gs, **kwargs):
super(Member, self).__init__(*args, **kwargs) |
RosettaCommons/binder | examples/example_struct/make_bindings_via_cmake.py | Python | mit | 4,103 | 0.002437 | #!/usr/bin/env python3
import glob
import os
import sys
import shutil
import subprocess
from distutils.sysconfig import get_python_inc
# Overall script settings
binder_executable = glob.glob(f'{os.getcwd()}/../../build/llvm-4.0.0/build_4.0.0*/bin/binder')[0]
bindings_dir = 'cmake_bindings'
binder_source = f'{os.getc... | ' '.join(command))
subprocess.check_call(command)
sources_to_compile = []
with open(f'{bindings_dir}/{py | thon_module_name}.sources', 'r') as fh:
for line in fh:
sources_to_compile.append(line.strip())
return sources_to_compile
def compile_sources(sources_to_compile):
os.chdir(bindings_dir)
lines_to_write = []
lines_to_write.append(f'project({python_module_name})')
for include_dir... |
charlescearl/VirtualMesos | src/webui/master/webui.py | Python | apache-2.0 | 2,037 | 0.015218 | # 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... | LATE_PATH.append('./webui/master/')
# TODO(*): Add an assert to confirm that all the arguments we are
# expecting have been passed to us, which will give us a better er | ror
# message when they aren't!
master_port = sys.argv[1]
webui_port = sys.argv[2]
log_dir = sys.argv[3]
bottle.debug(True)
bottle.run(host = '0.0.0.0', port = webui_port)
|
ARTFL-Project/PhiloLogic4 | extras/utilities/tei_cleanup.py | Python | gpl-3.0 | 8,791 | 0.00091 | import sys
import regex as re
from BeautifulSoup import BeautifulStoneSoup as bss
# REQUIRES BeautifulSoup3. BS4 breaks on Python recursion errors when it gets badly damaged texts.
def cleanup(infile, outfile):
# main routine. takes a file handle for input and output; called at the bottom of the file.
text... | for tag in soup.findAll():
| if tag.name in fix_case:
tag.name = fix_case[tag.name]
print(soup, file=outfile)
outfile.close()
# Annoyingly, BeautifulSoup requires you to declare ALL self-closing tags yourself; it will badly mangle your text if you miss one, so get this right.
self_closing = ["p", "index", "pb", "miles... |
mmechtley/psfMC | psfMC/model_parser.py | Python | mit | 2,467 | 0.000405 | import os
import ast
import six
from .ModelComponents import ComponentBase
_comps_name = '__components'
class ExprsToAssigns(ast.NodeTransformer):
"""
Walks the Abstract Syntax Tree from the parsed model file, and transforms
bare expressions into augmented assignments that are tacked on to the end
of... | Store())],
value=ast.List(elts=[], ctx=ast.Load()))
model_tree.body.insert(2, comps_node)
# Transform bare components expression | s into list append statements
model_tree = ExprsToAssigns().visit(model_tree)
ast.fix_missing_locations(model_tree)
# Process file within its local dir, so file references within are relative
# to its location instead of the script run location.
prev_dir = os.getcwd()
model_dir = os.path.dirnam... |
Kabal/eventghost-epson-tw700 | __init__.py | Python | mit | 5,840 | 0.010103 | eg.RegisterPlugin(
name = "Epson TW-700 Projector",
author = "Tom Wilson",
version = "0.1.0",
kind = "external",
guid = "{f6cfb453-416b-4276-92ac-c58ffe98972b}",
url = "",
description = (''),
canMultiLoad = True,
createMacrosOnAdd = True,
)
# Now we import some other t... | itialState()
except:
self.PrintError("Unable to open serial port")
def __stop__(self):
self.readerkiller = True
if self.serial is not None:
self.serial. | close()
self.serial = None
def Configure(self, port=0):
portCtrl = None
panel = eg.ConfigPanel(self)
portCtrl = panel.SerialPortChoice(port)
panel.AddLine("Port:", portCtrl)
while panel.Affirmed():
panel.SetResult(portCtrl.GetValue())
... |
manishbisht/Udacity | Full Stack Web Developer Nanodegree v2/P2 - Trivia API/backend/models.py | Python | mit | 1,781 | 0 | import os
from sqlalchemy import Column, String, Integer, create_engine
from flask_sqlalchemy import SQLAlchemy
import json
database_name = "trivia"
database_path = "postgres://{}:{}@{}/{}".format(
'postgres', 'abc@123', 'localhost:5432', database_name)
db = SQLAlchemy()
'''
setup_db(app)
binds a flask appli... | egory
self.difficulty = difficulty
def insert(self):
db.session.add(self)
db.session.commit()
def update(self):
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
|
def format(self):
return {
'id': self.id,
'question': self.question,
'answer': self.answer,
'category': self.category,
'difficulty': self.difficulty
}
'''
Category
'''
class Category(db.Model):
__tablename__ = 'categories'
id... |
simenon/pocket-query-downloader | gc_util.py | Python | gpl-2.0 | 5,704 | 0.007714 | #!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright (C) 2013 Albert Simenon
#
# 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... | elpFormatter
parser.description = "%s, version %s by %s (%s)\n\n%s" \
% (__filename__,__version__,__author__,__email__,__purpose__)
parser.add_argument(
"--browser","-b",
choices=BROWSERS,
default=BROWSERS[0],
help | ="browser used for visiting geocaching.com")
parser.add_argument(
"--download",
action="store_true",
help="download pocket queries")
parser.add_argument(
"--user","-u",
required=True,
help="Geocaching.com username")
parser.add_argument(
"--p... |
cernops/nova | nova/tests/unit/virt/libvirt/test_imagecache.py | Python | apache-2.0 | 42,304 | 0.000307 | # Copyright 2012 Michael Still and Canonical 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
#
# ... | ream)
handler.setFormatter(formatters.ContextFormatter())
mylog.logger.addHandler(handler)
yield stream
finally:
mylog.logger.removeHandler(handler)
class ImageCacheManagerTestCase(test.NoDBTestCase):
def setUp(self):
super(ImageCacheManagerTestCase, self).setUp()
... | 'instance-00000003',
'banana-42-hamster'])
def test_read_stored_checksum_missing(self):
self.stub_out('os.path.exists', lambda x: False)
csum = imagecache.read_stored_checksum('/tmp/foo', timestamped=False)
self... |
googleapis/python-pubsub | google/cloud/pubsub_v1/subscriber/client.py | Python | apache-2.0 | 11,505 | 0.002086 | # Copyright 2019, Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | .TYPE_CHECKING: # pragma: NO COVER
from google.cloud.pubsub_v1 import subscriber
from google.pubsub_v1.services.subscriber.transports.grpc import (
SubscriberGrpcTransport,
)
try:
__version__ = pkg_resources.get_distribution("google-cloud-pubsub").version
except pkg_resources.DistributionNotF... | = "0.0"
class Client(subscriber_client.SubscriberClient):
"""A subscriber client for Google Cloud Pub/Sub.
This creates an object that is capable of subscribing to messages.
Generally, you can instantiate this client with no arguments, and you
get sensible defaults.
Args:
kwargs: Any ad... |
Rolight/So-Spider | cluster_manager.py | Python | gpl-3.0 | 1,490 | 0 | import sys
import time
from scheduler import SoSpiderSchdulerBase
class SoClusterManager(SoSpiderSchdulerBase):
def __init__(self, name):
self.load_conf()
self.make_connection()
self.name = name
self.log_file = open('./logs/%s_cluster. | log' % self.name, 'w')
def log(self, text):
self.log_file.write(text + '\n')
self.log_file.flush()
def run(self):
self.log('ClusterManger has running as %s' % self.name)
while True:
time.sleep(5)
current_spider_key = self.key_of_spider(self.name)
... | , self.name)
all_spiders = self.redis_cache.smembers(cluster_key)
self.log('spiders supposed in cluster is %s' % all_spiders)
living_spiders = [
name for name in all_spiders
if self.redis_cache.exists(self.key_of_spider(name))
]
... |
n4hy/gnuradio | gr-trellis/src/examples/test_sccc_turbo1.py | Python | gpl-3.0 | 3,908 | 0.037615 | #!/usr/bin/env python
from gnuradio import gr
from | gnuradio import trellis, digital
from gnuradio import eng_notation
import math
import sys
import random
import fsm_utils
def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,seed):
tb = gr.top_block ()
# TX
src = gr.lfsr_32k_source_s()
src_head = gr.head (gr.sizeof... | e in shorts
s2fsmi = gr.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the outer FSM input cardinality
enc = trellis.sccc_encoder_ss(fo,0,fi,0,interleaver,K)
mod = gr.chunks_to_symbols_sf(constellation,dimensionality)
# CHANNEL
add = gr.add_ff()
... |
googleapis/python-talent | samples/snippets/job_search_commute_search_test.py | Python | apache-2.0 | 828 | 0 | # 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 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... | ssions and
# limitations under the License.
import os
import job_search_commute_search
PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"]
def test_commute_search(tenant):
jobs = job_search_commute_search.search_jobs(PROJECT_ID, tenant)
for job in jobs:
assert "projects/" in job
|
uber/ludwig | ludwig/utils/h3_util.py | Python | apache-2.0 | 3,350 | 0.000299 | #! /usr/bin/env python
# coding=utf-8
# Copyright (c) 2019 Uber Technologies, 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
#
# Unles... | its(h3, 64 - 19, 7, components['base_cell'])
for i, cell in enumerate(components['cells']):
h3 = set_bits(h3, 64 - 19 - (i + 1) * 3, 3, cell)
h3 = set_bits(h3, 64 - 1, 4, 0)
return h3
def bitslice(x, start_bit, slice_length):
ones_mask = 2 ** slice_length - 1
return (x & (ones_mask << star... | - 5, 4)
def h3_edge(h3_long):
return bitslice(h3_long, 64 - 8, 3)
def h3_resolution(h3_long):
return bitslice(h3_long, 64 - 12, 4)
def h3_base_cell(h3_long):
return bitslice(h3_long, 64 - 19, 7)
def h3_octal_components(h3_long):
res = h3_resolution(h3_long)
return "{0:0{w}o}".format(
... |
jakobharlan/avango | avango-blender/blender-addon/sockets/matrix_socket.py | Python | lgpl-3.0 | 1,640 | 0 | import bpy
from bpy.types import NodeSocket
from bpy.props import Floa | tVectorProperty
class MatrixSocket(NodeSocket):
bl_idname = "MatrixSocket"
bl_label = "Matrix Socket"
MatProp = FloatVectorProperty(
name='Mat',
description='Vector of 16 floats representing the Matrix',
default=(
| 1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
),
size=16,
)
def get_default_value(self):
if 'MatProp' in self.keys():
matrix = self['MatProp']
return [
matrix[0], matri... |
Kjir/papyon | papyon/service/description/RSI/GetMetadata.py | Python | gpl-2.0 | 1,488 | 0.004704 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <[email protected]>
#
# This program is free software; y | ou can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fr | ee 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 FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Lice... |
antoinecarme/pyaf | tests/artificial/transf_Integration/trend_LinearTrend/cycle_30/ar_/test_artificial_1024_Integration_LinearTrend_30__100.py | Python | bsd-3-clause | 271 | 0.084871 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset( | N = 1024 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 30, transform = "Integrat | ion", sigma = 0.0, exog_count = 100, ar_order = 0); |
andrewyoung1991/supriya | supriya/tools/ugentools/Dust.py | Python | mit | 2,414 | 0.003314 | # -*- encoding: utf-8 -*-
from supriya.tools.synthdeftools.SignalRange import SignalRange
from supriya.tools.ugentools.UGen import UGen
class Dust(UGen):
r'''A unipolar random impulse generator.
::
>>> dust = ugentools.Dust.ar(
... density=23,
... )
>>> dust
Dus... | density=density,
)
return ugen
@classmethod
def kr(
cls,
density=0,
):
r'''Constructs a control-rate unipolar random impulse generator.
::
>>> ugentools.Dust.kr(
... density=[1, 2],
... | )
UGenArray({2})
Returns unit generator graph.
'''
from supriya.tools import synthdeftools
calculation_rate = synthdeftools.CalculationRate.CONTROL
ugen = cls._new_expanded(
calculation_rate=calculation_rate,
density=density,
)
... |
wq/django-data-wizard | tests/data_app/admin.py | Python | mit | 170 | 0 | f | rom django.contrib import admin
from .models import SimpleModel, Type, FKModel
admin.site.register(SimpleModel)
admin.site.register(Type)
admin.site.register(FKModel)
| |
aron-bordin/Kivy-Tutorials | 5_Perception/Perception/revmob/__init__.py | Python | gpl-2.0 | 275 | 0 | from kivy.utils import platform
from kivy.logger import Logger
Logger.info('Loading RevMob module' | )
if platform() == 'android':
from .android import *
elif platform() == 'ios':
from .ios import *
else:
Logger.warning('[Rev | Mob] Unkown platform: %s' % platform())
|
our-city-app/oca-backend | src/solutions/common/jobs/notifications.py | Python | apache-2.0 | 8,697 | 0.003449 | # -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... | ' -moz-border-radius: 6px; border-radius: 6px; font-family: Arial; color: #ffffff; font-size: 14px;' \
' background: #3abb9e; padding: 8px 16px 8px 16px; text-decoration: none;'
signin_url = settings.get_signin_url()
if sln_settings.login:
signin_url += '?email=%s' % sln_settings.lo... | 'signin_url': signin_url,
'button_css': button_css,
'dashboard': transl('dashboard')
}
action_text = transl('if-email-body-3-button', dashboard_button=btn)
footer_text = transl('jobs_notification_footer', service_name=sln_settings.name, app_name=app.name,
dashboard_... |
tyrylu/orgedit | uimanager.py | Python | mit | 5,741 | 0.00749 | import wx
import wx.xrc as xrc
import structobject
uimgr = None
def get():
return uimgr
class UIManager(object):
def __init__(self, resource_file, top_level_name, top_level_type="frame", reuse_app=False, load_on=None):
global uimgr
self._event_aliases = {}
self.resource_name = resourc... | r(self, "top_level", None), name)
return load | _on
else:
return self.resource.LoadFrame(getattr(self, "top_level", None), name)
def get_dialog(self, name, load_on=None):
if load_on:
self.resource.LoadDialog(load_on, self.usable_parent, name)
return load_on
else:
return self.resource.LoadDi... |
rdp1070/PokeMath | Question.py | Python | gpl-3.0 | 5,970 | 0.019598 | __author__ = 'Mars'
import random
class Question:
def __init__(self, monster):
self.name = "Question"
self.monster = monster
class PercentMonsterLevel1(Question):
def __init__(self, monster):
Question.__init__(self,monster)
self.name = "PercentMonsterLevel1"
def makeQ(se... | ptions.append(random.randint(0,100))
i+=1
a1 = int((num1 / 100.0) * num2) # num1 is the percentage, which should mutltiply by num2
op | tions.append(a1)
random.shuffle(options)
print("Choose the correct answer: {0}").format(options)
return q1, a1, options
class PercentMonsterLevel2(Question):
def __init__(self,monster):
Question.__init__(self,monster)
self.name = "PercentMonsterLevel2"
def makeQ(self):... |
pshrmn/cryptonite | cryptonite/user_auth/schema.py | Python | mit | 3,906 | 0.00384 | import graphene
from graphene_django.types import DjangoObjectType
from django.contrib.auth import (get_user_model, authenticate,
login as auth_login, logout as auth_logout,
update_session_auth_hash)
from django.contrib.auth.forms import (UserCreationFor... | n()
errors = graphene.List(FormError)
def mutate(self, info, old_password, new_password1, new_password2):
form = PasswordChangeForm(info.context.user, data={
"old_password": old_password,
"new_password1": new_password1,
"new_password2": new_password2
})
... | rd(success=True, errors=[])
else:
return ChangePassword(success=False, errors=list_errors(form.errors))
class Mutation(object):
login_user = LoginUser.Field()
signup_user = SignupUser.Field()
logout_user = LogoutUser.Field()
change_password = ChangePassword.Field()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.