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 |
|---|---|---|---|---|---|---|---|---|
caioau/personal | fluxos/lista 2/grafo-6.py | Python | gpl-3.0 | 1,795 | 0.015042 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 27 01:20:46 2016
@author: caioau
"""
import matplotlib.pyplot as plt
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
def main():
G = nx.Graph() # G eh um grafo direcionado
# gera o grafo apartir de suas arest... | color"] = "black"
# G[1][2]["color"] = "red"
comprimento, caminho = nx.single_source_dijkstra(G, 1)
print caminho
for i in caminho:
# print i, comprimento[i], caminho[i]
for j in range(1, len(caminho[i])):
print caminho[i][j-1], caminho[i] | [j]
G[caminho[i][j-1]][caminho[i][j]]["color"] = "red"
desenhaGrafo(G, "grafo-6.png")
T = nx.minimum_spanning_tree(G)
desenhaGrafo(T, "grafo-6arv.png")
def desenhaGrafo(G,pngfilename): # desenha o grafo e salva numa imagem png
edge_labels=dict([((u,v,),d['weight']) # gera os labels das are... |
Pretagonist/Flexget | tests/test_metainfo.py | Python | mit | 6,791 | 0.003534 | from __future__ import unicode_literals, division, absolute_import
import pytest
class TestMetainfo(object):
config = """
tasks:
test_content_size:
mock:
- {title: 'size 10MB', description: 'metainfo content size should parse size 10.2MB from this'}
- {t... | "Jack's.Show.S03E01.blah.1080p"}
fals | e_positives:
mock:
- {title: 'FlexGet.epic'}
- {title: 'FlexGet.Apt.1'}
- {title: 'FlexGet.aptitude'}
- {title: 'FlexGet.Step1'}
- {title: 'Something.1x0.Complete.Season-FlexGet'}
- {title: 'Something.1xAll.Season.Complete-F... |
peterstark72/shapelink | shapelink.py | Python | mit | 7,087 | 0.016932 | #!/usr/bin/env python
import urllib
import urllib2
import json
import hashlib
import datetime
from collections import OrderedDict
AUTH_REQUIRETOKEN = "/auth/requiretoken"
BASEURL = "http://api.shapelink.com"
class ShapelinkException( Exception ):
pass
SHAPELINK_METHODS = {
'get_token' : {
're... | object):
def __init__(self, api, user_token, culture="sv"):
self.user_token = user_token
self.api = api
self.culture = culture
def diar | y(self, date=None):
'''Returns day activity for a specific day, today is default.
date - YYYY-MM-DD
'''
if not date:
date = datetime.datetime.today().strftime("%Y-%m-%d")
return self.api.get_day(self.user_token, date, self.culture)
def profile(self):
r... |
kdeloach/nyc-trees | src/nyc_trees/apps/survey/views.py | Python | agpl-3.0 | 26,088 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import os
import json
import shortuuid
from pytz import timezone
from celery import chain
from django_tinsel.exceptions import HttpBadRequestException
from django.conf import setting... | URVEY_DETAIL_QUERY = f.read()
def progress_page(request):
context = {
'legend_entries': [
{'mode': 'all', 'css_class': 'mapped', 'label': 'Mapped'},
{'mode': 'all', 'css_class' | : 'not-mapped', 'label': 'Not mapped'},
{'mode': 'all', 'css_class': 'unmappable',
'label': 'Could not be mapped'},
{'mode': 'my', 'css_class': 'mapped', 'label': 'Mapped by you'},
{'mode': 'my', 'css_class': 'not-mapped',
'label': 'Not mapped by you'},
... |
lielongxingkong/windchimes | swift/common/middleware/slo.py | Python | apache-2.0 | 19,534 | 0.000358 | # Copyright (c) 2013 OpenStack Foundation
#
# 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 ... | must be a PUT with the query parameter::
?multipart-manifest=put
The body of | this request will be an ordered list of files in
json data format. The data to be supplied for each segment is::
path: the path to the segment (not including account)
/container/object_name
etag: the etag given back when the segment was PUT
size_bytes: the size of the segment in bytes
The format... |
ksterker/wastesedge | scripts/dialogues/talan_start.py | Python | gpl-2.0 | 11,989 | 0.035032 | import dialogue
import adonthell
# -- pygettext support
def _(message): return message
class talan_start (dialogue.base):
text = [None,\
_("Oh, hullo again, $name."),\
_("Listen, I really am sorry about that fuss at the gate. I hope you will not hold it against me."),\
_("Please do not mention it again. I assu... | n's gems had been stolen and that Lady Silverhair was suspected of the theft."),\
_("So you did not see or hear anything out of place that night?"),\
_("No... no, not at all."),\
_("If you do not have any more questions ..."),\
_("No, thank you, I have a lot of work to do. You have been most helpful."),\
_("I... | ed him doing anything suspicious?"),\
_("Oh, he's a nasty sort, he is, sir. But other than being a busybody, I haven't noticed him doing anything that would lead me to believe that he is the thief."),\
_("Now, if you don't have any more questions..."),\
_("I wish you had not lied to me about the night of the thef... |
disabler/isida3 | lib/DNS/Base.py | Python | gpl-3.0 | 12,716 | 0.033894 | """
$Id: Base.py,v 1.12.2.10 2008/08/01 03:58:03 customdesigned Exp $
This file is part of the pydns project.
Homepage: http://pydns.sourceforge.net
This code is covered by the standard Python License.
Base functionality. Request and Response classes, that sort of thing.
"""
import socket, string, types, time, sel... | r=self.processUDPReply()
self.response = r
# FIXME: check waiting async queries
finally:
if not self.async:
self.s.close()
except socket.error:
continue
break
def sendTCPRequest(self, server):
" do the work of sending a TCP request "
self.response=None
for self.ns in server:... | CK_STREAM)
else: continue
else:
self.socketInit(socket.AF_INET, socket.SOCK_STREAM)
try:
# TODO. Handle timeouts &c correctly (RFC)
self.time_start=time.time()
self.conn()
buf = Lib.pack16bit(len(self.request))+self.request
# Keep server from making sendall hang
self.s.se... |
philba/myblog | myblog/urls.py | Python | mit | 1,474 | 0 | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import urls as djangoauth_urls
from search import views as search_views
from blog import views as blog_views
from wagtail.wagtai... | ively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the | site root:
# url(r'^pages/', include(wagtail_urls)),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatter... |
boada/planckClusters | MOSAICpipe/plugins/_dust.py | Python | mit | 3,312 | 0.002114 | import os
import sys
import time
# get the utils from the parent directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils import SEx_head
from pipe_utils import tableio, deredden
# Find the eBV dust correction for each source in the catalogs
def DustCorrection(self):
''' T... | print('# Writing Dust Extinction Catalog...', file=sys.stderr)
tableio.put_data(self.DustCat,
vars,
header=header,
format=format,
app | end='no')
print('# Dust file complete.', file=sys.stderr)
return
|
ssorj/blinky | misc/config.py | Python | apache-2.0 | 754 | 0.002653 | from blinky.appveyor import *
from blinky.circle import *
from blinky.github import | *
from blinky.jenkins import *
from blinky.travis impo | rt *
http_port = 8080
model.title = "Test CI"
# Components
proton_c = Component(model, "Proton C")
# Environments
multiple = Environment(model, "Multiple OSes")
# Agents
github = GitHubAgent(model, "GitHub")
# Categories
client_tests = Category(model, "Clients", "client")
# Groups
group = Group(model, clien... |
nico202/primeDiceBot | primeDiceClass.py | Python | gpl-3.0 | 6,205 | 0.005963 | ''' LICENCE
This file is part of primeDiceBot.
primeDiceBot 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.
primeDiceBo... | elif login_response == "Too many requests.":
# sys.exit("Too many requests. Wait before running the script again")
# else:
# print("Something went wrong, unknown error")
# sy | s.exit(login_response)
"""
Set the 'fairness' random number generator seed. It's strictly
required to set it to be able to bet
"""
def set_seed(self, seed = 5164131849335):
post_data = {
'seed': seed
}
result = self.session.post(self.seed_url + "?access_token="+... |
bpsagar/css2video | tests/parsers/value/test_color.py | Python | mit | 1,086 | 0 | import unittest
from css2video.constants import ValueType
from css2video.parsers.value import Color, ColorParseException
class TestCase(unittest.TestCas | e):
def test_parser(self):
response = Color.parse('#ffF')
self.assertEqual(
response,
dict(type=ValueType.color, red=255, green=255, blue=255, alpha=1)
)
response = Color.parse('#FFFFFF')
self.assertEqual(
response,
dict(type=... | rgba(0, 0, 0, 1)')
self.assertEqual(
response,
dict(type=ValueType.color, red=0, green=0, blue=0, alpha=1)
)
response = Color.parse('RGB(0, 0, 0)')
self.assertEqual(
response,
dict(type=ValueType.color, red=0, green=0, blue=0, alpha=1)
... |
OnroerendErfgoed/language-tags | language_tags/data/__init__.py | Python | mit | 334 | 0.002994 | import o | s
import json
from io import open
__all__ = ['get']
parent_dir = os.path.dirname(__file__)
data_dir = 'json/'
cache = {}
def get(name):
if name not in cache:
with open(os.path.join(parent_dir, data_dir, "%s.json" % name), encoding='utf-8') as f:
cache[name] = json.load(f)
return cache[... | ame]
|
wpoely86/easybuild-easyblocks | easybuild/easyblocks/generic/pythonpackage.py | Python | gpl-2.0 | 21,887 | 0.002878 | ##
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# Flemish Research Foundation ... | d_path = which(python_cmd)
if python_cmd_path is None:
log.debug("Python command '%s' not available through $PATH", python_cmd)
return False
if req_maj_ver is not None:
if req_min_ver is None:
req_majmin_ver = '%s.0' % req_maj_ver
... | .%s" % sys.version_info[:2])'
out, _ = run_cmd("%s -c '%s'" % (python_cmd, pycode), simple=False)
out = out.strip()
# (strict) check for major version
maj_ver = out.split('.')[0]
if maj_ver != str(req_maj_ver):
log.debug("Major Python version ... |
shunliz/test | python/flask/application/db/models.py | Python | apache-2.0 | 482 | 0.004149 | from sqlalchemy import Column, Integer, String
from sqlalchemy import Table
from application.db import Base
class User(Base):
__tablename__ = 'users'
id = Co | lumn(Integer, primary_key=True)
name = Column(String(50), unique=True)
password = Colum | n(String(120), unique=True)
def __init__(self, name=None, password=None):
self.name = name
self.password = password
def __repr__(self):
return '<User %r>' % (self.name)
|
ray-project/ray | python/ray/tune/cloud.py | Python | apache-2.0 | 10,640 | 0.000282 | import os
import shutil
import tempfile
from typing import Optional
from ray import logger
from ray.util import PublicAPI
from ray.util.ml_utils.cloud import (
download_from_bucket,
clear_bucket,
upload_to_bucket,
is_cloud_target,
)
@PublicAPI(stability="beta")
class TrialCheckpoint(os.PathLike):
... | y or cloud storage.
If the ``path`` is a local target and the checkpoint already exists
on local storage, the local directory is copied. Else, the checkpoint
is downloaded from cloud storage.
If the ``path`` is a cloud target and the checkpoint does not already
exist on local s... | heckpoints can be transferred across cloud storage providers.
Args:
path (Optional[str]): Path to save checkpoint at. If empty,
the default cloud storage path is saved to the default
local directory.
force_download (bool): If ``True``, forces (re-)downloa... |
ninefold/libcloud | libcloud/storage/drivers/ninefold.py | Python | apache-2.0 | 1,037 | 0.000964 | # 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 ... | tware
# 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 permi | ssions and
# limitations under the License.
from libcloud.storage.providers import Provider
from libcloud.storage.drivers.atmos import AtmosDriver
class NinefoldStorageDriver(AtmosDriver):
host = 'api.ninefold.com'
path = '/storage/v1.0'
type = Provider.NINEFOLD
name = 'Ninefold'
|
DeflatedPickle/pkinter | pkinter/boundbutton.py | Python | mit | 1,967 | 0.002034 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""""""
import tkinter as tk
from tkinter import ttk
# link
__title__ = "BoundButton"
__version__ = "1.0.3"
__author__ = "DeflatedPickle"
class BoundButton(ttk.Button):
"""
-----DESCRIPTION-----
A ttk Button that can be bound to any key to run any fu... | tton will run.
-----CONTENTS-----
---VARIABLES---
parent = The parent of the widget.
_text = The text of the Button.
_key = The key that will activate the Button.
_command = The function the button will run.
---TKINTER VARIABLES---
None
---WIDGETS---
self
... | t, text="", key="Return", command=None, *args):
ttk.Button.__init__(self, parent, default="active", text=text, command=command, *args)
self.parent = parent
self._text = text
self._key = key
self._command = command
self.bind("<{}>".format(key), command)
self.focu... |
karllessard/tensorflow | tensorflow/compiler/tests/complex_div_test.py | Python | apache-2.0 | 5,907 | 0.00237 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | complex(np.nan, 1),
complex(np.nan, np.inf), # C++ and Python diverge here.
complex(np.nan, np.nan),
],
dtype=dtype),
expected=np.array(
[
(1 + 1j) / complex(1, np.inf),
(1 + 1j) / complex... | complex(0 + 0j), # C++ and Python diverge here.
complex(0 + 0j), # C++ and Python diverge here.
(1 + 1j) / complex(np.nan, 1),
complex(0 + 0j), # C++ and Python diverge here.
(1 + 1j) / complex(np.nan, np.nan),
],
... |
xingjian-f/Leetcode-solution | 390. Elimination Game.py | Python | mit | 696 | 0.048851 | class Solution(object):
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
# a = range(1, n+1)
s = 2
if n == 1:
s = 1
length = n
step = 2
tag = 2
while length/2 > 1:
# print length, s, step
i... |
# while len(a) > 1:
# a = a[1::2]
# a = a[::-1]
| return s
for i in range(1, 50):
print Solution().lastRemaining(i) |
bjornaa/gridmap | test/test_gridmap0.py | Python | mit | 4,541 | 0.001763 | # -*- coding: utf-8 -*-
"""Unit tests for gridmap classed"""
# ----------------------------------
# Bjørn Ådlandsvik <bjorn@imr.no>
# Institute of Marine Research
# ----------------------------------
import sys
from math import pi
import unittest
import numpy as np
sys.path = ['..'] + sys.path # import from develop... | .map0.grid2ll(self.xp, self.yp)
# WGS84
lon1, lat1 = self.map1.grid2ll(self.xp, self.yp)
def test_ylon(self):
"""lon = ylon <=> x = xp"""
# lon = ylon => x = xp
lon, lat = self.ylon, 72.3
# sphere
x0, y0 = self.map0.ll2grid(lon, lat)
self.assertEqual... | p1.ll2grid(lon, lat)
self.assertEqual(x1, self.xp)
# x = xp => y = ylon
x, y = self.xp, 222.222
# sphere
lon0, lat0 = self.map0.grid2ll(x, y)
self.assertAlmostEqual(lon0, self.ylon, places=13)
# WGS84
lon1, lat1 = self.map1.grid2ll(x, y)
self.asse... |
c-oreills/pyFaceGraph | src/facegraph/url_operations.py | Python | unlicense | 2,148 | 0.003724 | import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combine... | query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = valu | e.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
""... |
drawquest/drawquest-web | website/sentry.conf.py | Python | bsd-3-clause | 4,246 | 0.004946 | import sys
import os.path
import os
def add_to_python_path(path):
if path not in sys.path:
sys.path.append(path)
add_to_python_path('/var/canvas/website')
from settings_sentry_common import *
from configuration import Config
CONF_ROOT = os.path.dirname(__file__)
DATABASES = {
'default': {
#... | s.SESBackend'
# Used for the django_ses e-mail backend
AWS_ACCESS_KEY_ID = Config['aws']['access_key']
AWS_SECRET_ACCESS_KEY = Config['aws']['secret_key']
DKIM_SELECTOR = 'amazonses'
DKIM_DOMAIN = 'example.com'
DKIM_PRIVATE_KEY_PATH = '/etc/canvas/dkim.private.key'
DKIM_PRIVATE_KEY = o | pen(DKIM_PRIVATE_KEY_PATH).read() if os.path.exists(DKIM_PRIVATE_KEY_PATH) else None
AWS_SES_VERIFY_BOUNCE_SIGNATURES = True
# Domains that are trusted when retrieving the certificate
# used to sign bounce messages.
AWS_SNS_BOUNCE_CERT_TRUSTED_DOMAINS = ['amazonaws.com', 'amazon.com']
DEFAULT_FROM_EMAIL = "passwordre... |
ScottWales/dmpr | test/test_dmpr.py | Python | apache-2.0 | 776 | 0.005155 | #!/usr/bin/env python
# Copyright | 2017 ARC Centre of Excellence for Climate Systems Science
# author: Scott Wales <scott.wales@unimelb.edu.au>
#
# 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/l... | an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from dmpr import *
def test_dmpr():
pass
|
lucidlylogicole/pallet | pallet/__init__.py | Python | mit | 41 | 0.073171 | __version | __='0.2.0'
fro | m .pallet import * |
jlinn/pylastica | pylastica/query/simplequerystring.py | Python | apache-2.0 | 1,809 | 0.002211 | __author__ = 'Joe Linn'
from pylastica.query.abstract import Abstra | ctQuery
class SimpleQueryString(AbstractQuery):
| """
@see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
"""
OPERATOR_AND = "and"
OPERATOR_OR = "or"
def __init__(self, query, fields=None):
"""
@param query:
@type query: str
@param fields:
@... |
joshuar500/mcratesv1 | mcratesv1_project/mcratesv1_project/settings.py | Python | apache-2.0 | 2,870 | 0 | """
Django settings for mcratesv1_project project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# ... | ddleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
... | ware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mcratesv1_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_process... |
Mariopilot808/BLNExporter | __init__.py | Python | gpl-2.0 | 1,407 | 0.004264 | """
/*******BLNexp
A QGIS plugin
Exports to Vector data to SurferBLN
-------------------
begin : 2014-16-09
copyright : (C) 2014 by Mario Noriega
email : mario.noriegaf@gmail.com
************... | nse as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* | *
***************************************************************************/
This script initializes the plugin, making it known to QGIS.
"""
def name():
return "BLN Exporter"
def description():
return "Converts Vector layers to BLN"
def version():
return "Version... |
shmish/core-assess | core/migrations/0005_auto_20170725_1458.py | Python | mpl-2.0 | 556 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-25 21:58
from __future__ import unicode_literals
from django.d | b import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20170716_0901'),
| ]
operations = [
migrations.RemoveField(
model_name='evidence',
name='student',
),
migrations.AlterField(
model_name='evidence',
name='done',
field=models.BooleanField(default=True),
),
]
|
CCI-MOC/GUI-Backend | api/v2/views/__init__.py | Python | apache-2.0 | 2,314 | 0.000864 | # flake8: noqa
from .account import AccountViewSet
from .allocation import AllocationViewSet
from .allocation_source import AllocationSourceViewSet
from .boot_script import BootScriptViewSet
from .base import BaseRequestViewSet
from .credential import CredentialViewSet
from .email_template import EmailTemplateViewSet
f... | plication import ProjectApplicationViewSet
from .project_link import ProjectExternalLinkViewSet
from .project_instance import ProjectInstanceViewSet
from .project_volume import ProjectVolumeViewSet
from .provid | er import ProviderViewSet
from .provider_machine import ProviderMachineViewSet
from .provider_type import ProviderTypeViewSet
from .quota import QuotaViewSet
from .resource_request import ResourceRequestViewSet
from .reporting import ReportingViewSet
from .size import SizeViewSet
from .status_type import StatusTypeView... |
horazont/aioxmpp | aioxmpp/roster/service.py | Python | lgpl-3.0 | 25,618 | 0.000156 | ########################################################################
# File name: service.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program 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 Foundati... | :class:`set` instances, which hold the :class:`Item` instances in
that group.
At no point one can observe empt | y :class:`set` instances in this
dictionary.
The :class:`Item` instances stay the same, as long as they represent the
identical roster entry on the remote side. That is, if the name or
subscription state are changed in the server side roster, the :class:`Item`
instance stays the same, but the at... |
carthagecollege/django-djsani | djsani/medical_history/waivers/views.py | Python | bsd-3-clause | 3,562 | 0 | # -*- coding: utf-8 -*-
"""Forms for medical history."""
import datetime
import os
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reve | rse_lazy
from djsani.core.utils import get_manager
from djsani.medical_history.waivers.models import Sicklecell
from djtools.fields import NEXT_YEAR
from djtools.fields.helpers import handle_uploaded_file
fro | m djtools.utils.convert import str_to_class
@login_required
def index(request, stype, wtype):
"""Generic waivers form."""
cid = request.user.id
# user student type and waiver type to build table name
table = 'cc_{0}_{1}_waiver'.format(stype, wtype)
# check for student manager record
manager =... |
idaholab/raven | framework/CodeInterfaces/Saphire/SaphireData.py | Python | apache-2.0 | 4,508 | 0.007542 |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | lues
"""
headerNames = []
outData = []
outFile = os.path.abspath(os.path.expanduser(outName))
data = np.loadtxt(outFile, dtype=object, delimiter=',', skiprows=2)
headers = data[0]
for i in range(1, len(data)):
for j in range(1, len(headers)):
name = _deweird(data[i,0]).strip().... | name + '_' + header)
outData.append(float(_deweird(data[i,j])))
return headerNames, outData
def writeCSV(self, output):
"""
Print data into CSV format
@ In, output, str, the name of output file
@ Out, None
"""
outObj = open(output.strip()+".csv", mode='w+b') if not output.e... |
CCI-MOC/GUI-Backend | api/v2/views/account.py | Python | apache-2.0 | 771 | 0 | from django.contrib.auth.models import AnonymousUser
from core.models import Identity
from api.v2.serializers.post import AccountSerializer
from api.v2.views.base import AdminAuthVie | wSet
class AccountViewSet(AdminAuthViewSet):
"""
API endpoint that allows providers to be viewed or edited.
"""
lookup_fields = ("id", "uuid")
queryset = Identity.objects.all()
serializer_class = AccountSerializer
h | ttp_method_names = ['post', 'head', 'options', 'trace']
def get_queryset(self):
"""
Filter providers by current user
"""
user = self.request.user
if (type(user) == AnonymousUser):
return Identity.objects.none()
identities = user.current_identities()
... |
huggingface/pytorch-transformers | src/transformers/models/fsmt/__init__.py | Python | apache-2.0 | 1,962 | 0.002039 | # flake8: noqa
# There's no way to ignore "F401 '...' imported but unused" warnings in this
# module, but to preserve other warnings. So, don't check this module at all.
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | Module class that surfaces all objects but only performs associated imports when the objects are requested.
"""
__file__ = gl | obals()["__file__"]
__path__ = [os.path.dirname(__file__)]
def _get_module(self, module_name: str):
return importlib.import_module("." + module_name, self.__name__)
sys.modules[__name__] = _LazyModule(__name__, _import_structure)
|
listen1/listen1 | listen1/app.py | Python | mit | 555 | 0.003604 | #!/usr/bin/e | nv python
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import options
from settings import settings
from urls import url_patterns
class TornadoBoilerplate(tornado.web.Application):
def __init__(self):
tornado.web.Application.__init__(self, url_patterns, **settin... | ()
if __name__ == "__main__":
main()
|
brownnrl/moneyguru | core/gui/general_ledger_table.py | Python | gpl-3.0 | 2,408 | 0.002076 | # Copyright 2019 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from core.trans import trget
from .column import Column
from ..model.sort i... | le=False, optional=True),
Column('transfer', display=trcol("Transfer")),
Column('debit', display=trcol("Debit")),
Column('credit', display=trcol("Credit")),
| Column('balance', display=trcol("Balance")),
]
ENTRY_ROWCLASS = GeneralLedgerRow
# --- Override
def _fill(self):
accounts = sorted(self.document.accounts, key=ACCOUNT_SORT_KEY)
for account in accounts:
rows = self._get_account_rows(account)
if not rows:
... |
youtube/cobalt | third_party/inspector_protocol/code_generator.py | Python | bsd-3-clause | 25,953 | 0.007976 | #!/usr/bin/env python
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os.path
import sys
import argparse
import collections
import functools
import re
import copy
try:
import json
except ImportErr... | e_name_prefix + file_name)
def to_file_name(config, file_name):
if config.use_snake_file_names:
return to_snake_case(file_name).replace(".cpp", ".cc")
return file_name
# ---- End of utilities exposed to generator ----
def initialize_jinja_env(jinja_dir, cache_dir, config):
# pylint: disable=F0401
sys.... | ja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(module_path),
# Bytecode cache is not concurrency-safe unless pre-cached:
# if pre-cached this is read-only, but writing creates a race condition.
bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
keep_trailing_newline=True, # newl... |
guptaankita/python-novaclient | novaclient/tests/functional/test_volumes_api.py | Python | apache-2.0 | 3,419 | 0 | # 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
# d... | create(1)
# Make sure we can still list servers after using the volume endpoint
self.client.servers.list()
# This cleanup tests volume delete
self.addCleanup(volume.delete)
# Wait for the volume to become | available
for x in six.moves.range(60):
volume = self.client.volumes.get(volume.id)
if volume.status == 'available':
break
elif volume.status == 'error':
self.fail('Volume %s is in error state' % volume.id)
time.sleep(1)
els... |
twilio/twilio-python | tests/integration/api/v2010/account/test_short_code.py | Python | mit | 6,758 | 0.003403 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ShortCodeTestCase(Integra... |
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/ShortCodes/SCXXXXXXXXXXX | XXXXXXXXXXXXXXXXXXXXX.json',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"api_version": "2010-04-01",
"date_created": null,
... |
mbdriscoll/asp-old | tests/em_ahc_test.py | Python | bsd-3-clause | 9,721 | 0.012036 | import unittest
import pylab as pl
import matplotlib as mpl
import itertools
import sys
import math
import timeit
import copy
from em import *
def generate_synthetic_data(N):
np.random.seed(0)
C = np.array([[0., -0.7], [3.5, .7]])
C1 = np.array([[-0.4, 1.7], [0.3, .7]])
Y = np.r_[
np.dot(np.ra... | f.plot_id % 10 <= self.num_subplots):
self.results['_'.join(['ASP v',str(self.plot_id-(100*self.num_subplots+11)),'@',str(self.gmm.D),str(self.gmm.M),str(self.N)])] = (str(self.plot_id), copy.deepcopy(means), copy. | deepcopy(covars), copy.deepcopy(Y))
self.plot_id += 1
#find closest components and merge
if M > 0: #don't merge if there is only one component
gmm_list = []
for c1 in range(0, self.gmm.M):
for c2 in range(c1+1, self.gmm.M):
new_component, dist = self.gmm.comp... |
TribeMedia/synapse | synapse/rest/key/v2/remote_key_resource.py | Python | apache-2.0 | 8,864 | 0.000113 | # Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ... | / 2 < now (%r)",
server_name, key_id,
ts_added_ms, ts_valid_until_ms, time_now_ms
)
if miss:
cache_misses.setdefault(server_name, set()).add | (key_id)
json_results.add(bytes(most_recent_result["key_json"]))
else:
for ts_added, result in results:
json_results.add(bytes(result["key_json"]))
if cache_misses and query_remote_on_cache_miss:
for server_name, key_ids in cache_misse... |
graycarl/iamhhb | manage.py | Python | mit | 812 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "iamhhb.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... | a
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variabl | e? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
djoproject/pyshell | pyshell/register/profile/command.py | Python | gpl-3.0 | 5,109 | 0 | #!/usr/bin/env python -t
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Jonathan Delvaux <pyshell@djoproject.net>
# 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... | Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pyshell.command.command import MultiCommand
from pyshell.register.profile.default import DefaultProfile
from pyshell.register.profile. | exception import RegisterException
from pyshell.utils.raises import raiseIfInvalidKeyList
from pyshell.utils.raises import raiseIfNotInstance
class CommandLoaderProfile(DefaultProfile):
def __init__(self, root_profile):
# TODO (issue #90) remove unload_priority/load_priority
# Why load priority a... |
ton212/TW-Interaction-Pull | main.py | Python | mit | 2,254 | 0.005768 | """
TW Interaction Puller
by @tonsai
License : MIT License
"""
from tweepy.streaming import StreamListener
from tweepy import OAuthHand | ler
from tweepy import Stream
from co | nfig import config, pushbullet_token
from pushbullet import PushBullet
import json
class StdOutListener(StreamListener):
""" A listener handles tweets are the received from the stream.
This is a basic listener that just prints received tweets to stdout.
"""
def on_status(self, status):
""" Fil... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/file/cmd/delete/errors.py | Python | unlicense | 1,652 | 0.00908 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: errors.py
import mcl.status
ERR_SUCCESS = mcl.status.MCL_SUCCESS
ERR_INVALID_PARAM = mcl.status.framework.ERR_START
ERR_GET_FULL_PATH_FAILED = mcl.st... | _FAILED = mcl.status.framework.ERR_START + 7
ERR_DEL_PATH_UNC_AFTER_REBOOT = mcl.status.framework.ERR_START + 8
ERR_DONE_MAX_ENTRIES = mcl.status.framework.ERR_START + 9
ERR_NO_MAX_SPECIFIED = mcl.status.framework.ERR_START + 10
ERR_SEND_FAILED = mcl.status.framework.ERR_START + 11
errorStrings = {ERR_INVALID_PARAM: 'I... | ctory for matching files',
ERR_MARSHAL_FAILED: 'Marshaling of deletion data failed',
ERR_FILE_IS_A_DIR: 'Given file is a directory -- refusing deletion',
ERR_DELETE_FAILED: 'Deletion failed',
ERR_API_FAILED: 'Failed to get delete api',
ERR_STAT_FAILED: 'Unable to check file',
ERR_DEL_PATH_UNC_AFTER_RE... |
0vercl0k/rp | src/third_party/capstone/bindings/python/capstone/mips_const.py | Python | mit | 17,669 | 0 | # For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT [mips_const.py]
MIPS_OP_INVALID = 0
MIPS_OP_REG = 1
MIPS_OP_IMM = 2
MIPS_OP_MEM = 3
MIPS_REG_INVALID = 0
MIPS_REG_PC = 1
MIPS_REG_0 = 2
MIPS_REG_1 = 3
MIPS_REG_2 = 4
MIPS_REG_3 = 5
MIPS_REG_4 = 6
MIPS_REG_5 = 7
MIPS_REG_6 = 8
MIPS_REG_7 = 9
MIPS_REG_8 = 10
MIPS_... | = 177
MIPS_INS_DBITSWAP = 178
MIPS_INS_DCLO = 179
MIPS_INS_DCLZ = 180
MIPS_INS_DDIV = 181
MIPS_INS_DDIVU = 182
MIPS_INS_DERET = 183
MIPS_INS_DEXT = 184
MIPS_INS_DEXTM = 185
MIPS_INS_DEXTU = 186
MIPS_INS_DI = 187
MIPS_INS_DINS = 188
MIPS_INS_DINSM = 189
MIPS_INS_DINSU = 190
MIPS_INS_DIV = 191
MIPS_INS_DIVU = 192
MIPS_I... |
MIPS_INS_DMFC1 = 197
MIPS_INS_DMFC2 = 198
MIPS_INS_DMOD = 199
MIPS_INS_DMODU = 200
MIPS_INS_DMTC0 = 201
MIPS_INS_DMTC1 = 202
MIPS_INS_DMTC2 = 203
MIPS_INS_DMUH = 204
MIPS_INS_DMUHU = 205
MIPS_INS_DMUL = 206
MIPS_INS_DMULT = 207
MIPS_INS_DMULTU = 208
MIPS_INS_DMULU = 209
MIPS_INS_DOTP_S = 210
MIPS_INS_DOTP_U = 211
MIPS... |
feikname/Scripts | python/openspades_wiki_tools.py | Python | mit | 3,906 | 0.001024 | #
# openspades_wiki_tools.py - v0.0.0 (not a release!)
# MIT License
#
from __future__ import print_function
import os
import platform
import sys
"""
This function gathers all settings present in the OpenSpades user resource
directory configuration file (SPConfig.cfg) and generates a markdown string to
be used in th... | lse:
cfg_md = " * {0}".format(cfg)
print(cfg_md)
def get_spconfig_path():
# Windows Location: %APPDATA%\OpenSpades\Resources
# Linux Location: $XDG_DATA_HOME/openspades/Resources
# Darwin Location: ~/Library/Application Support/OpenSpades/Resources
if platform.system() == "Window... | NotImplementedError("Windows not implemented yet")
appdata = os.environ.get("APPDATA")
if appdata == None:
raise RuntimeError("%APPDATA% not defined! (wtf?)")
cfg_file = os.path.join(appdata, "OpenSpades", "Resources",
"SPConfig.cfg")
return... |
flavoso/gerencex | gerencex/core/tests/test_hoursbalance_model.py | Python | gpl-3.0 | 5,457 | 0.002201 | import datetime
import pytz
from django.utils import timezone
from django.contrib.auth.models import User
from django.test import TestCase
from gerencex.core.models import HoursBalance, Timing, Office
from gerencex.core.time_calculations import DateData
class HoursBalanceModelTest(TestCase):
@classmethod
de... | time.timedelta(hours=-2).total_seconds()))
# Change in first credit or debit must change the second balance (see the
# next_balance_handler function at signals.py)
r1.credit = datetime.timedelta(hours=7).seconds
r1.save()
r2 = HoursBalance.objects.get(pk=2)
self.assertE... | nt(datetime.timedelta(hours=-1).total_seconds()))
class CreditTriggerTest(TestCase):
"""
The user credit is always registered at HourBalance via signal, when a checkout occurs.
See the 'credit_calculation' function, at signals.py
"""
@classmethod
def setUpTestData(cls):
Office.objects.... |
philipperemy/tensorflow-phased-lstm | helpers/__init__.py | Python | mit | 35 | 0.028571 | from .file_ | logger import FileLog | ger |
artas360/pythran | pythran/analyses/cfg.py | Python | bsd-3-clause | 4,991 | 0 | """ Computes the Control Flow Graph of a function. """
from pythran.passmanager import FunctionAnalysis
import ast
import networkx as nx
class CFG(FunctionAnalysis):
"""
Computes the Control Flow Graph of a function.
The processing of a node yields a pair containing
* the OUT nodes, to be linked wi... | ler's
this equation is not has good has it could be...
but we need type information to be more accurate
"""
currs = (node,)
raises = ()
for handler in node.handlers:
self.result.add_node(handler)
for n in node.body:
self.result.add_node(n)
... | lt.add_edge(curr, n)
currs, nraises = self.visit(n)
for nraise in nraises:
if type(nraise) is ast.Raise:
for handler in node.handlers:
self.result.add_edge(nraise, handler)
else:
raises += (nraise,)
... |
gmimano/commcaretest | corehq/apps/api/serializers.py | Python | bsd-3-clause | 4,533 | 0.00375 |
# Standard library imports
from io import BytesIO
# Django & Tastypie imports
from django.utils.encoding import force_unicode
from tastypie.bundle import Bundle
from tastypie.serializers import Serializer, get_type_string
# External imports
import defusedxml.lxml as lxml
from lxml.etree import Element, tostring, Lxm... | etree = super(CustomXMLSerializer, self).to_etree(data, options, name, depth)
id = etree.find('id')
if id is not None:
etree.attrib['id'] = id.findtext('.')
etree.remove(id)
return etree
class XFormInstanceSerializer(Serializer):
def to_xml(self, data, options=No... | data, options=options)
|
danceasarxx/pyfunk | pyfunk/monads/maybe.py | Python | gpl-3.0 | 1,877 | 0.000533 | import functools
import pyfunk.combinators as comb
from pyfunk.monads import Monad
@comb.curry
def or_else(x, mb):
"""
Extract a Maybe's value providing a default if Nothing
@sig or_else :: b -> Maybe a -> b
"""
return x if mb.nothing() else mb._value
@comb.curry
def ftry(fn):
"""
Wraps ... | wraps(fn)
def safe(*args, **kwargs):
try:
return Maybe.of(fn(*args, **kwargs))
except:
return Maybe.of(None)
return safe
@comb.curry
def cata(f, g, mb):
"""
Calls f if nothing exists and g if one does.
@sig cata :: Maybe e => (_ -> _) -> (a -> b) -> m a -> b |
"""
return f() if mb.nothing() else g(mb._value)
@comb.curry
def maybify(nullify, f):
"""
Creates a function that returns Maybe. Also accepts a Nonifier
that checks that transforms falsy value to None. One can use
misc.F if there is no need to nonify.
@sig maybify :: (a -> Bool) -> (a -> ... |
ludi1001/IonMedicationSystem | mongobacked/mongobacked/wsgi.py | Python | gpl-2.0 | 397 | 0.002519 | """
WSGI config for mongobacked project.
It exposes the WSGI callable as a modu | le-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mongobacke | d.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
wger-project/wger | wger/nutrition/views/bmi.py | Python | agpl-3.0 | 7,575 | 0 | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager 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 ... | ttp import HttpResponse
from django.shortcuts i | mport render
# wger
from wger.nutrition.forms import BmiForm
from wger.utils import helpers
logger = logging.getLogger(__name__)
"""
BMI views
"""
@login_required
def view(request):
"""
The BMI calculator detail page
"""
context = {}
form_data = {
'height': request.user.userprofile.hei... |
awlange/brainsparks | src/sandbox/cost.py | Python | mit | 1,017 | 0 | import src.sandbox.linalg as linalg
import numpy as np
class Cost(object):
def __init__(self):
pass
@staticmethod
def get(name):
if name == "quadratic":
return Cost.quadratic
if name == "np_quadratic":
return Cost.np_quadratic
return None
@sta... | ic
if name == "np_quadratic":
return Cost.np_d_quadratic
return None
@staticmethod
def quadratic(y, a):
"""
Cos | t for a single training data
"""
return linalg.vsqdistw(a, y)
@staticmethod
def d_quadratic(y, a):
"""
Cost derivative for a single training data
"""
return linalg.vminw(a, y)
@staticmethod
def np_quadratic(y, a):
return np.mean(np.square(np.lina... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/utilities/iterables.py | Python | agpl-3.0 | 34,793 | 0.001782 | from sympy.core import Basic, C
from sympy.core.compatibility import is_sequence, iterable #logically, they belong here
import random
def flatten(iterable, levels=None, cls=None):
"""
Recursively denest iterable containers.
>>> from sympy.utilities.iterables import flatten
>>> flatten([1, 2, 3])
... | if isinstance(node, Basic):
for arg in node.args:
for subtree in postorder_traversal(arg):
| yield subtree
elif iterable(node):
for item in node:
for subtree in postorder_traversal(item):
yield subtree
yield node
class preorder_traversal(object):
"""
Do a pre-order traversal of a tree.
This iterator recursively yields nodes that it has visited in a p... |
whiskeylover/idreamoftoast | toast/config.py | Python | apache-2.0 | 1,878 | 0.009052 | """ config.py """
import os
from flask import Flask
from peewee import MySQLDatabase, SqliteDatabase
#-------------------------------------------------------------------------------
# Environment
#-------------------------------------------------------------------------------
DB = 'idreamoftoast'
ENV = os.... | #-------------------------------------------------------------------------------
# Config Methods
#------------------------------- | ------------------------------------------------
def get_app():
app = None
# If env is set, we are in production!
if ENV:
app = Flask(__name__)
import logging
file_handler = logging.FileHandler(LOG_PATH + 'flask.log')
file_handler.setLevel(logging.WARNING)
file_handl... |
xiaomogui/lulu | lulu/lulu/python/linkAMQ/ConnectAMQ.py | Python | apache-2.0 | 4,337 | 0.005063 | __author__ = 'Administrator'
#coding=utf-8
import threading
from stompy.simple import Client
# 单例模式
class ConnectAMQSinleton(object):
__instance = None
__lock = threading.Lock() # used to synchronize code
__stompClient = None
# 默认订阅amf_pcap_dataamf_pcap_data队列
__subscribe = '/queue/amf_pcap_data'... | return ConnectAMQSinleton.__subscribe
# set方法
def setSubscribe(self, subscribe):
ConnectAMQSinleton.__subscribe = subscribe
class ConnectAMQ:
__stompClient = None
# 默认订阅amf_pcap_dataamf_pcap_data队列
__subscribe = '/queue/amf_pcap_data'
def __init__(self):
'init'
def ... | simple方式连接JMS服务器
# 指定hostname和port(tips:ActiveMQ支持多种协议连接stomp协议的默认端口为61613,这里不要写为61616)
ConnectAMQ.__stompClient = Client(hostname, port)
#stomp = Client()#如果是ActiveMQ和ActiveMQ客户端(本程序)在同一台机器可使用默认值:hostname="localhost",port=61613
# 连接服务器
ConnectAMQ.__stompClient.connect()
de... |
robalar/A2_Project | solver/__init__.py | Python | mit | 117 | 0.008547 | from solver.core import *
from solver.functions im | port *
from solver.calculus | import *
from solver.equations import * |
adrianolinux/lamp | lamp.py | Python | gpl-2.0 | 3,207 | 0.006548 | """
LAMP
"""
import numpy as np
tol = 1.e-6 # zero tolerance
def pdist(x):
"""
Pairwise distance between pairs of objects
TODO: find a fast function
"""
n, d = x.shape
dist = np.zeros((n, n))
for i in range(n):
for j in range(n):
dist[i][j] = np.linalg.norm(x[i] - x... | p.ndarray) and (type(xs) is np.ndarray) and (type(ys) is np.ndarray), \
"*** ERROR (Force-Scheme): project input must be numpy.array type."
ninst, dim = x.shape # number os instances, data di | mension
k, a = xs.shape # number os sample instances
p = ys.shape[1] # visual space dimension
assert dim == a, "*** LAMP Error: x and xs dimensions must be egual."
Y = np.zeros((ninst, p))
for pt in range(ninst):
# computes alphas
alpha = np.zeros(k)
for... |
iosonofabio/singlet | singlet/counts_table/counts_table_sparse.py | Python | mit | 10,070 | 0.000894 | # vim: fdm=indent
# author: Fabio Zanini
# date: 09/08/17
# content: Sparse table of gene counts
# Modules
import numpy as np
import pandas as pd
# Classes / functions
class CountsTableSparse(pd.SparseDataFrame):
'''Sparse table of gene expression counts
- Rows are features, e.g. ge | nes.
- Columns are samples.
'''
_metadata = [
'name',
'_spikeins',
'_otherfeatures',
'_normalized',
'pseudocount',
'dataset',
]
_spikeins = ()
_otherfeatures = ()
_normalized = False
pseudocount = 0.1
d... | '''Instantiate a CountsTable from its name in the config file.
Args:
tablename (string): name of the counts table in the config file.
Returns:
CountsTable: the counts table.
'''
from ..config import config
from ..io import parse_counts_table_sparse
... |
PyPSA/PyPSA | pypsa/io.py | Python | mit | 43,000 | 0.00707 |
## Copyright 2015-2021 PyPSA Developers
## You can find the list of PyPSA Developers at
## https://pypsa.readthedocs.io/en/latest/developers.html
## PyPSA is released under the open source MIT License, see
## https://github.com/PyPSA/PyPSA/blob/master/LICENSE.txt
"""Functions for importing and exporting data.
"""
... | der_name)
def get_attributes(self):
fn = os.path.join(self.csv_folder_name, "netw | ork.csv")
if not os.path.isfile(fn): return None
return dict(pd.read_csv(fn, encoding=self.encoding).iloc[0])
def get_snapshots(self):
fn = os.path.join(self.csv_folder_name, "snapshots.csv")
if not os.path.isfile(fn): return None
df = pd.read_csv(fn, index_col=0, encoding=s... |
fretboardfreak/space | tests/lib/cmdline/commands/test_quit.py | Python | apache-2.0 | 839 | 0 | # Copyright 2015 Curtis Sand
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma | y 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 COND... | express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import lib.cmdline.commands as commands
from .test_base import BaseCommandTest
class QuitTest(BaseCommandTest):
def setUp(self):
super().setUp()
self.command_class = comman... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/pylint/test/input/func_tokenize_error.py | Python | agpl-3.0 | 173 | 0.00578 | "" | "A module that is accepted by Python but rejected by tokenize.
The problem is the trailing line continuation at the end of the line,
which produces a TokenError. | """
""\
|
gamechanger/hydra | copy_stragglers.py | Python | bsd-2-clause | 4,159 | 0.003126 | #! /usr/bin/env python
import argparse
from compare_collections import MismatchLogger
from faster_ordered_dict import FasterOrderedDict
import gevent
import gevent.monkey
from gevent.pool import Pool
from pymongo.read_preferences import ReadPreference
import time
import utils
log = utils.get_logger(__name__)
POOL_SIZ... | py' | )
args = parser.parse_args()
# connect to source and destination
source = utils.parse_mongo_url(args.source)
source_client = utils.mongo_connect(source,
ensure_direct=True,
maxPoolSize=POOL_SIZE,
... |
dowlingw/pelican-attachments | __init__.py | Python | gpl-3.0 | 1,859 | 0.009145 | import os
import shutil
import six
from logging import warning, info
from pelican import signals
from pelican.contents import Static
from pelican.utils import copy, process_translations, mkdir_p
METADATA_KEY = 'attachments'
def get_generators(generators):
return AttachmentGenerator
def register():
signal... | ings = settings
self.siteurl = settings.get('SITEURL')
def gener | ate_context(self):
for article in self.context['articles']:
if METADATA_KEY in article.metadata:
files = article.metadata[METADATA_KEY].split(', ')
for file in files:
self._emitfile(article,file)
def _emitfile(self, article, filename):
... |
goshow-jp/Kraken | Python/kraken/ui/HAppkit_Editors/editor_widgets/color_editor.py | Python | bsd-3-clause | 2,883 | 0.005203 | from PySide import QtGui
from ..fe import FE
from ..widget_factory import EditorFactory
from ..base_editor import BaseValueEditor
from ..core.undo_redo_manager import UndoRedoManager
class ColorEditor(BaseValueEditor):
def __init__(self, valueController, parent=None):
super(ColorEditor, self).__init__(v... | rent=parent)
| hbox = QtGui.QHBoxLayout()
self._editors = []
self._qgraphcsScene = QtGui.QGraphicsScene(self)
self._qgraphcsView = QtGui.QGraphicsView(self)
self._qgraphcsView.setScene(self._qgraphcsScene)
self._qgraphcsView.setFixedSize(100, 20)
self._qgraphcsView.setSizePolicy(QtGu... |
simgunz/timekpr | src/original/gui/client/timekpr-client.py | Python | gpl-3.0 | 9,751 | 0.004 | #!/usr/bin/env python
import gtk
import gobject
import os
from time import strftime, sleep
import datetime
from timekprpam import *
from timekprcommon import *
import locale
import gettext
import sys
APP_NAME = "timekpr"
#Translation stuff
#Get the local directory
local_path = '/usr/share/locale'
locale.setlocale(l... | self.pnotifier()
'''
Run every checkInterval seconds, check if user has run out of time
'''
def checkLimits(self):
# Re-read settings in case they changed
self.limits, sel | f.bfrom, self.bto = readusersettings(self.username, self.conffile)
index = int(strftime("%w"))
# If the user is not a restricted user, set the tray icon to green padlock
if not isrestricteduser(self.username, self.limits[index]):
self.tray.set_from_file(self.green)
retur... |
zubie7a/Algorithms | CodeSignal/Arcade/Intro/Level_03/02_Common_Character_Count.py | Python | mit | 637 | 0.00157 | # https://app.codesignal.com/arcade/intro/level-3/JKKuHJknZNj4YGL32
from collections impor | t Counter
def commonCharacterCount(s1, s2):
# When counter is initialized with a Str | ing, since its a
# sequence it will store counts for each of its characters.
c1 = Counter(s1)
c2 = Counter(s2)
common = 0
# Given two strings, find the amount of common characters
# between both. This is the min count of a given character
# ocurring at both. If it doesn't occur, then value i... |
PaulWay/insights-core | insights/tests/test_extractors.py | Python | apache-2.0 | 3,827 | 0.001307 | import os
import unittest
import tempfile
import subprocess
import shlex
import gzip
import zipfile
from insights.core import archives
from insights.core.specs import SpecMapper
from . import insights_heartbeat
class TestTarExtractor(unittest.TestCase):
def test_from_buffer_with_directory(self):
arc_path ... | f.assertIn(tar_ex.content_type, archives.TarEx | tractor.TAR_FLAGS)
subprocess.call(shlex.split("rm -rf %s" % arc_path))
def test__assert_type_gzip_no_tar(self):
tmp_dir = tempfile.mkdtemp()
archive_path = os.path.join(tmp_dir, "file.log.gz")
with gzip.open(archive_path, 'wb') as f:
f.write("testing contents")
... |
fulfilio/nereid-webshop-elastic-search | website.py | Python | bsd-3-clause | 2,063 | 0 | # -*- coding: utf-8 -*-
'''
website
'''
from trytond.pool import Pool, PoolMeta
from nereid import request, route, render_template
from pagination import ElasticPagination
__metaclass__ = PoolMeta
__all__ = ['Website']
class Website:
"Nereid Website"
__name__ = 'nereid.website'
@classmethod
de... | if not config.get_es_connection(timeout=5):
# NO ES fallback to default search
return super(Website, cls).quick_search()
page = request.args.get('page', 1, type=int)
phrase = request.ar | gs.get('q', '')
logger = Pool().get('elasticsearch.configuration').get_logger()
search_obj = Product._quick_search_es(phrase)
products = ElasticPagination(
Product.__name__, search_obj, page, Product.per_page
)
if products:
logger.info(
... |
ptcrypto/p2pool-adaptive | p2pool/bitcoin/networks/titcoin.py | Python | gpl-3.0 | 1,188 | 0.004209 | import os
import platform
from twisted.internet import defer
from .. import data, helper
from p2pool.util import pack
P2P_PREFIX = '25174c22'.decode('hex')
P2P_PORT = 8698
ADDRESS_VERSION = 0
RPC_PORT = 8697
RPC_CHECK = defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
(yield helper.check_genesi... | 60 # s
SYMBOL = 'TIT'
CONF_FILE_FUNC = lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'titcoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/titcoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.titcoin'), 'titcoin.conf')
BLOCK_EXPLORER_URL_PREFI... | t/tx/'
SANE_TARGET_RANGE = (2**256//2**32//1000000 - 1, 2**256//2**32 - 1)
DUMB_SCRYPT_DIFF = 1
DUST_THRESHOLD = 0.001e8
|
jleni/QRL | src/qrl/core/ChainManager.py | Python | mit | 23,847 | 0.003103 | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import threading
from typing import Optional, Tuple
from pyqrllib.pyqrllib import bin2hstr
from pyqryptonight.pyqryptonight import StringToUInt256, UInt256ToString
fr... | ce(self, blockheader: BlockHeader, enable_logging=True):
with self.lock:
parent_metadata = self.get_block_metadata(blockheader.prev_headerhash)
parent_block = self._state.get_block(blockheader.prev_headerhash)
measurement = self.get_measurement(blockheader.timestamp, blockhe... | = DifficultyTracker.get(
measurement=measurement,
parent_difficulty=parent_metadata.block_difficulty)
if enable_logging:
logger.debug('-----------------START--------------------')
logger.debug('Validate #%s', blockheader.block_n... |
saisankargochhayat/algo_quest | leetcode/64.MinSumPath/soln.py | Python | apache-2.0 | 951 | 0.025237 | class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
row = len(grid)
col = len(grid[0])
dp = [[0]*col for i in range(row)]
minPath = 0
return self.findPath(grid, row-1, col-1, dp)
def findPath(self, grid, i, j, dp):
#print(i,j, min... | grid[i][j] + self.findPath(grid, i,max(0,j-1), dp)
return dp[i][j] #element to left
elif j == 0:
return self.findPath(grid, max(0,i-1),j, dp)+grid[i][j] #element on top
el | se:
a = self.findPath(grid, i,max(0,j-1), dp)+grid[i][j] #element to left
b = self.findPath(grid, max(0,i-1),j, dp)+grid[i][j] #element on top
dp[i][j] = min(a,b)
return dp[i][j]
|
enthought/depsolver | depsolver/solver/tests/scenarios/rules_generator.py | Python | bsd-3-clause | 5,572 | 0.00341 | import os.path as op
import tempita
from depsolver._package_utils \
import \
parse_package_full_name
from depsolver.compat \
import \
OrderedDict
from depsolver.package \
import \
PackageInfo
from depsolver.requirement \
import \
Requirement
from depsolver.solver.rules_... | ction printRules(Request $request)
{
$this->jobs = $request->getJobs();
$this->se | tupInstalledMap();
$this->decisions = new Decisions($this->pool);
$this->rules = $this->ruleSetGenerator->getRulesFor($this->jobs, $this->installedMap);
$this->watchGraph = new RuleWatchGraph;
foreach ($this->rules as $rule) {
printf("%s\\n", $rule);
}
}
}
$po... |
adazey/Muzez | libs/nltk/parse/__init__.py | Python | gpl-3.0 | 4,269 | 0.002342 | # Natural Language Toolkit: Parsers
#
# Copyright (C) 2001-2016 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# Edward Loper <edloper@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
#
"""
NLTK Parsers
Classes and interfaces for producing tree structures... | tiveDependencyParser,
ProbabilisticProjectiveDependencyParser)
from nltk.parse.nonprojectivedependencyparser import (NonprojectiveDependencyParser,
NaiveBayesDependencyScorer,
| ProbabilisticNonprojectiveParser)
from nltk.parse.malt import MaltParser
from nltk.parse.evaluate import DependencyEvaluator
from nltk.parse.transitionparser import TransitionParser
from nltk.parse.bllip import BllipParser
|
gunan/tensorflow | tensorflow/python/ops/control_flow_v2_func_graphs.py | Python | apache-2.0 | 2,205 | 0.004082 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | _init__(*args, **kwargs)
if ops.executing_eagerly_outside_functions():
func_graph.override_func_graph_name_scope(
self, self.outer_graph.get_name_scope())
class WhileCondFuncGraph(func_graph.FuncGraph):
"""FuncGraph for the condition of tf.while_loop().
This is used to distinguish while condi... | rgs)
if ops.executing_eagerly_outside_functions():
func_graph.override_func_graph_name_scope(
self, self.outer_graph.get_name_scope())
class WhileBodyFuncGraph(func_graph.FuncGraph):
"""FuncGraph for the body of tf.while_loop().
This is used to distinguish while bodies from other functions.
... |
lkesteloot/clock | frame.py | Python | apache-2.0 | 4,043 | 0.000989 |
# Copyright 2015 Lawrence Kesteloot
#
# 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 ag... | les, from the existing data.
minX = DPI*100
minY = DPI*100
maxX = -DPI*100
maxY = -DPI*100
floorY = -DPI*100
holes = []
for piece in data["pieces"]:
cx = piece["cx"]
cy = piece["cy"]
minX = min(minX, cx)
minY = min(minY, cy)
maxX = max(maxX, cx)
... | cy + v.y)
for hole in holes:
if hole["cx"] == cx and hole["cy"] == cy:
break
else:
holes.append({
"cx": cx,
"cy": cy,
"r": TIGHT_LARGE_BOLT_RADIUS,
})
# Add hole in lower-left since there are no axles... |
kartoza/jakarta-flood-maps | django_project/core/settings/dev.py | Python | bsd-2-clause | 3,007 | 0 | from .project import * # noqa
# Set debug to True for development
DEBUG = True
TEMPLATE_DEBUG = DEBUG
LOGGING_OUTPUT_ENABLED = DEBUG
LOGGING_LOG_SQL = DEBUG
PIPELINE_ENABLED = False
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Disable caching while in development
CACHES = {
'default': {
... | s)d '
'%(thread)d %(message)s')
},
'simple': {
'format': (
'%(name)s %(levelname)s %(filename)s L%(linen | o)s: '
'%(message)s')
},
},
'handlers': {
# console output
'console': {
'class': 'logging.StreamHandler',
'formatter': 'simple',
'level': 'DEBUG',
},
# 'logfile': {
# 'class': 'logging.FileHandler',
#... |
JshWright/home-assistant | homeassistant/components/sensor/cpuspeed.py | Python | apache-2.0 | 2,256 | 0 | """
Support for displaying the current CPU speed.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.cpuspeed/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CO... | e = config.get(CONF_NAME)
add_devices([CpuSpeedSensor(name)])
class CpuSpeedSensor(Entity):
"""Representation of a CPU sensor."""
def __init__(self, name):
"""Initialize the sensor."""
self._name = name
self._state = None
self._unit_of_measurement = 'GHz'
self.upd... |
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def device_state_attributes(self):
"""Return the state attributes."""
... |
cajone/pychess | lib/pychess/widgets/analyzegameDialog.py | Python | gpl-3.0 | 7,913 | 0.003033 | from __future__ import absolute_import
import time
import threading
from gi.repository import Gtk
from . import gamewidget
from pychess.Utils.const import HINT, SPY, BLACK, WHITE
from pychess.System import conf, fident
from pychess.System import uistuff
from pychess.System.idle_add import idle_add
from pychess.System... |
# ParsingErrors may happen when parsing "old" lines from
# analyzing engines, which haven't yet noticed their new tasks
log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" %
... | try:
pv = listToMoves(gamemodel.boards[ply - 1], oldmoves, validate=True)
gamemodel.add_variation(gamemodel.boards[ply - 1], pv, comment="Better is", score=score_str)
except ParsingError as e:
# ParsingErrors ... |
Neuvoo/legacy-portage | pym/portage/tests/ebuild/test_array_fromfile_eof.py | Python | gpl-2.0 | 1,023 | 0.028348 | # Copyright 2009 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
import array
import tempfile
from portage import | _unicode_decode
from portage import _unicode_encode
from portage.tests import TestCase
class ArrayFromfileEofTestCase(TestCase):
def testArrayFromfileEof(self):
# This tests if the following python issue is fixed
# in the currently running version of python:
# http://bugs.python.org/issue5334
input_data =... | put_data,
encoding='utf_8', errors='strict')
f = tempfile.TemporaryFile()
f.write(input_bytes)
f.seek(0)
data = []
eof = False
while not eof:
a = array.array('B')
try:
a.fromfile(f, len(input_bytes) + 1)
except (EOFError, IOError):
# python-3.0 lost data here
eof = True
if not a... |
chrishales/plot3d | task_plot3d.py | Python | bsd-3-clause | 18,140 | 0.016207 | from taskinit import *
from mpl_toolkits.mplot3d import axes3d, Axes3D
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.cm as cm
import numpy as np
from pylab import ion,ioff
# plot3d is released under a BSD 3-Clause License
# See LICENSE for details
# ... | ts all spw's in the
# scan summary, rather than the 1 selected | above. meh
scan_summary = ms.getscansummary()
scan_list = []
for scan in scan_summary:
if scan_summary[scan]['0']['FieldId'] == fid:
scan_list.append(int(scan))
scan_list.sort()
# get integration time in minutes; assume it doesn't change in
# any way throughout the... |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/rte.py | Python | gpl-3.0 | 5,026 | 0.028884 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(s... | ne(mg.get('url'))
if mg_rte_server and mg_url:
hds_url = url_or_none(mg_rte_server + mg_url)
if hds_url:
formats.extend(self._extract_f4m_formats(
hds_url, item_id, f4m_id='hds', fatal=False))
self._sort_formats(formats)
info_dict['formats'] = formats
return info_dict
class RteIE(RteBase... | ayer/[^/]{2,3}/show/[^/]+/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.rte.ie/player/ie/show/iwitness-862/10478715/',
'md5': '4a76eb3396d98f697e6e8110563d2604',
'info_dict': {
'id': '10478715',
'ext': 'mp4',
'title': 'iWitness',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'The spirit of ... |
kristofclaes/vigenere | src/vigenere/__init__.py | Python | mit | 262 | 0 | __v | ersion__ = '0.0.1'
__title__ = 'vigenere'
__description__ = 'Enciphe | ring and deciphering using the Vigenère algorithm.'
__uri__ = 'https://github.com/kristofclaes/vigenere'
__author__ = 'Kristof Claes'
__email__ = 'kristof.c@gmail.com'
__license__ = 'MIT'
|
rhyolight/nupic | tests/unit/nupic/algorithms/spatial_pooler_py_api_test.py | Python | agpl-3.0 | 9,840 | 0.009451 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | inParam = 1234
self.sp.setUpdatePeriod(inParam)
outParam = self.sp.getUpdatePeriod()
self.assertEqual(inParam, outParam)
def testGetPotentialRadius(self):
inParam = 56
self.sp.setPotentialRadius(inParam)
outParam = self.sp.getPotentialRadius()
self.assertEqu | al(inParam, outParam)
def testGetPotentialPct(self):
inParam = 0.4
self.sp.setPotentialPct(inParam)
outParam = self.sp.getPotentialPct()
self.assertAlmostEqual(inParam, outParam)
def testGetGlobalInhibition(self):
inParam = True
self.sp.setGlobalInhibition(inParam)
outParam = self.sp... |
KMUX-Project/KMUX | kmux/modules/root/__init__.py | Python | gpl-2.0 | 837 | 0 | '''
KMUX - a free and open source small business server.
Copyright (C) 2015, Julian Thomé <julian.thome.de@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, ... | NTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should | have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
'''
from .action.root import Root
|
joebos/django-allauth | allauth/socialaccount/providers/schedulepictures_oauth2/provider.py | Python | mit | 2,134 | 0.001874 | from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
from allauth.socialaccount import app_settings
class SchedulePicturesOAuth2Account(ProviderAccount):
def get_profile_url(self):
... | fault_scope(self):
scope = ["read", "write"]
#if app_settings.QUERY_EMAIL:
# scope.append('r_emailaddress')
return scope
def extract_common_fields(self, data):
return dict(username=data.get("username"),
email=data.get('email'),
#fi... | )
|
orbitvu/django-mama-cas | mama_cas/models.py | Python | bsd-3-clause | 13,586 | 0.000957 | from __future__ import unicode_literals
from datetime import timedelta
import logging
import os
import re
import time
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils.crypto import get_random_string
from django.utils.encoding import python_2_unicode_compat... | 0-9]{10,}-[a-zA-Z0-9]{%d}$" % TICKET_RAND_LEN)
ticket = models.CharField(_('ticket'), max_length=255, unique=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
on_delete=models.CASCADE)
expires = models.DateTime | Field(_('expires'))
consumed = models.DateTimeField(_('consumed'), null=True)
objects = TicketManager()
class Meta:
abstract = True
def __str__(self):
return self.ticket
@property
def name(self):
return self._meta.verbose_name
def consume(self):
"""
... |
adaptive-learning/flocs-web | tasks/models/instruction.py | Python | gpl-3.0 | 328 | 0 | from django.db import models
from flocs import entities
from flocsweb.mixins import Import | ExportMixin
class Instruction(models.Model, ImportExportMixin):
entity_class = entities.Instruction
instruction_id = models.CharField(max_length=256, primary_key=True)
def __str__(se | lf):
return self.instruction_id
|
caleblogan/twitter-scheduler | twitterscheduler/signals.py | Python | mit | 371 | 0 | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.signals import request_finished
from django.cont | rib.auth.models import User
from .models import Profile
@r | eceiver(post_save, sender=User)
def create_profile_receiver(sender, **kwargs):
if kwargs['created']:
Profile.objects.create(user=kwargs['instance'])
|
nsmoooose/csp | csp/tools/layout2/scripts/ui/controls/XmlPropertiesPaneItem.py | Python | gpl-2.0 | 11,459 | 0.040841 | import weakref
import wx
from AutoFitTextCtrl import AutoFitTextCtrl
from ...data import XmlNode
from ..commands.ModifyXmlAction import ModifyXmlDataAction
from ..commands.ModifyXmlAction import ModifyXmlAttributeAction
class ItemUpdater(object):
def __init__(self, propertiesPane, *args, **kwargs):
self.... | xt(self):
return ''
def CreateModifyWindow(self, parent, node):
return ModifyWindowData( parent, node, self.GetItemText(), self.GetActualImageName( self.GetItemImage() ) )
class ModifyWindowData(wx.TextCtrl):
def __init__(self, parent, node, nodeName, imageName):
wx.TextCtrl.__init__(self, parent, ... |
self.imageName = imageName
def GetAction(self):
return ModifyXmlDataAction( self.nodeName, self.imageName, self.node, self.GetValue() )
class ItemUpdaterText(ItemUpdaterData):
NodeClass = XmlNode.XmlNodeText
def GetItemImage(self):
return 'text'
def GetItemText(self):
return 'Text'
... |
patpatpatpatpat/stormpath-django | django_stormpath/urls.py | Python | apache-2.0 | 2,179 | 0.005966 | from django.conf.urls import url
from django.conf import settings
from django_stormpath import views
urlpatterns = [
url(r'^login/$', views.stormpath_id_site_login, name='stormpath_id_site_login'),
url(r'^logout/$', views.stormpath_id_site_logout, name='stormpath_id_site_logout'),
url(r'^register/$', vie... | ath_callback,
name='sto | rmpath_linkedin_login_callback'),
url(r'^social-login/(?P<provider>linkedin)/', views.stormpath_social_login,
name='stormpath_linkedin_social_login'),
]
if django.VERSION[:2] < (1, 8):
from django.conf.urls import patterns
urlpatterns = patterns('django_stormpath.views', *urlpattern... |
sigmunau/nav | python/nav/web/seeddb/utils/edit.py | Python | gpl-2.0 | 6,406 | 0.000156 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2011 UNINETT AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 2 as published by the Free
# Software Foundation.
#
# This program is... | s by creating instances of
NetboxCategories
:param nav.models.manage.NetboxGroup group: A netboxgroup
:param list[str] netbox_ids: a result from a request.POST.getlist that
| should contain netbox id's as strings
"""
netboxids = [int(x) for x in netbox_ids]
# Delete existing netboxcategories that are not in request
NetboxCategory.objects.filter(category=group).exclude(
netbox__pk__in=netboxids).delete()
# Add new netboxcategories that are in request
... |
meissnert/StarCluster-Plugins | gess_1_0.py | Python | mit | 962 | 0.022869 | from starcluster.clustersetup import ClusterSetup
from starcluster.logger import log
class GessInstaller(ClusterSetup):
def run(self, nodes, master, user, user_shell, volumes):
for node in nodes:
log.info("Installing GESS 1.0 on %s" % | (node.alias))
node.ssh.execute('wget -c -P /opt/software/gess/1.0 http://compbio.uthscsa.edu/GESS_Web/files/gess.src.tar.gz')
n | ode.ssh.execute('cd /opt/software/gess/1.0/ && tar xzf /opt/software/gess/1.0/gess.src.tar.gz')
node.ssh.execute('chmod +x /opt/software/gess/1.0/gess/GESS.py')
node.ssh.execute('mkdir -p /usr/local/Modules/applications/gess/;touch /usr/local/Modules/applications/gess/1.0')
node.ssh.execute('echo "#%Module... |
BigBoss424/webtutorials | python/learnpythonhard/ex/ex3.py | Python | gpl-3.0 | 474 | 0 | print "I will now count my chickens:"
print "Hens", 25+30 / 6
print "Roosters", 100 - 2 | 5 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is is ... | equal?", 5 <= -2
|
dannysellers/django_orders | tracker/views/misc_views.py | Python | gpl-2.0 | 3,196 | 0.019399 | from datetime import date, timedelta
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.contrib import messages
from django.contrib.auth.views import password_reset, password_reset_confirm
from django.core.urlresolvers import reverse
from django.db.model... |
""" Wrap the built-in password reset view and pass it the arguments
like the template name, email template name, subject template name
and the url to | redirect after the password reset is initiated.
These views aren't login-restricted because end-users will be able to
use these views to reset their passwords (at least until I write an
equivalent API endpoint). """
# From http://runnable.com/UqMu5Wsrl3YsAAfX/using-django-s-built-in-views-for-password-... |
seppius-xbmc-repo/ru | plugin.video.ndr/simpleplugin.py | Python | gpl-2.0 | 59,566 | 0.001679 | # -*- coding: utf-8 -*-
# Created on: 03.06.2015
"""
SimplePlugin micro-framework for Kodi content plugins
**Author**: Roman Miroshnychenko aka Roman V.M.
**License**: `GPL v.3 <https://www.gnu.org/copyleft/gpl.html>`_
"""
import os
import sys
import re
import inspect
import time
import pickle
im... | fo[4] is not None:
for i, line in enumerate(frame_info[4], frame_info[2] - frame_info[5]):
if i == frame_info[2]:
context += '{0}:>{1}'.format(str(i).rjust(5), line)
|
else:
context += '{0}: {1}'.format(str(i).rjust(5), line)
logger('Code context:\n' + context)
# logger('Global variables:\n' + _format_vars(frame_info[0].f_globals))
#logger('Local variables:\n' + _format_vars(frame_info[0].f_locals))
logger('***... |
okor/thumbor | thumbor/detectors/feature_detector/__init__.py | Python | mit | 1,356 | 0.001475 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
import cv2
import numpy as np
from thumbor.detectors import BaseDet... | ine = self.context.modules.engine
try:
img = np.array(
engine.convert_to_grayscale(
update_image=False,
with_alpha=False
)
)
except Exception as e:
logger.exception(e)
logger.warn('Err... | skipping to next detector')
self.next(callback)
return
points = cv2.goodFeaturesToTrack(
img,
maxCorners=20,
qualityLevel=0.04,
minDistance=1.0,
useHarrisDetector=False,
)
if points is not None:
for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.