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 |
|---|---|---|---|---|---|---|---|---|
holmes-app/holmes-api | tests/unit/handlers/test_domains_violations_prefs.py | Python | mit | 10,248 | 0.000878 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from preggy import expect
from tornado.testing import gen_test
from tornado.httpclient import HTTPError
from ujson import loads, dumps
from tests.unit.base import ApiTestCase
from tests.fixtures import (
DomainFactory, DomainsViolationsPrefsFactory, KeyFactory, UserFacto... | like([
{
'category': 'SEO',
'default_value': 100,
'title': 'My some.random.1',
'value': 100,
'key': 'some.random.1',
'unit': | 'number'
},{
'category': 'HTTP',
'default_value': 2,
'title': 'My some.random.2',
'value': 2,
'key': 'some.random.2',
'unit': 'number'
}
])
@gen_test
def test_can_get_prefs_with_inva... |
WikipediaLibrary/TWLight | TWLight/users/management/commands/user_update_eligibility.py | Python | mit | 5,266 | 0.003228 | from datetime import timedelta
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand
from TWLight.users.models import Editor
from TWLight.users.helpers.editor_data import (
editor_global_userinfo,
editor_valid,
editor_enough_edits,
editor_not_blocked,
... | sername.
if timedelta_days:
editors = editors.exclude(
editorlogs__timestamp__gt=now_or_datetime
- timedelta(days=timedelta_days),
)
# Optional wp_username filter.
if options["wp | _username"]:
editors = editors.filter(wp_username=str(options["wp_username"]))
# Iterator reduces memory footprint for large querysets
for editor in editors.iterator():
# T296853: avoid stale editor data while looping through big sets.
editor.refresh_from_db()
... |
blaze/dask | dask/blockwise.py | Python | bsd-3-clause | 56,476 | 0.001169 | from __future__ import annotations
import itertools
import os
from collections.abc import Hashable, Iterable, Mapping, Sequence
from itertools import product
from typing import Any
import tlz as toolz
from .base import clone_key, get_name_from_key, tokenize
from .compatibility import prod
from .core import flatten, ... | lockwise object.
``*arrind_pairs`` is similar to those in `make_blockwise_graph`, but in addition to
allowing for collections it can accept BlockwiseDep instances, which allows for lazy
evaluation of arguments to ``func`` which might be different for different
chunks/paritions.
See Also
------... | ical elements
# We use terms like _0, and _1 rather than provided index elements
unique_indices = {
i for ii in arrind_pairs[1::2] if ii is not None for i in ii
} | set(output_indices)
sub = { |
Inspq/ansible | lib/ansible/modules/windows/win_robocopy.py | Python | gpl-3.0 | 4,912 | 0.002036 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Corwin Brown <blakfeld@gmail.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 Lic... | Systems.
options:
src:
description:
- Source file/directory to sync.
required: true
dest:
description:
- Destination file/directory to sync (Will receive contents of src).
required: true
recurse:
description:
- Includes all subdirectories (Toggles the `/e` flag to RoboCopy). ... | nd in the destination that do not exist in the source (Toggles the `/purge` flag to RoboCopy). If "flags" is set, this will be ignored.
choices:
- true
- false
default: false
required: false
flags:
description:
- Directly supply Robocopy flags. If set, purge and recurse will be ignor... |
mehtadev17/mapusaurus | mapusaurus/respondents/managers.py | Python | cc0-1.0 | 254 | 0.003937 | from d | jango.db import models
class AgencyManager(models.Manager):
def get_all_by_code(self):
agencies = self.all()
agency_map = {}
for agency in agencies:
agency_map[agency.pk] = agency
return agency_ | map
|
xuru/pyvisdk | pyvisdk/mo/virtual_disk_manager.py | Python | mit | 16,908 | 0.011356 |
from pyvisdk.base.managed_object_types import ManagedObjectTypes
from pyvisdk.base.base_entity import BaseEntity
import logging
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
class VirtualDiskManager(BaseE... | cifies the hostname or
IP address of the VirtualCenter or ESX server and optionally the port. * is the
inventory path to the Datacenter containing the Datastore. * i | s the name of the
Datastore. * is a slash-delimited path from the root of the datastore.A
datastore path has the formwhere* is the datastore name. * is a slash-delimited
path from the root of the datastore.'''
def __init__(self, core, name=None, ref=None, type=ManagedObjectTypes.VirtualDiskManager):
... |
mwhudson/qemu | scripts/vmstate-static-checker.py | Python | gpl-2.0 | 12,817 | 0.001482 | #!/usr/bin/python
#
# Compares vmstate information stored in JSON format, obtained from
# the -dump-vmstate QEMU command.
#
# Copyright 2014 | Amit Shah <amit.shah@redhat.com>
# Copyright 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.
#
# Th... | Y 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 argparse
import json
import sys
# Count the number of errors found
taint = ... |
nvoron23/scipy | scipy/sparse/tests/test_base.py | Python | bsd-3-clause | 151,696 | 0.011286 | #
# Authors: Travis Oliphant, Ed Schofield, Robert Cimrman, Nathan Bell, and others
""" Test functions for sparse matrices. Each class in the "Matrix class
based tests" section become subclasses of the classes in the "Generic
tests" section. This is done by the functions in the "Tailored base
class for generic tests" ... | datsp = self.da | tsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datbsr = bsr_matrix(dat)
datcsr = csr_matrix(dat)
datcsc = csc_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equ... |
tsdmgz/ansible | test/runner/lib/cloud/azure.py | Python | gpl-3.0 | 6,070 | 0.002965 | """Azure plugin for integration tests."""
from __future__ import absolute_import, print_function
import os
from lib.util import (
ApplicationError,
display,
is_shippable,
)
from lib.cloud import (
CloudProvider,
CloudEnvironment,
)
from lib.http import (
HttpClient,
urlparse,
u | rlunparse,
parse_qs,
)
from lib.core_ci import (
AnsibleCoreCI,
)
class AzureCloudProvider(CloudProvider):
"""Azure cloud provider plugin. Sets up cloud resources before delegation."""
SHERLOCK_CONFIG_PATH = os.path.expanduser('~/.a | nsible-sherlock-ci.cfg')
def filter(self, targets, exclude):
"""Filter out the cloud tests when the necessary config and resources are not available.
:type targets: tuple[TestTarget]
:type exclude: list[str]
"""
if os.path.isfile(self.config_static_path):
return
... |
jaggu303619/asylum | openerp/addons/sale_margin/sale_margin.py | Python | agpl-3.0 | 4,272 | 0.006086 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | to_cur = self.pool.get('product.pricelist').browse(cr, uid, [pricelist])[0].currency_id.id
if product:
product = self.pool['product.product'].browse(cr, uid, product, context=context)
purchase_price = product.standard_price
to_uom = res.get('product_uom', uom)
... | ctx = context.copy()
ctx['date'] = date_order
price = self.pool.get('res.currency').compute(cr, uid, frm_cur, to_cur, purchase_price, round=False, context=ctx)
res['value'].update({'purchase_price': price})
return res
def _product_margin(self, cr, uid, ids, field_na... |
VHAINNOVATIONS/GE-Pressure-Ulcer | python_gui_decision_support_webportal/python/webapp/mmpspupc/models/assessment_reconstruction.py | Python | apache-2.0 | 2,000 | 0.0145 | from sqlalchemy import Column, Integer, String, DateTime, Numeric
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class AssessmentReconstruction(Base):
"""
Definition of AssessmentReconstruction object. It will be used by SQLAlchemy's ORM to map the object to
the system_a... | rectory',String)
keyCol = 'id'
editCols = ['start_time','reconstruction_data_directory' ]
editColsLabels = ['Start Time','Reconstruction Data Directory']
editColsTypes = ['date','string']
displayTableName = 'System Assessment Experiment Reconstruction'
def setFromData(self,data):
""... | # self.id = data['id']
self.session_id = data['session_id']
self.experiment_id = data['experiment_id']
self.start_time = data['start_time']
self.reconstruction_data_directory = data['reconstruction_data_directory']
def __json__(self, request):
return {'id'... |
dna2github/dna2oldmemory | dna2poem/tiny/matchbox/graph.py | Python | mit | 8,836 | 0.000226 | class GraphNode(object):
def __init__(self, name=None):
self.reset()
self.name = name
self.data = None
def __str__(self):
if self._strcache is None:
self._strcache = "<GraphNode %s>" % str(self.name)
return self._strcache
def __repr__(self):
retu... | n:
| continue
queue[i] = None
visit[id(one)] = n + len(next_level)
next_level.append(one)
if callback is not None:
if callback(node) is not None:
return self
next_level.reverse()
m = len(nex... |
soltys/ZUT_Algorytmy_Eksploracji_Danych | DataVisualization/app.py | Python | mit | 849 | 0.001181 | # -*- coding: utf-8 -*-
__author__ = 'Paweł Sołtysiak'
import pandas as pd
import scipy.io.arff as arff
from sklearn import cross_validation
from sklearn.decomposition import PCA
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
waveformData, waveformMeta = arff.loadarff(u'../Datasets/waveform-5000.ar... | desc, 0], Y[d == desc, 1], '.')
voteData, voteMeta = arff.loadarff(u'../Datasets/vote.arff')
df = pd.DataFrame(voteData)
desc = df.values[:, -1]
print df.replace('y', T | rue)
df = df.drop('Class', axis=1)
pca = PCA()
Y = pca.fit_transform(df.values)
for d in np.unique(desc):
plt.plot(Y[d == desc, 0], Y[d == desc, 1], '.')
plt.show() |
RI-imaging/nrefocus | nrefocus/pad.py | Python | bsd-3-clause | 5,111 | 0 | """Convenience functions for padding
.. versionadded:: 0.1.4
"""
from __future__ import division, print_function
import numpy as np
def _get_pad_left_right(small, large):
"""Compute left and right padding values.
Here we use the convention that if the padding
size is odd, we pad the odd part to the rig... | len(pv.shape) in [1, 2], "Only 1D and 2D arrays!"
assert len(pv.shape) == len(
size), "`size` must have same length as `av.shape`!"
if len(pv.shape) == 2:
return pv | [:size[0], :size[1]]
else:
return pv[:size[0]]
|
batxes/4Cin | Six_mouse_models/Six_mouse_models_final_output_0.2_-0.1_11000/mtx1_models/Six_mouse_models23848.py | Python | gpl-3.0 | 18,211 | 0.025534 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from V | olumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_sets={}
surf_sets={}
if "particle_0 geometry" not in marker_sets:
s=new_marker_set('particle_0 geometry')
marker_sets["particle_0 ... | ts["particle_0 geometry"]
mark=s.place_marker((2327.21, 8000.43, 3949.43), (0, 1, 0), 846)
if "particle_1 geometry" not in marker_sets:
s=new_marker_set('particle_1 geometry')
marker_sets["particle_1 geometry"]=s
s= marker_sets["particle_1 geometry"]
mark=s.place_marker((30.13, 8392.82, 5179.71), (0.7, 0.7, 0.7), 8... |
cedadev/cis | cis/data_io/products/HadGEM.py | Python | lgpl-3.0 | 5,253 | 0.003998 | from cis.data_io.products import NetCDF_Gridded
import logging
class HadGEM_CONVSH(NetCDF_Gridded):
"""
HadGEM plugin for reading NetCDF files converted by CONVSH. It implements a callback to pass to iris when
reading multiple files to allow correct merging
"""
def get_file_signature(self... | # for some HadGEM variables but most commands allow the user to override this field on output.
var_name = cube.name()
try:
cube.var_name = var_name
except ValueError as e:
logging.info("Unable to set var_name due to error: {}".format(e))
@staticmethod
def l... | d_single_file_callback(cube, field, filename):
# This method sets the var_name (used for outputting the cube to NetCDF) to the cube name. This can be quite
# for some HadGEM variables but most commands allow the user to override this field on output.
var_name = cube.name()
try:
... |
AFD-Illinois/grim | src/geometry/test_geometry.py | Python | gpl-3.0 | 31,846 | 0.016517 | import mpi4py, petsc4py
from petsc4py import PETSc
import numpy as np
import pytest
import gridPy
import geometryPy
petsc4py.init()
petscComm = petsc4py.PETSc.COMM_WORLD
comm = petscComm.tompi4py()
rank = comm.Get_rank()
numProcs = comm.Get_size()
PETSc.Sys.Print("Using %d procs" % numProcs)
N1 = int(pytest.config.... | * dr_dX1 # dX1 dphi
gCovCheck[2][0] = gCovCheck[0][2]
gCovCheck[2][1] = gCovCheck[1][2]
gCovCheck[2][2] = sigma * dtheta_dX2 * d | theta_dX2 # dX2 dX2
gCovCheck[2][3] = 0. # dX2 dphi
gCovCheck[3][0] = gCovCheck[0][3]
gCovCheck[3][1] = gCovCheck[1][3]
gCovCheck[3][2] = gCovCheck[2][3]
gCovCheck[3][3] = np.sin(theta)**2. \
* (sigma + blackHoleSpin**2. \
* (1. + 2.*r/sigma)*np.sin(theta)**2. \
... |
buck06191/BayesCMD | batch/abcsbh/__init__.py | Python | gpl-2.0 | 72 | 0 | # ABCS | BH -- a drastically hacked-down version of the ABC-SY | SBIO package
|
zhangzhonglai/heron | integration-test/src/python/integration_test/core/constants.py | Python | apache-2.0 | 1,130 | 0 | # Copyright 2016 Twitter. 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 agree... | user defined config key
USER_SPOUT_CLASSPATH = "user.spout.classpath"
USER_BOLT_CLASSPATH = "user.bolt.classpath"
# user defined max executions
USE | R_MAX_EXECUTIONS = "user.max.exec"
|
OpenPhilology/nidaba | nidaba/plugins/leptonica.py | Python | gpl-2.0 | 8,246 | 0.000121 | # -*- coding: utf-8 -*-
"""
nidaba.plugins.leptonica
~~~~~~~~~~~~~~~~~~~~~~~~
Plugin accessing `leptonica <http://leptonica.com>`_ functions.
This plugin requires a liblept shared object in the current library search
path. On Debian-based systems it can be installed using apt-get
.. code-block:: console
# apt-g... | ce the value of whsize. The min | imal
value is 2.
factor (float): The threshold reduction factor due to variance. 0 =<
factor < 1.
Returns:
(unicode, unicode): Storage tuple of the output file
Raises:
NidabaInvalidParameterException: Input parameters are outside the valid
... |
kbrebanov/ansible | lib/ansible/modules/network/avi/avi_cloudproperties.py | Python | gpl-3.0 | 3,643 | 0.000823 | #!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... | hyp_props=dict(type='list',),
info=dict(type='list',),
url=dict(type='str',),
uuid=dict(type='str',),
)
argument_specs.update(avi_common_argument_spec())
module = AnsibleModule(
argument_spec=argument_specs, supports_check_mode=True)
if not HAS_AVI:
return module.... | k.'))
return avi_ansible_api(module, 'cloudproperties',
set([]))
if __name__ == '__main__':
main()
|
bm2-lab/cage | src/core/sg/interface_sg.py | Python | mit | 2,004 | 0.003493 | import os
from src.core import prep
from sgprocessor import *
def ProcessSg(p, opts):
if opts.anno == True:
if 'BEDDB' not in os.environ:
p.error('$BEDDB Not Exist. See README')
str_path_sgfq = opts.sg
str_nm = os.path.basename(os.path.splitext(opts.sg)[0])
str_proj = 'aux'
str_... | status == 4:
| print('Annotated with RefSeq and UCSC Gene')
print('Warning: Some are marked with None')
elif int_status == 5:
print('Annotated with RefSeq, UCSC Gene and GENCODE')
print('Warning: Some are marked with None')
print('Done')
print('Merging sg and sgma... |
montenegroariel/sigos | apps/historias_clinicas/views.py | Python | gpl-3.0 | 4,039 | 0.00322 | from django.http import HttpResponseRedirect, JsonResponse
from django.views.generic import CreateView, UpdateView
from django.contrib.messages.views import SuccessMessageMixin
from .models import HistoriaClinica, Patologia
from .forms import HistoriaClinicaForms
from apps.afiliados.models import Titular, Adherente
f... | else:
return HttpResponseRedirect('/historia/clinica/alta/' + str(persona[0].id))
class HistoriaClinicaUpdate(SuccessMessageMixin, UpdateView):
model = HistoriaClinica
form_class = HistoriaClinicaForms
template_name = 'historias_clinicas/historia_clinica_form.html'
success_url =... | rm.instance.persona = Persona.objects.get(pk=HistoriaClinica.objects.get(pk=self.kwargs['pk']).persona.id)
self.success_url = '/historia/clinica/redireccion/%s' % str(HistoriaClinica.objects.get(
pk=self.kwargs['pk']).persona.id)
return super(HistoriaClinicaUpdate, self).form_valid(form)
... |
luogu-dev/cyaron | cyaron/log.py | Python | lgpl-3.0 | 3,103 | 0.006445 | from __future__ import print_function
from functools import partial
import sys
from threading import Lock
try:
import colorful
except ImportError:
class colorful:
def __getattr__(self, attr):
return lambda st: st
colorful = colorful()
from .utils import make_unicode
__print = print
def ... | c = a.copy()
for k, v in b.items():
c[k] = v
return c
_log_funcs = {}
_log_lock = Lock()
def log(funcname, *args, **kwargs):
"""log with log function specified by ``funcname``"""
_log_lock.acquire()
rv = _log_funcs.get(funcname, lambda *args, **kwargs: None)(*args, **kwargs)
_log_lo... | ()
return rv
"""5 log levels
1. debug: debug info
2. info: common info
3. print: print output
4. warn: warnings
5. error: errors
"""
debug = partial(log, 'debug')
info = partial(log, 'info')
print = partial(log, 'print')
warn = partial(log, 'warn')
error = partial(log, 'error')
def register_logfunc(f... |
oskar456/youtube-dl | youtube_dl/extractor/karrierevideos.py | Python | unlicense | 3,379 | 0.002073 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
fix_xml_ampersands,
float_or_none,
xpath_with_ns,
xpath_text,
)
class KarriereVideosIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?karrierevid... | self._search_regex(r'<h1 class="title">([^<]+)</h1>', webpage, 'video title'))
video_id = self._search_regex(
r'/config/video/(.+?)\.xml', webpage, 'video id')
# Server returns malformed headers
# Force Accept-Encoding: * to prevent gzipped results
playlist = self.... | s={'Accept-Encoding': '*'})
NS_MAP = {
'jwplayer': 'http://developer.longtailvideo.com/trac/wiki/FlashFormats'
}
def ns(path):
return xpath_with_ns(path, NS_MAP)
item = playlist.find('./tracklist/item')
video_file = xpath_text(
item, ns('./j... |
wydler/python-piko | piko/models.py | Python | gpl-2.0 | 6,161 | 0.000325 | import json
import socket
import struct
import hexdump
from piko.conf import settings
class Base(object):
pass
class Packet(Base):
""" PIKO packet class."""
request = ''
response = ''
__is_packed = False
__is_unpacked = False
def __init__(self, code, address, pack=settings.AUTOPACK):
... | ump.hexdump(packet.request)
self._sock.send(packet.request) |
packet.response = self._sock.recv(4096)
if settings.DEBUG:
print '-' * 76
hexdump.hexdump(packet.response)
return packet.response
class Device(Base):
"""Piko device class."""
data = {}
def __init__(self, host, port=81, addr=255):
self.sock = Socke... |
asposepdf/Aspose_Pdf_Cloud | Examples/Python/Examples/GetTextFormatOfPDFSegment.py | Python | mit | 1,391 | 0.010784 | import asposepdfcloud
from asposepdfcloud.PdfApi import PdfApi
from asposepdfcloud.PdfApi import ApiException
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import ResponseMessage
apiKey = "XXXXX" #sepcify App Key
appSid = "XXXXX" #sepcify App SID
api... | et input file name
name = "sample-input.pdf"
pageNumber = 1
fragmentNumber = 1
segmentNumber = 1
try:
#upload file to aspose cloud storage
response = storageApi.PutCreate(name, data_folder + name)
#invoke Aspose.Pdf Cloud SDK API to get text format of a particular segment
response = pdfApi.GetSegmentT... | sponse.TextFormat
print "count :: " + segTextFormat.FontName
print "count :: " + str(segTextFormat.FontSize)
except ApiException as ex:
print "ApiException:"
print "Code:" + str(ex.code)
print "Message:" + ex.message
|
bdeangelis/call_man_bat | static/frontend/jsonmaking.py | Python | mit | 6,080 | 0.026151 | import json, random, time, sys
"""
Creating a random JSON object based on lists of info and random numbers
to assign the index
"""
##Directory
input_file = "test.json"
###Success message takes the file_name and operation type (ie. written, closed)
def process_message(outcome, file_name, operation_type):
print "**... | t check_list
def check():
check_picker=random_chooser(1,10)
check=check_list[check_picker]
#=[1,2,3,5,6,8,98]
return check
##Random content picker from list content_list
def content():
content_picker=random_chooser(1,len(content_list))
content=content_list[content_picker]
return content
... | andom_chooser(1,20)):
messages_info_values = [date_picker(),pick_your_name(),random_place(),random_phone_number(),random_ext(),check(), content()]
messages_info_list = dict(zip(messages_info_keys, messages_info_values))
lister_maker.append(messages_info_list)
x=x+1
return lister_make... |
sassoftware/mint | mint/rest/middleware/error.py | Python | apache-2.0 | 3,212 | 0.004047 | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | t, e_type, e_value, e_tb, doEmail=True):
info = {
'uri' | : request.thisUrl,
'path' : request.path,
'method' : request.method,
'headers_in' : request.headers,
'request_params' : request.GET,
'post_params' : request.POST,
'remote' ... |
shankari/e-mission-server | emission/tests/analysisTests/configTests/TestSaveAllConfigs.py | Python | bsd-3-clause | 4,255 | 0.007051 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Standard imports
from future import standard_library
standard_library.install_aliases()
from builtins import *
import unittest
import datetime as pydt
import logging
imp... | a']['write_ts'] = 1440710000
cfg_2['data']['is_duty_cycling'] = False
edb.get_timeseries_db().insert_one(cfg_2)
tq = estt.TimeQuery("metadata.write_ts", 1440658800, 1440745200)
eacc.save_all_configs(self.androidUUID, tq)
saved_entries = list(edb.get_usercache_db().find({'user_id... | sor_config'}))
self.assertEqual(len(saved_entries), 1)
logging.debug(saved_entries[0])
self.assertEqual(saved_entries[0]['data']['is_duty_cycling'], cfg_2['data']['is_duty_cycling'])
def testOldOverride(self):
cfg_1 = copy.copy(self.dummy_config)
cfg_1['metadata']['write_ts'... |
dpazel/music_rep | instruments/instrument_class.py | Python | mit | 963 | 0.010384 | """
File: instrument_class.py
Purpose: Defines a major category of instruments in the instrument category. In this case,
is used to identity broad instrument types, e.g. stringw, woodwinds, bass, percussion, keyboards.
"""
from instruments.instrument_base import InstrumentBase
class InstrumentClass(Inst... | ng) name of class, e.g. woodwinds, strings
"""
InstrumentBase.__init__(self, name, parent)
self.__families = []
@property
def families(self):
return list(self.__families)
def add_family(self, family):
self.__families.append(family)
... | me)
|
nickbjohnson4224/greyhat-crypto-ctf-2014 | challenges/musicbox/musicbox.py | Python | mit | 4,204 | 0.024025 | import sys, struct, array
import SocketServer
# import StringIO as StringIO
# import pygame
p = 0x08d682598db70a889ff1bc7e3e00d602e9fe9e812162d4e3d06954b2ff554a4a21d5f0aab3eae5c49ac1aec7117709cba1b88b79ae9805d28ddb99be07ba05ea219654afe0c8dddac7e73165f3dcd851a3c8a3b6515766321420aff177eaaa7b3da39682d7e773aa863a729706d52... | 2cfb6a5a4cf34e7e8d5428b90b7aa1dbf9a7e965feab029220266ad0dabade6ae09362f6463eea60e3133bb79fc4af511057e31574f4b0f34b848b180fa20da7d9a6d8adedded9819da20b8923073e35f43ca75eeb9a1ab5451c3a5446306f93ef246759f59e65e498032d48aece56f437b4b7179daf3dfa80d6a36c211ed5acdfeaf91a7e8070a49a521f3c2e411a26eeaf8fab697535914982 | f1f7cda1e1aa1aac602f9606ea326632b4fbabf6b361fe118637e048c482
def bytesToInt(s):
x = 0
for c in s:
x = (x << 8) | ord(c)
return x
def verifySig(r, s, m):
#DSA, straight from Wikipedia
if not 0 < s < q and 0 < r < q:
return False
w = pow(s, q-2, q)
u1 = m*w % q
u2 = r*w % q
v = pow(g, u1, p) * pow(y, u2, p... |
holytortoise/abwreservierung | auto_process.py | Python | mit | 1,255 | 0.007177 | import os
from decouple import config
sudoPassword = config('SUDOPASSWORD')
def update():
"""
Automatisches Update des Reservierungssystems über Github
"""
try:
command_stop = 'sudo supervisorctl stop abwreservierung && sudo supervisorctl start abwreservierung && sudo chmod +x startup'
... | t:
pass
def alte_reservierungen():
"""
Automatisches entfernen der alten Reservierungen
"""
os.system("/bin/bash -c 'source ../django-server/bin/activate && python src/manage.py alte_reservierungen && deactivate'")
scheduler = BlockingScheduler()
scheduler.add_job(update, 'cron', day_of_week='... | ="mon-fri", hour=17)
scheduler.start()
|
tensorflow/lattice | tensorflow_lattice/sonnet_modules/__init__.py | Python | apache-2.0 | 709 | 0.00141 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""'sonnet_modules' namespace for TFL layers."""
from tensorflow_lattice.python.pwl_calibration_sonnet_module import PW | LCalibration
|
jgruselius/standalone_scripts | bravo_mailer.py | Python | mit | 1,107 | 0.025294 |
import smtplib
import argparse
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def main(args):
# Allow HTML-formatted emails (very simplistic atm, should be expanded if used)
msg = MIMEMultipart("alternative")
if args["body"].startswith("<html>", 0, 10):
msg.attach(MIMEText(a... | )
s.quit()
if __name__ == "__main__":
p = argparse.ArgumentParser(description="Send an email")
p.add_argument("--to", "-t", required=True, help="To address")
p.add_argument("--from", "-f", required=True, help="From address")
p.add_argument("--sub", "-s", required=True, help="Subject")
p.add_argument("--body", "-... | ")
args = p.parse_args()
main(vars(args))
|
cbxbiker61/wicd | gtk/gui.py | Python | gpl-2.0 | 33,021 | 0.003543 | #!/usr/bin/python
""" gui -- The main wicd GUI module.
Module containing the code for the main wicd GUI.
"""
#
# Copyright (C) 2007-2009 Adam Blackburn
# Copyright (C) 2007-2009 Dan O'Reilly
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Publ... | self.network_list.show_all()
self.status_area = self.wTree.get_object("connecting_hbox")
self.status_bar = self.wTree.get_object("statusbar")
menu = self.wTree.get_object("menu1")
self.status_area.hide_all()
if os.path.exists(os.path.join(wpath.images, "wicd.png")):
... | self.window.set_icon_from_file(os.path.join(wpath.images, "wicd.png"))
self.statusID = None
self.first_dialog_load = True
self.is_visible = True
self.pulse_active = False
self.pref = None
self.standalone = standalone
self.wpadrivercombo = None
self.connec... |
Microvellum/Fluid-Designer | win64-vc/2.78/Python/Scripts/enhancer.py | Python | gpl-3.0 | 1,649 | 0.001213 | #!c:\users\montes\documents\github\flu | id-designer\win64-vc\2.78\python\bin\python.exe
#
# The Python Imaging Library
# $Id$
#
# this demo script creates four windows containing an image and a slider.
# drag the slider to modify the image.
#
try:
from tkinter import Tk, Toplevel, Frame, Label, Scale, HORIZONTAL
except ImportError:
from Tkinter impo... | ImageTk, ImageEnhance
import sys
#
# enhancer widget
class Enhance(Frame):
def __init__(self, master, image, name, enhancer, lo, hi):
Frame.__init__(self, master)
# set up the image
self.tkim = ImageTk.PhotoImage(image.mode, image.size)
self.enhancer = enhancer(image)
sel... |
jay4ek/cs3240-labdemo | blarg.py | Python | mit | 76 | 0.026316 |
from helper import greeting
if "__name__" == "__main__":
greeting('bla | rg') | |
andriibekker/biddingsbase | main/utils.py | Python | bsd-3-clause | 279 | 0 | from django.shortcuts import render_to_response as _render_to_response
fro | m django.template import RequestContext
def render_to_response(request, *args, **kwargs):
kwargs.update({'context_instance': RequestContext(request)})
return _render_to_response(*args, ** | kwargs)
|
cychenyin/windmill | apscheduler/triggers/cron/fields.py | Python | mit | 3,059 | 0.002288 | # coding: utf-8
"""
Fields represent CronTrigger options which map to :class:`~datetime.datetime`
fields.
"""
from calendar import monthrange
from apscheduler.triggers.cron.expressions import (
AllExpression, RangeExpression, WeekdayPositionExpression, LastDayOfMonthExpression, WeekdayRangeExpression)
__all__ =... | f.COMPILERS:
match = compiler.value_re.match( | expr)
if match:
compiled_expr = compiler(**match.groupdict())
self.expressions.append(compiled_expr)
return
raise ValueError('Unrecognized expression "%s" for field "%s"' % (expr, self.name))
def __str__(self):
expr_strings = (str(e) for ... |
mozilla/zamboni | mkt/api/tests/test_renderers.py | Python | bsd-3-clause | 790 | 0 | from nose.tools import eq_
from mkt.api.renderers import SuccinctJSONRenderer
from mkt.site.tests | import TestCase
class TestSuccinctJSONRenderer(TestCase):
def setUp(self):
self.renderer = SuccinctJSONRenderer()
self.input = {'foo': 'bar'}
def test_no_spaces(self):
output = self.renderer.render(self.input)
eq_(output, '{"foo":"bar"}')
def test_indent_context(self):
... | '{\n "foo": "bar"\n}')
def test_accepted_header(self):
header = 'application/json; indent=4'
output = self.renderer.render(self.input, accepted_media_type=header)
eq_(output, '{\n "foo": "bar"\n}')
|
Tehnix/cred-server | cred/config.py | Python | bsd-3-clause | 2,169 | 0.000922 | """
The configuration files are searched for in the following order:
1. Local directory
2. Users home directory
3. Users app directory
4. System app directory
The file searched for is called .credrc for 1. and 2., and without the dot
for 3. and 4.. If none are found, it will use the default configurati... | eturn os. | path.join(os.getcwd(), config_file)
elif os.path.isfile(os.path.join(os.path.expanduser('~'), dot_config_file)):
return os.path.join(os.path.expanduser('~'), dot_config_file)
elif os.path.isfile(os.path.join(app_dirs.user_data_dir, config_file)):
return os.path.join(app_dirs.user_data_dir, confi... |
kyoren/https-github.com-h2oai-h2o-3 | h2o-py/tests/testdir_jira/pyunit_NOPASS_hex_1897_glm_offset.py | Python | apache-2.0 | 2,423 | 0.009492 | import sys
sys.path.insert(1, "../../")
import h2o, tests
def offset_1897():
print 'Checking binomial models for GLM with and without offset'
print 'Import prostate dataset into H2O and R...'
prostate_hex = h2o.import_file(tests.locate("smalldata/prostate/prostate.csv"))
print "Checking binomial... | iance())
print "r residual: {0}".format(216.339989007507)
assert abs(216.339989007507 - prostate_glm_h2o.residual_deviance()) < 0.1
print "Checking binomial model with offset..."
prostate_glm_h2o = h2o.glm(x=prostate_hex[["RACE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON", "AGE"]],
... | offset_column = "AGE", standardize = False)
print "h2o residual: {0}".format(prostate_glm_h2o.residual_deviance())
print "r residual: {0}".format(2761.76218461138)
assert abs(2761.76218461138 - prostate_glm_h2o.residual_deviance()) < 0.1
if __name__ == "__main__":
tests.run_test(sys.argv, offset... |
kaplun/Invenio-OpenAIRE | modules/bibformat/lib/bibformat_regression_tests.py | Python | gpl-2.0 | 20,498 | 0.004119 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2010, 2011 CERN.
##
## Invenio 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 ... | of='hx',
ln=CFG_SITE_LANG,
verbose=0,
search_pattern=[],
xml_record=None,
user_info=None,
on_the_fly=True)
| pageurl = CFG_SITE_URL + '/record/73?of=hx'
result = test_web_page_content(pageurl,
expected_text=result)
class BibFormatBibTeXTest(unittest.TestCase):
"""Check output produced by BibFormat for BibTeX output for
various records"""
def setUp(self):
""... |
NifTK/NiftyNet | niftynet/layer/dilatedcontext.py | Python | apache-2.0 | 1,675 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import tensorflow as tf
from niftynet.layer import layer_util
class DilatedTensor(object):
"""
This context manager makes a wrapper of input_tensor
When created, the input_tensor is dilated,
the input_tensor resumes to or... | atial_rank(self._tensor)
self.zero_paddings = [[0, 0]] * self.spatial_rank
self.block_shape = [dilation_factor] * self.sp | atial_rank
def __enter__(self):
if self.dilation_factor > 1:
self._tensor = tf.space_to_batch_nd(self._tensor,
self.block_shape,
self.zero_paddings,
na... |
smeissner/eden | static/scripts/tools/build.sahana.py | Python | mit | 14,872 | 0.003833 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# run as:
# python web2py.py -S eden -M -R applications/eden/static/scripts/tools/build.sahana.py
# or
# python web2py.py -S eden -M -R applications/eden/static/scripts/tools/build.sahana.py -A gis
#
#
# Built with code/inspiration from MapFish, OpenLayers & Michael C... | s
use_compressor = "c | losure_ws"
print "Using Closure via Web Service - limited to files < 1Mb!"
except ImportError:
print "No closure_ws"
if use_compressor == "closure":
if not warnings:
closure.extra_params = "--warning_level QUIET"
minimize = closure.minimize
elif use_c... |
essanpupil/cashflow | cashflow/urls.py | Python | mit | 1,046 | 0.000956 | """cashflow URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/ | topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base | d views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
f... |
oy-vey/algorithms-and-data-structures | 5-AdvancedAlgorithmsAndComplexity/Week1/evacuation/evacuation.py | Python | mit | 3,343 | 0.002094 | # python3
import queue
class Edge:
def __init__(self, u, v, capacity):
self.u = u
self.v = v
self.capacity = capacity
self.flow = 0
# This class implements a bit unusual scheme for storing edges of the graph,
# in order to retrieve the backward edge for a given edge quickly.
clas... | all forward edges are stored at even indices (starting from 0),
# whereas backward edges are stored at odd indices.
forward_edge = Edge(from_, to, capacity)
backward_edge = Edge(to, from_, 0)
self.graph[from_].append(len(self.edges))
self.e | dges.append(forward_edge)
self.graph[to].append(len(self.edges))
self.edges.append(backward_edge)
def size(self):
return len(self.graph)
def get_ids(self, from_):
return self.graph[from_]
def get_edge(self, id):
return self.edges[id]
def add_flow(self, id, flo... |
mtask/multissh | multissh.py | Python | apache-2.0 | 8,206 | 0.003656 | #!/usr/bin/python2
from fabric.api import *
from fabric.tasks import execute
import sys
import os
import argparse
import ntpath
import fnmatch
"""
Author: mtask@github.com
"""
class multissh(object):
def manage_servers(self, add=False, delete=False, param=None):
if add:
self.server = param.... | self.hosts.append(self.params[0])
self.users.append(self.params[1])
except Exception as e:
raise e
if list:
self | .server_num = 1
for self.h in self.hosts:
print "["+str(self.server_num)+"] "+self.h
self.server_num += 1
else:
return (self.hosts, self.users, self.keypath)
def run_cmd(self, cmd,sudo_=False, script=False, copy_file="", yesno=False):
def fi... |
alex-i-git/LearnPython-Diploma-Project | info.py | Python | mit | 29 | 0.034483 | from dbot impor | t info
inf | o() |
esneider/relationshit-server | app.py | Python | mit | 2,414 | 0.005385 | import os
import sys
import json
from flask import Flask, request, Response
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)
import database
@app.route('/')
def hello():
return 'Hello World!'
@app.route('/... | st.args.get('IMEI')
lists = database.process(userId)
data = json.dumps(lists)
resp = Response(response=data, mimetype="application/json")
print '[end] GET topLists'
sys.stdout.flush()
return resp
@app.route('/contactsData', methods = ['GET'])
def contactsData():
print '[start] GET cont... | serId)
data = json.dumps(blabla)
resp = Response(response=data, mimetype="application/json")
print '[end] GET contactsData'
sys.stdout.flush()
return resp
@app.route('/test')
def api_hello():
print "before calling process"
#database.test_query(db)
#database.contact_query(db, "352584... |
caceres/SlopedPlanesMacro | SlopedPlanesTaskPanel.py | Python | gpl-3.0 | 42,295 | 0.00104 | # -*- coding: utf8 -*-
# *****************************************************************************
# * *
# * Copyright (c) 2017 *
# * ... | *
# * *
# *****************************************************************************
import math
import FreeCAD
import FreeCADGui
from PySide import QtGui, QtCore
__title__ = "SlopedPlanesMacro... | anes):
''''''
self.updating = False
self.obj = slopedPlanes
self.shaping()
form = QtGui.QWidget()
self.form = form
form.setObjectName("TaskPanel")
form.setWindowTitle(self.obj.Label)
grid = QtGui.QGridLayout(form)
self.grid = grid
... |
boyombo/django-stations | stations/parcel/migrations/0003_parcel_date_loaded.py | Python | mit | 507 | 0 | # | -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-01-14 08:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('parcel', '0002_remove_client_gender'),
]
operations = [
... | |
ACJTeam/enigma2 | lib/python/Tools/KeyBindings.py | Python | gpl-2.0 | 8,341 | 0.030812 |
keyBindings = { }
from keyids import KEYIDS
from Components.config import config
from Components.RcModel import rc_model
keyDescriptions = [{
KEYIDS["BTN_0"]: ("UP", "fp"),
KEYIDS["BTN_1"]: ("DOWN", "fp"),
KEYIDS["KEY_OK"]: ("OK", ""),
KEYIDS["KEY_UP"]: ("UP",),
KEYIDS["KEY_DOWN"]: ("DOWN",),
KEYIDS["KEY... | D",),
KEYIDS["KEY_PLAYPAUSE"]: ("PLAYPAUSE",),
KEYIDS["KEY_CHANNELUP"]: ("BOUQUET+",),
KEYIDS["KEY_CHANNELDOWN"]: ("BOUQUET-",),
KEYIDS["KEY_0"]: ("0",),
KEYIDS["KEY_1"]: ("1",),
KEYIDS["KEY_2"]: ("2",),
KEYIDS["KEY_3"]: ("3",),
KEYIDS["KEY_4"]: ("4",),
KEYIDS["KEY_5"]: ("5",),
KEYIDS["KEY_6"]: ("6"... | ("STOP",),
KEYIDS["KEY_RECORD"]: ("RECORD",),
KEYIDS["KEY_BOOKMARKS"]: ("PORTAL",),
KEYIDS["KEY_VMODE"]: ("VMODE",),
KEYIDS["KEY_PROGRAM"]: ("TIMER",),
KEYIDS["KEY_SLEEP"]: ("SLEEP",),
KEYIDS["KEY_EPG"]: ("EPG",),
},
{ # Formuler F1
KEYIDS["BTN_0"]: ("UP", "fp"),
KEYIDS["BTN_1"]: ("DOWN", "fp"),... |
chrisdembia/yeadon | examples/bicyclerider/version_information.py | Python | bsd-3-clause | 5,785 | 0.002593 | """
An IPython extension that provides a magic command that displays
a table with information about versions of installed modules.
This makes it much easier to determine which versions of modules
were installed in the source IPython interpreter's environment.
Produces output in:
* Plaintext (IPython [qt]console)
* H... | ult, Sep 26 2013, 20:08:41) [GCC 4.6.3]
IPython 2.0.0-dev
OS posix [linux2]
sphinx 1.2b3
jinja2 2.7.1
Mon Dec 09 10:21 | :52 2013 CST
.. note:: ``%version_information`` expects to find the module version in
``<module>.__version__``.
If ``<module>.__version__`` is not set, it attempts to get a version
string with ``pkg_resources.require('<module>')[0].version``
(the ``version`` field from ``setup.py``).
This script is hoste... |
leapcode/soledad | src/leap/soledad/server/session.py | Python | gpl-3.0 | 4,855 | 0 | # -*- coding: utf-8 -*-
# session.py
# Copyright (C) 2017 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Thi... | credentials = self._credentialFactory.decode(auth_data, request)
except error.LoginFailed:
return UnauthorizedResource()
except Exception:
# If you port this to the newer log facility, be aware that
# the tests rely on the error to be l | ogged.
log.err(None, "Unexpected failure from credentials factory")
return ErrorPage(500, None, None)
# make sure the uuid given in path corresponds to the one given in
# the credentials
request_uuid = match.get('uuid')
if request_uuid and request_uuid != credent... |
Abjad/abjad | tests/test_Container_extend.py | Python | gpl-3.0 | 6,074 | 0 | import pytest
import abjad
def test_Container_extend_01():
"""
Extend container with list of leaves.
"""
voice = abjad.Voice("c'8 d'8")
abjad.beam(voice[:])
voice.extend([abjad.Note("c'8"), abjad.Note("d'8")])
assert abjad.lilypond(voice) == abjad.string.normalize(
r"""
... |
"""
voice = abjad.Voice("c'8 d'8")
abjad.beam(voice[:])
voice.extend([])
assert abjad.lilypond(voice) == abjad.string.normalize(
r"""
\new Voice
{
c'8
[
d'8
]
}
"""
), print(abjad.lilypond(voice))
ass... | ner leaves both
containers unchanged.
"""
voice = abjad.Voice("c'8 d'8")
abjad.beam(voice[:])
voice.extend(abjad.Voice([]))
assert abjad.lilypond(voice) == abjad.string.normalize(
r"""
\new Voice
{
c'8
[
d'8
]
}
... |
14bmkelley/raytracer-python | cast.py | Python | mit | 3,882 | 0.028336 | import collisions
import data
import vector_math
import math
def cast_ray(ray, sphere_list, amb, light, eye_point):
result_color = data.Color(1.0, 1.0, 1.0)
#test for closest sphere to the eye
collision_tuple = find_closest_collision(ray, sphere_list)
if collision_tuple:
#some useful variables
sphere_hit = col... | result_b += sphere_hit.color.b * light_scale * light.color.b * sphere_hit.finish.diff
#computing specular intensity
tmp_vector = vector_math.scale_vector(sphere_normal, 2 * light_scale)
reflection_vector = vector_math.difference_vector(light_normal, tmp_vecto | r)
eye_vector = vector_math.vector_from_to(eye_point, hit_point)
eye_normal = vector_math.normalize_vector(eye_vector)
spec_scale = vector_math.dot_vector(reflection_vector, eye_normal)
if spec_scale > 0:
result_r += light.color.r * sphere_hit.finish.spec * spec_scale ** (1 / float(sphere_hit.fin... |
crisisking/skybot | plugins/bf.py | Python | unlicense | 2,513 | 0.000398 | '''brainfuck interpreter adapted from (public domain) code at
http://brainfuck.sourceforge.net/brain.py'''
from builtins import chr
from builtins import range
import re
import random
import unittest
from util import hook
@hook.command
def bf(inp, max_steps=1000000, buffer_size=5000):
".bf <prog> -- executes bra... | if len(output) > 500:
break
elif c == ',':
memory[mp] = random.randint(1, 255)
elif c == '[':
if memory[mp] == 0:
ip = brackets[ip]
elif c == ']':
if memory[mp] != 0:
ip = brackets[ip]
| ip += 1
steps += 1
if steps > max_steps:
if output == '':
output = 'no output'
output += ' [exceeded %d iterations]' % max_steps
break
stripped_output = re.sub(r'[\x00-\x1F]', '', output)
if stripped_output == '':
if output !=... |
google/autocjk | src/evaluate_font.py | Python | apache-2.0 | 6,620 | 0.000152 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ) -> None:
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")
# Load in the generator,
generator = tf.keras.models.load_model(generator_lib.PATH_TO_GENERATOR)
n = 0
list_of_kwargs_to_function = []
| for lhs, rhs, character in _get_viable_ids(_FONT_PATH.value):
if _LIMIT.value and n >= _LIMIT.value:
break
n = n + 1
list_of_kwargs_to_function.append({
"generator": generator,
"lhs": lhs,
"rhs": rhs,
"character": character,
... |
AbletonAG/abl.pivotal_client | setup.py | Python | mit | 453 | 0 | from setuptools import setup, find_packages
setup(
name='abl.pivota | l_client',
| version='1.1.0',
description='A simple client for Pivotal Tracker',
author='Ableton Web Team',
author_email='webteam@ableton.com',
url='http://ableton.com/',
zip_safe=False,
install_requires=[],
packages=find_packages(),
include_package_data=True,
license='MIT',
entry_points={
... |
brynpickering/calliope | calliope/core/io.py | Python | apache-2.0 | 3,119 | 0.001282 | """
Copyright (C) 2013-2018 Calliope contributors listed in AUTHORS.
Licensed under the Apache 2.0 License (see LICENSE file).
io.py
~~~~~
Functions to read and save model results.
"""
import os
import xarray as xr
from calliope._version import __version__
from calliope import exceptions
from calliope.core.util.d... | ne'
# Convert `object` dtype coords to string
# FIXME: remove once xarray issue https://github.com/pydata/xarray/issues/2404 is resolved
for k, v in model_data.coords.items():
if v.dtype == 'O':
model_data[k] = v.astype('<U{}'.format(max([len(i.item()) for i in v])))
try:
m... | 4', encoding=encoding)
model_data.close() # Force-close NetCDF file after writing
finally: # Convert ints back to bools, 'None' back to None
for k in bool_attrs:
model_data.attrs[k] = bool(model_data.attrs[k])
for k in none_attrs:
model_data.attrs[k] = None
def sa... |
jboy/nim-pymod | libpy/UsefulConfigParser.py | Python | mit | 5,807 | 0.005166 | # Copyright (c) 2015 SnapDisco Pty Ltd, Australia.
# All rights reserved.
#
# This source code is licensed under the terms of the MIT license
# found in the "LICENSE" file in the root directory of this source tree.
import sys
if sys.version_info.major >= 3:
from configparser import RawConfigParser
else:
from ... | ine_comment_prefixes=(';',)."
# -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour
#
# Grrr...
if sys.version_info.major >= 3:
self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',))
else:
se... | try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try = filenames_to_try[:]
def read(self, filenames_to_try=[]):
if isinstance(filenames_to_try, str):
filenames_to_try = [filenames_to_try]
self._filenames_to_try.extend(filenames_to_try)
retu... |
Oneiroi/clustercheck | setup.py | Python | agpl-3.0 | 707 | 0.001414 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='clustercheck',
use_scm_version=True,
setup_requires | =['setuptools_scm'],
install_requires=[
'Twisted>=12.2',
'PyMySQL'
],
description='Standalone service for reporting of Percona XtraDB/Galera cluster nodes',
license='AGPL-3.0-only',
keywords='galera,mariadb,percona,database,cluster',
author='David Busby',
author_email='oneiro... | https://github.com/Oneiroi/clustercheck/',
packages=find_packages(),
entry_points={
'console_scripts': [
'clustercheck = clustercheck:main',
],
}
)
|
KarrLab/kinetic_datanator | datanator/parse_metabolite_concentration.py | Python | mit | 2,388 | 0.017588 | import pandas as pd
import urllib.request
import json
from datanator_query_python.config import config
from datanator_query_python.util import mongo_util
class ParseMetaboliteConcentration(mongo_util.MongoUtil):
def __init__(self,
MongoDB=None,
db=None,
... | nt.com/KarrLab/datanator/tutorial/docs/metabolites/"+metabolites[i]+".json")
data = json.loads(url.rea | d().decode())
collection.insert_one({"inchikey":data['inchikey']})
for j in range(len(data['concentrations'])):
sub_data = data['concentrations'][j]
collection.update_one({"inchikey":data['inchikey']},{"$addToSet":{'concentrations':sub_data}})
def main():
... |
udayinfy/openerp-7.0 | stock_with_cost/__init__.py | Python | agpl-3.0 | 1,119 | 0.000894 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open | Source Management Solution
# Copyright (c) 2010-2013 Elico Corp. All Rights Reserved.
# Author: Yannick Gouin <yannick.gouin@elico-corp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free S... | ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/li... |
deyvedvm/cederj | urionlinejudge/python/1014.py | Python | gpl-3.0 | 71 | 0 | X = in | t(input())
Y = float( | input())
M = X / Y
print("%.3f km/l" % M)
|
Pio1962/fondinfo | exercises/e5_2011_2_bisection.py | Python | gpl-3.0 | 448 | 0.004464 | import math
def sqrt_bisection(x: float) -> float:
low, high = 0, x
if high < 1:
high = 1
y = (hi | gh + low) / 2
delta = y ** 2 - x
| while not (-0.001 <= delta <= 0.001):
if delta < 0:
low = y
else:
high = y
y = (high + low) / 2
delta = y ** 2 - x
return y
if __name__ == '__main__':
x = float(input())
print(sqrt_bisection(x))
print(math.sqrt(x))
|
ahoarfrost/metaseek | server/migrations/versions/a482d6aceb85_.py | Python | mit | 670 | 0.001493 | """empty message
Revision ID: a482d6aceb85
Revises: 01356afcc714
Create Date: 2017-11-09 15:57:26.28 | 8532
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a482d6aceb85'
down_revision = '01356afcc714'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('discovery', sa.Column(... | nd Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('discovery', 'num_datasets')
# ### end Alembic commands ###
|
wd15/chimad-phase-field | _apps/box/test.py | Python | mit | 3,449 | 0.00116 | """Test main.py
"""
import os
import json
from unittest.mock import patch, Mock
from starlette.testclient import TestClient
from toolz.curried import pipe, curry
from fastapi import UploadFile
from click.testing import CliRunner
from boxsdk import JWTAuth
from main import app, get_auth, upload_to_box, get_config_fil... | urn pipe(
dict(
enterpriseID="test",
boxAppSettings=dict(
clientID="test",
clientSecret="test",
appAuth=dict(publicKeyID="test", passphrase="test"),
),
),
write_json("test_config.json"),
)
@patch("main.JWTA... | """Test the upload_to_box function
"""
with CliRunner().isolated_filesystem():
assert pipe(
get_test_config(),
upload_to_box(UploadFile("wow"), "test"),
equals(MockStream().get_data()),
)
@patch("main.JWTAuth", autospec=True)
@patch("main.Client", new=Moc... |
zonble/axe_py | axe4.py | Python | mit | 1,045 | 0.019139 | #!/usr/bin/env python
# encoding: utf-8
# http://axe.g0v.tw/level/4
import urllib2, re
lines = []; last_url = None
for index in range(1, 25):
url = "http://axe-level-4.herokuapp.com/lv4/" if index == 1 \
else "http://axe-level-4.herokuapp.com/lv4/?page=" + str(index)
# The hint is that we shall make our bot loo... | req = urllib2.Request(url)
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/537.73.11')
if last_url:
req.add_header(' | Referer', last_url)
last_url = url
html = urllib2.urlopen(req).read()
pattern = r"<tr>\s*<td>(.*)</td>\s*<td>(.*)</td>\s*<td>(.*)</td>\s*</tr>"
results = re.findall(pattern, html, re.MULTILINE)[1:]
format = '{"town": "%s", "village": "%s", "name" : "%s"}'
for result in results:
lines.append(format % tuple(resu... |
hugegreenbug/libgestures | include/build/android/pylib/utils/test_options_parser.py | Python | bsd-3-clause | 3,471 | 0.00461 | # Copyright (c) 2012 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.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. Thi... | eview']
option_parser.add_option('--profiler', dest='profilers', action='append',
choices=profilers,
help='Profiling tool to run during test. '
'Pass multiple times to run multiple profilers. '
'Available | profilers: %s' % profilers)
option_parser.add_option('--tool',
dest='tool',
help='Run the test under a tool '
'(use --tool help to list them)')
option_parser.add_option('--flakiness-dashboard-server',
dest='... |
jtpereyda/boofuzz | request_definitions/http_header.py | Python | gpl-2.0 | 13,946 | 0.000072 | from boofuzz import *
# List of all HTTP Headers I could find
# List of all blocks defined here (for easy copy/paste)
"""
sess.connect(s_get("HTTP HEADER ACCEPT"))
sess.connect(s_get("HTTP HEADER ACCEPTCHARSET"))
sess.connect(s_get("HTTP HEADER ACCEPTDATETIME"))
sess.connect(s_get("HTTP HEADER ACCEPTENCODING"))
sess.... | HEADER XREQUESTEDWITH"))
sess.connect(s_get("HTTP HEADER XWAPPROFILE"))
"""
# Fuzz | Accept header
# Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5
s_initialize("HTTP HEADER ACCEPT")
s_static("GET / HTTP/1.1\r\n")
s_static("Accept")
s_delim(":")
s_delim(" ")
s_string("text")
s_delim("/")
s_string("*")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0, output... |
tylertian/Openstack | openstack F/python-novaclient/novaclient/v1_1/floating_ips_bulk.py | Python | apache-2.0 | 1,938 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 IBM Corp.
# 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/licen... | ulk_cr | eate": {'ip_range': ip_range}}
if pool is not None:
body['floating_ips_bulk_create']['pool'] = pool
if interface is not None:
body['floating_ips_bulk_create']['interface'] = interface
return self._create('/os-floating-ips-bulk', body,
'floatin... |
jpec/tasks.py | config.py | Python | gpl-2.0 | 350 | 0 | # config | .py
# Configuration for tasks application.
# Author: Julien Pecqueur (julien@peclu.net)
# License: GPL
NAME = 'tasks.py'
VERSION = 0.1
# Path to tasks database
DB = './tasks.db'
# Interface to listen
HOST = '0.0.0.0'
PORT = '8081'
# Debug mode
DEBUG = False
# Auto-reload service in case of file cha... | = True
|
wtanaka/beam | sdks/python/apache_beam/version.py | Python | apache-2.0 | 870 | 0 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | 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 permissions and
# limitations under the License.
#
"""Apache Beam SDK version information and utilities."""
__version__ = '2.1.0.dev'
|
ZhangXiaoyu-Chief/sandwich | account/models.py | Python | apache-2.0 | 1,237 | 0.003314 | from djan | go.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name=u'用户名', on_delete=models.CASCADE, related_name="userprofile")
nickname = models.CharField(max_length=32, verbose_name=u'昵称')
avatar = m... | def __str__(self):
return self.nickname
def __unicode__(self):
return self.nickname
def get_info(self):
return {
"id": self.id,
"username": self.user.username,
"nickname": self.nickname if self.nickname else "",
"avatar": self.avatar if... |
rehandalal/buchner | docs/conf.py | Python | bsd-3-clause | 7,703 | 0.005452 | # -*- coding: utf-8 -*-
#
# buchner documentation build configuration file, created by
# sphinx-quickstart on Sun Mar 31 14:35:13 2013.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The n... | title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Wind... |
CooperLuan/devops.notes | taobao/top/api/rest/SubusersGetRequest.py | Python | mit | 303 | 0.029703 | '''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class SubusersGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, p | ort)
self.user_nick = None
def getapiname(self):
return 'taobao.subusers.get'
| |
Panos512/invenio | modules/websubmit/lib/functions/Send_APP_Mail.py | Python | gpl-2.0 | 12,215 | 0.009415 | ## This file is part of Invenio.
## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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... | il informing the original submitter of a
document that the referee has approved/ rejected the document. The
email is also sent to the referee for checking.
Parameters:
* addressesAPP: email addresses of the people who will receive
this email (comma separated list). this parameter may conta... | is string.
eg.: "<CATEG>-email@cern.ch"
* categformatAPP contains a regular expression used to compute
the category of the document given the reference of the
document.
eg.: if [categformatAFP]="TEST-<CATEG>-.*" and the reference
of the document is "TEST-CATEGORY1-20... |
sv0/django-markdown-app | example/project/wsgi.py | Python | lgpl-3.0 | 389 | 0 | """
WSGI config for project.
It exposes the WSGI callable as a module-level variable named | ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi | /
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from django.core.wsgi import get_wsgi_application # noqa
application = get_wsgi_application()
|
dominicrodger/django-magazine | magazine/tests/html_sanitizer.py | Python | mit | 1,974 | 0 | from django.test import TestCase
from magazine.utils.word_cleaner import clean_word_text
class HTMLSanitizerTestCase(TestCase):
def testStripAttributes(self):
html = (u"<a href=\"foobar\" name=\"hello\""
u"title=\"View foobar\" onclick=\"malicious()\">hello!</a>")
self.assertEqual... | p>')
# Check we don't care about case
html = u"""
<STYLE TYPE="TEXT/CSS" somethingelse="something">foobar</STYLE>
<p>hello!</p>
"""
self.assertEqual(clean_word_text(html), u'<p>he | llo!</p>')
# Check multiple style blocks are stripped
html = u"""
<STYLE TYPE="TEXT/CSS" somethingelse="something">foobar</STYLE>
<p>hello!</p>
<style type="text/css" somethingelse="something">foobar</style>
"""
self.assertEqual(clean_word_text(html), u'<p>hello!</p>')
def testStyleStrippe... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractMercurytranslations7BlogspotCom.py | Python | bsd-3-clause | 578 | 0.032872 |
def extractMercurytranslations7Blogspo | tCom(item):
'''
Parser for 'mercurytranslations7.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous',... | pe=tl_type)
return False
|
jordanemedlock/psychtruths | temboo/core/Library/Utilities/Encoding/HTMLUnescape.py | Python | apache-2.0 | 2,975 | 0.00437 | # -*- coding: utf-8 -*-
###############################################################################
#
# HTMLUnescape
# Replaces character entity names in the specified text with equivalent HTML markup characters.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache Licens... | tion
import json
class HTMLUnescape(C | horeography):
def __init__(self, temboo_session):
"""
Create a new instance of the HTMLUnescape Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(HTMLUnescape, self).__init__(temboo_session, '/Library/Utilities/Encoding... |
pytorch/fairseq | examples/latent_depth/latent_depth_src/__init__.py | Python | mit | 380 | 0 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the | root directory of this source tree.
from . import multilingual_translation_latent_depth # noqa
from .loss import latent_depth # noqa
from .models import latent_multilingual_transformer # noqa
from .modules import latent_layers # | noqa
|
stdlib-js/stdlib | lib/node_modules/@stdlib/math/base/special/besselj1/benchmark/python/scipy/benchmark.py | Python | apache-2.0 | 2,191 | 0 | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complian | ce 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 permissions and
# limitations under the License.
"""Benchmark scipy.special.j1."""
from __future__ import print_function
import timeit
NAME = "besselj1"
REPEATS = 3
ITER... |
hfoffani/pddl-lib | pddlpy/__init__.py | Python | apache-2.0 | 665 | 0.001506 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 Hernán M. Foffani
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | 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 .pddl import DomainProblem
|
dalek7/umbrella | Python/DDUtil.py | Python | mit | 339 | 0.020649 | import os
import datetime
def exit():
| os._exit(0)
def GetTimeString(m = -1):
if m==0:
s1 = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
else:
s1 = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
return s1
|
def MakeDir(directory):
if not os.path.exists(directory):
os.makedirs(directory) |
prathamtandon/g4gproblems | Graphs/binary_tree_to_bst.py | Python | mit | 1,610 | 0.001863 | """
Given a binary tree, convert it to BST. The conversion should be done in such a way
that keeps the original structure of binary tree.
Input:
10
/ \
2 7
/ \
8 4
Output:
8
/ \
4 10
/ \
2 7
Input:
10
/ \
... | ree and store it in a temp array.
2. Sort the temp array.
3. Do another inorder traversal, this time replace tree node values with values from sorted array.
Time complexity is O(nlog(n))
"""
def binary_ | to_bst(root):
result = []
inorder(root, result, False)
result = sorted(result)
inorder(root, result, True)
def inorder(root, result, result_to_bst):
if root:
inorder(root.left, result, result_to_bst)
if result_to_bst:
data = result.pop(0)
root.data = data
... |
philrosenfield/core_overshoot_clusters | setup.py | Python | mit | 901 | 0 | from setuptools import setup, find_packages
setup(name='core_overshoot_clusters',
version='0.1',
description='Repo for reproducing Rosenfield et. al ApJ 2017, xxx, xxx',
url='http://github.com/philrosenfield/core_overshoot_clusters',
author='Philip Rosenfield',
author_email='philip.rosenf... | packages=['core_overshoot_clusters'],
zip_safe=False,
classifiers=['License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2 | ',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'],
install_requires=['matplotlib', 'numpy', 'astropy', 'scipy', 'pandas'],
include_package_data=True)
|
Azure/azure-sdk-for-python | sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py | Python | mit | 7,926 | 0.005804 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | return cls(pipeline_response, deserialized, {})
return deserialized |
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuatio... |
koala-ai/tensorflow_nlp | nlp/text_representation/glove/run.py | Python | apache-2.0 | 1,371 | 0.001459 | # -*- coding: utf-8 -*-
import argparse
import tensorflow as tf
from nlp.text_representation.glove.train import train
def main(args):
if args.process == tf.estimator.ModeKeys.TRAIN:
train(args)
else:
raise Exception("cannot support this process:" + args.process)
if __name__ == '__main__':
... | ult='data/glove')
parser.add_argument('--log_dir', required=True, type=str, default='data/glove/log')
parser.add_argument('--embedding_size', type=int, default=300)
parser.add_argument('--context_size', type=int, default=10)
parser.add_argument('--max_vocab_size', type=int, default=100000)
| parser.add_argument('--min_occurrences', type=int, default=1)
parser.add_argument('--scaling_factor', type=float, default=0.75)
parser.add_argument('--cooccurrence_cap', type=int, default=100)
parser.add_argument('--batch_size', type=int, default=512)
parser.add_argument('--learning_rate', type=float,... |
Ledoux/ShareYourSystem | Pythonlogy/build/lib/ShareYourSystem/Standards/Viewers/Pyploter/05_ExampleDoc.py | Python | mit | 925 | 0.083243 |
#ImportModules
import ShareYourSystem as SYS
#figure
MyPyploter=SYS.PyploterClass(
).mapSet(
{
'-Charts':
{
'|a':{
'-Draws':[
('|0',{
'PyplotingDrawVariable':
[
(
'plot',
{
'#lia | rg':[
[1,2,3],
[2,6,3]
],
'#kwa | rg':{
'linestyle':"",
'marker':'o'
}
}
)
]
}),
('|1',{
'PyplotingDrawVariable':
[
(
'plot',
{
'#liarg':[
[0,1,2],
[2,3,4]
],
'#kwarg':{
'linestyle':"... |
Mesitis/community | sample-code/Python/20 Users/validate_token.py | Python | mit | 2,764 | 0.01411 | '''
- login and get token
- process 2FA if 2FA is setup for this account
- Validates password for changing password using forgot password
'''
import requests
import json
get_token_url = "https://api.canopy.cloud:443/api/v1/sessions/"
validate_otp_url = "https://api.canopy.cloud:443/api/v1/sessions/otp/validate.json... | tten_password_token = ""
payload = {"token":forgotten_password_token}
headers = {
'authorization': token,
'username': username,
'content-type': "a | pplication/x-www-form-urlencoded",
'x-app-switch-user': str(switch_user_id)
}
response = requests.request("POST", validate_token_url, data=payload, headers=headers)
print json.dumps(response.json(), indent=4, sort_keys = True)
|
eirki/script.service.koalahbonordic | service.py | Python | mit | 2,275 | 0.002637 | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, absolute_import, division)
import datetime as dt
import xbmc
import xbmcgui
from threading import Thread
from lib import constants as const
from lib import kodi
if const.os == "win":
import pywin32setup
from lib import playb... |
"15 min": 900,
"30 min": 1800,
"1 hour": 3600,
"2 hours": 7200
}[kodi.settings["schedule frequency"]]
scheduler_enabled = kodi.settings["enable schedule"]
player_active = kodi.r | pc("Player.GetActivePlayers")
koala_active = xbmcgui.Window(10000).getProperty("%s running" % const.addonname) == "true"
if player_active or koala_active or not scheduler_enabled:
continue
kodi.log("Starting scheduled update next update at %s" %
(dt.datetime.now() +... |
aroig/offlineimap | offlineimap/folder/Gmail.py | Python | gpl-2.0 | 15,648 | 0.003962 | # Gmail IMAP folder support
# Copyright (C) 2008 Riccardo Murri <riccardo.murri@gmail.com>
# Copyright (C) 2002-2007 John Goerzen <jgoerzen@complete.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free So... | "label" from
the message and keep it in the "All mails" folder. To really delete
a message it needs to be copied to the Trash folder. However, this
is dangerous as our folder moves are i | mplemented as a 1) delete in
one folder and 2) append to the other. If 2 comes before 1, this
will effectively delete the message from all folders. So we cannot
do that until we have a smarter folder move mechanism.
For more information on the Gmail IMAP server:
http://mail.google.com/support/bin... |
brownlegion/testfleet | startup.py | Python | apache-2.0 | 994 | 0.016097 | #print(" _____ _ _ _ ");
#print("| __ \ (_) (_) | | ");
#print("| | \/_ _ _ __ ___ _ _ ___ | | _____ _____ ");
#print("| | __| | | | '_ ` _ \| | | / __| | |/ _ \ \ / / _ \ ");
#print("| |_\ | |_| | | | | | | | | \_ | _ \ | | (_) \ V | __/_ ");
#print(" \____/\__,_|_| |_| |_|_| |_|___/ |_|\___/ \_/ \___(_) ");
#print("| __ \ (_) (_) | (_)/ _| ");
#print("| | \/_ _ _ __ ___ _ _ ___ | |_| |_ ___ ");
#print("| | __| | | | '_ ` _ \| | | / __| | | | _/ _ \ ");
#print("| |_\ | |_| | |... | || __/_ ");
#print(" \____/\__,_|_| |_| |_|_| |_|___/ |_|_|_| \___(_) ");
#print(" ");
print(... |
linuxscout/arramooz | scripts/nouns/t.py | Python | gpl-2.0 | 2,802 | 0.025241 | COMP_PREFIX_LIST_MODEL={
"":{'tags':(u"", ), "vocalized":(u"", )},
u'ب':{'tags':(u'جر', ), "vocalized":(u"بِ", )},
u'ل':{'tags':(u'جر', ), "vocalized":(u"لِ", )},
u'ال':{'tags':(u'تعريف', ), "vocalized":(u"الْ", )},
u'بال':{'tags':(u'جر', u'تعريف', ), "vocalized":(u" | بِالْ", )},
u'لل':{'tags':(u'جر', u'تعريف', ), "voc | alized":(u"لِلْ", )},
}
COMP_SUFFIX_LIST_MODEL=[
"",
u'ي',
u"كَ",
];
# affixes tags contains prefixes and suffixes tags
affix_tags = snconst.COMP_PREFIX_LIST_TAGS[procletic]['tags'] \
+snconst.COMP_SUFFIX_LIST_TAGS[encletic_nm]['tags'] \
... |
bozzzzo/quark | quarkc/test/emit/expected/py/marshalling/m/__init__.py | Python | apache-2.0 | 3,469 | 0.004901 | from quark_runtime import *
import quark.reflect
import marshalling_md
import quark
class Inner(object):
def _init(self):
self.inner_int = None
self.inner_string = None
self.inner_float = None
self.inner_string_list = None
def __init__(self): self._init()
def setup(self,... | f = float(i);
(self).inner_int = i
(self).inner_string = (u"str of ") + (_toString(i))
(self).inner_float = (300.14) + (f)
(self).inner_s | tring_list = _List([u"i"])
return self
def _getClass(self):
return u"m.Inner"
def _getField(self, name):
if ((name) == (u"inner_int")):
return (self).inner_int
if ((name) == (u"inner_string")):
return (self).inner_string
if ((name) == (u"inner_... |
google/strabo | client/python/setup.py | Python | apache-2.0 | 1,044 | 0.002874 | #
# Copyright 2015 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle | ss 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 setu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.