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 |
|---|---|---|---|---|---|---|---|---|
jespino/anillo | anillo/middlewares/json.py | Python | bsd-2-clause | 3,333 | 0.0015 | try:
import simplejson as json
except ImportError:
import json
import functools
from cgi import parse_header
def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):
"""
A middleware that parses the body of json requests and
encodes the json responses.
NOTE: this middle... | preserve_raw_body=preserve_raw_body
)
wrapped_func = wrap_json_body(func, preserve_raw_body=preserv | e_raw_body)
wrapped_func = wrap_json_response(wrapped_func, encoder=encoder)
return wrapped_func
def wrap_json_body(func=None, *, preserve_raw_body=False):
"""
A middleware that parses the body of json requests and
add it to the request under the `body` attribute (replacing
the previous value)... |
grcanosa/my-telegram-bot | src/not_used/handlers/cmdcollection.py | Python | gpl-3.0 | 1,143 | 0.033246 | #!/usr/bin/python3
import random;
import logging;
import emoji
import telegram
from telegram import Update;
from telegram.ext import Updater;
from telegram.ext import CommandHandler as CH;
from ..data import peopleemoji as LPEOPLEEMOJI;
logger = logging.getLogger(__name__);
class CmdCollection:
def __init__(sel... | self._cmd_list = [];
self._user_reg = userReg;
self._priority = priority;
def add_cmd(self,dispatcher,cmdprocessor):
self._cmd_list.append(cmdprocessor);
dispatcher.add_handler(CH(cmdprocessor.get_cmd(),self.process),self._priority);
def proc_phrase(self,bot,update):
... | process(self._user_reg,bot,update):
added = True;
break;
if not added:
text = "Command not defined yet! ";
catcry= emoji.emojize(":crying_cat_face:",use_aliases=True);
text += (catcry*4)
bot.send_message(chat_id=update.message.chat_... |
lemonad/jaikuengine | common/test/api.py | Python | apache-2.0 | 59,862 | 0.005813 | # Copyright 2009 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 or agreed to in writing, ... |
rv = self.get('/api/json', {'method': 'presence_get_contacts',
'nick': 'popular@example.com',
'since_time': str(timestamp_between)})
self.assertEqual(rv.get('servertime', ''), str(timestamp2), str(rv))
self.assertEqual(len(rv.get('rv', {}).get... | .get('extra', {}).get('status', ''),
'baz', str(rv))
self.assertEqual(rv['rv']['contacts'][0]['presence'].get('extra', {}).get('given_name', ''),
'Cele', str(rv))
self.assertEqual(rv['rv']['contacts'][0]['presence'].get('extra', {}).get('family_name', ''),
... |
apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/breakcom.py | Python | unlicense | 1,866 | 0 | from __future__ import unicode_literals
import re
import json
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_age_limit,
)
class BreakIE(InfoExtractor):
_VALID_URL = r'http://(?:www\.)?break\.com/video/(?:[^/]+/)*.+-(?P<id>\d+)'
_TESTS = [{
'url': 'http://www.break... | 'width': media['width'],
'height': media['height'], |
} for media in info['media'] if media.get('mediaPurpose') == 'play']
if not formats:
formats.append({
'url': info['videoUri']
})
self._sort_formats(formats)
duration = int_or_none(info.get('videoLengthInSeconds'))
age_limit = parse_age_... |
plotly/python-api | packages/python/plotly/plotly/validators/scattercarpet/_metasrc.py | Python | mit | 444 | 0.002252 | import _plotly_utils.basevalidators
class MetasrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="metasrc", parent_name="scattercarpet", ** | kwargs):
super(MetasrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
role=kwargs.pop("role", "info"),
| **kwargs
)
|
mhb8898/Sadjad-AI-Server | model/map.py | Python | gpl-3.0 | 5,611 | 0.027981 |
from enum import Enum
from random import randint
import json
import time
N=10
class ObjectType(Enum):
empty=0
red=1
blue=2
yellow=3
black=4
green=5
# pig=7
# giant_pig=8
rock=9
wood=10
glass=11
rocket=12
bomb=13
laser=14
def __init__(self,number,color=None... | mber%2:
for x in range(N):
if any([power is self.map[x][j] for power in powers]):
self.action(x, j)
self.map[x][j]=ObjectType.empty
else:
| for y in range(N):
if any([power is self.map[i][y] for power in powers]):
self.action(i, y)
self.map[i][y]=ObjectType.empty
elif self.map[i][j] is ObjectType.bomb:
# print "bomb"
l=[(i,j) for i in range(-2,3) ... |
MacHu-GWU/sqlite4dummy-project | sqlite4dummy/tests/functionality/test_MetaData.py | Python | mit | 5,883 | 0.007691 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
本测试模块用于测试与 :class:`sqlite4dummy.schema.MetaData` 有关的方法
class, method, func, exception
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from sqlite4dummy import *
from sqlite4dummy.tests.basetest import *
from datetime import dateti... | _metadata.get_table("test").\
c._bytes_with_default.default, self.bytes_)
self.assertE | qual(second_metadata.get_table("test").\
c._date_with_default.default, self.date_)
self.assertEqual(second_metadata.get_table("test").\
c._datetime_with_default.default, self.datetime_)
self.assertEqual(second_metadata.get_table("test").\
... |
omaraboumrad/djanground | backend/dryorm/urls.py | Python | mit | 971 | 0 | """dryorm URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.ho | me, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls | import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
from core import views
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='index.html')),
ur... |
lukauskas/dgw | dgw/evaluation/tests/test_resampling.py | Python | gpl-3.0 | 1,877 | 0.001598 | import unittest
import numpy as np
from numpy.testing import assert_array_equal
from dgw.evaluation.resampling import extend_point, shrink_to_a_single_point
class TestExtending(unittest.TestCase):
def test_extend_point(self):
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
ans = np.array([0, 1, ... | oint(a, 1, 2))
def test_extend_point_left_boundary(self):
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])
ans = np.array([0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8])
assert_array_equal(ans, extend_point(a, 0, 4))
def test_extend_point_right_boundary(self):
a = np.array([0, 1, 2, 3, 4, 5... | lf):
a = np.array([0, 1, 2, 3, 3, 3, 3, 4, 5, 6])
ans = np.array([0, 1, 2, 3, 4, 5, 6])
assert_array_equal(ans, shrink_to_a_single_point(a, 3, 4))
b = np.array([0, 1, 2, 3, 8, 9, 10, 4, 5, 6])
ans = np.array([0, 1, 2, np.mean([3, 8, 9, 10]), 4, 5, 6])
assert_array_equ... |
FDio/vpp | test/vpp_ip.py | Python | apache-2.0 | 6,921 | 0 | """
IP Types
"""
import logging
from ipaddress import ip_address
from socket import AF_INET, AF_INET6
from vpp_papi import VppEnum
from vpp_object import VppObject
try:
text_type = unicode
except NameError:
text_type = str
_log = logging.getLogger(__name__)
class DpoProto:
DPO_PROTO_IP4 = 0
DPO_P... | def __init__(self, addr):
| self.addr = addr
self.ip_addr = ip_address(text_type(self.addr))
def encode(self):
if self.version == 6:
return {'ip6': self.ip_addr}
else:
return {'ip4': self.ip_addr}
@property
def version(self):
return self.ip_addr.version
@property
def a... |
chshu/openthread | tests/scripts/thread-cert/Cert_5_1_07_MaxChildCount.py | Python | bsd-3-clause | 10,758 | 0.001301 | #!/usr/bin/env python3
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | timeout': config.DEFAULT_CHILD_TIMEOUT,
'allowlist': [ROUTER]
},
4: {
'name': 'MED2',
'is_mtd': True,
'mode': 'rn',
'panid': 0xface,
'timeout': config.DEFAULT_CHILD_TIMEOUT,
'allowlist': [ROUTER]
},
5: {
... | d': True,
'mode': 'rn',
'panid': 0xface,
'timeout': config.DEFAULT_CHILD_TIMEOUT,
'allowlist': [ROUTER]
},
6: {
'name': 'MED4',
'is_mtd': True,
'mode': 'rn',
'panid': 0xface,
'timeout': config.DEF... |
diegojromerolopez/djanban | src/djanban/apps/boards/migrations/0056_auto_20170311_2036.py | Python | mit | 866 | 0.002309 | # - | *- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-03-11 19:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('boards', '0055_auto_20170311_0321'),
]
operations = [
migrations.AddField(
... | d. It is automatically generated and stored.', null=True, upload_to=b'', verbose_name='Identicon'),
),
migrations.AddField(
model_name='board',
name='identicon_hash',
field=models.CharField(blank=True, default='', help_text='Identicon hash used to know when to update ... |
dpwrussell/openmicroscopy | components/tools/OmeroPy/src/omero/util/ROI_utils.py | Python | gpl-2.0 | 22,495 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# ------------------------------------------------------------------------------
# Copyright (C) 2006-2016 University of Dundee. All rights reserved.
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General P... | ##
# Initialise the ROICoordinate.
# @param z The z-section.
# @param t The timepoint.
def __init__(self, z=0, t=0):
self.theZ = rint(z)
self.theT = rint(t)
##
# Set the (z, t) for the roi using the (z, t) of the ROICoordinate.
# @param roi The ROI to set the (z, t) on.
... | roi.setTheT(self.theT)
##
# Get the (z, t) from the ROI.
# @param See above.
#
def setCoordFromROI(self, roi):
self.theZ = roi.getTheZ()
self.theT = roi.getTheT()
##
# Interface to inherit for accepting ROIDrawing as a visitor.
# @param visitor The ROIDrawingCompoent.
#
class R... |
sephalon/python-ivi | ivi/agilent/agilentE3634A.py | Python | mit | 1,924 | 0.004678 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 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... | E USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .agilentE3600A import *
from .. import scpi
class agilentE3634A(agilentE3600A, scpi.dcpwr.OCP):
"Agilent E3634A IVI DC power supply driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'E3634A')
... | self._output_count = 1
self._output_spec = [
{
'range': {
'P25V': (25.75, 7.21),
'P50V': (51.5, 4.12)
},
'ovp_max': 55.0,
'ocp_max': 7.5,
'voltage_max': 25.75,
... |
openmv/openmv | scripts/examples/OpenMV/22-Optical-Flow/image-patches-differential-rotation-scale.py | Python | mit | 3,596 | 0.009177 | # Image Patches Differential Optical Flow Rotation/Scale
#
# This example shows off using your OpenMV Cam to measure
# rotation/scale by comparing the current and the previous
# image against each other. Note that only rotation/scale is
# handled - not X and Y translation in this mode.
#
# However, this examples goes b... | s of...
BLOCK_W = 16 # pow2
BLOCK_H = 16 # pow2
# To run this demo effectively please mount your OpenMV Cam on a steady
# base and SLOWLY rotate the camera around the lens and move the camera
| # forward/backwards to see the numbers change.
# I.e. Z direction changes only.
import sensor, image, time, math
# NOTE!!! You have to use a small power of 2 resolution when using
# find_displacement(). This is because the algorithm is powered by
# something called phase correlation which does the image comparison
# ... |
aaronkl/RoBO | robo/task/synthetic_functions/hartmann6.py | Python | bsd-3-clause | 1,747 | 0.001717 | '''
Created on 14.07.2015
@author: Aaron Klein
'''
import numpy as np
from robo.task.base_task import BaseTask
class Hartmann6(BaseTask):
def __init__(self):
X_lower = np.array([0, 0, 0, 0, 0, 0])
X_upper = np.array([1, 1, 1, 1, 1, 1])
opt = np.array([[0.20169, 0.150011, 0.476874, 0.27... | [4047, 8828, 8732, 5743, 1091, 381]])
def objective_function(self, x):
"""6d Hartmann test function
input bounds: 0 <= | xi <= 1, i = 1..6
global optimum: (0.20169, 0.150011, 0.476874, 0.275332, 0.311652, 0.6573),
min function value = -3.32237
"""
external_sum = 0
for i in range(4):
internal_sum = 0
for j in range(6):
internal_sum = internal_sum + se... |
OKThess/website | main/migrations/0001_initial.py | Python | mit | 736 | 0.001359 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-03 11:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Team',... | ame', models.CharField(max_length=100)),
('description', models.TextField()),
('company_link', models.CharField(max_length=500)),
('image_link', models.C | harField(max_length=500)),
],
),
]
|
lamastex/scalable-data-science | db/xtraResources/edXBigDataSeries2015/CS100-1x/Module 3: Lectures.py | Python | unlicense | 3,213 | 0.001867 | # Databricks notebook source exported at Mon, 14 Mar 2016 03:21:05 UTC
# MAGIC %md
# MAGIC **SOURCE:** This is from the Community Edition of databricks and has been added to this databricks shard at [/#workspace/scalable-data-science/xtraResources/edXBigDataSeries2015/CS100-1x](/#workspace/scalable-data-science/xtraRes... | nce/master/images/AWS_logoTM_200px.png)](https://www.awseducate.com/microsite/CommunitiesEngageHome).
# COMMAND ----------
# MAGIC %md
# MAGIC <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-n... | censed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/">Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License</a>.
# COMMAND ----------
# MAGIC %md
# MAGIC ## Module Three Lectures
# COMMAND ----------
# MAGIC %md
# MAGIC ### Lecture 5: Semi-Structured D... |
jawilson/home-assistant | homeassistant/components/garages_amsterdam/__init__.py | Python | apache-2.0 | 1,819 | 0.00055 | """The Garages Amsterdam integration."""
from datetime import timedelta
import logging
import async_timeout
import garages_amsterdam
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coor... |
for garage in await garages_amsterdam.get_garages(
aiohttp_client.async_get_clientsession(hass)
)
}
coordinator = DataUpdateCoordinator(
hass,
logging.getLogger(__name__),
name=DOMAIN,
update_method=async_get_garages,
... | t_refresh()
hass.data[DOMAIN] = coordinator
return coordinator
|
heran7/edx-platform | common/lib/xmodule/xmodule/modulestore/inheritance.py | Python | agpl-3.0 | 4,454 | 0.001796 | from datetime import datetime
from pytz import UTC
from xblock.fields import Scope, Boolean, String, Float, XBlockMixin, Dict
from xmodule.fields import Date, Timedelta
from xblock.runtime import KeyValueStore
class InheritanceMixin(XBlockMixin):
"""Field definitions for inheritable fields"""
graded = Boole... | mapped to their serialized values
"""
return module.get_explicitly_set_fields_by_scope(Scope.settings)
class InheritanceKeyValueStore(KeyValueStore):
"""
Common superclass for kvs's which know about inheritance of | settings. Offers simple
dict-based storage of fields and lookup of inherited values.
Note: inherited_settings is a dict of key to json values (internal xblock field repr)
"""
def __init__(self, initial_values=None, inherited_settings=None):
super(InheritanceKeyValueStore, self).__init__()
... |
gc313/Learning-Python | testcurses.py | Python | lgpl-3.0 | 292 | 0.058219 | import androidhelper
import curses
droid = androidhelper.Android()
win=curses.initscr()
result="No result"
try:
win.box()
w,h=win.getmaxyx()
win.addstr(2,2,"Curses Test % | sx%s" % (w,h))
win.addstr(10,10,"Hit a key")
win.getch()
finally:
curses.endwin()
print( | "Result=",result)
|
SerjDDD/ArcadeMachine | gpio/led.py | Python | gpl-2.0 | 246 | 0.020325 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO. | BCM)
GPIO.setwarnings(False)
led = 19
GPIO.setup(led, GPIO.OUT)
x = 20
while x > 0:
GPIO.output(led, 1)
time.sleep(0.2)
GPIO.output(led, 0)
time.sleep(0.2)
x = x - 1
GPIO. | cleanup()
|
duke8253/trafficserver | tests/gold_tests/pluginTest/cookie_remap/substitute.test.py | Python | apache-2.0 | 4,520 | 0.001991 | '''
'''
# 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");... | /theunmatchedpath" \
-H"Cookie: oxalpha=3333" \
-H "Proxy-Connection: keep-alive" \
--verbose \
'''.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.StillRunningAfter = ts
tr.StillRunningAfter = server
tr = Test.AddT | estRun("Substitute $cr_req_url using $cr_urlencode")
tr.Processes.Default.Command = '''
curl \
--proxy 127.0.0.1:{0} \
"http://www.example.com/magic" \
-H"Cookie: acgamma=dfndfdfd" \
-H "Proxy-Connection: keep-alive" \
--verbose \
'''.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.StillRunningAfter = ... |
marrow/schema | test/validate/test_pattern.py | Python | mit | 3,413 | 0.024905 | from functools import partial
from random import choice, randrange
from string import ascii_letters as letters, digits, punctuation, whitespace
from marrow.schema.testing import ValidationTest
from marrow.schema.validate.pattern import alphanumeric, username, twitterusername, facebookusername, creditcard, hexcolor, al... | in(choice(chars) for _ in range(size))
bs = partial(rs, chars=punctuation + whitespace)
class TestAlphanumeric(ValidationTest):
validator = alphanumeric.validate
valid = (None, ) + tuple(rs((2,11)) for _ in range(10))
invali | d = (bs((5,11)) for _ in range(10))
class TestUsername(ValidationTest):
validator = username.validate
valid = ()
invalid = ()
class TestTwitterUsername(ValidationTest):
validator = twitterusername.validate
valid = ()
invalid = ()
class TestFacebookUsername(ValidationTest):
validator = facebookusername.vali... |
andela-jngatia/Picture-This | picturethis/imageeditor/urls.py | Python | mit | 561 | 0 | from django.conf.urls i | mport url
from rest_framework.urlpatterns import format_suffix_patterns
from viewsets import PhotoListView, EditedPhotoListView, PhotoDetailView, \
EditedPhotoUpdateView
urlpatterns = [
url(r'^photos/$', PhotoListView.as_view()),
url(r'^photos/(?P<pk>[0-9]+)/$', PhotoDetailView.as_view()),
url(r'^photo... | , EditedPhotoListView.as_view()),
url(r'^photos/(?P<photo_id>[0-9]+)/edits/(?P<pk>[0-9]+)/$',
EditedPhotoUpdateView.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
|
manchicken/gist_per_day | utils/threaded_csv_into_mongo.py | Python | unlicense | 2,553 | 0.031727 | #!/usr/bin/env python
import sys, getopt, csv, pprint
from pymongo import MongoClient
import threading
import time
import traceback
_THREAD_LIMIT = 10
print_lock = threading.Lock()
global_mongo = MongoClient(max_pool_size=_THREAD_LIMIT)
tsem = threading.Semaphore(value=_THREAD_LIMIT)
def usage(msg):
if msg !=... | ongo(record, mongo)
def run_csv_file(csvfile, mongo):
all_threads = []
print('Gonna load the CSV file "{csvfile}" into mongodb "{mongo}"\n'.format(csvfile=csvfile, mongo=mongo))
with open(csvfile,'rb') as incsv:
tsem.acquire()
with print_lock: print 'Thread is available...'
t = threading.Thread(ta... | _threads.append(t)
# Join all threads
for t in all_threads:
if t.isAlive(): t.join()
def main(argv):
csvfile=None
mongo=None
try:
opts, args = getopt.getopt(argv, 'hf:m:',['file=','mongo='])
except getopt.GetoptError:
usage(None)
for one, arg in opts:
if one == '-h':
usage(No... |
Azure/azure-sdk-for-python | sdk/recoveryservices/azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/activestamp/operations/_private_endpoint_connection_operations.py | Python | mit | 20,920 | 0.00478 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Accept'] = _SERIALIZER.he | ader("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_put_request_initial(
vault_name: str,
resource_group_name: str,
subscription_id: str,
private_endpoint_conn... |
ksrajkumar/openerp-6.1 | openerp/addons/email_template/wizard/mail_compose_message.py | Python | agpl-3.0 | 10,036 | 0.004583 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | browse(cr, uid, ids, context=context):
had_template = record.use_template
record.write({'use_template': not(had_template)})
if had_template:
# equivalent to choosing an empty template
| onchange_defaults = self.on_change_template(cr, uid, record.id, not(had_template),
False, email_from=record.email_from,
email_to=record.email_to, context=context)
record.write(onchan... |
learric/rivals_api | questions/migrations/0001_initial.py | Python | apache-2.0 | 1,423 | 0.002108 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-15 21:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... | on_delete=django.db.models.deletion.CASCADE, to='questions.Question'),
), |
]
|
wavefrontHQ/python-client | test/test_derived_metric_definition.py | Python | apache-2.0 | 1,356 | 0 | # coding: utf-8
"""
Wavefront REST API
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ... | ition() # noqa: E501
| pass
if __name__ == '__main__':
unittest.main()
|
gazeti/aleph | aleph/migrate/versions/e34d28e9a167_rename_documentpage.py | Python | mit | 365 | 0 | """rename documentpage
Revision ID: e34d28 | e9a167
Revises: a5ccf5eaa73f
Create Date: 2016-03-08 10:22:16.063105
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = 'e34d28e9a167'
down_revision = 'a5ccf5eaa73f'
def upgrade():
op.rename_table('page', 'document_page')
def downgrade():
op.rename_table('document_page', | 'page')
|
ncollins/pyquantfi | payoffs.py | Python | bsd-3-clause | 425 | 0.009412 | # PyQuantFi - payoffs.py
# (c) 2012 Nick Collins
def VanillaCall(k):
def | call(s):
return max(s - k, 0)
return call
def VanillaPut(k):
def call(s):
return max(k - s, 0)
return call
def DigitalCall(k):
def call(s):
if s > k: return 1
else: return 0
return ca | ll
def DigitalPut(k):
def call(s):
if s < k: return 1
else: return 0
return call
|
MuckRock/muckrock | muckrock/task/migrations/0033_auto_20181112_1623.py | Python | agpl-3.0 | 3,427 | 0.000875 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-11-12 21:23
# Django
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foia', '0062_auto_20181112_1623'),
('task', '0032_auto_20180713_1455'),
]
... | request due to an in-state citzenship law.'
), ('contact info changed', 'User supplied contact info.'), (
'no | proxy', 'No proxy was available.'
), (
'agency update',
'An agency logged in to the site and updated a request.'
), (
'agency new email',
'An agency with no primary email set replied via email.'
... |
Drinka/Aya | cogs/moderator.py | Python | mit | 2,181 | 0.00321 | import random
import discord
from discord.ext import commands
class Mod:
"""Moderation tools"""
def __init__(self, Aya):
self.Aya = Aya
@commands.command(pass_context=True)
async def kick(self, ctx, *, member):
"""Kicks someone out of the server"""
kickmsg = ['Poor %s is out!... | .format(ctx.message.author))
@commands.command(pass_context=True)
async def ban(self, ctx, *, member):
banmsg = ['We won\'t see %s again!', 'These people really really don\'t understand', 'See you never %s!']
try:
await se | lf.Aya.ban(member, delete_message_days=1)
await self.Aya.say(random.choice(banmsg) % member)
except discord.Forbidden:
await self.Aya.send_message(ctx.message.channel, '{}: Who do you really think you are?'
.format(ctx.message.author))
@comman... |
arkem/pyflag | src/pyflag/tests.py | Python | gpl-2.0 | 4,688 | 0.011305 | #!/usr/bin/env python
# Michael Cohen <scudette@users.sourceforge.net>
#
# ******************************************************
# Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$
# ******************************************************
#
# * This program is free software; you can redistribute it... | l Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# ******************************************************
""" This file defines a variety of things related to tests """
import unittest
from pyflag.FileSystem ... | gsh as pyflagsh
import pyflag.conf
config=pyflag.conf.ConfObject()
class FDTest(unittest.TestCase):
## These must be overridden with a file which is at least 100
## bytes long
test_case = ""
test_inode = ""
def setUp(self):
self.fs = DBFS(self.test_case)
self.fd = self.fs.open(... |
jeffminsungkim/datelikeus | src/datelikeus/users/apps.py | Python | mit | 276 | 0 | from | django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'datelikeus.users'
verbose_name = "Users"
def ready(self):
"""Override this to put in:
Users system checks
| Users signal registration
"""
pass
|
pinax/pinax-images | pinax/images/compat.py | Python | mit | 145 | 0 | try:
from acc | ount.mixins import LoginRequiredMixin
except ImportError:
from django.contrib.auth.mixins import Login | RequiredMixin # noqa
|
kalhartt/yadnss | django/skills/utils.py | Python | gpl-2.0 | 4,764 | 0.013644 | #!/usr/bin/python2.7
from dragonnest.settings import STATIC_ROOT
from skills.models import *
from PIL import Image, ImageDraw, ImageFont
import os
_ASCIIMAP = [chr(n) for n in ([45] + range(48, 58) + range(65, 91) + [95] + range(97, 123))]
_ALPHABET = dict(zip(range(64), _ASCIIMAP))
_ALPHABET_REVERSE = dict(zip(_ASCII... | ng'%img_path)
else:
img_path = os.path.join(STATIC_ROOT, 'img', 'lo', '%d.png'%img_path)
# Crop the icon from the imagemap
cropx = iconw*((slevel[n][0].icon%100)%10)
cropy = iconw*((slevel[n][0].icon%100)/10)
box = (c | ropx, cropy, cropx+iconw, cropy+iconw)
skill_img = Image.open(img_path).convert('RGBA')
skill_img = skill_img.crop(box)
img.paste(skill_img, (x,y), skill_img)
# Draw the skill level badge
msg = '%d/%d' % (slevel[n][1], SkillLevel.objects.filter(skill=slevel[n][0], requir... |
galica9999/sleuthkitvisualizer-475-2161-MacLennan | multiGui.py | Python | mit | 3,686 | 0.009495 | import tkinter as tk # python3
#import gui
#import Tkinter as tk # python
TITLE_FONT = ("Helvetica", 18, "bold")
class gui_Frame(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each ... | start page",
command=lambda: controller.show_frame("fileInputFrame"))
button.pack(side = "bottom")
button2 = tk.Button(self, text="Go to Page | Two",
command=lambda: controller.show_frame("commandOptionsFrame"))
button2.pack(side="right", padx=20)
class commandOptionsFrame(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.... |
xzased/lvm2py | lvm2py/lvm.py | Python | gpl-3.0 | 7,587 | 0.003559 | #This file is part of lvm2py.
#lvm2py 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.
#lvm2py is distributed in the hope that it will be... | raise HandleError("Failed to create VG.")
for device in devices:
if not os.pa | th.exists(device):
self._destroy_vg(vgh)
raise ValueError("%s does not exist." % device)
ext = lvm_vg_extend(vgh, device)
if ext != 0:
self._destroy_vg(vgh)
raise CommitError("Failed to extend Volume Group.")
try:
... |
lifeloverxg/principles-of-computing-2 | test_mini_project7.py | Python | mit | 11,001 | 0.008181 | # unit tests for Mini-project 7 (The Fifteen Puzzle), by k., 08/02/2014
import unittest
from mini_project7 import Puzzle
class TestFunctions(unittest.TestCase):
def setUp(self):
pass
def test_lower_row_invariant(self):
state = Puzzle(4, 4, [[4, 2, 3, 7], [8, 5, 6, 10], [9, 1, 0, 11], [12, 13,... | 14, 15]])
self.assertFalse(state.lower_row_invariant(2, 2))
state = Puzzle(4, 4, [[4, 2, 3, 7], [8, 5, 6, 10], [9, 0, 1, 11], [12, 13, 14, 15]])
self.assertFalse(state.lower_row_invariant(2, 2))
state = Puzzle(4, 4, [[4, 2, 3, 7], [8, 5, 6, 10], [9, 1, 0, 12], [11, 13, 14, 15]])
... | 6, 1], [9, 0, 10, 11], [12, 13, 14, 15]])
self.assertTrue(state.lower_row_invariant(2, 1))
state = Puzzle(4, 4, [[4, 2, 3, 7], [8, 5, 6, 1], [9, 0, 10, 11], [13, 12, 14, 15]])
self.assertFalse(state.lower_row_invariant(2, 1))
state = Puzzle(3, 3, [[8, 7, 6], [5, 4, 3], [2, 1, 0]])
... |
zemuvier/Python-courses | plugins/HiPlugin.py | Python | gpl-3.0 | 414 | 0.007246 | from template import PluginTemplate
class HiPlugin(PluginTemplate):
"""
HiPlugin - simplest plugin to che | ck that Levitan is running.
It responds 'hi' to 'hi' from user
"""
def __init__(self, config=None):
self.requests = ["^\s*hi\s*$"]
def process(self, skype_message):
return "hi"
def check_plugin_config(self):
return {'status': True, 'errorMessage': No | ne} |
bxlab/bx-python | lib/bx/__init__.py | Python | mit | 23 | 0 | __v | ersion__ = '0.8.13'
| |
meteoswiss-mdr/monti-pytroll | scripts/input_test.py | Python | lgpl-3.0 | 9,570 | 0.023302 | from __future__ import division
from __future__ import print_function
def input(in_msg):
import inspect
in_msg.input_file = inspect.getfile(inspect.currentframe())
print("*** read input from ", in_msg.input_file)
# 8=MSG1, 9=MSG2, 10=MSG3
#in_msg.sat_nr=0
#in_msg.RSS=True
#in_msg.sat_n... | phr_hl')
#in_msg.RGBs.append('sphr_ki')
#in_msg.RGBs.append('sphr_li')
#in_msg.RGBs.append('sphr_ml')
#in_msg.RGBs.append('sphr_quality')
##in_msg.RGBs.append('sphr_sflag | ')
#in_msg.RGBs.append('sphr_shw')
#in_msg.RGBs.append('sphr_tpw')
#-------------------
# experimental
#in_msg.RGBs.append('clouddepth') # test according to Mecikalski, 2010
##in_msg.RGBs.append('RII')
#----------------
# chose area
#----------------
in_msg.areas.append... |
great-expectations/great_expectations | tests/cli/utils.py | Python | apache-2.0 | 4,550 | 0.000659 | import traceback
from _pytest.logging import LogCaptureFixture
from click.testing import Result
VALIDATION_OPERATORS_DEPRECATION_MESSAGE: str = "Your data context with this configuration version uses validation_operators, which are being deprecated."
LEGACY_CONFIG_DEFAULT_CHECKPOINT_STORE_MESSAGE: str = (
"Detect... | (
click_result.exception
)
assert (
"traceback" not in click_result.output.lower()
), f"Found a traceback in the console output: {click_resul | t.output}"
assert (
"traceback" not in click_result.stdout.lower()
), f"Found a traceback in the console output: {click_result.stdout}"
try:
assert (
"traceback" not in click_result.stderr.lower()
), f"Found a traceback in the console output: {click_result.stderr}"
ex... |
jakobharlan/avango | examples/touch_example/modules/gesture_detectors.py | Python | lgpl-3.0 | 2,904 | 0.012741 | import avango
import avango.gua
from examples_common.device import TouchDevice
from examples_common.device import TouchCursor
class TapDetector(avango.script.Script):
| Cursor = TouchCursor()
TapDetected = avango.SFBool()
TapPosition = avango.gua.SFVec2()
TapTimeThreshold = avango.SFFloat() # in seconds
def __init__(self):
self.super(TapDetector).__init__()
self.always_evaluate(True)
self.TapTimeThreshold.value = 0.5
self.__timer = avan... | ):
self.TapDetected.value = False
self.TapPosition.value = avango.gua.Vec2(-1.0, -1.0)
self.__touch_start_time = 0
self.__touch_start_position = avango.gua.Vec2(-1.0, -1.0)
self.__last_cursor_state = 4
def evaluate(self):
if self.__last_cursor_state == 4 and self.Cursor.State.value != 4:
... |
saeki-masaki/glance | glance/async/flows/convert.py | Python | apache-2.0 | 3,953 | 0 | # Copyright 2015 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... | # specified. There's no "sane" | default for this
# because the dest format may work differently depending
# on the environment OpenStack is running in.
conversion_format = CONF.taskflow_executor.conversion_format
if conversion_format is None:
if not _Convert.conversion_missing_warned:
msg = ... |
LABETE/TestYourProject | TestYourProject/contrib/sites/migrations/0002_set_site_domain_and_name.py | Python | bsd-3-clause | 955 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrat | ions
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings. | SITE_ID,
defaults={
"domain": "TestYourProject.com",
"name": "TestYourProject"
}
)
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=setti... |
HuuHoangNguyen/Python_learning | bitwise_operators.py | Python | mit | 586 | 0.006826 | #!/usr/bin/python
a = 60 # 60 = 2b00111100
b = 13 # 13 = 2b00001101
c = 0 # 0 = 2b00000000
c = a & b # 12 = 2b00001100
print "Line 1: Value of c = a & b is: ", c
c = a | b # 61 = 2b00111101
print "Line 2: Value of c = a | b is: ", c
c = a ^ b # 49 = 2b00110001
print "L... | # 15 = | 2b00001111
print "Line 6: Value of c = a >> 2 is: ", c
|
OpenTechFund/WebApp | opentech/public/funds/migrations/0005_link_text_optional.py | Python | gpl-2.0 | 536 | 0.001866 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-01-25 13:08
from __future | __ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('public_funds', '0004_fundpagerelatedpage'),
]
operations = [
migrations.AlterField(
model_name='labpage',
name='link_text',
f... | nks', max_length=255),
),
]
|
antingshen/BeaverDam | annotator/migrations/0009_auto_20170815_1341.py | Python | bsd-2-clause | 469 | 0 | # -*- coding: utf-8 -*-
# Generat | ed by Django 1.10 on 2017-08-15 20:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('annotator', '0008_video_labels'),
]
operations = [
migrations.AlterField(
model_name='vid | eo',
name='labels',
field=models.ManyToManyField(blank=True, to='annotator.Label'),
),
]
|
MuckRock/muckrock | muckrock/accounts/migrations/0021_auto_20161228_1233.py | Python | agpl-3.0 | 2,686 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-12-28 12:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0020_profile_preferred_proxy'),
]
operations = [
migrations.AddField(
model_name='statistic... | ,
migrations.AddField(
model_name='statistics',
name='machine_requests_no_docs',
field=models.IntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='statistics',
name='machine_requests_partial',
field=model... | model_name='statistics',
name='machine_requests_payment_required',
field=models.IntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='statistics',
name='machine_requests_submitted',
field=models.IntegerField(blank=True, null=... |
zenodo/invenio | invenio/modules/pages/admin.py | Python | gpl-2.0 | 3,432 | 0 | # -*- coding: utf-8 -*-
# This file is part of Invenio.
# Copyright (C) 2014, 2015 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 l... | a_env.get_template(field.data)
except TemplateNotFound:
raise ValidationError("Selected template d | oes not exist.")
def same_page_choosen(form, field):
"""Check that we are not trying to assign list page itself as a child."""
if form._obj is not None:
if field.data.id == form._obj.list_id:
raise ValidationError(
'You cannot assign list page itself as a child.')
class P... |
LindaLinsefors/EinSumConv | EinSumConv/tensor.py | Python | bsd-2-clause | 6,432 | 0.024876 | import sympy.core.cache
# Why doesn't it work to use "import sympy.core.compatibility" and call "with_metaclass" as "sympy.core.compatibility.with_metaclass"?
from sympy.core.compatibility import with_metaclass
from sympy.core.function import AppliedUndef, FunctionClass
from sympy.core.core import BasicMeta
from sympy... | ummy('b);
>>> x=sympy.Symbol('x')
>>> isi | nstance(TensorFunction('TF')(a,b)(x), sympy.Function)
True
'''
def isTensor(exp):
'''Test if exp is a Tensor or TensorFunction.
Only returns True for Tensor with index/indecis and TensorFunction with index/indecis and argument(s)
Only test the top type of exp, e.g. does not detect a derivative of... |
wbap/V1 | python/setup.py | Python | apache-2.0 | 657 | 0.004566 | from setuptools import setup, find_packages
import sys, os
version = '1.0.0'
setup(name='brica1',
version=version,
description="",
long_description="""\
""",
classifiers=[], # Ge | t strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='ktnyt',
author_email='kotone [at] sfc.keio.ac.jp',
url='',
license='Apache v2',
packages=find_packages(exclude=['ez_setup', 'examples', ' | tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'numpy'
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
jawilson/home-assistant | homeassistant/components/flipr/binary_sensor.py | Python | apache-2.0 | 1,353 | 0.000739 | """Support for Flipr binary sensors."""
from __future__ import annotations
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_PROBLEM,
BinarySensorEntity,
BinarySensorEntity | Description,
)
from . import FliprEntity
from .const import DOMAIN
BINARY_SENSORS_TYPES: tuple[BinarySensorEntityDescription, ...] = (
BinarySensorEntityDescription(
key="ph_status",
name="PH Status",
device_class=DEVICE_CLASS_PROBLEM,
),
BinarySensorEntityDescription(
key=... | evice_class=DEVICE_CLASS_PROBLEM,
),
)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Defer sensor setup of flipr binary sensors."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
FliprBinarySensor(coordinator, description)
for desc... |
alaski/nova | nova/hacking/checks.py | Python | apache-2.0 | 30,206 | 0.000894 | # Copyright (c) 2012, Cloudscaling
# 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... | now() must be used instead of datet | ime.%s()"
datetime_funcs = ['now', 'utcnow']
for f in datetime_funcs:
pos = logical_line.find('datetime.%s' % f)
if pos != -1:
yield (pos, msg % f)
def _get_virt_name(regex, data):
m = regex.match(data)
if m is None:
return None
driver = m.group(1)
# Ignore... |
oblique-labs/pyVM | rpython/jit/metainterp/test/test_recursive.py | Python | mit | 47,329 | 0.005599 | import py
from rpython.rlib.jit import JitDriver, hint, set_param
from rpython.rlib.jit import unroll_safe, dont_look_inside, promote
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.debug import fatalerror
from rpython.jit.metainterp.test.support import LLJitMixin
from rpython.jit.codewriter.po... | print main(100)
res = self.meta_interp(main, [100], enable_opts='', inline=True)
assert res == 0
def test_guard_failure_and_then_exception_in_inlined_function(self):
def p(pc, code):
code = hlstr | (code)
return "%s %d %s" % (code, pc, code[pc])
myjitdriver = JitDriver(greens=['pc', 'code'], reds=['n', 'flag'],
get_printable_location=p)
def f(code, n):
pc = 0
flag = False
while pc < len(code):
myjitdri... |
colloquium/spacewalk | backend/server/handlers/xmlrpc/errata.py | Python | gpl-2.0 | 9,420 | 0.005839 | #
# Copyright (c) 2008--2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | and p.name_id = LOOKUP_PACKAGE_NAME(:name)
-- map to a channel
and p.id = cp.package_id
and cp.channel_id = dcm.channel_id
and dcm.release = :dist
| -- map to an errata as well
and p.id = ep.package_id
and ep.errata_id = e.id
-- the errata and the channel have to be linked
and ce.channel_id = cp.channel_id
-- and the channel has to be public
and cp.channe... |
jianajavier/pnc-cli | pnc_cli/buildconfigsetrecords.py | Python | apache-2.0 | 1,916 | 0.002088 | __author__ = 'thauser'
from argh import arg
import logging
from pnc_cli import utils
from pnc_cli.swagger_client.apis import BuildconfigurationsetsApi
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
sets_api = BuildconfigurationsetsApi(utils.get_api_client())
bcsr_api = BuildconfigsetrecordsApi(util... | call(bcsr_api, 'get_specific', id=id)
if not response:
logging.error("A BuildConfigurationSetRecord with ID {} does not exist.".format(id))
return
return response.content
@arg("id", help="ID of BuildConfigSetRecord to retrieve build rec | ords from.")
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_records_for_build_config_set(id, page_size=200, sort="", q=""):
"""
Get a list of BuildRecords for the given BuildConfigSetRecord
"""
... |
PhilipCastiglione/learning-machines | uninformed_search/algorithms/dfs.py | Python | mit | 4,778 | 0.003139 | """Depth-First Search is a search strategy where, starting at the root of a
tree of nodes to explore, the first child node encountered is explored
continually until a leaf node is reached, whereupon the parent of the leaf node
will have it's next child explored, effectively giving priority to nodes
farthest from the ro... | es()),
"current frontier nodes": [node.state for node in self.frontier.contents],
"number of frontier nodes": len(self. | frontier.contents),
"max number of frontier nodes": self.frontier.max
}
"""Visited nodes includes explored nodes and nodes on the frontier."""
def _visited_nodes(self):
return self.explored + self.frontier.contents or [] # must return a list
"""Adds states that can be reached f... |
open-contracting/validator | django/website/validator/forms.py | Python | gpl-2.0 | 1,886 | 0.002121 | # -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Div, Field, HTML
from crispy_forms.bootstrap import InlineRadios
class TextValidatorForm(forms.Form):
content = forms.CharField(widget=forms.Textarea, required=False)
fi... | self.helper.form_action = '.'
self.helper.form_method = 'post'
self.helper.layout = Layout(
Div(
Div(
Div(
Div(HTML("<p>Submit the data through | <strong>File</strong>, <strong>URL</strong> or <strong>Content</strong>. Only one input type at time will be validated.</p>")),
Div(Field('file')),
Div(Field('url')),
Div(Field('content')),
css_class="panel-body"
... |
neuroo/equip | equip/utils/files.py | Python | apache-2.0 | 1,118 | 0.016995 | # -*- coding: utf-8 -*-
"""
equip.utils.files
~~~~~~~~~~~~~~~~~
:copyrigh | t: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
import os
__normalize_path = lambda x: os.path.abspath(x)
def file_extension(filename):
if '.' not in filename:
return None
return filename[filename.rfind('.') + 1:].lower()
def good_ext(fext, l=None):
retur... | in names:
srcname = __normalize_path(os.path.join(directory, name))
try:
if os.path.isdir(srcname):
try:
scan_dir(srcname, files, l_ext)
except:
continue
elif os.path.isfile(srcname) \
and (not l_ext \
or good_ext(srcname[srcname.rfind(... |
shuoli84/gevent_socketio2 | socketio/engine/response.py | Python | mit | 1,322 | 0.002269 | # coding=utf-8
from webob.response import Response as WSGIResponse
from gevent.event import Event
from ..event_emitter import EventEmitter
class Response(WSGIResponse, EventEmitter):
"""
The Main reason for this class is make the response waitable. The primary event loop can listen on response
when end() ... | , did you call response.end() several times?')
if status_code is not None:
self.status_code = status_code
if body is not None:
self.body = body
self.event.set()
self.emit('post_end')
def join(self):
"""
Wait on the response object
"... | ect already ended
"""
return self.event.is_set()
|
uvasrg/EvadeML | classifiers/wepawet_wrapper.py | Python | mit | 4,325 | 0.008555 | import time
import os
import sys
import xml.etree.ElementTree as ET
_current_dir = os.path.abspath(os.path.dirname(__file__))
import_path = os.path.join(_current_dir, './wepawet')
sys.path.append(import_path)
from submit_to_wepawet import wepawet_submit_file, AnalysisOptions, wepawet_query
_current_dir = os.path.absp... | task_ids.append(task_id)
#results[file_path]['task_id'] = task_id
#for file_path, status in results.items():
# status['result' | ] = query_task(status['task_id'])
for task_id in task_ids:
status = query_task(task_id)
results.append(status)
return results
def wepawet(file_paths):
# submit files of unknown indices to wepawet
logger.info("Submit %d files to wepawet." % len(file_paths))
task_ids = wepawet.su... |
openstack/networking-6wind | networking_6wind/common/constants.py | Python | apache-2.0 | 1,169 | 0 | # Copyright 2015 6WIND S.A.
# 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... | DGE_PREFIX = 'brq'
# fp agent type
FP_AGENT_ | TYPE = '6WIND Fast Path agent'
# vhostuser socket settings
VHOSTUSER_SOCKET_DIR = '/tmp'
VHOSTUSER_SOCKET_MODE = 'client'
VHOSTUSER_SOCKET_PREFIX = 'vhost-socket-'
# vhostuser fp plug
# duplicate this constant from nova.network.model.py,
# in case of containerized setups: nova modules can be installed
# in another co... |
janeen666/mi-instrument | mi/dataset/param_dict.py | Python | bsd-2-clause | 7,444 | 0.00309 | #!/user/bin/env python
"""
@package mi.dataset.param_dict
@file mi/dataset/param_dict.py
@author Emily Hahn
@brief Extend the protocol param dict to handle dataset encoding exceptions
"""
import re
from mi.core.instrument.protocol_param_dict import ProtocolParameterDict, ParameterDescription
from mi.core.instrument.p... | """
| self.value = None
class Parameter(object):
"""
A parameter dictionary item.
"""
def __init__(self, name, f_format, value=None, expiration=None):
"""
Parameter value constructor.
@param name The parameter name.
@param f_format The function that formats the parameter... |
karllessard/tensorflow | tensorflow/python/kernel_tests/matrix_inverse_op_test.py | Python | apache-2.0 | 7,837 | 0.00587 | # | Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required | by 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 permissions and
# limitations under the License.
# ====================... |
karesansui/karesansui | karesansui/gadget/guestby1currentsnapshot.py | Python | mit | 4,377 | 0.004569 | # -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# 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 lim... | DERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# |
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machi... |
fredzannarbor/pagekicker-community | scripts_python_3/bin/nerv35.py | Python | apache-2.0 | 2,890 | 0.03391 | #!/usr/local/bin/python
###################################################
# Jeffrey Herbstman
# nerv3.py
# Goal: Named entity recognition script to pull names/place from text
# called as python nerv3.py text_path_or_file
#
# Inputs:
# path - text file or directory containing text files
# output - output file name
# O... | "target file or directory for NER")
parser.add_argument('outfile', help = "target file for output")
parser.add_argument('uuid', help = "uuid")
args = parser.parse_args()
in_file = args.path
out_file = args.outfile
uuid = args.uuid
folder = os.path.join(tmpdir, uuid)
print(folder)
with open(in_file, 'rb') a... | read()
AlchemyApi_Key = 'b887e176b6a650093c3d4ca635cd1b470be6584e'
url = 'https://gateway-a.watsonplatform.net/calls/text/TextGetRankedNamedEntities'
payload = { 'apikey': AlchemyApi_Key,
'outputMode': 'xml',
'text': text,
'max_items': '3'
}
r = requests.post(url,payload)
... |
cgwire/zou | zou/migrations/versions/3b0d1321079e_.py | Python | agpl-3.0 | 799 | 0 | """Add replies column
Revision ID: 3b0d1321079e
Revises: 1e2d77a2f0c4
Create Date: 2021-11-03 23:32:15.720557
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_ | utils
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "3b0d1321079e"
down_revision = "1e2d77a2f0c4"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"comment",
sa.C... | ),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("comment", "replies")
# ### end Alembic commands ###
|
legacysurvey/pipeline | py/legacypipe/runs.py | Python | gpl-2.0 | 2,529 | 0.00949 | from __future__ import print_function
from legacypipe.survey import LegacySurveyData
class DecamSurvey(LegacySurveyData):
def filter_ccd_kd_files(self, fns):
return [fn for fn in fns if 'decam' in fn]
def filter_ccds_files(self, fns):
return [fn for fn in fns if 'decam' in fn]
def filter_a... | = np.delete(I, np.where((ccds.filter[I] == 'g') * (ccds.expnum[I] != 661055))[0])
#I = np.delete(I, np.where((ccds.filter[I] == 'z') * (ccds.expnum[I] != 790242))[0])
return I
class OdinData(LegacySurveyData):
#def filter_ccd_kd_files(self, fns):
# return [fn for fn in fns if ('90prime' in ... | for fn in fns if ('odin' in fn)]
def filter_annotated_ccds_files(self, fns):
return [fn for fn in fns if ('odin' in fn)]
def get_default_release(self):
return 200
class HscData(LegacySurveyData):
#def filter_ccd_kd_files(self, fns):
# return [fn for fn in fns if ('90prime' in fn) or ... |
hazelnusse/sympy-old | sympy/thirdparty/pyglet/pyglet/gl/agl.py | Python | bsd-3-clause | 28,537 | 0.00855 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2007 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | brary/Frameworks/AGL.framework/Headers/agl.h:81
AGL_ACCUM_BLUE_SIZE = 16 # /System/Library/Frameworks/AGL.framework/Headers/agl.h:82
AGL | _ACCUM_ALPHA_SIZE = 17 # /System/Library/Frameworks/AGL.framework/Headers/agl.h:83
AGL_PIXEL_SIZE = 50 # /System/Library/Frameworks/AGL.framework/Headers/agl.h:88
AGL_MINIMUM_POLICY = 51 # /System/Library/Frameworks/AGL.framework/Headers/agl.h:89
AGL_MAXIMUM_POLICY = 52 # /System/Library/Frameworks/AGL.framework/He... |
berkmancenter/mediacloud | apps/common/tests/python/mediawords/job/test_broker/python_worker.py | Python | agpl-3.0 | 637 | 0 | #!/usr/bin/env python3
"""Test Py | thon worker."""
from mediawords.job import JobBroker
from mediawords.util.log import create_logger
from mediawords.util.perl import decode_object_from_bytes_if_needed
log = create_logger(__name__)
def run_job(x: int, y: int) -> int:
if isinstance(x, bytes):
x = decode_object_from_bytes_if_needed(x)
... | '__main__':
app = JobBroker(queue_name='TestPythonWorker')
app.start_worker(handler=run_job)
|
codebugtools/codebug_tether | docs/conf.py | Python | gpl-3.0 | 8,707 | 0.006776 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CodeBug Tether documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 20 15:23:09 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this... | rmation about the project.
project = 'CodeBug Tether'
copyright = '2015, OpenLX'
# The version info for the project you | 're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# The short X.Y version.
# NOTE: this is the version of the firmware download too so don't change
# this with minor changes in the software if the firmware h... |
qtproject/qtqa | scripts/lancebot/lancebot.py | Python | gpl-3.0 | 32,623 | 0.002084 | # ###########################################################################
#
# Copyright (C) 2019 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of the Quality Assurance module of the Qt Toolkit.
#
# $QT_BEGIN_LICENSE:GPL-EXCEPT$
# Commercial License Usage
# Licensees holding valid... | batch file and saves PATH variables from
# the batch to the local os.environ
for var in vars.splitlines():
var = var.decode('cp1252')
k, _, v = map(str.strip, var.strip().partition('='))
if k.startswith('?'):
continue
os.environ[k] = v
if os.path.lexists(flexBis... | TH"] += (";" + os.path.dirname(os.path.normpath(JOMPath)))
compiler = shutil.which("jom.exe")
if compiler:
print(f"Found JOM at {compiler}")
else:
print(f"{hr} ERROR: JOM NOT FOUND ON SYSTEM. ABORTING... {hr}")
print("See README.md for more information on how to specify a JOM locati... |
abhishek8gupta/sp17-i524 | project/S17-IO-3017/code/projectearth/dbscanplot.py | Python | apache-2.0 | 3,601 | 0.01083 | import requests
import time
import dblayer
from sklearn.cluster import DBSCAN
import plotly
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import random
import testfile
# Create random colors in list
color_list = []
def generate_color(ncluster):
for i in range(ncluster):
color = '... | geo=dict(scope=('north america', 'south america'),
projection=dict(type='orthographic',rotation=dict(lon=-60)),
showland=True, landcolor='#191919',
| showcountries=True,
showocean=True, oceancolor='rgb(217,217,255)',
showframe=False,
),
xaxis=dict(showgrid=False, zeroline=False),
y... |
flipjack/misrutas | project/app/migrations/0035_auto_20151102_1328.py | Python | mit | 914 | 0.003282 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('app', '0034_auto_20151102_1210'),
]
operations = [
migrations.CreateModel(
name... | ('friend_user', models.ForeignKey(related_name='Friend_request_request', to=settings.AUTH_USER_MODEL)),
('me_user', models.ForeignKey(related_name='Friend_request_user', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterField(
model_name='my_groups... | field=models.CharField(default=b'1671C1', max_length=25),
),
]
|
jkonecki/autorest | AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py | Python | mit | 1,526 | 0.003277 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | Product
<fi | xtures.acceptancetestsazureresource.models.FlattenedProduct>`
:param dictionaryofresources:
:type dictionaryofresources: dict
"""
_attribute_map = {
'productresource': {'key': 'productresource', 'type': 'FlattenedProduct'},
'arrayofresources': {'key': 'arrayofresources', 'type': '[Flat... |
eadgarchen/tensorflow | tensorflow/python/keras/_impl/keras/layers/merge_test.py | Python | apache-2.0 | 8,416 | 0.01616 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# | Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License a | t
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governin... |
GelaniNijraj/PyMaterial | MBase/MValueAnimator.py | Python | mit | 2,211 | 0.001809 | from MBase.MFinalValueReachedException import MFinalValueReachedException
class MValueAnimator:
"""
A class to animate single integer or float values. It would also
help in applying various mathematical functions to the progress
of the animation.
"""
def __init__(self, initial_value, final_val... | .__step_value
if self.__current_value < self.__final_value:
self.__current_value = self.__final_value
| else:
raise MFinalValueReachedException('I\'ve reached my bounds man...')
return self.__current_value
def get_original_value(self):
""" Returns the initial value """
return self.__initial_value
def get_final_value(self):
""" Returns the value to be r... |
pllim/astropy | astropy/table/tests/test_column.py | Python | bsd-3-clause | 34,643 | 0.000693 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy.utils.tests.test_metadata import MetaBaseTest
import operator
import pytest
import numpy as np
from numpy.testing import assert_array_equal
from astropy.tests.helper import assert_follows_unicode_guidelines
from astr... | r, c)):
assert np.all(eq) if test_equal else not np.any(eq)
assert len(eq) == 3
if Column is table.Column:
assert type(eq) == np.ndarray
else:
assert type(eq) == np.ma.core.MaskedArray
assert eq.dtyp... | olumn behave sensibly"""
arr = np.array([1, 2, 3])
c = Column(arr, name='a')
for ufunc, test_true in ((np.isfinite, True),
(np.isinf, False),
(np.isnan, False),
(np.sign, True),
... |
gkc1000/pyscf | pyscf/fci/direct_nosym.py | Python | apache-2.0 | 9,431 | 0.005408 | #!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | y.zeros_like(fcivec)
libfci.FCIcontract_a_1e_nosym(h1e.ctypes.data_as(ctypes.c_void_p),
fcivec.ctypes.data_as(ctypes.c_void_p),
ci1.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb),
| ctypes.c_int(na), ctypes.c_int(nb),
ctypes.c_int(nlinka), ctypes.c_int(nlinkb),
link_indexa.ctypes.data_as(ctypes.c_void_p),
link_indexb.ctypes.data_as(ctypes.c_void_p))
libfci.FCIcontract_b_... |
vz10/secretBot | db_actions.py | Python | mit | 3,577 | 0.002516 | from boto3.dynamodb.conditions import Attr
def update_users_followers(username, follower_id, table, remove=False):
'''
Find all the users that %username% follows and
update their "followers" list and "followers_count" amount
'''
item = table.get_item(Key={'username': username}).get('Item', False)... | hoto_id': 0
}
)
def update_user(update, table):
username = str(update['message']['chat']['id'])
followers = table.scan(
FilterExpression=Attr('follow').contains(username)
)
item = table.get_item(Key={'username': username})['Item']
item['first_name'] = update.message.f... | 'follow'])
item['followers'] = [x['username'] for x in followers['Items']]
item['photo_id'] = item.get('photo_id', 0)
table.put_item(Item=item)
def update_user_photo(photo, username, table):
table.update_item(
Key={
'username': username
},
UpdateExpr... |
Cobliteam/shelver | shelver/test/conftest.py | Python | mpl-2.0 | 2,676 | 0 | import pytest
from shelver.image import Image
from shelver.provider.test import TestProvider
@pytest.fixture
def provider():
return TestProvider({})
@pytest.fixture
def images():
return {
'fedora': Image.from_dict({
'name': 'fedora',
'curr | ent_version': '25',
'environment': 'test',
'description': 'Fedora 25',
'template_path': 'fedora.yml',
'instance_type': 't2.micro'}),
'server': Image.from_dict({
'name': 'serv | er',
'current_version': '2',
'environment': 'test',
'description': 'Base server',
'template_path': 'server.yml',
'instance_type': 't2.micro',
'base': 'fedora'}),
'web': Image.from_dict({
'name': 'web',
'current_versi... |
captiosus/treadmill | tests/utils_test.py | Python | apache-2.0 | 12,668 | 0 | """This contains the unit tests for treadmill.utils.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import os
import shutil
import signal
import stat
import tempfile
import time
import unittest
# Disab... | ilobytes, '10')
self.assertEqual(10 * 1024, utils.kilobytes('10M'))
self.assertEqual(10 * 1024, utils.kilobytes('10m'))
self.a | ssertEqual(10 * 1024 * 1024, utils.kilobytes('10G'))
self.assertEqual(10 * 1024 * 1024, utils.kilobytes('10g'))
def test_size_to_bytes(self):
"""Test conversion of units to bytes."""
self.assertEqual(10, utils.size_to_bytes(10))
self.assertEqual(-10, utils.size_to_bytes(-10))
... |
atuljain/odoo | addons/website_mail/controllers/main.py | Python | agpl-3.0 | 3,844 | 0.003382 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms ... | _follower="on", email=False, **post):
cr, uid, context = request.cr, request.uid, request.context
partner_obj = request.registry['res.partner']
user_obj = request.registry['res.users']
_id = int(id)
_message_is_follower = message_is_follower == 'on'
_object = request.re... | ect]
# search partner_id
public_id = request.website.user_id.id
if uid != public_id:
partner_ids = [user_obj.browse(cr, uid, uid, context).partner_id.id]
else:
# mail_thread method
partner_ids = _object._find_partner_from_emails(
cr, S... |
srfraser/services | src/releng_notification_policy/releng_notification_policy/api.py | Python | mpl-2.0 | 8,694 | 0.002991 | # -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
from datetime import datetime, timedelta
from flask impo... | quests import get
from json import JSONDecodeError
from cli_common import log
from backend_common.auth import auth
import os
import mohawk
logger = log.get_logger(__name__)
AUTHENTICATION_SCOPE_PREFIX = 'project:releng:services/releng_notification_policy/permission/'
def get_policies_in_json_serializable_fo | rm(notification_policies: List[Policy]) -> List[dict]:
return [
policy.to_dict()
for policy in notification_policies
]
@auth.require_scopes([AUTHENTICATION_SCOPE_PREFIX + 'get_message'])
def get_message_by_uid(uid: str) -> dict:
session = current_app.db.session
message = session.query... |
CertainlyUncertain/Kinetic-Gunner-Gunner-of-Angst | utils.py | Python | gpl-3.0 | 502 | 0.011952 | # Utilities ------------------------------------------------------ | ------------ #
import math
def clamp(val, min, max):
if val <= min:
return min
elif val >= max:
return max
return val
def fixAngle(angle):
while angle > 180.0:
angle -= 360.0
while angle < -180.0:
angle += 360.0
| return angle
def diffAngle(angle1, angle2):
return fixAngle(angle1 - angle2)
# Utilities ------------------------------------------------------------------ # |
srossross/uvio | uvio/tests/test_idle.py | Python | mit | 720 | 0.004167 | import unittest
from uvio.loop import Loop
from uvio.idle import Idle
from uvio.handle import Handle
class Test(unittest.TestCase):
def test_init(self):
loop = Loop.create()
called = False
def callback():
print("callback called!")
nonlocal called
cal... | = True
idle.stop()
print("idle")
idle = Idle(callback)
| self.assertFalse(idle.is_active())
idle.start(loop)
self.assertTrue(idle.is_active())
self.assertFalse(idle.closing())
self.assertFalse(called)
print("run")
loop.run()
self.assertTrue(called)
if __name__ == '__main__':
unittest.main()
|
agconti/njode | env/lib/python2.7/site-packages/allauth/socialaccount/helpers.py | Python | bsd-3-clause | 5,989 | 0 | from django.contrib import messages
from django.contrib.auth import logout
from django.shortcuts import render_to_response, render
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.forms import ValidationError
from django.core.urlresolvers import reverse
from allauth.u... | uest, sociallogin)
def _complete_social_login(request, sociallogin):
if request.user.is_authenticated():
logout(request)
if sociallogin.is_ | existing:
# Login existing user
ret = _login_social_account(request, sociallogin)
else:
# New social user
ret = _process_signup(request, sociallogin)
return ret
def complete_social_signup(request, sociallogin):
return complete_signup(request,
soci... |
yeyanchao/calibre | src/calibre/library/server/base.py | Python | gpl-3.0 | 10,970 | 0.006472 | #!/usr/bin/env python
# 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'
import os
import logging
from logging.handlers import RotatingFileHandler
import cherrypy
from cherrypy.process.plugins im... | ack = None
try:
self.max_cover_width, self.max_cover_height = \
map(int, self.opts.max_cover.split('x'))
except:
self.max_cover_width = 1200
self.max_cover_height = 1600
path = P('content_server')
self.build_time = fromtimestamp... | at(path).st_mtime)
self.default_cover = open(P('content_server/default_cover.jpg'), 'rb').read()
if not opts.url_prefix:
opts.url_prefix = ''
cherrypy.engine.bonjour.ip_address = listen_on
cherrypy.engine.bonjour.port = opts.port
cherrypy.engine.bonjour.prefix = opts... |
veloutin/papas | apmanager/genericsql/models.py | Python | agpl-3.0 | 8,678 | 0.016711 | # PAPAS Access Point Administration System
# Copyright (c) 2010 Revolution Linux inc. <info@revolutionlinux.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
... | l import Decimal
DATABASE_CHOICE = (
('MY', 'MySQL'),
('PG', 'PostgreSQL'),
)
ENCODING_CHOICE = (
('8859', 'ISO-8859-1'),
('UTF8', 'Unicode'),
)
class DataSource(models.Model):
name = models.CharField(max_length = 100, unique=True,
help_text=u"A name to easily identify this data source ... | e name of the database containing the data for the report.")
database_type = models.CharField(max_length = 2, choices = DATABASE_CHOICE)
host = models.CharField(max_length = 100)
port = models.PositiveIntegerField(
help_text=u"Leave blank to use default port.", blank=True, null=True)
user = mode... |
ravibhure/ansible | lib/ansible/utils/module_docs_fragments/vca.py | Python | gpl-3.0 | 2,639 | 0.001516 | # (c) 2016, Charles Paul <cpaul@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a | ny later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A | PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
class ModuleDocFragment(object):
# Parameters for VCA modules
DOCUMENTATION = """
options:
us... |
makinacorpus/Geotrek | geotrek/authent/serializers.py | Python | bsd-2-clause | 265 | 0 | from rest_framework import serializers as rest_serializers
from geotrek.authent import models as authent_models
class StructureSerializer(rest_serializers.ModelSerializer):
class Meta:
model = authent_models.Structure
| fields | = ('id', 'name')
|
pierredepaz/politics-of-code | 09_python_nlp/a_NLP/twitter_tokenizer.py | Python | unlicense | 7,606 | 0.003287 | # code by christopher potts
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This code implements a basic, Twitter-aware tokenizer.
A tokenizer is a function that splits a string of text into words. In
Python terms, we map string and unicode objects into lists of unicode
objects.
There is not a single right way to... | er objects, there is a | single option:
preserve_case. By default, it is set to True. If it is set to
False, then the tokenizer will downcase everything except for
emoticons.
The __main__ method illustrates by tokenizing a few examples.
I've also included a Tokenizer method tokenize_random_tweet(). If the
twitter library is install... |
gogoair/foremast | src/foremast/utils/encoding.py | Python | apache-2.0 | 2,470 | 0.00081 | # Foremast - Pipeline Tooling
#
# Copyright 2018 Gogo, 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... | for the specific language governing permissions and
# limitations under the License.
"""Generate base64 encoded User Data."""
import ba | se64
from .templates import get_template
def generate_encoded_user_data(
env='dev',
region='us-east-1',
generated=None,
group_name='',
pipeline_type='',
canary=False,
):
r"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.... |
WebArchivCZ/Seeder | Seeder/core/generic_views.py | Python | mit | 5,479 | 0 | """
Shared generic views used across the modules
"""
from django.contrib import messages
from django.http.response import HttpResponseRedirect, JsonResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.base import View, Con... | self.process_action(action)
return HttpResponseRedirect(self.get_success_url())
else:
self.add_message(_('Action {0} not allowed.').format(action),
messages.ERROR)
return HttpResponseRedirect(self.get_fail_url())
class EditView... | SS)
return HttpResponseRedirect(self.get_object().get_absolute_url())
class ObjectMixinFixed(SingleObjectMixin):
"""
This mixin can be used with login and form mixin
"""
def dispatch(self, *args, **kwargs):
self.object = self.get_object()
return super().dispatch(*args, **kwarg... |
jorisvandenbossche/pandas | pandas/tests/indexes/timedeltas/test_indexing.py | Python | bsd-3-clause | 12,228 | 0.000818 | from datetime import (
datetime,
timedelta,
)
import re
import numpy as np
import pytest
from pandas import (
Index,
NaT,
Timedelta,
TimedeltaIndex,
Timestamp,
notna,
timedelta_range,
to_timedelta,
)
import pandas._testing as tm
class TestGetItem:
def test_ellipsis(self):... | sert result.freq == expected.freq
result = idx[4::-1]
expected = TimedeltaIndex(
["5 day", "4 day", "3 day", "2 day", "1 day"], freq="-1D", name="idx"
)
tm.assert_index_equal(result, expected)
assert result.freq == e | xpected.freq
@pytest.mark.parametrize(
"key",
[
Timestamp("1970-01-01"),
Timestamp("1970-01-02"),
datetime(1970, 1, 1),
Timestamp("1970-01-03").to_datetime64(),
# non-matching NA values
np.datetime64("NaT"),
],
)
... |
KrzysztofStachanczyk/Sensors-WWW-website | www/env/lib/python2.7/site-packages/django/db/migrations/operations/special.py | Python | gpl-3.0 | 7,662 | 0.002741 | from __future__ import unicode_literals
from django.db import router
from .base import Operation
class SeparateDatabaseAndState(Operation):
"""
Takes two lists of operations - ones that will be used for the database,
and ones that will be used for the state change. This allows operations
that don't ... | to_state)
def describe(self):
return "Custom state/database change combination"
class RunSQL(Operation):
"""
Runs some raw SQL. A reverse SQL statement may be provided.
Also accepts a list of operations that represent the state change effected
| by this SQL change, in case it's custom column/table creation/deletion.
"""
noop = ''
def __init__(self, sql, reverse_sql=None, state_operations=None, hints=None, elidable=False):
self.sql = sql
self.reverse_sql = reverse_sql
self.state_operations = state_operations or []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.