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 |
|---|---|---|---|---|---|---|---|---|
elena/django | tests/template_tests/syntax_tests/i18n/test_blocktranslate.py | Python | bsd-3-clause | 27,773 | 0.003497 | import inspect
import os
from functools import partial, wraps
from asgiref.local import Local
from django.template import Context, Template, TemplateSyntaxError
from django.test import SimpleTestCase, override_settings
from django.utils import translation
from django.utils.safestring import mark_safe
from django.util... | sertEqual(output, 'å')
@setup({'i18n05': '{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx{% endblocktranslate %}'})
def test_i18n05(self):
"""simple translation of a stri | ng with interpolation"""
output = self.engine.render_to_string('i18n05', {'anton': 'yyy'})
self.assertEqual(output, 'xxxyyyxxx')
@setup({'i18n07': '{% load i18n %}'
'{% blocktranslate count counter=number %}singular{% plural %}'
'{{ counter }} plural{% en... |
tensorflow/similarity | tensorflow_similarity/retrieval_metrics/bndcg.py | Python | apache-2.0 | 5,659 | 0.00053 | # Copyright 2021 The TensorFlow 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 or agreed to ... | rank = tf.range(1, self.k + 1, dtype="float")
rank_weights = tf.math.divide(tf.math.log1p(rank), tf.math.log(2.0))
| # the numerator is simplier here because we are using binary weights
dcg = tf.math.reduce_sum(k_slice / rank_weights, axis=1)
# generate the "ideal ordering".
ideal_ordering = tf.sort(k_slice, direction="DESCENDING", axis=1)
idcg = tf.math.reduce_sum(ideal_ordering / rank_weights, a... |
Neluso/SIFPAF | plot.py | Python | gpl-3.0 | 1,454 | 0 | import matplotlib.pyplot as plt
from h5py import File
from numpy import array
def launch_plots(): # TODO set activation of different plots
plot3d = plt.figure( | 'Plot 3D')
xy_plane = plt.fi | gure('XY')
xz_plane = plt.figure('XZ')
yz_plane = plt.figure('YZ')
ax_plot3d = plot3d.add_subplot(111, projection='3d')
ax_xy = xy_plane.add_subplot(111)
ax_xz = xz_plane.add_subplot(111)
ax_yz = yz_plane.add_subplot(111)
ax_plot3d.set_title('3D')
ax_plot3d._axis3don = False
ax_xy.se... |
cmusatyalab/elijah-provisioning | elijah/provisioning/server.py | Python | apache-2.0 | 46,655 | 0.004758 | #!/usr/bin/env python
#
# Cloudlet Infrastructure for Mobile Computing
#
# Author: Kiryong Ha <krha@cmu.edu>
#
# Copyright (C) 2011-2013 Carnegie Mellon 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist | ributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import functools
import traceback
import sys
import time
impo... |
pandaoknight/leetcode | sum_problem_dynamic_programming/two-sum-iv-input-is-a-bst/hash-table.py | Python | gpl-2.0 | 1,485 | 0.005506 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x, left = None, right = None):
self.val = x
self.left = left
self.right = right
class Solution(object):
"""
【思路】
1. 这里我们使用hashtable,而python中的dict就是hashtable... | nt s.findTarget(TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(6, None, TreeNode(7))), 9)
print s.findTarget(TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(6, None, TreeNode(7))), 13)
print s.findTarget(TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(6, None, Tre | eNode(7))), 20)
|
simbha/mAngE-Gin | lib/django/utils/version.py | Python | mit | 2,279 | 0.000878 | from __future__ import unicode_literals
import datetime
import os
import subprocess
from django.utils.lru_cache import lru_cache
def get_version(version=None):
"Returns a PEP 386-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version num... | S format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file_ | _)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(times... |
zsdonghao/tensorlayer | tensorlayer/initializers.py | Python | apache-2.0 | 7,005 | 0.001999 | #! /usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
__all__ = [
'Initializer', 'Zeros', 'Ones', 'Constant', 'RandomUniform', 'RandomNormal', 'TruncatedNormal',
'deconv2d_bilinear_upsampling_initializer'
]
class Initializer(object):
"""Initializer base class: all initial... | zer):
"""Initializer that generates tensors initialized to a con | stant value.
Parameters
----------
value : A python scalar or a numpy array.
The assigned value.
"""
def __init__(self, value=0):
self.value = value
def __call__(self, shape, dtype=None):
return tf.constant(self.value, shape=shape, dtype=dtype)
def get_config(sel... |
codelieche/codelieche.com | apps/account/views/message.py | Python | mit | 3,318 | 0.000353 | # -*- coding:utf-8 -*-
"""
用户消息相关的视图
"""
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from account.serializers.message... | ss = MessageSerializer
# 权限控制
permission_classes = (IsAuthenticated,)
class MessageListView(generics.ListAPIView):
"""
用户消息列表api View
> 用户只能看到自 | 己的消息列表
"""
# queryset = Message.objects.filter(deleted=False)
serializer_class = MessageSerializer
# 权限控制
permission_classes = (IsAuthenticated,)
# 搜索和过滤
filter_backends = (DjangoFilterBackend, SearchFilter)
filter_fields = ('category', 'unread')
search_fields = ('title', 'content')... |
o-unity/lanio | old/lsrv/bin/getTemp.py | Python | gpl-2.0 | 977 | 0.022518 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re, os, time
# function: read and parse sensor data file
def read_sensor(path):
value = "U"
try:
f = open(path, "r")
line = f.readline()
if re.match(r"([0-9a-f]{2} ){9}: crc=[0-9a-f]{2} YES", line):
line = f.readline()
m = re.match(r"([0-9a-... | s:
# path = "/sys/bus/w1/devices/28-0314640daeff/w1_slave"
# print read_sensor(path)
# time.sleep(30)
flag = 1
temp = 0
temp2 = 0
while (flag):
temp2 = temp
temp = read_sensor("/sys/bus/w1/devices/28-0314640daeff/w1_slave") |
if temp2 != temp:
print temp
time.sleep(11)
|
pierce403/EmpirePanel | lib/modules/collection/screenshot.py | Python | bsd-3-clause | 3,876 | 0.015222 | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Get-Screenshot',
'Author': ['@obscuresec', '@harmj0y'],
'Description': ('Takes a screenshot of the current desktop and '
'returns ... | if self.options['Ratio']['Value']:
if self.options['Ratio']['Value']!='0':
self.info['OutputExtension'] = 'jpg'
else:
self.options['Ratio']['Value'] = ''
self.info['OutputExtension'] = 'png'
else:
self.info['OutputExtension'] =... | values['Value'] and values['Value'] != '':
if values['Value'].lower() == "true":
# if we're just adding a switch
script += " -" + str(option)
else:
script += " -" + str(option) + " " + str(values['Value'])
... |
brainwane/zulip | zerver/tests/test_external.py | Python | apache-2.0 | 5,500 | 0.003273 | import time
from unittest import mock
import DNS
from django.conf import settings
from django.core.exceptions import ValidationError
from django.http import HttpResponse
from zerver.forms import email_is_not_mit_mailing_list
from zerver.lib.rate_limiter import (
RateLimitedUser,
RateLimiterLockingException,
... | elf) -> None:
with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)):
self.assertEqual(compute_mit_user_fullname("1234567890@mit.edu"), "1234567890@mit.edu")
with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDO... | tch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)):
self.assertRaises(ValidationError, email_is_not_mit_mailing_list, "1234567890@mit.edu")
with mock.patch('DNS.dnslookup', side_effect=DNS.Base.ServerError('DNS query status: NXDOMAIN', 3)):
self.asser... |
lk-geimfari/elizabeth | mimesis/data/int/person.py | Python | mit | 140,388 | 0 | """Provides all the generic data related to the personal information."""
from typing import Tuple
BLOOD_GROUPS = (
"O+",
"A+",
"B+",
"AB+",
"O−",
"A−",
"B−",
"AB−",
)
GENDER_SYMBOLS: Tuple[str, str, str] = (
"♂",
"♀",
"⚲",
)
USERNAMES = [
"aaa",
"aaron",
"aban... | eptable",
"acceptance",
"accepte | d",
"accepting",
"accepts",
"access",
"accessed",
"accessibility",
"accessible",
"accessing",
"accessories",
"accessory",
"accident",
"accidents",
"accommodate",
"accommodation",
"accommodations",
"accompanied",
"accompanying",
"accomplish",
"accom... |
mlflow/mlflow | examples/pytorch/AxHyperOptimizationPTL/ax_hpo_iris.py | Python | apache-2.0 | 2,854 | 0.002803 | import argparse
import mlflow
from ax.service.ax_client import AxClient
from iris import IrisClassification
from iris_data_module import IrisDataModule
import pytorch_lightning as pl
def train_evaluate(params, max_epochs=100):
model = IrisClassification(**params)
dm = IrisDataModule()
dm.setup(stage="fit"... | er of ax-client experimental trials. Type:int
:param params: Model parameters. Type:dict
"""
with mlflow.start_run(run_name="Parent Run"):
train | _evaluate(params=params, max_epochs=max_epochs)
ax_client = AxClient()
ax_client.create_experiment(
parameters=[
{"name": "lr", "type": "range", "bounds": [1e-3, 0.15], "log_scale": True},
{"name": "weight_decay", "type": "range", "bounds": [1e-4, 1e-3]},
... |
alexforencich/python-ivi | ivi/anritsu/anritsuMN9610B.py | Python | mit | 7,432 | 0.005113 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2017 Alex Forencich
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 righ... | code = int(self._ask("ERR?").split(' ')[1])
error_message = ["No error", "Command error", "Execution error", "Co | mmand and execution error"][error_code]
return (error_code, error_message)
def _utility_lock_object(self):
pass
def _utility_reset(self):
pass
def _utility_reset_with_defaults(self):
self._utility_reset()
def _utility_self_test(self):
code = 0
message ... |
shawnadelic/shuup | shuup/admin/modules/shops/views/edit.py | Python | agpl-3.0 | 4,592 | 0.001089 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
from djang... | nguages", shop_languages)
return obj
class ShopBaseFormPart(FormPart):
priority = 1
def get_form_defs(self):
yield Templated | FormDef(
"base",
ShopBaseForm,
template_name="shuup/admin/shops/_edit_base_shop_form.jinja",
required=True,
kwargs={
"instance": self.object,
"languages": configuration.get(self.object, "languages", settings.LANGUAGES)
... |
emilybache/DiamondKata | python/test_diamond_centrist_iterative.py | Python | mit | 5,199 | 0.004039 | """
These test cases can be used to test-drive a solution to the diamond kata, in an interative manner.
The idea is that you iterate towards a full solution, each test cycle you are closer to a full solution
than in the previous one. The thing with iterating is you may delete stuff that was there before,
or add stuff ... | "Z"],
# [" ", " ", " "]]
def ignore_Diamond_with_0_1_coordinates_marked_with_a_Z():
assert diamond.Diamond('B').diamond() == \
[[" ", "Z", " "],
[" ", " ", " "],
[" ", " ", " "]]
# assert diamond.Diamond('C').diamond() == \
# [[" ", " ", " ", " ", " "],
# ["... | [" ", " ", " ", " ", " "],
# [" ", " ", " ", " ", " "]]
def ignore_Diamond_with_minus2_1_coordinates_marked_with_a_Z():
assert diamond.Diamond('C').diamond() == \
[[" ", " ", " ", " ", " "],
["Z", " ", " ", " ", " "],
[" ", " ", " ", " ", " "],
[" ", " ", " ",... |
coskundeniz/bitirme-projesi | config.py | Python | gpl-2.0 | 370 | 0 | # -*- coding: utf-8 -*-
import os
DEBUG = True
SECRET_KEY = '\x0f v\xa5!\xb8*\x14\xfeY[\xaf\x83\xd4}vv*\xfb\x85'
abs_pat | h = os.path.abspath('app.db')
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + abs_path
# config for forms
CSRF_ENABLED = True
CSRF_SESSION_KEY = '\x0f v\xa5!\xb8*\x14\xfeY[\xaf\x83\xd4}vv*\xfb\x85'
UPLOAD_FOLDER = os.path.j | oin(os.getcwd(), "uploads/")
|
ge0rgi/cinder | cinder/scheduler/filter_scheduler.py | Python | apache-2.0 | 29,487 | 0 | # Copyright (c) 2011 Intel Corporation
# Copyright (c) 2011 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.... | l_exists_on'] = backend
weighed_backends = self._get_weighted_candidates(context, request_spec,
filter_properties)
if n | ot weighed_backends:
raise exception.NoValidBackend(
reason=_('No valid backends for volume %(id)s with type '
'%(type)s') % {'id': request_spec['volume_id'],
'type': request_spec['volume_type']})
for weighed_backend i... |
gem/sidd | ui/helper/ms_attr_delegate.py | Python | agpl-3.0 | 3,434 | 0.00728 | # Copyright (c) 2011-2013, ImageCat Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is... | useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
| # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
dialog for editing mapping scheme branches
"""
from PyQt4.QtCore import Qt, QVariant
from PyQt4.QtGui import QItemDelegate, QComboBox, QMessageBox
from ui.con... |
upsight/doctor | doctor/types.py | Python | mit | 33,198 | 0.000151 | """
Copyright © 2017, Encode OSS Ltd. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following dis... | UnionType can have multiple types, simply return the native type
of the first type defined in the types attribute.
If _native_type is set based on initializing a value with the class,
then we return the dynamically modified | type that matches that of the
value used during instantiation. e.g.
>>> from doctor.types import UnionType, string, boolean
>>> class BoolOrStr(UnionType):
... description = 'bool or str'
... types = [boolean('a bool'), string('a string')]
...
>>> BoolOrStr... |
dataversioncontrol/dvc | setup.py | Python | apache-2.0 | 1,895 | 0 | from setuptools import setup, find_packages
from dvc import VERSION
install_requires = [
"ply>=3.9", # See https://github.com/pyinstaller/pyinstaller/issues/1945
"configparser>=3.5.0",
"zc.lockfile>=1.2.1",
"future>=0.16.0",
"colorama>=0.3.9",
"configobj>=5.0.6",
"networkx>=2.1",
"pyy... | remotes = gs + s3 + azure + ssh
setup(
name="dvc",
version=VERSION,
description="Git for data scientists - manage your code and data together",
long_description=open("README.rst", "r").read(),
author="Dmitry Petrov",
author_email="dmitry@dataversioncontrol.com",
download_url="https://github... | ": gs,
"s3": s3,
"azure": azure,
"ssh": ssh,
# NOTE: https://github.com/inveniosoftware/troubleshooting/issues/1
':python_version=="2.7"': ["futures"],
},
keywords="data science, data version control, machine learning",
classifiers=[
"Development Status :: 4 -... |
cynja/coffeenator | webinterface/urls.py | Python | gpl-3.0 | 551 | 0.00363 | from django.conf.urls import patterns, include, url
urlpatt | erns = | patterns('',
url(r'^$', 'webinterface.view.dashboard.main'),
url(r'^dashboard/$', 'webinterface.view.dashboard.main'),
url(r'^login/$', 'webinterface.view.login.main'),
url(r'^login/ajax/$', 'webinterface.view.login.ajax'),
url(r'^settings/$', 'webinterface.view.settings.main'),
url(r'^settings... |
OCA/knowledge | document_page_portal/models/document_page.py | Python | agpl-3.0 | 381 | 0 | # Copyright 2020 - TODAY, Marcel S | avegnago - Escodoo
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class DocumentPage(models.Model):
_inherit = "document.page"
is_public = fields.Boolean(
"Public Page",
help="If true | it allows any user of the portal to have "
"access to this document.",
)
|
kehao95/Wechat_LearnHelper | src/env/lib/python3.5/site-packages/aiohttp/hdrs.py | Python | gpl-3.0 | 3,148 | 0 | """HTTP Headers constants."""
from .multidict import upstr
METH_ANY = upstr('*')
METH_CONNECT = upstr('CONNECT')
METH_HEAD = upstr('HEAD')
METH_GET = upstr('GET')
METH_DELETE = upstr('DELETE')
METH_OPTIONS = upstr('OPTIONS')
METH_PATCH = upstr('PATCH')
METH_POST = upstr('POST')
METH_PUT = upstr('PUT')
METH_TRACE = ups... | AUTHORIZATION = upstr('AUTHORIZATION')
CACHE_CONTROL = upstr('CACHE-CONTROL')
CONNECTION = upstr('CONNECTION')
CONTENT_DISPOSITION = upstr('CONTENT-DISPOSITION')
CONTENT_ENCODING = upstr('CONTENT-ENCODING') |
CONTENT_LANGUAGE = upstr('CONTENT-LANGUAGE')
CONTENT_LENGTH = upstr('CONTENT-LENGTH')
CONTENT_LOCATION = upstr('CONTENT-LOCATION')
CONTENT_MD5 = upstr('CONTENT-MD5')
CONTENT_RANGE = upstr('CONTENT-RANGE')
CONTENT_TRANSFER_ENCODING = upstr('CONTENT-TRANSFER-ENCODING')
CONTENT_TYPE = upstr('CONTENT-TYPE')
COOKIE = upstr... |
persandstrom/home-assistant | tests/components/config/test_customize.py | Python | apache-2.0 | 3,519 | 0 | """Test Customize config panel."""
import asyncio
import json
from unittest.mock import patch
from homeassistant.bootstrap import async_setup_component
from homeassistant.components import config
from homeassistant.config import DATA_CUSTOMIZE
@asyncio.coroutine
def test_get_entity(hass, aiohttp_client):
"""Test... | ))
assert resp.status == 200
result = yield from resp.json()
assert result == {'result': 'ok'}
state = hass.states.get('hello.world')
assert state.state == 'state'
assert dict(state.attributes) == {
'a': 'b', 'name': 'Beer', 'entities': ['light.top', 'light.bottom']}
orig_data['he... | _data
@asyncio.coroutine
def test_update_entity_invalid_key(hass, aiohttp_client):
"""Test updating entity."""
with patch.object(config, 'SECTIONS', ['customize']):
yield from async_setup_component(hass, 'config', {})
client = yield from aiohttp_client(hass.http.app)
resp = yield from client... |
sghai/robottelo | robottelo/ui/locators/common.py | Python | gpl-3.0 | 9,297 | 0 | # -*- encoding: utf-8 -*-
"""Implements different locators for UI"""
from selenium.webdriver.common.by import By
from .model import LocatorDict
common_locators = LocatorDict({
# common locators
"body": (By.CSS_SELECTOR, "body"),
# Notifications
"notif.error": (
By.XPATH, "//div[contains(@c... | ia-label='Close']"),
"cancel": (
By.XPA | TH,
"//button[contains(@ng-click,'cancel') and "
"not(contains(@class,'ng-hide'))][contains(., 'Cancel')]"
),
"name": (By.ID, "name"),
"label": (By.ID, "label"),
"description": (By.ID, "description"),
"kt_select_action_dropdown": (
By.XPATH,
("//button[contains(@ng-cl... |
blue-bird1/xss_fuzz | data/attribute.py | Python | apache-2.0 | 636 | 0.001572 | #! /usr/bin/env python
# coding:utf-8
"""html tag attribute"""
from lib.data import BaseXssData
class Attribute(BaseXssData):
"""html tag attribute data"""
def __init__( | self):
_data = [
'accesskey',
'class',
'contenteditable',
'contextmenu',
'data-*',
'dir',
'draggable',
'dropzone',
'hidden',
'id',
'lang',
'spellcheck',
'st... | super(Attribute, self).__init__(_data)
|
aepereyra/smslock | creatabla.py | Python | apache-2.0 | 264 | 0.003788 | #!/usr/bin/python
import sqlite3
conn = sqlite3.connect('accesslist.db')
conn.execute('''CREATE TA | BLE USUARIO
(CELLPHONE CHAR(11) PRIMARY KEY NOT NULL,
PASSWD CHAR(138) NOT NULL);''')
pr | int "Table created successfully";
conn.close()
|
tfroehlich82/erpnext | erpnext/regional/india/setup.py | Python | gpl-3.0 | 7,127 | 0.027641 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, os, json
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
from frappe.permissions import add_permission
... | lary Component', 'salary_component': 'Arrear', 'description': 'Arrear', 'type': 'Earning'},
{'doctype': 'Salary Component', 'salary_component': 'Leave Enca | shment', 'description': 'Leave Encashment', 'type': 'Earning'}
]
for d in docs:
try:
doc = frappe.get_doc(d)
doc.flags.ignore_permissions = True
doc.insert()
except frappe.NameError:
pass
|
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdeui/KPassivePopupMessageHandler.py | Python | gpl-2.0 | 584 | 0.008562 | # encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
im | port PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
class KPassivePopupMessageHandler(__PyQt4_QtCore.QObject, __PyKDE4_kdecore.KMessageHandler):
# no doc
def message(self, *args, **kwargs): # real signature unknown
pass
def __init | __(self, *args, **kwargs): # real signature unknown
pass
|
coderwjq/adt_python | 02-linked_list/04-single_cycle_linked_list.py | Python | apache-2.0 | 5,206 | 0.000222 | # coding:utf-8
# 单向循环链表的相关操作:
# is_empty() 判断链表是否为空
# length() 返回链表的长度
# travel() 遍历
# add(item) 在头部添加一个节点
# append(item) 在尾部添加一个节点
# insert(pos, item) 在指定位置pos添加节点
# remove(item) 删除一个节点
# search(item) 查找节点是否存在
class Node(object):
"""节点"""
def __init__(self, item):
self.elem = item
self.next... | if node:
node.next = node
def is_empty(self):
"""判断链表是否为空"""
return self.__head is None
def length(self):
"""返回链表的长度"""
if self.is_empty():
return 0
else:
cur = self.__head
count = 1
while cur.next is ... | return
else:
cur = self.__head
while cur.next is not self.__head:
print(cur.elem, end=" ")
cur = cur.next
# 循环结束,cur指向尾节点,但是尾节点元素尚未打印,需要单独输出
print(cur.elem)
def add(self, item):
"""在头部添加一个节点,头插法"""
... |
Baumelbi/IntroPython2016 | students/weidnem/session2/grid.py | Python | unlicense | 289 | 0.010381 | '''
'' | '
def printgrid():
print("this will be a grid")
pos = 0
while pos < 11:
if pos % 5 == 0:
print("+----+----+")
pos += 1
else:
print("| | |")
pos += 1
else:
print()
printgrid()
| |
ginolhac/tutorials | python/advanced/celery/code/ulhpccelery/tasks.py | Python | gpl-3.0 | 224 | 0 | from __future__ import absolute_import, unicode_literals
from .celery import app
@app.task
def add(x, y):
return x + y
@app.task
def mul(x, y):
return x * y
@app.task
def xsum(numbers):
return sum(number | s)
| |
dmych/cn | sync.py | Python | gpl-3.0 | 3,222 | 0.034761 | # This file is part of Coffee Notes project
#
# Coffee Notes is a crossplatform note-taking application
# inspired by Notational Velocity.
# <https://github.com/dmych/cn>
#
# Copyright (c) Dmitri Brechalov, 2011
#
# Coffee Notes is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | .remove(k)
synced_count += 1
else:
for k in db.keys(deleted=True):
litem = db.get(k)
if litem['deleted'] != 0:
log(' DEL: %s' % k)
db.remove(k)
sys.stderr.write('Synced %s notes.\n' % synced_count)
return time.time()
if __name__ == '__main__':
import | sys
email = sys.argv[1]
password = sys.argv[2]
sync('./', email, password)
|
Rusk85/pyload | module/plugins/hoster/ReloadCc.py | Python | gpl-3.0 | 4,866 | 0.003494 | from module.plugins.Hoster import Hoster
from module.common.json_layer import json_loads
from module.network.HTTPRequest import BadHeader
class ReloadCc(Hoster):
__name__ = "ReloadCc"
__version__ = "0.5"
__type__ = "hoster"
__description__ = """Reload.Cc hoster plugin"""
# Since we want to allo... | except ValueError:
self.limitDL = 1
else:
self.limitDL = 0
try:
self.download(data['link'], disposition=True)
except BadHeader, e:
if e.code == 404:
self.fail | ("File Not Found")
elif e.code == 412:
self.fail("File access password is wrong")
elif e.code == 417:
self.fail("Password required for file access")
elif e.code == 429:
# Too many connections, wait 2 minutes and ... |
alexston/calibre-webserver | src/calibre/devices/teclast/__init__.py | Python | gpl-3.0 | 237 | 0.008439 | #!/ | usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
| |
khchine5/opal | opal/migrations/0013_inpatientadmission.py | Python | agpl-3.0 | 1,852 | 0.0027 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import opal.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('opal', '0012_maritalst... | ],
options={
'abstract': False,
},
bases=(opal.models.UpdatesFromDictMixin, models.Model),
),
] | |
DMSC-Instrument-Data/plankton | docs/conf.py | Python | gpl-3.0 | 1,551 | 0.001934 | # -*- coding: utf-8 -*-
#
# lewis documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 9 16:42:53 2016.
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
# -- General configuration ------------------------------------------------
needs... | e = None
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
todo_include_todos = False
modindex_common_prefix = ["lewis."]
# -- Options for HTML output ---------------------------------------------
# This is from the sphinx_rtd_theme documentation to make the page work with RTD
on_rt... | rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_logo = "resources/logo/lewis-logo.png"
html_static_path = []
html_show_sourcelink = True
htmlhelp_basename = "lewisdoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
"papersize": "a4pap... |
FeodorM/amm_code | cm/lab_3/2_.py | Python | mit | 205 | 0 | from numpy import *
from cmlib import showMatr
A = matrix([[1, 2, 0], |
[0, 2, 2]])
B = matrix([[3, -1],
[-1, 3],
[1, 0]])
res = (A * | B).T
showMatr(array(res))
|
kapilrastogi/Impala | tests/util/parse_util.py | Python | apache-2.0 | 1,994 | 0.015045 | # Copyright (c) 2015 Cloudera, 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 o... | _to_mb(mem, units):
mem = float(mem)
if mem <= 0:
return
units = units.strip().upper()
if units.endswith("B"):
units = units[:-1]
if not units:
mem /= 10 ** 6
elif units == "K":
mem /= 10 ** 3
elif units == "M":
pass
elif units == "G":
mem *= 10 ** 3
elif units == "T":
mem ... | else:
raise Exception('Unexpected memory unit "%s"' % units)
return int(mem)
|
mjirayu/sit_academy | cms/djangoapps/upload_videos/migrations/0001_initial.py | Python | agpl-3.0 | 1,745 | 0.006877 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UploadVideo'
db.create_table('upload_videos_uploadvideo',... | ('name', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('course_id', self.gf('x | module_django.models.CourseKeyField')(max_length=255, db_index=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, db_index=True, blank=True)),
('video', self.gf('django.db.models.fields.files.FileField')(max_length=255)),
))
db.send... |
algernon/hy | hy/compiler.py | Python | mit | 90,185 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright (c) 2013, 2014 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Julien Danjou <julien@danjou.info>
# Copyright (c) 2013 Nicolas Dandrimont <nicolas.dandrimont@crans.org>
# Copyright (c) 2013 James King <james@agentultra.com>
# Copyright (c) 2013, 2014 Bob Tolbert <bob@t... | ission 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 li | mitation
# 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
# all copies o... |
fossilet/6.00x | week2/problemset2/ps2_2.py | Python | mit | 470 | 0.004255 | from __future__ imp | ort division
balance = 9999999
annualInterestRate = 0.18
min_pay = 10
def pay(m, min_pay):
if m == 1:
ub = (balance - min_pay) * (1 + annualInterestRate / 12)
return ub
else:
last_ub = pay(m - 1, min_pay)
ub = (la | st_ub - min_pay) * (1 + annualInterestRate / 12)
return ub
ub = pay(12, min_pay)
while ub > 0:
min_pay += 10
ub = pay(12, min_pay)
print('Lowest Payment: %d' % min_pay)
|
mikelarre/odoomrp-wip-1 | product_last_purchase_sale_info/models/sale_order.py | Python | agpl-3.0 | 1,749 | 0 | # -*- encoding: utf-8 -*-
############################################################################ | ##
#
# Avanzosc - Avanced Open Source Consulting
# Copyright (C) 2011 - 2014 Avanzosc <http://www.avanzosc.com>
#
# This program is free software: you can redistribute | it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without... |
ypu/virt-test | virttest/virsh_unittest.py | Python | gpl-2.0 | 12,157 | 0.000082 | #!/usr/bin/python
import unittest
import logging
import common
from autotest.client import utils
class bogusVirshFailureException(unittest.TestCase.failureException):
def __init__(self, *args, **dargs):
self.virsh_args = args
self.virsh_dargs = dargs
def __str__(self):
msg = ("Code... | al(len(args), 0)
self.assertEqual(len(dargs), 1)
self.assertEqual(dargs.keys(), ['foo'])
self.assertEqual(dargs.values(), ['bar'])
def test_args_and_dargs(self):
# save some typing
VC = self.virsh.VirshClosure
tcinst = sel | f.SomeClass(foo='bar')
vcinst = VC(self.somefunc, tcinst)
args, dargs = vcinst('foo')
self.assertEqual(len(args), 1)
self.assertEqual(args[0], 'foo')
self.assertEqual(len(dargs), 1)
self.assertEqual(dargs.keys(), ['foo'])
self.assertEqual(dargs.values(), ['bar'])
... |
jml/flocker | flocker/volume/functional/test_filesystems_zfs.py | Python | apache-2.0 | 19,664 | 0 | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Functional tests for ZFS filesystem implementation.
These tests require the ability to create a new ZFS storage pool (using
``zpool``) and the ability to interact with that pool (using ``zfs``).
Further coverage is provided in
:module:`flocker.volume.t... | = pool.create(volume)
def gotFilesystem(filesystem):
self.assertEqual(
filesystem.get_path().path,
subprocess.check_output(
[b"zfs", b"get", b"-H", b"-o", b" | value",
b"mountpoint", filesystem.name]).strip())
d.addCallback(gotFilesystem)
return d
def test_no_maximum_size(self):
"""
The filesystem is created with no ``refquota`` property if the maximum
size is unspecified.
"""
mount_root = FileP... |
t-brink/pscic | psciclib/units.py | Python | gpl-3.0 | 1,401 | 0.002143 | # Copyright (C) 2015 Tobias Brink
#
# 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 distributed in ... | tions by default.
Q_ = ureg.Quantity
UndefinedUnitError = pint.UndefinedUnitError
def _init():
# Add currencies to registry.
aliases = {"PLN": "zł"}
# TODO: make the download thing optional! ship default .xml!
# TODO: error handling
data = currency.get_exchange_rates()
ureg.define("EUR = [ | currency]")
for cur, rate in data["rates"].items():
if cur in aliases:
ureg.define("{} = {} * EUR = {}".format(aliases[cur], 1/rate,
cur))
else:
ureg.define("{} = {} * EUR".format(cur, 1/rate))
|
piyush-jain1/GSoC17OctaveGeometry | inst/io/@svg/simplepath.py | Python | gpl-3.0 | 6,961 | 0.0102 | #!/usr/bin/env python
"""
simplepath.py
functions for digesting paths into a simple list structure
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; eit... | else:
#command was omited
#use last command's implicit next command
needParam = False
if lastCommand:
if lastCommand.isupper():
command = pathdefs[lastCommand][0]
else:
command = pathdefs[lastCo... | while numParams > 0:
if needParam:
try:
token, isCommand = lexer.next()
if isCommand:
raise Exception, 'Invalid number of parameters'
except StopIteration:
raise Exception, 'Unexpected end of ... |
googleapis/python-aiplatform | samples/snippets/model_service/get_model_evaluation_tabular_regression_sample_test.py | Python | apache-2.0 | 1,059 | 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi | ng, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import get_model_evaluation_sample
PROJECT_ID = ... | el_evaluation_sample(capsys):
get_model_evaluation_sample.get_model_evaluation_sample(
project=PROJECT_ID, model_id=MODEL_ID, evaluation_id=EVALUATION_ID
)
out, _ = capsys.readouterr()
assert "metrics_schema_uri" in out
|
toomoresuch/pysonengine | parts/google_appengine/google/appengine/api/taskqueue/taskqueue.py | Python | mit | 33,902 | 0.006224 | #!/usr/bin/env python
#
# Copyright 2007 Google 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 o... | rror):
"""The task's relative URL is invalid."""
class BadTaskStateError(Error):
"""The task is in the wrong state for the requested operation."""
class InvalidQueueError(Error):
"""The Queue's configuration is invalid."""
class InvalidQueueNameError(InvalidQueueError):
"""The Queue's name is invalid."""
... | or this app."""
class DuplicateTaskNameError(Error):
"""The add arguments contain tasks with identical names."""
class TooManyTasksError(Error):
"""Too many tasks were present in a single function call."""
class DatastoreError(Error):
"""There was a datastore error while accessing the queue."""
class BadT... |
bailabs/bench-v7 | setup.py | Python | gpl-3.0 | 963 | 0.015576 | from setuptools import setup, find_packages
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
import re, ast
# get version from __version_ | _ variable in bench/__init__.py
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('bench/__init__.py', 'rb') as f:
version = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
requirements = parse_requirements("requirements.txt", session="")
setup(
name='bench',
d... | include_package_data=True,
install_requires=[str(ir.req) for ir in requirements],
dependency_links=[str(ir._link) for ir in requirements if ir._link],
entry_points='''
[console_scripts]
bench=bench.cli:cli
''',
)
|
arenadata/ambari | ambari-server/src/main/resources/stacks/ADH/1.0/services/YARN/package/scripts/params_windows.py | Python | apache-2.0 | 2,998 | 0.005337 | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... | s.environ["HADOOP_COMMON_HOME"], "share", "hadoop", "mapreduce")
hadoopMapredExamplesJarName = "hadoop-mapreduce-examples-2.*.jar"
exclude_hosts = default("/clusterHostInfo/decom_nm_hosts", [])
exclude_file_path = default("/configurations/yarn-site/yarn.resourcemanager.nodes.exclude-path","/etc/hadoop/conf/yarn.exclud... | _hosts = default("/clusterHostInfo/nm_hosts", [])
#incude file
include_file_path = default("/configurations/yarn-site/yarn.resourcemanager.nodes.include-path", None)
include_hosts = None
manage_include_files = default("/configurations/yarn-site/manage.include.files", False)
if include_file_path and manage_include_files... |
timemath/hmfs | fs/hmfs/test/hold_file_open.py | Python | gpl-2.0 | 296 | 0.003378 | #!/us | r/bin/python3
from os.path import expanduser
home = expanduser('~')
file_list = []
for i in range(2048):
with open(home + "/mount_hmfs/orphan_{:d}.txt".format(i), 'w') as file:
file_list.append(file)
file.write("ssssssssssssssssssss")
#hold files
while True:
p | ass
|
ashang/calibre | src/calibre/gui2/actions/show_template_tester.py | Python | gpl-3.0 | 1,940 | 0.006701 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' |
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.template_dialog import TemplateDialog
from calibre.gui2 import error_dialog
class ShowTemplateTesterAction(InterfaceAction):
name = 'Template tester'
action_spec = (_('Template tester'), 'debug.png', None, '')
dont_add_to = froz... | late to test using data from the selected book')
self.first_time = True
self.qaction.triggered.connect(self.show_template_editor)
def show_template_editor(self, *args):
view = self.gui.current_view()
if view is not self.gui.library_view:
return error_dialog(self.gui, _('... |
puiterwijk/HttpCA | Signer/setup.py | Python | bsd-3-clause | 2,106 | 0.019468 | #-*- coding: UTF-8 -*-
# Copyright (c) 2013, Patrick Uiterwijk <puiterwijk@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above ... | 6
__requires__ = ['SQLAlchemy >= 0.7']
import pkg_resources
from setuptools import setup, find_packages
setup( name = 'httpca_signer'
, version | = '0.1'
, author = 'Patrick Uiterwijk'
, author_email = 'puiterwijk@gmail.com'
, packages = find_packages()
, zip_safe = False
, include_package_data = True
, install_requires = ['pika', 'SQLAlchemy>=0.7'])
|
janusnic/py-21v | scope/2.py | Python | mit | 188 | 0.047872 |
def mathem(a,b):
a = a/2
b = b+10
print(a+b)
num1 = 100
num2 = 12
math | em(num1,num2)
print num1
print num2
def mathem2():
| print(num1+num2)
mathem2()
print a
print b |
nke001/attention-lvcsr | libs/Theano/theano/gof/compilelock.py | Python | mit | 14,977 | 0.000134 | # Locking mechanism to ensure no two compilations occur simultaneously
# in the same compilation directory (which can cause crashes).
import atexit
import os
import socket # only used for gethostname()
import time
import logging
from contextlib import contextmanager
import numpy as np
from theano import config
fro... | uments to be forwarded to the `lock` function when
acquiring the lock.
:note: We can lock only on 1 directory at a time.
"""
if lock_dir i | s None:
lock_dir = os.path.join(config.compiledir, 'lock_dir')
if not hasattr(get_lock, 'n_lock'):
# Initialization.
get_lock.n_lock = 0
if not hasattr(get_lock, 'lock_is_enabled'):
# Enable lock by default.
get_lock.lock_is_enabled = True
get_lock.loc... |
jameschch/Lean | Algorithm.Python/FutureOptionCallITMExpiryRegressionAlgorithm.py | Python | apache-2.0 | 6,809 | 0.006168 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Licen... | vent):
if orderEvent.Status != OrderStatus.F | illed:
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
return
if not self.Securities.ContainsKey(orderEvent.Symbol):
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
security = self.Se... |
prando/photoselector | photo.py | Python | mit | 11,323 | 0.012276 | try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import tkMessageBox
except ImportError:
from tkinter import messagebox as tkMessageBox
try:
import tkFileDialog
except ImportError:
from tkinter import filedialog as tkFileDialog
import os
from PIL import Image, ImageTk
... | cted images & append to it.
if self.selected:
self.out_file_path_str = tkFileDialog.askdirectory (title='Choose target dir to s | tore selected files')
if not self.out_file_path_str:
tkMessageBox.showerror ("Error", "Choose valid dir")
return
self.out_file_path_str = os.path.join (self.out_file_path_str, 'selected_photos.txt')
with open (self.out_file_path_str, "a") as f:
... |
luiseiherrera/jsmd | blog/admin.py | Python | gpl-3.0 | 653 | 0.01072 | from | django.contrib import admin
from blog.models imp | ort Post
class PostAdmin(admin.ModelAdmin):
#fields display on change list
list_display = ('title', 'description')
#fields to filter the change list with
list_filter = ('published', 'created')
#fields to search in change list
search_fields = ('title', 'description', 'content')
#enable the ... |
PoornimaNayak/autotest-client-tests | linux-tools/ibus/ibus.py | Python | gpl-2.0 | 1,230 | 0.004878 | #!/bin/python
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error
class ibus(test.test):
"""
Autotest module for testing basic functionality
of ibus
@author Ramesh YR, rameshyr@linux.vnet.ibm.com ##
"""
version... | """
self.nfail = 0
logging.info('\n Test initialize successfully')
def run_once(self, test_path=''):
"""
Trigger test run
"""
try:
os.environ["LTPBIN"] = "%s/shared" %(test_path)
ret_val = subprocess.Popen(['./ibus.sh'], cwd="%s/ibus" %(... | logging.error("Test Failed: %s", e)
def postprocess(self):
if self.nfail != 0:
logging.info('\n nfails is non-zero')
raise error.TestError('\nTest failed')
else:
logging.info('\n Test completed successfully ')
|
arthurdejong/python-stdnum | stdnum/se/__init__.py | Python | lgpl-2.1 | 1,012 | 0 | # __init__.py - collection of Swedish numbers
# coding: utf-8
#
# Copyright (C) 2012 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 | .1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You sho... | n Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Swedish numbers."""
# provide aliases
from stdnum.se import personnummer as personalid # noqa: F401
from stdnum.se import postnummer as postal_code # noqa: F401
|
gm2211/vpnAlfredWorkflow | src/alp/request/requests_cache/backends/base.py | Python | gpl-3.0 | 5,357 | 0.001307 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
requests_cache.backends.base
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Contains BaseCache class which can be used as in-memory cache backend or
extended to support persistence.
"""
from datetime import datetime
import hashlib
from copy import copy
from alp.request ... | ory = tuple(self.restore_response(r) for r in response.history)
return result
def create_key(self, request):
key = hashlib.sha256()
key.update(_to_bytes(request.method.upper()))
k | ey.update(_to_bytes(request.url))
if request.body:
key.update(_to_bytes(request.body))
return key.hexdigest()
def __str__(self):
return 'keys: %s\nresponses: %s' % (self.keys_map, self.responses)
# used for saving response attributes
class _Store(object):
pass
def _to_by... |
philpot/trump-insult-haiku | nytorg.py | Python | apache-2.0 | 4,644 | 0.004091 | [('GROUP', 10),
('UNITED STATES SENATOR', 8),
("''", 4),
# media outlet
('NEWS ORGANIZATION', 5),
('NEWSPAPER', 4),
('MAGAZINE', 3),
('TELEVISION SHOW', 2),
('NEWS WEBSITE', 1),
# media person
('BLOGGER, THE WASHINGTON POST', 1),
('ANCHOR, FOX NEWS', 1),
('FOX NEWS ANCHOR', 1),
("CONTRIBUTOR, 'THE VIEW'", 1... | L CONSULTANT', 1),
# political: Democratic rival
('DEMOCRATIC CANDIDATE, FORMER GOVERNOR OF MARYLAND', 1),
('FORMER RHODE ISLAND GOVERNOR', 1),
# p | olitical: other Democratic
('MARYLAND SENATOR', 1),
('MAYOR OF SAN JOSE, CALIF.', 1),
('MAYOR OF NEW YORK CITY', 1),
('FORMER MAYOR OF PHILADELPHIA', 1),
("PROTESTERS OF MR. TRUMP'S RALLIES", 1),
# foreign leader
('PRINCE, SAUDI ARABIA', 1),
('GERMAN CHANCELLOR', 1),
# business leader
('FORMER BUSINESS EXEC... |
LuqueDaniel/LoL-Server-Status | lol_server_status/gui/widgets/about.py | Python | gpl-3.0 | 2,800 | 0.003214 | # -*- coding: utf-8 -*-
#
# This file is part of LoL Server Status
#
# LoL Server Status 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
# any later version.
#
# LoL Server ... | T ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have receiv | ed a copy of the GNU General Public License
# along with LoL Server Status. If not, see <http://www.gnu.org/licenses/>.
#
# Source: <http://github.com/LuqueDaniel/LoL-Server-Status>
#LoL Server Status imports
from lol_server_status import __version__
from lol_server_status import __author__
from lol_server_status imp... |
rsalmaso/wagtail | wagtail/contrib/redirects/filters.py | Python | bsd-3-clause | 828 | 0 | import django_filters
from | django.utils.translation import gettext as _
from wagtail.admin.filters import WagtailFilterSet
from wagtail.admin.widgets import ButtonSelect
from wagtail.core.models import Site
class RedirectsReportFilterSet(WagtailFilterSet):
is_permanent = django_filters.ChoiceFilter(
label=_("Type"),
method... | site = django_filters.ModelChoiceFilter(
field_name="site", queryset=Site.objects.all()
)
def filter_type(self, queryset, name, value):
if value and self.request and self.request.user:
queryset = queryset.filter(is_permanent=value)
return queryset
|
robertnishihara/ray | rllib/train.py | Python | apache-2.0 | 7,814 | 0 | #!/usr/bin/env python
import argparse
import os
from pathlib import Path
import yaml
import ray
from ray.cluster_utils import Cluster
from ray.tune.config_parser import make_parser
from ray.tune.result import DEFAULT_RESULTS_DIR
from ray.tune.resources import resources_to_json
from ray.tune.tune import _make_schedule... | if exp["config"]["framework"] not in ["tf2", "tfe"]:
| raise ValueError("Must enable --eager to enable tracing.")
exp["config"]["eager_tracing"] = True
if args.v:
exp["config"]["log_level"] = "INFO"
verbose = 2
if args.vv:
exp["config"]["log_level"] = "DEBUG"
verbose = 3
if arg... |
papajijaat/Face-Detect | code/face_detect.py | Python | mit | 869 | 0.002301 | import cv2
im | port sys
#cascPath = sys.argv[1]
#faceCascade = cv2.CascadeClassifier(cascPath)
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GR... | caleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if... |
askdaddy/PerfKitBenchmarker | perfkitbenchmarker/__init__.py | Python | apache-2.0 | 679 | 0 | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | icense is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the speci | fic language governing permissions and
# limitations under the License.
import gflags as flags # NOQA
import gflags_validators as flags_validators # NOQA
|
HellerCommaA/flask-material-lite | sample_application/__init__.py | Python | mit | 2,763 | 0.001448 | from flask import Flask, render_template, flash
from flask_material_lite import Material_Lite
from flask_appconfig import AppConfig
from flask_wtf import Form, RecaptchaField
from flask_wtf.file import FileField
from wtforms import TextField, HiddenField, ValidationError, RadioField,\
BooleanField, SubmitField, Int... | ppconfig is not necessary, but
# highly recommend =)
# https://github.com/mbr/flask-appconfig
Material_Lite(app)
# in a real app, these should be configured through Flask-Appconfig
app.config['SECRET_KEY'] = 'devkey'
app.config['RECAPTCHA_... | KEY'] = \
'6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw'
@app.route('/', methods=('GET', 'POST'))
def index():
form = ExampleForm()
form.validate_on_submit() # to get error messages to the browser
flash('critical message', 'critical')
flash('error message', 'error')
... |
ray-project/ray | rllib/utils/tf_ops.py | Python | apache-2.0 | 229 | 0 | from ray.rllib.utils.deprecation import depr | ecation_warning
from ray.rllib.utils.tf_utils import * # noqa
deprecation_warning(
old="ray.rllib.utils.tf_ops.[...]",
new="ray.rllib.utils.tf_utils.[...]",
error=Tru | e,
)
|
infoxchange/django-localflavor | tests/test_pk/forms.py | Python | bsd-3-clause | 355 | 0.002817 | from django.forms import ModelForm
from .models import PakistaniPlace
class PakistaniPlaceForm(ModelForm):
"" | " Form for storing a Pakistani place. """
class Meta:
model = PakistaniPlace
fields = ('state', 'state_required', 'state_default', 'postcode', ' | postcode_required', 'postcode_default',
'phone', 'name')
|
MrCrawdaddy/humans | profiles/views.py | Python | mit | 2,056 | 0.002918 | from django.shortcuts import render, HttpResponseRedirect, redirect
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import CreateView
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.forms.models import inlineformset_... | ',
'interests', 'state'))
formset = ProfileInlineFormset(instance=user)
if request.user.is_authenticated() and r | equest.user.id == user.id:
if request.method == "POST":
user_form = ProfileForm(request.POST, request.FILES, instance=user)
formset = ProfileInlineFormset(request.POST, request.FILES, instance=user)
if user_form.is_valid():
created_user = user_form.save(commit... |
EmanueleCannizzaro/scons | src/engine/SCons/Tool/yacc.py | Python | mit | 4,613 | 0.003685 | """SCons.Tool.yacc
Tool-specific initialization for yacc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, ... | ile.add_action('.y', YaccAction)
c_file.add_emitter('.y', yEmitter)
c_file.add_action('.yacc', YaccAction)
c_file.add_emitter('.yacc', yEmitter)
# Objective-C
c_file.add_action('.ym', YaccAction)
c_file.add_emitter('.ym', ymEmitter)
# C++
| cxx_file.add_action('.yy', YaccAction)
cxx_file.add_emitter('.yy', yyEmitter)
env['YACC'] = env.Detect('bison') or 'yacc'
env['YACCFLAGS'] = SCons.Util.CLVar('')
env['YACCCOM'] = '$YACC $YACCFLAGS -o $TARGET $SOURCES'
env['YACCHFILESUFFIX'] = '.h'
env['YACCHXXFILESUFFIX'] = '.hpp'
... |
lnls-sirius/dev-packages | siriuspy/tests/pwrsupply/variables.py | Python | gpl-3.0 | 3,146 | 0.000638 | """Test values to test read_all_variables methods.
Used by test in controller and model modulesself.
"""
# TODO: change string format return from serial
values = [
8579, 6.7230000495910645, 6. | 7230000495910645,
[b'V', b'0', b'.', b'0', b'7', b' ', b'2', b'0', b'1', b'8', b'-', b'0', b'3',
b'-', b'2', b'6', b'V', b'0', b'.', b'0', b'7', b' ', b'2', b'0', b'1', b'8', b'-', b'0',
b'3', b'-', b'2', b'6'], 5, 8617, 0, 2, 1, 0.0, 0.0, 1.0 | , 0.0,
[1.0, 1.0, 1.0, 0.0], 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0, 0, 0, 0,
6.722831726074219, 1.23291015625, 5.029296875, 53.0]
bsmp_values = [
'\x00', '\x13', '\x00', 'ô', '\x83', '!', 'Ñ', '"', '×', '@', 'Ñ', '"',
'×', '@', 'V', '0', '.', '0', '7', ' ', '2', '0', '1', '8', '-', '0', '3',
'-', ... |
johnwoltman/geotest | geotest/settings.py | Python | mit | 2,023 | 0 | """
Django settings for geotest project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... | go.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'geotest',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.midd | leware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_UR... |
gunnery/gunnery | gunnery/task/migrations/0002_auto__add_field_executioncommandserver_celery_task_id.py | Python | apache-2.0 | 12,042 | 0.007806 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ExecutionCommandServer.celery_task_id'
db.add_column(u'ta... | oleanField', [], {'default': 'False'}),
'name': ('django.db.models.f | ields.CharField', [], {'max_length': '128'})
},
u'core.server': {
'Meta': {'unique_together': "(('environment', 'name'),)", 'object_name': 'Server'},
'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'servers'", 'to': u"orm['core.Environment']"})... |
brezerk/q4wine-web | rss/views.py | Python | gpl-3.0 | 1,075 | 0.005581 | # Create your views here.
from django.contrib.syndication.views import Feed
from q4wine.news.models import News
from django.utils.feed | generator import Atom1Feed
import string
class RssSiteNewsFeed(Feed):
title = "News related to q4wine development stuff and its community life."
link = "/rss/"
description = """Here is all news related to q4wine development stuff and its community life.\
If you are involved into the q4wi... | e')[:10]
def item_title(self, item):
rss_title = str(item.date.year) + "-" + str(item.date.month) + "-" + str(item.date.day)
rss_title += " " + item.title
return rss_title
def item_description(self, item):
return item.content
def item_link(self, item):
url = "/#" +... |
kwikteam/phy | phy/gui/tests/test_state.py | Python | bsd-3-clause | 2,810 | 0.001423 | # -*- coding: utf-8 -*-
"""Test gui."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import logging
import os
import shutil
from ..state import GUIState, _gui_state_path, _get_default_state_p... | -----------------------------------------------------------
# Test GUI state
#------------------------------------------------------------------------------
class MyClass(object):
pass
def test_get_default_state_path():
assert str(_get_default_state_path( | MyClass())).endswith(
os.sep.join(('gui', 'tests', 'static', 'state.json')))
def test_gui_state_view_1(tempdir):
view = Bunch(name='MyView0')
path = _gui_state_path('GUI', tempdir)
state = GUIState(path)
state.update_view_state(view, dict(hello='world'))
assert not state.get_view_state(Bun... |
nosix/PyCraft | src/pycraft/service/composite/entity/__init__.py | Python | lgpl-3.0 | 188 | 0.005319 | # -*- coding: utf8 -*-
from | .player import PlayerEntity
from .base import MobEntity
from .item import ItemEntity
__all__ = [
'PlayerEntity', |
'MobEntity',
'ItemEntity',
] |
geky/pyOCD | pyOCD/flash/flash_kl28z.py | Python | apache-2.0 | 6,139 | 0.018081 | """
mbed CMSIS-DAP debugger
Copyright (c) 2006-2013 ARM Limited
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 ... | , 0xe018d101, 0xb0052004, 0x480dbdf0,
0x68014478, 0xcd02600f, 0x60416800, 0x2006490a, 0xf00071c8, 0x4604f88b, 0x69809801, 0xd0002800,
0x2c004780, 0x1d3fd103, 0x2e001f36, 0x4620d1e7, 0x0000e7e3, 0x000002ec, 0x40020000, 0xb081b5ff,
0x460e4614, 0x23084605, 0xff90f7ff, 0xd1272800, 0x686868a9, 0xf882f000, 0x4271... | f84cf000, 0xd1032800, 0x19f61be4, 0x2000e7e3,
0xbdf0b005, 0x00000272, 0x40020000, 0x2800b510, 0x4804d006, 0x71c22240, 0xf0007181, 0xbd10f837,
0xbd102004, 0x40020000, 0x9f08b5f8, 0x4616001c, 0xd005460d, 0xf7ff2304, 0x2800ff49, 0xe01dd101,
0xbdf82004, 0x4478480f, 0x600d6801, 0x2202490e, 0x9a0671ca, 0x680072ca... |
francbartoli/geonode | geonode/maps/management/commands/remove_broken_layers.py | Python | gpl-3.0 | 1,375 | 0 | # -*- coding: utf-8 -*-
#########################################################################
#
# | Copyright (C) 2018 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 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 Pub... |
mashaoze/esp-idf | examples/wifi/iperf/iperf_test.py | Python | apache-2.0 | 26,855 | 0.002495 | """
Test case for iperf example.
This test case might have problem running on windows:
1. direct use of `make`
2. use `sudo killall iperf` to force kill iperf, didn't implement windows version
The test env Example_ShieldBox do need the following config::
Example_ShieldBox:
ap_list:
- ssid: "ssid"
... | r config will make this easy.
# Use | default value `99` for config with best performance.
BEST_PERFORMANCE_CONFIG = "99"
class TestResult(object):
""" record, analysis test result and convert data to output format """
PC_BANDWIDTH_LOG_PATTERN = re.compile(r"(\d+).0\s*-\s*(\d+).0\s+sec\s+[\d.]+\s+MBytes\s+([\d.]+)\s+Mbits/sec")
DUT_BANDWIDTH... |
tsh/coursera-algorithmic-thinking | Week 1/graph_loader.py | Python | apache-2.0 | 908 | 0.005507 | """
Provided code for Application portion of Module 1
Imports physics citation graph
"""
###################################
# Code for loading citation graph
CITATION_URL = "phys-cite_graph.txt"
def load_graph(graph_url):
"""
Function that loads a graph given the URL
for a text representation of the gr... | en(graph_url)
graph_text = graph_file.read()
graph_lines = graph_text.split('\n')
graph_lines = graph_lines[ : -1]
print "Loaded graph with", len(graph_lines), "nodes"
answer_graph = {}
for line in graph_lines:
neighbors = line.split(' ')
node = int(neighbors[0])
answer... | raph = load_graph(CITATION_URL)
|
detectlanguage/detectlanguage-python | detectlanguage/api.py | Python | mit | 353 | 0.033994 | import detectlanguage
def detect(data):
result = detectlanguage.client.post('detect', { 'q': data })
re | turn result['data']['detections']
def simple_detect(data):
result = detect(data)
return result[0]['language']
def user_status():
return detectlanguage. | client.get('user/status')
def languages():
return detectlanguage.client.get('languages')
|
stuti-rastogi/leetcodesolutions | 140_wordBreak2.py | Python | apache-2.0 | 760 | 0.003947 | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
return self.helper(s, wordDict, {})
| def helper(self, s, wordDict, memo):
if s in memo: return memo[s]
if not s: return []
res = []
for word in wordDict:
if not s.star | tswith(word):
continue
if len(word) == len(s):
res.append(word)
else:
resultOfTheRest = self.helper(s[len(word):], wordDict, memo)
for item in resultOfTheRest:
item = word + ' ' + item
res.app... |
Guts/isogeo-notifier | web/isogeo_notify/management/commands/api2db.py | Python | gpl-3.0 | 2,944 | 0.001359 | # -*- coding: UTF-8 -*-
#!/usr/bin/env python
# ############################################################################
# ########## Libraries #############
# ##################################
# Standard library
import logging
from os import path
# 3rd party modules
import arrow
from isogeo_pysdk import Isogeo
... | ########## Globals ##############
# #################################
# logger = logging.getLogger("ElPaso")
# ############################################################################
# | ########### Classes #############
# #################################
class Command(BaseCommand):
args = '<foo bar ...>'
help = 'our help string comes here'
def _update_db(self):
"""Update metadata list from API."""
# get stored metadata
db_mds = Metadata.objects.all()
db_... |
sanskritiitd/sanskrit | dictionary/sanskrit-english/wil.py | Python | gpl-3.0 | 442 | 0.025 | # -*- coding: utf-8 -*-
out = open('wil_orig.words.out', 'w')
for line in open('wil_orig_utf8_slp1.txt').xreadlines():
line = line.strip()
if ".{#" in line:
word = line.split('{#')[1].split('#}')[0].split(' ') | [0].split('(')[0].split(',')[0].split('.')[0].split('/')[0].split('\\')[0].split('-')[0].split('{')[0].replace("'","").replace('*','').replace('†','').replace('[','').replace('?','')
out.write(word+'\n' | );
out.close()
|
Vaypron/ChromaPy | Example Scripts/Mouse/1. setColor.py | Python | mit | 342 | 0 | import ChromaPy32 as Chroma # Import the Chroma Module
fro | m time import sleep
Mouse = Chrom | a.Mouse() # Initialize a new Mouse Instance
RED = (255, 0, 0) # Initialize a new color by RGB (RED,GREEN,BLUE)
Mouse.setColor(RED) # sets the whole Mouse-Grid to RED
Mouse.applyGrid() # applies the Mouse-Grid to the connected Mouse
sleep(5)
|
hosiet/flasktex | src/client.py | Python | bsd-3-clause | 2,633 | 0.002659 | #!/usr/bin/env python3
"""
Testing Client for flasktex.
"""
__license__ = 'BSD-3'
__docformat__ = 'reStructuredText'
import os
import urllib.request
def ft_checkalive(url:str):
"""
Check whether given server is alive.
"""
resp = None
try:
resp = urllib.request.urlopen(url+'/ping').read... | )
print('checking entryfile...', end='')
if not entryfile in dir_content:
print('Cannot find given entryfile. Giving up.')
return
print('pass')
print('checking worker name...', end='')
print('skipped')
print('checking timeout value...', end='')
if int(timeout) < 30:
p... | .')
return
print('pass')
print('\n...Success!')
return {
'url': str(url),
'texdir': str(texdir),
'entryfile': str(entryfile),
'worker': str(worker),
'timeout': int(timeout)
}
def ft_client_submission(user_input):
import flasktex
from flasktex.... |
RNAer/qiita | qiita_db/test/test_study.py | Python | bsd-3-clause | 28,241 | 0 | from unittest import TestCase, main
from datetime import datetime
from future.utils import viewitems
from qiita_core.exceptions import IncompetentQiitaDeveloperError
from qiita_core.util import qiita_test_checker
from qiita_db.base import QiitaObject
from qiita_db.study import Study, StudyPerson
from qiita_db.investi... | ts of different strains were "
"examined. These roots were obtained November 11, 2011 fr | om "
"plants that had been harvested in the summer. Future "
"studies will attempt to analyze the soils and rhizospheres "
"from the same location at different time points in the plant "
"lifecycle.",
'spatial_series': False,
'study... |
chrishadi/SublimeRunOnSave | runonsave.py | Python | mit | 830 | 0.015663 | import sublime, sublime_plugin
class RunOnSave(sublime_plugin.EventListener):
def on_post_save(self, view):
# Check if project has run-on-save enabled.
settings = view.settings()
if settings.get('run_on_save') == 1:
command = | settings.get('command')
if command is not None:
option_dict = {'cmd': command}
folders = view.window().folders()
if folders is not None and len(folders) > 0:
option_dict['working_dir'] = folders[0]
path = settings.get('path')
if path is not None:
option_... | option_dict['env'] = environment_dict;
view.window().run_command('exec', option_dict)
|
pincopallino93/rdfendpoints | parser/dbpediamap.py | Python | apache-2.0 | 2,410 | 0.007054 | __author__ = 'Lorenzo'
planet_mapper = {
'<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>': 'planet type', # link to yago category, can be explored more
'<http://live.dbpedia.org/ontology/wikiPageExternalLink>': 'external link', # many
'<http://live.dbpedia.org/property/inclination>': 'inclination', ... | ity
'<http://live.dbpedia.org/property/period>': 'period', # quantity
'<http://live. | dbpedia.org/property/meanTemp>': 'average temperature', # quantity
'<http://live.dbpedia.org/ontology/abstract>': 'abstract', # text
'<http://live.dbpedia.org/property/meanAnomaly>': 'average anomaly', # quantity
'<http://live.dbpedia.org/property/siderealDay>': 'sideral day', # quantity
'<http://l... |
geeklhem/pimad | setup.py | Python | gpl-3.0 | 504 | 0.001984 | from setuptools import setup
setup(name='pimad',
version=open('VERSION').read(),
descrip | tion='Pimad is modeling adaptive dynamics',
url='http://www.eleves.ens.fr/home/doulcier/projects/celladhesion/',
author='Guilhem Doulcier',
long_description=open('README').read(),
author_email='guilhem.doulcier@ | ens.fr',
license='GPLv3',
packages=['pimad'],
install_requires=[
'numpy',
'scipy',
'pandas',
'matplotlib',
],
)
|
qedsoftware/commcare-hq | corehq/apps/receiverwrapper/views.py | Python | bsd-3-clause | 7,843 | 0.001275 | import logging
from couchdbkit import ResourceNotFound
from couchdbkit.ext.django.loading import get_db
from django.http import (
HttpResponseBadRequest,
HttpResponseForbidden,
)
from casexml.apps.case.xform import get_case_updates, is_device_report
from corehq.apps.domain.decorators import (
check_domain_m... | ck_domain_migration
def post(request, domain, app_id=None):
try:
if domain_requires_auth(domain):
# "redirect" to the secure version
# an actual redirect doesn't work because it becomes a GET
| return secure_post(request, domain, app_id)
except ResourceNotFound:
return HttpResponseBadRequest(
'No domain with name %s' % domain
)
return _process_form(
request=request,
domain=domain,
app_id=app_id,
user_id=None,
authenticated=F... |
google/ml-fairness-gym | runner.py | Python | apache-2.0 | 1,900 | 0.003684 | # coding=utf-8
# Copyright 2022 The ML Fairness Gym 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 applicab... | ON will be written.')
FLAGS = flags.FLAGS
def main(argv):
if len(argv) > 1:
raise app.UsageError('Too many command-line arguments.')
gin.parse_config_file(FLAGS.gin_config_path)
runner = runner_lib.Runner()
results = runner.run()
logging.info('Results: %s', results)
with open(FLAGS.output_path, 'w... | __main__':
app.run(main)
|
gena/qgis-earthengine-plugin | contrib/__init__.py | Python | mit | 108 | 0.018519 | # Migrating som | e useful EE utils from https://code.earthengine.google.com/?accept_repo | =users/gena/packages
|
looooo/pivy | scons/scons-local-1.2.0.d20090919/SCons/compat/_scons_shlex.py | Python | isc | 11,866 | 0.001517 | # -*- coding: iso-8859-1 -*-
"""A lexical analyzer class for simple shell-like syntaxes."""
from __future__ import print_function
# Module and documentation by Eric S. Raymond, 21 Dec 1998
# Input stacking and error message cleanup added by ESR, March 2000
# push_source() and pop_source() made explicit by ESR, January... | the lexer's input source stack."
if is_basestring(newstream):
newstream = StringIO(newstream)
self.filestack.appendleft((self.infile, self.instream, self.lineno))
self | .infile = newfile
self.instream = newstream
self.lineno = 1
if self.debug:
if newfile is not None:
print('shlex: pushing to file %s' % (self.infile,))
else:
print('shlex: pushing to stream %s' % (self.instream,))
def pop_source(self):
... |
kiddinn/l2t-tools | plugins/yara_match.py | Python | gpl-3.0 | 3,103 | 0.003867 | #!/usr/bin/python
"""
This is a simple plugin that does the same deal as the l2t_find_evil.py script does.
It loads up a YARA rule file and runs it against each line in the CSV file and if there
is a match it will fire up an alert.
Copyright 2012 Kristinn Gudjonsson (kristinn ( a t ) log2timeline (d o t) net)
This fi... | eline.net)'
__version__ = '0.1'
class YaraMatch(plugin.L2tPlugin):
"""Count the number of lines that contain a file inside System32."""
def __init__(self, separator, rule_file):
"""Constructor.
Args:
separator: The CSV file sep | arator, usually a comma or a tab.
rule_file: The path to a YARA rule file.
Raises:
IOError: If the YARA rule file does not exist.
"""
if not os.path.isfile(rule_file):
raise IOError('The YARA rule file does not exist.')
super(YaraMatch, self).__init__(separator)
self.rules = yara... |
yujiali/pynn | pynn/nn.py | Python | mit | 20,622 | 0.003831 | """
A python neural network package based on gnumpy.
Yujia Li, 09/2014
TODO:
- right now YNeuralNet I/O only supports NeuralNet as the type for component
nets (network construction and forward/backward prop works for other types
of component nets just fine). Ideally this should be extended to
StackedNeuralNet ... | yer neural net, loss is only (possibly)
added at the output layer.
"""
def __init__(self, in_dim=None, out_dim=None):
self.in_dim = in_dim
self.out_dim = out_dim
self.layers = []
self.layer_params = []
self.param_size = 0
self.loss = None
self.output... | nlin_type=None, dropout=0, sparsity=0,
sparsity_weight=0, init_scale=1, params=None, init_bias=0, use_batch_normalization=False):
"""
By default, nonlinearity is linear.
Return the newly added layer.
"""
if self.output_layer_added:
raise NetworkConstruct... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.