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 |
|---|---|---|---|---|---|---|---|---|
chinageology/GeoPython | geopytool/CIA.py | Python | gpl-3.0 | 10,636 | 0.010566 | from ImportDependence import *
from CustomClass import *
class CIA(AppForm):
useddf=pd.DataFrame()
Lines = []
Tags = []
description = 'Chemical Index of Alteration'
unuseful = ['Name',
'Mineral',
'Author',
'DataType',
'Label',
... | = ['Label','SiO2','Al2O3','Fe2O3','MgO','CaO','Na2O',' | K2O','P2O5','MnO','TiO2']
ItemsToTest = ['Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size', 'Alpha',
'Style', 'Width']
for i in ItemsAvalibale:
if 'O' not in i and i !='Label':
dataframe = dataframe.drop(i, 1)
WholeIt... |
takeontom/pyluxafor | pyluxafor/pyluxafor.py | Python | mit | 4,987 | 0 | # -*- coding: utf-8 -*-
import usb
class LuxaforFlag(object):
DEVICE_VENDOR_ID = 0x04d8
DEVICE_PRODUCT_ID = 0xf372
MODE_STATIC_COLOUR = 1
MODE_FADE_COLOUR = 2
MODE_STROBE | = 3
MODE_WAVE = 4
MODE_PATTERN = 6
LED_TAB_1 = 1
LED_TAB_2 = 2
LED_TAB_3 = 3
LED_BACK_1 = 4
LED_BACK_2 = 5
LED_BACK_3 = 6
LED_TAB_SIDE = 65
LED_BACK_SIDE = 66
LED_ALL = 255
WAVE_SINGLE_SMALL = 1
WAVE_SINGLE_LARGE = 2
WAVE_DOUBLE_SMALL = 3
WAVE_DOUBLE_L | ARGE = 4
PATTERN_LUXAFOR = 1
PATTERN_RANDOM1 = 2
PATTERN_RANDOM2 = 3
PATTERN_RANDOM3 = 4
PATTERN_POLICE = 5
PATTERN_RANDOM4 = 6
PATTERN_RANDOM5 = 7
PATTERN_RAINBOWWAVE = 8
def __init__(self):
self.device = None
def get_device(self):
"""
Retrieve a PyUSB... |
dpeddi/ws-28xx | CWeatherStationConfig.py | Python | gpl-3.0 | 11,102 | 0.037651 | #!/usr/bin/python
## This driver is based is based on reverse engineering of HeavyWeather 2800 v 1.54
## All copyright goes to La Crosse Technology (c) 2008
## Python port by Eddi De Pieri <eddi@depieri.net>
## Use this software as your own risk.
## Me and La Crosse Technology is not responsable for any damage using ... | atherStationHighLowAlarm::SetLowAlarm(&self._AlarmPress | ure, a);
USBHardware.ReverseByteOrder(nbuf, 34+start, 5);
#USBHardware.ReadPressureShared(nbuf, 34+start, &a, &b);
#v19 = Conversions::ToInhg(a);
#v25 = b - v19;
#if ( fabs(v25) > 1.0 )
#{
# Conversions::ToInhg(a);
# v20 = CTracer::Instance();
# CTracer::WriteTrace(v20, 30, "high pressure alarm dif... |
MagicStack/MagicPython | test/statements/import3.py | Python | mit | 1,061 | 0.042413 | from....import a
from...import b
from..import c
from.import d
| from : keyword.control.import.python, source.python
.... : punctuation.separator.period.python, source.python
import : keyword.control.import.python, source.python
| : source.python
a : source.python
from : keyword.control.import.python, source.python
... : punctuation.separator.period.python, source.python
import : keyword.control.import.python, source.python
: source.python
b : source.python
from : keywor... |
googlei18n/fontuley | src/third_party/fontTools/Lib/fontTools/ttLib/tables/_c_m_a_p.py | Python | apache-2.0 | 45,080 | 0.032276 | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval, readHex
from fontTools.ttLib import getSearchRange
from fontTools.unicode import Unicode
from . import DefaultTable
import sys
import struct
import array
import operator
cl... | bHeader.glyphIndexArray[0]
for gid in subHeader.glyphIndexArray:
if (gid != 0) and (gid < minGI):
minGI = gid
# The lowest gid in glyphIndexArray, after subtracting idDelta, must be 1.
# idDelta is a shor | t, and must be between |
caronc/datetools | src/pytest.py | Python | gpl-2.0 | 2,031 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Datetools provide a method of manipulating and working dates and times.
# Copyright (C) 2013-2018 Chris Caron <lead2gold@gmail.com>
#
# This file is part of Datetools. Datetools is free software; you can
# redistribute it and/or modify it under the terms of the GNU Gener... | True)
# Drifting inline
print dateblock("*/10 +5", ref=date(2000, 1, 1), block=False)
# Drifting inline (with option specified, inline should over-ride)
# Drifting without use of +
print dateblock("*/10 * * * * * 5", ref=date(2000, 2, 1), block=False)
# Drifting with multiple options specified
print dateblock("* 10 +5,... | 3, 1), block=False)
|
simonward86/MySJcLqwwx | ML_predict.py | Python | apache-2.0 | 3,255 | 0.006759 | import pandas as pd
import numpy as np
from random import sample
from sklearn.ensemble import RandomForestClassifier
def ML_BuySell(all_data, predictDate, predictors, previous_results, limit=0.0051,
limit_comp=np.arange(-.015, 0.02, 0.001), days_previous=252, train_split=0.8, n=3,acc_limit=0.75):
"... | i - 1] > pred_v[i])
if l:
change = change + (l* limit_comp[i])
# If it is more than what we want, precede.
if change > limit:
return pd.concat([
pd.DataFrame({"Price": all_data.ix[all_data.index == predictDate, "price"],
"Regime": 1,
... | ata.ix[all_data.index == predictDate, "price"],
"Regime": -1,
"Signal": "Sell"})
])
else:
return None
|
ian-r-rose/SHTOOLS | examples/python/TimingAccuracy/TimingAccuracyDHC.py | Python | bsd-3-clause | 2,509 | 0.007573 | #!/usr/bin/env python
"""
This script is a python version of TimingAccuracyDHC. We use numpy functions to
simplify the creation of random coefficients.
"""
import os
import sys
import time
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), "../../.."))
import pyshtools as shtools
#==== MAIN F... | 1) * (maxdeg + 1))
cilm = np.zeros((2, (maxdeg + 1), (maxdeg + 1)), dtype=np.complex)
random_numbers = np.random.normal(loc=0., scale=1., size=2 * (maxdeg + 1) * (maxdeg + 1))
cilm.imag = random_numbers.reshape(2, maxdeg + 1, maxdeg + 1)
random_numbers = np.random.normal(loc=0., scale=1., size=2 * (m... | 1:]**beta) / (2. * ls[1:] + 1.))[None, :, None]
#---- time spherical harmonics transform for lmax set to increasing powers of 2 ----
lmax = 2
print 'lmax maxerror rms tinverse tforward'
while lmax <= maxdeg:
# trim coefficients to lmax
cilm_trim = cilm[:, :lmax + 1, :lm... |
googleapis/python-functions | docs/conf.py | Python | apache-2.0 | 12,404 | 0.000564 | # -*- coding: utf-8 -*-
# Copyright 2021 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 agr... | on file (.ico) being 16x16 or | 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# Add any ext... |
jcmgray/quijy | quimb/tensor/tensor_tebd.py | Python | mit | 20,340 | 0 | import numpy as np
import quimb as qu
class NNI:
"""An simple interacting hamiltonian object used, for instance, in TEBD.
Once instantiated, the ``NNI`` hamiltonian can be called like ``H_nni()``
to get the default two-site term, or ``H_nni((i, j))`` to get the term
specific to sites ``i`` and ``j``.... | nterms = self.n - int(not self.cyclic)
return sum(
qu.norm(self((i, i + 1)), ntype)
for i in range(nterms)
) / nterms
def __repr__(self):
return f"<NNI(n={self.n}, cyclic={self.cyclic})>"
clas | s TEBD:
"""Class implementing Time Evolving Block Decimation (TEBD) [1].
[1] Guifré Vidal, Efficient Classical Simulation of Slightly Entangled
Quantum Computations, PRL 91, 147902 (2003)
Parameters
----------
p0 : MatrixProductState
Initial state.
H : NNI or array_like
Den... |
Germanika/plover | plover/oslayer/wmctrl.py | Python | gpl-2.0 | 1,274 | 0 |
import sys
if sys.platform.startswith('win32'):
import win32gui
GetForegroundWindow = win32gui.GetForegroundWindow
SetForegroundWindow = win32gui.SetForegroundWindow
elif sys.platform.startswith('darwin'):
from Foundation import NSAppleScript
def GetForegroundWindow():
return NSAppl... | ocessError:
return None
def SetForegroundWi | ndow(w):
"""Returns focus to previous application."""
try:
call(['wmctrl', '-i', '-a', str(w)])
except CalledProcessError:
pass
|
USGS-Astrogeology/GDAL_scripts | gdal_baseline_slope/python2/slope_histogram_cumulative_graph.py | Python | unlicense | 4,103 | 0.013892 | #!/usr/bin/env python
#/******************************************************************************
# * $Id$
# *
# * Project: GDAL Make Histogram and Cumulative graph from Tab delimited tab as
# generated by gdal_hist.py
# * Purpose: Take a gdal_hist.py output and create a histogram plot using matp... | lize figure
fig, ax1 = plt.subplots()
#calculate unscaled values
#df.value = (df.value * 5) - 0.2
#df.ix[df.value < 0] = 0; df
#not to reverse histogram before calculating 'approx' stats
#min = round(df.value.min(),2)
#max = round(df.value.max(),2)
#mean = round(df.value.mean(),2)
#stddev = round(df.value.std(),2)
#r... | n) + (stddev * stddev)),2)
#statsDict = {'Min':min,'Max':max,'Mean':mean \
#,'StdDev':stddev,'RMS':rms}
#statsSeries = pd.Series(statsDict,name='stats')
#statsSeries.sort()
#t = table(ax1, statsSeries, \
#loc='lower right', colWidths=[0.1] * 2)
#t.set_fontsize(18)
#props = t.properties()
#cells = p... |
cpicanco/player_plugins | filter_opencv_threshold.py | Python | gpl-3.0 | 3,093 | 0.012937 | # -*- coding: utf-8 -*-
'''
Pupil Player Third Party Plugins by cpicanco
Copyright (C) 2016 Rafael Picanço.
The present file is distributed under the terms of the GNU General Public License (GPL v3.0).
You should have received a copy of the GNU General Public License
along with this program. If not, see <ht... | Apply cv2.threshold in each channel of the (world) frame.img
"""
uniqueness = "not_unique" |
def __init__(self, g_pool, threshold=177, thresh_mode="BINARY", otsu=False):
super(Filter_Opencv_Threshold, self).__init__(g_pool)
# run before all plugins
# self.order = .1
# run after all plugins
self.order = .99
# initialize empty menu
self.menu = None
... |
netgio/voicecount | devicecode/SpeakPythonMakeDB.py | Python | mit | 4,765 | 0.057712 | import antlr3;
import sqlite3;
import pickle;
import sys, os;
import re;
from SpeakPython.SpeakPython import SpeakPython;
from SpeakPython.SpeakPythonLexer import SpeakPythonLexer;
from SpeakPython.SpeakPythonParser import SpeakPythonParser;
#sort results based on length of labels
def sortResults(results):
l = len(r... | ase under function name
if len(f.kGroupRegexes) > 0:
kleeneEntries.append((f.getName(), pickle.dumps(f.kGroupRege | xes)));
f.results = sortResults(f.results);
funcEntries.append((f.getName(), f.getExp(), pickle.dumps(f.getResults())));
print "All function test cases passed";
c.executemany("INSERT INTO functions VALUES (?,?,?)", funcEntries);
c.executemany("INSERT INTO kleene VALUES (?,?)", kleeneEntries);
conn.commit()... |
ricardovice/CacheGenerator | setup.py | Python | mit | 329 | 0.006079 | from distutils.core import setup
version = '1.1.1'
setup(name='CacheGenerator',
version=version,
description="CacheGenerator for | Django",
author="Ricardo Santos",
author_email="rica | rdo@getgears.com",
url="http://github.com/ricardovice/CacheGenerator/",
packages = ['cachegenerator']
)
|
luotao1/Paddle | python/paddle/fluid/tests/unittests/distributed_passes/test_dist_fuse_bn_add_act_pass.py | Python | apache-2.0 | 3,476 | 0.000863 | # Copyright (c) 2022 PaddlePaddle 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 ap... | paddle.distributed.passes import new_pass, PassManager
import unittest
from dist_pass_test_base import DistPassTestBase
class BatchNormAddActNet(nn.Layer):
def __init__(self):
super(BatchNo | rmAddActNet, self).__init__()
self.conv1 = nn.Conv2D(3, 8, (3, 3), data_format="NHWC")
self.conv2 = nn.Conv2D(3, 8, (3, 3), data_format="NHWC")
self.bn1 = nn.BatchNorm2D(8, data_format="NHWC")
self.bn2 = nn.BatchNorm2D(8, data_format="NHWC")
self.relu = nn.ReLU()
def forwar... |
sharehub/DBRest | dbrest/contacts/urls.py | Python | mit | 858 | 0.005828 | from django.conf.urls import patterns, include, url
from django.conf import settings
# Here, user contacts.profile will cause some 'mismatch' since contacts is also a module
from profile import ProfileView
from contacts import ContactsView
from authen import Authenticate
strid = settings.CONTACT_URL['strid']
user = s... | patterns = patterns('',
url(r'^api/'+auth+'$', Authenticate.as_view()),
url(r'^api/(?P<'+strid+r'>\w{16})/$', ProfileView.as_v | iew()),
url(r'^api/(?P<'+strid+r'>\w{16})/(?P<'+contact+r'>\d+)/$', ContactsView.as_view()),
url(r'^(?P<'+user+r'>\w{5,18})/(?P<'+strid+r'>\w{16})/$', ProfileView.as_view()),
url(r'^(?P<'+user+r'>\w{5,18})/(?P<'+strid+r'>\w{16})/(?P<'+contact+r'>\d+)/$', ContactsView.as_view()),
)
|
johnshiver/football_tools | football/core/management/commands/show_top_players.py | Python | mit | 607 | 0.001647 | import sys
from django.core.management.base import BaseCommand, CommandError
import nflgame
from terminaltables import AsciiTable
from ...models import Player, Team, Season, Week, WeeklyStats
class Command(BaseCommand):
help = 'takes option position, displays top players as table'
def add_arguments(self, ... | # Named (optional) arguments
parser.add_argument('position', nargs=1)
def handle(self, *args, **options):
p = options['position']
if p:
Player.show_ | top_players(position=p[0])
else:
Player.show_top_players()
|
openstack/neutron-vpnaas | doc/source/conf.py | Python | apache-2.0 | 8,813 | 0.003858 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 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 app... | ---------------------------
# Gr | ouping the document tree for man pages.
# List of tuples 'sourcefile', 'target', u'title', u'Authors name', 'manual'
#man_pages = [
# ('man/neutron-server', 'neutron-server', u'Neutron Server',
# [u'OpenStack'], 1)
#]
# -- Options for HTML output -------------------------------------------------
# The theme ... |
Hiestaa/cognitive-racer | GameEngine/GameObjects/Car/behaviour.py | Python | lgpl-3.0 | 3,344 | 0.031998 | # -*- coding: utf8 -*-
import logging
import math
from Graphx import graphx
from GameEngine.GameObjects.gameObjectBehaviour import GameObjectBehaviour
from Brains.human import HumanBrain
from conf import conf
class CarBehaviour(GameObjectBehaviour):
brainTypes = {
'human': HumanBrain
}
"""
Behaviour of the ... |
self._newHeading = self._model.headingAngle + \
self._model.constant('maniability')
self._newVelocity = self._model.velocity
self.move()
def update(self, stateManager):
"""
Use the brain the take the decision about what is the next action, then
update the model according to what has been decided.
""... | elf._model.velocity = self._newVelocity
self._model.position = self._newPosition
# self._ruleChecker.check(self._model.getCurrentState(),
# self._model.getPreviousState())
|
eroicaleo/LearningPython | interview/leet/450_Delete_Node_in_a_BST.py | Python | mit | 2,059 | 0.004371 | #!/usr/bin/env python3
# Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
# Basically, the deletion can be divided into two stages:
# Search for a node to remove.
# If the node is found, delete the node.
# Not... |
# 5
# / \
# 3 6
# / \ \
# 2 4 7
# Given key to delete is 3. So we find the node with value 3 and delete it.
# One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
# 5
# / \
# 4 6
# / \
# 2 7
# Another valid answer is [5,2,6,null,4,null,7].
# 5
# / ... | None):
# self.val = val
# self.left = left
# self.right = right
from tree import *
class Solution:
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if root == None:
return None
if key < root.val:
root.left = self.deleteNode(root.left, key)... |
Botong/songtaste | lib/requests/auth.py | Python | apache-2.0 | 6,120 | 0.000817 | # -*- coding: utf-8 -*-
"""
requests.auth
~~~~~~~~~~~~~
This module contains the authentication handlers for Requests.
"""
import os
import re
import time
import hashlib
| from base64 import b64encode
from .compat import urlparse, str
from .cookies import | extract_cookies_to_jar
from .utils import parse_dict_header
CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
return 'Basic ' + b64encode(('%s:%s' % (username, passwo... |
zisko/swift | utils/jobstats/jobstats.py | Python | apache-2.0 | 10,591 | 0.000189 | #!/usr/bin/python
#
# ==-- jobstats - support for reading the contents of stats dirs --==#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014-2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/... | g chrome's
'catapult' trace format"""
return {"name": self.module,
"cat": self.jobkind,
"ph": "X", | # "X" == "complete event"
"pid": self.jobid,
"tid": 1,
"ts": self.start_usec,
"dur": self.dur_usec,
"args": self.jobargs}
def start_timestr(self):
"""Return a formatted timestamp of the job's start-time"""
t... |
goors/flask-microblog | models/PostFile.py | Python | apache-2.0 | 335 | 0.026866 | from models import d | b
from models.Post import Post
class PostFile(db.Model):
__tablename__ = 'PostFile'
Id = db.Column(db.Integer, primary_key = True)
Post = db.Column(db.Integer, db.ForeignKey(Post.Id))
FileName = db.Column(db.String(128))
def __init__(self, post, file):
self.Post = post
self.FileName = fi | le
|
loretoparisi/docker | theano/rsc15/preprocess.py | Python | mit | 3,325 | 0.008724 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 25 16:20:12 2015
@author: Balázs Hidasi
@lastmodified: Loreto Parisi (loretoparisi at gmail dot com)
"""
import sys
import os
import numpy as np
import pandas as pd
import datetime as dt
# To redirect output to file
class Logger(object):
def __init__(self, filename=... | ata.SessionId, session_train)]
test = data[np.in1d(data.SessionId, session_test)]
test = test[np.in1d(tes | t.ItemId, train.ItemId)]
tslength = test.groupby('SessionId').size()
test = test[np.in1d(test.SessionId, tslength[tslength>=2].index)]
print('Full train set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(train), train.SessionId.nunique(), train.ItemId.nunique()))
train.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_tra... |
smmribeiro/intellij-community | python/testData/psi/MissingListSeparators.py | Python | apache-2.0 | 11 | 0.090909 | a = | [1 2 | 3] |
drnextgis/QGIS | python/plugins/db_manager/db_plugins/postgis/plugin.py | Python | gpl-2.0 | 14,923 | 0.002278 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@... | parent):
from .data_model import PGSqlResultModel
return PGSqlResultModel(self, sql, parent)
def registerDatabaseActions(self, mainWindow):
Database.registerDatabaseActions(self, mainWindow)
# add a separator
separator = QAction(self)
separator.setSeparator(True)
... | self.tr("&Table"))
action = QAction(self.tr("Run &Vacuum Analyze"), self)
mainWindow.registerAction(action, self.tr("&Table"), self.runVacuumAnalyzeActionSlot)
action = QAction(self.tr("Run &Refresh Materialized View"), self)
mainWindow.registerAction(action, self.tr("&Table"), self.r... |
anbangr/trusted-juju | juju/providers/ec2/tests/test_state.py | Python | agpl-3.0 | 4,134 | 0 | from yaml import dump
from twisted.internet.defer import succeed, fail
from txaws.s3.exception import S3Error
from juju.lib.testing import TestCase
from juju.providers.ec2.tests.common import EC2TestMixin
class EC2StateTest(TestCase, EC2TestMixin):
def setUp(self):
EC2TestMixin.setUp(self)
sup... | tant_bucket(self):
"""
When loading saved state from s3, the system retur | ns False if the
s3 control bucket does not exist.
"""
self.s3.get_object(self.env_name, "provider-state")
error = S3Error("<error/>", 404)
error.errors = [{"Code": "NoSuchBucket"}]
self.mocker.result(fail(error))
self.mocker.replay()
provider = self.get_p... |
ISEAGE-ISU/cdc2-2015-www | isucdc2/urls.py | Python | mit | 469 | 0.008529 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'isucdc2 | .views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('cdc.urls', namespace="cdc")),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ | ROOT)
|
jyotsna1820/django | tests/get_or_create/models.py | Python | bsd-3-clause | 1,518 | 0.000659 | """
33. get_or_create()
``get_or_create()`` does what it says: it tries to look up an object with the
given parameters. If an object isn't found, it creates one with the given
parameters.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compa... | elf.last_name)
class DefaultPerson(models.Model):
first_name = models.CharField(max_length=100, default="Anonymous")
class ManualPrimaryKeyTest(models.Model):
id = models.IntegerField(primary_key=True)
data = models.CharField(max_length=100)
class Profile(models.Model):
person = models.ForeignKey(... | _length=256)
tags = models.ManyToManyField(Tag)
class Publisher(models.Model):
name = models.CharField(max_length=100)
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, ... |
mattvonrocketstein/smash | smashlib/plugins/cli_update.py | Python | mit | 1,850 | 0.004324 | """ smashlib.plugins.cli_update
The handler for "smash --update". This will default to
using whatever branch is already checked out
"""
from fabric import api
from goulash.python import splitext, ops
from smashlib import get_smash
from smashlib.util import CLOpt
from smashlib.plugins import Plugin
from smash... | self.run_update()
finally:
self.smash.shell.run_cell('exit')
def run_update(self):
""" """
smash_dir = data.SMASH_DIR
with api.lcd(smash_dir):
with api.settings(api.hide('warnings'), warn_only=True, quiet=True):
result = api.local('... | changed = (1 == result.return_code)
if changed:
error = "aborting due to local changes in {0}"
self.report(error.format(smash_dir))
else:
api.local('git pull')
api.local('./bin/pip install -r requirements.txt')
def load_... |
lizardsystem/lizard-blockbox | lizard_blockbox/management/commands/merge_measures_blockbox.py | Python | gpl-3.0 | 294 | 0 | from d | jango.core.management.base import BaseCommand
from lizard_blockbox import import_helpers
class | Command(BaseCommand):
args = ""
help = "Merge the measure shapes to get one json."
def handle(self, *args, **kwargs):
import_helpers.merge_measures_blockbox(self.stdout)
|
andydandy74/ClockworkForDynamo | nodes/1.x/python/Material.Properties.py | Python | mit | 540 | 0.02963 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
mats = UnwrapElement(IN[0])
colorlist = list()
glowlist = list()
classlist = list()
shinylist = list()
smoothlist = list()
translist = list()
for mat in mats:
colorlist.append(mat.Color)
if mat.Glow:
glowlist.append(T | rue)
else:
glowlist.append(False)
classlist.append(mat.MaterialClass)
shinylist.append(mat.Shininess)
smoothlist.append(mat.Smoothness)
translist.append(mat.Transparency)
OUT = (classlist,colorlist,glowlist,shinylist | ,smoothlist,translist) |
shifvb/DarkChina | http_proxy/tools/async_IO.py | Python | mit | 1,931 | 0.000518 | # The MIT License (MIT)
#
# Copyright shifvb 2015
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... | in_ is client:
out = target
else:
| out = client
if data:
# # debug
# if out == target:
# print('client->server {}\n'.format(data))
# else:
# print('server->client {}\n'.format(data))
out.send(data)
... |
meisamhe/GPLshared | Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/nonuniform_random_number_generation.py | Python | gpl-3.0 | 1,235 | 0 | import sys
import random
import collections
import itertools
import bisect
# @include
def nonuniform_random_number_generation(values, probabilities):
prefix_sum_of_probabilities = (
[0.0] + list(itertools.accumulate(probabilities)))
interval_idx = bisect.bisect(prefix_sum_of_probabilities,
... | generation(T, P))
# Test. Perform the nonuniform random number generation for n * k_times
# times and calculate the distribution of each bucket.
k_times = 100000
counts = collections.Counter(
int(nonuniform_random_number_generation(T, P))
for _ in range(n * k_times))
for i in range(n... | print(counts[i] / (n * k_times), P[i])
assert abs(counts[i] / (n * k_times) - P[i]) < 0.01
if __name__ == '__main__':
main()
|
pisceanfoot/py_easyXY | py_easyXY/datetime/tzone.py | Python | apache-2.0 | 309 | 0.038835 | """
def toLocal(dt, offset = 8):
dt: datetime
offset: default 8 china time
"""
import datetime
def toLocal(dt, offset = 8):
localDateTim | e = dt + datetime.timedelta(hours=offset)
return localDateTime
if __name__ = | = '__main__':
now = datetime.datetime.utcnow()
print now
print toLocal(now)
print now |
fdoray/tracecompare-benchmark | scripts/summary.py | Python | gpl-3.0 | 9,109 | 0.016797 | #!/usr/bin/env python3
#
# The MIT License (MIT)
#
# Copyright (C) 2015 - Francois Doray <francois.pierre-doray@polymtl.ca>
#
# 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 restricti... | _mean - base_mean) / NUM_ACTIONS,
100 * tracepoint_stddev / tracepoint_mean))
print('')
# Experiment: LIBUNWIND
def SummaryLibunwind(results_dir):
NUM_ACTIONS = 1
base = | GetFileMean(results_dir + '/libunwind-base.csv')
minregs = GetXYFileValues(results_dir + '/libunwind-optimal-withcache.csv')
minregs_nocache = GetXYFileValues(results_dir + '/libunwind-optimal-nocache.csv')
master_nocache = GetXYFileValues(results_dir + '/libunwind-nocache.csv')
base_stddev = GetXYFileStdDev(r... |
paridin/django-inplaceedit | testing/testing/example_extra_fields/urls.py | Python | lgpl-3.0 | 1,090 | 0.001835 | # Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> or <pmartin@yaco.es>
#
# 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 Foundation, either version 3 of the License, or
# (at your option)... | Public License for more details.
#
# You should have received a cop | y of the GNU Lesser General Public License
# along with this programe. If not, see <http://www.gnu.org/licenses/>.
try:
from django.conf.urls import include, patterns, url
except ImportError: # Django < 1.4
from django.conf.urls.defaults import include, patterns, url
urlpatterns = patterns('testing.example... |
Thraxis/pymedusa | sickbeard/indexers/indexer_exceptions.py | Python | gpl-3.0 | 1,776 | 0.003378 | # coding=utf-8
# URL: https://pymedusa.com
#
# This file is part of Medusa.
#
# Medusa 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.... | or, tvdb_userabort, tvdb_shownotfound, tvdb_showincomplete,
tvdb_seasonnotfound, tvdb_episodenotfound, tvdb_attributenotfound)
indexerExcepts = ["indexer_exception", "indexer_error", "indexer_userabort", "indexer_shownotfound", "indexer_showincomplete",
"indexer_... | ownotfound", "tvdb_showincomplete",
"tvdb_seasonnotfound", "tvdb_episodenotfound", "tvdb_attributenotfound"]
# link API exceptions to our exception handler
indexer_exception = tvdb_exception
indexer_error = tvdb_error
indexer_userabort = tvdb_userabort
indexer_attributenotfound = tvdb_attributenotfound
... |
skosukhin/spack | lib/spack/llnl/util/tty/color.py | Python | lgpl-2.1 | 9,290 | 0 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ed string will have no color.
``cwrite`` and ``cprint`` are equivalent to ``write()`` and ``print()``
calls in python, but they colorize their output. If the ``stream`` argument is
not supplied, they write to ``sys.stdout``.
Here are some example color expressions:
========== ======================================... | Turn on bright red coloring
@*{foo} Bold foo, but don't change text color
@_{bar} Underline bar, but don't change text color
@*b Turn on bold, blue text
@_B Turn on bright blue text with an underline
@. Revert to plain formatting
@*g{green} Print out 'green' in bold, green text, th... |
CarloNicolini/CarloNicolini.github.io | sections/science/_posts/example_cEWRG.py | Python | mit | 4,329 | 0.026565 | import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import root
import bct
eps = np.finfo(float).eps
def pij_wij(x,y,t):
xij = np.outer(x,x)
yij = np.outer(y,y)
pij = xij*((yij)**t)/(1.0+xij*(yij**t) - (yij**t))
wij = (t*(xij-1.0)*(yij**t))/((1.0 + xij*(yij**t) - (yij**t) )) - 1.0/(n... | imization result
plt.figure(figsize=(12,8))
plt.subplot(2,3,1)
im = plt.imshow(pij)
plt.colorbar(im,fraction=0.046, pad=0.04)
plt.grid(False)
plt.title('$p_{ij}$')
| plt.subplot(2,3,2)
im = plt.imshow(wij)
plt.colorbar(im,fraction=0.046, pad=0.04)
plt.grid(False)
plt.title('$<w_{ij}>$')
plt.subplot(2,3,3)
im = plt.imshow(W)
plt.colorbar(im,fraction=0.046, pad=0.04)
plt.grid(False)
plt.title('empirical matrix')
plt.subplot(2,3,4)
plt.... |
ICOS-Carbon-Portal/data | src/main/python/mongo-to-pg/Postgres.py | Python | gpl-3.0 | 1,006 | 0.033797 | from configparser import ConfigParser
import psycopg2
class Postgres(object):
def __init__(self, db_name):
filename = 'database.ini'
section = 'postgresql'
parser = ConfigParser()
parser.read(filename)
self.db = {}
if parser.has_section(section):
self.db['database'] = db_name
par... | onn = None
try:
self.conn = psycopg2.connect(**self.db)
self.cur = self.conn.cursor()
|
except (Exception, psycopg2.DatabaseError) as error:
print(error)
def close(self):
self.conn.close()
def execute(self, sql, params = ()):
self.cur.execute(sql, params)
self.conn.commit()
def get_version(self):
self.connect()
self.cur.execute('SELECT version()')
version = self.cur.... |
juanjux/python-driver | native/python_package/test/test_python_driver.py | Python | gpl-3.0 | 6,751 | 0.003555 | import io
import json
import os
import subprocess
import sys
import unittest
from os.path import join, abspath, dirname
sys.path.append('..')
from python_driver import __version__, get_processor_instance
from python_driver.requestprocessor import (
Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeExcept... | ults('json')
self.assertEqual(len(res), 1)
self.assertDictEqual(res[0] , {'driver': 'python23:%s' % __version__,
'errors': ['test error'],
'filepath': 'test.py',
'ast': None,
... | '__main__':
unittest.main()
|
bcarroll/authmgr | authmgr/tests/factories.py | Python | bsd-3-clause | 761 | 0 | # -*- coding: utf-8 -*-
"""F | actories to help in tests."""
from factory import PostGenerationMethodCall, Sequence
from factory.alchemy import SQLAlchemyModelFactory
from authmgr.database import db
from authmgr.user.models import User
class BaseFactory(SQLAlchemyModelFactory):
"""Base factory."""
class Meta:
"""Factory configura... | abstract = True
sqlalchemy_session = db.session
class UserFactory(BaseFactory):
"""User factory."""
username = Sequence(lambda n: 'user{0}'.format(n))
email = Sequence(lambda n: 'user{0}@example.com'.format(n))
password = PostGenerationMethodCall('set_password', 'example')
active = True
... |
163gal/Time-Line | libs/wx/tools/Editra/src/ebmlib/txtutil.py | Python | gpl-3.0 | 1,195 | 0.003347 | ######################################################################### | ######
# Name: txtutil.py #
# Purpose: Text Utilities. #
# Author: Cody Precord <cprecord@editra.org> #
# Copyright: (c) 2009 Cody Precord <staff@editra.org> ... | odel Library: Text Utilities
Utility functions for managing and working with text.
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: txtutil.py 62571 2009-11-08 17:53:27Z CJP $"
__revision__ = "$Revision: 62571 $"
__all__ = [ 'IsUnicode', ]
#---------------------------------------------------... |
rootulp/xpython | exercises/grains/grains.py | Python | mit | 56 | 0 | def | on_square():
pass
def total_after(): |
pass
|
anaslamaizi/Projet-ODOO | __init__.py | Python | artistic-2.0 | 160 | 0.00625 | # -*- coding: utf-8 -*-
import u | ser
import inscription
import notes
import util
import stage
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4 | : |
heavywatal/practice-py | Kazuki526/test.py | Python | mit | 16 | 0 | p | rint("tes | t\n")
|
hiezust/teask | website/migrations/0031_auto_20170601_1502.py | Python | gpl-3.0 | 1,475 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-06-01 12:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0030_github_user'),
]
operations = [
migrations.AddFi | eld(
model_name='linkedin_user',
name='number_all_repos',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='linkedin_user',
name='number_repos1',
field=models.IntegerField(default=0),
),
migra... | me='number_repos2',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='linkedin_user',
name='number_repos3',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='linkedin_user',
... |
alex/readthedocs.org | readthedocs/editor/models.py | Python | mit | 726 | 0.00551 | from django.db import models
class BranchManager(models.Manager):
def get_branch(self, user, project):
try:
return self.get(user=user, project=project, active=True)
except:
return self.create(us | er=user, project=project, active=True)
class Branch(models.Model):
user = models.F | oreignKey('auth.User')
project = models.ForeignKey('projects.Project')
active = models.BooleanField(default=True)
pushed = models.BooleanField(default=False)
title = models.TextField(default='')
comment = models.TextField(default='')
objects = BranchManager()
def __unicode__(self):... |
HurtowniaPixeli/pixelcms-server | cms/nav/apps.py | Python | mit | 176 | 0 | from django.apps import AppConfig
| from django.utils.translation import ugettext_lazy as _
| class NavConfig(AppConfig):
name = 'cms.nav'
verbose_name = _('Navigation')
|
apapiu/live_cnn | live_cnn/reusing_model.py | Python | apache-2.0 | 861 | 0.019744 | import sys
import os
import cv2
from keras.models import load_model
sys.path.append("/Users/alexpapiu/Documents/Conv/OpenCV_CNN")
from webcam_cnn_pipeline import return_compiled_model_2, real_time_pred
model_name = sys.argv[1]
w = 1.5*144
h = 2*144
#keep track of all labels:
all_labels = {"model_hand":["A", "B", "C... | ad", "normal"]}
labelz = dict(enumerate(all_labels[model_name]))
os.chdir("/Users/alexpapiu/Documents/Data/OpenCV_CNN")
model = return_compiled_model_2(input_shape = (3,int(h),int(w)),
num_class = len(labelz))
model.load_weights(model_name)
#open a new video:
cp = cv2.VideoCap... | model, labelz, cp = cp, nframes = 10000)
|
murrayo/yape | yapesrv/scripts/perfmon_tab.py | Python | mit | 3,197 | 0.001877 | # pandas and numpy for data manipulation
import pandas as pd
import numpy as np
import sqlite3
from bokeh.plotting import Figure
from bokeh.models import (
CategoricalColorMapper,
HoverTool,
ColumnDataSource,
Panel,
FuncTickFormatter,
SingleIntervalTicker,
LinearAxis,
)
from bokeh.models im... | xis_type="datetime",
title="perfmon",
output_backend="webgl",
)
cm = plt.get_cmap("gist_rainbow")
numlines = len(perfmon.columns)
mypal = [cm(1.0 * i / numlines) for i in range(numlines)]
mypal = list(map(lambda x: colors.rgb2hex(x), mypal))
col =... | key in src.data.keys():
if key == "datetime":
continue
l = key + " "
col = col + 1
cline = p.line(
perfmon.index.values,
perfmon[key],
line_width=1,
alpha=0.8,
color=mypal[col... |
facebookexperimental/eden | eden/scm/tests/test-issue1438-t.py | Python | gpl-2.0 | 789 | 0.001267 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# Copyright (c) Mercurial Contributors.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
from testutil.dott import feature, sh, | testtmp # noqa: F401
feature.require(["symlink"])
# https://bz.mercurial-scm.org/1438
sh % "hg init repo"
sh % "cd repo"
sh % "ln -s foo l | ink"
sh % "hg add link"
sh % "hg ci -mbad link"
sh % "hg rm link"
sh % "hg ci -mok"
sh % "hg diff -g -r '0:1'" > "bad.patch"
sh % "hg up 0" == "1 files updated, 0 files merged, 0 files removed, 0 files unresolved"
sh % "hg import --no-commit bad.patch" == "applying bad.patch"
sh % "hg status" == r"""
R link
... |
bpsinc-native/src_third_party_chromite | cbuildbot/stages/release_stages.py | Python | bsd-3-clause | 14,805 | 0.006754 | # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module containing the various stages that a builder runs."""
import json
import logging
import os
from chromite.cbuildbot import commands
from ch... | b
from chromite.lib import gs
from chromite.lib import osutils
from chromite.lib import parallel
from chromite.lib import timeout_util
class InvalidTestConditionException(Exception):
"""Raised when pre-conditions for a test aren't met."""
class SignerTestStage(artifact_stages.ArchivingStage):
"""Run signer rela... | s'
config_name = 'signer_tests'
# If the signer tests take longer than 30 minutes, abort. They usually take
# five minutes to run.
SIGNER_TEST_TIMEOUT = 1800
def PerformStage(self):
if not self.archive_stage.WaitForRecoveryImage():
raise InvalidTestConditionException('Missing recovery image.')
... |
pepeportela/edx-platform | openedx/core/djangoapps/course_groups/cohorts.py | Python | agpl-3.0 | 21,299 | 0.002535 | """
This file contains the logic for cohorts, as exposed internally to the
forums, and to the cohort admin views.
"""
import logging
import random
import request_cache
from courseware import courses
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.validat... | id, "cohort_name": cohort.name, "user_id": user_id}
for user_id in user_id_iter
for cohort in cohort_iter
)
action = kwargs["action"]
instance = kwarg | s["instance"]
pk_set = kwargs["pk_set"]
reverse = kwargs["reverse"]
if action == "post_add":
event_name = "edx.cohort.user_added"
elif action in ["post_remove", "pre_clear"]:
event_name = "edx.cohort.user_removed"
else:
return
if reverse:
user_id_iter = [instanc... |
iulian787/spack | var/spack/repos/builtin/packages/exuberant-ctags/package.py | Python | lgpl-2.1 | 532 | 0.005639 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class ExuberantCtags(AutotoolsPackage):
| """The canonical ctags generator"""
homepage = "http://ctags.sourceforge.net"
url = "http://downloads.sourceforge.ne | t/project/ctags/ctags/5.8/ctags-5.8.tar.gz"
version('5.8', sha256='0e44b45dcabe969e0bbbb11e30c246f81abe5d32012db37395eb57d66e9e99c7')
|
SivagnanamCiena/coding-skills-sample-code | coding102-REST-python/learning-lab-basics-step3.py | Python | apache-2.0 | 4,557 | 0.010753 | # Getting started with APIC-EM APIs
# Follows APIC-EM Basics Learning Lab
# Basics Learning Lab Full example for Get Devices, Get Hosts, Get Policies, Get Applications
# * THIS SAMPLE APPLICATION AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
# * OF ANY KIND BY CISCO, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT ... | ntroller as the base URL
# So lets define a variable | for the controller IP or DNS so we don't have to keep typing it
controller_url = "http://sandboxapic.cisco.com/"
# Get Devices
# This function allows you to view a list of all the devices in the network(routers and switches).
get_devices_url = controller_url + 'api/v0/network-device'
#Perform GET on get_devices_url ... |
EmbodiedCognition/pagoda | examples/cooper.py | Python | mit | 478 | 0 | # | !/usr/bin/env python
import click
import logging
import os
import pagoda
import pagoda.viewer
def full(name):
return os.path.join(os.path.dirname(__file__), name)
@click.command()
def main():
logging.basicConfig()
w = pagoda.cooper.World(dt=1. / 120)
w.load_skeleton(full('../optimi | zed-skeleton.txt'))
w.load_markers(full('cooper-motion.c3d'), full('../optimized-markers.txt'))
pagoda.viewer.Viewer(w).run()
if __name__ == '__main__':
main()
|
gwiedeman/eadmachine | source/EADtoSpreadsheet/func/dsc.py | Python | unlicense | 7,348 | 0.02613 | # module for the Container List <dsc>
import xml.etree.cElementTree as ET
from components import components
import globals
import wx
from messages import error
from mixed_content import mixed_content
def dsc(dsc_root, FASheet, version):
from wx.lib.pubsub import pub
wx.CallAfter(pub.sendMessage, "update_spread", msg... | nt.find('did').attrib['id']
else:
| ComponentNumber_element.text = mixed_content(component.find('did/unitid'))
if component.find('did/unittitle') is None:
pass
else:
ComponentName_element.text = mixed_content(component.find('did/unittitle'))
if cmpnt_count > 51:
pass
elif cmpnt_count == 51:
er... |
elationfoundation/overview_archive | overview_archive/utils/identify.py | Python | gpl-2.0 | 1,836 | 0.001635 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of overview archive.
# Copyr | ight © 2015 seamus tuohy, <stuohy@internews.org>
#
# This program is free software: you can redistribute it and/or | modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of ME... |
Xeralux/tensorflow | tensorflow/contrib/py2tf/pyct/static_analysis/live_values.py | Python | apache-2.0 | 4,891 | 0.008587 | # 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... | # * a symbol is new, like the new name of a function we just renamed.
else:
pass
# TODO(mdan): Attempt to trace its value through the local chain.
# TODO(mdan): Use type annotations as fallback.
if not symbol_is_modified:
if node.id in self.context.arg_values:
... | l', obj)
anno.setanno(node, 'fqn', (obj.__class__.__name__,))
return node
def visit_Attribute(self, node):
self.generic_visit(node)
if anno.hasanno(node.value, 'live_val'):
assert anno.hasanno(node.value, 'fqn')
parent_object = anno.getanno(node.value, 'live_val')
if not hasat... |
mmnelemane/neutron | neutron/tests/unit/plugins/ml2/drivers/mech_sriov/agent/extension_drivers/test_qos_driver.py | Python | apache-2.0 | 3,672 | 0.001362 | # Copyright 2015 Mellanox Technologies, 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 t... | _update_rule(self):
self.qos_driver.update(self.port, self.qos_policy)
self.max_rate_mock.assert_called_once_with(
self.ASSIGNED_MAC, self.PCI_SLOT, self.rule.max_kbps)
def test_delete_rules(self):
self.qos_driver.delete(self.port, self.qos_policy)
self.max_rate_mock.ass... | self.ASSIGNED_MAC, self.PCI_SLOT, 0)
def test__set_vf_max_rate_captures_sriov_failure(self):
self.max_rate_mock.side_effect = exceptions.SriovNicError()
self.qos_driver._set_vf_max_rate(self.ASSIGNED_MAC, self.PCI_SLOT)
def test__set_vf_max_rate_unknown_device(self):
with m... |
satyammittal/sample-platform | mod_customized/controllers.py | Python | isc | 5,822 | 0.002233 | """
mod_customized Controllers
===================
In this module, users can test their fork branch with customized set of regression tests
"""
from flask import Blueprint, g, request, redirect, url_for, flash
from github import GitHub, ApiError
from datetime import datetime, timedelta
from decorators import template_... | eir repo that are not more than 30 days old.
User can customized test based on selected regression tests and platforms.
Also Display list of customized tests started by user.
User will be redirected to the same page on submit.
"""
fork_test_form = TestForkForm(request.form)
username ... | =g.github['bot_token'])
repository = gh.repos(username)(g.github['repository'])
# Only commits since last month
last_month = datetime.now() - timedelta(days=30)
commit_since = last_month.isoformat() + 'Z'
commits = repository.commits().get(since=commit_since)
commit_arr =... |
naturalness/unnaturalcode | unnaturalcode/test_eclipse.py | Python | agpl-3.0 | 1,489 | 0.012089 | #!/usr/bin/python
# Copyright 2017 Dhvani Patel
#
# This file is part of UnnaturalCode.
#
# UnnaturalCode 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 Licen... | FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with UnnaturalCode. If not, see <http://www.gnu.org/licenses/>.
from check_eclipse_syntax import checkEclipseSyntax
from compi | le_error import CompileError
import unittest
ERROR_TEST = """public class HelloWorld {
public static void main(String[] args)
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World)
}
}
"""
class TestStringMethods(unittest.TestCase):
def test_syntax_ok(self):
... |
gtamazian/bioformats | bioformats/synteny_plot.py | Python | mit | 10,165 | 0.000197 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
# Gaik Tamazian, 2019
# mail (at) gtamazian (dot) com
"""Routines for producing synteny plots."""
import gzip
import sys
from functools import reduce
from operator import itemgetter
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patch... | block edge
:param f_color: color the block is filled in
:param p: a plotting parameter; its value should be between 150 and
300
:returns: the list of the AxesSubplot objects with the added synteny
block
"""
global_x_max = reduce(max, map(lambda x: x.get_xlim()[1], axes))
alpha = ... | ax = axes[chr_dict[chrom]]
_, x_max = ax.get_xlim()
y_min, _ = ax.get_ylim()
assert strand is None or strand in {'+', '-'}, "incorrect strand"
l |
ruibarreira/linuxtrail | usr/lib/python2.7/dist-packages/numpy/distutils/__config__.py | Python | gpl-3.0 | 1,269 | 0.020489 | # This file is generated by /tmp/buildd/python-numpy-1.8.2/setup.py
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
blas_info={'libraries': [ | 'blas'], 'library_dirs': ['/usr/lib'], 'language': 'f77'}
lapack_info={'libraries': ['lapack'], 'library_dirs': ['/usr/lib'], 'language': 'f77'}
atlas_threads_info={}
blas_opt_info={'libraries': ['blas'], 'library_dirs': ['/usr/lib'], 'define_macros': [('NO_ATLAS_INFO', 1)], 'language': 'f77'} |
openblas_info={}
atlas_blas_threads_info={}
lapack_opt_info={'libraries': ['lapack', 'blas'], 'library_dirs': ['/usr/lib'], 'define_macros': [('NO_ATLAS_INFO', 1)], 'language': 'f77'}
atlas_info={}
lapack_mkl_info={}
blas_mkl_info={}
atlas_blas_info={}
mkl_info={}
def get_info(name):
g = globals()
return g.ge... |
rlworkgroup/metaworld | metaworld/envs/mujoco/sawyer_xyz/v2/sawyer_hammer_v2.py | Python | mit | 5,835 | 0.000343 | import numpy as np
from gym.spaces import Box
from | metaworld.envs import reward_utils
from metaworld.envs.asset_path_utils import full_v2_path_for
from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set
class SawyerHammerEnvV2(SawyerXYZEnv):
HAMMER_HANDLE_LENGTH = 0.14
def __init__(self):
hand_low = (-0.5, 0.40, ... | , 0.4, 0.0)
obj_high = (0.1, 0.5, 0.0)
goal_low = (0.2399, .7399, 0.109)
goal_high = (0.2401, .7401, 0.111)
super().__init__(
self.model_name,
hand_low=hand_low,
hand_high=hand_high,
)
self.init_config = {
'hammer_init_pos... |
xiviwo/baiducloud | const.py | Python | gpl-3.0 | 977 | 0.012282 | from random import randint
import os
PAN_HOST = "pan.baidu.com"
PAN_INDEX = "http://" + PAN_HOST
DISK_HOME = PAN_INDEX + '/disk/home'
FILE_MANAGER = PAN_INDEX + "/api/filemanager"
CLOUD_DL = PAN_INDEX + "/rest/2.0/services/cloud_dl"
PASSPORT_HOST = 'passport.baidu.com'
PASSPORT_INDEX = "https://" + PASSPORT_HOST
PASS | PORT_API = PASSPORT_INDEX + "/v2/api"
USERAGENTLIST = [ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Saf | ari/537.36',
'Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',]
USERAGENT = USERAGENTLIST[randint(0,len(USERAGENTLIST)-1)]
GREEN = u"\033[42m%s\033[m"
BLUE = u"\033[44m%s\033[m"
RED = u"... |
qisanstudio/qsapp-suibe | src/suibe/panel/article.py | Python | mit | 2,836 | 0.000724 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from wtforms import validators
from jinja2 import Markup
from flask.ext.admin.contrib.sqla import ModelView
from studio.core.engines import db
from suibe.models import SlideModel, ArticleModel
from .forms import CKTextAreaField
class Article(ModelView)... | 'describe': '描述',
'image': '图片链接',
'link': '链接',
'date_created': '创建时间'}
column_list = ['id', 'order', 'title', 'describe', 'image', 'link', 'date_created']
column_default_sort = ('order', True)
form_args = {
| 'image': {'label': '图片', 'validators': [validators.Required(),
validators.URL()]},
'link': {'label': '链接', 'validators': [validators.Required(),
validators.URL()]},
}
def _show_image(self, context, mode... |
Johnetordoff/osf.io | addons/mendeley/tests/test_views.py | Python | apache-2.0 | 1,232 | 0.004058 | # -*- coding: utf-8 -*-
import mock
import pytest
from future.moves.urllib.parse import urlparse, urljoin
from addons.base.tests import views
from addons.base.tests.utils import MockFolder
from addons.mendeley.models import Mendeley
from addons.mendeley.tests.utils import MendeleyTestCase, mock_responses
from tests.b... | Case
from addons.mendeley.provider import MendeleyCitationsProvider
from addons.mendeley.serializer import MendeleySerializer
API_URL = 'https://api.mendeley.com'
pytestmark = pytest.mark.django_db
class TestAuthViews(MendeleyTestCase, views.OAuthAddonAuthViewsTestCaseMixin, OsfTestCase):
pass
class TestConfigV... | ()
Serializer = MendeleySerializer
client = Mendeley
citationsProvider = MendeleyCitationsProvider
foldersApiUrl = urljoin(API_URL, 'folders')
documentsApiUrl = urljoin(API_URL, 'documents')
mockResponses = mock_responses
@mock.patch('addons.mendeley.models.NodeSettings._fetch_folder_name',... |
espressomd/espresso | samples/visualization_cellsystem.py | Python | gpl-3.0 | 2,509 | 0.000399 | # Copyright (C) 2010-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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 v... | nergy()
print( | f"After Minimization: E_total = {energy['total']:.2e}")
print("Tune skin")
system.cell_system.tune_skin(0.1, 4.0, 1e-1, 1000)
print(system.cell_system.get_state())
system.thermostat.set_langevin(kT=1, gamma=1, seed=42)
visualizer.run(1)
|
labase/activnce | main/activity/database.py | Python | gpl-2.0 | 5,622 | 0.012132 | # -*- coding: utf-8 -*-
"""
################################################
Plataforma ActivUFRJ
################################################
:Author: *Núcleo de Computação Eletrônica (NCE/UFRJ)*
:Contact: carlo@nce.ufrj.br
:Date: $Date: 2009-2010 $
:Status: This is a "work in progress"
:Revision: $Revision: 0.0... | if (doc.type=="group" ) {
emit([doc.registry_id, doc._id, doc.data_cri, 0], doc);
| }
}
''')
activity_pendent = ViewDefinition('activity', 'pendent', \
'''
function(doc) {
if (doc.type=="activity" && (!... |
alternativehood/toasyncio | setup.py | Python | mit | 897 | 0.003344 | # encoding: utf-8
from setuptools import setup, find_packages
import toasyncio
setup(
name='toasyncio',
packages=find_packages(exclude=['tests']),
install_requires=(
'tornado>=4.2',
'asyncio',
),
author=toasyncio.__author__,
version=toasyncio.__version__,
author_email=", ".j... | ,
license='MIT',
keywords=(
"tornado",
"asyncio",
),
url='https://github.com/mosquito/toasyncio',
description='Transparent convert any asyncio futures and inline yield methods to tornado futures.',
zip_safe=False,
classifiers=[
'Environment :: Console',
'Progr... | Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
) |
rdhyee/dlab-finance | crossings/nbboex.py | Python | isc | 5,138 | 0.011872 | # Project : Dlab-Finance
# W251 Nital Patwa and Ritesh Soni
# Desc : This program counts for each exchange, the #of times it produced best bid (or ask) and average size of bid (or ask)
# The purpose is to understand what roles exchanges such as BATS play.
# Usage Instructions
# Change inputDir for daily quote file and ... | ((list1[i][2] == 0) or (list1[i][8] == 'B')):
bidList[exchangeList.index(list1[i][6])] = 0
bidSize[exchangeList.index(list1[i][6])] = 0 # size
if ((list1[i][4] != 0) & (list1[i][5] != 0)):
askList[exchangeList.index(list1[i][7])] = list1[i][4]
askSize[exchangeLis... | changeList.index(list1[i][7])] = 0
for j in range(len(exchangeList)):
if (bbExCnt[j] > 0):
bbExSize[j] = bbExSize[j]/bbExCnt[j]
if (baExCnt[j] > 0):
baExSize[j] = baExSize[j]/baExCnt[j]
nbboList.append((record[0],(bbExCnt, bbExSize, baExCnt, baExSize)))
return ... |
peterwilletts24/Python-Scripts | Tephigram/Tephigrams_From_Radiosonde_Climatology_Onset.py | Python | mit | 11,003 | 0.020813 | # Now make a simple example using the custom projection.
import pdb
import sys
import os
import pkg_resources
pkg_resources.require('matplotlib==1.4.0')
import datetime
from dateutil.relativedelta import relativedelta
import re
import math
from matplotlib.ticker import ScalarFormatter, MultipleLocator
from matplotlib... | 0,9),P,color='k',ls='-',alpha=.5,lw=0.8)
ax.add_moist_adiabats(linspace(-40,40,18),P,color='k',ls='--',alpha=.5,lw=0.8, do_labels=False)
ax.other_housekeeping(pmax, pmin, 40,-40)
wbax = fig.add_axes([0.75,tephigram_plot_bottom,0.12,tephigram_plot_height],frameon=False, sharey=ax, l... | fig.add_axes([0.85,0.085,.12,tephigram_plot_height], frameon=False, axisbg='w')
# Plot the data using normal plotting functions, in this case using semilogy
ax.semilogy(T, p, 'r', linewidth=2)
ax.semilogy(Td, p, 'r',linewidth=2)
# row_labels=(
# ... |
bowlofstew/changes | changes/api/task_index.py | Python | apache-2.0 | 268 | 0 | f | rom __future__ import absolute_import
from changes.api.base import APIView
from changes.models import Task
class TaskIndexAPIView(APIView):
def get(self):
queryset = Task.query.order_by(Task.date_created.desc())
r | eturn self.paginate(queryset)
|
mathgl67/pymmr | mmr/plugins/research/freedb.py | Python | gpl-2.0 | 2,675 | 0.003364 | #!/usr/bin/env python
# vi:ai:et:ts=4 sw=4
#
# -*- coding: utf8 -*-
#
# PyMmr My Music Renamer
# Copyright (C) 2007-2010 mathgl67@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, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WA | RRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51... |
laurentb/weboob | modules/bp/pages/__init__.py | Python | lgpl-3.0 | 1,981 | 0.003029 | # -*- coding: utf-8 -*-
# Copyrigh | t(C) 2010-2011 Nicolas Duhamel
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or |
# (at your option) any later version.
#
# This weboob module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have recei... |
teltek/edx-platform | lms/djangoapps/mobile_api/users/tests.py | Python | agpl-3.0 | 20,030 | 0.002646 | """
Tests for users API
"""
import datetime
import ddt
import pytz
from django.conf import settings
from django.template import defaultfilters
from django.test import RequestFactory, override_settings
from django.utils import timezone
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import patch
f... | = CourseFactory.create()
set_prerequisite_courses(course_with_prereq.id, [unicode(prerequisite_course.id)])
# Create list of courses with various expected courseware_access responses and corresponding expected codes
courses = [
course_with_prereq,
CourseFactory.create(s... | True),
CourseFactory.create(visible_to_staff_only=True, mobile_available=True),
CourseFactory.create(start=self.LAST_WEEK, mobile_available=True, visible_to_staff_only=False),
]
expected_error_codes = [
MilestoneAccessError().error_code, # 'unfulfilled_milestones'
... |
shield-h2020/dare-sec-topo | cybertop/vnsfo.py | Python | apache-2.0 | 1,650 | 0.000606 | # Copyright 2018 Politecnico di Torino
#
# 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... | vnsfs = response.json()["vnsf"]
# | search for first running instance which matches the query
for vnsf in vnsfs:
target_vnf = vnsf['vnfd_id'][:-5].lower()
if vnfd_id[:-5].lower() in target_vnf and attack_name.lower() in target_vnf:
LOG.info("Found instance=" + vnsf['vnfr_id'] +
" f... |
morphean/deep-learning | linear-regression/linear-regression.py | Python | apache-2.0 | 380 | 0.005263 | import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt
df = pd.read_fwf('brain_body.txt')
x_values = df[['Brain']]
y_values = df[['Bo | dy']]
| #train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)
# visualise results
plt.scatter(x_values, y_values)
plt.plot(x_values, body_reg.predict(x_values))
plt.show() |
kmolab/kmolab.github.io | data/py/script1.py | Python | agpl-3.0 | 2,826 | 0.008922 | import sys
import time
import traceback
import javascript
from browser import document as doc, window, alert
has_ace = True
try:
editor = window.ace.edit("editor")
session = editor.getSession()
session.setMode("ace/mode/python")
editor.setOptions({
'enableLiveAutocompletion': True,
'enableS... | fo.minor, info.micro)
output = ''
def show_console(ev):
doc["console"].value = output
doc["console"].cols = 60
doc["console"].rows = 10
# load a Python script
def load_script(evt):
_name = evt.target.value + '?foo=%s' % time.time()
editor.setValue(open(_name).read())
# run a script, in global na... |
doc["console"].value = ''
src = editor.getValue()
if storage is not None:
storage["py_src"] = src
t0 = time.perf_counter()
try:
#ns = {'__name__':'__main__'}
ns = {'__name__':'editor'}
exec(src, ns)
state = 1
except Exception as exc:
traceback.pri... |
ckane/crits | crits/vocabulary/relationships.py | Python | mit | 4,362 | 0.000688 | from crits.vocabulary.vocab import vocab
class RelationshipTypes(vocab):
"""
Vocabulary for Relationship Types.
"""
COMPRESSED_FROM = "Compressed From"
COMPRESSED_INTO = "Compressed Into"
CONNECTED_FROM = "Connected From"
CONNECTED_TO = "Connected To"
CONTAINS = "Contains"
CONTA... | BY:
return cls.DECODED
elif relationship == cls.DECRYPTED:
return cls.DECRYPTED_BY
elif relationship == cls.DECRYPTED_BY:
return cls.DECRYPTED
elif relationship == cls.DOWNLOADED:
return cls.DOWNLOADED_BY
elif relationship == cls.DOWNLOADED... | ls.DOWNLOADED_TO
elif relationship == cls.DOWNLOADED_TO:
return cls.DOWNLOADED_FROM
elif relationship == cls.DROPPED:
return cls.DROPPED_BY
elif relationship == cls.DROPPED_BY:
return cls.DROPPED
elif relationship == cls.INSTALLED:
return c... |
samdmarshall/pyxcscheme | pyxcscheme/ProfileAction.py | Python | bsd-3-clause | 611 | 0.018003 | from .Base_Action import *
class ProfileAction(Base_Action):
def __init__(self, action_xml, root_action=None):
super(self.__class__, self).__init__(action_xml, root_action)
self.shouldUseLaunchS | chemeArgsEnv = self.contents.get('shouldUseLaunchSchemeArgsEnv');
self.savedToolIdentifier = self.contents.get('savedToolIdentifier');
| self.useCustomWorkingDirectory = self.contents.get('useCustomWorkingDirectory');
self.buildConfiguration = self.contents.get('buildConfiguration');
self.debugDocumentVersioning = self.contents.get('debugDocumentVersioning'); |
caterinaurban/Typpete | typpete/tests/scion_err/lib/defines.py | Python | mpl-2.0 | 4,117 | 0.000729 | # Copyright 2015 ETH Zurich
#
# 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 la | w or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
:mod:`defines` --- Constants
=====... | a PathSegment in realtime seconds.
# TODO(shitz): This value should be externally configurable. The problem is that
# the revocation hash tree TTL needs to be at least as large as MAX_SEGMENT_TTL,
# but having a TTL of 1 day makes the hash tree generation costly enough that it
# times out on CircleCI. Thus, we should ... |
BorgERP/borg-erp-6of3 | server/openerp/workflow/wkf_expr.py | Python | agpl-3.0 | 3,130 | 0.007348 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it | and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without eve... | of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import sys
import openerp.netsvc as netsvc
import openerp.osv as base
import openerp.pooler as pooler
from openerp.t... |
JakubBrachTieto/openthread | tests/scripts/thread-cert/Cert_5_6_01_NetworkDataRegisterBeforeAttachLeader.py | Python | bsd-3-clause | 4,513 | 0.000665 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | self.nodes[SED1].enable_whitelist()
self.nodes[SED1].set_timeout(3)
def tearDown(self):
for node in list(self.nodes.values()):
node.stop()
del self.nodes
def test(self):
self.nodes[LEADER].start()
self.nodes[LEADER].set_state('leader')
self.assertEq... | self.nodes[LEADER].get_state(), 'leader')
self.nodes[LEADER].add_prefix('2001:2:0:1::/64', 'paros')
self.nodes[LEADER].add_prefix('2001:2:0:2::/64', 'paro')
self.nodes[LEADER].register_netdata()
self.nodes[ROUTER].start()
time.sleep(5)
self.assertEqual(self.nodes[ROUTER... |
BateauNautilus/DriveSimulator | lib/pythoncan/examples/virtual_can_demo.py | Python | mit | 822 | 0.006083 | """
This demo creates multiple processes of Producers to spam a socketcan bus.
"""
import time
import logging
import concurrent.futures
import | can
can.rc['interface'] = 'socketcan_native'
from can.interfaces.interface import Bus
can_interface = 'vcan0'
def producer(id):
""":param id: Spam the bus with messages including the data id."""
bus = Bus(can_interface)
for i in range(16):
msg = can.Message(arbitration_id=0x0cf02200, data=[id, i... | , 4, 1])
bus.send(msg)
# TODO Issue #3: Need to keep running to ensure the writing threads stay alive. ?
time.sleep(2)
if __name__ == "__main__":
#logging.getLogger('').setLevel(logging.DEBUG)
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
executor.map(producer,... |
iw3hxn/LibrERP | res_users_kanban/models/inherit_res_users.py | Python | agpl-3.0 | 2,957 | 0.005749 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2017 Didotech SRL
import logging
from openerp.osv import fields, orm
import tools
from openerp import addons
_logger = logging.getLogger(__name__)
... | "resized as a 128x128px image, with aspect ratio preserved. "\
"Use this field in form views or some kanban views."),
'image_small': fields.function(_get_image, fnct_inv=_set_image,
string="Small-sized image", type="binary", multi="_get_image",
store={
... | s a 64x64px image, with aspect ratio preserved. "\
"Use this field anywhere a small image is required."),
'has_image': fields.function(_has_image, type="boolean"),
}
_defaults = {
'image': lambda self, cr, uid, ctx={}: self._get_default_image(cr, uid, ctx),
}
# vim:expand... |
lil-cain/satori | satori/sysinfo/ohai.py | Python | apache-2.0 | 109 | 0 | " | ""."""
def get_systeminfo(resource, config, interactive=False):
"""."""
return {' | ohai': 'there!'}
|
akosyakov/intellij-community | python/testData/refactoring/pullup/abstractMethodHasMeta/SuperClass.after.py | Python | apache-2.0 | 215 | 0.004651 | from abc import ABCMeta, abstractmethod
class Parent(obj | ect):
__metaclass__ = ABCMeta
@abstractmethod
def my_meth | od2(self):
pass
@abstractmethod
def my_method(self, foo):
pass |
0101/django-pytest | django_pytest/conftest.py | Python | bsd-3-clause | 3,390 | 0.00236 | import os, sys
from fu | nctools import partial
if 'DJANGO_SETTINGS_MOD | ULE' not in os.environ:
sys.path.append('.')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
from django.test.client import Client
from django.test.utils import setup_test_environment, teardown_test_environment
from django.core.management import call_command
from django.core i... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/api_server.py | Python | bsd-3-clause | 33,071 | 0.006108 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | import channel_service_stub
from google.appengine.api.files import file_service_stub
from google.appengine.api.logservice import logservice_stub
from google.appengi | ne.api.search import simple_search_stub
from google.appengine.api.taskqueue import taskqueue_stub
from google.appengine.api.prospective_search import prospective_search_stub
from google.appengine.api.memcache import memcache_stub
from google.appengine.api.system import system_stub
from google.appengine.api.xmpp import ... |
feist/pcs | pcs/daemon/run.py | Python | gpl-2.0 | 4,728 | 0 | import os
import signal
import socket
from pathlib import Path
from tornado.ioloop import IOLoop
from tornado.locks import Lock
from tornado.web import Application
from pcs import settings
from pcs.daemon import log, ruby_pcsd, session, ssl, systemd
from pcs.daemon.app import sinatra_ui, sinatra_remote, ui
from pcs.d... | ver_name=socket.gethostname(),
cert_location=settings.pcsd_cert_location,
key_location=settings.pcsd_key_location,
ssl_options=env.PCSD_SSL_OPTIONS,
ssl_ciphers=env.PCSD_SSL_CIPHERS,
)
try:
SignalInfo.server_manage = HttpsServerManage(
make_app,
po... | socket.gaierror as e:
log.pcsd.error(
"Unable to bind to specific address(es), exiting: %s ", e
)
raise SystemExit(1) from e
except OSError as e:
log.pcsd.error("Unable to start pcsd daemon, exiting: %s ", e)
raise SystemExit(1) from e
except ssl.SSLCertKeyExc... |
Alamot/code-snippets | encodings/test_encodings.py | Python | unlicense | 4,814 | 0.00187 | #!/usr/bin/env python
'''
*******************************************************************************
Description: This tool can help you determine the character
encoding of a text file by converting one line from
the file to every(?) possible character encoding.
It wri... | tten.\n")
if __name__ == '__main__':
na | rgs = len(sys.argv)-1
if nargs < 1 or nargs > 2:
exit("Usage: test_encodings.py filename [number of line to test]")
if nargs == 2:
line_number = int(sys.argv[2])
else:
line_number = 1
write_encodings(sys.argv[1], line_number, 'utf_8')
|
mikesun/xen-cow-checkpointing | tools/pygrub/src/LiloConf.py | Python | gpl-2.0 | 4,887 | 0.006753 | #
#LiloConf.py
#
import sys, re, os
import logging
import GrubConf
class LiloImage(object):
def __init__(self, lines, path):
self.reset(lines, path)
def __repr__(self):
return ("title: %s\n"
" root: %s\n"
" kernel: %s\n"
" args: %s\n"
| " initrd: %s\n" %(self.title, self.root, self.kernel,
self.args, self.initrd))
def reset(self, lines, path):
self._initrd = self._kernel = self._readonly = None
self._args = ""
self.title = ""
self.lines = []
self.path = pat... | rom_line(self, line, replace = None):
(com, arg) = GrubConf.grub_exact_split(line, 2)
if self.commands.has_key(com):
if self.commands[com] is not None:
setattr(self, self.commands[com], re.sub('^"(.+)"$', r"\1", arg.strip()))
else:
logging.info("I... |
deepmind/open_spiel | open_spiel/python/algorithms/adidas_utils/games/big.py | Python | apache-2.0 | 4,268 | 0.005155 | # Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | for each player
Returns:
np.array (length num players) of payoffs
"""
return self.pt[tuple([slice(None)] + policies)]
def best_response(self, mixed_strategy, return_exp=False):
"""Return best response and its superiority over the current strategy.
Args:
mixed_strategy: np.ndarray (d... | bool, whether to return how much best response exploits the
given mixed strategy (default is False)
Returns:
br: int, index of strategy (ties split randomly)
exp: u(br) - u(mixed_strategy)
"""
logging.warn("Assumes symmetric game! Returns br for player 0.")
gradient = misc.pt_reduce... |
bacemtayeb/Tierra | src/modules/services/smb.py | Python | gpl-3.0 | 8,923 | 0.001121 | import socket
import struct
import sys
import util
from threading import Thread
from service import Service
class smb(Service):
def __init__(self):
super(smb, self).__init__('SMB Service')
self.config['port'].value = 445
self.captured_hashes = {}
self.info = """
... | truct.unpack('<h', data[46:48])[0]
host_offset = struct.unpack('<I', data[48:52])[0]
lm_hash = ntlm_hash = ''
# LM hash
for i in data[lm_offset:lm_offset + 24]:
tmp = str(hex(ord(i))).replace('0x', '')
if le | n(tmp) is 1:
# hex() removes leading 0's in hex; we need them.
tmp = '0' + tmp
lm_hash += tmp
# NTLM hash
for i in data[ntlm_offset:ntlm_offset + 24]:
tmp = str(hex(ord(i))).replace('0x', '')
if len(tmp) is 1:
tmp = '0' ... |
wangy1931/tcollector | collectors/builtin/map_reduce.py | Python | lgpl-3.0 | 11,834 | 0.003634 | import time
import requests
from collectors.lib import utils
from collectors.lib.collectorbase import CollectorBase
# reference by https://hadoop.apache.org/docs/r2.7.2/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapredAppMasterRest.html
REST_API = {"YARN_APPS_PATH": "ws/v1/cluster/apps",
"MAPREDU... | e_job_metrics(self, running_apps):
'''
Get metrics for each MapReduce job.
Return a dictionary for each MapReduce job
{
job_id: {
'job_name': job_name,
'app_name': app_name,
'user_name': user_name,
'tracking_url': tracking_url
... | y:
running_jobs = {}
for app_id, (app_name, tracking_url) in running_apps.iteritems():
ts = time.time()
metrics_json = self.request_url("%s%s" % (tracking_url,REST_API['MAPREDUCE_JOBS_PATH']))
if metrics_json.get('jobs'):
if met... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.