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
ConstellationApps/Forms
constellation_forms/models/log.py
Python
isc
1,879
0
from .formSubmission import FormSubmission from django.contrib.auth.models import User from django.db
import models from django.template.defaultfilters import slugify class Log(models.Model): """ Form Submission Log Database Model Attributes: * owner - user submitting the m
essage * submission - form submission associated * timestamp - time of submission entry * private - display to non-owners? * message - log entry * mtype - type of log entry * 1 - user message (default) * 2 - system action * 3 - form status change * 4 - attached file * fil...
beanbaginc/django-evolution
django_evolution/utils/datastructures.py
Python
bsd-3-clause
2,717
0
"""Utilities for working with data structures. Version Added: 2.1 """ from __future__ import unicode_literals from collections import OrderedDict from django_evolution.compat import six def filter_dup_list_items(items): """Return list items with duplicates filtered out. The order of items will be pre...
copy). * Any lists that are in both the source and destination will be combined by appending the source list to the destinataion list (and this will not recurse into lists). * Any dictionaries that are in both the source and destinataion will be merged using this function. * Any keys that ...
dictionary that exist in both dictionaries will result in a :py:exc:`TypeError`. Version Added: 2.1 Args: dest (dict): The destination dictionary to merge into. source (dict): The source dictionary to merge into the destination. Raises: TypeE...
UB-Heidelberg/UBHD-OMPArthistorikum
controllers/home.py
Python
gpl-3.0
318
0.006289
# -*- coding: utf-8 -*- ''' Copyright (c) 2015 Heidelbe
rg University Library Distributed under the GNU GPL v3. For full terms see the file LICENSE.md ''' from ompannouncements import Announcements def index(): a = Announcemen
ts(myconf, db, locale) news_list = a.create_announcement_list() return locals()
edio/randrctl
randrctl/xrandr.py
Python
gpl-3.0
10,440
0.002969
import os from functools import reduce, lru_cache import logging import re import subprocess from randrctl import DISPLAY, XAUTHORITY from randrctl.exception import XrandrException, ParseException from randrctl.model import Profile, Viewport, XrandrConnection, Display logger = logging.getLogger(__name__) class Xra...
ld = True val = m.group(3).strip() elif in_field and m and (len(indent) >= len(
m.group(1)) or m.group(1) == indent): return val elif in_field and not line.startswith(indent): return val elif in_field: val += line.strip() lines_collected += 1 if field == 'EDID' and lines_collected >= 8: ...
sunil07t/e-mission-server
bin/debug/load_timeline_for_day_and_user.py
Python
bsd-3-clause
1,612
0.008685
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * import json import bson.json_util as bju import emission.core.get_database as...
retain", action="store_true", help="specify whether the entries should overwrite existing ones (default) or create new ones") parser.add_argument("-v", "--verbose", type=int, help="after how many lines we should print a status message.") args = parser.parse_args() fn = args.timeline_filena...
print(fn) print("Loading file " + fn) tsdb = edb.get_timeseries_db() user = ecwu.User.register(args.user_email) override_uuid = user.uuid print("After registration, %s -> %s" % (args.user_email, override_uuid)) entries = json.load(open(fn), object_hook = bju.object_hook) for i, entry in ...
Vastra-Gotalandsregionen/verifierad.nu
helper.py
Python
mit
10,385
0.003467
# coding: utf-8 """ This file is where things are stuffed away. Probably you don't ever need to alter these definitions. """ import sys import os.path import uuid import dateutil.parser import datetime from bs4 import BeautifulSoup from urllib.parse import urlparse, urljoin import gzip import requests impor...
not in lvl1_url.text.lower()) and ( "javascript:" not in lvl1_url.text.lower()) and ( "tel:" not in lvl1_url.text.lower()) and ( "mailto:" not in lvl1_url.text.lower()) and ( "#" not in lvl1_url.text.lower()): if lv...
er.parse(lvl1_url.lastmod.string).replace(tzinfo=None) if limit is not None and date is not None and date > limit: date_and_url = (lvl1_url.lastmod.string, lvl1_url.loc.string) found_urls.append( date_and_url) # if date...
birdsarah/bokeh
bokeh/models/plots.py
Python
bsd-3-clause
15,281
0.001701
""" Mo
dels for representing top-level plot objects. """ from __future__ import absolute_import from six import string_types from ..enums import Location from ..mixins import LineProps, TextProps from ..plot_object import PlotObject from ..properties import Bool, Int, String, Color, Enum, Auto, Instance, Either, List, Dict...
rt nice_join from .glyphs import Glyph from .ranges import Range, Range1d from .renderers import Renderer, GlyphRenderer from .sources import DataSource, ColumnDataSource from .tools import Tool, ToolEvents from .widget import Widget def _select_helper(args, kwargs): """ Allow fexible selector syntax. R...
heyman/locust
locust/test/test_util.py
Python
mit
1,232
0.000812
import unittest from locust.util.timespan import parse_timespan from locust.util.rounding import proper_round class TestParseTimespan(unittest.TestCase): def test_parse_timespan_invalid_values(self): self.assertRaises(ValueError, parse_timespan, None) self.assertRaises(ValueError, parse_timespan, ...
sertEqual(3, proper_round(2.5)) self.assertEqual(4, proper_round(3.5)) self.assertEqual(5, proper_round(4.5)) self.assertEqual(6, pro
per_round(5.5))
dw/scratch
tcp_ka2.py
Python
mit
658
0
import socket import sys def set_keepalive(sock, interval=1, probes=5): sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, interval) if hasattr(socket, 'TCP_KEEPCNT'): sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, probes) if hasattr(socket, 'TCP_KEEPIDLE'): sock.setsockopt(sock...
() set_keepalive(s) s.listen(1) while True: csock, addr = s.acc
ept() set_keepalive(csock) print csock.recv(512)
Eric89GXL/vispy
vispy/visuals/transforms/base_transform.py
Python
bsd-3-clause
7,578
0.001715
# -*- coding: utf-8 -*- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ API Issues to work out: - MatrixTransform and STTransform both have 'scale' and 'translate' attributes, but they are used in very different ways. It ...
o shader template variables. Example:: code = 'void main() { gl_Position = $transform($position); }' func = shaders.Function(code) tr =
STTransform() func['transform'] = tr # use tr's forward mapping for $function """ return self.shader_map() def update(self, *args): """ Called to inform any listeners that this transform has changed. """ self.changed(*args) def __mul__(self, tr): ...
liampauling/flumine
tests/test_config.py
Python
mit
865
0
import unittest from flumine import config class ConfigTest(unittest.TestCase): def test_init(self): self.assertFalse(config.simulated) self.assertTrue(config.simulated_stra
tegy_isolation) self.assertIsInstance(config.customer_strategy_ref, str) self.assertIsInstance(con
fig.process_id, int) self.assertIsNone(config.current_time) self.assertFalse(config.raise_errors) self.assertEqual(config.max_execution_workers, 32) self.assertFalse(config.async_place_orders) self.assertEqual(config.place_latency, 0.120) self.assertEqual(config.cancel_la...
tochikuji/pyPyrTools
pyrtools/mkRamp.py
Python
mit
1,617
0.002474
import numpy import math def mkRamp(*args): ''' mkRamp(SIZE, DIRECTION, SLOPE, INTERCEPT, ORIGIN) Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar) containing samples of a ramp function, with given gradient DIRECTION (radians, CW from X-axis, default = 0), SLOPE (per pixel...
2: slope = args[2]
else: slope = 1 if len(args) > 3: intercept = args[3] else: intercept = 0 if len(args) > 4: origin = args[4] else: origin = (float(sz[0] - 1) / 2.0, float(sz[1] - 1) / 2.0) #-------------------------- xinc = slope * math.cos(direction) yinc = slo...
Acimaz/Google_Apple_Financial_Reporter
AppleReporter.py
Python
mit
4,732
0.005283
from subprocess import * import gzip import string import os import time import ApplePythonReporter class ApplePythonReport: vendorId = YOUR_VENDOR_ID userId = 'YOUR_ITUNES_CONNECT_ACCOUNT_MAIL' password = 'ITUNES_CONNECT_PASSWORD' account = 'ACCOUNT_ID' mode = 'Robot.XML' dateType = 'Daily' ...
if(attempts >= self.maxAttempts): break attempts += 1 time.sleep(1) if os.path.isfile(fileName): print 'Fetching SubscriptionEvents..' with open(fileName, 'rb') as inF: text = inF.read().splitlines
() for row in text[1:]: line = string.split(row, '\t') # print line[self.eventIndex].__str__() if line[0].__str__().endswith(date[-2:]): if line[self.eventIndex] == 'Cancel': self.cancellation...
markreidvfx/pyaaf2
examples/import_media.py
Python
mit
17,403
0.008045
#!/usr/bin/env python from __future__ import ( unicode_literals, absolute_import, print_function, division, ) import aaf2 import traceback import subprocess import json import os import datetime import sys import tempfile import shutil import time import fractions from aaf2 import auid from pprint...
: format = "%S.%f" t = datetime.timedelta(seconds=float(seconds)) return str(t) def has_alpha(stream): if stream['pix_fmt'] in ('yuva444p10le','rgba'): return True return False def c
onform_media(path, output_dir, start=None, end=None, duration=None, width=None, height=None, frame_rate=None, video_profile_name=None, audio_profile_name=None...
arfc/moltres
property_file_dir/cnrs-benchmark/feedback.py
Python
lgpl-2.1
2,292
0
import numpy as np def extrapolate(xs_name): """Extrapolate cross section based on thermal salt expansion feedback. Extrapolates cross section data at 900 K to 1500 K at 50 K intervals based on the thermal salt expansion feedback formula from [1]. Writes the extrapolated data back into the .txt cross...
codes dedicated to molten salt fast reactors," Annals of Nuclear Energy, vol. 142, July 2020, 107428. """ rho_900 = 2.0e3 # Density at 900 K [kg m-3] alpha = 2.0e-4 # Thermal expansion coeff [K-1] input_file = "benchmark_" + xs_name + ".txt" # Setup temperature values to extra...
f = open(input_file, 'r+') lines = f.readlines() data_900 = list(lines[0].split()) f.close() # Setup space separated data to be written back into txt s = " " xs = [s.join(data_900) + "\n"] h = open(input_file, 'w') for i in range(len(temp)): # Calculate density at temp[i] ...
particl/particl-core
test/functional/feature_maxtipage.py
Python
mit
1,997
0.002003
#!/usr/bin/env python3 # Copyright (c) 2022 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test logic for setting nMaxTipAge on command line. Nodes don't consider themselves out of "initial block do...
mework from test_framework.util import assert_equal DEFAULT_MAX_TIP_AGE = 24 * 60 * 60 class MaxTipAgeTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 def test_maxtipage(self, maxtipage, set_parameter=True): node_miner = self.no...
nect_nodes(0, 1) # tips older than maximum age -> stay in IBD cur_time = int(time.time()) node_ibd.setmocktime(cur_time) for delta in [5, 4, 3, 2, 1]: node_miner.setmocktime(cur_time - maxtipage - delta) self.generate(node_miner, 1) assert_equal(node_...
liqd/adhocracy4
tests/forms/test_forms.py
Python
agpl-3.0
1,198
0
import pytest from dateutil.parser import parse from django import forms from adhocracy4.forms.fields import DateTimeField class DateTimeForm(forms.Form): date = DateTimeField( time_format='%H:%M', required=False, require_all_fields=False, ) @pytest.mark.django_db def test_datetimef...
ta = {'date_0': '2023-01-01', 'date_1': ''} form = DateTimeForm(data=data) assert form.is_valid() assert form.cleaned_
data['date'] == \ parse('2023-01-01 00:00:00 UTC')
redhat-openstack/manila
manila/tests/api/v1/test_share_types.py
Python
apache-2.0
8,424
0
# Copyright 2011 OpenStack Foundation # 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 l...
) ) request = fakes.HTTPRequest.blank("/v2") output = view_builder.index(request, raw_share_types) self.assertIn('share_types', output) for i in range(0, 10): expected_share_type = dict( name='new_type', extra_specs={}, ...
[i], expected_share_type) @ddt.data(None, True, 'true', 'false', 'all') def test_parse_is_public_valid(self, value): result = self.controller._parse_is_public(value) se
brettwooldridge/buck
scripts/artificialproject/file_path_generator.py
Python
apache-2.0
7,481
0.000535
# Copyright 2018-present Facebook, 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 i...
ath = path self._last_package_remaining_targets = ( weighted_choice(self._build_file_sizes) - 1
) return path def generate_path_in_package( self, package_path, depth, component_generator, extension ): if depth == 0: return "" if self._file_samples_dirty: self._sizes_by_depth_in_package.clear() for dir_entries in self._file_samples.va...
ukBaz/ble_beacon
tests/data/pkt_capture.py
Python
gpl-2.0
39,109
0.006648
data = [ b'\x04\x0e\x04\x01\x05 \x00', b'\x04\x0e\x04\x01\x0b \x00', b'\x04\x0e\x04\x01\x0c \x00', b'\x04>+\x02\x01\x03\x01\x97\xe7/s\x18b\x1f\x1e\xff\x06\x00\x01\t \x02[=cdI\xb9kQl\x977W\xc2V?\xa2k\xe7\x1c\xf4\x9d\xd7\x85\xc9', b'\x04>\x1a\x02\x01\x00\x01\x07\xbb\xd8!p\\\x0e\x02\x01\x06\n\xffL\x00\...
04>\x1e\x02\x01\x00\x01\x1bQm\xb7Qd\x12\x02\x01\x1a\x02\n\x0c\x0b\xffL\x00\x10\x06\x03\x1e\xa0\xdeI?\xae', b'\x04>\x0c
\x02\x01\x04\x01\x1bQm\xb7Qd\x00\xac', b'\x04>(\x02\x01\x02\x01\xb9\xf6\x0f\xfd\xe2\\\x1c\x03\x03\x9f\xfe\x17\x16\x9f\xfe\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xaf', b'\x04>\x16\x02\x01\x04\x01\xb9\xf6\x0f\xfd\xe2\\\n\t\xff\xe0\x00\x01z\xca\x86\xa1\xca\xb0', b"\x04>...
atumanov/ray
python/ray/rllib/models/torch_action_dist.py
Python
apache-2.0
1,516
0
from __future__ import absolute_import from __future__ import division from __future__ import print_function try: import torch except ImportError: pass # soft dep from ray.rllib.models.action_dist import ActionDistribution from ray.rllib.utils.annotations import override class TorchDistributionWrapper(Acti...
def __init__(self, inputs): self.dist = torch.distributions.categorical.Categorical(logits=inputs) class TorchDiagGaussian(TorchDistributionWrapper): """Wrapper class for PyTorch Normal distribution.""" @override(ActionDistribution) def __init__(self, inputs): mean, log_std = torch.c...
self.dist = torch.distributions.normal.Normal(mean, torch.exp(log_std)) @override(TorchDistributionWrapper) def logp(self, actions): return TorchDistributionWrapper.logp(self, actions).sum(-1)
cans/tappy-pkg
tap/tests/__init__.py
Python
bsd-2-clause
105
0
# Copyright (c) 2
015, Matt Layman """Tests for tappy""" from tap.
tests.testcase import TestCase # NOQA
rhoml/lemur
lemur/auth/views.py
Python
apache-2.0
8,442
0.002961
""" .. module: lemur.auth.views :platform: Unix :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ import jwt import base64 import requests from flask import g, Blueprint, current_app from fl...
le.get('thumbnailPhotoUrl'), # incase profile isn't google+ enabled ro
les ) # Tell Flask-Principal the identity
RedHatInsights/insights-core
insights/parsers/pluginconf_d.py
Python
apache-2.0
3,141
0
""" pluginconf.d configuration file - Files ======================================= Shared mappers for parsing and extracting data from ``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained in this module are: PluginConfD - files ``/etc/yum/pluginconf.d/*.conf`` ---------------------------------------------------...
#[some-unsigned-custom-channel] #gpgcheck = 0 """ def parse_content(self, content): deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.") plugin_dict =
{} section_dict = {} key = None for line in get_active_lines(content): if line.startswith('['): section_dict = {} plugin_dict[line[1:-1]] = section_dict elif '=' in line: key, _, value = line.partition("=") k...
zuun77/givemegoogletshirts
leetcode/python/839_similar-string-groups.py
Python
apache-2.0
1,451
0.009649
import collections class Solution: def numSimilarGroups(self, A): UF = {} for i in range(len(A)): UF[i] = i def find(x): if x != UF[x]: UF[x] = find(UF[x]) return UF[x] def union(x, y): UF.setdefault(x, x) UF.setdefault(...
i = 0 j = -1 while i<len(s1): if s1[i] != s2[i]: if j == -1: j = i else: break i += 1 return s1[i+1:] == s2[i+1:] N, W = len(A), len(A[0]) if N < W*W: for i in range(len(A)): UF[i]...
range(i+1, len(A)): if match(A[i], A[j]): union(i, j) else: d = collections.defaultdict(set) for idx, w in enumerate(A): lw = list(w) for i in range(W): for j in range(i+1, W): ...
zoucaitou/azeroth-spider
azeroth_spider/dytt.py
Python
mit
310
0.006452
# -*- coding: utf-8 -*- from queue.producer import Producer from queue.consumer import Consumer from queue.bloom_filter import BloomFilter class Dytt: def main(): for i in range(15): # Producer().start() Consumer().start() if __name__ == '__main__':
main()
ESOedX/edx-platform
lms/djangoapps/utils.py
Python
agpl-3.0
368
0
""" Helper Methods """ im
port six def _get_key(key_or_id, key_cls): """ Helper method to get a course/usage key either from a string or a key_cls, where the key_cls (CourseKey or UsageKey) will simply be returned. """ return ( key_cls.from_string(key_or_id) if isinstance(key_or_id, six.string_types) ...
)
giupo/flypwd
flypwd/keys.py
Python
bsd-3-clause
658
0.00304
# -*- coding:utf-8 -*- import logging import warnings from flypwd.config import config with warnings.catch_warnings(): warnin
gs.simplefilter("ignore") from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 log = logging.getLogger(__name__) def check_key(keyfile): """ checks the RSA key file raises ValueError if not valid """ with open(keyfile, 'r') as f: return RSA.importKey(f.read(), pass...
) def encrypt_with_pub(pwd, pub): cipher = PKCS1_v1_5.new(pub) return cipher.encrypt(pwd.encode('utf-8'))
alexforencich/hdg2000
fpga/tb/test_wb_mcb_32.py
Python
mit
10,990
0.012648
#!/usr/bin/env python2 """ Copyright (c) 2015 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
rst=rst, current_test=current_test, wb_adr_i=wb_adr_i, wb_dat_i=wb_dat_i, wb_dat_o=wb_dat_o, wb_we_i=wb_we_i, wb_sel_i=wb_sel_i, wb_stb_i=wb_stb_i, wb_ack_o=wb_ack_o, wb_c...
mcb_cmd_bl=mcb_cmd_bl, mcb_cmd_byte_addr=mcb_cmd_byte_addr, mcb_cmd_empty=mcb_cmd_empty, mcb_cmd_full=mcb_cmd_full, mcb_wr_clk=mcb_wr_clk, mcb_wr_en=mcb_wr_en, mcb_wr_mask=mcb_wr_mask, mcb_wr_data=mcb_wr_...
sgkang/PhysPropIP
codes/ZarcFit2016-01-26.py
Python
mit
44,212
0.011626
#### ZarcFit.py #### for interactive model fitting of spectral electrical impedance observations. # Seogi Kang and Randy Enkin, developed starting November 2015. # Based on ZarcFit.vi, written in LabView by Randy Enkin, Geological Survey of Canada # Using Python version 3.4 and QT version 4.8 # # requires files Zar...
# Set-up frequency range ZarcFitWindow.frequency = frequency ZarcFitWindow.frequencyorig = frequency.copy() ZarcFitWindow.nfreq = ZarcFitWindow.frequency.size ZarcFitWindow.spinBoxHighFreq.setValue(0) ZarcFitWindow.labelHighFreq.setText("{:,}".format(ZarcFitWindow.freque...
.frequencyorig[-1])+" Hz") ZarcFitWindow.freqindhigh = ZarcFitWindow.nfreq ZarcFitWindow.initializeFigure() ZarcFitWindow.addmplCole() ZarcFitWindow.t0 = time.time() # super(Main, ZarcFitWindow).__init__() # ZarcFitWindow.setupUi(ZarcFitWindow) ...
uudiin/bleachbit
bleachbit/GuiPreferences.py
Python
gpl-3.0
18,737
0.000907
# vim: ts=4:sw=4:expandtab # -*- coding: UTF-8 -*- # BleachBit # Copyright (C) 2008-2015 Andrew Ziem # http://bleachbit.sourceforge.net # # 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...
eta.set_sensitive(options.get('check_online_updates')) self.cb_beta.connect( 'toggled', self.__toggle_callback, 'check_beta') updates_box.pack_start(self.cb_beta, False) if 'nt' == os.name: self.cb_winapp2 = gtk.CheckButton( _("Dow...
self.cb_winapp2.set_sensitive( options.get('check_online_updates')) self.cb_winapp2.connect( 'toggled', self.__toggle_callback, 'update_winapp2') updates_box.pack_start(self.cb_winapp2, False) vbox.pack_start(updates_box, False...
hzlf/openbroadcast
website/tools/dgs2/discogs_client/models.py
Python
gpl-3.0
21,790
0.000964
from dgs2.discogs_client.exceptions import HTTPError from dgs2.discogs_client.utils import parse_timestamp, update_qs, omit_none class SimpleFieldDescriptor(object): """ An attribute that determines its value using the object's fetch() method. If transform is a callable, the value will be passed through ...
instance.changes[self.name] = value
return raise AttributeError("can't set attribute") class ObjectFieldDescriptor(object): """ An attribute that determines its value using the object's fetch() method, and passes the resulting value through an APIObject. If optional = True, the value will be None (rather than an APIObject ...
jie-lin/libvmi
tools/pyvmi/examples/process-list.py
Python
gpl-3.0
1,982
0.001009
#!/usr/bin/env python """ The LibVMI Library is an introspection library that simplifies access to memory in a target virtual machine or in a file containing a dump of a system's physical memory. LibVMI is based on the XenAccess Library. Copyright 2011 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000...
ny later version. LibVMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public ...
win_tasks") name_offset = vmi.get_offset("win_pname") - tasks_offset pid_offset = vmi.get_offset("win_pid") - tasks_offset list_head = vmi.read_addr_ksym("PsInitialSystemProcess") next_process = vmi.read_addr_va(list_head + tasks_offset, 0) list_head = next_process while True: procname...
cgarrard/osgeopy-code
Chapter12/listing12_1.py
Python
mit
378
0.002646
# Function to stack raster bands. im
port numpy as np from osgeo import gdal def stack_bands(filenames): """Returns a 3D array containing all band data from all files.""" bands = [] for fn in filenames: ds = gdal.Open(fn) for i in range(1, ds.RasterCount + 1): bands.append(ds.GetRasterBand(i).ReadAsArray()) ret...
WayneDW/Sentiment-Analysis-in-Event-Driven-Stock-Price-Movement-Prediction
util.py
Python
mit
13,305
0.006238
#!/usr/bin/env python3 import os import sys import copy import re import time import datetime from urllib.request import urlopen import numpy as np import nltk from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import json import torch import torch.autograd as autograd import...
e-16} batch = args.batch_size for idx in range(int(X.shape[0]/batch) + 1): feature = torch.LongTensor(X[(idx*batch):(idx*batch+batch),]) target = torch.LongTensor(y[(idx*batch):(idx*batch+batch)]) if args.cuda: feature, target = feature.cuda(), target.cuda() log
it = model(feature) loss = F.cross_entropy(logit, target, size_average=False) avg_loss += loss.data.item() predictor = torch.exp(logit[:, 1]) / (torch.exp(logit[:, 0]) + torch.exp(logit[:, 1])) for xnum in range(1, 3): thres = round(0.2 * xnum, 1) idx_thres = (pre...
alexpilotti/python-keystoneclient
keystoneclient/middleware/s3_token.py
Python
apache-2.0
10,573
0
# Copyright 2012 OpenStack Foundation # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011,2012 Akira YOSHIYAMA <akirayoshiyama@gmail.com> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "Lic...
ion code.""" self.app = app self.logger = logging.getLogger(conf.get('log_name', __name__)) self.logger.debug('Starting the %s component', PROTOCOL_NAME) self.logger.warning( 'This middleware module is deprecated as of v0.11.0 in favor of ' 'keystonemiddleware.s3_...
our WSGI pipeline ' 'to reference the new middleware package.') self.reseller_prefix = conf.get('reseller_prefix', 'AUTH_') # where to find the auth service (we use this to validate tokens) auth_host = conf.get('auth_host') auth_port = int(conf.get('auth_port', 35357)) ...
karthik-sethuraman/ONFOpenTransport
RI/flask_server/tapi_server/models/tapi_oam_mip_ref.py
Python
apache-2.0
2,530
0.000395
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from tapi_server.models.base_model_ import Model from tapi_server.models.tapi_oam_meg_ref import TapiOamMegRef # noqa: F401,E501 from tapi_server import util class T...
_init__(self, meg_uuid=None, mip_local_id=None): # noqa: E501 """TapiOamMipRef - a model defined in OpenAPI :param meg_uuid: The
meg_uuid of this TapiOamMipRef. # noqa: E501 :type meg_uuid: str :param mip_local_id: The mip_local_id of this TapiOamMipRef. # noqa: E501 :type mip_local_id: str """ self.openapi_types = { 'meg_uuid': str, 'mip_local_id': str } self.at...
coder0xff/Plange
documentation/syntax-cgi.py
Python
bsd-3-clause
5,936
0.012298
#!/usr/bin/python import yaml import pprint import os import pdb import re import cgi import codecs import sys import cgitb cgitb.enable() if (sys.stdout.encoding is None): print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." ...
"syntax" in details: syntaxString = simplifySyntaxStringAddLinks(details["syntax"]) title = "syntax" if "assoc" in details: title = title + " (associativity: " + details["assoc"] + ")" print "\t\t<div class=\"syntax\...
must contain a syntax element") if "example" in details: print loadExample(details["example"]) if "examples" in details: for example in details["examples"]: print loadExample(example) if "notes" in details: print "\t\t<h2...
tensorflow/docs
tools/tensorflow_docs/api_generator/doc_controls.py
Python
apache-2.0
12,723
0.006445
# Lint as: python3 # Copyright 2018 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 ...
ls" def set_custom_page_builder
_cls(obj, cls): """Replace most of the generated page with custom content.""" setattr(obj, _CUSTOM_PAGE_BUILDER_CLS, cls) def get_custom_page_builder_cls(obj): """Gets custom page content if available.""" return getattr(obj, _CUSTOM_PAGE_BUILDER_CLS, None) _DO_NOT_DOC = "_tf_docs_do_not_document" def do_n...
kengz/python-structure
setup.py
Python
mit
976
0.004098
#!/usr/bin/env python import os from setuptools import setup, find_packages from structure import __version__ # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # READM
E file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() # the setup setup( name='structure', version=__version__, description='An demonstration of PyPi.', # long_description=read...
='example pypi tutorial', packages=find_packages(exclude=('docs', 'tests', 'env', 'index.py')), include_package_data=True, install_requires=[ ], extras_require={ 'dev': [], 'docs': [], 'testing': [], }, classifiers=[], )
amitsela/incubator-beam
sdks/python/apache_beam/io/localfilesystem.py
Python
apache-2.0
8,015
0.005989
# # 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...
ions) def exists(self, path): """Check if the provided path exists on the FileSystem. Args: path: string path that needs to be checked. Returns: boolean flag indicating if path exists """ return os.path.exists(path) def delete(self, paths): """Deletes files or directories at the pr...
d paths. Directories will be deleted recursively. Args: paths: list of paths that give the file objects to be deleted Raises: ``BeamIOError`` if any of the delete operations fail """ def _delete_path(path): """Recursively delete the file or directory at the provided path. "...
repotvsupertuga/tvsupertuga.repository
script.module.openscrapers/lib/openscrapers/sources_openscrapers/de/tata.py
Python
gpl-2.0
8,804
0.005793
# -*- coding: UTF-8 -*- # ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######. # .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....## # .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#....
ry: sources.append( {'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'],
'language': 'de', 'url': i, 'direct': True, 'debridonly': False}) except: pass return sources except: return def resolve(self, url): return url def __search_movie(self, imdb, year): try: ...
jabesq/home-assistant
homeassistant/components/hive/__init__.py
Python
apache-2.0
2,196
0
"""Support for the Hive devices.""" import logging from pyhiveapi import Pyhiveapi import voluptuous as vol from homeassistant.const import ( CONF_PASS
WORD, CONF_SCAN_INTERV
AL, CONF_USERNAME) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform _LOGGER = logging.getLogger(__name__) DOMAIN = 'hive' DATA_HIVE = 'data_hive' DEVICETYPES = { 'binary_sensor': 'device_list_binary_sensor', 'climate': 'device_list_climate', 'w...
marcioweck/PSSLib
reference/deap/doc/code/tutorials/part_3/logbook.py
Python
lgpl-3.0
1,381
0.003621
import pickle from deap import tools from stats import record logbook = tools.Logbook() logbook.record(gen=
0, evals=30, **record) print(logbook) gen, avg = logbook.select("gen", "avg") pickle.dump(logbook, open("logbook.pkl", "w")) # Cleaning the pickle file ... import os os.remove("logbook.pkl") l
ogbook.header = "gen", "avg", "spam" print(logbook) print(logbook.stream) logbook.record(gen=1, evals=15, **record) print(logbook.stream) from multistats import record logbook = tools.Logbook() logbook.record(gen=0, evals=30, **record) logbook.header = "gen", "evals", "fitness", "size" logbook.chapters["fitness"].h...
stuckj/dupeguru
hscommon/tests/table_test.py
Python
gpl-3.0
9,340
0.006852
# Created By: Virgil Dupras # Created On: 2008-08-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/g...
after cancel_edits(). Previously, only _update_selection would # be called. class MyTable(TestGUITable): def _restore_selection(self, previous_selec
tion): self.selected_indexes = [6] table = MyTable(10) table.refresh() table.add() table.cancel_edits() eq_(table.selected_indexes, [6]) def test_restore_selection_with_previous_selection(): # By default, we try to restore the selection that was there before a refresh table...
hzlf/openbroadcast
website/cms/test_utils/project/second_urls_for_apphook_tests.py
Python
gpl-3.0
696
0.005747
from django.conf import settings from django.conf.urls.defaults import handler500, handler404, patte
rns, include, \ url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'), url(r'^media/cms/(?P<path>.*)$', 'django.views.static.serve', {'document...
h>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^', include('cms.test_utils.project.second_cms_urls_for_apphook_tests')), )
nanonyme/nanoplay
nanoplay/__init__.py
Python
mit
76
0
from nan
oplay import PayloadProtocol, C
ontrolProtocol, Player, CustomServer
hanakamer/eskisozluk-clone
App/eksi/manage.py
Python
gpl-2.0
247
0
#!/usr
/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eksi.settings") from django.core.management import execute_from_command_line execute_from_command_line(s
ys.argv)
zhaochl/python-utils
utils/mail_util.py
Python
apache-2.0
3,970
0.013465
#!/usr/bin/python # -*- coding: utf-8 -*- import email import mimetypes from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage import smtplib from time import sleep def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText): strFrom = fro...
msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) #设定纯文本信息 #msgText = MIMEText(plainText, 'plain', 'GB18030') msgText = MIMEText(plainText, 'plain', 'utf-8') msgAlternative.attach(msgText) #设定HTML信息
#msgText = MIMEText(htmlText, 'html', 'GB18030') msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) #设定内置图片信息 #fp = open('test.jpg', 'rb') #msgImage = MIMEImage(fp.read()) #fp.close() #msgImage.add_header('Content-ID', '<image1>') #msgRoot.attach(msgImage) ...
albireox/marvin
python/marvin/tests/utils/test_images.py
Python
bsd-3-clause
11,203
0.002856
# !usr/bin/env python2 # -*- coding: utf-8 -*- # # Licensed under a 3-clause BSD license. # # @Author: Brian Cherinka # @Date: 2017-06-20 16:36:37 # @Last modified by: Brian Cherinka # @Last Modified time: 2017-11-13 15:16:57 from __future__ import print_function, division, absolute_import from marvin.utils.genera...
available when in local mode' # with warnings.catch_warnings(record=True) as cm: # warnings.simplefilter('always') # image = getImagesByList([get_cube.plateifu], mode='local', as_url=True, download=True) # assert cm[-1].category is MarvinUserWarning # assert errmsg in str...
ge) class TestImagesByPlate(object): @pytest.mark.parametrize('plateid, mode, errmsg', [('8485abcd', 'local', 'Plateid must be a numeric integer value'), (None, 'notvalidmode', 'Mode must be either auto, local, or remote')], ...
tzuria/Shift-It-Easy
webApp/shift-it-easy-2015/web/pages/__init__.py
Python
mit
177
0.00565
#
To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor.
caphrim007/ansible
lib/ansible/modules/cloud/azure/azure_rm_loadbalancer.py
Python
gpl-3.0
36,330
0.002175
#!/usr/bin/python # Copyright (c) 2016 Thomas Stringer, <tomstr@microsoft.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
rom virtual machine scale sets. - NICs that are associated with individual virtual machines
cannot reference an inbound NAT pool. - They have to reference individual inbound NAT rules. suboptions: name: description: Name of the inbound NAT pool. required: True frontend_ip_configuration_name: description: A reference to...
googleinterns/vm-network-migration
vm_network_migration/module_helpers/instance_group_helper.py
Python
apache-2.0
4,376
0.0016
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
region of the instance group zone: zone of the instance group preserve_instance_ip: only valid for an unmanaged instance group """ def build_instance_group(self) -> InstanceGroup: """ Build an object which is an instance of the InstanceGroup's subclass """ #...
one instance group pass else: if 'Instance Group Manager' not in instance_group_configs[ 'description']: return UnmanagedInstanceGroup(self.compute, self.project, self.instance_group_name, ...
TheArchives/Nexus
core/plugins/respawn.py
Python
bsd-2-clause
1,072
0.012127
# The Nexus software is licensed under the BSD 2-Clause license. # # You should have recieved a copy of this license with the software. # If you did not, you can find one at the following link. # # http://opensource.org/licenses/bsd-license.php from core.plugins import ProtocolPlugin from core.decorators import * fro...
if username in self.client.factory.usernames: self.client.factory.usernames[username].respawn() else: self.client.sendServerMessage("%s is not on the server." % username) return self.client.factory.usernames[username].sendServerMessage
("You have been respawned by %s." % self.client.username) self.client.sendServerMessage("%s respawned." % username)
plepe/pgmapcss
pgmapcss/types/image_png.py
Python
agpl-3.0
1,840
0.002717
from .default import default import os import re class image_png(default): def __init__(self, key, stat): default.__init__(self, key, stat)
self.data = {} def compile(self, prop): if not os.path.exists(prop['value']): print("Image '{}' not found.".format(prop['value'])) else: # Convert SVG to PNG m = re.search("\.svg$", prop['value']) if m: from wand.ima
ge import Image from wand.color import Color from wand.api import library dest = self.stat['icons_dir'] + "/" + prop['value'].replace('/', '_') + ".png" print("svg icon detected. converting '{0}' to '{1}'".format(prop['value'], dest)) with...
davidfarr/mg-gap
mg-gap/mg-gap-py/mg-gap/test_files/reduceVCF.py
Python
mit
1,210
0.005785
# -*- coding: utf-8 -*- """ Created on Sun Mar 10 10:43:53 2019 @author: Heathro Description: Reduces a vcf file to meta section and one line for each chromosome number for testing and debugging purposes. """ # Open files to read from and write to vcfpath = open("D:/MG_GAP/Ali_w_767.vcf", "rU") testvcf = open("REDU...
counter at 0
elif current_chrom != temp_chrom: counter = 0 temp_chrom = current_chrom testvcf.write(line) # Include the meta lines and header line else: testvcf.write(line) testvcf.close() vcfpath.close()
hoehermann/wxpyWha
whastack.py
Python
gpl-3.0
3,522
0.010789
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """@package docstring Yowsup connector for wxpyWha (a simple wxWidgets GUI wrapper atop yowsup). Uses WhaLayer to build the Yowsup stack. This is based on code from the yowsup echo example, the yowsup cli and pywhatsapp. """ SECONDS_RECONNECT_DELAY = 10 import sys # ...
e): interface = self.stack.getLayerInterface(WhaLayer) interface.sendMessage(outgoingMessage) def disconnect(self): interface = self.stack.getLayerInterface(WhaLayer) interface.disconnect() def start(self): logging.basicConfig(level=logging.WARNING) ...
NetworkLayer.EVENT_STATE_CONNECT)) try: self.stack.loop() except AuthError as e: sys.stderr.write("Authentication Error\n") except KeyboardInterrupt: # This is only relevant if this is the main module # TODO: disconnect ...
alex/changes
changes/api/build_restart.py
Python
apache-2.0
1,841
0.000543
from sqlalchemy.orm import joinedload from datetime import datetime from changes.api.base import APIView from changes.api.build_index import execute_build from changes.config import db from changes.constants import Result, Status from changes.models import Build, Job, JobStep, ItemStat class BuildRestartAPIView(API...
nnerjoin=True), joinedload('author'), joinedload('source').joinedload('revision'), ).get(build_id) if build is None: return '', 404 if build.status != Status.finished: return '', 400 # ItemStat doesnt cascade by itself stat_ids = ...
[ j[0] for j in db.session.query(Job.id).filter(Job.build_id == build.id) ] if job_ids: step_ids = [ s[0] for s in db.session.query(JobStep.id).filter(JobStep.job_id.in_(job_ids)) ] stat_ids.extend(job_ids) ...
appeltel/AutoCMS
print_records.py
Python
mit
801
0.002497
"""Print all records in the pickle for the specified test""" import sys import argparse from autocms.core
import (load_configuration, load_records) def main(): """Print all records corresponding to test given as an argument""" parser = argparse.ArgumentParser(description='Submit one or more jobs.') parser.add_argument('testname', help='test directory') parser.add_argument('-c', '--configfile', type=str, ...
_configuration(args.configfile) records = load_records(args.testname,config) for job in records: print str(job)+'\n' return 0 if __name__ == '__main__': status = main() sys.exit(status)
ThomasYeoLab/CBIG
stable_projects/fMRI_dynamics/Kong2021_pMFM/part2_pMFM_control_analysis/Primary_gradients/scripts/CBIG_pMFM_step33_test_GradPC2Grad.py
Python
mit
4,115
0.000486
# /usr/bin/env python ''' Written by Kong Xiaolu and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md ''' import os import numpy as np import torch import CBIG_pMFM_basic_functions as fc def CBIG_mfm_test_desikan_main(gpu_index=0): ''' This function is to implement the test...
for k in range(vali_sel_num): corr_t[k] = (corr_tr[k, :] > 0.98).all() if not corr_t.any(): vali_sel[:, i] = vali_sort_all[:, p] p_set[i] = p i += 1 p += 1 result_save = np.zeros((3 * n_node + 1 + 11, vali_sel_num)) result_save[0:8, :] = v...
li_sel_num): test_cost = np.zeros((3, n_set)) for k in range(1): arx = np.tile(vali_sel[8:, j:j + 1], [1, n_set]) total_cost, fc_cost, fcd_cost = fc.CBIG_combined_cost_test( arx, n_dup) test_cost[0, n_set * k:n_set * (k + 1)] = fc_cost test...
dendory/scripts
wikipedia_define.py
Python
mit
347
0.028818
#!/usr/bin/env python3 # Uses the wikipedia module to define words on th
e command line import wikipedia import sys sys.argv.pop(0) for word in sys.argv: try: if word[0] != '-':
if '-full' in sys.argv: print(wikipedia.summary(word)) else: print(wikipedia.summary(word, sentences=1)) except: print("* Unknown word: " + word)
bengland2/fsstress
fsd_log.py
Python
apache-2.0
1,486
0.004038
import os import logging # standardize use of logging module in fs-drift def start_log(prefix, verbosity=0): log = logging.getLogger(prefix) if os.getenv('LOGLEVEL_DEBUG') != None or verbosity != 0: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) log_format = prefix + ' %(...
formatter = logging.Formatter(log_format) h = logging.StreamH
andler() h.setFormatter(formatter) h.setLevel(logging.INFO) log.addHandler(h) h2 = logging.FileHandler('/var/tmp/fsd.%s.log' % prefix) h2.setFormatter(formatter) log.addHandler(h2) log.info('starting log') return log # assumptions: # - there is only 1 FileHandler associated with logge...
williamFalcon/pytorch-lightning
tests/models/test_hooks.py
Python
apache-2.0
38,377
0.002528
# Copyright The PyTorch Lightning team. # # 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 i...
_train_batch_end(self, outputs, batch, batch_idx, dataloader_idx): self.num_train_batches += 1 overridden_model = OverriddenModel() not_overridden_model = NotOverriddenModel() not_overridden_model.training_epoch_end = None trainer = Tra
iner(max_epochs=1, default_root_dir=tmpdir, overfit_batches=2) trainer.fit(overridden_model) assert overridden_model.len_outputs == overridden_model.num_train_batches @RunIf(min_gpus=1) @mock.patch("pytorch_lightning.accelerators.accelerator.Accelerator.lightning_module", new_callable=PropertyMock) def test_...
laosiaudi/tensorflow
tensorflow/python/util/deprecation.py
Python
apache-2.0
12,098
0.004877
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
> level: location = stack[level] return '%s:%d in %s.' % (location[1], location[2], location[3]) return '<unknown>' def deprecated(date, instructions): """Decorator for marking functions or methods deprecated. This decorator logs a deprecation warning whenever the
decorated function is called. It has the following format: <function> (from <module>) is deprecated and will be removed after <date>. Instructions for updating: <instructions> <function> will include the class name if it is a method. It also edits the docstring of the function: ' (deprecated)' is ...
otuncelli/turkish-stemmer-python
TurkishStemmer/transitions/__init__.py
Python
apache-2.0
516
0.007782
__all__ = ["Transition"] class Transition(object): def __init__(self, startState, nextState, word, suffix, marked): self.startState = startState self.nextState = nextState self.word = word self.suffix = suffix self.marked = Fal
se def similarTransitions(self, transitions): for transition in transitions: if (self.startState == transition.startState and self.nextState == transition.nextState):
yield transition
yehzhang/RapidTest
tests/test_by_examples.py
Python
mit
1,535
0.001954
from unittest import TestCase EXAMPLES_PATH = '../examples' SKIPPED_EXAMPLES = {472, 473, 477} def _set_test_class(): import re from imp import load_module, find_module, PY_SOURCE from pathlib import Path def _load_module(name, file, pathname, description): try: load_module(name,...
(module_name, *module_tuple) return _m sols_module_name = 'solutions' _load_module(sols_module_name, *find_module(sols_module_name, [EXAMPLES_PATH])) pat_example = re.compile(r'\d+\. .+\.py') attrs = {} for i,
example_path in enumerate(Path(EXAMPLES_PATH).iterdir()): if not re.match(pat_example, example_path.name): continue module_name = example_path.stem if int(module_name.split('. ')[0]) in SKIPPED_EXAMPLES: continue module_tuple = open(str(example_path), 'rb'), examp...
ahmetalpbalkan/permalinker
application/downloader.py
Python
apache-2.0
140
0
# coding=utf-8 im
port requests def download(url): resp = requests.get(url) # TODO add retries return resp.content, resp.headers
nuxis/p0sX-server
p0sx/pos/migrations/0002_itemingredient_exclusive.py
Python
mit
448
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-03-19 02:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('p
os', '0001_initial'), ] operations = [ migrations.AddField(
model_name='itemingredient', name='exclusive', field=models.BooleanField(default=False), ), ]
lincoln-lil/flink
flink-python/pyflink/table/tests/test_environment_settings_completeness.py
Python
apache-2.0
2,417
0.002482
################################################################################ # 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...
e Python :class:`EnvironmentSettings.Builder` is consistent with Java `org.apache.flink.table.api.EnvironmentSettings$Builder`. """ @classmethod def p
ython_class(cls): return EnvironmentSettings.Builder @classmethod def java_class(cls): return "org.apache.flink.table.api.EnvironmentSettings$Builder" if __name__ == '__main__': import unittest try: import xmlrunner testRunner = xmlrunner.XMLTestRunner(output='target/...
sahlinet/fastapp
fastapp/plugins/singleton.py
Python
mit
1,074
0.003724
import logging logger = logging.getLogger(__name__) class Singleton(type): def __init__(cls, name, bases, dict): super(Singleton, cls).__init__(name, bases, dict) cls.instance = None def __call__(cls, keep=True, *args, **kwargs): logger.debug("Handle singleton instance for %s with arg...
ngleton instance for %s with args (keep=%s): %s, %s" % (cls, keep, args, kwargs)) cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance else: logger.debug("Return cached singleton instance for %s with args (keep=%s): %s, %s" % (cls...
nce for %s with args (keep=%s): %s, %s" % (cls, keep, args, kwargs)) return super(Singleton, cls).__call__(*args, **kwargs) return None
jalaziz/validictory
validictory/tests/test_defaults.py
Python
mit
1,074
0
from unittest import TestCase import validictory class TestItems
(TestCase): def test_property(self): schema = { "type": "object", "properties": { "foo": { "default": "bar" }, "baz": { "type": "integer" } } } data = ...
def test_item(self): schema = { 'type': 'object', 'type': 'array', 'items': [ { 'type': 'any' }, { 'type': 'string' }, { 'default': 'baz...
TwilioDevEd/airtng-flask
airtng_flask/__init__.py
Python
mit
801
0.002497
import os from airtng_flask.config import config_env_files from flask import Flask from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager db = SQLAlchemy() bcrypt = Bcrypt() login_manager = LoginManager() def create_app(config_name='development', p_db=db, p_bcry...
config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False p_db.init_app(new_app) p_bcrypt.init_app(new_app) p_login_manager.init_app(new_app) p_login_manager.login_view = 'register' return new_app def config_app(config_name, new_app): new_app.config.from_object(config_env_files[config_name]) app = c...
.views
jmjj/messages2json
messages2json/__init__.py
Python
mit
140
0
# -*- coding: utf-8 -*- """ Created on Wed Mar 2 10:56:34 2016 @auth
or: jmjj (Jari Juopperi, jmjj@juopperi.org) """ fro
m .main import *
ChawalitK/odoo
addons/web_editor/controllers/main.py
Python
gpl-3.0
10,264
0.00341
# -*- coding: utf-8 -*- from openerp.http import request, STATIC_CACHE from openerp.addons.web import http import json import io from PIL import Image, ImageFont, ImageDraw from openerp import tools import cStringIO import werkzeug.wrappers import time import logging logger = logging.getLogger(__name__) class Web_Edi...
], type='http', auth="none") def export_icon_to_png(self, icon, color='#000', size=100, alpha=255, font='/web/static/lib/fontawesome/fonts/fontawesome-webfont.ttf'): """ This method converts an unicode character to an image (using Font Aw
esome font by default) and is used only for mass mailing because custom fonts are not supported in mail. :param icon : decimal encoding of unicode character :param color : RGB code of the color :param size : Pixels in integer :param alpha : transparency of the...
jbalm/ActuarialCashFlowModel
esg/credit_risk/JLT.py
Python
gpl-3.0
10,706
0.014413
## Progam packages from .credit_model_classes import credit_model_base from ...asset.Asset_data import Asset_data from ..generator_correlated_variables import generator_correlated_variables from ...core_math.function_optim import function_optim from ...core_math.functions_credit import generator_matrix, exp_matrix ## ...
Type : float 6. market_name : market name Type : string Output: _______ 1. RN_migration_matrix : risk-neutral migration matrix Type : matrix 7x7
2. spreads : credit spreads Type : vector of length 7 Methods: _______ 1. add_time_horizon 2. get_spread 3. get_hist_transition_matrix 4. calibrate_spread 5. calibrate_price 6. generate...
firebase/grpc-SwiftPM
setup.py
Python
apache-2.0
15,931
0.006403
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
PIPE, stdout=PIPE, stderr=PIPE) cc_test.communicate(input=code_test) return cc_test.returncode != 0 # There are some situations (like on Windows) where CC, CFLAGS, and LDFLAGS are # entirely ignored/dropped/forgotten by distutils and its Cygwin/MinGW suppor...
the multitude of operating systems this ought to build on. # We can also use these variables as a way to inject environment-specific # compiler/linker flags. We assume GCC-like compilers and/or MinGW as a # reasonable default. EXTRA_ENV_COMPILE_ARGS = os.environ.get('GRPC_PYTHON_CFLAGS', None) EXTRA_ENV_LINK_ARGS = os....
Net-ng/kansha
kansha/card_addons/due_date/view.py
Python
bsd-3-clause
2,112
0.001894
#-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- import peak import datetime from nagare import presentation, security, ajax, i18n from nagare.i18...
.a(class_='bt
n', id_=id_).action(self.calendar().toggle): h << h.i(class_='icon-alarm') h << _('Due date') h << self.calendar.on_answer(self.set_value) return h.root
alxgu/ansible
lib/ansible/modules/network/f5/bigiq_application_fastl4_udp.py
Python
gpl-3.0
21,905
0.00137
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameter
s from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.ipaddress import is_valid_ip from library.module_utils.network.f5.icontrol import bigiq_version except ImportError: from ansible.module_utils.network.f5.bigiq import F5RestClient from ansible.m...
jesseops/i3-lemonbar
i3_lemonbar.py
Python
mit
370
0.002703
#!/usr/bin/env python3 import os from i3
_lemonbar_conf import * cwd = os.path.dirname(os.path.abspath(__file__)) lemon = "lemonbar -p -f '%s' -f '%s' -g '%s' -B '%s' -F '%s'" % (font, iconfont, geometry, color_back, color_fore) feed = "python3 -c 'import i3_lemonbar_feeder; i3_lemonbar_feeder.run()'" check_output('cd %s; %s | %s' % (cwd, feed, lemon), she...
passren/Roxd
member/models.py
Python
gpl-2.0
727
0.005502
from __future__ import unicode_literals from django.db import transaction from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, unique=True, verbose_name=('user')) phone = models.CharField(max_leng...
), ('QQ', 'QQ'), ) source = models.CharField(max_length=2, choices=USER_SOURCE, default='LO') created_date = models.DateTimeField(auto_now_add=True) last_upda
ted_date = models.DateTimeField(auto_now=True) @transaction.atomic def createUser(self): self.user.save() self.save()
Krozark/django-slider
slider/utils.py
Python
bsd-2-clause
3,032
0.005937
import os, unicodedata from django.utils.translation import ugettext_lazy as _ from django.core.files.storage import FileSystemStorage from django.db.models.fields.files import FileField from django.core.files.storage import default_storage from django.conf import settings from django.utils.safestring import mark_safe...
from easy_thumbnails.files import get_thumbnailer media = getattr(settings, 'THUMBNAIL_MEDIA_URL', settings.MEDIA_URL) attrs = [] try: src = "%s%s" % (media, get_thumbnailer(image).get_thumbnail(options)) except: src = "" if alt is not None: attrs.appe...
if self.thumbnail_alt_field_name: kwargs['alt'] = getattr(obj, self.thumbnail_alt_field_name) return self._thumb(getattr(obj, self.thumbnail_image_field_name), **kwargs) thumbnail.allow_tags = True thumbnail.short_description = _('Thumbnail') def file_cleanup(sender, **kwargs): "...
nim65s/MarkDownBlog
dmdb/sitemaps.py
Python
gpl-3.0
320
0
from django.contrib.sitemaps import Sitemap from .models import Bl
ogEntry class BlogEntrySitemap(Sitemap): changefreq = "yearly" priority = 0.6 protocol = 'https' def items(self): return BlogEntry.on_site.filter(is_visible=True) def lastmod(self, item): return item.modification
h4wkmoon/shinken
shinken/objects/contact.py
Python
agpl-3.0
13,143
0.004337
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2014: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redis...
ere my_type = 'contact' properties = Item.properties.copy() properties.update({ 'contact_name': StringProp(fill_brok=['full_status']), 'alias': StringProp(default='none', fill_brok=['full_status']), 'contactgroups': StringProp(default='', fill_brok=['full_status'])...
default='1', fill_brok=['full_status']), 'service_notifications_enabled': BoolProp(default='1', fill_brok=['full_status']), 'host_notification_period': StringProp(fill_brok=['full_status']), 'service_notification_period': StringProp(fill_brok=['full_status']), 'host_notification_options'...
huggingface/transformers
utils/test_module/custom_modeling.py
Python
apache-2.0
772
0
import torch from transformers import PreTrainedModel from .custom_configuration import CustomConfig, NoSuperInitConfig class CustomModel(PreTrainedModel): config_class = CustomConfig def __init__(self, config): super().__init__(config) self.linear = torch.nn.Linear(config.hidden_size, conf...
nfig.attribute, config.attribute) def forward(self, x): return self.linear(x) def
_init_weights(self, module): pass
knoppo/pi3bar
pi3bar/tests/plugins/test_uptime.py
Python
mit
1,771
0
import unittest try: from unittest import mock except ImportError: import mock from pi3bar.plugins.uptime import get_uptime_seconds, uptime_format, Uptime class GetUptimeSecondsTestCase(unittest.TestCase): def test(self): m = mock.mock_open(read_data='5') m.return_value.readline.return_val...
tEqual(5, seconds) class UptimeFormatTestCase(unittest.TestCase): def test_seconds(self): s = uptime_format(5) self.assertEqual('0:00:00:05', s) def test_minutes(self):
s = uptime_format(3540) self.assertEqual('0:00:59:00', s) def test_hours(self): s = uptime_format(49020) self.assertEqual('0:13:37:00', s) def test_days(self): s = uptime_format(135420) self.assertEqual('1:13:37:00', s) def test_format_days_applied_to_hours(self): ...
mattoufoutu/ToolBoxAssistant
ToolBoxAssistant/__init__.py
Python
gpl-3.0
5,458
0.001649
# -*- coding: utf-8 -*- import os import re try: import simplejson as json except ImportError: import json from ToolBoxAssistant.app import AppFactory from ToolBoxAssistant.helpers import get_svn_url, readfile, find_versionned_folders, yes_no, Color from ToolBoxAssistant.log import logger VERSION = '0.1' cl...
folder, Color.GREEN+app_name+Color.END, vcs_type )) cfg_file, regex, handler = self.vcs_repo_finders[vcs_type] cfg_path = os.path.join(app_folder, cfg_file) app_specs = { 'type': vcs_type, 'url': handler(r...
= app_specs if new_apps_found: outfile = args.merge or args.file if os.path.exists(outfile): logger.warning('file already exists: %s' % Color.GREEN+outfile+Color.END) if not yes_no('Overwrite ?'): logger.error('operation aborted by use...
fizz-ml/pytorch-aux-reward-rl
replay_buffer.py
Python
mit
4,985
0.004814
import numpy as np import random class ReplayBuffer: """ Buffer for storing values over timesteps. """ def __init__(self): """ Initializes the buffer. """ pass def batch_sample(self, batch_size): """ Randomly sample a batch of values from the buffer. """ ...
r_t, s_t1, done def _put(self, s_t, a_t, reward, done): self.actions[self.current_index] = a_t self.states[self.current_index] = s_t self.rewards[self.current_index] = reward
self.dones[self.current_index] = done self._icrement_index() def put_act(self, s_t, a_t): """ Puts the current state and the action taking into Experience Replay. Args: s_t: Current state. a_t: Action taking at this state. Raises: ...
Fale/ansible
lib/ansible/module_utils/urls.py
Python
gpl-3.0
77,490
0.00231
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
util except ImportError: # python 2.4 (likely rhel5 which doesn't have tls1.1 support in its openssl) pass else: libssl_name = ctypes.util.find_library('ssl') libssl = ctypes.CDLL(libssl_name) for method in ('TLSv1_1_method', 'TLSv1_2_method'): try: ...
negotiate and hope # the server has disabled sslv2 and 3. best we can do. PROTOCOL = ssl.PROTOCOL_SSLv23 break except AttributeError: pass del libssl # The following makes it easier for us to script updates of the bundled backports.s...
Scriptopathe/simso-exp
simsoexp/migrations/0006_auto_20150721_1432.py
Python
bsd-2-clause
2,084
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simsoexp', '0005_schedulingpolicy_class_name'), ] operations = [ migrations.RemoveField( model_name='results', ...
t=False, ), migrations.AddField( model_name='results', name='norm_laxity',
field=models.IntegerField(default=0), preserve_default=False, ), migrations.AddField( model_name='results', name='on_schedule', field=models.IntegerField(default=0), preserve_default=False, ), migrations.AddField( ...
tbabej/astropy
astropy/table/column.py
Python
bsd-3-clause
41,990
0.001143
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from ..extern import six from ..extern.six.moves import zip import warnings import weakref from copy import deepcopy import numpy as np from num...
n a string column is assigned a value that gets truncated because the base (numpy) string length is too short. This does not inherit from AstropyWarning because w
e want to use stacklevel=2 to show the user where the issue occurred in their code. """ pass def _auto_names(n_cols): from . import conf return [str(conf.auto_colname).format(i) for i in range(n_cols)] # list of one and two-dimensional comparison functions, which sometimes return # a Column clas...
daniellawrence/pyspeccheck
speccheck/port.py
Python
mit
2,928
0
#!/usr/bin/env python from .util import Spec class Port(Spec): STATES = [ "listening", "closed", "open", "bound_to", "tcp", "tcp6", "udp" ] def __init__(self, portnumber): self.portnumber = portnumber self.get_state() self.state = { 'state': '...
portnumber, self.state['state'] ) def sb_closed(self, *args): if self._make_sure(self.state['state'], "closed"): return True, "Port %s is closed" % self.portnumber return False, "Port %s is current %s not closed" % ( self.portnumber, self.state['state'] ...
if self._make_sure(self.state['proto'], "tcp"): return True return "Port %s is using protocol %s not TCP" % ( self.portnumber, self.state['proto'] ) def sb_udp(self, *args): if self._make_sure(self.state['proto'], "udp"): return True retu...
cosven/FeelUOwn
feeluown/config.py
Python
gpl-3.0
2,065
0.000504
import logging import warnings from collections import namedtuple logger = logging.getLogger(__name__) Field = namedtu
ple('Field', ('name', 'type_', 'default', 'desc', 'warn')) class Config: """配置模块 用户可以在 rc 文件中配置各个选项的值 """ def __init__(self): object.__setattr__(self, '_fields', {}) def __getattr__(self, name): # tips: 这里不能用 getattr 来获取值, 否则会死循环 if name == '_fields': return ...
buteError: return self._fields[name].default return object.__getattribute__(self, name) def __setattr__(self, name, value): if name in self._fields: field = self._fields[name] if field.warn is not None: warnings.warn('Config field({}): {}'.for...
antoinecarme/sklearn2sql_heroku
tests/regression/RandomReg_500/ws_RandomReg_500_XGBRegressor_db2_code_gen.py
Python
bsd-3-clause
130
0.015385
from sk
learn2sql_heroku.tests.regression import generic as reg_gen reg_gen.test_model("XGBRegressor" , "RandomReg_500" , "db
2")
young-geng/leet_code
problems/20_valid-parentheses/main.py
Python
mit
920
0.003261
# https://leetcode.com/problems/valid-parentheses/ class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if not s: return True stack = [] for i in xrange(len(s)): # if its opening it, its getting deeper so add...
stack.append(s[i]) # if not it must be a closing parenth # in which case check if stack is empty if not pop and c
heck # whether popped elem is closed with the current item else: if len(stack) == 0: return False last = stack.pop() if s[i] == ")" and last != "(": return False if s[i] == "]" and last != "[": return False ...
sdispater/cleo
tests/io/inputs/test_option.py
Python
mit
2,858
0
import pytest from cleo.exceptions import LogicException from cleo.exceptions import ValueException from cleo.io.inputs.option import Option def test_create(): opt = Option("option") assert "option" == opt.name assert opt.shortcut is None assert opt.is_flag() assert not opt.accepts_value() a...
def test_optional_value_with_default(): opt = Option("option", flag=False, requires_value=False, default="Defaul
t") assert not opt.is_flag() assert opt.accepts_value() assert not opt.requires_value() assert not opt.is_list() assert opt.default == "Default" def test_required_value(): opt = Option("option", flag=False, requires_value=True) assert not opt.is_flag() assert opt.accepts_value() ...
mattseymour/django
django/contrib/gis/db/backends/spatialite/base.py
Python
bsd-3-clause
3,105
0.001932
from ctypes.util import find_library from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.base import ( DatabaseWrapper as SQLiteDatabaseWrapper, SQLiteCursorWrapper, ) from .client import SpatiaLiteClient from .features import DatabaseFeatures f...
ATIALITE_LIBRARY_PATH', find_library('spatialite')) if not self.spatialite_lib: raise ImproperlyConfigured('Unable to locate the SpatiaLite library. ' 'Make sure it is in your library path, or set ' ...
' ) super(DatabaseWrapper, self).__init__(*args, **kwargs) def get_new_connection(self, conn_params): conn = super(DatabaseWrapper, self).get_new_connection(conn_params) # Enabling extension loading on the SQLite connection. try: co...
python-xlib/python-xlib
Xlib/__init__.py
Python
lgpl-2.1
1,184
0
# Xlib.__init__ -- glue for Xlib package # # Copyright (C) 2000-2002 Peter Liljenberg <petli@ctrl-c.liu.se> # # This library 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 2.1 # of th...
hope that it
will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to ...
grimoirelab/arthur
arthur/worker.py
Python
gpl-3.0
1,980
0
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Bitergia # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This ...
nse 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. # # Authors: # Santiago Dueñas <sduenas@bitergia.com> # Alvaro del Castillo San F...
class ArthurWorker(rq.Worker): """Worker class for Arthur""" def __init__(self, queues, **kwargs): super().__init__(queues, **kwargs) self.__pubsub_channel = CH_PUBSUB @property def pubsub_channel(self): return self.__pubsub_channel @pubsub_channel.setter def pubsub_c...
shafiquejamal/socialassistanceregistry
nr/nr/formulas.py
Python
bsd-3-clause
137
0.021898
from django.conf import settings def mask_toggle(number_to_mask_or_unmask
): return int(nu
mber_to_mask_or_unmask) ^ settings.MASKING_KEY
mhbu50/erpnext
erpnext/hr/doctype/vehicle_log/test_vehicle_log.py
Python
gpl-3.0
3,526
0.025241
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt import unittest import frappe from frappe.utils import cstr, flt, nowdate, random_string from erpnext.hr.doctype.employee.test_employee import make_employee from erpnext.hr.doctype.vehicle_log.vehicle_log import make_expense_claim...
one if not self.employee_id: self.employee_id = make_employee("testdriver@example.com", company="_Test Company") self.license_plate = get_vehicle(self.employee_id) def tearDown(self): frappe.delete_doc("Vehicle", self.license_plate, force=1) frappe.delete_doc("Employee", self.employee_id
, force=1) def test_make_vehicle_log_and_syncing_of_odometer_value(self): vehicle_log = make_vehicle_log(self.license_plate, self.employee_id) #checking value of vehicle odometer value on submit. vehicle = frappe.get_doc("Vehicle", self.license_plate) self.assertEqual(vehicle.last_odometer, vehicle_log.odome...