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 |
|---|---|---|---|---|---|---|---|---|
edx/edx-notifications | testserver/forms.py | Python | agpl-3.0 | 1,437 | 0.007655 | import re
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Username"), error_mess... | )
password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, re | nder_value=False)), label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))
def clean_username(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
... |
c4sc/arividam | config/wsgi.py | Python | mit | 1,445 | 0 | """
WSGI config for arividam project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... | s.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()
# Ap | ply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
3dfxsoftware/cbss-addons | smile_access_control/res_group.py | Python | gpl-2.0 | 4,958 | 0.003025 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under th... | #########################
from osv import osv
class IrModel(osv.osv):
_inherit = 'ir.model'
def _get_first_level_relations(self, cr, uid, ids, context):
field_obj = self.pool.get('ir.model.fields')
field_ids = field_obj.search(cr, uid, [
('ttype', 'in', ('many2one', 'one2many', '... | s, ['relation'], context=None)]
return self.search(cr, uid, [('model', 'in', models)], context=context)
return []
def get_relations(self, cr, uid, ids, level=1, context=None):
"""
Return models linked to models given in params
If you don't want limit the relations level,... |
landism/pants | src/python/pants/java/nailgun_client.py | Python | apache-2.0 | 7,580 | 0.010818 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import errno
import ... | f._session.remote_pid is not None:
os.kill(self._session.remote_pid, signal.SIGINT)
def exec | ute(self, main_class, cwd=None, *args, **environment):
"""Executes the given main_class with any supplied args in the given environment.
:param string main_class: the fully qualified class name of the main entrypoint
:param string cwd: Set the working directory for this command
:param list args: any ar... |
plotly/python-api | packages/python/plotly/plotly/validators/densitymapbox/colorbar/_ticksuffix.py | Python | mit | 485 | 0.002062 | import _pl | otly_utils.basevalidators
class TicksuffixValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="ticksuffix", parent_name="densitymapbox.colorbar", **kwargs
):
super(TicksuffixValidator, self).__init__(
plotly_name=plotly_name,
parent_... | rgs
)
|
jniemann66/ReSampler | android/src/libsndfile/Scripts/cstyle.py | Python | lgpl-2.1 | 8,137 | 0.057638 | #!/usr/bin/python -tt
#
# Copyright (C) 2005-2017 Erik de Castro Lopo <[email protected]>
#
# Released under the 2 clause BSD license.
"""
This program checks C code for compliance to coding standards used in
libsndfile and other projects I run.
"""
import re
import sys
class Preprocessor:
"""
Preprocess lines ... | missing space after close square brace" )
, ( re.compile ("\[ "), "space after open square brace" )
, ( re.compile (" \]"), "space before close square brace" )
# Space around operators.
, ( re.compile ("[^\s] | [\*/%+-][=][^\s]"), "missing space around opassign" )
, ( re.compile ("[^\s][<>!=^/][=]{1,2}[^\s]"), "missing space around comparison" )
# Parens around single argument to return.
, ( re.compile ("\s+return\s+\([a-zA-Z0-9_]+\)\s+;"), "parens around return value" )
# Parens around single case argument.
... |
kalaspuff/tomodachi | tests/test_invalid_services.py | Python | mit | 1,285 | 0.003891 | from typing import Any
import pytest
from run_test_service_helper import start_service
def test_invalid_filename(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SystemExit):
services, future = start_service("tests/services/no_servi | ce_existing.py", monkeypatch)
out, err = capsys.readouterr()
assert "Invalid service, no such service" in err
def test_invalid_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(NameError):
services, future = start_service("tests/services/invalid_se | rvice.py", monkeypatch)
out, err = capsys.readouterr()
assert "Unable to load service file" in err
def test_syntax_error_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SyntaxError):
services, future = start_service("tests/services/syntax_error_service.py", monkeypat... |
loles/solar | examples/riak/riaks.py | Python | apache-2.0 | 9,183 | 0.003594 | #!/usr/bin/env python
# To run:
# python example-riaks.py deploy
# solar changes stage
# solar changes process
# solar orch run-once last
# python example-riaks.py add_haproxies
# solar changes stage
# solar changes process
# solar orch run-once last
import click
import sys
from solar.core import resource
from sola... | sc_http):
single_hpsc.connect(single_hpc, {"backends": "config:backends",
"listen_po | rt": "config:listen_port",
"protocol": "config:protocol",
"name": "config:name"})
for single_hpc, single_hpsc in zip(hpc, hpsc_pb):
single_hpsc.connect(single_hpc, {"backends": "config:backends",
... |
bert/geda-gaf | xorn/src/python/geda/netlist/pp_hierarchy.py | Python | gpl-2.0 | 6,338 | 0.001104 | # xorn.geda.netlist - gEDA Netlist Extraction and Generation
# Copyright (C) 1998-2010 Ales Hvezda
# Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details)
# Copyright (C) 2013-2017 Roland Lutz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Genera... | if len(port.cpins) > 1:
port.error(_("multiple pins on I/O symbol"))
continue
ports.append(port)
if not ports:
cpin.warn(_("missing | I/O symbol for port `%s' "
"inside schematic") % label)
elif len(ports) > 1:
cpin.warn(_("multiple I/O symbols for port `%s' "
"inside schematic") % label)
for port in ports:
src_net = port.cpins[0].local_n... |
xi4nyu/mango_task | tasks/demo2.py | Python | gpl-2.0 | 314 | 0.012739 | # coding: utf-8
"""Demo2
"""
from common.task_base import TaskBase
class DemoTa | sk2(TaskBase):
def __call__(self):
print "demo2 was called."
@property
def desc(self):
return "demo2"
@property
def cron(self):
return | dict(day_of_week="mon-fri", second=2)
|
thruflo/pyramid_torque_engine | setup.py | Python | unlicense | 1,368 | 0.019737 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'pyramid_torque_engine',
version = '0.5.4',
description = 'Pyramid and nTorque based dual queue work engine system.',
author = 'James Arthur',
author_email = 'username: thruflo, domain: gmail.co... | s_require = [
'coverage',
'nose',
'mock'
],
entry_points = {
'console_scripts': [
'engine_notification = pyramid_t | orque_engine.notification_table_executer:run'
]
}
)
|
miller-tamil/research_on_email_marketting | web1_ads/Line_separator.py | Python | apache-2.0 | 144 | 0.006944 | lines = open('line.txt', 'r').readlines()
lines_set = set(lines)
out = open | ('workfile.txt', 'w')
for line in lines_se | t:
out.write(line)
|
vimalkumarvelayudhan/riboplot | tests/test_riboplot.py | Python | bsd-3-clause | 7,454 | 0.003488 | import os
import shutil
import logging
import unittest
import tempfile
fro | m riboplot import ribocore, riboplot
# use testing configuration
CFG = riboplot.CONFIG = riboplot.config.TestingConfig()
logging.disable(logging.CRITICAL)
class CheckArgumentsTestCase(unittest.TestCase):
"""Check if all arguments sent on the command line are valid."""
parser = riboplot.create_parser()
d... | "If bedtools is not in PATH, raise an error."""
args = self.parser.parse_args(
['-b', CFG.RIBO_FILE, '-f', CFG.TRANSCRIPTOME_FASTA, '-t', CFG.TRANSCRIPT_NAME, '-n', CFG.RNA_FILE])
save_path = os.environ['PATH']
os.environ['PATH'] = ''
self.assertRaises(OSError, ribocore.check... |
rhempel/ev3dev-lang-python | ev3dev2/control/rc_tank.py | Python | mit | 1,496 | 0.004679 |
import logging
from ev3dev2.motor import MoveTank
from ev3dev2.sensor.lego import InfraredSensor
from time import sleep
log = logging.getLogger(__name__)
# ============
# Tank classes
# ============
class RemoteControlledTank(MoveTank):
def __init__(self, left_motor_port, right_motor_port, polarity='inversed', ... | = self.make_move(left_motor, self.speed_sp* -1)
self.remote.on_channel1_top_right = self.make_move(right_motor, self.speed_sp)
self.remote.on_chan | nel1_bottom_right = self.make_move(right_motor, self.speed_sp * -1)
self.channel = channel
def make_move(self, motor, dc_sp):
def move(state):
if state:
motor.run_forever(speed_sp=dc_sp)
else:
motor.stop()
return move
def main(sel... |
kernevil/samba | python/samba/tests/param.py | Python | gpl-3.0 | 3,667 | 0.000273 | # Unix SMB/CIFS implementation.
# Copyright (C) Jelmer Vernooij <[email protected]> 2007
#
# 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) a... | file = param.LoadParm()
file.set("workgroup", "bla")
self.assertEqual("BLA", file.get("workgroup"))
def test_is_mydomain(self):
file = param.LoadParm()
file.set("workgroup", "bla")
self.assertTrue(file.is_mydomain("BLA"))
self.assertFalse(file.is_mydomain("FOOBAR")... | self.assertTrue(file.is_myname("BLA"))
self.assertFalse(file.is_myname("FOOBAR"))
def test_load_default(self):
file = param.LoadParm()
file.load_default()
def test_section_nonexistent(self):
samba_lp = param.LoadParm()
samba_lp.load_default()
self.assertR... |
MuckRock/muckrock | muckrock/jurisdiction/migrations/0021_remove_jurisdiction_full_name.py | Python | agpl-3.0 | 368 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-03-26 15:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jurisdiction', '0020_auto_20180312_1413 | '),
]
operations = [
migrations.Re | moveField(
model_name='jurisdiction',
name='full_name',
),
]
|
TinyTinni/OF_Plugin-PyMesh | openmesh-python/tests/test_trimesh_circulator_face_vertex.py | Python | bsd-3-clause | 1,723 | 0.006965 | import unittest
import openmesh
import numpy as np
class TriMeshCirculatorFaceVertex(unittest.TestCase):
def setUp(self):
self.mesh = openmesh.TriMesh()
# Add some vertices
self.vhandle = []
self.vhandle.append(self.mesh.add_vertex(np.array([0, 1, 0])))
self.vhandle.appe... | self.mesh.add_face(self.vhandle[2], self.vhandle[1], self.vhandle[4])
'''
Test setup:
0 ==== 2
|\ 0 /|
| \ / |
|2 1 3|
| | / \ |
|/ 1 \|
3 ==== 4
'''
def test_face_vertex_iter_without_increment(self):
self.assertEqual(self.fh0.idx(), 0)
# Iterate around face 0 at the top
fv_it = openmesh.FaceVertexIter(self.mesh, self.fh0)
self.assertEqual(next(fv_it).idx... |
twankim/weaksemi | gen_data.py | Python | mit | 3,619 | 0.023211 | # -*- coding: utf-8 -*-
# @Author: twankim
# @Date: 2017-05-05 00:06:53
# @Last Modified by: twankim
# @Last Modified time: 2017-10-19 23:50:33
import numpy as np
from sklearn.datasets import make_blobs
class genData:
def __init__(self,n,m,k,min_gamma=1,max_gamma=1.25,std=1.0):
self.n = n
self... | )*(1-np.exp(-(self.gamma-1)**2 /8.0))))
))
else:
return int(np.ceil( 8*np.log(2*self.k*(self.m+1)/delta) / (self.gamma-1)**2 ))
def calc_beta(self,delta,weak='random',q=1.0,nu=None,rho=None):
assert (q >0) and (q<=1), "q must be in (0,1]"
asser... | \
"weak must be in ['random','local','global']"
if weak == 'random':
if q < 1:
return int(np.ceil(np.log(2*self.k*np.log(self.n)/delta) / np.log(1.0/(1-q))))
return 1
|
olt/mapproxy | mapproxy/image/transform.py | Python | apache-2.0 | 12,700 | 0.002598 | # This file is part of the MapProxy project.
# Copyright (C) 2010 Omniscale <http://omniscale.de>
#
# 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... | ormation.
Each QUAD is a rectangle in the destination image, like ``(0, 0, 100, 100)`` and
a list of four pixel coordinates in the source image that match the destination rectangle.
The four points form a quadliteral (i.e. not a rectangle).
PIL's image transform uses affine transformation to fill each ... | alculated dynamically to keep the deviation in the image
transformation below one pixel. Image transformations for large map scales can be transformed with
1-4 QUADs most of the time. For low scales, transform_meshes can generate a few hundred QUADs.
It generates a maximum of one QUAD per |
ini-bdds/ermrest | ermrest/ermpath/__init__.py | Python | apache-2.0 | 788 | 0.006345 |
#
# Copyright 2013-2015 University of Southern California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complia | nce with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express o... | ning permissions and
# limitations under the License.
#
"""ERMREST data path support
The data path is the core ERM-aware mechanism for searching,
navigating, and manipulating data in an ERMREST catalog.
"""
from resource import *
|
Kovak/KivySurvey | kivy_survey/survey.py | Python | mit | 5,884 | 0.001869 | from __future__ import unicode_literals, print_function
from jsontowidget import widget_from_json
class Survey(object):
def __init__(self, json_survey, **kwargs):
super(Survey, self).__init__(**kwargs)
self.survey_file = json_survey
self.questionnaires = {}
self.prev_questionnaires... | ndex-1]
else:
return None
def get_next_questionnaire(self, current_questionnaire):
q = self.questionnaires[current_questionnaire]
return q.next_questionnaire
def get_allow_forward(self, current_questionnaire):
q = self.questionnaires[current_questionnaire]
... | store_current_questionnaire(self, current_questionnaire):
self.prev_questionnaires.append(current_questionnaire)
def get_previous_questionnaire(self):
try:
return self.prev_questionnaires[-1]
except:
return None
def pop_previous_questionnaire(self):
... |
YiqunPeng/Leetcode-pyq | solutions/339NestedListWeightSum.py | Python | gpl-3.0 | 1,788 | 0.006152 | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list | .
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """ |
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(s... |
sonic182/portfolio3 | courses/migrations/0015_auto_20161028_1057.py | Python | mit | 445 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 201 | 6-10-28 10:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0014_course_views'),
]
operations = [
migrations.AlterField(
model_name='course',
name='title',
... | ength=160),
),
]
|
butala/pyrsss | pyrsss/mag/iaga2hdf.py | Python | mit | 10,261 | 0.000585 | import os
import sys
import math
import logging
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as NP
import pandas as PD
from pyglow.pyglow import Point
from geomagio.StreamConverter import get_obs_from_geo, get_geo_from_obs
from obspy.core.stream import Stream
from obspy.core.utcdatet... | ='X').traces[0].data,
B_Y=geo.select(channel='Y').traces[0].data)
def he2df(df, header):
"""
Add `B_H` and `B_E` (surface magnetic field in local geomagnetic
coordinates, H is local north and E is local east) to the
:class:`DataFrame` *df* and return. The record *header* is
ne... | df.columns):
# The USGS geomag-algorithms module requires the magnetic
# field magnitude B_F to transform from XY to HE --- add the
# B_F column if it is not present
values = zip(df['B_X'].values,
df['B_Y'].values,
df['B_Z'].values)
df =... |
pawhewitt/Dev | SU2_PY/change_version_number.py | Python | lgpl-2.1 | 2,840 | 0.011268 | #!/usr/bin/env python
## \file change_version_number.py
# \brief Python script for updating the version number of the SU2 suite.
# \author A. Aranake
# \version 5.0.0 "Raven"
#
# SU2 Original Developers: Dr. Francisco D. Palacios.
# Dr. Thomas D. Economon.
#
# SU2 Developers: Prof. Juan J.... | r line in f.readlines():
candidate = line.split(':')[0]
if not candidate in filelist a | nd candidate.find(sys.argv[0])<0:
filelist.append(candidate)
f.close()
print filelist
# Prompt user before continuing
yorn = ''
while(not yorn.lower()=='y'):
yorn = raw_input('Replace %s with %s in the listed files? [Y/N]: '%(oldvers,newvers))
if yorn.lower()=='n':
print 'The file version.txt contains mat... |
DJ-Tai/practice-problems | leet-code/python/solution-461-hamming-distance.py | Python | mit | 293 | 0.006826 | class Solution(object):
| def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x = x ^ y # Logical XOR
y = 0
while x:
y += 1
x | = x & (x-1)
return y
|
shannara/subuser | logic/subuserlib/builtInCommands/dev.py | Python | lgpl-3.0 | 2,852 | 0.030154 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#external imports
import sys
import optparse
import json
import os
import uuid
import subprocess
#internal imports
import subuserlib.commandLineArguments
import subuserlib.profile
import subuserlib.paths
subuserExecutable = os.path.join(subuserlib.paths.getSubuserDir(),"logi... | description = """ Create and run a subuser related to a dev image.
"""
parser=optparse.OptionParser(usage=usage,description=description,formatter=subuserlib.commandLineArguments.HelpFormatterThatDoesntReformatDescription())
parser.add_option("--ls",dest="ls",action="store_true",default=False,help="List dev imag... | e dev images associated with this folder. Note: This always uses the layer cache. Use subuser update all to update fully without layer caching.")
parser.add_option("--remove",dest="remove",action="store_true",default=False,help="Remove dev images associated with this folder.")
parser.add_option("--entrypoint",dest=... |
claman/apollo | apollo.py | Python | mit | 4,618 | 0.012343 | #!/usr/bin/env python
import argparse
import datetime
class Book:
def __init__(self, title, author, owned, start, end, physical, date):
self.title = title
self.author = author
self.owned = owned
self.start = start
self.end = end
self.physical = physical
self.date = date
def readTime(sel... | end
print 'Format: ' + self.physical
print 'First Published: ' + self.date
print self.readTime()
print
def stats():
totalBooks, totalPhysical, totalEbooks = 0, 0, 0
totalRead, tot | alOwned, totalBorrowed = 0, 0, 0
books_list.next()
books_list.next()
for line in books_list:
line = line.strip('|\n')
entry = line.split('|')
currentBook = Book(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6])
totalBooks += 1
if currentBook.physical == 'Paperback' or forma... |
xiaohan2012/lst | check_dataframe.py | Python | mit | 74 | 0 | import sys
impor | t pandas as pd
df = pd.read_pickle(sys.arg | v[1])
print df
|
mlackman/pymapp | pymapp/setters.py | Python | lgpl-2.1 | 1,495 | 0.011371 |
class Attribute(object):
def __init__(self, target_attribute_name):
self.target_attribute_name = target_attribute_name
def set(self, target_object, value):
target_object.__dict__[self.target_attribute_name] = value
def get(self, target_object):
return getattr(target_object, self.target_attribute_n... | to target object attribute"""
def __init__(self, object_target_attribute_name, mapper):
super().__init__(object_targe | t_attribute_name)
self.mapper = mapper
def get(self, target_object):
value = super().get(target_object)
return self.mapper.to_hash(value)
def set(self, target_object, value):
target_object.__dict__[self.target_attribute_name] = self.mapper.from_hash(value)
class ListRelation(Attribute):
"""Sets... |
EricMuller/mynotes-backend | requirements/twisted/Twisted-17.1.0/src/twisted/application/twist/__init__.py | Python | mit | 166 | 0 | # -*- test | -case-name: twisted.application.twist.test -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
C{twist} command line tool.
"" | "
|
knotman90/google-interview | problems/distributedJam/dcj_linux/dcj/command_chooser.py | Python | gpl-3.0 | 1,360 | 0.005147 | """Class for choosing cli commands."""
import argparse
class CommandChooser(object):
"""Chooses command to run based on commandline arguments."""
def __init__(self, commands_dict):
"""Initialize CommandChooser.
Args:
commands_dict: dict from command name to | object responsible for executing
the command. The object should provide t | wo methods:
* AddToParser(parser) returning parser to parse arguments passed to the
command.
* Decription() returning string that will describe the command when
using --help flag.
* Run(args) runing the commands with given args.
"""
self.commands_dict = commands_dict
... |
CSCI-462-01-2017/bedrock | bedrock/redirects/tests/test_util.py | Python | mpl-2.0 | 16,002 | 0.002062 | # This Source Code Form is subject to the terms of the Mozi | lla Public
# License, v. 2.0. | If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from urlparse import parse_qs, urlparse
from django.conf.urls import RegexURLPattern
from django.test import TestCase
from django.test.client import RequestFactory
from mock import patch
from nose.tools impo... |
koparasy/faultinjection-gem5 | src/cpu/inorder/InOrderCPU.py | Python | bsd-3-clause | 4,432 | 0.003159 | # Copyright (c) 2007 MIPS Technologies, 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 of conditions and the following disclaimer;
# redis | tributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote prod... |
jeremiahyan/odoo | addons/l10n_ar/models/account_move_line.py | Python | gpl-3.0 | 1,367 | 0.002926 | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _l10n_ar_prices_and_taxes(sel | f):
self.ensure_one()
invoice = self.move_id
included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
price_unit = self.tax_ids.with_ | context(round=False).compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)
price_unit = price_unit['total_excluded']
price_subtotal = self.price_subtotal
else:
price_unit = included_taxes.compute_all(
self... |
IEEEDTU/CMS | Assessment/views/Assignment.py | Python | mit | 2,991 | 0.001672 | from django.core import serializers
from django.http import HttpResponse, JsonResponse
from Assessment.models import *
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
import json
@csrf_exempt
@require_GET
def getAssignmentByCode(request):
resp... | response_data['exception'] = str(e)
else:
response_data['success'] = '1'
global data
try:
data = serializers.serialize('json', C)
except Exception as e:
data = serializers.seriali | ze('json', [C, ])
response_data["assignment"] = json.loads(data)
return JsonResponse(response_data)
@csrf_exempt
@require_GET
def retrieveAssignmentResponses(request):
response_data = {}
try:
C = AssignmentResponse.objects.retrieveAssignmentResponsesByStudent(request.GET)
except Excep... |
bqbn/addons-server | src/olympia/reviewers/views.py | Python | bsd-3-clause | 65,909 | 0.000926 | import functools
import json
import time
from collections import OrderedDict
from datetime import date, datetime, timedelta
from django import http
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator
from ... | gettext('Add-on Review Guide'), |
'https://wiki.mozilla.org/Add-ons/Reviewers/Guide',
),
)
)
sections[gettext('Security Scanners')] = [
(
gettext('Flagged By Scanners'),
reverse('reviewers.queue_scanners'),
),
(
... |
anhstudios/swganh | data/scripts/templates/object/building/poi/shared_dathomir_freedprisonerscamp_large1.py | Python | mit | 465 | 0.047312 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION | FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_dathomir_freedprisonerscamp_large1.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### EN | D MODIFICATIONS ####
return result |
mylene-campana/hpp-rbprm-corba | script/tests/skeleton_plateforms_path.py | Python | lgpl-3.0 | 5,500 | 0.021822 | #/usr/bin/env python
# author: Mylene Campana ([email protected])
# Script which goes with hpp-rbprm-corba package.
# The script launches a skeleton-robot and a ??? environment.
# It defines init and final configs, and solve them with RBPRM.
# Range O | f Motions are sphe | res linked to the 4 end-effectors
#blender/urdf_to_blender.py -p rbprmBuilder/ -i /local/mcampana/devel/hpp/src/animals_description/urdf/skeleton.urdf -o skeleton_blend.py
#TODO: Lombaire joints -> impose same values
from hpp.corbaserver import Client
from hpp.corbaserver.rbprm.problem_solver import ProblemSolver
f... |
sfcl/ancon | index/migrations/0013_auto_20170221_2204.py | Python | gpl-2.0 | 578 | 0.00173 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017 | -02-21 17:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('index', '0012_cartridgeitemname_manufacturer'),
]
operations = [
migrations.AlterField(
mo... | acturer',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='common.Manufacturer'),
),
]
|
endlessm/chromium-browser | third_party/grpc/src/test/http2_test/test_max_streams.py | Python | bsd-3-clause | 1,926 | 0.004673 | # Copyright 2016 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | er express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
impor | t hyperframe.frame
import logging
import http2_base_server
class TestcaseSettingsMaxStreams(object):
"""
This test sets MAX_CONCURRENT_STREAMS to 1 and asserts that at any point
only 1 stream is active.
"""
def __init__(self):
self._base_server = http2_base_server.H2ProtocolBaseServer()
self._ba... |
pirobot/pedsim_ros | pedsim_simulator/scripts/mocktracks_rss_scenario_one.py | Python | bsd-2-clause | 12,091 | 0.022248 | #!/usr/bin/env python
# Author: Timm Linder, [email protected]
#
# Publishes fake tracked persons and the corresponding detections (if not occluded) at
# /spencer/perception/tracked_persons and /spencer/perception/detected_persons.
import rospy, yaml, tf
from spencer_tracking_msgs.msg import TrackedPersons, Tr... | dCells
from math import cos, sin, tan, pi, radians
def createTrackedPerson(track_id, x, y, theta):
trackedPerson = TrackedPerson()
theta = radians(theta) + pi/2.0
trackedPerson.track_id = track_id
quaternion = tf.transformations.quaternion_from_euler(0, 0, theta)
trackedPerson.pose.pose.position... | son.pose.pose.orientation.x = quaternion[0]
trackedPerson.pose.pose.orientation.y = quaternion[1]
trackedPerson.pose.pose.orientation.z = quaternion[2]
trackedPerson.pose.pose.orientation.w = quaternion[3]
trackedPerson.pose.covariance[0 + 0 * 6] = 0.001 # x
trackedPerson.pose.covariance[1 + 1 * 6]... |
ilveroluca/pydoop | test/common/test_pydoop.py | Python | apache-2.0 | 2,152 | 0 | # BEGIN_COPYRIGHT
#
# Copyright 2009-2015 CRS4.
#
# 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 agree... | r_name())
self.assertEqual('pydoop', os.path.basename(directory))
def suite():
suite_ = unittes | t.TestSuite()
suite_.addTest(TestPydoop('test_home'))
suite_.addTest(TestPydoop('test_conf'))
suite_.addTest(TestPydoop('test_pydoop_jar_path'))
return suite_
if __name__ == '__main__':
_RUNNER = unittest.TextTestRunner(verbosity=2)
_RUNNER.run((suite()))
|
LimpidTech/django-themes | themes/managers.py | Python | mit | 1,188 | 0.000842 | from django.contrib.sites import models as site_models
from django.db import models
def _get_current_site(request):
# Attempts to use monodjango.middleware.SiteProviderMiddleware
try:
return Site.objects.get_current(request)
except TypeError:
pass
return Site.objects.get_current()
c... | = Site.objects.get_current()
| return self.get(sites_enabled=site)
def get_list_by_request(self, request=None):
""" Gets a list of themes that are available for the given request. """
return self.get_list(_get_current_site(request))
def get_list(self, site=None):
""" Get a list of themes available on a specific sit... |
tbenthompson/LMS_public | lms_code/lib/gps.py | Python | mit | 1,311 | 0.003051 | from scipy.io import loadmat
# which_profile = "LMS"
# which_profile = "longer_profile2"
# which_profile = "properly_aligned3"
def get_stations(which_profile):
all_gps = loadmat('data/gps/CalaisGanSocquetBanerjeeApel_in_Calais_RF_trim_Clean_Tog.sta.data.mat')
all_station_names = all_gps['station_name']
... | gps = loadmat(' | data/gps/' + which_profile + '.profile.mat')
names = prof_gps['profile_station_names']
stations = []
for (idx, n) in enumerate(names):
s = dict()
s['name'] = n
s['distance'] = prof_gps['parallel_distance'][idx][0]
s['parallel_vel'] = prof_gps['parallel_vel'][idx][0]
s... |
mvinoba/MinervaBot | MinervaBot.py | Python | gpl-3.0 | 4,031 | 0.001488 | from getpass import getpass
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdri... | r todos
try:
renovartodos = driver.find_element_by_partial_link_text('Renovar Todos')
except exceptions.NoSuchElementException:
mensagem = driver.find_element_by_class_name('text3')
print(mensagem.text)
else:
# Clica em renovar todos
renovarto | dos.send_keys(Keys.RETURN)
# Imprime na tela o resultado da renovacao
tabela = driver.find_elements_by_tag_name('table')[-1]
linhas = tabela.find_elements_by_tag_name('tr')
cabecalho = linhas[0].find_elements_by_tag_name('th')
for livro in linhas[1:]:
corpo = livro.find_elements_by_tag_name... |
anish/phatch | phatch/data/info.py | Python | gpl-3.0 | 16,717 | 0.00252 | # -*- coding: UTF-8 -*-
# Phatch - Photo Batch Processor
# Copyright (C) 2007-2008 www.stani.be
#
# 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 ... | telis Grammatikakis'},
{'name': u'arnau'},
{'name': u'Arnaud Bonatti'},
{'name': u'Aron Xu'},
{'name': u'Artin'},
{'name': u'Artur Chmarzyński'},
{'name': u'Åskar'},
{'name': u"Balaam's Miracle"},
{'name': u'Bjørn Sivertsen'},
{'name': u'bt4wang'},... | u'Daniel Nylander'},
{'name': u'Daniel Voicu'},
{'name': u'Daniele de Virgilio'},
{'name': u'Darek'},
{'name': u'David A Páez'},
{'name': u'David Machakhelidze'},
{'name': u'deukek'},
{'name': u'Diablo'},
{'name': u'DiegoJ'},
{'name': u'Dirk Tas'}... |
goirijo/thermoplotting | old/scripts/strainrelaxations.py | Python | mit | 3,619 | 0.038685 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import math
#Reads deformations.txt, generated via
#`casm query -k 'struc_score(PRIM,basis_score)' 'struc_score(PRIM,lattice_score)' 'struc_score(../NiAl-B2/PRIM-true.vasp,basis_score)' 'struc_score(../NiAl-B2/PRIM-true.vasp,latti... | tch(color | ='blue', label=r'\textbf{HCP}')
ax.legend(handles=[red_patch,green_patch,blue_patch],prop={'size':12},loc="upper left")
plt.tight_layout()
plt.show()
#Save the configurations that are FCC
FCCindx=[(bestscore==0)]
FCCnames=names[FCCindx]
FCCfiltered=np.array(FCCscore[FCCindx],dtype="S25")
FCCdump=np.vstack((FCCnames... |
c3nav/c3nav | src/c3nav/routing/route.py | Python | apache-2.0 | 9,539 | 0.002516 | # flake8: noqa
import copy
from collections import OrderedDict, deque |
import numpy as np
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
def describe_location(location, locations):
if location.can_describe:
final_location = locations.get(location.pk)
if final_location is not None:
location = f... | lude_type=True, detailed=False, simple_geometry=True)
if hasattr(location, 'serialize_position'):
result.update(location.serialize_position())
return result
class Route:
def __init__(self, router, origin, destination, path_nodes, options,
origin_addition, destination_addition, ori... |
atria-soft/zeus | tools/service-picture/lutin_zeus-service-picture.py | Python | apache-2.0 | 845 | 0.040237 | #!/usr/bin/python
import realog.debug as debug
import lutin.tools a | s tools
import lutin.macro as macro
def get_type():
return "LIBRARY"
#return "BINARY"
def get_sub_type():
return "TOOLS"
def get_desc():
return "ZEUS picture service"
def get_licence():
return "MPL-2"
def get_compagny_type():
return "com"
def get_compagny_name():
return "atria-soft"
def get_maintainer():... | _module.add_depend([
'zeus'
])
zeus_macro = macro.load_macro('zeus')
zeus_macro.parse_object_idl(my_module, 'appl/zeus-service-picture.srv.zeus.idl')
#module_zeus = target.get_module('zeus')
#module_zeus.parse_service_idl(my_module, 'appl/zeus-service-picture.zeus.idl')
my_module.add_flag('c++', "-DSER... |
meta-it/misc-addons | ir_attachment_s3/models/ir_attachment.py | Python | lgpl-3.0 | 3,506 | 0.001997 | # -*- coding: utf-8 -*-
import os
import hashlib
import logging
from odoo import api, models, _
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
try:
import boto3
except:
_logger.debug('boto3 package is required which is not \
found on your installation')
class IrAttachm... | f _inverse_datas(self):
s3 = self._get_s3_resource()
condition = self._get_s3_settings('s3.condition', 'S3_CONDITION')
if not s3:
# set s3_records to empty recordset
s3_records = self.env[self. | _name]
elif condition:
s3_records = self.filtered(lambda r: safe_eval(condition, {}, {'attachment': r}, mode="eval"))
else:
# if there is no condition then store all attachments on s3
s3_records = self
s3_records = s3_records._filter_protected_attachments()
... |
toconn/Python3-Core | Source/ua/core/utils/fileutils.py | Python | gpl-3.0 | 4,659 | 0.013093 | import glob
import os
import shutil
from ua.core.utils.isfirst import IsFirst
# Renamed Methods:
#
# dir_file_names -> read_dir_file_names
# dir_file_paths -> read_dir_file_paths
# get_dir_file_names -> read_dir_file_names
# get_dir_file_paths -> read_dir_file_paths
# latest_file -> read_latest_fil... | ext(path):
with open(path, 'r') as file_handle:
content_text = file_handle.read()
return content_text
def path_file_name (file_path):
''' Returns the full file name from the path (dir/filename.ext -> filename.ext)
'''
file_name = os.path.bas | ename(file_path)
return file_name
def rename (current_path, new_path):
os.renames(current_path, new_path)
|
gedhe/sidesa2.0 | input_administrasi_surat.py | Python | gpl-2.0 | 2,779 | 0.011875 | #Boa:Frame:adm_surat
import wx
import wx.lib.buttons
import frm_sideka_menu
import pembuatan_surat_keluar
import surat_masuk
def create(parent):
return adm_surat(parent)
[wxID_ADM_SURAT, wxID_ADM_SURATSTATICLINE1, wxID_ADM_SURATTOMBOL_INPUT_SURAT,
wxID_ADM_SURATTOMBOL_KEMBALI_KE_MENU, wxID_ADM_SURATTOMBOL_SURA... | edit
wx.Frame.__init__(self, id=wxID_ADM_SURAT, name=u'adm_surat',
parent=prnt, pos=wx.Point(641, 356), size=wx.Size(417, 102),
style=wx.DEFAULT_FRAME_STYLE, title=u'Administrasi Persuratan')
self.SetClientSize(wx.Size(417, 102))
self.Center(wx.BOTH)
self.to... | surat = wx.lib.buttons.GenBitmapTextButton(bitmap=wx.NullBitmap,
id=wxID_ADM_SURATTOMBOL_INPUT_SURAT, label=u'Surat Masuk',
name=u'tombol_input_surat', parent=self, pos=wx.Point(16, 16),
size=wx.Size(184, 31), style=0)
self.tombol_input_surat.Bind(wx.EVT_BUTTON,
... |
foundit/Piped | piped/decorators.py | Python | mit | 447 | 0 | # Copyright (c) 2010-2011, Found IT A/S and Piped Project Contributors.
# See LICENSE for details.
""" Decorators used in the project """
def coroutine(func):
""" Advances the coroutine to its first yield. | """
def wrapper(*args, **kw):
gen = func(*args, **kw)
gen.next()
return gen
wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__
| wrapper.__doc__ = func.__doc__
return wrapper
|
beepaste/beepaste | beepaste/views/panels.py | Python | gpl-3.0 | 1,941 | 0.004637 | from pyramid_layout.panel import panel_config
from pyramid.view import view_config
from os.path import join
from beepaste.paths import base
from ..models.users import Users
import datetime
import json
@panel_config(name='navbar', renderer='templates/panels/navbar.jinja2')
def navbar(context, request):
return {}
@... | items
)
return item
items = []
# items.append(nav_item('resume', '#', [nav_item(name, request.route_path(name)) for name in ['resume_list','resume_edit']]))
items.append(nav_item('<i class="fa fa-plus-circle" aria-hidden="true"></i> Create Paste', request.route_pa | th('home')))
items.append(nav_item('<i class="fa fa-cogs" aria-hidden="true"></i> API', request.route_path('api_intro')))
items.append(nav_item('<i class="fa fa-info" aria-hidden="true"></i> About Us', request.route_path('about')))
return {'items': items}
@panel_config(name='authors', renderer='templates/p... |
cjk4wr/cs3240-labdemo | Test.py | Python | mit | 38 | 0 | __a | uthor__ = 'cjk4wr'
pr | int("test!")
|
metalink-dev/checker | metalinkcw.py | Python | gpl-2.0 | 11,953 | 0.011211 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
########################################################################
#
# Project: Metalink Checker
# URL: https://github.com/metalink-dev/checker
# E-mail: [email protected]
#
# Copyright: (C) 2007-2016, Neil McNab
# License: GNU General Public License Version 2
# (h... | ope that it will be useful,
# but WITHOUT ANY WARRANTY; without even th | e 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., 59 Temple Place, Suite 330, Boston, ... |
upsuper/onenet-firefox | tools/extract_pac.py | Python | mit | 796 | 0.005025 | #!/usr/bin/env python3
import re
import | sys
import base64
_pac_line = re.compile(r"^var pac_(\S+) = '([a-zA-Z0-9+/]+=*)';$")
def parse_line(line):
match = _pac_line.match(line)
if not match:
return None
return (match.group(1), base64.b64decode(match.group(2)))
def extract_pac_files(source):
for line in source:
result = pars... | a = result
print("extract {}, length {} bytes".format(name, len(data)))
with open('data/pac/' + name + '.pac', 'wb') as pac:
pac.write(data)
def main():
if not sys.argv[1]:
print('Expect popup.js')
exit(1)
with open(sys.argv[1], 'r') as f:
extract_pac_files(... |
SanPen/GridCal | src/GridCal/Engine/Devices/load.py | Python | lgpl-3.0 | 9,713 | 0.00278 | # GridCal
# Copyright (C) 2022 Santiago Peñate Vera
#
# 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) any later version.
#
# This pr... | urn {'id': self.idtag,
'type': 'load',
'phases': 'ps',
'name': self.name,
'name_code': self.code,
'bus': self.bus.idtag,
'active': bool(self.active),
| 'g': self.G,
'b': self.B,
'ir': self.Ir,
'ii': self.Ii,
'p': self.P,
'q': self.Q
}
else:
return dict()
def get_profiles_dict(self, version=3):
"""
:ret... |
iemejia/incubator-beam | sdks/python/apache_beam/transforms/util_test.py | Python | apache-2.0 | 42,823 | 0.00822 | #
# 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 us... | h_estimator.next_batch_size())
with batch_estimator.record_time(actual_sizes[-1]):
| clock.sleep(batch_duration(actual_sizes[-1]))
self.assertEqual(expected_sizes, actual_sizes)
def test_target_overhead(self):
clock = FakeClock()
batch_estimator = util._BatchSizeEstimator(
target_batch_overhead=.05, target_batch_duration_secs=None, clock=clock)
batch_duration = lambda ba... |
rusch95/calypso | src/common/metro.py | Python | bsd-3-clause | 2,521 | 0.003173 | #####################################################################
#
# metro.py
#
# Copyright (c) 2016, Eran Egozy
#
# Released under the MIT License (http://opensource.org/licenses/MIT)
#
#####################################################################
from clock import kTicksPerQuarter, quantize_tick_up
cla... | , self.patch[0], self.patch[1])
# find the tick of the next beat, and make it "beat aligned"
now = self.sched.get_tick()
next_beat = quantize_tick_up(now, self.beat_len)
# now, post the _noteon function (and remember this command)
| self.on_cmd = self.sched.post_at_tick(next_beat, self._noteon)
def stop(self):
if not self.playing:
return
self.playing = False
# in case there is a note on hanging, turn it off immediately
if self.off_cmd:
self.off_cmd.execute()
# ca... |
zamattiac/osf.io | website/addons/base/views.py | Python | apache-2.0 | 25,393 | 0.001536 | import datetime
import httplib
import os
import uuid
import markupsafe
from flask import make_response
from flask import redirect
from flask import request
import furl
import jwe
import jwt
from modularodm import Q
from modularodm.exceptions import NoResultsFound
from framework import sentry
from framework.auth imp... | turn {
'id': user._id,
'email': '{}@osf.io'.format(user._id),
'name': user.fullname,
}
return {}
@collect_auth
def get_auth(auth, **kwargs):
cas_resp = None
if not auth | .user:
# Central Authentication Server OAuth Bearer Token
authorization = request.headers.get('Authorization')
if authorization and authorization.startswith('Bearer '):
client = cas.get_client()
try:
access_token = cas.parse_auth_header(authorization)
... |
Zlash65/erpnext | erpnext/accounts/doctype/exchange_rate_revaluation_account/exchange_rate_revaluation_account.py | Python | gpl-3.0 | 296 | 0.006757 | # -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see licens | e.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import | Document
class ExchangeRateRevaluationAccount(Document):
pass
|
LEAF-BoiseState/SPEED | Other/download_SNOTEL.py | Python | mit | 805 | 0.014907 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 8 17:10:51 2015
@author: kawatson
Purpose: Download data from select SNOTEL sites for a given time period
and save data to text files
Required libraries: Climata (available via PyPI | "pip install climata")
"""
# Import Climata
from climata.snotel import Regi... | = "WTEQ",
)
# Iterate over sites and write data to text files
for site in sites:
f = open(site.stationtriplet.split(':')[0] + ".txt","w")
print "Writing data to file for: " + site.name
for row in site.data:
| f.write(str(row.date)+","+str(row.value)+"\n")
f.close() |
lukas-hetzenecker/home-assistant | homeassistant/components/sense/const.py | Python | apache-2.0 | 2,110 | 0 | """Constants for monitoring a Sense energy sensor."""
import asyncio
from sense_energy import SenseAPITimeoutException
DOMAIN = "sense"
DEFAULT_TIMEOUT = 10
ACTIVE_UPDATE_RATE = 60
DEFAULT_NAME | = "Sense"
SENSE_DATA = "sense_data"
SENSE_DEVICE_UPDATE = "sense_devices_update"
SENSE_DEVICES_DATA = "sense_devices_data"
SENSE_DISCOVERED_DEVICES_DATA = "sense_discovered_devices"
SENSE_TRENDS_COORDINATOR = "sense_trends_coordinator"
ACTIVE_NAME = "Energy"
ACTIVE_TYPE = "active"
ATTRIBUTION = "Data provided by Sen... | UCTION_PCT_NAME = "Net Production Percentage"
PRODUCTION_PCT_ID = "production_pct"
NET_PRODUCTION_NAME = "Net Production"
NET_PRODUCTION_ID = "net_production"
TO_GRID_NAME = "To Grid"
TO_GRID_ID = "to_grid"
FROM_GRID_NAME = "From Grid"
FROM_GRID_ID = "from_grid"
SOLAR_POWERED_NAME = "Solar Powered Percentage"
SOLAR_POW... |
rartino/ENVISIoN | envisionpy/utils/exceptions.py | Python | bsd-2-clause | 2,304 | 0.00651 | # ENVISIoN
#
# Copyright (c) 2019 Jesper Ericsson
# 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 notice, this
# list o... | in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#... | AIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# O... |
zamanashiq3/code-DNN | dense_v1.py | Python | mit | 2,055 | 0.019951 | """
locally connected implimentation on the lip movement data.
Akm Ashiquzzaman
[email protected]
Fall 2016
after 1 epoch , val_acc: 0.0926
"""
from __future__ import print_function, division
#random seed fixing for reproducibility
import numpy as np
np.random.seed(1337)
import time
#Data loading
X_train = np.... | n
X_train = X_train.reshape((X_tra | in.shape[0],53*53)).astype('float32')
Y_train = Y_train.reshape((Y_train.shape[0],4702)).astype('float32')
#setting batch_size and epoch
batchSize = 20
tt_epoch = 1
from keras.models import Sequential
from keras.layers import Dense,Dropout, Activation
#time to measure the experiment.
tt = time.time()
#model build... |
jmartinm/inspire-next | inspire/modules/predicter/tasks.py | Python | gpl-2.0 | 4,080 | 0.00049 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2015 CERN.
#
# INSPIRE 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... | # The new variable is needed due to how parameters in closures work
full_model_path = model_path
if not os.path.isfile(full_model_path):
obj.log.error(
"Model file {0} not found! Skipping prediction...".format(
full_model_path
)
... | d = prepare_prediction_record(record)
pipeline = load_model(full_model_path)
result = {}
if not top_words:
decision, scores = predict(pipeline, prepared_record, top_words)
else:
decision, scores, top_core, top_noncore, top_rejected = \
predict(pi... |
mgraupe/acq4 | acq4/util/flowchart/Analysis.py | Python | mit | 48,966 | 0.014051 | # -*- coding: utf-8 -*-
from acq4.pyqtgraph.flowchart.library.common import *
import acq4.util.functions as functions
import numpy as np
import scipy
#from acq4.pyqtgraph import graphicsItems
import acq4.pyqtgraph as pg
import acq4.util.metaarray as metaarray
#import acq4.pyqtgraph.CheckTable as CheckTable
from collec... | #guesses.extend(output['guesses'])
#eventData.extend(output['eventData'])
#indexes.extend(output['indexes'])
#xVals.extend(output['xVals'])
#yVals.extend(output['yVals'])
#output = np.concatenate(data)
for i in range(len(i... | tFits'].isChecked():
item = pg.PlotDataItem(x=xVals[i], y=yVals[i], pen=(0, 0, 255), clickable=True)
item.setZValue(100)
self.plotItems.append(item)
item.eventIndex = indexes[i]
item.sigClicked.connect(self.fitClicked)
... |
janezkranjc/clowdflows | workflows/perfeval/visualization_views.py | Python | gpl-3.0 | 446 | 0.024664 | from django.shortcuts import render
def perfeval_display_summation(request,input_dict,output_dict,widget):
i | f sum(input_dict['intList']) == input_dict['sum']:
check = 'The calculation appe | ars correct.'
else:
check = 'The calculation appears incorrect!'
return render(request, 'visualizations/perfeval_display_integers.html',{'widget':widget,'input_dict':input_dict, 'output_dict':output_dict, 'check':check})
|
fbergmann/libSEDML | examples/python/create_nested_task.py | Python | bsd-2-clause | 1,555 | 0.001286 | #!/bin/env python
import libsedml
def create_nested_task(file_name):
doc = libsedml.SedDocument(1, 4)
# create simulation
sim = doc.createSteadyState()
sim.setId("steady1")
# need to set the correct KISAO Term
alg = sim.createAlgorithm()
alg.setKisaoID("KISAO:0000282")
# create ... | teModel()
model.setId("model1")
model.setLanguage("urn:sedml:language:sbml")
model.setSource("oscli.xml")
# create tasks
task = doc.createTask()
task.setId( | "task0")
task.setModelReference("model1")
task.setSimulationReference("steady1")
task = doc.createRepeatedTask()
assert(isinstance(task, libsedml.SedRepeatedTask))
task.setId("task1")
task.setResetModel(True)
task.setRangeId("current")
range = task.createUniformRange()
assert(isins... |
bmaggard/luigi | test/worker_parallel_scheduling_test.py | Python | apache-2.0 | 5,302 | 0.000377 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | itations under the License.
#
import contextlib
import gc
import os
import pickle
import time
from helpers import unittest
import luigi
import mock
import psutil
from luigi.worker import Worker
def running_children():
children = set()
process = psutil.Process(os.getpid())
for child in process.children()... | yield
try:
gc.disable()
yield
finally:
gc.enable()
class SlowCompleteWrapper(luigi.WrapperTask):
def requires(self):
return [SlowCompleteTask(i) for i in range(4)]
class SlowCompleteTask(luigi.Task):
n = luigi.IntParameter()
def complete(self):
time.sl... |
oshadmon/StreamingSQL | tests/test_db.py | Python | mit | 4,584 | 0.006981 | """
The following tests that db connections works properly.
Make sure the default configurations match your connection to the database
"""
import pymysql
import warnings
warnings.filterwarnings("ignore")
from StreamingSQL.db import create_connection, execute_command
from StreamingSQL.fonts import Colors, Formats
"""D... | error is properly returned when there is an incorrect port number
Assert:
Proper error is returned/formatted
"""
error = | "2003: Cant connect to MySQL server on '%s' [Errno 61] Connection refused"
error = (Formats.BOLD + Colors.RED + "Connection Error - " + error + Formats.END + Colors.END) % host
cur = create_connection(host=host, port=port + 13, user=usr, password=paswd, db=db)
try:
assert cur == error
except A... |
leighpauls/k2cro4 | third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/abstractsequencedcommand.py | Python | bsd-3-clause | 2,379 | 0.001261 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# R | edistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions | are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or othe... |
weechat/weechat.org | weechat/common/views.py | Python | gpl-3.0 | 1,083 | 0 | #
# Copyright (C) 2003-2022 Sébastien Helleu <[email protected]>
#
# This file is part of WeeChat.org.
#
# WeeChat.org 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
#... |
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Some useful views."""
from django.views.generic import TemplateView
class TextTemplateView(TemplateView):
"""View for a plain text file."""
def render_to_response... | xt, **response_kwargs)
|
pylayers/pylayers | pylayers/simul/tests/test_espoo.py | Python | mit | 2,820 | 0.040426 | from pylayers.simul.link import *
from pylayers.antprop.channel import *
from pylayers.antprop.antenna import *
from pylayers.util.geomutil import *
# parameters
fmin = 31.8 # GHz
fmax = 33.4 # GHz
bw = fmax - fmin # bandwidth in GHz
nf = 10001 # sweep frequency points
fc = (fmin + fmax)/... | l_H only the ground reflection
DL.eval(force=1,cutoff=3,threshold=0.4,nD=1,ra_ceil_H=0)
#DL.C.cut(threshold_dB=90)
# angular range
phimin = np.pi/4. # 45 deg
phimax = 3*np.pi/2. # 270 deg
phistep = 5*np.pi/180. # 5 deg
phi = np.arange(phimin,phimax,phistep)
# angular frequency profile
afp = DL.afp(phi)
# an... | fp.toadp()
# adp.imshow(cmap=cm.jet)
# plt.figure()
# adp.imshow(cmap=cm.jet)
# polarplot
# plt.figure()
adp.polarplot(vmin=-130,title='PADP of BS-MS1')#+str())
plt.show()
# DL.R.show(L=DL.L,rlist=DL.C.selected)
|
borisroman/vdsm | lib/vdsm/ipwrapper.py | Python | gpl-2.0 | 18,145 | 0 | # Copyright 2013-2014 Red Hat, Inc.
#
# 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 WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Pu... |
tensorflow/tensorboard | tensorboard/data/server/pip_package/build_test.py | Python | apache-2.0 | 2,101 | 0 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# | Licensed under the Apache License, Version 2.0 (the " | License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT... |
mtulio/kb | dev/satellite6_api/running_queries.py | Python | apache-2.0 | 2,617 | 0.006123 | #!/usr/bin/python
# Red Hat Satellite - API Guide - 4.2.2. Running Queries Using Python
# Link: https://access.redhat.com/documentation/en-US/Red_Hat_Satellite/6.1/html-single/API_Guide/index.html#idp10992432
#
# You can create and run a Python script to achieve the same results as those described in Section 4.3, “API... | urn r.json()
def get_results(url):
jsn = get_json(url)
if jsn.get('error'):
print "Error: " + jsn['error']['message']
else:
if jsn.get('results'):
return jsn['results']
elif 'results' not in jsn:
return jsn
else:
print "No results found"
... | = get_results(url)
if results:
print json.dumps(results, indent=4, sort_keys=True)
def display_info_for_hosts(url):
hosts = get_results(url)
if hosts:
for host in hosts:
print "ID: %-10d Name: %-30s IP: %-20s OS: %-30s" % (host['id'], host['name'], host['ip'], host['operatingsy... |
jrslocum17/pynet_test | Bonus3/napalm_get_model.py | Python | apache-2.0 | 1,612 | 0.004348 | #!/usr/bin/env python
"""
Ex 1. Construct a script that retrieves NAPALM facts from two IOS routers, two Arista switches, a | nd one Junos device.
pynet-rtr1 (Cisco IOS) 184.105.247.70
pynet-rtr2 (Cisco IOS) 184.105.247.71
pynet-sw1 (Arista EOS) 184.105.247.72
pynet-sw2 (Arista EOS) 184.105.247.73
juniper-srx 184.105.247.76
Retrieve the 'model | ' number from each device and print the model to standard out.
As part of this exercise define the devices that you use in a Python file (for example my_devices.py) and import
these devices into your program. Optionally, define the devices in a YAML file and read this my_devices.yml file in.
"""
from __future__ impor... |
atodorov/anaconda | pyanaconda/ui/tui/spokes/__init__.py | Python | gpl-2.0 | 4,212 | 0.000237 | # The base classes for Anaconda TUI Spokes
#
# Copyright (C) (2012) Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This progr... | be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 t | he
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
... |
jmeyers314/batoid | tests/test_Sphere.py | Python | bsd-2-clause | 7,740 | 0.001163 | import batoid
import numpy as np
from test_helpers import timer, do_pickle, all_obj_diff, init_gpu, rays_allclose
@timer
def test_properties():
rng = np.random.default_rng(5)
for i in range(100):
R = rng.normal(0.0, 0.3) # negative allowed
sphere = batoid.Sphere(R)
assert sphere.R == ... | (
sphere.sag(x, y),
R*(1-np.sqrt(1.0-(x*x + y*y)/R/R))
)
# Make sure non-unit stride arrays also work
np.testing.assert_allclose(
sphere.sag(x[::5,::2], y[::5,::2]),
R*(1-np.sqrt(1.0-(x*x + y*y)/R/R))[::5,::2]
)
do_pickle(sphere)
... | f test_normal():
rng = np.random.default_rng(577)
for i in range(100):
R = 1./rng.normal(0.0, 0.3)
sphere = batoid.Sphere(R)
for j in range(10):
x = rng.uniform(-0.7*abs(R), 0.7*abs(R))
y = rng.uniform(-0.7*abs(R), 0.7*abs(R))
result = sphere.normal(x,... |
forseti-security/forseti-security | google/cloud/forseti/services/model/modeller.py | Python | apache-2.0 | 3,684 | 0 | # Copyright 2017 The Forseti Security 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... | True)
def list_model(self):
"""Lists all models.
Returns:
list: list of Models in dao
"""
model_manager = self.config.model_manager
| return model_manager.models()
def get_model(self, model):
"""Get details of a model by name or handle.
Args:
model (str): name or handle of the model to query
Returns:
Model: db Model instance dao
"""
model_manager = self.config.model_manager
... |
fredex42/gnmvidispine | gnmvidispine/vs_user.py | Python | gpl-2.0 | 5,073 | 0.008673 | from .vidispine_api import VSApi,VSException,VSNotFound
import xml.etree.ElementTree as ET
import re
from pprint import pprint
class VSUserGroup(VSApi):
def __init__(self,*args,**kwargs):
super(VSUserGroup, self).__init__(*args,**kwargs)
self.dataContent = None
def populateFromXML(self,xmlNod... |
def description(self):
return self._nodeContentOrNone('description')
@property
def role(self):
#FIXME: not sure of schema under this node. might need more processing.
return self._nodeContentOrNone('role')
#return a dict of metadata
@property
def metadata(self):
... |
try:
for n in self.dataContent.find('{0}metadata'.format(ns)):
try:
key = n.find('{0}key'.format(ns))
val = n.find('{0}value'.format(ns))
rtn[key] = val
except:
continue
except:
... |
ktbyers/scp_sidecar | ansible_modules/cisco_file_transfer.py | Python | apache-2.0 | 3,025 | 0.002975 | #!/usr/bin/python
"""Ansible module to transfer files to Cisco IOS devices."""
from ansible.module_utils.basic import *
from netmiko import ConnectHandler, FileTransfer
def main():
"""Ansible module to transfer files to Cisco IOS devices."""
module = AnsibleModule(
argument_spec=dict(
host=... | source_file = module.params['source_file']
dest_file = module.params['dest_file']
dest_file_system = module.params['dest_file_system']
enable_scp = module.boolean(module.params['enable_scp'])
overwrite = module.boolean(module.params['overwrite'])
check_mode = module.check_mode
scp_changed = Fal... | correct MD5
if scp_transfer.check_file_exists() and scp_transfer.compare_md5():
module.exit_json(msg="File exists and has correct MD5", changed=False)
if not overwrite and scp_transfer.check_file_exists():
module.fail_json(msg="File already exists and overwrite set to false")
... |
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/elan/Certified_Build.py | Python | gpl-3.0 | 2,028 | 0.0143 | def Send_Certified_By_Automation():
import smtplib
from elan import ElanSettings
import os
from elan.ElanSettings import Script_Runner_Log
def send_email(subject,
body,
user='[email protected]',
pwd='corebrands123',
... | #######################################################BUild number
with open(ElanSettings.Build_File_List) as f:
Elan_Build_List = f.readlines()
Elan_Build_List = [x.strip() for x in Elan_Build_List]
Elan_Build_List.sort()
try:
Elan_Build = Elan_Build_List[-1]
except:
... |
with open(Script_Runner_Log, 'r') as myfile:
body_log=myfile.read()
bodylogList = body_log.split('\n')
bodylogList = bodylogList[::-1]
body_log = "\n".join(str(x) for x in bodylogList)
body_Text = body_log + '\n' + str(os.environ['COMPUTERNAME'])
compName = str(os.environ['COM... |
canvasnetworks/canvas | website/canvas/after_signup.py | Python | bsd-3-clause | 698 | 0.008596 | import urllib
from canvas import util
def make_cookie_key(key):
return 'after_signup_' + str(key)
def _get(request, key):
key = make_cookie_key(key)
val = request.COOKIES.get(key)
if val is not N | one:
val = util.loads(urllib.unquote(val))
return (key, val,)
def get_posted_comment(request):
'''
Gets a comment waiting to be posted, if one exists.
Returns a pair containing the cookie key used to retrieve it and its deserialized JSON.
'''
#TODO use dcramer's django-cookies so that ... | and isolated.
return _get(request, 'post_comment')
|
jianglu/mojo | mojo/tools/mojo_shell.py | Python | bsd-3-clause | 446 | 0.017937 | #!/usr/bin/env python
# Copyright 2014 The C | hromium Authors. All rights reser | ved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
def main():
print 'Good news, the shell runner has moved! Please use: '
print ''
print ' mojo/devtools/common/mojo_shell'
print ''
print 'as you would use mojo_shell.py before.'
return -... |
MisterTofu/scrapy-midleware | middleware/TorProxy.py | Python | gpl-3.0 | 1,353 | 0.000739 | # Source:
# http://stackoverflow.com/questions/21839676/how-to-write-a-downloadhandler-for-scrapy-that-makes-requests-through-socksipy
from txsocksx.http import SOCKS5Agent
from scrapy.core.downloader.handlers.http11 import HTTP11DownloadHandler, ScrapyAgent
from twisted.internet import reactor
from scrapy.xlib.tx impo... | quest)
class ScrapyTorAgent(ScrapyAgent):
def _get_agent(self, request, timeout):
bindaddress = request.meta.get('bindaddress') or self._bindAddress
proxy = request.meta.get('proxy')
self.use_tor = settings['TOR']
self.tor_server = settings['TOR_SERVER']
self.tor_port = se... | rver,
self.tor_port, timeout=timeout,
bindAddress=bindaddress)
agent = SOCKS5Agent(reactor, proxyEndpoint=proxyEndpoint)
return agent
|
jeremiah-c-leary/vhdl-style-guide | vsg/rules/generic/rule_002.py | Python | gpl-3.0 | 575 | 0 |
from vsg.rules import token_indent
from vsg import token
lTokens = []
lTokens.append(token.generic_clause.generic_keyword)
class rule_002(token_indent):
'''
This rule ch | ecks the indent of the **generic** keyword.
**Violation**
.. code-block:: vhdl
entity fifo is
generic (
entity fifo is
generic (
**Fix**
.. co | de-block:: vhdl
entity fifo is
generic (
entity fifo is
generic (
'''
def __init__(self):
token_indent.__init__(self, 'generic', '002', lTokens)
|
scality/scality-manila-utils | setup.py | Python | apache-2.0 | 663 | 0 | # Copyright (c) 2015 Scality SA
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain | a copy of the License at
# |
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing ... |
Rctue/nao-lib | nao_temp.py | Python | gpl-2.0 | 64,405 | 0.01784 | ## Nao functions version 1.41
## change log:
## 1.02: Added class "Region"
## 1.02: Resolution stuff.
## 1.03: Detect() now returns an object of the class "Region()"
## 1.04: Added Aldebarans face detection NaoFaceLocation().
## 1.05: Added the gesture() function and EyeLED() function.
## 1.06: Now able to look ... | offset and gain. Default changed to up -0.2.
## 1.38: Speed of GetImage() improved. Removed dependency on Python Image Library
## 1.39: Removed "from naoqi import xxx" statements.
## 1.40: Added ALRobotPosture proxy, GoToPosture and proper InitPose() and Crouch(); InitProxy rewritten
## 1.41: Added Landmark detect... | und detection
import numpy as np
import cv2
from time import time
from time import sleep
#import Image
import random
import math
import sys
import os
import csv
import naoqi
from collections import deque
__naoqi_version__='2.1'
__nao_module_name__ ="Nao Library"
__version__='2.0'
gftt_list =... |
grplyler/netcmd | netcmd_actions.py | Python | gpl-2.0 | 231 | 0.008658 | __author | __ = 'ryanplyler'
def sayhi(config):
error = None
try:
server_output = "Executing action 'sayhi()'"
response = "HI THERE!"
except:
error = 1
return | server_output, response, error
|
liujuan118/Antiphishing | label_image.py | Python | gpl-3.0 | 1,615 | 0.013622 | import tensorflow as tf, sys
def label_iamge(image_path):
# image_path = sys.argv[1]
# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in t | f.gfile.GFile("/files/retrained_labels.txt")]
# Unpersists graph from file
with tf.gfile.FastGFile("/files/retrained_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
# | Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(softmax_tensor, \
{'DecodeJpeg/contents:0': image_data})
# Sort to show labels of first prediction in order of confidence
top_... |
yamateh/robotframework | src/robot/utils/robotinspect.py | Python | apache-2.0 | 1,085 | 0 | # Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# L | icensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with | the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or imp... |
eduNEXT/edunext-platform | import_shims/studio/third_party_auth/tests/specs/test_google.py | Python | agpl-3.0 | 449 | 0.008909 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-p | osition,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated | _import('third_party_auth.tests.specs.test_google', 'common.djangoapps.third_party_auth.tests.specs.test_google')
from common.djangoapps.third_party_auth.tests.specs.test_google import *
|
wangyang59/tf_models | video_prediction/prediction_input_flo_chair_old.py | Python | apache-2.0 | 4,801 | 0.008956 | # Copyright 2016 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | OR_CHAN)
image1.set_shape([ORIGINAL_HEIGHT, ORIGINAL_WIDTH, COLOR_CHAN])
image1 = tf.cast(image1, tf.float32) / 255.0
image2_buffer = tf.reshape(features["image2_raw"], shape=[])
image2 = tf.image.decode_jpeg(image2_buffer, channels=COLOR_CHAN)
im | age2.set_shape([ORIGINAL_HEIGHT, ORIGINAL_WIDTH, COLOR_CHAN])
image2 = tf.cast(image2, tf.float32) / 255.0
flo = tf.decode_raw(features['flo'], tf.float32)
flo = tf.reshape(flo, [ORIGINAL_HEIGHT, ORIGINAL_WIDTH, 2])
if training:
images = tf.concat([image1, image2], axis=2)
images = tf.image.random... |
kmatheussen/radium | bin/old/X11_MenuDialog.py | Python | gpl-2.0 | 1,375 | 0.055273 |
import sys,os,string
def GFX_MenuDialog(filename,*items):
file=open(filename,'w')
file.writelines(map(lambda x:x+"\n", items))
file.close()
os.system("python X11_MenuDialog.py "+filename);
if __name__=="__main__":
import qt,string
class WidgetView ( qt.QWidget ):
def __init__( self, *arg... | mSelected( self, index ) | :
txt = qt.QString()
txt = "List box item %d selected" % index
print txt
file=open(sys.argv[1],'w')
file.write(self.dasitems[index])
file.close();
a.quit()
a = qt.QApplication( sys.argv )
w = WidgetView()
a.setMainWidget( w )
w.show()
a.exec_loop()
... |
polyaxon/polyaxon | core/polyaxon/polypod/compiler/__init__.py | Python | apache-2.0 | 2,209 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m | ay obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License | is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any, Dict, Optional
from polyaxon.polyflow import V1CompiledOperation
from polyaxon.po... |
httpdss/pinax-mobility | mobility/conf/settings.py | Python | mit | 1,051 | 0.002854 | from django.conf import settings
# PLEASE: Don't change anything here, use your site settings.py
USER_AGENTS = {
'jqtouch': r'AppleWebKit/.*Mobile/',
}
USER_AGENTS.update(getattr(settings, 'MOBILITY_USER_AGENTS', {}))
TEMPLATE_MAPPING = {
'index': ('index_template', 'index.html'),
'display_login_form': (... | login_template', 'login.html'),
'app_index': ('app_index_template', 'app_index.html'),
'render_change_form': ('change_form_template', 'change_form.html'),
'changelist_vi | ew': ('change_list_template', 'change_list.html'),
'delete_view': ('delete_confirmation_template', 'delete_confirmation.html'),
'history_view': ('object_history_template', 'object_history.html'),
'logout': ('logout_template', 'registration/logged_out.html'),
'password_change': ('password_change_template... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.