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 |
|---|---|---|---|---|---|---|---|---|
Nymphet/acgnz-spider | AcgnzSpider/spiders/AcgnzSpider01.py | Python | mit | 3,584 | 0.003627 | # -*- coding: utf-8 -*-
import scrapy
import logging
from scrapy.utils.project import get_project_settings
from time import sleep
from AcgnzSpider.items import AcgnzItem
class AcgnzSpider(scrapy.Spider):
name = 'acgnz.cc'
start_urls = ['http://www.acgnz.cc/sign']
allowed_domains = ['acgnz.cc']
def... | ]': self.settings.get('LOGIN_CREDENTIALS_EMAIL'),
'user[pwd]': self.settings.get('LOGIN_CREDENTIALS_PWD' | ),
'user[remember]': '1',
'type': 'login',
'theme-nonce': '85dd62e1f6'
},
callback=self.parse_follow_seq
)
def parse_follow_seq(self, response):
if 'success' not in response.body:
raise CloseSpider('login failed')
... |
automl/paramsklearn | tests/components/regression/test_sgd.py | Python | bsd-3-clause | 1,757 | 0.003415 | import unittest
from ParamSklearn.components.regression.sgd import SGD
from ParamSklearn.util import _test_regressor, _test_regressor_iterative_fit
import sklearn.metrics
class SGDComponentTest(unittest.TestCase):
def test_default_config | uration(self):
for i in range(10):
predictions, targets = _ | test_regressor(SGD)
self.assertAlmostEqual(0.092460881802630235,
sklearn.metrics.r2_score(y_true=targets,
y_pred=predictions))
def test_default_configuration_iterative_fit(self):
for i in range(10):
... |
stacksync/manager | users/views.py | Python | gpl-2.0 | 125 | 0.008 | from django.http import HttpResponse
def | index(request):
return HttpResponse("Hello, world. You're at th | e users index") |
sparkslabs/kamaelia_ | Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/Games4Kids/BasicSprite.py | Python | apache-2.0 | 3,562 | 0.010668 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ve... | image = self.original
self.rect = self.image.get_rect()
self.rect.center = self.pos
center = list(self.rect.center)
current = self.image
pos = center
dx,dy = 0,0
d = 10 # Change me to change the velocity of the sprite
while 1:
self.image = cur... | current = self.image
if self.dataReady("translation"):
pos = self.recv("translation")
if self.dataReady("inbox"):
event = self.recv("inbox")
if event == "start_up": dy = dy + d
if event == "stop_up": dy = dy - d
... |
riscmaster/risc_maap | risc_msgs/src/foo_msgs/msg/_Landmark.py | Python | bsd-2-clause | 4,376 | 0.020567 | """autogenerated by genpy from foo_msgs/Landmark.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class Landmark(genpy.Message):
_md5sum = "2edff07075d48378c13052415416989c"
_type = "foo_msgs/Landmark"
_has_header = False #flag to mark the prese... | writing '%s'" % (type(te), str(te), str(_x))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
... | end += length
if python3:
self.name = str[start:end].decode('utf-8')
else:
self.name = str[start:end]
_x = self
start = end
end += 24
(_x.x, _x.y, _x.z,) = _struct_3d.unpack(str[start:end])
return self
except struct.error as e:
raise genpy.Deserial... |
gbiggs/ros_book_sample_code | chapter3/src/message_subscriber.py | Python | apache-2.0 | 275 | 0 | #!/usr/bin/env python
import rospy
from chapter3.msg import Compl | ex
def callback(msg):
print 'Real:', msg.real
print 'Imaginary:', msg.imaginary
print
rospy.init_node('message_subscriber')
sub = rospy.Subscriber('complex' | , Complex, callback)
rospy.spin()
|
Freso/listenbrainz-server | listenbrainz_spark/recommendations/recording/tests/test_candidate.py | Python | gpl-2.0 | 25,386 | 0.003782 | from datetime import datetime
import sys
from listenbrainz_spark.tests import SparkTestCase
from listenbrainz_spark.recommendations.recording import candidate_sets
from listenbrainz_spark.recommendations.recording import create_dataframes
from listenbrainz_s | park import schema, utils, config | , path, stats
from listenbrainz_spark.exceptions import (TopArtistNotFetchedException,
SimilarArtistNotFetchedException)
from pyspark.sql import Row
from unittest.mock import patch
import pyspark.sql.functions as f
from pyspark.sql.types import StructField, StructType, String... |
essteban/Auto-DJ | Python Scripts/sliceWav.py | Python | gpl-3.0 | 327 | 0.04893 | #!/usr/bin/python
import wave |
import struct
def slice(f,w,init,end):
outFile = wave.open('cutted | _'+f,'w')
outFile.setparams((2,2,44100,0,'NONE','not compressed'))
w.setpos(init)
for i in range((end-w.tell())):
frames = w.readframes(1)
outFile.writeframes(frames)
outFile.close()
|
pratikmshah/practice | py-data-analysis/ftpDownloader-test.py | Python | mit | 831 | 0.008424 | # -*- coding: utf-8 -*-
"""
Created on Sat May 21 16:43:47 2016
@author: Pratik
"""
from ftplib import FTP
import os
# login and download file from ftp site and retrieve file (use default params)
def ftpDownloader(filename, host="ftp.pyclass.com", user="student@pyclass.com", passwd="student123"):
ftp = FTP(host) ... | /r
ftp.retrbinary('RETR %s' % f | ilename, file.write) # read contents of pdf and write to our file |
Kraymer/beets | beets/dbcore/query.py | Python | mit | 27,242 | 0 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... | fast=True):
super(RegexpQuery, self).__init__(field, pattern, fast)
pattern = self._normalize(pattern)
try:
self.pattern = re.compile(self.pattern)
except re.error as exc:
# Invalid regular expression.
raise Invali | dQueryArgumentValueError(pattern,
u"a regular expression",
format(exc))
@staticmethod
def _normalize(s):
"""Normalize a Unicode string's representation (used on both
patterns and matched values).
... |
chris1610/pbpython | code/advanced_excel.py | Python | bsd-3-clause | 2,204 | 0.002269 | """
See http://pbpython.com/advanced-excel-workbooks.html for details on this script
"""
from __future__ import print_function
import pandas as pd
from xlsxwriter.utility import xl_rowcol_to_cell
def format_excel(writer, df_size):
""" Add Excel specific formatting to the workbook
df_size is a tuple represent... | ol_to_cell(df_size[0] + 1, df_size[1] - 1)
# This assumes we start in the left hand corner
table_range = 'A1:{}'.format(table_end)
worksheet.add_table(table_range, {'c | olumns': [{'header': 'account',
'total_string': 'Total'},
{'header': 'Total Sales',
'total_function': 'sum'},
{'header... |
MingfeiPan/leetcode | stack/394.py | Python | apache-2.0 | 616 | 0.003247 | class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
multi = 0
ret = ''
for c in s:
if c == '[':
| stack.append(ret)
stack.append(multi)
ret = ''
multi = 0
elif c == ']':
num = stack.pop()
| temp = stack.pop()
ret = temp + num*ret
elif c.isdigit():
multi = multi*10 + int(c)
else:
ret += c
return ret
|
jeremiahyan/odoo | addons/test_mail/tests/test_mail_thread_internals.py | Python | gpl-3.0 | 16,837 | 0.004158 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from unittest.mock import DEFAULT
from werkzeug.urls import url_parse, url_decode
from odoo import exceptions
from odoo.addons.test_mail.models.test_mail_models import MailTestSimple
from... | s.common import tagged, HttpCase
from odoo.tools import mute_logger
class TestChatterTweaks(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestChatterTweaks, cls).setUpClass()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({'name... | ser(self.user_employee).with_context({'mail_create_nosubscribe': True}).message_post(
body='Test Body', message_type='comment', subtype_xmlid='mail.mt_comment')
self.assertEqual(self.test_record.message_follower_ids.mapped('partner_id'), original.mapped('partner_id'))
@mute_logger('odoo.addons.... |
SaikWolf/gnuradio | grc/core/utils/odict.py | Python | gpl-3.0 | 3,418 | 0.001755 | """
Copyright 2008-2015 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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... | py())
def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value
def __getitem__(self, key):
return self._data[key]
def __delitem__(self, key):
del self._data[key]
self._keys.remove(key)
def keys(sel... | py_dict = odict()
copy_dict._data = self._data.copy()
copy_dict._keys = list(self._keys)
return copy_dict
def insert_after(self, pos_key, key, val):
"""
Insert the new key, value entry after the entry given by the position key.
If the positional key is None, insert a... |
email2liyang/pypoll | mysite/books/forms.py | Python | mit | 445 | 0.008989 | from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(required=True,max_length=4)
email = forms.Ema | ilField(required=False)
message = forms.CharField(required=True,widget=forms.Textarea)
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message)
if num_words < 3:
raise forms.ValidationError( | "not enouth words")
return message |
mhugent/Quantum-GIS | python/plugins/processing/algs/gdal/sieve.py | Python | gpl-2.0 | 3,202 | 0.000312 | # -*- coding: utf-8 -*-
"""
***************************************************************************
sieve.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*********************************... | *************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from PyQt4 import QtGui, QtCore
from processing.core.GeoAlgorithm import GeoAlgorithm
from proce... | eterNumber import ParameterNumber
from processing.outputs.OutputRaster import OutputRaster
from processing.tools.system import *
from processing.algs.gdal.GdalUtils import GdalUtils
class sieve(GeoAlgorithm):
INPUT = 'INPUT'
THRESHOLD = 'THRESHOLD'
CONNECTIONS = 'CONNECTIONS'
OUTPUT = 'OUTPUT'
... |
xuleiboy1234/autoTitle | tensorflow/tensorflow/examples/speech_commands/train.py | Python | mit | 16,617 | 0.007041 | # Copyright 2017 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... | ]
time_shift_samples = int((FLAGS.time_shift_ms * FLAGS.sample_rate) / 1000)
# Figure out the learning rates for each training phase. Since it's often
# effective to have high learning rates at the start of training, followed by
# lower levels towards the end, the number of steps and learning rates can be
# s... | 01
# will run 13,000 training loops in total, with a rate of 0.001 for the first
# 10,000, and 0.0001 for the final 3,000.
training_steps_list = map(int, FLAGS.how_many_training_steps.split(','))
learning_rates_list = map(float, FLAGS.learning_rate.split(','))
if len(training_steps_list) != len(learning_rates... |
diogo149/treeano | examples/mnist_ml_l2.py | Python | apache-2.0 | 3,309 | 0.000302 | from __future__ import division, absolute_import
from __future__ import print_function, unicode_literals
import itertools
import numpy as np
import sklearn.datasets
import sklearn.cross_validation
import sklearn.metrics
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
import canopy
imp... | network,
[canopy.handlers.time_call(key="valid_time"),
canopy.handlers.override_hyperparameters(dropout_probability=0),
canopy.handlers.chunk_variables(batch_size=BATCH_SIZE,
variables=["x", "y"])],
{"x": "x", "y": "y"},
{"cost": "cost", "pred": "pred"})
... | sults_dict):
valid_out = valid_fn(valid)
probabilities = valid_out["pred"]
predicted_classes = np.argmax(probabilities, axis=1)
results_dict["valid_cost"] = valid_out["cost"]
results_dict["valid_time"] = valid_out["valid_time"]
results_dict["valid_accuracy"] = sklearn.metrics.accuracy_score(
... |
mitsuhiko/pip | tests/functional/test_requests.py | Python | mit | 366 | 0.010929 | import pytest
@pytest.mark.skipif
def t | est_timeout(script):
result = script.pip("--timeout", "0.01", "install", "-vvv", "INITools",
expect_error=True,
)
assert "Could not fetch URL https://pypi.python. | org/simple/INITools/: timed out" in result.stdout
assert "Could not fetch URL https://pypi.python.org/simple/: timed out" in result.stdout
|
giorgioladu/Rapa | portal.py | Python | apache-2.0 | 987 | 0 | # -*- coding: utf-8 -*-
#
# portal.py # # # # # # # # # #
# | #
# Copyright 2016 Giorgio Ladu <giorgio.ladu >at< gmail.com> #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. ... | E-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 Licen... |
andree1320z/deport-upao-web | deport_upao/apps/productos/urls.py | Python | mit | 176 | 0 | from django.conf.urls import url
from .views import list_products
app_na | me = "producto"
urlpatterns = [ |
url(r'list-productos/$', list_products, name='list_products'),
]
|
rahulvgmail/TripMapR | TripMapR/travelogue/migrations/0005_auto_20150420_1747.py | Python | bsd-3-clause | 770 | 0.002597 | # -*- coding: utf-8 -*-
from __future__ import unicode_li | terals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('travelogue', '0004_auto_20150418_1655'),
]
operations = [
migrations.AddField(
model_name='tripnote',
name='date_taken',
field=models.DateTimeFie... | =True, editable=False, blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='tripnote',
name='view_count',
field=models.PositiveIntegerField(default=0, verbose_name='view count', editable=False),
preserve_default=True,
... |
resamsel/dbmanagr | src/tests/test_options.py | Python | gpl-3.0 | 4,176 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2014 René Samselnig
#
# This file is part of Database Navigator.
#
# Database Navigator 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, ... | '1',
options.format_value(None, 1)
)
self.assertEqual(
"'d'",
options.format_value(None, 'd')
)
self.assertEqual(
u'7',
options.format_value(user.column('id'), 7)
)
self.assertEqual(
u"'a'",
... | format_value(user.column('id'), 'a')
)
self.assertEqual(
'null',
options.format_value(user.column('id'), None)
)
self.assertEqual(
'true',
options.format_value(user2.column('deleted'), True)
)
self.assertEqual(
'... |
ripiuk/fant_sizer | setup.py | Python | mit | 1,096 | 0 | from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name="fant_sizer",
version="0.7",
author="Rypiuk Oleksandr",
author_email="ripiuk96@gmail.com",
description="fant_sizer command-line file-information",
url="https://github.com/ripiuk/fan... | t :: Console',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Intended Au | dience :: Developers',
'Intended Audience :: Information Technology',
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3.6'
],
packages=find_packages(),
long_description=open(join(dirname(__file__), "README.rst")).read(),
... |
tomzx/decision-trees | clothes.py | Python | mit | 145 | 0.075862 | from enum import Enum
class Clothes(Enum):
Underwear = 1
Pants = 2
Shorts = 3
Socks = 4
| Shoes = 5
Shirt | = 6
Coat = 7
Hat = 8
Gloves = 9 |
lele94218/social_network_paper | facebook/getdata/old_clustering_example.py | Python | gpl-2.0 | 1,361 | 0.012491 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 03 10:16:52 2015
@author: Keine
"""
import sqlite3
cx = sqlite3.connect("../text2DB/get_data.db")
distxy = [([0.0] * 49) for i in range(49)]
cu = cx.cursor()
for i in range(49):
for j in range(49):
if i == j:
distxy[i-1][j-1] = 0.0
else:
... | nt distxy[49-1][48-1]
#from scipy.cluster.hierarchy import linkage, dendrogram
#R = dendrogram(linkage(distxy, method='complete'))
#suptitle('Cluster Dendrogram', fontweight='bold', fontsize=14);
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist, squareform
from scipy.cluste... | hierarchy import linkage, dendrogram
data_dist = pdist(distxy) # computing the distance
data_link = linkage(data_dist) # computing the linkage
dendrogram(data_link)
plt.xlabel('User_ID')
plt.ylabel('Similarity ratio')
plt.suptitle('Hierarchy Clustering', fontweight='bold', fontsize=14);
|
nicko96/Chrome-Infra | infra/services/builder_alerts/__main__.py | Python | bsd-3-clause | 12,085 | 0.009516 | #!/usr/bin/env python
# Copyright 2014 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 argparse
import contextlib
import cStringIO
import datetime
import gzip
import json
import logging
import multiprocessing
import... | # FIXME: The builder info doesn't really belong here. The builder
# revisions tool uses this and we happen to have the builder json cached
# at this point so it's cheap to compute, but it should be moved
# to a different feed.
data, stale_builder_alerts = (
buildbot.latest_builder_... | ster_alert)
return (master_alerts, data, stale_builder_alerts, master_url)
except:
# Put all exception text into an exception and raise that so it doesn't
# get eaten by the multiprocessing code.
raise Exception(''.join(traceback.format_exception(*sys.exc_info())))
def query_findit(findit_... |
yangshun/cs4243-project | app/surface.py | Python | mit | 3,220 | 0.000932 | import numpy as np
class Surface(object):
def __init__(self, image, edge_points3d, edge_points2d):
"""
Constructor for a surface defined by a texture image and
4 boundary points. Choose the first point as the origin
of the surface's coordinate system.
:param image: image a... | e(model, Polyhedron)
self.models.append(model)
class Line2D(object):
def __init_ | _(self, point1, point2):
"""
Using the line equation a*x + b*y + c = 0 with b >= 0
:param point1: starting point
:param point2: ending point
:return: a Line object
"""
assert len(point1) == 2 and len(point2) == 2
self.a = point2[1] - point1[1]
sel... |
Rusk85/pyload | module/plugins/hoster/VeehdCom.py | Python | gpl-3.0 | 2,311 | 0.001731 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from module.plugins.Hoster import Hoster
class VeehdCom(Hoster):
__name__ = 'VeehdCom'
__type__ = 'hoster'
__pattern__ = r'http://veehd\.com/video/\d+_\S+'
__config__ = [
('filename_spaces', 'bool', "Allow spaces in filename", 'False'),
... | lf.load(url)
def file_exists(self):
if self.html is None:
self.download_html()
if '<title>Veehd</title>' in self.html:
return False
return True
def get_file_name(self):
if self.html is None:
self.download_html()
match = re.search(r'... | self.fail("video title not found")
name = match.group(1)
# replace unwanted characters in filename
if self.getConfig('filename_spaces'):
pattern = '[^0-9A-Za-z\.\ ]+'
else:
pattern = '[^0-9A-Za-z\.]+'
name = re.sub(pattern, self.getConfig('replacement... |
rolandgeider/wger | wger/manager/tests/test_schedule.py | Python | agpl-3.0 | 23,910 | 0.001046 | # 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 later version.
#
# wger W... | workout = Schedule.objects.get(pk=1)
self.user_login('admin')
response = self.client.get(workout.get_absolute_url())
self.assertEqual(response.status_code, 403)
self.user_login('test')
response = self.client.get(workout.get_absolute_url())
self.as | sertEqual(response.status_code, 200)
self.user_logout()
response = self.client.get(workout.get_absolute_url())
self.assertEqual(response.status_code, 403)
class ScheduleRepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(se... |
frankrousseau/weboob | modules/arte/browser.py | Python | agpl-3.0 | 9,423 | 0.001804 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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... | ' in result['videoJsonPlayer']['VTU'].keys():
| video.thumbnail = BaseImage(result['videoJsonPlayer']['VTU']['IUR'])
video.thumbnail.url = video.thumbnail.id
return video
def home(self):
self.location('http://videos.arte.tv/%s/videos/toutesLesVideos' % self.lang)
def get_video_from_program_id(self, _id):
... |
jmchilton/lwr | galaxy/jobs/metrics/collectl/cli.py | Python | apache-2.0 | 5,442 | 0.018927 | from string import Template
import subprocess
import logging
log = logging.getLogger( __name__ )
COMMAND_LINE_TEMPLATE = Template(
"$collectl_path $destination_arg $mode_arg $subsystems_arg $interval_arg $procfilt_arg $flush_arg $sep_arg"
)
MODE_RECORD = "record"
MODE_PLAYBACK = "playback"
class CollectlCli( ob... | f.__subsystems_arg( kwargs.get( "subsystems", [] ) )
flush = kwargs.get( "flush", None )
| command_args[ "flush_arg"] = "--flush %s" % flush if flush else ""
sep = kwargs.get( "sep", None )
command_args[ "sep_arg" ] = "--sep=%s" % sep if sep else ""
self.command_args = command_args
def __subsystems_arg( self, subsystems ):
if subsystems:
return "-s%s" %... |
libvmi/libvmi | tools/windows-offset-finder/rekall_offset_finder.py | Python | lgpl-3.0 | 5,390 | 0.001299 | #!/usr/bin/env python3
"""
Rekall offset finder.
Usage:
rekall_offset_finder.py [options] <domain> [<url>]
Options:
-d --debug Enable debug output
-u URI, --uri=URI Specify Libvirt URI [Default: qemu:///system]
-o --old Use the old config format
-h --help ... | domain = con.lookupByName(domain_name)
# take dump
logging.info('Dumping %s physical memory to %s', domain.name(),
ram_dump.name)
flags = libvirt.VIR_DUMP_MEMO | RY_ONLY
dumpformat = libvirt.VIR_DOMAIN_CORE_DUMP_FORMAT_RAW
domain.coreDumpWithFormat(ram_dump.name, dumpformat, flags)
ram_dump.flush()
# extract offsets
config = extract_offsets(domain.name(), ram_dump.name)
else:
config = e... |
roadmapper/ansible | test/units/plugins/lookup/test_lastpass.py | Python | gpl-3.0 | 6,829 | 0.001464 | # (c)2016 Andrew Zenk <azenk@umn.edu>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | d_in_true(self):
lp = MockLPass()
self.assertTrue(lp.logged_in)
def test_lastpass_logged_in_false(self):
lp = LoggedOutMockLPass()
self.assertFalse(lp.logged_in)
def test_lastpass_show_disconnected(self):
| lp = DisconnectedMockLPass()
with self.assertRaises(LPassException):
lp.get_field('0123456789', 'username')
def test_lastpass_show(self):
lp = MockLPass()
for entry in MOCK_ENTRIES:
entry_id = entry.get('id')
for k, v in six.iteritems(entry):
... |
GhostshipSoftware/avaloria | game/gamesrc/commands/world/character_commands.py | Python | bsd-3-clause | 7,180 | 0.004457 | from ev import Command, CmdSet
from src.commands.default.muxcommand import MuxCommand
class CmdAttack(Command):
"""
Begin to fight a target, typically an npc enemy.
Usage:
attack target-name
"""
key = 'attack'
aliases = ['kill']
help_category = "Combat"
locks = "cmd:all()"
... | nc(self):
caller = self.caller
caller.display_charact | er_sheet()
class CmdLoot(Command):
"""
Pass a corpse name to this command to loot the corpse.
Usage:
loot <corpse>
"""
key = 'loot'
help_category = "General"
locks = "cmd:all()"
def parse(self):
self.what = self.args.strip()
def func(self):
obj =... |
jmadajian/CinemaFlowWorks | Examples/kitchen_sink.py | Python | gpl-3.0 | 41,711 | 0.000479 | # -*- coding: utf-8 -*-
import kivymd.snackbar as Snackbar
from kivy.app import App
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.properties import ObjectProperty
from kivy.uix.image import Image
from kivymd.bottomsheet import MDListBottomSheet, MDGridBottomSheet
from kivymd.button import MDIconBu... | MDCard:
size_hint: Non | e, None
size: dp(320), dp(180)
pos_hint: {'center_x': 0.5, 'center_y': 0.3}
BoxLayout:
orientation:'vertical'
padding: dp(8)
MDLabel:
text: 'Title'
theme_text_color... |
elfnor/sverchok | nodes/modifier_make/polygons_adaptative.py | Python | gpl-3.0 | 5,472 | 0.001102 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
from bpy.props import FloatProperty
import bmesh
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import (updateNode, Vector_generate,
... | tch_long_repeat)
from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata
# "coauthor": "Alessandro Zomparelli (sketchesofcode)"
class AdaptivePolsNode(bpy.types.Node, SverchCustomTreeNode):
''' Make spread one object on another adaptively polygons of mesh (not including matrixes, so apply scale-rot-loc ctrl+... |
Pexego/PXGO_00053_2013_VT | project-addons/sale_product_customize/wizard/mrp_create_prod.py | Python | agpl-3.0 | 2,350 | 0.000426 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Pexego All Rights Reserved
# $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affer... | ##################################################################
from openerp import models, fields, api, exceptions, _
class CreateMountedProd(models.TransientModel):
_name = "mrp.mounted.product.create.wizard"
mount_product = fields.Many2one('product.product',
'Mount ... | 'mounted product', required=True)
@api.multi
def create_product(self):
if not self.mount_product.default_code or not \
self.mounted_product.default_code:
raise exceptions.except_orm(_('Code error'),
_('One of the ... |
nrjl/GPN | active_statruns.py | Python | mit | 7,118 | 0.00562 | # Simple 1D GP classification example
import time
import numpy as np
import matplotlib.pyplot as plt
import GPpref
import plot_tools as ptt
from active_learners import ActiveLearner, UCBLatent, PeakComparitor, LikelihoodImprovement, ABSThresh, UCBAbsRel
import test_data
import pickle
class Learner(object):
def __i... | GPpref.PrefProbit(),
'abs_likelihood': GPpref.AbsBoundProbit()}
# Get initial solution
for nl, learner in enumerate(learners):
learner.build_model(training_data)
learner.model.set_hyperparameters(log_hyp)
f = learner.model.solve_laplace()
| fhat, vhat = learner.model.predict_latent(x_test)
y_abs_est = learner.model.abs_posterior_mean(x_test, fhat, vhat)
wrms_results[nl, 0, trial_number] = wrms(y_abs_true, y_abs_est)
for obs_num in range(n_queries):
learners[4].obs_arguments['p_rel'] = max(0.0, (20-obs_num)/20.0)
for nl... |
L0st1nC0d3/TextAdventure | todb.py | Python | epl-1.0 | 1,112 | 0.003597 | import sys
import sqlite3
import os
import os.path
def main(dbname):
con = sqlite3.connect(dbname)
con.execute("CREATE TABLE IF NOT EXISTS rooms(id INTEGER PRIMARY KEY, name TEXT NOT NULL,"
" description TEXT NOT NULL)")
con.commit()
path = "./rooms"
| for f in os.listdir(path):
f_n = os.path.join(path, f)
base, extension = os.path.splitext(f)
if extension == '.json' and 'r' in base:
with open(f_n, 'r') as fa:
json = fa.read()
if len(base) == 3:
s = base[1]+base[2]
... | format(int(s)))
con.execute("INSERT OR REPLACE INTO rooms(id, name, description)"
"VALUES(?, ?, ?);", (int(s), json.decode('utf8'), json.decode('utf8')))
con.commit()
con.close()
if __name__ == "__main__":
if len(sys.argv) != 2:
... |
senttech/Cura | plugins/PerObjectSettingsTool/__init__.py | Python | agpl-3.0 | 1,195 | 0.005858 | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from . import PerObjectSettingVisibilityHandler
from PyQt5.QtQml import qmlRegisterType
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
def getMetaData():
retu... | nfigure Per Model Settings"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml",
"weight": 3
},
}
def register(app):
qmlRegisterType(PerObjectSettingVisibilityHandler.PerObjectSettingVisibilityHandler, "Cura", 1, 0,
"PerObje... | sTool() }
|
tobias-froehlich/cryspy | cryspy/lab.py | Python | gpl-3.0 | 6,803 | 0.00588 | import cryspy.numbers
import cryspy.geo
class Goniometer:
def __init__(self, motiontype, axis, direction, parametername):
assert motiontype in ["translation", "rotation"], \
"First parameter for creating a Goniometer " \
"must be one of the strings " \
"'translation' or ... | %16s |\n" \
"| around |\n" \
"| %s-axis |\n" \
" \\ %16s / "\
%(self.parameternames[0], self.axis, self.direction)
else:
return cryspy.blockprint.block([[str(self.lower_g... | def __mul__(self, right):
if isinstance(right, Goniometer):
for parametername in right.parameternames:
assert parametername not in self.parameternames, \
"Cannot multiply two Goniometers which have " \
"both the parameter '%s'."%(parameter... |
GluuFederation/community-edition-setup | install.py | Python | mit | 4,334 | 0.004845 | #!/usr/bin/python3
import sys
sys.path.append('/usr/lib/python3.6/gluu-packaged/')
import site
import re
import glob
import os
import subprocess
import argparse
import time
import zipfile
import shutil
import distutils
import requests
from urllib.parse import urljoin
run_time = time.strftime("%Y-%m-%d_%H-%M-%S")
c... |
os.chmod('/install/community-edition-setup/setup.py', 33261)
post_setup = '/install/community-edition-setup/post-setup-add-components.py'
if os.path.exists(post_setup):
os.chmod(post_setup, 33261)
gluu_install = '/install/community-editi | on-setup/gluu_install.py'
if os.path.exists(gluu_install):
os.remove(gluu_install)
if argsp.o:
npy_download_link = 'https://github.com/npcole/npyscreen/archive/master.zip'
result = requests.get(npy_download_link, allow_redirects=True)
with open(npyscreen_package, 'wb') as w:
w.write(result.cont... |
google/clusterfuzz | src/clusterfuzz/_internal/chrome/build_info.py | Python | apache-2.0 | 6,483 | 0.009409 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, | Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS ... | r implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for fetching build info from OmahaProxy."""
import json
import re
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system... |
Apreche/Wikibloks | allauth/utils.py | Python | mit | 2,568 | 0.001558 | from django.conf import settings
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
fr | om django.core.validators import validate_email, ValidationError
from django.db.models import EmailField
from emailconfirmation.models import EmailAddress
def get_login_redirect_url(request):
"""
Returns a url to redirect to after the login
"""
if 'next' in request.session:
next = request.sess... | return request.POST.get('next')
else:
return getattr(settings, 'LOGIN_REDIRECT_URL', '/')
def generate_unique_username(txt):
username = slugify(txt.split('@')[0])
max_length = User._meta.get_field('username').max_length
i = 0
while True:
try:
if i:
... |
24OI/CodeStack | cpplint.py | Python | gpl-2.0 | 241,962 | 0.008853 | #!/usr/bin/env python
#
# Copyright (c) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... | provided, then a count
is provided for each category like 'build/class'.
root=subdir
The root directory used fo | r deriving header guard CPP variable.
By default, the header guard CPP variable is calculated as the relative
path to the directory that contains .git, .hg, or .svn. When this flag
is specified, the relative path is calculated from the specified
directory. If the specified directory does not ex... |
oopsno/arena | src/arena/cmd.py | Python | bsd-3-clause | 1,864 | 0.000536 | import subprocess
class CmdArgument(object):
_PREFIX = None
_KEY = None
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
@property
def prefix(self):
return self._PREFIX
@property
def key(self):
return s... | def __str__(self):
try:
return self.format()
except NotImplementedError:
return '{}{} "{}"'.format(self._PREFIX, self._KEY, self._value)
class Cmd(object):
def __init__(self, cmd: | str):
self._cmd = cmd
self._args = []
def config(self, *args: [CmdArgument]):
self.clear_args()
self.add_arg(args)
def add_arg(self, *arg: [CmdArgument]):
self._args.extend(arg)
def clear_args(self):
self._args.clear()
@property
def command(self) ... |
ncbray/pystream | bin/decompiler/destacker/maindestacker.py | Python | apache-2.0 | 20,089 | 0.030514 | # Copyright 2011 Nicholas Bray
#
# 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... | region.entry()
output = None
newdefns = {}
while block:
outblock, stack = self(block, stack)
if outblock != None and outblock in self.defns:
for k, v in self.defns[outblock].iteritems():
assert not k in newd | efns, (k, newdefns)
newdefns[k] = v
assert isinstance(stack, PythonStack) or stack==None, block
output = appendSuite(output, outblock)
assert block.numExits() <= 1
if block.numExits() == 0:
# Stack exists if this is a normal exit
break
elif stack == None:
break
else:
#assert s... |
tamasgal/km3pipe | examples/network/udp_dispatcher.py | Python | mit | 1,173 | 0.000853 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Tamas Gal <tgal@km3net.de>
# License: MIT
#!/usr/bin/env python
# vim: ts=4 sw=4 et
"""
=============================
UDP Forwarder for ControlHost
=============================
A simple UDP forwarder for ControlHost messages.
This application is used to forward... | DPFor | warder(kp.Module):
def configure(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.counter = 0
def process(self, blob):
if str(blob["CHPrefix"].tag) == "IO_MONIT":
self.sock.sendto(blob["CHData"], ("127.0.0.1", 56017))
if self.counter % 100... |
Jwely/cdo-api-py | docs/example/dc_weather_data.py | Python | mit | 2,346 | 0.002984 | from cdo_api_py import Client
import pandas as pd
from datetime import datetime
from pprint import pprint
# initialize a client with a developer token ,
# note 5 calls per second and 1000 calls per day limit for each token
token = "my token here!"
my_client = Client(token, default_units=None, default_limit=1000)
# the... | )
# we can get big lists of station data with
big_df = pd.DataFrame()
for rowid, station in stations.iterrows(): # remember this is a pandas dataframe!
station_data = my_client.get_data_by_station(
datasetid=datasetid,
stationid=station['id'], # remember this is a pandas dataframe
start... | enddate=enddate,
return_dataframe=True, # this defaults to True
include_station_meta=True # flatten station metadata with ghcnd readings
)
pprint(station_data)
big_df = pd.concat([big_df, station_data], sort=False)
# Now we can do whatever we want with our big dataframe. Lets sort... |
telminov/django-voximplant | voximplant/migrations/0009_auto_20160516_0649.py | Python | mit | 813 | 0.00123 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-16 06:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('voximplant', '0008_auto_20160514_0800'),
]
operations = [
migrations.RemoveF... | d(
model_name='calllist',
name='downloaded',
field=models.DateTimeField(blank=True, help_text='Last datetime of checking state from VoxImplant', null=True),
),
migrations.AlterField(
model_name='calllistphone',
| name='completed',
field=models.DateTimeField(blank=True, null=True),
),
]
|
clarkperkins/stackdio | stackdio/core/viewsets.py | Python | apache-2.0 | 13,461 | 0.002303 | # -*- coding: utf-8 -*-
# Copyright 2017, Digital Reasoning
#
# 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... | ioModelPermissionsViewSet(StackdioBasePermissionsViewSet):
model_cls = None
model_or_object = 'model'
permission_classes = (StackdioPermissionsModelPermissions,)
def get_model_cls(self):
assert self.model_cls, (
"'%s' should include a `model_cls` attribute or override the `get_model... | _.__name__
)
return self.model_cls
def get_model_name(self):
return self.get_model_cls()._meta.model_name
def get_app_label(self):
ret = self.get_model_cls()._meta.app_label
if ret == 'auth':
# one-off thing, since users/groups are in the `users` app, not `a... |
nachandr/cfme_tests | cfme/tests/physical_infrastructure/ui/test_physical_server_details.py | Python | gpl-2.0 | 3,611 | 0.001662 | import pytest
from cfme.physical.provider.lenovo import LenovoProvider
from cfme.utils.appliance.implementations.ui import navigate_to
pytestmark = [pytest.mark.tier(3), pytest.mark.provider([LenovoProvider], scope="module")]
@pytest.fixture(scope="module")
def physical_server(appliance, provider, setup_provider_mo... | evices != "0" else
not storage_device_view.is_displayed)
def test_physical_server_details_stats(physical_server):
"""Navigate to the physical server details pag | e and verify that the stats match
Polarion:
assignee: rhcf3_machine
casecomponent: Infra
initialEstimate: 1/4h
"""
physical_server.validate_stats(ui=True)
|
macarthur-lab/xbrowse | seqr/views/apis/users_api.py | Python | agpl-3.0 | 7,234 | 0.003179 | import json
import urllib
from anymail.exceptions import AnymailError
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models imp... | ate_json_response
from seqr.views.utils.orm_to_json_utils import _get_json_for_user, get_json_for_ | project_collaborator_list, \
get_project_collaborators_by_username
from seqr.views.utils.permissions_utils import get_projects_user_can_view, get_project_and_check_permissions, CAN_EDIT
from seqr.model_utils import create_xbrowse_project_collaborator, delete_xbrowse_project_collaborator
from settings import API_LOG... |
cmshobe/landlab | landlab/graph/hex/hex.py | Python | mit | 27,221 | 0.001212 | r"""
Examples
--------
::
* - *
/ \ / \
* - * - *
/ \ / \ / \
* - * - * - *
\ / \ / \ /
* - * - *
\ / \ /
* - *
>>> from landlab.graph import TriGraph
>>> graph = TriGraph((5, 2), node_layout="hex", sort=True)
>>> graph.number_of_nodes
14
>>> graph.x_of_node
ar... | wer_left[0]
y_of_node[:] += xy_of_lower_left[1]
return x_of_node, y_of_node
class VerticalRectTriGraphCython:
@staticmethod
def xy_of_node(shape, spacing=1.0, xy_of_lower_left=(0.0, 0.0)):
from .ext.hex import fill_xy_of_node_rect_vertical
n_rows, n_cols = shape
x_spa... | y_spacing = spacing
x_of_node = np.empty(n_rows * n_cols, dtype=float)
y_of_node = np.empty(n_rows * n_cols, dtype=float)
fill_xy_of_node_rect_vertical(shape, x_of_node, y_of_node)
x_of_node *= x_spacing
y_of_node *= y_spacing
x_of_node += xy_of_lower_left[0]
... |
sephiroth6/nodeshot | nodeshot/core/layers/migrations/0001_initial.py | Python | gpl-3.0 | 8,891 | 0.008211 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Layer'
db.create_table('layers_layer', (
(u'id', self.gf('django.db.models.field... | models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'gender': ('django.db.models.fi | elds.CharField', [], {'max_length': '1', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'T... |
rackerlabs/django-DefectDojo | dojo/unittests/test_bulk_risk_acceptance_api.py | Python | bsd-3-clause | 6,446 | 0.006826 | import datetime
from rest_framework.authtoken.models import Token
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIClient
from dojo.models import Product_Type, Product, Engagement, Product_Type_Member, Test, Finding, User, Test_Type, Role
from dojo.authorization.roles_permiss... | ), dat | a=accepted_risks,
format='json')
self.assertEquals(len(result.json()), 17)
self.assertEquals(self.test_a.unaccepted_open_findings.count(), 17)
self.assertEquals(self.test_b.unaccepted_open_findings.count(), 33)
self.assertEquals(self.test_c.unaccepted_op... |
simphony/tornado-webapi | tornadowebapi/renderers/tests/test_json_renderer.py | Python | bsd-3-clause | 287 | 0 | import unittest
from | tornadowebapi.renderers import JSONRenderer
class TestJSONRenderer(unittest.TestCase):
def test_basic_rendering(self):
renderer = JSONRenderer()
self.assertEqual(renderer.render({}), "{}")
self.assertEqual(ren | derer.render(None), None)
|
TeXitoi/navitia | source/jormungandr/jormungandr/modules/v1_routing/v1_routing.py | Python | agpl-3.0 | 9,012 | 0.000555 | # coding=utf-8
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open p... |
self.api.app.url_map.strict_slashes = False
self.module_resources_manager.register_resource(Index.Index())
self.add_resource(Index.Index,
'/',
'',
endpoint='index')
self.module_resources_manager.register_reso... | endpoint='technical_status')
coverage = '/coverage/'
region = coverage + '<region:region>/'
coord = coverage + '<lon:lon>;<lat:lat>/'
self.add_resource(Coverage.Coverage,
coverage,
region,
coord,
... |
Rondineli/django-sso | django_sso/sso_request/urls.py | Python | gpl-2.0 | 242 | 0 | # -*- coding:utf-8 -*-
from django.c | onf.urls import patterns, url
from django.contrib import admin
from views import AssertView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', | AssertView.as_view(), name='redirect'),
)
|
bbc/ebu-tt-live-toolkit | ebu_tt_live/bindings/_itts.py | Python | bsd-3-clause | 69 | 0 | # -*- coding: utf-8 -*-
from | ebu_tt_live.bind | ings.raw._itts import *
|
bw4sz/MotionMeerkat_Bisque | MotionMeerkat/report.py | Python | gpl-3.0 | 3,667 | 0.011999 | import time
import csv
def report(ob):
#Create log file
log_file_report = ob.file_destination + "/" + "Parameters_Results.log"
log_report = file(log_file_report, 'a' )
#Print parameters
#Batch or single file
log_report.write("\nRun type: %s" % ob.runtype)
if ob.... | " % ob.ROI_include)
log_report.write("\nArea counter?: %s" % ob.set_areacounter)
log_report.write("\nOutput type?: %s\n\n" % ob.makeVID)
#Ending time
end | =time.time()
#total_time()
total_min=(end-ob.start)/60
#processed frames per second
pfps=float(ob.frame_count)/(total_min*60)
##Write to log file
log_report.write("Total run time (min): %.2f \n " % total_min)
log_report.write("Average frames per second: %.2f \n... |
BhallaLab/moose-examples | squid/squid_demo.py | Python | gpl-2.0 | 43,246 | 0.005113 | # -*- coding: utf-8 -*-
# Description: Squid Model
# Author: Subha
# Maintainer: Dilawar Singh <dilawars@ncbs.res.in>
# Created: Mon Jul 9 18:23:55 2012 (+0530)
# Version:
# Last-Updated: Wednesday 12 September 2018 04:23:52 PM IST
# PyQt5 version
import sys
import os
from collections import defaultdict
impo... | - β<sub>m</sub> * m </p>
and similarly for h.
The steady state values are:
<p> m<sub>∞</sub> = α<sub>m</sub>/(α<sub>m</sub> + β<sub>m</sub | >) </p>
and time constant for steady state is:
<p>τ<sub>m</sub> = 1/ (α<sub>m</sub> + β<sub>m</sub>) </p>
and similarly for h.
"""
tooltip_KChan = """<h3>K+ channel conductance</h3>
<p/>The K+ channel conductance in squid giant axon is given by:
<p> G<sub>K</sub> = Ḡ<sub>K</sub> * n<sup>4</sup></p>
and the current ... |
j16r/rust | src/etc/mirror-all-snapshots.py | Python | apache-2.0 | 944 | 0.003178 | #!/usr/bin/env python
# xfail-license
import os, tarfile, hashlib, re, shutil
from snapshot import *
f = open(snapshotfile)
date = None
rev = None
platform = None
snap = None
i = 0
for line in f.readlines():
i += 1
parsed = parse_line(i, line)
if (not parsed): continue
if parsed["type"] == "snapshot... | e = parsed["date"]
rev = parsed["rev"]
elif rev != None and parsed["type"] == "file":
platform = parsed["platform"]
hsh = parsed["hash"]
snap = full_snapshot_name(date, rev, platform, hsh)
dl = os.path.join(download_dir_base, snap)
url = download_url_base + "/" + sna... | print("got download with ok hash")
else:
raise Exception("bad hash on download")
|
TeamEOS/device_xiaomi_cancro | releasetools/releasetools.py | Python | gpl-2.0 | 1,275 | 0.008627 | #
# Copyright (C) 2015 The CyanogenMod Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | ll/bin/resize2fs_static", "/dev/block/platform/msm_sdcc.1/by-name/s | ystem");');
info.script.AppendExtra('run_program("/sbin/e2fsck", "-fy", "/dev/block/platform/msm_sdcc.1/by-name/system");');
def FullOTA_InstallEnd(info):
info.script.AppendExtra('mount("ext4", "EMMC", "/dev/block/platform/msm_sdcc.1/by-name/system", "/system", "");');
info.script.AppendExtra('run_program(... |
zhunor/tweet_to_geojson | tweet_to_geojson.py | Python | mit | 1,117 | 0.029543 | import json
import pprint
import geojson
from geojson import Feature, Point, FeatureCollection
data = []
geoms = []
tweet_features = []
with open('raw.json') as twtr_hamdata:
for satir in twtr_hamdata:
data.append(json.loads(satir))
for i in range(0,len(data)):
geoms.append(data[i]["geo"]["coordina... | eoms[i][0], geoms[i][1]
my_feature = Feature(geometry=Point((float(geoms[i][1]),float(geoms[i][0]))),\
properties={"user_location":data[i]["user"]["location"],\
"user_id": data[i]["id"],\
"user_name":data[i]["user"]["name"],\
"screen_name":data[i]["user"]["screen_name"],\
"followers_count":data[... | me":data[i]["created_at"]})
tweet_features.append(my_feature)
#print tweet_features
tweet_FeatureCollection = FeatureCollection(tweet_features[:])
#print tweet_FeatureCollection["type"]
try:
saveFile = open('tweets.geojson','a')
saveFile.write(json.dumps(tweet_FeatureCollection))
saveFile.close()
excep... |
prasanna08/oppia | core/controllers/voice_artist.py | Python | apache-2.0 | 5,564 | 0.00018 | # coding: utf-8
# Copyright 2018 The Oppia 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 r | equired by applicable law or agreed to in w | riting, 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.
"""Controllers for the translation changes."""
from __f... |
babybunny/rebuildingtogethercaptain | test/test_main.py | Python | apache-2.0 | 1,940 | 0.00567 | """Functional tests f | or main views."""
import os
import unittest
from webtest import TestApp
import app_engine_test_utils
from gae import main
from test import test_models
app = TestApp(main.app)
class WelcomeTest(unittest.Tes | tCase):
def setUp(self):
app_engine_test_utils.activate_app_engine_testbed_and_clear_cache()
def testHelp(self):
response = app.get('/help')
self.assertEquals('200 OK', response.status)
def testRoot(self):
os.environ['ROOMS_DEV_SIGNIN_EMAIL'] = "rebuildingtogether.nobody@gmail.com"
response ... |
Dob3r/python_seleniumwebdriver | Model/Customer.py | Python | apache-2.0 | 493 | 0.004057 |
class Customer:
def __init__(self, firstname, lastname, country, address, postcode, city, email, phone, pas | sword):
self.firstname = firstname
self.lastname = lastname
self.country = country
self.address = address
self.postcode = postcode
self.city= city
self.email = email
self.phone = phone
self.password = password
def __repr__(self):
retur... | s:%s" % (self.email, self.firstname, self.lastname)
|
valsteen/ableton-live-webapi | ext_libs/Cython/Compiler/ModuleNode.py | Python | unlicense | 122,308 | 0.002502 | #
# Module parse tree node
#
import cython
cython.declare(Naming=object, Options=object, PyrexTypes=object, TypeSlots=object,
error=object, warning=object, py_object_type=object, UtilityCode=object,
EncodedString=object)
import os, time
from PyrexTypes import CPtrType
import Future
im... | ding
else:
env.doc = self.doc
env.directi | ves = self.directives
self.body.analyse_declarations(env)
def process_implementation(self, options, result):
env = self.scope
env.return_type = PyrexTypes.c_void_type
self.referenced_modules = []
self.find_referenced_modules(env, self.referenced_modules, {})
if optio... |
frankrousseau/weboob | weboob/browser/filters/standard.py | Python | agpl-3.0 | 23,209 | 0.00194 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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 opti... | urn self.default_or_raise(ParseError('Element %r not found' % self.selector))
class AsyncLoad(Filter):
def __call__(self, item):
link = self.select(self.selector, item, key=self._key, obj=self._obj)
return item.page.browser.async_open(link)
class | Async(_Filter):
def __init__(self, name, selector=None):
super(Async, self).__init__()
self.selector = selector
self.name = name
def __and__(self, o):
if isinstance(o, type) and issubclass(o, _Filter):
o = o()
self.selector = o
return self
def __... |
hanya/MRI | pythonpath/mytools_Mri/ui/controller.py | Python | apache-2.0 | 2,539 | 0.010634 | # Copyright 2011 Tsutomu Uchino
#
# 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 ... | = "mytools.mri.UIController"
def __init__(self,frame, model):
self.frame = frame
self.model = model
self.ui = None
|
def set_ui(self, ui):
self.ui = ui
def get_imple_name(self):
return self.ui.pages.get_imple_name()
# XTitle
def getTitle(self):
return self.frame.getTitle()
def setTitle(self, title):
self.frame.setTitle(title)
def dispose(self):
self.fr... |
ArcEye/machinekit-testing | src/hal/user_comps/vismach/scaragui.py | Python | lgpl-2.1 | 5,700 | 0.017719 | #!/usr/bin/python2.4
# Copyright 2007 John Kasunich and Jeff Epler
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any lat... | .0
for setting in sys.argv[1:]: exec setting
# calculate a bunch of other dimensions that are used
# to scale the model of the machine
# most of these scale factors are arbitrary, to give
# a nicely proportioned machine. If you know specifics
# for the machine you are modeling, feel free to change
# these numbers
t... | 5*d5+d6*d6) # don't change
tool_dia = tool_len / 6.0
# diameters of the arms
l1_dia = d2 / 5.0
l2_dia = d4 / 5.0
l3_dia = l2_dia * 0.8
# diameters of the "lumps" at the joints
j0_dia = l1_dia * 1.5
j1_dia = max(l1_dia * 1.25, l2_dia * 1.5)
j2_dia = l2_dia * 1.25
# other dims
j0_hi = l1_dia * 1.2
j1_hi1 = l1_dia * 1.1
... |
roycem90/python-o365 | O365/inbox.py | Python | apache-2.0 | 2,984 | 0.037198 | from O365.message import Message
import logging
import json
import requests
log = logging.getLogger(__name__)
class Inbox( object ):
'''
Wrapper class for an inbox which mostly holds a list of messages.
Methods:
getMessages -- downloads messages to local memory.
Variables:
inbox_url -- url used for fetc... |
test your filter stirng here: https://outlook.office365.com/api/v1.0/me/messages?$filter=
if that accepts it then you know it works.
'''
self.filters = f_string
return True
#To | the King!
|
StevenLOL/aicyber_semeval_2016_ivector | System_2/steps/conf/append_eval_to_ctm.py | Python | gpl-3.0 | 1,989 | 0.019608 | #!/bin/env python
# Copyright 2015 Brno University of Technology (author: Karel Vesely)
# Apache 2.0
import sys,opera | tor
# Append Levenshtein alignment of 'hypothesis' and 'reference' into 'CTM':
# (i.e. the output of 'align-text' post-processed by 'wer_per_utt_details.pl')
# The tags in the appended column are:
# 'C' = correct
# 'S' = substitution
# 'I' = insertion
# 'U' = unknown (not part of scored segment)
if len(sys.argv)... | (1)
dummy, eval_in, ctm_in, ctm_eval_out = sys.argv
if ctm_eval_out == '-': ctm_eval_out = '/dev/stdout'
# Read the evalutation,
eval_vec = dict()
with open(eval_in, 'r') as f:
while True:
# Reading 4 lines encoding one utterance,
ref = f.readline()
hyp = f.readline()
op = f.readline()
csid = f.... |
dmlc/tvm | tests/python/contrib/test_ethosu/cascader/__init__.py | Python | apache-2.0 | 832 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | uted 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.
"""Test infrastructure for the NPU cascader"""
|
codewarrior0/pymclevel | items.py | Python | isc | 19,714 | 0.001572 | from collections import defaultdict
import logging
logger = logging.getLogger(__file__)
items_txt = """
:version 27
# Blocks
# ID NAME FILE CORDS DAMAGE
1 Stone terrain.png 1,0
2 Grass terrain.png 3,0
3 Dirt terr... | terrain.png 7,1
42 Block_of_Iron terrain.png 6,1
43 Double_Stone_Slab terrain.png 5,0 0
43 Double_Sandstone_Slab terrain.png 0,12 1
43 Double_Wooden_Slab terrain.png 4,0 2
43 Double_Stone_Slab terrain.png 0,1 3
44 Stone_Slab | special.png 2,2 0
44 Sandstone_Slab special.png 1,2 1
44 Wooden_Slab special.png 3,0 2
44 Stone_Slab special.png 1,0 3
44 Bricks_Slab special.png 0,0 4
44 Stone_Bricks_Slab special.png 2,0 5
45 Bricks terrain.png ... |
edx/insights | src/edinsights/modulefs/modulefs.py | Python | agpl-3.0 | 3,765 | 0.012218 | import json
import os
import os.path
import types
from django.conf import settings
from models import FSExpirations
if settings.DJFS['type'] == 'osfs':
from fs.osfs import OSFS
elif settings.DJFS['type'] == 's3fs':
from fs.s3fs import S3FS
from boto.s3.connection import S3Connection
from boto.s3.key ... | fs = get_filesystem(module)
if fs.exists(o.filename):
fs.remove(o.filename)
o.delete()
def patch_fs(fs, namespace, url_method):
''' | Patch a filesystem object to add two methods:
get_url returns a URL for a resource stored on that filesystem. It takes two parameters:
filename: Which resource
timeout: How long that resource is available for
expire sets a timeout on how long the system should keep the ... |
cnbird1999/ava | ava/import_google/migrations/0008_googledirectorygroup_group.py | Python | gpl-2.0 | 502 | 0.001992 | # -*- coding: utf-8 -*-
from __future__ import unicode_litera | ls
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core_group', '0001_initial'),
('import_google', '0007_googledirectorygroup_identity'),
]
operations = [
migrations.AddField(
model_name='googledirectorygroup',
... | to='core_group.Group', blank=True, null=True),
),
]
|
dreadatour/Cactus | cactus/tests/test_ui.py | Python | bsd-3-clause | 2,199 | 0.003183 | # coding:utf-8
import unittest2 as unittest
from cactus import ui
class UITestCase(unittest.TestCase):
def test_coerce_yes_no(self):
self.assertEqual(True, ui._yes_no_coerce_fn("y"))
self.assertEqual(True, ui._yes_no_coerce_fn("Y"))
self.assertEqual(False, ui._yes_no_coerce_fn("n"))
... | _url_coerce_fn, "www.example.com")
self.assertRaises(ui.InvalidInput, ui._url_coerce_fn, "www.example.com ")
self.assertRaises(ui.InvalidInput, ui._url_coerce_fn, "http://")
self.assertRaises(ui.InvalidInput, ui._url_coerce_fn, | "/")
self.assertRaises(ui.InvalidInput, ui._url_coerce_fn, "http://www.example.com/somewhere/")
self.assertRaises(ui.InvalidInput, ui._url_coerce_fn, "http://www.example.com/#hash")
# Disabled for now with the desktop app
# class InteractiveUITestCase(BaseTestCase):
# def test_site_url_not_set(s... |
lhilt/scipy | scipy/stats/_rvs_sampling.py | Python | bsd-3-clause | 6,992 | 0 | from __future__ import division, print_function, absolute_import
import numpy as np
import warnings
from scipy._lib._util import check_random_state
def rvs_ratio_uniforms(pdf, umax, vmin, vmax, size=1, c=0, random_state=None):
"""
Generate random samples from a probability density function using the
rati... | t rejected at 5% significance level):
>>> stats.kstest(rvs, 'norm')[1]
0.3420173467307603
The exponential distribution provides another example where the bounding
rectangle can be determined explicitly.
>>> np.random.seed(12345)
>>> rvs = stats.rvs_ratio_uniforms(lambda x: np.exp(-x), umax=1,... | in=0, vmax=2*np.exp(-1), size=1000)
>>> stats.kstest(rvs, 'expon')[1]
0.928454552559516
Sometimes it can be helpful to use a non-zero shift parameter `c`, see e.g.
[2]_ above in the case of the generalized inverse Gaussian distribution.
"""
if vmin >= vmax:
raise ValueError("vmin must... |
deddokatana/PyMiningCalc | PyMiningCalc/calc.py | Python | gpl-3.0 | 2,447 | 0.009399 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Crypto-currency mining calculator
Copyright (C) 2013 "Working4coins" <working4coins@gmail.com>
You can donate: https://sites.google.com/site/working4coins/donate
This program is free software: you can redistribute it and/or modify
it under the term... | ee <http://www.gnu.org/licenses/>
"""
import time
import datetime
#import simplejson as json
#import locale
import os
import argparse
from MiningCalc.miningcalc_btc import BTCMiningCalculator
from MiningCalc.miningcalc_ltc import LTCMiningCalculator
if __name__ == "__main__":
#locale.setlocale(locale.LC_ALL, '... | , 'fr_FR') # to print number with commas as thousands separators
parser = argparse.ArgumentParser(description='Use the following parameters')
parser.add_argument('currency1', action="store", help="use this flag to set currency mining calculator (BTC, LTC...)")
parser.add_argument('--loop', action="store"... |
mitdbg/modeldb | client/verta/verta/_swagger/_public/modeldb/model/ModeldbDatasetPartInfo.py | Python | mit | 1,057 | 0.014191 | # THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class ModeldbDatasetPartInfo(BaseType):
def __init__(self, path=None, size=None, checksum=None, last_modified_at_source=None):
required = {
"path": False,
"size": False,
| "checksum": False,
"last_modified_at_source": False,
}
self.path = path
self.size = size
self.checksum = checksum
self.last_modified_at_source = last_modified_at_source
for k, v in required.items():
if self[k] is None and v:
raise ValueError('attribute {} is required'.format... | e:
d['size'] = tmp
tmp = d.get('checksum', None)
if tmp is not None:
d['checksum'] = tmp
tmp = d.get('last_modified_at_source', None)
if tmp is not None:
d['last_modified_at_source'] = tmp
return ModeldbDatasetPartInfo(**d)
|
hy-2013/scrapy | tests/test_pipeline_media.py | Python | bsd-3-clause | 10,657 | 0.002252 | from __future__ import print_function
from twisted.trial import unittest
from twisted.python.failure import Failure
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.python import log as txlog
from scrapy.http import Request, Response
from scrapy.spider impo... | w_i | tem is item)
self.assertEqual(new_item['results'], [(True, rsp1)] |
aetilley/revscoring | revscoring/utilities/score.py | Python | mit | 1,550 | 0.001935 | """
``revscoring score -h``
::
Scores a set of revisions.
Usage:
score (-h | --help)
score <model-file> <rev_id>... --api=<uri> [--verbose]
Options:
-h --help Print this documentation
<model-file> Path to a model file
--api=<url> The url pointing to a Med... | gs = docopt.docopt(__doc__, argv=argv)
model = MLScorerModel.load(open(args['<model-file>'], 'rb'))
extractor = APIExtractor(api.Session(args['--api']),
language=model.language)
rev_ids = [int(rev_id) for rev_id in args['<rev_id>']]
verbose = args['--verbos | e']
run(model, extractor, rev_ids, verbose)
def run(model, extractor, rev_ids, verbose):
if verbose: logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
)
error_features = extractor.extract(rev_ids, model.features)
for rev_id, (erro... |
ormiret/tinfoil-hat | scrape_moray.py | Python | apache-2.0 | 1,124 | 0.032918 | import urllib, urllib2, re
from bs4 import BeautifulSoup
def scrape(url):
home = 'http://www.moray.gov.uk/'
datePattern = r'[0-9][0-9]-[0-9][0-9]-20[0-9][0-9]'
departments = r'(Chief Executive\'s Office|Corporate Services|Education and Social Care|Environmental Services|Multiple Services)'
html = urllib2.urlopen... | #print pl.string + ' : ' + pl['href']
foi = urllib2.urlopen(home+pl['href']).read()
foiSoup = BeautifulSoup(foi)
bill = foiSoup.find('div', {'class': 'boxj_txt_ara'})
if bill is not None:
print bill.p
except UnicodeEncodeError:
pass
|
url = 'http://www.moray.gov.uk/moray_standard/page_62338.html'
scrape(url) |
RRShieldsCutler/clusterpluck | clusterpluck/tools/compileclustertypes.py | Python | mit | 1,143 | 0.029746 | #!/usr/bin/env python
# Takes antismash output files in the current directory
# and grabs the cluster types summary file, generating
# a single txt file with all the cluster ID, types, and ranges.
# USAGE
# $ python compileclustertypes.py -o output_filename
# Returns tab-delimited txt file in the current directory.
i... | rtswith('abbrev'):
newdata = pd.read_csv(os.path.join(dir, 'cluster_sequences', file), delimiter='\t', header=0, usecols=[0,1,2])
outfile = outfile.append(newdata)
e | lse:
pass
else:
pass
outfile.to_csv(args.output,sep='\t',index=False)
if __name__ == '__main__':
parser = make_arg_parser()
args = parser.parse_args()
main()
|
dlareau/puzzlehunt_server | huntserver/tests.py | Python | mit | 33,380 | 0.002756 | from django.test import TestCase, override_settings
from django.urls import reverse
from huntserver import models, forms, templatetags
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.exceptions import ValidationError
from datetime import timedelta
try:
from SimpleHTTP... | eate | (team=team, is_response=False, text="foobar",
time=timezone.now())
models.Unlockable.objects.create(puzzle=puzzle, content_type="TXT", content="foobar")
def test_unicode(self):
str(models.Hunt.objects.all()[0])
str(models.Puzzle.objects.all()[0])
... |
wbsljh/caravel | caravel/models.py | Python | apache-2.0 | 73,950 | 0.000325 | """A collection of ORM sqlalchemy models for Caravel"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
import functools
import json
import logging
import re
import textwrap
from collections import namedtuple... | flask_appbu | ilder.models.decorators import renders
from flask_appbuilder.filemanager import get_file_original_name
from flask_babel import lazy_gettext as _
from pydruid.client import PyDruid
from pydruid.utils.filters import Dimension, Filter
from pydruid.utils.postaggregator import Postaggregator
from pydruid.utils.having impo... |
kylepjohnson/cltk | src/cltk/stem/__init__.py | Python | mit | 61 | 0 | """Init for `cltk.tokenize`."""
from .processes imp | ort *
| |
coreswitch/openconfigd | vendor/github.com/osrg/gobgp/test/scenario_test/bgp_router_test.py | Python | apache-2.0 | 16,381 | 0 | # Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | stant_relative(self):
q1 = self.quaggas['q1']
q2 = self.quaggas['q2']
q3 = self.quaggas['q3']
q5 = QuaggaBGPContainer(name='q5', asn=65005, router_id='192.168.0.6')
initial_wait_time | = q5.run()
time.sleep(initial_wait_time)
for q in [q2, q3]:
q5.add_peer(q)
q.add_peer(q5)
med200 = {'name': 'med200',
'type': 'permit',
'match': '0.0.0.0/0',
'med': 200}
q2.add_policy(med200, self.gobgp, 'ou... |
ceball/param | tests/API1/testdaterangeparam.py | Python | bsd-3-clause | 2,007 | 0.003986 | """
Unit tests for DateRange parameter.
"""
import datetime as dt
import param
from . import API1TestCase
# Assuming tests of range parameter cover most of what's needed to
# test date range.
class TestDateRange(API1TestCase):
bad_range = (dt.datetime(2017,2,27),dt.datetime(2017,2,26))
def test_wrong_type_... | nge()
try:
Q(a=self.bad_range)
except ValueError:
pass
else:
raise AssertionError( | "Bad date type was accepted.")
def test_wrong_type_set(self):
class Q(param.Parameterized):
a = param.DateRange()
q = Q()
try:
q.a = self.bad_range
except ValueError:
pass
else:
raise AssertionError("Bad date type was accepted... |
Fuzzwah/mplayer-web-rfid-control | sse.py | Python | gpl-2.0 | 4,199 | 0.006192 | """
This component is modified from https://github.com/marinho/tornado
Released unde | r the Apache License http://www.apache.org/licenses/LICENSE-2.0.html
"""
import time
import tornado.web, tornado.escape, tornado. | ioloop
import hashlib, json
class SSEHandler(tornado.web.RequestHandler):
_closing_timeout = False
_live_connections = [] # Yes, this list is declared here because it is used by the class methods
def __init__(self, application, request, **kwargs):
super(SSEHandler, self).__init__(application, requ... |
magestik/TuxStereoViewer | src/lib_shutter.py | Python | gpl-3.0 | 6,327 | 0.041252 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import functions
import Image
import math, time
import sys
import pygtk
pygtk.require('2.0')
import gtk
import gtk.gtkgl
from OpenGL.GL import *
from OpenGL.GLU import *
from threading import Thread
import gobject
gobject.threads_init() # For prevent GTK freeze
import dbus
... | ereo3d.shutters', '/org/stereo3d/shutters')
self.RefreshControl = controller(parent.stereo, shutters, left, right, int(self.conf['rate']))
except:
print "Can't connect to the daemon !" # GTK POP-UP ?
else:
self.RefreshControl.start()
def swap_eyes(self):
self.left, self.right = self.right, self.left
... | t, self.oleft # Backup
taille = self.right.size
self.height, self.width = taille[1], taille[0]
elif self.height > 0 and self.width > 0:
if self.height > maxh or self.width > maxw or force == 1:
qrh, qrw = (self.height + 0.00000000) / maxh, (self.width + 0.00000000) / maxw
qrmax = max(qrh, qr... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/django_extensions/db/fields/__init__.py | Python | agpl-3.0 | 20,102 | 0.000995 | """
Django Extensions additional model fields
"""
import re
import six
import string
import warnings
try:
import uuid
HAS_UUID = True
except ImportError:
HAS_UUID = False
try:
import shortuuid
HAS_SHORT_UUID = True
except ImportError:
HAS_SHORT_UUID = False
from django.core.exceptions import ... | ield: self.slugify_func(getattr(model_instance, field))
slug = self.separator.join(map(slug_for_field, self._populate_from))
start = 2
else:
# get slug from the current model instance
slug = getattr(model_instance, self.attname)
# model_instance is bei... | t slug
return slug
# strip slug depending on max_length attribute of the slug field
# and clean-up
self.slug_len = slug_field.max_length
if self.slug_len:
slug = slug[:self.slug_len]
slug = self._slug_strip(slug)
original_slug = slug
if s... |
pwnbus/scoring_engine | scoring_engine/config.py | Python | mit | 80 | 0 | from scoring_engine.config | _loader import ConfigLoader
con | fig = ConfigLoader()
|
grupydf/grupybr-template | {{cookiecutter.repo_name}}/.plugins/sitemap/__init__.py | Python | gpl-3.0 | 22 | 0.045455 | from | .sitemap impor | t * |
nexdatas/tools | test/NXSCreateStdCompDBE_test.py | Python | gpl-3.0 | 1,642 | 0 | #!/usr/bin/env python
# This file is part of nexdatas - Tango Server for NeXus data writer
#
# Copyright (C) 2012-2018 DESY, Jan Kotanski <jkotan@mail.desy.de>
#
# nexdatas 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.
#
# nexdatas is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the im... | SS 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 nexdatas. If not, see <http://www.gnu.org/licenses/>.
# \package test nexdatas
# \file XMLConfigurator_test.py
# unittests for field Tags runn... |
badassdatascience/pyDome | pyDome.py | Python | gpl-3.0 | 5,599 | 0.020897 | # pyDome: A geodesic dome calculator
# Copyright (C) 2013 Daniel Williams
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | files output/test.wrl and output/test.dxf.'
print
print 'Options:'
print
print '\t-r, --radius\tRadius of generated dome. Must be floating point. Default 1.0.'
print
print '\t-f, --frequency\tFrequency of generated dome. Must be an integer. Default 4.'
print
print '\t-v, --vthreshold\tDistance required... | lt 0.0000001. Must be floating point.'
print
print '\t-t, --truncation\tDistance (ratio) from the bottom to truncate. Default 0.499999. I advise using only the default or 0.333333. Must be floating point.'
print
print '\t-b, --bom-rounding\tThe number of decimal places to round chord length output in the genera... |
AlexStarov/Shop | applications/ajax/callback.py | Python | apache-2.0 | 6,232 | 0.001174 | # -*- coding: utf-8 -*-
__author__ = 'Alex Starov'
try:
from django.utils.simplejson import dumps
# import simplejson as json
except ImportError:
from json import dumps
# import json
from django.http import HttpResponse
def callback_data_send(request, ):
if request.is_ajax():
if request.... | return HttpResponse(data, mimetype, )
else:
print(callback, )
""" Отправка заказа обратного звонка """
subject = u'Заказ обратного звонка от пользователя: %s на номер: %s. Интернет магазин Кексик.' % (name, phone, )
from django.temp... | tent = render_to_string('email_request_callback_content.html',
{'name': name,
'email': email,
'phone': phone, }, )
from django.utils.html import strip_tags
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.