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 |
|---|---|---|---|---|---|---|---|---|
cburmeister/fluid | app/lib/chromecast.py | Python | mit | 1,942 | 0.000515 | """
A wrapper around pychromecast for interacting with a Chromecast device.
"""
import pychromecast
import time
class Chromecast(object):
"""An object for interacting with a Chromecast device."""
def __init__(self, host):
"""Initialize the Chromecast."""
self.host = host
| self.connection = self.connect()
def connect(self):
"""Returns a connection to the Chromecast."""
try:
connection = pychromecast.Chromecast(self.host)
except:
return
if not connection:
return
connection.wait()
time.sleep(1)
... | n:
return
self.connection.disconnect(blocking=False)
def cast(self, url, mimetype, title):
"""Cast the url to the chromecast."""
self.connection.media_controller.play_media(url, mimetype, title=title)
def play(self):
"""Resume playback of the media on the Chromecas... |
jordanemedlock/psychtruths | temboo/core/Library/GitHub/GitDataAPI/Tags/GetTag.py | Python | apache-2.0 | 4,161 | 0.005287 | # -*- coding: utf-8 -*-
###############################################################################
#
# GetTag
# Retrieves a specified tag object.
#
# Python versions 2.6, 2.7, 3.x
#
| # Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# s... | stributed 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.
#
#
###############################################################################
from temboo.core.choreogra... |
MediffRobotics/DeepRobotics | DeepLearnMaterials/tutorials/real world examples/bank_marketing_learning/bank_marketing_tfnn.py | Python | gpl-3.0 | 905 | 0 | import tfnn
import pandas as pd
bank_data = pd.read_csv('bank-full.csv', sep=';')
data = tfnn.Data(bank_data.iloc[:, :-1], bank_data.ilo | c[:, -1])
data.encode_cat_y(inplace=True)
data.encode_cat_x(inplace=True)
network = tfnn.ClfNetwork(data.xs.shape[1], data.ys.shape[1],)
data = network.normalizer.minmax_fit(data, -1, 1)
train_data, test_data = data.train_test_split()
network.add_hidden_layer(50, activator=tfnn.nn.relu)
network.add_output_layer(activat... | nn.train.GradientDescentOptimizer(0.0001))
evaluator = tfnn.Evaluator(network)
for i in range(1000):
b_xs, b_ys = train_data.next_batch(100, loop=True)
network.run_step(b_xs, b_ys)
if i % 50 == 0:
print(evaluator.compute_accuracy(test_data.xs, test_data.ys))
# print(test_data.ys.iloc[:,0].value_cou... |
MichaelCoughlinAN/Odds-N-Ends | Python/Python Modules/XBee-2.3.1/setup.py | Python | gpl-3.0 | 1,137 | 0 | import re
from setuptools import setup, find_packages
# Auto detect the library version from the __init__.py file
with open('xbee/__init__.py', 'r') as fd:
version = re.search(r'^__versio | n__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot | find version information')
setup(
name='XBee',
version=version,
description='Python tools for working with XBee radios',
long_description=open('README.rst').read(),
url='https://github.com/nioinnovation/python-xbee',
author='n.io',
author_email='info@n.io',
license='MIT',
classifie... |
mbagnardi/end_of_day_two | DefensiveProgramming_3.py | Python | mit | 3,722 | 0.011822 |
# coding: utf-8
# # Defensive programming (2)
# We have seen the basic idea that we can insert
# assert statments into code, to check that the
# results are what we expect, but how can we test
# software more fully? Can doing this help us
# avoid bugs in the first place?
#
# One possible ap... | 1])
retur | n (low, high)
else:
return None
def range_overlap(ranges):
# Return common overlap among a set of
# [low, high] ranges.
if len(ranges) == 1:
# Special case of one range -
# overlaps with itself
return(ranges[0])
elif len(ranges) == 2:
# Just return from fi... |
RYLF/pythontip | 20.py | Python | gpl-3.0 | 568 | 0.023936 | # coding=utf-8
# Title:信息加密
# 给你个小写英文字符串a和一个非负数b(0<=b<26), 将a中的每个小写字符替换成字母表中比它大b的字母。这里将字母表的z和a相连,如果超过了z就回到了a。
# 例如a="cagy", b=3,
# 则输出 :fdjb
# Test
a, b="cagy",3
# Answer
e = []
for i in range(0,len(a)):
c = ord(a[i])+b # 转换成整数
if c> 122: # 如果大于z则减去26
c -= 26
e.append(chr(c)) ... | str | |
ajoymajumdar/genie | genie-client/src/main/python/tests/job_tests/test_geniejob.py | Python | apache-2.0 | 12,048 | 0.001162 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import unittest
from mock import patch
from nose.tools import assert_equals, assert_raises
import pygenie
from ..utils import FakeRunningJob
assert_equals.__self__.maxDiff = None
@pygenie.adapter.genie_3.set_jobname
def... | cations('app1') \
.applications('app2') \
.archive(False) \
.cluster_tags('cluster1') \
.cluster_tags('cluster2') \
| .command_arguments('genie job repr args') \
.command_tags('cmd1') \
.command_tags('cmd2') \
.dependencies('/dep1') \
.dependencies('/dep2') \
.description('description') \
.disable_archive() \
.genie_email('jsmith@email.com') \
... |
mat128/netman | netman/core/objects/__init__.py | Python | apache-2.0 | 790 | 0 | # Copyright 2015 Internap.
#
# 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, so... | IS" B | ASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Model(object):
def __eq__(self, other):
return isinstance(other, type(self)) and vars(self) == vars(other)
def ... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/appfw/appfwpolicy.py | Python | apache-2.0 | 13,731 | 0.040055 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | y. Must begin with a letter, number, or the underscore character (_), and mus | t contain only letters, numbers, and the hyphen (-), period (.) pound (#), space ( ), at (@), equals (=), colon (:), and underscore characters.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my... |
swcurran/tfrs | backend/api/migrations/0009_auto_20170821_2313.py | Python | apache-2.0 | 26,613 | 0.002104 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-08-21 23:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0008_auto_20170817_2124'),
]
operations = [
... | AddField(
model_name='audit',
name='UPDATE_TIMESTAMP',
field=models.DateTimeField(auto_now=True, null=True),
),
migrations.AddField(
model_name='audit',
name='UPDATE_USER',
field=models.ForeignKey(blank=True, null=True, on_delete=dj... | DATE_USER', to='api.User'),
),
migrations.AddField(
model_name='credittrade',
name='CREATE_TIMESTAMP',
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AddField(
model_name='credittrade',
name='CREATE_USER... |
google/clusterfuzz | src/clusterfuzz/_internal/tests/core/bot/fuzzers/utils_test.py | Python | apache-2.0 | 4,971 | 0.00523 | # Copyright 2019 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, ... | self.as | sertFalse(utils.is_fuzz_target_local(path))
def test_not_a_fuzzer_blocklisted_name(self):
path = self._create_file(
'jazzer_driver', contents=b'LLVMFuzzerTestOneInput')
self.assertFalse(utils.is_fuzz_target_local(path))
def test_not_a_fuzzer_without_extension(self):
path = self._create_file('a... |
lstorchi/teaching | xyzviewer/datastr/refer.py | Python | gpl-3.0 | 70 | 0.071429 | a = [1,2,3, | 4]
b = a
a.append(5)
print(b)
x = 3
y = x |
x = 4
print(y)
|
samsu/neutron | tests/unit/test_provider_configuration.py | Python | apache-2.0 | 8,840 | 0 | # Copyright 2013 VMware, 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 ap... | erConfiguration([])
prov = {'service_type': constants.LOADBALANCER,
| 'name': 'name',
'driver': 'path',
'default': False}
pconf.add_provider(prov)
self.assertEqual(len(pconf.providers), 1)
self.assertEqual(pconf.providers.keys(),
[(constants.LOADBALANCER, 'name')])
self.assertEqual(pcon... |
wkschwartz/django | tests/urlpatterns_reverse/included_named_urls.py | Python | bsd-3-clause | 354 | 0 | from django.urls import include, path, re_path
from .views import empty_view
urlpatterns = [
path('', empty_view, name="named-url3"),
re_path(r'^extra/(?P<extra>\w+)/$', empty_view, name | ="named-url4"),
re_path(r'^(?P<one>[0-9]+)|(?P<t | wo>[0-9]+)/$', empty_view),
path('included/', include('urlpatterns_reverse.included_named_urls2')),
]
|
zheguang/voltdb | lib/python/voltcli/voltadmin.d/update.py | Python | agpl-3.0 | 3,159 | 0.003166 | # This file is part of VoltD | B.
# Copyright (C) 2008-2014 VoltDB Inc.
#
# This file contains original code and/or modification | s of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, inc... |
pedro-b/layer-switcher | pytmx/tmxloader3.py | Python | mit | 18,700 | 0.003155 | """
Map loader for TMX Files
bitcraft (leif.theden at gmail.com)
v.7 -- for python 3.x
If you have any problems, please contact me via email.
Tested with Tiled 0.7.1 for Mac.
released under the LGPL v3
======================================================================
Design Goals:
Simple api
Memory eff... | tilelayers[layer].data[y][x]
except (IndexError, ValueError):
msg = "Coords: ({0},{1}) in layer {2} is invalid.".format(x, y, layer)
raise Exception(msg)
| else:
try:
return self.images[gid]
except (IndexError, ValueError):
msg = "Coords: ({0},{1}) in layer {2} has invalid GID: {3}/{4}.".format(x, y, layer, gid, len(self.images))
raise Exception(msg)
def getTileGID(self, x, y, layer):
... |
bartekjagiello/inteygrate_flaskapp | yowsup/env/env.py | Python | gpl-3.0 | 2,580 | 0.005814 | import abc
import logging
from six import with_metaclass
logger = logging.getLogger(__name__)
DEFAULT = "Android"
class YowsupEnvType(abc.ABCMeta):
def __init__(cls, name, bases, dct):
if name != "YowsupEnv":
YowsupEnv.registerEnv(cls)
super(YowsupEnvType, cls).__init__(name, bases, d... | def getDeviceName(self):
pass
@abc.abstractmethod
def g | etManufacturer(self):
pass
@abc.abstractmethod
def isAxolotlEnabled(self):
pass
def getBuildVersion(self):
return ""
def getResource(self):
return self.getOSName() + "-" + self.getVersion()
def getUserAgent(self):
return self.__class__._USERAGENT_STRING.fo... |
bmcfee/librosa | tests/test_core.py | Python | isc | 61,375 | 0.000945 | #!/usr/bin/env python
# CREATED:2013-03-08 15:25:18 by Brian McFee <brm2132@columbia.edu>
# unit tests for librosa core (__init__.py)
#
from __future__ import print_function
# Disable cache
import os
try:
os.environ.pop("LIBROSA_CACHE_DIR")
except:
pass
import librosa
import glob
import numpy as np
import ... | oad(
os.path.join("tests", DATA["wavfile"][0]), sr=None, mono=DATA["mono"]
)
# Verify that the sample rate is correct
| assert sr == DATA["sr"]
assert np.allclose(y, DATA["y"])
@pytest.mark.parametrize("res_type", ["kaiser_fast", "kaiser_best", "scipy"])
def test_load_resample(res_type):
sr_target = 16000
fn = librosa.ex("trumpet")
y_native, sr = librosa.load(fn, sr=None, res_type=res_type)
y2 = librosa.res... |
rg3/youtube-dl | youtube_dl/extractor/tf1.py | Python | unlicense | 3,073 | 0.002279 | # coding: utf-8
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_iso8601,
try_get,
)
class TF1IE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tf1\.fr/[^/]+/(?P<program_slug>[^/]+)/videos/(?P<id>[^/?&#]+)\.ht... | 'variabl | es': json.dumps({
'programSlug': program_slug,
'slug': slug,
})
})['data']['videoBySlug']
wat_id = video['streamId']
tags = []
for tag in (video.get('tags') or []):
label = tag.get('label')
if not label:... |
ChillyCider/Tuxemon | tuxemon/core/states/dialog/__init__.py | Python | gpl-3.0 | 1,325 | 0 | from __future__ import division
import pygame
from core.components.menu.menu import PopUpMenu
from core.components.ui.text import TextArea
class DialogState(PopUpMenu):
""" Game state with a graphic box and s | ome text in it
Pressing the action button:
* if text is being displayed, will cause text speed to go max
* when text is displayed completely, then will show the next message
* if there are no more messages, then the dialog will close
"""
default_character_delay = .05
def startup(self, **kw | args):
super(DialogState, self).startup(**kwargs)
self.text_queue = kwargs.get("text", list())
self.text_area = TextArea(self.font, self.font_color)
self.text_area.rect = self.calc_internal_rect()
self.sprites.add(self.text_area)
def on_open(self):
self.next_text()
... |
itkinside/ari | ari/util/dict.py | Python | gpl-2.0 | 947 | 0 | #! /usr/bin/env python
#
# Copyright (C) 2007 Stein Magnus Jodal
#
# 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,
#... | py 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, MA 02110-1301 USA.
#
#
# Authors: Stein Magnus Jodal <jodal@samfundet.no>
#
def explode_kwargs(kwargs):
"""Explode a multilevel dict of kwargs"""
if '... | |
joyxu/autotest | database_legacy/migrations/033_add_host_attributes.py | Python | gpl-2.0 | 504 | 0 | UP_SQL = """
CREATE TABLE `host_attributes` (
`id` integer AUTO_INCREMENT NOT NULL P | RIMARY KEY,
`host_id` integer NOT NULL,
`attribute` varchar(90) NOT NULL,
`value` varchar(300) NOT NULL,
FOREIGN KEY (host_id) REFERENCES hosts (id),
KEY (attribute | )
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
"""
DOWN_SQL = """
DROP TABLE IF EXISTS host_attributes;
"""
def migrate_up(manager):
manager.execute_script(UP_SQL)
def migrate_down(manager):
manager.execute_script(DOWN_SQL)
|
Kinnay/NintendoClients | tests/nex/test_settings.py | Python | mit | 655 | 0.045802 |
from nintendo.nex import settings
def test_constants():
s = settings.default()
assert s.TRANSPORT_UDP == 0
assert s.TRANSPORT_TCP == 1
assert s.TRANSPORT_WEBSOCKET == 2
assert s.COMPRESSION_NONE == 0
assert s.COMPRESSION_ZLIB == 1
assert s.ENCRYPTION_NONE == 0
assert s.ENCRYPTION_RC4 == 1
... | rberos.key_size"] == 32
copy = s.copy()
s["kerberos.key_size"] = 100
assert s["kerberos.key_size"] == 100
assert copy["kerberos.key_size"] == 32
s.reset()
assert s["kerberos.key_size"] == 32
s.load("friends")
assert s["kerberos.key_size"] == 16
| |
agarciamontoro/leap-motion-project | menu.py | Python | gpl-2.0 | 3,777 | 0.007413 | from primitives import Image, Button, Circle
from constants import *
from operator import add
'''
Button for navigating between screens. Its main attribute is the next_screen variable,
which points to an object of class Screen. This object is returned when the buttos in pressed
'''
class NavigationalButton(Button):
... | d a loader, whi | ch is called whenever a button is being pressed
'''
class Menu:
def __init__(self,start_screen=None,loader=None):
self.start_screen = start_screen
self.loader = loader
self.current_screen = self.start_screen
self.pointer = Circle()
self.enabled = False
# Returns the me... |
GFibrizo/TPS_7529 | TP3/Mochila_aprox/calculador_mochila.py | Python | apache-2.0 | 1,966 | 0.004069 | from math import ceil
def round(valor, n, max_value, precision):
result = int(ceil(valor / (max_value * (precision / n))))
return result
def calcular_mochila(items, pesoMax, precision):
n = len(items)
filtered_items = filter(lambda item: (item[1] <= pesoMax), items)
max_value = reduce(lambda ite... | hila(filtered_items, pesoMax)
return reduce(lambda valor1, valor2: valor1 + valor2, [items[i][0] for i in resultado2]), resultado2
def sum_valores_hasta(items, pos):
total = 0
for i in xrange(pos):
total += items[i][0]
return total |
def getValorMaxEnM(M, pesoMax, items):
valorMax = 0
n = len(items)-1
for valor in xrange(len(M[n])):
if M[n][valor] <= pesoMax and valor >= valorMax:
valorMax = valor
return valorMax
def _calcular_mochila(items, pesoMax):
sumVal = sum_valores_hasta(items, len(items))
n... |
dermoth/gramps | gramps/gui/views/navigationview.py | Python | gpl-2.0 | 17,924 | 0.001395 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2001-2007 Donald N. Allingham
# Copyright (C) 2009-2010 Nick Hall
#
# 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 v... | -------------------------------------
class NavigationView(PageView):
"""
The NavigationView class is the base class for all Data Views that require
navigation functionalilty. Views that need bookmarks and forward/back | ward
should derive from this class.
"""
def __init__(self, title, pdata, state, uistate, bm_type, nav_group):
PageView.__init__(self, title, pdata, state, uistate)
self.bookmarks = bm_type(self.dbstate, self.uistate, self.change_active)
self.fwd_action = None
self.back_acti... |
pseudonym117/Riot-Watcher | src/riotwatcher/_apis/valorant/urls/__init__.py | Python | mit | 82 | 0 | from .Con | tentApiUrls import ContentApiUrls
from .MatchApiUrls import MatchApiUrl | s
|
frontg8/frontg8lib | doc/ext/breathe/breathe/apidoc.py | Python | bsd-3-clause | 5,570 | 0.000539 | # -*- coding: utf-8 -*-
"""
breathe.apidoc
~~~~~~~~~~~~~~
Parses doxygen XML tree looking for C/C++ modules and creates ReST files
appropriately to create code documentation with Sphinx. It also creates a
modules index (See TYPEDICT below.).
This is derived from the "sphinx-autopackage" script... | run:
os.makedirs(args.destdir)
args.rootpath = os | .path.abspath(args.rootpath)
recurse_tree(args)
if not args.notoc:
for key, value in TYPEDICT.items():
create_modules_toc_file(key, value, args)
# So program can be started with "python -m breathe.apidoc ..."
if __name__ == "__main__":
main()
|
relekang/rmoq | rmoq/backends.py | Python | mit | 3,665 | 0.003001 | # -*- coding: utf-8 -*-
import os
import re
from . import compat
class RmoqStorageBackend(object):
"""
Base backend for rmoq backends. All storage backends for rmoq must inherit this
backend if it is to be used with rmoq.
"""
def get(self, prefix, url):
"""
Fetches a request resp... | f the request response.
"""
raise NotImplementedError
| @staticmethod
def _parse(content):
return (
compat.make_str(content.split('\n')[0]),
compat.make_str('\n'.join(content.split('\n')[1:]))
)
@staticmethod
def clean_url(url, replacement='_'):
"""
Cleans the url for protocol prefix and trailing slash ... |
DT42/BerryNet | berrynet/engine/tfliteyolov4_engine.py | Python | gpl-3.0 | 8,435 | 0.002964 | import logging
import time
from argparse import ArgumentParser
from os import path
import cv2
import numpy as np
import tensorflow as tf
from berrynet.engine import DLEngine
from berrynet import logger
class TFLiteYoloV4DetectorEngine(DLEngine):
def __init__(self, model, labels, threshold=0.1, num_threads=1):
... | self.img_h = tensor.shape[0]
frame = cv2.cvtColor(tensor, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame, (416, 416))
frame = np.expand_dims(frame, axis=0)
if self.input_dtype == np.f | loat32:
frame = (1.0 / 255.0) * frame
frame = frame.astype('float32')
else:
# default data type returned by cv2.imread is np.unit8
pass
return frame
def filter_boxes(self, box_xywh, scores, score_threshold=0.4, input_shape = tf.constant([416,416])):
... |
rtfd/readthedocs.org | readthedocs/rtd_tests/tests/projects/test_admin_actions.py | Python | mit | 2,812 | 0.001422 | # -*- coding: utf-8 -*-
import django_dynamic_fixture as fixture
from unittest import mock
from django import urls
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.auth.models import User
from django.test import TestCase
from readthedocs.core.models import UserProfile
from readthedocs.... | ed=False).count(), 2)
@mock.patch('readthedocs.projects.admin.clean_project_resources')
def test_project_delete(self, clean_project_resources):
"""Test project and artifacts are remo | ved."""
action_data = {
ACTION_CHECKBOX_NAME: [self.project.pk],
'action': 'delete_selected',
'index': 0,
'post': 'yes',
}
resp = self.client.post(
urls.reverse('admin:projects_project_changelist'),
action_data,
)
... |
PXke/invenio | invenio/modules/workflows/views/__init__.py | Python | gpl-2.0 | 1,091 | 0.011916 | # -*- coding: utf- | 8 -*-
## This file is part of Invenio.
## Copyright (C) 2013, 2014 CERN.
##
## Invenio 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 versio... | ICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 331, Boston, MA 02111-1307, USA.
"""
invenio.modules.workflows.views
... |
JeffHeard/terrapyn | geocms/utils.py | Python | apache-2.0 | 15,689 | 0.00478 | """ This module contains miscellaneous utility functions and classes for creating the OWS webservices. The most useful
functions in the module are probably the date manipulation functions.
"""
from collections import namedtuple
import datetime
import json
from django.contrib.auth.models import User, Group, AnonymousU... | on', status=code)
def user_page(user):
user_page, created = DirectoryEntry.objects.get_or_create(title=best_name(user), owner=user, in_menus=[], public=False, parent=None)
if created:
user_page.title = best_name(user) # this is a hack to assure that the slug is correct
user_page.save()
ret... |
def get_layer_page_for_user(user):
p, _ = DirectoryEntry.objects.get_or_create(title="Layers", in_menus=[], public=False, owner=user, parent=user_page(user))
return p
def get_stylesheet_page_for_user(user):
p, _ = DirectoryEntry.objects.get_or_create(title="Stylesheets", in_menus=[], public=False, owner=... |
mic4ael/indico | indico/modules/events/requests/base.py | Python | mit | 7,379 | 0.001355 | # This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask_pluginengine import plugin_context
from wtforms.fields... | fy_rejected_request, notify_withdrawn_request)
from indico.modules.events.requests.views import WPRequestsEventManagement
from indico.util.date_time import now_utc
from indico.util.i18n import _
from indico.web.flask.templating import get_overridable_template_name, get_template_module
from indico.web.forms.base import ... | lf.request = kwargs.pop('request')
super(RequestFormBase, self).__init__(*args, **kwargs)
class RequestManagerForm(IndicoForm):
action_buttons = {'action_save', 'action_accept', 'action_reject'}
comment = TextAreaField(_('Comment'),
description=_('The comment will be shown... |
google-research/deeplab2 | model/decoder/motion_deeplab_decoder.py | Python | apache-2.0 | 9,007 | 0.003109 | # coding=utf-8
# Copyright 2022 The Deeplab2 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 ... | Y KIND, either express or implied.
# See the License for the specific language governing | permissions and
# limitations under the License.
"""This file contains the code for the Motion-DeepLab decoder."""
import tensorflow as tf
from deeplab2 import common
from deeplab2 import config_pb2
from deeplab2.model.decoder import panoptic_deeplab
class MotionDeepLabDecoder(tf.keras.layers.Layer):
"""A Motio... |
HackerEcology/SuggestU | suggestu/social/backends/base.py | Python | gpl-3.0 | 8,286 | 0.000241 | from requests import request, ConnectionError
from social.utils import module_member, parse_qs
from social.exceptions import AuthFailed
class BaseAuth(object):
"""A django.contrib.auth backend that authenticates the user based on
a authentication provider response"""
name = '' # provider name, it's stor... | def auth_allowed(self, response, details):
"""Return True if the user should be allowed to authenticate, by
default check if email is whitelisted (if there's a whitelist)"""
emails = self.setting('WHITELISTED_EMAILS', [])
domains = self.setting('WHITELISTED_DOMAINS', [])
email =... | allowed = True
if email and (emails or domains):
domain = email.split('@', 1)[1]
allowed = email in emails or domain in domains
return allowed
def get_user_id(self, details, response):
"""Return a unique ID for the current user, by default from server
res... |
liamcurry/py3kwarn | py3kwarn2to3/pygram.py | Python | mit | 1,068 | 0 | # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Export the Python grammar and symbols."""
# Python imports
import os
# Local imports
from .pgen2 import driver
# The grammar file
_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt")
_PATTERN_GRA... | es an attribute for each grammar symbol (nonterminal),
whose value is the symbol's type (an int >= 256).
"""
for name, symbol in grammar.symbol2number.items():
setattr(self, name, symbol)
python_grammar = driver.load_grammar(_GRAMMAR_FILE)
pyth | on_symbols = Symbols(python_grammar)
python_grammar_no_print_statement = python_grammar.copy()
del python_grammar_no_print_statement.keywords["print"]
pattern_grammar = driver.load_grammar(_PATTERN_GRAMMAR_FILE)
pattern_symbols = Symbols(pattern_grammar)
|
sacrefies/csc643_bigdata | project1/src/queries.py | Python | apache-2.0 | 7,595 | 0.005925 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017 team1@course_bigdata, Saint Joseph's University
#
# 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/li... | ])
print "\n"
print 'd) City Count and Total Population per State by Map/Reduce:'
for r in state_pop_city_count_map_reduce():
print r['_id'], ': (city cnt: ', r['value']['cityCount'], ', total pop: ', r['value']['pop'], ')'
print "\n"
print 'e) Average Population f | or Each State with MapReduce:'
for r in average_state_population_with_map_reduce():
print '%s: (city cnt: %d, total pop: %d, avg pop: %.2f)' % \
(r['_id'], r['value']['cityCount'], r['value']['pop'], r['value']['avgPop'])
print "\n"
print "f) Least Populus State by Map/Reduce:",
for (k... |
kch42/dotstr_edit | dotstr_edit.py | Python | mit | 15,425 | 0.03592 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import strfile
import wx
import sys, os
import locale, gettext
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
class TransDictListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
"""ListCtrl for a translation dictionary"""
def __init__(self, parent):
wx.ListCtrl.... | y of the selected translation.
If no translation is selected, an empty string will be returned
"""
index = self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
return "" if index == -1 else self.dict.keys()[index]
def OnGetItemText(self, item, col):
"""Basic implementation of the LC_VIRTUAL me... | new translation key
"""
def __init__(self, parent):
# Layout stuff
wx.Dialog.__init__(self, parent, title=_("New entry"), size=(500,-1))
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(wx.StaticText(self, label=_("Name of your new entry:")), 0, wx.EXPAND | wx.ALL, 5)
hbox = wx.BoxSizer(wx.HORIZONTAL)
self... |
timlinux/geonode | setup.py | Python | gpl-3.0 | 1,905 | 0.00105 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | = 10
from pip._internal.req import parse_requirements
from pip._internal.downl | oad import PipSession
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
from pip.download import PipSession
from distutils.core import setup
from setuptools import find_packages
# Parse requirements.txt to get the list of dependencies
inst_req = parse_requirements('requirements.txt... |
santosfamilyfoundation/TrafficCloud | app/handlers/baseHandler.py | Python | mit | 2,285 | 0.003063 | import tornado.web
import json
import traceback
import os
class BaseHandler(tornado.web.RequestHandler):
def initialize(self):
self.error_message = None
self.MB = 1024*1024
self.GB = 1024*self.MB
def find_argument(self, arg_name, default=None):
method_type = self.request.method... | if ret_val:
return ret_val
else:
return default
def write_error(self, status_code, **kwargs):
self.set_header('Content-Type', 'application/json')
erro | r_dict = {
'code': status_code
}
if self.error_message != None:
error_dict['error_message'] = self.error_message
print("ERROR: "+self.error_message)
if self.settings.get('serve_traceback') and 'exc_info' in kwargs:
lines = []
for line... |
redahe/opportuner | modules/concerts_range.py | Python | apache-2.0 | 400 | 0.0025 | #!/usr/bin/python
import sys
import re
import json
ln = 0
pattern = re.compile('.*[A-Z|a-z]+.*')
for line in sys.stdin.readlines():
ln += 1
dat | a = json.loads(line)
name = data.pop('name')
name = name.replace(' ', '_')
score = (100 - ln)
if pattern.match(name):
score += 15
print s | core, name.encode('utf-8'), json.dumps(data, ensure_ascii=False).encode('utf-8')
|
metacloud/python-troveclient | troveclient/tests/test_client.py | Python | apache-2.0 | 1,531 | 0 | # Copyright 2011 OpenStack Foundation
# Copyright 2013 Rackspace Hosting
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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 co... | apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permiss... | mitations
# under the License.
import testtools
import troveclient.v1.client
from troveclient import client as other_client
from troveclient.openstack.common.apiclient import client
from troveclient.openstack.common.apiclient import exceptions
class ClientTest(testtools.TestCase):
def test_get_client_class... |
ksmit799/Toontown-Source | toontown/town/DLStreet.py | Python | mit | 280 | 0.003571 | import Street
class DLStreet(Street.Street):
def __init__(self, loader, parentFSM, doneEvent):
St | reet.Street.__init__(self, loader, parentFSM, doneEvent)
| def load(self):
Street.Street.load(self)
def unload(self):
Street.Street.unload(self)
|
proevo/pythondotorg | events/factories.py | Python | apache-2.0 | 1,814 | 0.001103 | import factory
from .models import Calendar
class CalendarFactory(fa | ctory.DjangoModelFactory):
class Meta:
model = Calendar
django_get_or_create = ('slug',)
name = factory.Sequence(lambda n: 'Calendar {}'.format(n))
def initial_data():
return {
'calendars': [
CalendarFactory( |
name='Python Events Calendar',
slug='python-events-calendar',
twitter='https://twitter.com/PythonEvents',
url='https://www.google.com/calendar/ical/j7gov1cmnqr9tvg14k62'
'1j7t5c@group.calendar.google.com/public/basic.ics',
... |
GeoMop/GeoMop | src/JobPanel/backend/connection.py | Python | gpl-3.0 | 36,774 | 0.002502 | from .json_data import JsonData
from .environment import Environment
from .path_converter import if_win_lin2win_conv_path
# import in code
#from .service_proxy import DelegatorProxy
#from .service_base import ServiceStatus
import shutil
import os
import os.path
import threading
import logging
import errno
import sele... | st_ok=True)
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
if (follow_symlinks and os.path.isdir(srcname)) or \
(not follow_symlinks and not os.path.islink(srcname) and os.path.isdir(srcname)):
self._... | ctionSSH(ConnectionBase):
class SftpPool:
"""
Class for managing SFTP sessions.
Reasons for use this class:
- unable to use one SFTP session in multiple threads
- we do not want to open and close SFTP session in each SFTP operation
- we want to limit number of SFTP... |
arpho/bb | exporter/Label.py | Python | mit | 342 | 0.038012 | class Label:
def collectLabel(self,l):
"""genera l'elenc | o delle etichette, perche' potrebbero essere presenti varie versioni di documenti nella collezione in mongodb
@param list: lista degli item in da inserire nel file excel
@return: []"""
labels = {}
for i in l:
labels = dict(labels.items()+i.items())
return lab | els.keys() |
anhstudios/swganh | data/scripts/templates/object/intangible/pet/shared_mouse_droid.py | Python | mit | 424 | 0.049528 | #### 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 = Intangible()
result.template = "object/intangible/pet/shared_mouse_droid.iff"
result.attribute_template_id = -1
result.stfName("","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS | ####
return result |
jamesgao/kiln_controller | kiln/manager.py | Python | gpl-2.0 | 5,025 | 0.034229 | import os
import stepper
import time
import random
import thermo
import threading
import traceback
import logging
import states
import PID
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class TempLog(object):
def __init__(self, history, interval=60, suffix=""): #save data every 60 seconds
impo... | elif isinstance(output, dict) and "type" in output:
self.notify(output)
elif output is not None:
logger.warn("Unknown state output: %r"%output)
def run(self):
while self.running:
self._change_state(self.state.run())
def manager_stop(self | ):
self.running = False
self.state_change.set()
class Profile(threading.Thread):
"""Performs the PID loop required for feedback control"""
def __init__(self, schedule, therm, regulator, interval=1, start_time=None, callback=None,
Kp=.03, Ki=.015, Kd=.001):
super(Profile, self).__init__()
self.daemon = Tru... |
NeejaYanglea/Python-google-course | copyspecial/copyspecial.py | Python | apache-2.0 | 2,207 | 0.019483 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
"""
#... | todir = args[1]
del args[0:2]
tozip = ''
if args[0] == '--tozip':
tozip = args[1]
del args[0:2]
if len(args) == 0:
print "error: must specify one or more dirs"
sys.exit(1)
# +++your code here+++
# Call your functions
if todir:
copy_to(get_special_paths(args[1]), todir)
elif to... | |
MyRobotLab/pyrobotlab | home/hairygael/GESTURES/signature.py | Python | apache-2.0 | 3,256 | 0.107801 | def signature():
##approach
i01.setHeadSpeed(0.75,0.75,1.0,1.0,1.0)
i01.setArmSpeed("left",0.75,0.75,0.75,0.75)
i01.setArmSpeed("rig | ht",0.75,0.75,0.75,0.75)
i01.setHandSpeed("left",0.75,0.75,0.75,0.75,0.75,0.75)
i01.setHandSpeed("right",0.75,0.75,0.75,0.75,0.75,0.75)
i01.moveHead(0,102,90,90,74)
i01.moveArm("left",84,73,49,10)
i01.moveArm(" | right",82,67,45,24)
i01.moveHand("left",2,2,2,2,2,120)
i01.moveHand("right",180,180,180,179,180,165)
sleep(2)
##approach left hand
i01.moveHead(0,83,90,90,74)
i01.moveArm("left",70,65,55,10)
i01.moveArm("right",101,67,63,24)
i01.moveHand("left",2,2,2,2,2,120)
i01.moveHand("r... |
shree-shubham/Unitype | The Minion Game.py | Python | gpl-3.0 | 345 | 0 | s = raw_input().lower()
score1 = score2 = 0
for i | in xrange(len(s)):
if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u':
score2 += len(s)-i
else:
score1 += len(s)-i
if score1 > score2:
print 'Stuart ' + str(score1)
elif score1 < score2:
prin | t 'Kevin ' + str(score2)
else:
print 'Draw'
|
afomm/autotest-docker | subtests/docker_cli/start/simple.py | Python | gpl-2.0 | 3,603 | 0 | """
Test usage of docker 'start' command
initialize:
1) prepare docker container, but don't start it
run_once:
2) execute docker start using the nonexisting name
3) execute the new container using `docker run`
4) execute docker start using the running docker name
5) stop the container
6) execute docker start using the... | self.sub_stuff['container_name'] = None # name of the container
def initialize(self):
super(simple, self).initialize()
self._init_stuff()
config.none_if_empty(self | .config)
# Get free name
docker_containers = DockerContainers(self)
name = docker_containers.get_unique_name()
self.sub_stuff['container_name'] = name
def _start_container(self, name):
""" Create, store in self.sub_stuff and execute container """
self.sub_stuff['cont... |
bitesandbytes/upgraded-system | src/vanilla_lstm.py | Python | mit | 22,530 | 0.000666 | '''
Build a tweet sentiment analyzer
'''
from __future__ import print_function
import cPickle as pickle
import sys
import time
from collections import OrderedDict
import numpy
import theano
import theano.tensor as tensor
from theano import config
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
... | = 123
numpy.random.seed(SEED)
def numpy_floatX(data):
return numpy.asarray(data, dtype=config.floatX)
# NOTE (bitesandbytes) : Important; set minibatch_size = 1 ?
def get_minibatches_idx(n, minibatch_size, shuffle=False):
"""
Used to shuffle the dataset at each iteration.
"""
idx_list = numpy.... | ="int32")
if shuffle:
numpy.random.shuffle(idx_list)
minibatches = []
minibatch_start = 0
for i in range(n // minibatch_size):
minibatches.append(idx_list[minibatch_start:
minibatch_start + minibatch_size])
minibatch_start += minibatch_size
if (minibatch_start != n... |
onaio/kpi | kpi/utils/viewset_mixins.py | Python | agpl-3.0 | 1,151 | 0 | # coding: utf-8
from django.shortcuts import get_object_or_404
from kpi.models import Asset, Collection
class AssetNestedObjectViewsetMixin:
@property
def asset(self):
if not hasattr(self, '_asset'):
asset = get_object_or_404(Asset, uid=self.asset_uid)
setattr(self, '_asset',... | if not hasattr(self, '_asset_uid'):
asset_uid = self.get_parents_query_dict().get('asset')
setattr(self, '_asset_uid', asset_uid)
return self._asset_uid
class CollectionNestedObjectViewsetMixin:
@property
def collection(self):
if not hasattr(self, '_collection'):... | ection
@property
def collection_uid(self):
if not hasattr(self, '_collection_uid'):
collection_uid = self.get_parents_query_dict().get('collection')
setattr(self, '_collection_uid', collection_uid)
return self._collection_uid
|
Yawning/pyptlib | pyptlib/util/subproc.py | Python | bsd-3-clause | 9,484 | 0.001792 | """Common tasks for managing child processes.
To have child processes actually be managed by this module, you should use
the Popen() here rather than subprocess.Popen() directly.
Some parts do not yet work fully on windows (sending/trapping signals).
"""
import atexit
import inspect
import os
import signal
import su... | descendents when this process dies.
"""
# TODO(infinity0): write a test for this, similar to test_killall_kill
# Note: setting this to True defeats the point of some of the tests, so
# keep the default value as False. Perhaps we could make that work better.
_kill_children_on_death = bool(os.getenv("... | win32con, win32job, win32process
_CHILD_PROCS = []
# TODO(infinity0): add functionality to detect when any child dies, and
# offer different response strategies for them (e.g. restart the child? or die
# and kill the other children too).
SINK = object()
# get default args from subprocess.Popen to use in subproc.Pope... |
dbbhattacharya/kitsune | vendor/packages/nose/nose/twistedtools.py | Python | bsd-3-clause | 5,391 | 0.002411 | """
Twisted integration
-------------------
This module provides a very simple way to integrate your tests with the
Twisted_ event loop.
You must import this module *before* importing anything from Twisted itself!
Example::
from nose.twistedtools import reactor, deferred
@deferred()
def test_resolve():
... | actor()
def stop_reactor():
"""Stop the reactor and join the reactor thread until it stops.
Call this function in teardown at the module or package level to
reset the twisted system after your tests. You *must* do this if
you mix tests using these tools a | nd tests using twisted.trial.
"""
global _twisted_thread
reactor.stop()
reactor_thread.join()
for p in reactor.getDelayedCalls():
if p.active():
p.cancel()
_twisted_thread = None
def deferred(timeout=None):
"""
By wrapping a test function with this decorator, you ca... |
jaakkojulin/potku | Widgets/MatplotlibImportTimingWidget.py | Python | gpl-2.0 | 6,288 | 0.005249 | # coding=utf-8
'''
Created on 6.6.2013
Updated on 29.8.2013
Potku is a graphical user interface for analyzation and
visualization of measurement data collected from a ToF-ERD
telescope. For physics calculations Potku uses external
analyzation components.
Copyright (C) Timo Konu
This program is free software; you... |
Args:
parent: An ImportTimingGraphDialog class object.
output_file: A string representing file to be graphed.
icon_manager: An IconManager class object.
timing: A tuple representing low & high t | iming limits.
'''
super().__init__(parent)
super().fork_toolbar_buttons()
self.canvas.manager.set_title("Import coincidence timing")
self.icon_manager = icon_manager
# TODO: Multiple timings ?
timing_key = list(timing.keys())[0]
self.__limit_low, self.__li... |
elatomczyk/dook | cowork/offices/urls.py | Python | gpl-3.0 | 270 | 0.003704 | from django.conf.urls import url
from . import views
urlpat | terns = [
url(r'^$', views.OfficeListView.as_view(), name='list'),
url(r'^add/$', views.OfficeAddView.as_view(), name='ad | d'),
#url(r'^delete/$', views.OfficeDeleteView.as_view(), name='delete'),
]
|
Victorian-Bioinformatics-Consortium/nesoni | nesoni/samcount.py | Python | gpl-2.0 | 46,723 | 0.020482 |
from nesoni import io, bio, grace, config, sam, span_index, annotation, working_directory
import os, sys, collections, random
def subsample(n, p):
#Note that this is rather inefficient
result = 0
for i in xrange(n):
if random.random() <= p:
result += 1
return result
def add_lists... | - Use alignments from "filter:" or "consensus:"\
""")
@config.String_flag('types', 'Comma separated list of feature types to us | e.')
@config.String_flag('locii', 'Only use features with these locus_tags. Note: --types filter is still applied.')
@config.String_flag('strand', """\
How to use the relative strand of fragment and feature:
pool - data is not single stranded, use both strands
forward - only count fragments on the same strand
revers... |
infinnovation/micropython | tests/net_hosted/connect_poll.py | Python | mit | 748 | 0.005348 | # test that socket.connect() has | correct polling behaviour before, during and after
try:
import usocket as socket, uselect as select
except:
import socket, select
def test(peer_addr):
s | = socket.socket()
poller = select.poll()
poller.register(s)
# test poll before connect
# note: CPython can return POLLHUP, so use the IN|OUT mask
p = poller.poll(0)
print(len(p), p[0][-1] & (select.POLLIN | select.POLLOUT))
s.connect(peer_addr)
# test poll during connection
print(... |
lampjian/effectivelang | CPP/CRF++/CRF++-0.54/python/CRFPP.py | Python | gpl-3.0 | 4,579 | 0.011793 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.38
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
# This file is compatible with both classic and new-style classes.
from sys import version_info
if version_info >= (... | e)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
... | e,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self)... |
kennedyshead/home-assistant | homeassistant/components/screenlogic/__init__.py | Python | apache-2.0 | 6,104 | 0.001147 | """The Screenlogic integration."""
import asyncio
from datetime import timedelta
import logging
from screenlogicpy import ScreenLogicError, ScreenLogicGateway
from screenlogicpy.const import (
EQUIPMENT,
SL_GATEWAY_IP,
SL_GATEWAY_NAME,
SL_GATEWAY_PORT,
)
from homeassistant.config_entries import Config... | import HomeAssistant
fr | om homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from .config_flow import async_discover_gateways_by_unique_id, name_for_mac
from .c... |
SINGROUP/pycp2k | pycp2k/classes/_coord2.py | Python | lgpl-3.0 | 328 | 0.006098 | from pycp2k.inputsection import InputSection
class _coord2(InputSection):
def __init__(self):
Inp | utSection. | __init__(self)
self.Default_keyword = []
self._name = "COORD"
self._repeated_default_keywords = {'Default_keyword': 'DEFAULT_KEYWORD'}
self._attributes = ['Default_keyword']
|
eofs/django-oauth-api | oauth_api/tests/test_client_credentials.py | Python | bsd-2-clause | 6,525 | 0.002912 | from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from oauth_api.models import get_application_model, AccessToken
from oauth_api.settings import oauth_api_settings
from oauth_api.tests.views import RESPONSE_DATA... | (response.data['token_t | ype'], 'Bearer')
self.assertTrue(self.scopes_valid(response.data['scope'], oauth_api_settings.SCOPES))
self.assertEqual(response.data['expires_in'], oauth_api_settings.ACCESS_TOKEN_EXPIRATION)
def test_invalid_scope(self):
"""
Request an access toke and try to fetch data using it
... |
vsoch/docfish | docfish/wsgi.py | Python | mit | 1,430 | 0 | '''
WSGI config
It exposes | the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
Copyright (c) 2017 Vanessa Sochat
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated docume... | on, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in... |
github/codeql | python/ql/src/experimental/Security/CWE-074/JinjaGood.py | Python | mit | 523 | 0 | from django.urls import path
from django.http import HttpResponse
from | jinja2 import Templa | te as Jinja2_Template
from jinja2 import Environment, DictLoader, escape
def a(request):
# Load the template
template = request.GET['template']
env = SandboxedEnvironment(undefined=StrictUndefined)
t = env.from_string(template)
name = request.GET['name']
# Render the template with the context ... |
ramcn/demo3 | venv/lib/python3.4/site-packages/compressor/tests/test_storages.py | Python | mit | 2,465 | 0.002028 | from __future__ import with_statement, unicode_literals
import errno
import os
from django.core.files.base import ContentFile
from django.core.files.storage import get_storage_class
from django.test import TestCase
from django.utils.functional import LazyObject
from compressor import storage
from compressor.conf impo... | aise OSError(errno.ENOENT, 'Fake ENOENT')
try:
os.remove = race_remove
self.default_storage.save('race.file', ContentFile('Fake ENOENT'))
self.default_storage.delete('race | .file')
self.assertFalse(self.default_storage.exists('race.file'))
finally:
# Restore os.remove
os.remove = original_remove
|
selvait90/jira-automation | sample.py | Python | gpl-3.0 | 349 | 0.014327 | #!/usr/bin/env python
# sample module
from jira.client import JIRA
def main():
jira = JIRA()
JIRA(options={'server': 'http://localhost:8100'})
projects = jir | a.projects()
print projects
for project in projects:
print project.key
| # Standard boilerplate to call the main() function.
if __name__ == '__main__':
main() |
xujun10110/url-abuse | url_abuse_async.py | Python | agpl-3.0 | 14,884 | 0.000739 | #!/usr/bin/env python
#
#
# Copyright (C) 2014 Sascha Rommelfangen, Raphael Vinot
# Copyright (C) 2014 CIRCL Computer Incident Response Center Luxembourg (SMILE gie)
#
from datetime import date
import json
import redis
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from pyfau... | ache:
if day is None:
day = date.today().isoformat()
else:
day = day.isoformat()
key = date.today().isoformat() + '_mails'
return r_cache.sadd(key, url)
def is_valid_url(url):
cached = _cache_get(url, 'valid')
key = date.today().isoformat() + '_submissio... | ex = Faup()
if url.startswith('hxxp'):
url = 'http' + url[4:]
elif not url.startswith('http'):
url = 'http://' + url
logging.debug("Checking validity of URL: " + url)
fex.decode(url)
scheme = fex.get_scheme()
host = fex.get_host()
if scheme is None or host is None:
re... |
ulif/pulp | server/pulp/server/managers/consumer/profile.py | Python | gpl-2.0 | 5,469 | 0.000731 | """
Contains profile management classes
"""
from celery import task
from pulp.plugins.loader import api as plugin_api, exceptions as plugin_exceptions
from pulp.plugins.profiler import Profiler
from pulp.server.async.tasks import Task
from pulp.server.db.model.consumer import UnitProfile
from pulp.server.exceptions im... | @param consumer_id: uniquely identifies the consumer.
@type consumer_id: str
@return: A list of profiles:
{consumer_id:<str>, content_type:<str>, profile:<dict>}
@rtype: list
"""
collection = UnitProfile.get_collection()
query = dict(consumer_id=consumer_... | """
Return a list of unit profiles that match the provided criteria.
@param criteria: A Criteria object representing a search you want
to perform
@type criteria: pulp.server.db.model.criteria.Criteria
@return: list of UnitProfile instances
... |
tSed/buildroot | support/testing/tests/fs/test_jffs2.py | Python | gpl-2.0 | 1,675 | 0.001791 | import os
import subprocess
import infra.basetest
def jffs2dump_find_file(files_list, fname):
for file_name in files_list:
file_name = file_name.strip()
if file_name.startswith("Dirent") and file_name.endswith(fname):
return True
return False
class TestJffs2(infra.basetest.BRTest)... | sybox"))
self.emulator.boot(arch="armv7",
kernel="builtin",
kernel_cmdline=["root=/dev/mtdblock0",
"rootfstype=jffs2"],
options=["-drive", "file={},if=pflash".format(img)])
self.e... | cmd = "mount | grep '/dev/root on / type jffs2'"
_, exit_code = self.emulator.run(cmd)
self.assertEqual(exit_code, 0)
|
affo/nova | nova/tests/unit/api/openstack/compute/contrib/test_block_device_mapping.py | Python | apache-2.0 | 13,756 | 0.000073 | # Copyright 2013 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 requ... | 'metadata': {
'hello': 'world',
'open': 'stack',
},
},
}
if no_image:
del body['server']['imageRef']
return body
def _test_create(self, params, no_image=False, override_controller=None):
body = self... | /fake/servers')
req.method = 'POST'
req.headers['content-type'] = 'application/json'
req.body = jsonutils.dumps(body)
if override_controller:
override_controller.create(req, body=body).obj['server']
else:
self.controller.create(req, body=body).obj['serve... |
plum-umd/java-sketch | java_sk/util.py | Python | mit | 2,237 | 0.008941 | import os
from itertools import ifilter, ifilterfalse
from ast.utils import utils
from ast.body.classorinterfacedeclaration import ClassOrInterfaceDeclaration
import glob2
"""
regarding paths and files
"""
# clean all the contents in the designated path, excluding that path
def clean_dir(path):
for root, dirs, ... | ]
# return tname
# # unboxking, e.g., Character -> char
# def unboxing(tname):
# if tname in C.autoboxing:
# for i, v in enumerate(C.autoboxing):
# if tname == v: return C.primitives[i]
# return tname
def add_object(ast):
clss = utils.extract_nodes([ClassOrInterfaceDeclaration], ast)
clss... | endsList:
n.extendsList = [obj]
obj.subClasses.append(n)
map(obj_subs, clss)
ast.types.append(obj)
def rm_subs(clss):
return filter(lambda c: not c.extendsList and not c.implementsList, clss)
def sanitize_mname(mname):
return mname.replace("[]",'s')
# ~ List.partition in OCaml
#... |
yehnan/python_book_yehnan | ch12/ch12_flow.py | Python | gpl-2.0 | 359 | 0.011142 |
def foo():
try :
raise ValueError
ex | cept IndexError:
p | rint('IndexError')
finally:
print('foo finally')
print('foo end')
def bar():
try:
foo()
except ValueError:
print('ValueError')
finally:
print('bar finally')
print('bar end')
bar()
print('program end')
|
ouroboros8/phrasepasser | tests.py | Python | mit | 2,692 | 0.001486 | import unittest
import string, random
from generate import gen_passphra | se, possibilities, \
possibilities_magnitude
def generate_word(
size=6,
chars=string.digits+string.ascii_letters):
'''
| Return a (non-cryptographically-secure) random word 'size'
characters long composed of the characters 'chars'.
'''
return ''.join([random.choice(chars) for _ in range(0, size)])
def generate_test_wordlist(size=100):
'''
Returns a string of 'size' random words.
'''
max_word_len = 12
mi... |
akamensky/sssd | src/tests/intg/kdc.py | Python | gpl-3.0 | 5,483 | 0 | #
# MIT Kerberos server class
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful, bu... | config(self, include_files):
for name, contents in include_files.items():
include_fpath = os.path.join(self.includedir, name)
with open(include_fpath, 'w') as include_file:
include_fi | le.write(contents)
def add_principal(self, princ, password=None):
args = ["kadmin.local", "-q"]
if password is None:
args += ["addprinc -randkey %s" % (princ)]
else:
args += ["addprinc -pw %s %s" % (password, princ)]
return self._run_in_env(args, self.get_krb... |
jayceyxc/hue | apps/filebrowser/src/filebrowser/lib/archives.py | Python | apache-2.0 | 7,361 | 0.009781 | #!/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... | for the specific language governing permissions and
# limitations under the License.
#
# Utilities for dealing with file modes.
import bz2
import os
import posixpath
import tarfile
import tempfile
from desktop.lib.exceptions_renderable | import PopupException
from django.utils.translation import ugettext as _
from filebrowser.conf import ARCHIVE_UPLOAD_TEMPDIR
from zipfile import ZipFile
__all__ = ['archive_factory']
class Archive(object):
"""
Acrchive interface.
"""
def extract(self, path):
"""
Extract an Archive.
Should retur... |
holgerdell/td-validate | autotest-tw-solver.py | Python | mit | 6,041 | 0.001655 | #!/usr/bin/env python3
"""
Automatically test a given treewidth solver:
./autotest-tw-solver.py path/to/my/solver
The test is run on some corner cases, and on graphs were past PACE submissions
exhibited bugs.
Optional argument:
--full run test on all graphs with min-degree 3 and at most 8 vertices
Require... | 't care)
"""
# This covers some corner cases (comments, empty graphs, etc)
for grfile in glob.glob("test/valid/*.gr") | :
yield grfile, open(grfile, "r"), None
# Test cases where some tw-solvers were buggy in the past
for grfile in glob.glob("test/tw-solver-bugs/*.gr"):
treewidth = None
with open(grfile[:-3] + ".td") as td_stream:
treewidth = read_tw_from_td(td_stream)
yield grfile, o... |
shamangeorge/beets | beetsplug/gmusic.py | Python | mit | 5,347 | 0 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2017, Tigran Kostandyan.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitatio... | _id']
uploader_name = self.config['uploader_name']
self.m.login(oauth_credentials=oauth_file,
uploader_id=uploader_id.as_str().upper() or None,
uploader_name=uploader_name.as_str() or None)
| else:
self.m.perform_oauth(oauth_file)
def upload(self, lib, opts, args):
items = lib.items(ui.decargs(args))
files = self.getpaths(items)
self.authenticate()
ui.print_(u'Uploading your files...')
self.m.upload(filepaths=files)
ui.print_(u'Your files we... |
yfried/ansible | lib/ansible/modules/network/f5/bigip_ike_peer.py | Python | gpl-3.0 | 25,483 | 0.001373 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | ption:
- C(always) will allow to update passwords if the user chooses to do so.
C(on_create) will only set the password for newly created IKE peers.
default: always
choices:
- always
- on_create
partition:
description:
- Device partition to m | anage resources on.
default: Common
state:
description:
- When C(present), ensures that the resource exists.
- When C(absent), ensures the resource is removed.
default: present
choices:
- present
- absent
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
-... |
rybesh/pybtex | pybtex/bibtex/names.py | Python | mit | 6,400 | 0.003906 | # Copyright (c) 2007, 2008, 2009, 2010, 2011 Andrey Golovizin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... | names = join(names, '.~', '. ')
else:
names = join(names)
else:
names = self.delimiter.join(names)
formatted_part = self.pre_text + names + self.post_text
if self.tie == '~':
discretionary = tie_or_space(formatted_part)
elif self.tie =... | port name_part
class NamePart(object):
def __init__(self, part, abbr=False):
self.part = part
self.abbr = abbr
def __repr__(self):
abbr = 'abbr' if self.abbr else ''
return 'person.%s(%s)' % (self.part, abbr)
kwargs... |
ahmadiga/min_edx | openedx/core/djangoapps/course_groups/views.py | Python | agpl-3.0 | 19,178 | 0.002399 | """
Views related to course groups functionality.
"""
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_POST
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage
from django.core.urlresolvers import reverse
from dj... | .json.get(
'cohorted_course_wide_discussions', cohorted_course_wide_discussions
)
cohorted_inline_discussions = request.json.get(
| 'cohorted_inline_discussions', cohorted_inline_discussions
)
settings_to_change['cohorted_discussions'] = cohorted_course_wide_discussions + cohorted_inline_discussions
if 'always_cohort_inline_discussions' in request.json:
settings_to_change['always_cohort_in... |
darren-rogan/CouchPotatoServer | couchpotato/core/providers/automation/imdb/__init__.py | Python | gpl-3.0 | 907 | 0.003308 | from .main import IMDB
def start():
return IMDB()
config = [{
'name': 'imdb',
'groups': [
{
'tab': 'automation',
'name': 'imdb_automation',
'label': 'IMDB',
'description': 'From any <strong>public</strong> IMDB watchlists. Url should be the RSS link.... | 'default': False,
'type': 'enabler',
},
{
'name': 'automation_urls_use',
'label': 'Use',
},
{
'name': 'automation_urls',
'label': 'url',
... | },
],
}]
|
savioabuga/phoenix | phoenix/utils/view_utils.py | Python | bsd-3-clause | 528 | 0.003788 | class AjaxTemplateMixin(object):
ajax_template_name = ''
template | _name = ''
def dispatch(self, request, *args, **kwargs):
if not hasattr(self, 'ajax_template_name'):
split = self.template_name.split('.html')
split[-1] = '_inner'
split.appe | nd('.html')
self.ajax_template_name = ''.join(split)
if request.is_ajax():
self.template_name = self.ajax_template_name
return super(AjaxTemplateMixin, self).dispatch(request, *args, **kwargs) |
Vauxoo/server-tools | module_auto_update/tests/__init__.py | Python | agpl-3.0 | 122 | 0 | # License LGPL-3.0 or later (https://www.g | nu.org/licenses/lgpl).
from . import test_ad | don_hash
from . import test_module
|
akretion/account-financial-tools | currency_rate_update/__openerp__.py | Python | agpl-3.0 | 1,514 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 CamptoCamp. All rights reserved.
# @author Nicolas Bessi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publi... | ed to ensure account security groups are present
],
"data": [
"view/service_cron_data.xml",
"view/currency_rate_update.xml",
"view/company_view.xml",
"security/ir.model.acces | s.csv",
],
"demo": [],
"active": False,
'installable': True
}
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/dogapi/stats/__init__.py | Python | agpl-3.0 | 51 | 0 | from dogapi.stats.dog_stats_api import DogStat | sApi
| |
LaunchKey/launchkey-python | launchkey/factories/directory.py | Python | mit | 1,866 | 0 | """Directory Factory"""
# pylint: disable=too-many-arguments
from .. import LAUNCHKEY_PRODUCTION
from ..clients import DirectoryClient, ServiceClient
from .base import BaseFactory
class DirectoryFactory(BaseFactory):
"""Factory for creating clients when representing a LaunchKey Directory"""
def __init__(se... | :param directory_id: UUID for the requesting directory
:param private_key: PEM formatted private key string
:param url: URL for the LaunchKey API
:param testing: Boolean stating whether testing mode is being used.
This will determine whether SSL validation occurs.
:param: transpo... | currently only supported transport is
launchkey.transports.JOSETransport. If you wish to set encryption or
hashing algorithms, this is where you would do it. IE:
JOSETransport(jwt_algorithm="RS512", jwe_cek_encryption="RSA-OAEP",
jwe_claims_encryption="A256CBC-HS512", content_hash_algori... |
danielecook/gist-alfred | github/Permissions.py | Python | mit | 3,634 | 0.008255 | # -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | -pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# #
# This file | is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the te... |
pguth/borgweb | borgweb/views/logs.py | Python | bsd-3-clause | 4,696 | 0.000639 | """
logs view
"""
import os
from flask import current_app, render_template, jsonify
from . import blueprint
SUCCESS, INFO, WARNING, DANGER = 'success', 'info', 'warning', 'danger'
def overall_classifier(f):
# TODO: we need sane logging with log levels, sane return codes, logging
# of return codes in... | ion)
else:
log_lines = []
log_lines = [(line_classifier(line), line) for line in log_lines]
return jsonify(dict(lines=log_lines, offset=offset))
@blueprint.route('/logs/<int:index>')
def get_log(index):
log_dir, log_files = _get_logs()
try:
log_file = log_files[index]
except In... | lse:
log_file = os.path.join(log_dir, log_file)
with open(log_file, 'r') as f:
length = f.seek(0, os.SEEK_END)
status = overall_classifier(f)
return jsonify(dict(filename=log_file, status=status, length=length))
@blueprint.route('/logs')
def get_logs():
log_dir, log_files = _get_lo... |
OCA/carrier-delivery | delivery_carrier_default_tracking_url/models/stock_picking.py | Python | agpl-3.0 | 340 | 0 | # -*- coding: utf-8 -*-
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://w | ww.gnu.org/licenses/agpl).
from odoo import fields, models
class StockPicking(models.Model):
_inherit = 'stock.picking'
| default_tracking_url = fields.Char(
related='carrier_id.default_tracking_url',
readonly=True,
)
|
mrh1997/pyclibrary | pyclibrary/c_parser.py | Python | mit | 62,500 | 0.00024 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by PyCLibrary Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT/X11 license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------... | _(cls, (type_spec,) + declarators)
def __init__(self, type_spec, *declarators, **argv):
super(Type, self).__init__()
self.type_quals = (argv.pop('type_quals', None) or
((),) * (1 + len(declarators)))
if len(self.type_quals) != 1 + len(declarators):
rai... | rs")
assert len(argv) == 0, 'Invalid Parameter'
def __eq__(self, other):
if isinstance(other, Type):
if self.type_quals != other.type_quals:
return False
return super(Type, self).__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
... |
2ndQuadrant/ansible | test/lib/ansible_test/_internal/ci/azp.py | Python | gpl-3.0 | 10,254 | 0.003511 | """Support code for working with Azure Pipelines."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import tempfile
import uuid
from .. import types as t
from ..encoding import (
to_bytes,
)
from ..config import (
CommonConfig,
TestConfig,
)
... | are_core_ci_auth(self, context): # type: (AuthContext) -> t.Dict[str, t.Any]
"""Return authentication details for Ansible Core CI."""
try:
request = dict(
| org_name=os.environ['SYSTEM_COLLECTIONURI'].strip('/').split('/')[-1],
project_name=os.environ['SYSTEM_TEAMPROJECT'],
build_id=int(os.environ['BUILD_BUILDID']),
task_id=str(uuid.UUID(os.environ['SYSTEM_TASKINSTANCEID'])),
)
except KeyError as... |
glaudsonml/kurgan-ai | libs/Target.py | Python | apache-2.0 | 2,614 | 0.014537 | '''
Kurgan AI Web Application Security Analyzer.
http: | //www.kurgan.com.br/
Author: Glaudson Ocampos - <glaudson@vortexai.com.br>
Created in May, 11th 2016.
'''
import requests
import config
import sys
import warnings
import validators
sys.path.append('../')
class Target(object):
host = None
method = ''
headers = {}
uri = ''
webserver = ''
schem... | uri = '/'
scheme = 'http'
def set_host(self, val):
self.host = val
def get_host(self):
return self.host
def set_port(self, val):
self.port = val
def get_port(self):
return self.port
def set_method(self, val):
self.method = val
... |
iulian787/spack | var/spack/repos/builtin/packages/r-pkgmaker/package.py | Python | lgpl-2.1 | 1,591 | 0.001257 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RPkgmaker(RPackage):
"""This package provides some low-level utilities to use for package
... | 6a')
depends_on('r@3.0.0:', type=('build', 'run'))
depends_on('r-registry', type=('build', 'run'))
depends_on('r-codetools', type=('build', 'run'))
depends_on('r-digest', type=('build', 'run'))
depend | s_on('r-stringi', type=('build', 'run'))
depends_on('r-magrittr', type=('build', 'run'))
depends_on('r-stringr', type=('build', 'run'))
depends_on('r-xtable', type=('build', 'run'))
depends_on('r-withr', type=('build', 'run'))
depends_on('r-bibtex@0.4:', type=('build', 'run'))
|
abacusresearch/gitflow | gitflow/procedures/scheme/scheme_procedures.py | Python | mit | 10,745 | 0.004281 | import os
from typing import Optional
import semver
from gitflow import _, version
from gitflow.common import Result
from gitflow.const import VersioningScheme
from gitflow.version import VersionConfig
def filter_sequence_number(version_config, prev_version, gl | obal_seq):
if version_config.versioning_scheme == VersioningScheme.SEMVER_WITH_SEQ:
if prev_version is not None:
version_seq = semver.parse_version_info(prev_version).prerelease
if version_seq is not None:
# must throw if not an integer
version_seq = i... | ueError('the version sequence number is defined, while the global one is not')
if version_seq > global_seq:
raise ValueError('the version sequence number is greater than the global sequence number')
if global_seq is None:
global_seq = 0
else:
global_se... |
rasjostrom/hocapontas | hocapontas/storage/json_db.py | Python | gpl-3.0 | 1,393 | 0.000718 | import json
import os.path
from shutil import copyfile
DB_PATH = os.path.join(os.path.expanduser('~'), '.ulf.json')
DB_BAK_PATH = os.path.join(os.path.expanduser('~'), '.ulf.json.bak')
class JsonDB:
def read(self):
data = '[]'
try:
with open(DB_PATH, 'r') as f:
data ... | , 'w') as f:
json.dump(data, f, ensure_ascii=False)
def update(self, item_id, item):
copyfile(DB_PATH, DB_BAK_PATH)
data = self.read()
data[item_id] = item
with open(DB_PATH, 'w') as f:
json.dump(data, f, ensure_ascii=False)
def reset(self):
if o... | n(DB_PATH, 'w') as f:
f.write('[]')
|
pychess/pychess | lib/pychess/System/uistuff.py | Python | gpl-3.0 | 16,160 | 0.000928 | import colorsys
import sys
import xml.etree.cElementTree as ET
# from io import BytesIO
from gi.repository import Gtk, Gdk, GObject, Pango
from gi.repository.GdkPixbuf import Pixbuf
from pychess.System import conf
from pychess.System.Log import log
from pychess.System.prefix import addDataPrefix
def createCombo(com... | ensures a consistent lightness over all colors.
rgb = colorsys.hsv_to_rgb(hue, 1, 1)
rgb = colorsys.hsv_to_rgb(hue, 1, (1 - rgb[1]) * 0.2 + 0.6)
# This algorithm ought to balance colors more precisely, but it overrates
# the lightness of yellow, and nearly makes it black
# yiq = colorsys.rgb_to_yiq... | (.125, yiq[1], yiq[2])
return rgb
def keepDown(scrolledWindow):
def changed(vadjust):
if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
vadjust.set_value(vadjust.get_upper() - vadjust.get_page_size())
vadjust.need_scroll = True
scrolledWindow.get_vadjustment()... |
alirizakeles/tendenci | tendenci/apps/emails/models.py | Python | gpl-3.0 | 6,803 | 0.004851 | import uuid
from django.db import models
from django.core.mail.message import EmailMessage
from django.conf import settings
from tendenci.apps.perms.models import TendenciBaseModel
from tinymce import models as tinymce_models
from tendenci.apps.site_settings.utils import get_setting
class Email(TendenciBaseModel):
... | ah] to %5Bblah%5D for replace line
tmp_value = "%5B" + key[1:-1] + "%5D"
if email_d[key] <> None:
self.body = self.body.replace(key, email_d[key])
self.body = self.bod | y.replace(tmp_value, email_d[key])
else:
self.body = self.body.replace(key, '')
self.body = self.body.replace(tmp_value, '')
return boo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.