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 |
|---|---|---|---|---|---|---|---|---|
gangadhar-kadam/nassimapp | support/doctype/maintenance_schedule/maintenance_schedule.py | Python | agpl-3.0 | 10,225 | 0.034425 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import webnotes
from webnotes.utils import add_days, cstr, getdate
from webnotes.model.doc import addchild
from webnotes.model.bean import getlist
f... | e(d.end_date):
msgprint("Start date should be less than end date for item "+d.item_code)
raise Exception
def validate_sales_o | rder(self):
for d in getlist(self.doclist, 'item_maintenance_detail'):
if d.prevdoc_docname:
chk = webnotes.conn.sql("select t1.name from `tabMaintenance Schedule` t1, `tabMaintenance Schedule Item` t2 where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1", d.prevdoc_docname)
if chk:
ms... |
zsjohny/jumpserver | apps/users/models/user.py | Python | gpl-2.0 | 18,955 | 0.000106 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import uuid
import base64
import string
import random
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractUser
from django.core.cache import cache
from django.db import models
from django.... | return False
@lazyproperty
def can_admin_current_org(self):
return current_org.can_admin_by(self)
@lazyproperty
| def can_audit_current_org(self):
return current_org.can_audit_by(self)
@lazyproperty
def can_user_current_org(self):
return current_org.can_user_by(self)
@lazyproperty
def can_admin_or_audit_current_org(self):
return self.can_admin_current_org or self.can_audit_current_org
... |
tehmaze/ansi | ansi/colour/bg.py | Python | mit | 1,639 | 0.025625 | #pylint: disable=C0103,R0903
from ansi.colour.base import Graphic
from ansi.colour.fx import bold
# ECMA-048 standard names
black = Graphic('40')
red = Graphic('41')
green = Graphic('42')
yellow = Graphic('43')
blue = Graphic('44')
magenta = Graphic('45')
cy... | = bold + cyan
boldwhite = bold + white
# High intensity variants
brightblack = Graphic('100')
brightred = Graphic('101')
brightgreen = Graphic('102')
brightyellow = Graphic('103')
brightblue = Graphic('104')
brightmagenta = Graphic('105')
brightcyan = Graphic('106')
brightwh | ite = Graphic('107')
# Convenience wrappers
brown = yellow # Not in ANSI/ECMA-048 standard
grey = white # Not in ANSI/ECMA-048 standard
gray = white # US English
darkgrey = boldblack
darkgray = boldblack # US E... |
shashisp/blumix-webpy | app/gluon/tests/test_cache.py | Python | mit | 3,558 | 0.003092 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for gluon.cache
"""
import os
import unittest
from fix_path import fix_sys_path
fix_sys_path(__file__)
from storage import Storage
from cache import CacheInRam, CacheOnDisk, Cache
oldcwd = None
def setUpModule():
global oldcwd
if oldcwd is ... | ssertEqual(cache('a', lambda: 2, 100), 1)
cache.clear('b')
self.assertEqual(cache('a', lambda: 2, 100), 1)
cache.clear('a')
self.assertEqual(cache('a', lambda: 2, 100), 2)
cache.clear()
self.assertEqual(cache('a', lambda: 3, 100), 3)
self.assertEqual | (cache('a', lambda: 4, 0), 4)
#test singleton behaviour
cache = CacheInRam()
cache.clear()
self.assertEqual(cache('a', lambda: 3, 100), 3)
self.assertEqual(cache('a', lambda: 4, 0), 4)
#test key deletion
cache('a', None)
self.assertEqual(cache('a', lambda:... |
chemelnucfin/tensorflow | tensorflow/python/feature_column/feature_column_v2.py | Python | apache-2.0 | 183,637 | 0.005015 | # 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... | ns:
```python
# Define features and transformations
deep_feature_columns = [age_column, embedded_dept_column]
wide_feature_columns = [dept_column, bucketized_age_column,
cross_dept_age_column]
# Build deep model
estimator = | DNNClassifier(
feature_columns=deep_feature_columns,
hidden_units=[500, 250, 50])
estimator.train(...)
# Or build a wide model
estimator = LinearClassifier(
feature_columns=wide_feature_columns)
estimator.train(...)
# Or build a wide and deep model!
estimator = DNNLinearCombinedClassifi... |
litex-hub/lxbe-tool | lxbe_tool/providers/docker.py | Python | apache-2.0 | 323 | 0.006192 |
"""
Based on this example -> https://github.com/open-power/pdbg/blob/master/.build.sh
TEMPDIR=`mktemp -d ${HOME}/pdbgobjXXXXXX`
RUN_TMP="docker run --rm=true --user=${USER} -w ${TEMPDIR} -v ${HOME}:${HOME} -t ${CONTAINER}"
${RUN_TMP} ${SR | CDIR}/configure --host=arm-linux-gnueabi
${RUN_T | MP} make
rm -rf ${TEMPDIR}
"""
|
AnderssonPeter/pytrafikverket | pytrafikverket/__init__.py | Python | mit | 708 | 0 | """Pytrafikverket module."""
# flake8: noqa
from pytrafikverket.trafikverket import (AndFilter, FieldFilter, FieldSort,
Filter, FilterOperation, NodeHelper,
OrFilter, SortOrder, Trafikverket)
from pytrafikverket.trafikverket_train import ... | TrainStop, TrainStopStatus)
from pytrafikverket. | trafikverket_weather import (TrafikverketWeather,
WeatherStationInfo)
from pytrafikverket.trafikverket_ferry import (TrafikverketFerry,
FerryStop, FerryStopStatus)
|
Comcast/rulio | examples/stockfs.py | Python | apache-2.0 | 4,418 | 0.005885 | #!/usr/bin/python
# Copyright 2015 Comcast Cable Communications Management, 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 ... | ", line, "\n"
line = re.sub(r'[%"\n]+', "", line)
print "clean ", line, "\n"
data = line.split(",")
ns = map(float, data)
q = {}
q["bid"] = ns[0]
q["ask"] = ns[1]
q["change"] = ns[2]
q["percentChange"] = ns[3]
q["lastTradeSize"] = ns[4]
return q
class handler(BaseHTTPReques... | Handler):
def do_GET(self):
protest(self, "You should POST with json.\n")
return
def do_POST(self):
if not self.path == '/facts/search':
protest(self, "Only can do /facts/search.\n")
return
try:
content_length = int(self.headers['Content-Lengt... |
tchellomello/home-assistant | homeassistant/components/firmata/switch.py | Python | apache-2.0 | 2,287 | 0 | """Support for Firmata switch output."""
import logging
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from .const import (
CONF_INITIAL_STATE,
CONF_NEGATE_STA... | ch in board.switches:
pin = switch[CONF_PIN]
pin_mode = switch[CONF_PIN_MODE]
initial = switch[CONF_INITIAL_STATE]
negate = switch[CONF_NEGATE_STATE]
api = FirmataBinaryDigitalOutput(board, pin, pin_mode, initial, negate)
try:
api.setup()
except Firmat... | ince pin already in use.",
switch[CONF_PIN],
)
continue
name = switch[CONF_NAME]
switch_entity = FirmataSwitch(api, config_entry, name, pin)
new_entities.append(switch_entity)
if new_entities:
async_add_entities(new_entities)
class FirmataSw... |
klahnakoski/TestLog-ETL | vendor/jx_sqlite/expressions/number_op.py | Python | mpl-2.0 | 1,194 | 0.000838 | # encoding: utf-8
#
#
# This Source Code Form is subject to the term | s of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division, unicode_literals
from jx_base.expressions import NumberOp as Nu... | wrap
from mo_sql import sql_coalesce
class NumberOp(NumberOp_):
@check
def to_sql(self, schema, not_null=False, boolean=False):
value = SQLang[self.term].to_sql(schema, not_null=True)
acc = []
for c in value:
for t, v in c.sql.items():
if t == "s":
... |
7kbird/chrome | tools/telemetry/telemetry/core/backends/chrome/inspector_runtime.py | Python | bsd-3-clause | 2,006 | 0.008973 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import exceptions
class InspectorRuntime(object):
def __init__(self, inspector_backend):
self._inspector_backend = inspector_backe... | tions.EvaluateException(res['result']['result']['description'])
if res['result']['result']['type'] == 'undefined':
return None
return res['res | ult']['result']['value']
def EnableAllContexts(self):
"""Allow access to iframes."""
if not self._contexts_enabled:
self._contexts_enabled = True
self._inspector_backend.SyncRequest({'method': 'Runtime.enable'},
timeout=30)
return self._max_context_id... |
batra-mlp-lab/DIGITS | digits/frameworks/errors.py | Python | bsd-3-clause | 825 | 0.006061 | # Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved.
from digits.utils import subclass
@subclass
class Error(Exception):
pass
@subclass
class BadNetw | orkError(Error):
"""
Errors that occur when validating a network
"""
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
@subclass
class NetworkVisualizationError(Error):
"""
Errors that occur when validating a network
"""
... | self.message = message
def __str__(self):
return repr(self.message)
@subclass
class InferenceError(Error):
"""
Errors that occur during inference
"""
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
|
xamurej/py3-cli-skel | cli_app/options.py | Python | mit | 888 | 0 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""Module docstring.
This serves as a long usage message.
"""
import configargparse
from cli_app import log
LOG = log.Logger.get()
class Options(object):
def __init__(self):
self.parser = configargparse.ArgParser(
default_config_files=['./conf... | elf.parser.add('-c',
'--my-config',
required=False,
is_config_file=True,
help='config file | path')
# this option can be set in a config file because it starts with '--'
self.parser.add('--text',
required=False,
help='text for output',
default='Hello world',
env_var='APP_TEXT')
def parse(self):... |
diegobill/django-cities | cities/management/commands/table_autocomplete.py | Python | mit | 1,726 | 0.009849 | from django.core.management.base import BaseCommand
from django.db import connections, reset_queries
from ...models import *
class Command(BaseCommand):
def handle(self, *args, **options):
self.table_autocomplete()
def table_autocomplete(self):
#tabela cache para autocomplete
#pegand... | set = 0
places = Place.objects.all()[offset:limit]
sql_packet=''
while len(places)>0:
for place in places:
| for language in languages:
sql = "INSERT INTO cities_table_autocomplete_%s (id, name, slug, active, deleted) VALUES (%s,'%s','%s',%s,%s);" % (
language[:2],
place.id,
place.translated_name(language).replace("'",'"'),
... |
gltn/stdm | stdm/composer/custom_items/label.py | Python | gpl-2.0 | 2,466 | 0.001217 | # /***************************************************************************
# * *
# * 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 *
# * t... | QtCore import (
QCoreApplication
)
from qgis.PyQt.QtXml import (
QDomDocument,
QDomElement
)
from qgis.core import (
QgsLayoutItemRegistry,
QgsLayoutItemAbstractMetadata,
QgsLayoutItemLabel,
QgsReadWriteContext
)
from stdm.ui.gui_utils import GuiUtils
STDM_DATA_LABEL_ITEM_TYPE = QgsLayoutI... | ed_field = None
def type(self):
return STDM_DATA_LABEL_ITEM_TYPE
def icon(self):
return GuiUtils.get_icon('db_field.png')
def linked_field(self) -> Optional[str]:
return self._linked_field
def set_linked_field(self, field: Optional[str]):
self._linked_field = field
... |
onelab-eu/myslice | portal/resources.py | Python | gpl-3.0 | 1,955 | 0.01688 | import json
import time
import re
from django.sho | rtcuts import render
| from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.sites.models import Site
from unfold.page import Page
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_admin_query, exec... |
YongJang/PythonTelegram | examples/referenced/bs4NaverITNews.py | Python | gpl-2.0 | 1,503 | 0.019398 | import pymysql
import sys
import time
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
def getPost() :
html = Request('http://news.naver.com/main/list.nhn | ?mode=LS2D&mid=shm&sid1=105&sid2=230', headers={'User-Agent':'Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)'})
page = urlopen(html).read()
soup = BeautifulSoup(page , from_encoding="utf-8")
page_num_list = soup.find("div" , { "class" : ... |
page_num = len(page_num_list)
date_num_list = soup.find("div" , { "class" : "viewday" }).find_all('a') #page개수
date_num = len(date_num_list)
print("page_num :" + str(page_num))
print("date_num :" + str(date_num))
for n in range(len(page_num_list))
print(page_num_list[n])
print(... |
ray-project/ray | dashboard/modules/snapshot/tests/test_job_submission.py | Python | apache-2.0 | 5,558 | 0.001439 | import logging
import os
import sys
import time
import json
import jsonschema
import pprint
import pytest
import requests
from ray._private.test_utils import (
format_web_url,
wait_for_condition,
wait_until_server_available,
)
from ray.dashboard import dashboard
from ray.dashboard.tests.conftest import * ... | time_s) <= 2
if entry["status"] == "SUCCEEDED":
job_succeeded = True
assert entry["endTime"] >= entry["startTime"] + job_sleep_time_s
return legacy_job_succeeded and job_succeeded
wait_for_condition(wait_for_job_to_succeed, timeout=30)
def test_fai... | = ray_start_with_dashboard.address_info["webui_url"]
assert wait_until_server_available(address)
address = format_web_url(address)
job_sleep_time_s = 5
entrypoint_cmd = (
'python -c"'
"import ray;"
"ray.init();"
"import time;"
f"time.sleep({job_sleep_time_s});"
... |
rtts/qqq | mptt/__init__.py | Python | gpl-3.0 | 879 | 0.005688 |
VERSION = (0, 5, 'pre')
# NOTE: This method was removed in 0.4.0, but restored in 0.4.2 after use-cases were
# reported that were impossible by merely subclassing MPTTModel.
def register(*args, **kwargs):
"""
Registers a model class as an MPTTModel, adding MPTT fields and adding MPTTModel to __bases__.
T... | pt mptt.AlreadyRegistered:
# pass
class AlreadyRegistered(Exception):
"Deprecated - don't use this anymore. It's never thrown, you don't nee | d to catch it"
|
rizumu/dialogos | dialogos/models.py | Python | bsd-3-clause | 880 | 0 | from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Comment(models.Model):
author = models.ForeignKey(User, null=True, related_na... | ield(max_length=255, blank=True)
website = models.CharField(max_length=255, blank=True)
content_type = models.ForeignKey(ContentType)
object_id = models.IntegerField()
content_object = GenericForeignKey()
comment = models.TextField()
submit_date = models.DateTimeField(default=datetime.now)
... | IPAddressField(null=True)
public = models.BooleanField(default=True)
def __unicode__(self):
return "pk=%d" % self.pk
|
317070/kaggle-heart | configurations/j7_jeroen_ch.py | Python | mit | 10,276 | 0.005936 | """Single slice vgg with normalised scale.
"""
import functools
import lasagne as nn
import numpy as np
import theano
import theano.tensor as T
import data_loader
import deep_learning_layers
import image_transform
import layers
import preprocess
import postprocess
import objectives
import theano_printer
import update... | ze, image_size),
| "sliced:data:ax": (batch_size, 30, 15, image_size, image_size),
"sliced:data:shape": (batch_size, 2,),
"sunny": (sunny_batch_size, 1, image_size, image_size)
# TBC with the metadata
}
# Objective
l2_weight = 0.000
l2_weight_out = 0.000
def build_objective(interface_layers):
# l2 regu on certain la... |
tkaitchuck/nupic | examples/bindings/svm_how_to.py | Python | gpl-3.0 | 8,034 | 0.013069 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | ersistence"
numpy.random.seed(42)
n_dims = 2
n_class = 12
size = 100
labels = numpy.random.random_integers(0, 256, size)
samples = numpy.zeros((size, n_dims), dtype=type)
print "Generating data"
for i in range(0, size):
t = 6. | 28 * numpy.random.random_sample()
samples[i][0] = 2 * labels[i] + 1.5 * numpy.cos(t)
samples[i][1] = 2 * labels[i] + 1.5 * numpy.sin(t)
print "Creating dense classifier"
classifier = algo.svm_dense(0, n_dims = n_dims, seed=42)
print "Adding sample vectors to dense classifier"
for y... |
kondra/latent_ssvm | smd.py | Python | bsd-2-clause | 3,199 | 0.006877 | import numpy as np
import sys
from trw_utils import *
from heterogenous_crf import inference_gco
from pyqpbo import | binary_general_graph
from scipy.optimize import fmin_l_bfgs_b
def trw(node_weights, edges, edge_weights, y,
max_iter=100, verbose=0, tol=1e-3,
get_energy=None):
n_nodes, n_states = node_weights.shape
n_edges = edges.shape[0]
y_hat = []
lambdas = np.zeros(n_nodes)
mu = np.zeros((... | s))
_pairwise = np.zeros((n_edges, 2, 2))
for i in xrange(n_edges):
_pairwise[i,1,0] = _pairwise[i,0,1] = -0.5 * edge_weights[i,k,k]
pairwise.append(_pairwise)
for i in xrange(n_edges):
e1, e2 = edges[i]
node_weights[e1,:] += 0.5 * np.diag(edge_weights[i,:,:])
... |
eduNEXT/edx-platform | openedx/features/course_duration_limits/migrations/0003_auto_20181128_1407.py | Python | agpl-3.0 | 601 | 0.001664 | # Generated by Django 1.11.16 on 2018-11-28 19:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_dura | tion_limits', '0002_auto_20181119_0959'),
]
operations = [
migrations.AlterField(
model_name='coursedurationlimitconfig',
name='enabled_as_of',
field=models.DateTimeField(blank=True, default=None, he | lp_text='If the configuration is Enabled, then all enrollments created after this date (UTC) will be affected.', null=True, verbose_name='Enabled As Of'),
),
]
|
pmav99/praktoras | checks.d/cacti.py | Python | bsd-3-clause | 8,178 | 0.001712 | # (C) Fractal Industries, Inc. 2016
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
from collections import namedtuple
from fnm | atch import fnmatch
impo | rt os
import time
# 3rd party
try:
import rrdtool
except ImportError:
rrdtool = None
import pymysql
# project
from checks import AgentCheck
CFUNC_TO_AGGR = {
'AVERAGE': 'avg',
'MAXIMUM': 'max',
'MINIMUM': 'min'
}
CACTI_TO_DD = {
'hdd_free': 'system.disk.free',
'hdd_used': 'system.disk.us... |
CIRCL/AIL-framework | bin/modules/submit_paste.py | Python | agpl-3.0 | 15,703 | 0.004776 | #!/usr/bin/env python3
# -*-coding:UTF-8 -*
"""
The Submit paste module
================
This module is taking paste in redis queue ARDB_DB and submit to global
"""
##################################
# Import External packages
##################################
import os
import sys
import gzip
import io
import redi... | IZE:
self.r_serv_log_submit.set(f'{uuid}:nb_total', 1)
self.create_paste(uuid, paste_content.encode(), ltags, ltagsgalaxies, uuid, source)
time.sleep(0.5)
else:
self.abord_file_submission(uuid, f'Text size is over {SubmitPaste.TEXT_MAX_SIZE} bytes')
def _man... | Create a paste for given file
"""
self.redis_logger.debug('manage')
if os.path.exists(file_full_path):
self.redis_logger.debug(f'file exists {file_full_path}')
file_size = os.stat(file_full_path).st_size
self.redis_logger.debug(f'file size {file_size... |
iksaif/euscan | pym/euscan/scan.py | Python | gpl-2.0 | 5,444 | 0 | from __future__ import print_function
import os
import sys
from datetime import datetime
import portage
import gentoolkit.pprinter as pp
from gentoolkit.query import Query
from gentoolkit.package import Package
from euscan import CONFIG, BLACKLIST_PACKAGES
from euscan import handlers, output
from euscan.out import ... | e).total_seconds()
output.metadata("scan_time", scan_time, show=False)
is_current_version_stable = is_version_stable(ver)
if len(result) > 0:
if not (CONFIG['format'] or CONFIG['quiet']):
print("")
for cp, url, version, handler, confidence in result:
| if CONFIG["ignore-pre-release"]:
if not is_version_stable(version):
continue
if CONFIG["ignore-pre-release-if-stable"]:
if is_current_version_stable and \
not is_version_stable(version):
continue
if CONFI... |
bkosawa/admin-recommendation | admin_recommendation/settings.py | Python | apache-2.0 | 6,881 | 0.001017 | """
Django settings for recomendation project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
from __... | }
}
DATABASE_ROUTERS = ['my_router.MyRouter']
# CELERY STUFF
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://l | ocalhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'America/Sao_Paulo'
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'd... |
google/active-qa | third_party/bi_att_flow/my/tensorflow/__init__.py | Python | apache-2.0 | 51 | 0.019608 | from | third_party.bi_att_flow.my.tensorflow impor | t * |
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/approximation/matching.py | Python | gpl-3.0 | 1,155 | 0 | """
**************
Graph Matching
**************
Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent
edges; that is, no two edges share a common vertex.
`Wikipedia: Matching <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
"""
import networkx as nx
__all__ = ["min_maximal_matching"]... | ----------
.. [1] Vazirani, Vijay A | pproximation Algorithms (2001)
"""
return nx.maximal_matching(G)
|
lem8r/website-themes | facebook_instant_article/models/website_blog.py | Python | lgpl-3.0 | 659 | 0 | # -*- coding: utf-8 -*-
# from openerp import api, fields, models, _
from openerp.osv import osv, fields
from openerp.addons.website.models.website import slug
from op | enerp import SUPERUSER_ID
import requests
class FbBlogPost(osv.Model):
_inherit = 'blog.post'
_columns = {
'fb_content': fields.html('FB Content', sanitize=False),
'fb_import_id': fields.char('FB Import ID'),
'fb_import_status_ok': fields.boolean('FB Import Status',
... | e_id': fields.char('FB Article ID'),
'fb_publisher_token': fields.char('FB Publisher Token'),
}
|
Varun-Teja/Projects | Proxy/Proxy.py | Python | mit | 3,866 | 0.010347 | from socket import *
import sys, time
if len(sys.argv) <= 1:
print 'Usage: "python proxy.py server_ip"\n[server_ip : It is the IP Address of the Proxy Server'
sys.exit(2)
# Create a server socket, bind it to a port and start listening
tcpSERVERPort = 8080
tcpSERVERSock = socket(AF_INET, SOCK_STREAM)
fp = open... | ..'
elap = time.time()
diff = elap - t
# Close the socket and the server sockets
tcpCLIENTSock.close()
fp.write("\n time taken =" + str(diff))
| fp.write("\n bytes sent =" + str(a))
fp.write("\n bytes received =" + str(b))
fp.write("\n")
fp.close()
print "Closing the server connection"
tcpSERVERSock.close()
|
DisposaBoy/GoSublime | gs9o.py | Python | mit | 19,161 | 0.035489 | from .gosubl import about
from .gosubl import gs
from .gosubl import gsq
from .gosubl import gsshell
from .gosubl import mg9
from .gosubl import sh
from .gosubl.margo import mg
from .gosubl.margo_state import actions
import datetime
import json
import os
import re
import shlex
import string
import sublime
import sublim... | : True,
"indent_subsequent_lines": True,
"line_numbers": False,
"auto_complete": True,
"auto_complete_selector": "text",
"highlight_line": True,
"draw_indent_guides": True,
"scroll_past_end": True,
"indent_g | uide_options": ["draw_normal", "draw_active"],
"word_separators": "./\\()\"'-:,.;<>~!@#$%&*|+=[]{}`~?",
}
opts.update(gs.setting('9o_settings'))
for opt in opts:
vs.set(opt, opts[opt])
vs.set("9o", True)
vs.set("9o.wd", wd)
color_scheme = gs.setting("9o_color_scheme", "")
if color_scheme:
if c... |
toobaz/pandas | pandas/compat/_optional.py | Python | bsd-3-clause | 3,494 | 0.000859 | import distutils.version
import importlib
import types
import warnings
# Update install.rst when updating versions!
VERSIONS = {
"bs4": "4.6.0",
"bottleneck": "1.2.1",
"fastparquet": "0.2.1",
"gcsfs": "0.2.2",
"lxml.etree": "3.8.0",
"matplotlib": "2.2.2",
"numexpr": "2.6.2",
"odfpy": "... | ise", "ignore"}
msg = version_message.format(
| minimum_version=minimum_version, name=name, actual_version=version
)
if on_version == "warn":
warnings.warn(msg, UserWarning)
return None
elif on_version == "raise":
raise ImportError(msg)
return module
|
cjcjameson/gpdb | gpMgmt/bin/gppylib/test/unit/test_unit_guccollection.py | Python | apache-2.0 | 12,742 | 0.003061 | from mock import *
from gp_unittest import *
from gpconfig_modules.database_segment_guc import DatabaseSegmentGuc
from gpconfig_modules.file_segment_guc import FileSegmentGuc
from gpconfig_modules.guc_collection import GucCollection
class GucCollectionTest(GpTestCase):
def setUp(self):
self.subject = GucC... | ubject.update(FileSegmentGuc(row))
self.assertIn("Master value: master_value | file: -", self.subject.report())
self.assertIn("Segment value: value | file: -", self.subject.report())
def test_when_multiple_dbids_per_contentid_reports_failure(self):
row = ['-1', 'guc_name', 'master_ | value', '1']
self.subject.update(FileSegmentGuc(row))
row = ['-1', 'guc_name', 'master_value', '2']
self.subject.update(FileSegmentGuc(row))
row = ['0', 'guc_name', 'value', '3']
self.subject.update(FileSegmentGuc(row))
row = ['0', 'guc_name', 'value', '4']
self.... |
aolsux/DeepThought | deepthought/factories.py | Python | gpl-3.0 | 1,527 | 0.00131 | '''
available factories:
feed_forward_perceptron
'''
import numpy
from mlpdata import MLPData
class zero_matrix(object):
def __init__(self, rows, cols):
self.__row | s = rows
self.__cols = cols
def rows(self):
return self.__rows
def cols(self):
return self.__cols
def __repr__(self):
return str(self.rows()) + "x" + str(self.cols()) + " zero matrix"
class numpy_dense_matrix(n | umpy.ndarray):
def rows(self):
return self.shape[0]
def cols(self):
return self.shape[1]
def __repr__(self):
return str(self.rows()) + "x" + str(self.cols()) + " dense matrix"
def feed_forward_factory(layers, afunction):
'''
determines:
- number of layers
... |
sigmunau/nav | python/nav/portadmin/snmputils.py | Python | gpl-2.0 | 31,038 | 0.000161 | #
# Copyright (C) 2010 Norwegian University of Science and Technology
# Copyright (C) 2011-2015 UNINETT AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by
# ... | d, if_index):
"""Query the given interface."""
handle = self._get_read_only_handle()
result = None
try:
result = handle.get(self._get | _query(oid, if_index))
except NoSuchObjectError as no_such_ex:
_logger.debug("_query_netbox: NoSuchObjectError = %s", no_such_ex)
return result
def _get_read_write_handle(self):
"""Get a read and write SNMP-handle.
:rtype: nav.Snmp.Snmp
"""
if self.read_... |
hkust-smartcar/sc-studio | src/sc_studio/string_view.py | Python | mit | 1,489 | 0.032236 | '''
sc_studio.string_view
Author: Ming Tsang
Copyright (c) 2014-2015 HKUST SmartCar Team
Refer to LICENSE for details
'''
import binascii
import logging
import time
import tkinter
from tkinter import Tk, Text
from sc_studio import config
from sc_studio.view import View
class StringView(View):
def __init__(self, par... | )
self._tk = Tk()
self._text | = Text(self._tk, bg = config.COL_GREY_900,
fg = config.COL_GREY_100)
self._tk.title("String view")
self._text.pack(side = tkinter.LEFT, fill = tkinter.Y)
self._tk.protocol("WM_DELETE_WINDOW", self.on_press_close)
self._file = open("string_" + str(int(time.time() * 1000)) + ".txt", "w")
def run(self):
... |
JadsonReis/sistema-nacional-cultura | planotrabalho/utils.py | Python | agpl-3.0 | 880 | 0.001136 | import re
f | rom datetime import date
d | ef get_or_none(model, **kwargs):
try:
return model.objects.get(**kwargs)
except model.DoesNotExist:
return None
def validar_cnpj(cnpj):
cnpj = ''.join(re.findall('\d', str(cnpj)))
if (not cnpj) or (len(cnpj) < 14):
return False
inteiros = list(map(int, cnpj))
novo = i... |
crossroadchurch/paul | openlp/core/ui/firsttimewizard.py | Python | gpl-2.0 | 17,462 | 0.00315 | # -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# ------------------------------------------------------... | self.bible_check_box = QtGui.QCheckBox(self.plugin_page)
self.bible_check_box.setChecked(True)
self.bible_check_bo | x.setObjectName('bible_check_box')
self.plugin_layout.addWidget(self.bible_check_box)
self.image_check_box = QtGui.QCheckBox(self.plugin_page)
self.image_check_box.setChecked(True)
self.image_check_box.setObjectName('image_check_box')
self.plugin_layout.addWidget(self.image_check... |
minaevmike/praktica | Diplom/Samples/minimal-django-file-upload-example-master/src/for_django_1-5/myproject/myproject/myapp/urls.py | Python | gpl-2.0 | 169 | 0.005917 | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import pattern | s, url
urlpatte | rns = patterns('myproject.myapp.views',
url(r'^list/$', 'list', name='list'),
)
|
eroicaleo/LearningPython | PythonTricks/ch04_05.py | Python | mit | 1,316 | 0.007599 | #!/usr/bin/env python
def print_banner(s):
print('##------------------------------------------------------------------------------')
print(f'## {s}')
print('##------------------------------------------------------------------------------')
print_banner('First implementation')
class Base:
def foo(self... | Concrete(Base):
def foo(self):
pass
assert issubclass(Concrete, Base)
try:
print('Instantiate b = Base()')
b = Base()
| except TypeError as err:
print(f'Got this TypeError error: {err!r}')
try:
print('Instantiate c = Concrete()')
c = Concrete()
except TypeError as err:
print(f'Got this TypeError error: {err!r}')
|
ShengGuangzhi/SummerTree | algorithm/python_version/basic/max_sub_array.py | Python | mit | 2,257 | 0.001329 | import math
def max_sub_array(array, begin=None, end=None):
def max_sub_array_mid(arr, begin_m, end_m, middle):
l_sum, l_max_index, l_max_sum = 0, None, None
l_local = middle - 1
while l_local >= begin_m:
l_sum += arr[l_local]
if l_max_index is None:
... | )
m = max_sub_array_mid(array, begin, end, mid)
if l['sum'] >= r['sum'] and l['sum'] >= m['sum']:
return l
elif r['sum'] >= l['sum'] and r['sum'] >= m['sum']:
return r
else:
return m
if __name__ == '__main__':
test_list = [13, -3, -25, 20, -3, -16, -23, 1 | 8, 20, -7, 12, -5, -22, 15, -4, 7]
result = max_sub_array(test_list)
print('begin :', result['begin'], 'end:', result['end'], 'sum:', result['sum'])
|
Axilent/Dox | dox/client.py | Python | bsd-3-clause | 2,050 | 0.019512 | """
Axilent Client functionality for Dox.
"""
from sharrock.client import HttpClient, ResourceClient, ServiceException
from dox.config import get_cfg
from dox.utils import slugify
def _get_resource(app,resource,library=True):
"""
Gets a resource client.
"""
cfg = get_cfg()
apikey_setting = 'library... | a content library resource.
"""
return _get_resource('axilent.library','content')
def get_library_client():
"""
Gets the library API client.
"""
return _get_client('axilent.library')
def ping_library():
"""
Pings the library.
" | ""
cfg = get_cfg()
lib = get_library_client()
lib.ping(project=cfg.get('Connection','project'),content_type=cfg.get('Connection','content_type'))
def get_content_api():
"""
Gets the content API.
"""
return _get_client('axilent.content',library=False)
def get_content_resource():
"""
... |
tartavull/tigertrace | tigertrace/util/rehuman_semantics.py | Python | mit | 1,483 | 0.011463 | from tqdm import tqdm
from collections import defaultdict
import h5py
import networkx as nx
import struct
import numpy as np
# hl = None
# ml = None
# with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/human_semantic_labels.h5','r') as f:
# hl = f['main'][:]
# with h5py.F... | (int))
# def max_key_from_dict( d ):
# max_key = d.keys()[0]
# max_val = d[max_key]
# for k,v in d.iteritems():
# if v > max_val:
# max_val = v
# max_key = k
# return max_key
# for z in tqdm(xrange(hl.shape[0])):
# for y in xrange(hl.shape[1]):
# for x in xrange(hl.shape[2]):
# sof... | mapping[ml_label] = best_hl
# final = np.zeros(shape=ml.shape)
# for z in tqdm(xrange(hl.shape[0])):
# for y in xrange(hl.shape[1]):
# for x in xrange(hl.shape[2]):
# final[z,y,x] = mapping[ml[z,y,x]]
with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/sparse_s... |
sjtsp2008/oompa | oompa/tracking/UpdateLogger.py | Python | apache-2.0 | 6,922 | 0.010546 | #
# UpdateLogger.py
#
"""
package oompa.tracking
TODO: stil waffling about whether to log two-columns - "datetime {json}" or "{json-with-datetime-field}"
"""
import json
import os
from datetime import datetime
class UpdateLogger:
"""
records updates for later replay
"""
def __init__(self, c... | ath):
yield json.loads( | line)
return
def organizeUpdatesByEntity(self, updates):
"""
organize updates by ( subject_kind, subject ) from the update
"""
byEntity = {}
for update in updates:
entity = ( update["subject_kind"], update["subject"] )
byEntity.set... |
vineodd/PIMSim | GEM5Simulation/gem5/src/systemc/tests/verify.py | Python | gpl-3.0 | 19,486 | 0.00195 | #!/usr/bin/env python2
#
# Copyright 2018 Google, Inc | .
#
# 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;
# redistributions 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 th... |
Empire-of-Code-Puzzles/checkio-empire-auto-painting | verification/src/referee.py | Python | gpl-2.0 | 2,173 | 0.001381 | from checkio_referee import RefereeCodeGolf
from checkio_referee import covercodes, validators, representations
import settings_env
from tests import TESTS
class AutoPaintingValidator(validators.BaseValidator):
def validate(self, outer_result):
steps, k, n = self._test["validation_data"]
if not ... | details | = [0 for _ in range(n)]
good_ch = "".join(str(r) for r in range(n))
good_ch += ","
if any(ch not in good_ch for ch in outer_result):
return validators.ValidatorResult(False, "Wrong symbol in the result.")
for act in actions:
if len(act) > k:
retur... |
zhongpei/softether-client | endpoints/main.py | Python | gpl-3.0 | 6,782 | 0.010764 | #!coding: utf-8
"""
Usage:
main.py <host> <username> <password> [-r] [--port=<port>] [--hub=<hub>] [--pppoe-username=<username>] [--pppoe-password=<password>] [--output=<output>]
Options:
-h --help Show help
-r Change route to make connect to Packetix Server alwa... | split("|")
if key.find("Session Status") != -1 :
if value.find("Connection Completed (Session Established)") != -1:
return True,value
else:
return False,value
return False,"error"
if __name__ == '__main__':
args = docopt | (__doc__)
logging.basicConfig(
level=logging.DEBUG,
format='%(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
#print args
if args.get("--env"):
if os.getenv("HOST"):
args['<host>'] = os.getenv("HOST")
if os.getenv("USERNAME"):
args['<... |
jairomoldes/PyTango | tango/exception.py | Python | lgpl-3.0 | 6,718 | 0.002233 | # ------------------------------------------------------------------------------
# This file is part of PyTango (http://pytango.rtfd.io)
#
# Copyright 2006-2012 CELLS / ALBA Synchrotron, Bellaterra, Spain
# Copyright 2013-2014 European Synchrotron Radiation Facility, Grenoble, France
#
# Distributed under the terms of ... | ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
# DevError pickle
# -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
def __DevError__getin | itargs__(self):
return ()
def __DevError__getstate__(self):
return self.reason, self.desc, self.origin, int(self.severity)
def __DevError__setstate__(self, state):
self.reason = state[0]
self.desc = state[1]
self.origin = state[2]
self.severity = ErrSeverity(state[3])
def __init_DevError()... |
chenke91/ckPermission | app/api_v1/resources/tests.py | Python | mit | 403 | 0.009926 | #encoding: utf-8
from flask.ext.restful import Resource, reqparse
class Test(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('id', type=int)
super(AccountAPI, self).__init__()
| def get(self):
return {'id': id}
def post(self):
p | ass
def put(self):
pass
def delete(self):
pass |
PersianWikipedia/pywikibot-core | scripts/archive/__init__.py | Python | mit | 99 | 0 | # -*- | coding: utf-8 -*-
"""THIS DIRECTORY IS TO HOLD B | OT SCRIPTS THAT NO LONGER ARE MAINTAINED."""
|
mwillmott/techbikers | server/urls.py | Python | mit | 482 | 0 | fro | m django.conf.urls import include, url
from django.views.generic.base import RedirectView
from server.views import app
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Uncomment the next line to enable | the admin:
url(r'^admin/', include(admin.site.urls)),
# API
url(r'^api/', include('server.api.urls')),
# Catchall and routing is handled by the client app
url(r'^', app)
]
|
yunojuno/django-s3-upload | example/migrations/0001_initial.py | Python | mit | 1,676 | 0.002983 | # Generated by Django 3.1 on 2020-08-25 12:15
import django.db.models.deletion
from django.db import migrations, models
import s3upload.fields
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Cat",
fie... | models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"custom_filename",
s3upload.... | n",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
... |
matthappens/taskqueue | taskqueue/venv_tq/lib/python2.7/site-packages/gevent/coros.py | Python | mit | 251 | 0.011952 | # This module definitely remains in 1.0.x, probably in versions after that too.
import warnings
warnings.warn('geven | t.coros has been renamed to gevent.lock', DeprecationWarning, stacklevel=2)
from gevent.lock import *
from gev | ent.lock import __all__
|
brianrodri/oppia | core/domain/user_domain.py | Python | apache-2.0 | 46,090 | 0.000195 | # coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | les: list(str). Roles of the user.
banned: bool. Whether the uses is banned.
username: str or None. Identifiable username to display in the UI.
last_agreed_to_terms: datetime.datetime or None. When the user
last agreed to the terms of the site.
last_starte... | me or None. When
the user last started the state editor tutorial.
last_started_state_translation_tutorial: datetime.datetime or None.
When the user last started the state translation tutorial.
last_logged_in: datetime.datetime or None. When the user last
... |
airfrog/okws | test/regtest/cases/85.py | Python | gpl-2.0 | 1,198 | 0.038397 |
import copy
description = "test sort"
arr = [ 10, 3, 44, 15, 40 , | -10, -1000, 0, 0, 3000]
arr2 = [ -10.2, 4.33, 1.999, -399.22, -10000.1001, 10.9, 3.922, 59.01, -33.11, 0.3, 0.2, 0.1, 0.001, -0.001, -0.2, -0.4, -0.3, -0.222 ]
arr3 = [ { "key" : k } for k in arr2 ]
filedata = """{$
locals { v : %(ar | r)s, v2 : [], w : %(arr2)s, u : %(arr3)s, l }
def rcmp (a, b) { return b - a; }
v2 = sort (v, cmp);
v3 = sort (v, rcmp);
v4 = sort (w);
l = lambda (a,b) {
locals { diff : b.key - a.key };
return cmp_float (diff);
} ;
v5 = sort (u, l);
v6 = sort2 (u, lambda (x) { return (0... |
JeyZeta/Dangerous | Dangerous/Weevely/modules/shell/sh.py | Python | mit | 3,972 | 0.012085 | '''
Created on 22/ago/2011
@author: norby
'''
from core.moduleexception import ModuleException, ProbeException, ExecutionException, ProbeSucceed
from core.moduleguess import ModuleGuess
from core.argparse import ArgumentParser, StoredNamespace
from core.argparse import SUPPRESS
from ast import literal_eval
import rand... | )
self.argparser.add_argument('-no-stderr', help='Suppress error output', action='store_false')
self.argparser.add_argument( | '-vector', choices = self.vectors.keys())
self.argparser.add_argument('-just-probe', help=SUPPRESS, action='store_true')
def _init_stored_args(self):
self.stored_args_namespace = StoredNamespace()
setattr(self.stored_args_namespace, 'vector', None )
def _execute_vector(self):
... |
sozforex/furry-train | tests/test_nettoips.py | Python | mit | 1,059 | 0.002833 | from click.testing import CliRun | ner
from furrytrain.nettoips import main
def test_main():
cases = [(' 10.234.10.0/30 ',
'10.234.10.0\n10.234.10.1\n10.234.10.2\n10.234.10.3\n'),
('1000.234.10.0/30',
'error: 1000.234.10.0/30\n'),
('1000.234.10.0/30 ',
'error: 1000.234.10.0/30 \n... | '255.255.255.253\n'
'255.255.255.254\n'
'255.255.255.255\n'),
('192.168.0.0/31',
'192.168.0.0\n192.168.0.1\n'),
]
for input, output in cases:
isolated_main(input, output)
def isolated_main(input, output, only_cidr=True):
runner =... |
llvm-mirror/lldb | packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py | Python | apache-2.0 | 3,765 | 0.000531 | """
Test breakpoint command for different options.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
class BreakpointOptionsTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test(self):
"""Test bre... | d("settings set tar | get.language c")
lldbutil.run_break_set_by_symbol(
self, 'ns::func', sym_exact=False, num_expected_locations=0)
# Run the program.
self.runCmd("run", RUN_SUCCEEDED)
# Stopped once.
self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
substr... |
jbu/personis | personis/examples/aelog/httplib2/__init__.py | Python | gpl-3.0 | 68,094 | 0.005698 | from __future__ import generators
"""
httplib2
A caching http interface that supports ETags and gzip
to conserve bandwidth.
Requires Python 2.3 or later
Changelog:
2007-08-18, Rick: Modified so it's able to use a socks proxy if needed.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright... | ock, keyfile=key_file, certfile=cert_file,
cert_reqs=cert_reqs, ca_certs=ca_certs)
except (AttributeError, ImportError):
ssl_SSLError = None
def _ssl_wrap_ | socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, ... |
pedsm/deepHack | old/rating/main.py | Python | mit | 126 | 0.007937 | def rate(Likes, Comme | nts, Tags):
a = 0.0143
b = 0.0413
c = 0.0367
return Likes * a + Comments * b + Tags * c
| |
KMarkert/servir-vic-training | scripts/calibrate_vic.py | Python | gpl-3.0 | 6,662 | 0.01486 | #******************************************************************************
# FILE: calibrate_vic.py
# AUTHOR: Kel Markert
# EMAIL: kel.markert@nasa.gov
# ORGANIZATION: NASA-SERVIR, UAH/ESSC
# MODIFIED BY: n/a
# CREATION DATE: 22 Feb. 2017
# LAST MOD DATE: 03 Apr. 2017
# PURPOSE: This script performs a simple calib... | ')
simSeries = xr.DataArray(simCsv.Discharge,coords=[ | simtimes],dims=['time'])
simSeries = simSeries.sel(time=slice('2005-03-01','2009-12-31')).data
# calculate model performance statistics
r = stats.pearsonr(obsSeries,simSeries)
nse = 1 - (sum((obsSeries-simSeries)**2)/sum((obsSeries-obsSeries.mean())**2))
bias = np.mean(simSeries... |
mwilliamson/abuse | python/test/abuse/test_parse.py | Python | bsd-2-clause | 5,846 | 0.008724 | import funk
from funk import expects
from funk import allows
from funk.tools import assert_that
import funk.matchers as m
from abuse.generate import RuleSet
from abuse.generate import NonTerminal
from abuse.parse import parse
from abuse.parse import MissingArrow
from abuse.parse import MissingClosingBrace
from abuse.p... | 14)",
line_number=3, character_number=14, non_terminal="INSULT"),
m.is_a(NoProductionRule)
)))
@funk.with_co | ntext
def test_adds_error_if_sentence_has_no_production_rule(context):
errors = []
parse("", RuleSet(), errors);
assert_that(errors, m.contains_exactly(m.all_of(
m.has_attr(message="No production rule for non-terminal $SENTENCE",
non_terminal="SENTENCE"),
m.is_a(... |
comic/comic-django | app/grandchallenge/jqfileupload/migrations/0001_initial.py | Python | apache-2.0 | 1,357 | 0.000737 | # Generated by Django 1.11.11 on 2018-03-20 18:38
from django.db import migrations, models
import grandchallenge.jqfileupload.models
class Migration(migrations.Migration):
| initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="StagedFile",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
... | verbose_name="ID",
),
),
("csrf", models.CharField(max_length=128)),
("client_id", models.CharField(max_length=128, null=True)),
("client_filename", models.CharField(max_length=128)),
("file_id", models.UUIDField()),
... |
choltha/mailinabox | management/mailconfig.py | Python | cc0-1.0 | 21,317 | 0.028193 | #!/usr/bin/python3
import subprocess, shutil, os, sqlite3, re
import utils
from email_validator import validate_email as validate_email_, EmailNotValidError
import idna
def validate_email(email, mode=None):
# Checks that an email address is syntactically valid. Returns True/False.
# Until Postfix supports SMTPUTF8,... | CII
# characters only; IDNs must be IDNA-encoded.
#
# When mode=="user", we're checking that this can be a user account name.
# Dovecot has tighter restrictions - letters, numbers, underscore, and
# dash only!
#
# When mode=="alias", we're allowing anything that can be in a Postfix
# alias table, i.e. omitting ... | part ("@domain.tld") is OK.
# Check the syntax of the address.
try:
validate_email_(email,
allow_smtputf8=False,
check_deliverability=False,
allow_empty_local=(mode=="alias")
)
except EmailNotValidError:
return False
if mode == 'user':
# There are a lot of characters permitted in email addresse... |
Fuchai/Philosophy-Machine | vae_mining/binary_mining.py | Python | apache-2.0 | 1,418 | 0.022567 | # binary mining.
# say we have a pair of binary encoded predicates, and we have have a sample of the truth values of them
# we want to learn if some logic exist between the two predicates. A->B or B->A. Nothing more.
# given bayesian null prior, establish a confidence method to hypothesize and learn.
# Just a sanity ch... | )
print(clf.predict_proba([1]))
# Done. This example just illustrates that decisio | n tree can learn binary predicates pretty easily.
# Most of the time extraction of feature to produce binary labels will be much harder than anything.
# We will use VAE to achieve that.
# Second tttest. I want to spot the permutation with decision tree.
#
# Try to use softmax to encode.
# Actually a good ide... |
mkuron/espresso | testsuite/scripts/tutorials/test_04-lattice_boltzmann_part2.py | Python | gpl-3.0 | 1,053 | 0 | # Copyright (C) 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 version.
#
# ESPResSo is distributed in the hope that it will be useful,
# but WITHO | UT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unitt... |
oculusstorystudio/kraken | Python/kraken/core/objects/operators/operator.py | Python | bsd-3-clause | 12,620 | 0.001189 | """Kraken - objects.operators.operator module.
Classes:
Operator - Base operator object.
"""
import re
from kraken.core.configs.config import Config
from kraken.core.objects.scene_item import SceneItem
class Operator(SceneItem):
"""Operator representation."""
def __init__(self, name, parent=None, metaData=... | elif token is 'type':
builtName += nameTemplate['types | '][objectType]
elif token is 'name':
builtName += self.getName()
elif token is 'component':
if self.getParent() is None:
skipSep = True
continue
builtName += self.getParent().getName()
elif to... |
SteveMcGrath/Concord | registration/app.py | Python | gpl-2.0 | 1,312 | 0.000762 | from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
app = Flask(__name__)
app.config.from_object('config')
db =... | (db.Text)
redeemed = db.Column(db.Boolean, default=False)
email = db.Column(db.Text)
name = db.Column(db.Text)
classes = db.Column(db.PickleType)
@app.route('/<tickethash>')
def checkin(tickethash):
ticket = Ticket.query.filter_by(ticket_hash=tickethash).first()
if ticket is None:
mess... | rue
db.session.merge(ticket)
db.session.commit()
message, code = ['Successfully Checked in!', 'success']
return render_template('page.html', message=message, code=code, ticket=ticket)
|
sven-hm/pythonocc-core | examples/core_topology_edge.py | Python | lgpl-3.0 | 3,032 | 0.004947 | ##Copyright 2009-2015 Thomas Paviot (tpaviot@gmail.com)
##
##This file is part of pythonOCC.
##
##pythonOCC 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
##(... | al Public License
##alo | ng with pythonOCC. If not, see <http://www.gnu.org/licenses/>.
import math
from OCC.gp import gp_Pnt, gp_Lin, gp_Ax1, gp_Dir, gp_Elips, gp_Ax2
from OCC.BRepBuilderAPI import (BRepBuilderAPI_MakeEdge,
BRepBuilderAPI_MakeVertex)
from OCC.TColgp import TColgp_Array1OfPnt
from OCC... |
MSFTOSSMgmt/WPSDSCLinux | Providers/Scripts/2.4x-2.5x/Scripts/nxEnvironment.py | Python | mit | 9,103 | 0.002087 | #!/usr/bin/env python
# ===================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# See license.txt for license information.
# ===================================
import os
import sys
import imp
protocol = imp.load_source('protocol', '../protocol.py')
nxDSCLog = imp.load_source('n... | t':
# set the variable to the new values
l = p.Name + '=' + p.Value + '\n'
n += l
el | se:
n += l
# not found - present requested so add it.
if not found and p.Ensure == 'present':
if p.Path is True: |
phantom-root/tasks | hashes/300_homemade_hash/other/botanlq/calc_script.py | Python | mit | 814 | 0.003686 | R = [x for x in range(97, 123) if chr(x) not in 'tfpeqwzgnib']
b = 0x56, 0x2B, 0x0F, 0xC5
number = 0
for x0 in R:
for x1 in R:
for x3 in R:
_00 = b[0] ^ x0
_11 = b[1] | x1
Y0 = _00 ^ _11
Y1 = b[3] ^ _11
Y3 = b[2 | ] & (_00 & x3)
for x4 in R:
for x5 in R:
t_00 = Y0 ^ x4
t_11 = Y1 | x5
if (t_00 ^ t_11) == 0xDD and (Y3 ^ t_11) == 0xFE:
x6 = 0x9A ^ t_11
if x6 in R:
... | number += 1
#print(s)
print(number)
|
subutai/nupic.research | src/nupic/research/frameworks/pytorch/regularization.py | Python | agpl-3.0 | 2,505 | 0.003593 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | from the updates on the
# regular objective function
loss.backward()
optimizer.step()
l1_regularization_step(params=model.parameters(), lr=0.1, weight_decay=1e-3)
:param params: a | list of parameters on which the L1 regularization update will be
performed, conditioned on whether attribute `requires_grad` is True
:param lr: the learning rate used during optimization, analogous to the `lr`
parameter in `torch.optim.SGD`
:param weight_decay: the L1 penalty c... |
CalvinHsu1223/LinuxCNC-EtherCAT-HAL-Driver | configs/sim/gladevcp/hitcounter.py | Python | gpl-2.0 | 28 | 0.035714 | ../../gladev | cp/hitcount | er.py |
idaholab/raven | tests/framework/PostProcessors/TSACharacterizer/TrainingData/generators.py | Python | apache-2.0 | 3,313 | 0.009055 | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.or | g/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
# limitation... | 0):
"""
Generates a signal using Fourier properties.
@ In, amps, np.array, amplitudes of waves
@ In, periods, np.array, periods to use
@ In, phases, np.array, phase offsets to use
@ In, pivot, np.array, time-like parameter
@ In, mean, float, offset value
@ Out, signal, np.array, generated ... |
zamattiac/SHARE | providers/edu/opensiuc/migrations/0001_initial.py | Python | apache-2.0 | 661 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-08 15:45
from __future__ import unicode_literals
from | django.db import migrations
import share.robot
class Migration(migrations.Migration):
dependencies = [
('share', '0001_initial'),
('djcelery', '0001_initial'),
]
operations = [
migrations.RunPython(
code=share.robot.RobotUserMigration('edu.opensiuc'),
),
... | n('edu.opensiuc'),
),
]
|
wb253/goapp | app/pingback.py | Python | gpl-3.0 | 5,006 | 0.005793 | # vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2003, Mathieu Fenniak
# 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 abov... | (txt)
le.close()
return links
def autoPingback(sourceURI, reST = None, HTML = None):
"""Scans the input text, which can be in either reStructuredText or HTML
format, pings every linked website for auto-discovery-capable pingback
servers, and does an appropriate pingback.
The following... | reST != None or HTML != None
if reST != None:
links = reSTLinks(reST)
else:
links = htmlLinks(HTML)
for link in links:
util.do_pingback(sourceURI,link)
|
jiarong/SSUsearch | scripts/plot-pcoa.py | Python | bsd-3-clause | 2,303 | 0.012158 | #! /usr/bin/env python
# by gjr; 021514
"""
Plot PCoA results from pcoa in mothur
% python plot-pcoa.py <file.pcoa.axis> <file.pcoa.loadings> <outfile>
"""
import sys, os
import matplotlib
matplotlib.use('Agg')
#matplotlib.use('Pdf')
import matplotlib.pyplot as plt
import numpy as np
import brewer2mpl
i | mport pandas
almost_black = '#262626'
def main():
if len(sys.argv) != 4:
print >> sys.stderr, \
'Usage: python %s <file.pcoa.axis> <file.pcoa.loadings> <outfile>'\
%(os.path.basename(sys.argv[0]))
sys.exit(1)
outfile = sys.argv[3]
if outfile.lower().endswith... | df = pandas.read_csv(sys.argv[1], sep='\t', index_col=False)
#df = pandas.read_csv(sys.argv[1], sep='\t')
df = df.set_index('group', drop=True, append=False)
df = df.dropna(how='all')
# only first two dimensions
dfx = df[[0,1]]
# % variation explained
df2 = pandas.read_csv(sys.argv[2], ... |
waterponey/scikit-learn | sklearn/ensemble/iforest.py | Python | bsd-3-clause | 11,906 | 0.000168 | # Authors: Nicolas Goix <nicolas.goix@telecom-paristech.fr>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# License: BSD 3 clause
from __future__ import division
import numpy as np
import scipy as sp
from warnings import warn
from scipy.sparse import issparse
import numbers
from ..external... | random_state=random_state),
# here above max_features has no links with self.max_features
bootstrap=bootstrap,
bootstrap_features=False,
n_estimators=n_estimators,
max_samples=max_samples,
max_features=max_features,
n_jobs=n_jobs,
... | n = contamination
def _set_oob_score(self, X, y):
raise NotImplementedError("OOB score not supported by iforest")
def fit(self, X, y=None, sample_weight=None):
"""Fit estimator.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
... |
GFZ-Centre-for-Early-Warning/REM_RRVS | webapp/models.py | Python | bsd-3-clause | 6,057 | 0.006604 | '''
---------------------------
models.py
---------------------------
Created on 24.04.2015
Last modified on 13.01.2016
Author: Marc Wieland, Michael Haas
Description: Defines the database model
----
'''
from webapp import db
from flask_security import RoleMixin, UserMixin
from geoalchemy2 import Geometry
from sqla... | _args__ = {'schema':'users'}
id = db.Column(db.Integer(), primary_key=True)
name = ''
class User(db.Model, UserMixin):
"""
User for RRVS
"""
__tablename__="users"
__table_args__ = {'schema':'users'}
id = db.Column(db.Integer(), primary_key=True)
authenticated = db.Column(db.Boolea... | ''
def is_active(self):
"""True, as all users are active."""
return True
def get_id(self):
"""Return the taskid to satisfy Flask-Login's requirements."""
return self.id
def is_authenticated(self):
"""Return True if the user is authenticated."""
return self... |
sserrot/champion_relationships | venv/Lib/site-packages/win32/Demos/win32wnet/testwnet.py | Python | mit | 3,461 | 0.030338 | import win32api
import win32wnet
import sys
from winnetwk import *
import os
possible_shares = []
def _doDumpHandle(handle, level = 0):
indent = " " * level
while 1:
items = win32wnet.WNetEnumResource(handle, 0)
if len(items)==0:
break
for item in items:
try:
if item.dwDisplayType == RESOURC... | esource(handle, 0)
if len(items)==0:
break
xtra = [i.lpLocalName[0].lower() for i in items if i.lpLocalName]
existing.extend(xtra)
finally:
handle.Close()
for maybe in 'defghijklmnopqrstuvwxyz':
if maybe not in existing:
return maybe
raise RuntimeError("All drive mappings are taken?")
def Tes | tConnection():
if len(possible_shares)==0:
print("Couldn't find any potential shares to connect to")
return
localName = findUnusedDriveLetter() + ':'
for share in possible_shares:
print("Attempting connection of", localName, "to", share.lpRemoteName)
try:
win32wnet.WNetAddConnection2(share.dwType, localNa... |
EdDev/vdsm | lib/vdsm/throttledlog.py | Python | gpl-2.0 | 3,750 | 0 | #
# Copyright 2016-2017 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 ... |
Depending on throttling settings and the | current logging level `message`
and `args` may not be logged at all. So don't perform expensive
preprocessing of `args` before calling this function. If you need to
modify it before logging it, you may want to use something like
`vdsm.common.logutils.Suppressed` or its subclasses.
"""
... |
Tvlistings/tuxtrax | penguicontrax/api/functions.py | Python | gpl-3.0 | 593 | 0 | from flask import g
def return_null_if_not_logged_in(func):
def return_none(*args, **kwargs):
if g.user is None:
return "You must be logged in to perform this action.", 401
return func(*args, **kwargs)
return return_none
def return_null_if_not_staff(func):
def return_ | none(*args, **kwargs) | :
if g.user is None:
return "You must be logged in to perform this action.", 401
if not g.user.staff:
return "You must be staff to perform this action.", 403
return func(*args, **kwargs)
return return_none
|
Blue-Labs/utf8-percentage-complete-bar | completion-status-bar.py | Python | apache-2.0 | 3,154 | 0.011097 | #!/usr/bin/env python
'''
Need to put your tty into utf8 mode? see utf-8(7) man page
The official ESC sequence to switch from an ISO 2022 encoding scheme (as used for
instance by VT100 terminals) to UTF-8 is ESC % G ("\x1b%G"). The corresponding
return sequence from UTF-8 to ISO 2022 is ESC % @ ("\x1b%@")... | e #0')
print()
draw_completion_status_bar(1, 'status line #1')
print()
for n in range(19):
draw_completion_status_bar(n, 'status line #2')
time.sleep(0.1)
print()
draw_completion_status_bar(57, 'status line #3')
print()
draw_completion_status_bar(100, 'status line | #4')
print()
if __name__ == '__main__':
if False: # want to see what your current encoding information is?
print('STDOUT Encoding: %s, isatty(%s), locale.getpreferredencoding(%s), sys.getfilesystemencodig(%s)' %(
sys.stdout.encoding, sys.stdout.isatty(), locale.getpreferredencoding(), sys.g... |
RussTheAerialist/zensitting | daemon/zend/__init__.py | Python | gpl-2.0 | 20 | 0 | _ | _author__ = 'rhay'
| |
pchaigno/grr | gui/http_api_test.py | Python | apache-2.0 | 6,014 | 0.004656 | #!/usr/bin/env python
"""Tests for HTTP API."""
import json
from grr.gui import api_aff4_object_renderers
from grr.gui import api_call_renderers
from grr.gui import http_api
from grr.lib import flags
from grr.lib import registry
from grr.lib import test_lib
from grr.lib import utils
from grr.lib.rdfvalues import s... | t_renderers.Api | AFF4ObjectRendererArgs,
"RDFValueCollection": (api_aff4_object_renderers.
ApiRDFValueCollectionRendererArgs)
}
def Render(self, args, token=None):
result = {
"method": "GET",
"path": args.path,
"foo": args.foo
}
if args.additional_args:
... |
indrajitr/ansible | lib/ansible/modules/cron.py | Python | gpl-3.0 | 25,911 | 0.00274 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Dane Summers <dsummers@pinedesk.biz>
# Copyright: (c) 2013, Mike Grozak <mike.grozak@gmail.com>
# Copyright: (c) 2013, Patrick Callahan <pmc@patrickcallahan.com>
# Copyright: (c) 2015, Evan Kaufman <evan@digitalflophouse.com>
# Copyright: (c) 2015, Luca... | - Description | of a crontab entry or, if env is set, the name of environment variable.
- Required if C(state=absent).
- Note that if name is not set and C(state=present), then a
new crontab entry will always be created, regardless of existing ones.
- This parameter will always be required in future releases.... |
jfkirk/tensorrec | test/test_representation_graphs.py | Python | apache-2.0 | 2,973 | 0.004709 | from nose_parameterized import parameterized
from unittest import TestCase
from tensorrec import TensorRec
from tensorrec.representation_graphs import (
LinearRepresentationGraph, NormalizedLinearRepresentationGraph, FeaturePassThroughRepresentationGraph,
WeightedFeaturePassThroughRepresentationGraph, ReLURepr... | NormalizedLinearRepresentationGraph, 50, 60, 20],
["fpt_user", FeaturePassThroughRepresentationGraph, NormalizedLinearRepresentationGraph, 50, 60, 50],
["fpt_item", NormalizedLin | earRepresentationGraph, FeaturePassThroughRepresentationGraph, 50, 60, 60],
["fpt_both", FeaturePassThroughRepresentationGraph, FeaturePassThroughRepresentationGraph, 50, 50, 50],
["weighted_fpt", WeightedFeaturePassThroughRepresentationGraph, WeightedFeaturePassThroughRepresentationGraph,
50, ... |
google/upvote_py2 | upvote/gae/utils/user_utils.py | Python | apache-2.0 | 901 | 0.00333 | # Copyright 2017 Google Inc. All Righ | ts 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/LICEN | SE-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 Lice... |
mudragada/util-scripts | PyProblems/LogFileProcessing/logFileParser.py | Python | mit | 1,318 | 0.002276 | """ 1. Parse log file of a webserver
2. Print the filename and number of bytes delivered for 200 responses
"""
import re
import sys
from os import path
import operator
import itertools
log_file_path = "server.log"
log_data = []
pattern = re.compile(r'\[(?P<time>.+)\](\s+\")(?P<requestType>\w+)(\s+)(?P<fileName>.... | em['bytes'])
respCode = item['httpResponse']
if (respCode == '200'):
if key not in fileDict.keys():
fileDict[key] = value
else:
oldValue = int(fileDict.get(key))
value = oldValue+value
fileDict[key] = value
print(fileDict)
print( | dict(sorted(fileDict.items(), key=operator.itemgetter(1))))
sorted_fileDict = dict(sorted(fileDict.items(), key=operator.itemgetter(1)))
out_Dict = dict(itertools.islice(sorted_fileDict.items(), 10))
for k, v in out_Dict.items():
print (str(k) + " " + str(v))
|
gutomaia/nesasm_py | nesasm/__init__.py | Python | bsd-3-clause | 985 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import argparse
from nesasm.compiler import compile_file
def main(argv=None):
parser = argparse.ArgumentParser(
prog="nesasm",
description='NESasm - NES Assembly Compiler',
epilog='')
subparsers = parser.add_subparsers(
... | bparsers.add_parser('asm') # TODO, aliases=['asm'])
asm_cmd.add_argument('input', nargs='?', metavar='INPUT',
help="input c6502 asm file")
asm_cmd.add_argument('-o', '--output', metavar='OUTPUT',
help="output NES file")
asm_cmd.add_argument('-p', '--path', ... | :])
args.func(args)
def exec_asm(args):
compile_file(args.input, output=args.output, path=args.path)
|
hyphaltip/cndtools | util/rotateTabDelim.py | Python | gpl-2.0 | 1,070 | 0.001869 | #!/usr/bin/env python
# Copyright (c) 2006
# Colin Dewey (University of Wisconsin-Madison)
# cdewey@biostat.wisc.edu
#
# 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 Li... | it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, | write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys
rows = [line[:-1].split('\t') for line in sys.stdin]
maxLen = max(map(len, rows))
for row in rows:
if len(row) < maxLen:
row.extend(["NA"] * (maxLen - len(row)))
rows = zip(*rows)
for row in ... |
puttarajubr/commcare-hq | custom/ilsgateway/tanzania/handlers/keyword.py | Python | bsd-3-clause | 786 | 0.001272 | from corehq.apps.sms.api import send_sms_to_verified_number
from corehq.util.translation import localize
from django.utils.transla | tion import ugettext as _
class KeywordHandler(object):
def __init__(self, user, domain, args, verified_contact, msg):
self.user = user
self.domain = domain
self.args = args
self.verified_contact = verified_contact
self.msg = msg
def handle(self):
raise NotImp... | d_contact.owner
with localize(owner.get_language_code()):
send_sms_to_verified_number(self.verified_contact, _(message) % kwargs)
|
vishnupriyam/review-classification | classify.py | Python | cc0-1.0 | 1,294 | 0.016229 | import sys
import pickle
from nltk.tokenize import word_tokenize
from cleaneddata.remove_stopwords_nltk import read_words, clean_review
from model.generateModel import generatemodel
from validation.validate import predict
review = raw_input("Enter a review to classify: ")
try:
paramfile = open("model/savedmodel.p... | _words("cleaneddata/stopwords.txt")
review = clean_review(review,stopwords)
#predict the class of the review
testreview = []
testreview.append(review)
predicted_class = predict(testreview,PP,PN,positive_probabilities,negative_probabilities,unseen_pos_prob,unseen_neg_prob)
print(predicted_cla | ss)
|
Opentrons/labware | api/tests/opentrons/protocols/execution/test_execute_python.py | Python | apache-2.0 | 2,472 | 0 | import pytest
from opentrons.protocol_api import ProtocolContext
from opentrons.protocols.execution import execute, execute_python
from opentrons.protocols.parse import parse
def test_api2_runfunc():
def noargs():
pass
with pytest.raises(SyntaxError):
execute_python._runfunc_ok(noargs)
d... | te.run_protocol(p | roto, context=ctx)
def test_bad_protocol(loop):
ctx = ProtocolContext(loop)
no_args = parse('''
metadata={"apiLevel": "2.0"}
def run():
pass
''')
with pytest.raises(execute_python.MalformedProtocolError) as e:
execute.run_protocol(no_args, context=ctx)
assert "Function 'run()' does no... |
robertoalotufo/ia636 | ia636/iadctmatrix.py | Python | bsd-3-clause | 322 | 0.021739 | # -*- encoding: utf-8 -*-
# Module iadctmatrix
from numpy import *
def iad | ctmatrix(N):
from iameshgrid import iameshgrid
x, u = iameshgrid(range(N), range(N)) # (u,x)
alpha = ones((N,N)) * sqrt(2./N)
alp | ha[0,:] = sqrt(1./N) # alpha(u,x)
A = alpha * cos((2*x+1)*u*pi / (2.*N)) # Cn(u,x)
return A
|
Francis-Liu/animated-broccoli | nova/utils.py | Python | apache-2.0 | 53,116 | 0.00032 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | ing.
Basic packet structure is below.
Client packet (14 bytes)::
0 1 8 9 13
| +-+--------+-----+
|x| cli_id |?????|
+-+--------+-----+
x = packet identifier 0x38
cli_id = 64 bit identifier
? = unknown, probably flags/padding
Server packet (26 bytes)::
0 1 8 9 13 14 21 2225
+-+--------+-----+--------+----+
|x| ... |
camradal/ansible | lib/ansible/modules/system/runit.py | Python | gpl-3.0 | 9,034 | 0.007084 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, Brian Coca <bcoca@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... | ', opt_dirs=self.extra_paths)
self.svstat_cmd = module.get_bin_path('sv', opt_dirs=self.extra_paths)
self.svc_full = '/'.join([ self.service_dir, self.name ])
self.src_full = '/'.join([ self.service_src, self.name ])
self.enabled = os.path.lexists(self.svc_full) |
if self.enabled:
self.get_status()
else:
self.state = 'stopped'
def enable(self):
if os.path.exists(self.src_full):
try:
os.symlink(self.src_full, self.svc_full)
except OSError:
e = get_exception()
... |
efiring/numpy-work | numpy/core/setupscons.py | Python | bsd-3-clause | 4,414 | 0.004304 | import os
import sys
import glob
from os.path import join, basename
from numpy.distutils import log
from numscons import get_scons_build_dir
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration,dot_join
from numpy.distutils.command.scons import get_scons_pkg... | tblas.c'),
join('blasdot', 'cblas.h')]
api_definition = [join('code_generators', 'array_api_order.txt'),
join('code_generators', 'multiarray_api_order.txt'),
join('code_generators', 'ufunc_api_order.txt')]
core_src = [join('src', basename(i)) for i... | *.c'))]
core_src += [join('src', basename(i)) for i in glob.glob(join(local_dir,
'src',
'*.src'))]
source_files = dot_blas_src + api_definition + core_src + \
[jo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.