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 |
|---|---|---|---|---|---|---|---|---|
ibadami/pytorch-semseg | ptsemseg/models/pspnet.py | Python | mit | 3,018 | 0.004639 | import torch.nn as nn
from utils import *
class pspnet(nn.Module):
def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, is_batchnorm=True):
super(pspnet, self).__init__()
self.is_deconv = is_deconv
self.in_channels = in_channels
self.is_batchnorm = is_b... | # filters = [x / self.feature_scale for x in filters]
self.inplanes = filters[0]
# Encoder
self.convbnrelu1 = conv2DBatchNormRelu(in_channels=3, k_size=7, n_filters= | 64,
padding=3, stride=2, bias=False)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
block = residualBlock
self.encoder1 = self._make_layer(block, filters[0], self.layers[0])
self.encoder2 = self._make_layer(block, filters[1... |
TheWylieStCoyote/gnuradio | gr-fec/python/fec/extended_encoder.py | Python | gpl-3.0 | 2,704 | 0.003328 | #!/usr/bin/env python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from __future__ import absolute_impor | t
from __future__ import unicode_literals
from gnuradio import gr, | blocks
from . import fec_swig as fec
from .threaded_encoder import threaded_encoder
from .capillary_threaded_encoder import capillary_threaded_encoder
from .bitflip import read_bitlist
class extended_encoder(gr.hier_block2):
def __init__(self, encoder_obj_list, threading, puncpat=None):
gr.hier_block2.__... |
CVBDL/ccollab2eeplatform-python | ccollab2eeplatform/utils.py | Python | mit | 2,434 | 0.000822 | """Custom utils."""
from datetime import date
from itertools import groupby as groupby_
def to_isoformat(date_str):
"""Convert an ISO 8601 like date string to standard ISO 8601 format.
Args:
date_str (str): An ISO 8601 like date string.
Returns:
str: A standard ISO 8601 date string.
... | date
reverse = True
else:
reverse = False
result = []
while start_date <= stop_date:
result.append(start_date.isoformat()[0:7])
year = start_date.year
month = start_date | .month
if month == 12:
year += 1
month = 1
else:
month += 1
start_date = date(year, month, 1)
return reverse and sorted(result, reverse=reverse) or result
def groupby(iterable, key=None, reverse=False):
"""Wrapper of itertools.groupby function.
... |
flodolo/bedrock | tests/pages/firefox/developer.py | Python | mpl-2.0 | 870 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from selenium.webdriver.common.by import By
from pages.base import BasePage
from pages.regions.download_button import ... | refox/developer/"
_primary_download_locator = (By.ID, "intro-download")
_secondary_download_locator = (By.ID, "footer-download")
@property
def primary_download_button(self):
el = self.find_element(*self._primary_download_locator)
return DownloadButton(self, root=el)
@property
... | ondary_download_locator)
return DownloadButton(self, root=el)
|
aplanas/rally | tests/unit/plugins/openstack/scenarios/ceilometer/test_utils.py | Python | apache-2.0 | 13,257 | 0 | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | lf._test_atomic_action_timer(self.scenario.atomic_actions(),
"ceilometer.set_alarm_state")
def test__list_events(self):
self.assertEqual(
self.scenario._list_events(),
self.admin_clie | nts("ceilometer").events.list.return_value
)
self._test_atomic_action_timer(self.scenario.atomic_actions(),
"ceilometer.list_events")
def test__get_events(self):
self.assertEqual(
self.scenario._get_event(event_id="fake_id"),
se... |
SteffenDE/monitornjus-classic | admin/setn.py | Python | mit | 6,805 | 0.031599 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2015 Steffen Deusch
# Licensed under the MIT license
# Beilage zu MonitorNjus, 14.09.2015 (Version 0.9.3)
import os
workingdir = os.path.dirname(os.path.realpath(__file__))
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import imp
modulesdir = wor... | RL=../admin/index.py\">"
cnum = form.getfirst("createnum", None)
dnum = form.getfirst("delnum" | , None)
if cnum is not None and cnum.isdigit():
num = int(cnum)
if num == int(common.getrows())+1:
common.createrow(num)
else:
raise Warning("Neues Displayset - falsche Zahl: "+str(num))
elif dnum is not None and dnum.isdigit():
num = int(dnum)
if num <= int(common.getrows()):
common.delr... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/shapely/tests/test_collection.py | Python | agpl-3.0 | 870 | 0.006897 | import unittest
from shapely.geometry import LineString
from shapely.geometry.collection import GeometryCollection
class CollectionTestCase(unittest.TestCase):
def test_array_interface(self):
m = GeometryCollection()
self.failUnlessEqual(len(m), 0)
self.failUnlessEqual(m.geoms, [])
def... | , (2,1), (2,2)])
collection = a.intersection(b)
child = collection.geoms[0]
# delete parent of child
del collection
# access geometry, this should not seg fault as 1.2.15 did
child.to_wkt()
def test_suite() | :
return unittest.TestLoader().loadTestsFromTestCase(CollectionTestCase)
|
elbeanio/contented | test/app.py | Python | mit | 312 | 0.003205 | import unittest
from contented.app impo | rt Application
class AppTests(unittest.TestCase):
def test_load_app(self):
app = Application({})
self.assertTrue(hasattr(app, "sett | ings"))
self.assertTrue(hasattr(app, "content_map"))
self.assertTrue(hasattr(app, "request_processors")) |
hiphoox/experior | timetracking/models.py | Python | bsd-3-clause | 14,572 | 0.023813 | from django.db import models
from django_extensions.db.models import TimeStampedModel
from django.contrib.auth.models import User, UserManager
import datetime
####################################################################################################
####################################### Catalogs #######... | f __unicode__(self):
return u"%s, %s" % (self.name , self.description)
### | #################################################################################################
class Sector(TimeStampedModel):
"""Business sectors"""
name = models.CharField(max_length=80)
description = models.CharField(max_length=100)
enabled = models.BooleanField(default=True)
def __unicode__... |
josephsl/stationPlaylist | addon/appModules/tracktool.py | Python | gpl-2.0 | 3,301 | 0.019388 | # StationPlaylist Track Tool
# An app module for NVDA
# Copyright 2014-2021 Joseph Lee, released under gPL.
# Functionality is based on JFW scripts for SPL Track Tool by Brian Hartgen.
# Track Tool allows a broadcaster to manage track intros, cues and so forth.
# Each track is a list item with descriptions such as tit... | ion", "Cue", "Overlap", "Intro", "Outro", "Segue", "Hook Start",
"Hook Len", "Year", "Album", "CD Code", "URL 1", "URL 2", "Genre", "Mood", "Energy",
"Tempo", "BPM", "Gender", "Rating", "Filename", "Client", "Other", "Intro Link", "Outro Link",
"ReplayGain", "Reco | rd Label", "ISRC", "Language", "Restrictions", "Exclude from Requests"
)
class TrackToolItem(SPLTrackItem):
"""An entry in Track Tool, used to implement some exciting features.
"""
def reportFocus(self):
# Play a beep when intro exists.
if self._getColumnContentRaw(self.indexOf("Intro")) is not None:
to... |
sciyoshi/yamlmod | yamlmod.py | Python | mit | 1,179 | 0.028838 | import os
import imp
import sys
import yaml
class YamlImportHook:
def find_module(self, fullname, path=None):
name = fullname.split('.')[-1]
for folder in path or sys.path:
if os.path.exists(os.path.join(folder, '%s.yml' % name)):
return self
return None
def load_module(self, fullname):
if fullname... | h = sys.path
for folder in path:
if os.path.exists(os.path.join(folder, '%s.yml' % name)):
mod.__file__ = os.path.join(folder, '%s.yml' % name)
mod.__package__ = pkg
mod.__loader__ = self
|
mod.__dict__.update(yaml.load(open(mod.__file__)) or {})
return mod
# somehow not found, delete from sys.modules
del sys.modules[fullname]
# support reload()ing this module
try:
hook
except NameError:
pass
else:
try:
sys.meta_path.remove(hook)
except ValueError:
# not found, skip removing
pass... |
patrickglass/Resty | resty/__init__.py | Python | apache-2.0 | 667 | 0 | """
Module Resty
Date: November 25, 2013
Company: SwissTech Consulting.
Author: Patrick Glass <patrickglass@gmail.com>
Copyright: Copyright 2013 SwissTech Consulting.
This class implements a simple rest api framework for interfacing with the
Server via its REST API.
"""
__title__ = 'Resty'
__version__ = '0.1'
__autho... | s'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Patrick Glass'
from resty.api import RestyAPI
from resty.exceptions import (
RestApiException,
RestApiUrlException,
RestApiAuthError,
RestApiBadRequest,
RestApiServersDown
| )
from resty.auth import RestAuthToken
from resty.request import request
|
pypa/twine | tests/test_main.py | Python | apache-2.0 | 2,736 | 0.002193 | # Licensed under the Apa | che 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, software
# distributed under the License is distributed on... | RANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import pretend
import requests
from twine import __main__ as dunder_main
from twine.commands import upload
def test_exception_handling(monk... |
waveform80/gpio-zero | docs/examples/led_bargraph_1.py | Python | bsd-3-clause | 400 | 0 | from gpiozero import LEDBarGraph
from time import sleep
from __future__ import division # required for python 2
graph = LEDBarGraph(5, | 6, 13, 19, 26, 20)
graph.value = 1 # (1, 1, 1, 1, 1, 1)
sleep(1)
graph.value = 1/2 # (1, 1, 1, 0, 0, 0)
sleep(1)
graph.value = -1/2 # (0, 0, 0, 1, | 1, 1)
sleep(1)
graph.value = 1/4 # (1, 0, 0, 0, 0, 0)
sleep(1)
graph.value = -1 # (1, 1, 1, 1, 1, 1)
sleep(1)
|
cgalleguillosm/accasim | extra/examples/workload_generator-example.py | Python | mit | 1,782 | 0.018519 | from accasim.experimentation.workload_generator import workload_generator
if __name__ == '__main__':
#===========================================================================
# Workload filepath
#===========================================================================
workload = 'worklo... | =================================
generator = workload_generator(workload, sys_config, performance, request_limits)
#===========================================================================
# Generate n jobs and save them to the nw filepath
#=======================================================... | ====
n = 100
nw_filepath = 'new_workload.swf'
jobs = generator.generate_jobs(n, nw_filepath)
|
napsternxg/haiku_rnn | haiku_gen.py | Python | gpl-2.0 | 3,766 | 0.004514 | from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.preprocessing.sequence import pad_sequences
import numpy as np
import random, sys
'''
Example script to generate haiku Text.
It is recommended to run this script on G... | tropy', optimizer='rmsprop')
# helper function to sample an index from a probability array
def sample(a, temperature=1.0):
a = np.log(a)/temperature
a = np.exp(a)/np.sum(np.exp(a))
return np.argmax(np.rand | om.multinomial(1,a,1))
# train the model, output generated text after each iteration
def generate_from_model(model, begin_sent=None, diversity_l=[0.2, 0.5, 1.0, 1.2]):
if begin_sent is None:
start_index = random.randint(0, len(text) - maxlen - 1)
for diversity in diversity_l:
print
pr... |
jumpserver/jumpserver | apps/authentication/views/feishu.py | Python | gpl-3.0 | 7,469 | 0.000538 | from django.http.response import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from urllib.parse import urlencode
from django.views import View
from django.conf import settings
from django.http.request import HttpRequest
from django.db.utils import IntegrityError
from rest_framework.permi... | a)
@staticmethod
def get_failed_response(redirect_url, title, msg):
message_data = {
| 'title': title,
'error': msg,
'interval': 5,
'redirect_url': redirect_url,
}
return FlashMessageUtil.gen_and_redirect_to(message_data)
def get_already_bound_response(self, redirect_url):
msg = _('FeiShu is already bound')
response = self.get_fai... |
kaaveland/anybot | im/__init__.py | Python | gpl-2.0 | 449 | 0.002227 | """
This package supplies tools for working with automated services
connected to a server. It was written with | IRC in mind, so it's not
very generic, in that it pretty much assumes a single client connected
to a central server, and it's not easy for a client to add further connections
at runtime (But possible, though you might have to avoid selector.Reactor.loop.
"""
__all__ = [
"irc",
"selector",
| "connection",
"irc2num"
]
|
sunlightlabs/billy | billy/scrape/utils.py | Python | bsd-3-clause | 5,127 | 0.000585 | import re
impo | rt itertools
import subprocess
import collections
def convert_pdf(filename, type='xml'):
commands = {'text': ['pdftotext', '-layout', filename, '-'],
'text-nolayout': ['pdftotext', filename, '-'],
'xml': ['pdftohtml', '-xml', '-stdout', filename],
'html': ['pdftohtm... | cess.Popen(commands[type], stdout=subprocess.PIPE,
close_fds=True).stdout
except OSError as e:
raise EnvironmentError("error running %s, missing executable? [%s]" %
' '.join(commands[type]), e)
data = pipe.read()
pipe.close()
return ... |
sara-02/fabric8-analytics-stack-analysis | util/error/error_codes.py | Python | gpl-3.0 | 322 | 0.003106 | """Error codes used during the analysis."""
ERR_INPUT_INVALID = {
"name": "ERR_INPUT_INVALID ",
"msg": "Input is invalid."
}
ERR_MODEL_NOT_AVAILABLE = {
"name": "ERR_MODEL_NOT_AVAILABLE",
"ms | g": "Model does not seem to be available! It should be either trained or loaded "
"before scoring."
}
| |
tlake/data-structures-mk2 | tests/test_insertion_sort.py | Python | mit | 1,008 | 0.003968 | # -*- coding | utf-8 -*-
from __future__ import unicode_literals
import pytest
from structures.insertion_sort import insertion_sort
@pytest.fixture
def sorted_list():
return [i for i in xrange(10)]
@pytest.fixture
def reverse_list():
r | eturn [i for i in xrange(9, -1, -1)]
@pytest.fixture
def average_list():
return [5, 9, 2, 4, 1, 6, 8, 7, 0, 3]
def test_sorted(sorted_list):
insertion_sort(sorted_list)
assert sorted_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_worst(reverse_list):
insertion_sort(reverse_list)
assert revers... |
dmartinezgarcia/Python-Programming | Chapter 8 - Software Objects/exercise_1.py | Python | gpl-2.0 | 2,396 | 0.00793 | # Exercise 1
#
# Improve the Critter caretaker program by allowing the user to specify how much food he or she feeds the critter and
# how long he or she plays with the critter. Have these values affect how quickly the critter's hunger and boredom
# levels drop.
#
class Critter(object):
"""A virtual pet"""
def... | 0, boredom | = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self, hunger_val = 1, boredom_val = 1):
self.hunger += hunger_val
self.boredom += boredom_val
@property
def mood(self):
unhappiness = self.hunger + self.boredom
if un... |
scanny/python-pptx | pptx/chart/plot.py | Python | mit | 13,213 | 0.000076 | # encoding: utf-8
"""
Plot-related objects. A plot is known as a chart group in the MS API. A chart
can have more than one plot overlayed on each other, such as a line plot
layered over a bar plot.
"""
from __future__ import absolute_import, print_function, unicode_literals
from .category import Categories
from .dat... | plot has overlap of 100 by default.
"""
overlap = self._element.overlap
if overlap is None:
| return 0
return overlap.val
@overlap.setter
def overlap(self, value):
"""
Set the value of the ``<c:overlap>`` child element to *int_value*,
or remove the overlap element if *int_value* is 0.
"""
if value == 0:
self._element._remove_overlap()
... |
pklfz/fold | tensorflow_fold/util/proto_test.py | Python | apache-2.0 | 5,810 | 0.001721 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache. | org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitati... | low_fold.util import test3_pb2
from tensorflow_fold.util import test_pb2
from google.protobuf import text_format
# Make sure SerializedMessageToTree can see our proto files.
proto_tools.map_proto_source_tree_path("", os.getcwd())
# Note: Tests run in the bazel root directory, which we will use as the root for
# our ... |
2013Commons/HUE-SHARK | apps/shell/setup.py | Python | apache-2.0 | 1,754 | 0.017104 | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | ppend(os.path.join(path, fname).replace(strip, ""))
return ret
os.chdir(os.path.dirname(os.path.abspath(__file__)))
setup(
name = "shell",
version = VERSION,
url = 'http://github.com/cloudera/hue',
description = 'Shell interface in Hue',
author = 'Hue',
packages = find_packages('src'),
package_ | dir = {'': 'src'},
install_requires = ['setuptools', 'desktop'],
entry_points = { 'desktop.sdk.application': 'shell=shell' },
zip_safe = False,
package_data = {
# Include static resources. Package_data doesn't
# deal well with directory globs, so we enumerate
# the files manually.
'shell': expa... |
danxhuber/k2epic | checkk2fov/__init__.py | Python | mit | 135 | 0.014815 | #!/usr/bin/env python
| # -*- coding: utf-8 -*-
from __future__ import (division,absolute_import)
from | .K2onSilicon import K2onSilicon
|
shawncaojob/LC | QUESTIONS/96_unique_binary_search_trees.py | Python | gpl-3.0 | 2,402 | 0.005412 | # 96. Unique Binary Search Trees My Submissions QuestionEditorial Solution
# Total Accepted: 84526 Total Submissions: 224165 Difficulty: Medium
# Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
#
# For example,
# Given n = 3, there are a total of 5 unique BST's.
#
# 1 ... | while i < n:
tmp += res[i] * res[n-1-i]
i += 1
res[n] = tmp
return res[n]
import unittest
class TestSolution(unittest.TestCase):
def test_0(self):
self.assertEqual(Solution().numTrees(3), 5)
def test_1(self):
self.assertEqual(Soluti... | numTrees(4), 14)
if __name__ == "__main__":
unittest.main()
|
hsnlab/nffg | nffg_elements.py | Python | apache-2.0 | 90,210 | 0.008081 | # Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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... | r(self, key):
return setattr(self, key, value)
else:
raise KeyError(
"%s object has no key: %s" % (self.__class__.__name__, key))
def __contains__ (self, item):
"""
Return true if the given ``item`` is exist.
:param item: searched attribute name
:type item: str or int
:re... | ool
"""
return hasattr(self, item)
def get (self, item, default=None):
"""
Return with the attribute given by ``item``, else ``default``.
:param item: searched attribute name
:type item: str
:param default: default value
:type default: object
:return: found attribute or default
... |
uranusjr/django | django/db/models/sql/query.py | Python | bsd-3-clause | 96,523 | 0.000912 | """
Create SQL statements for QuerySets.
The code in here encapsulates all of the SQL construction so that QuerySets
themselves do not have to (and could be backed by things other than SQL
databases). The abstraction barrier only works one way: this module has to know
all about the internals of models in order to get ... | " % params_type)
self.cursor = connection.cursor()
self.cursor.execute(self.sql, params)
class Query:
"""A single SQL query."" | "
alias_prefix = 'T'
subq_aliases = frozenset([alias_prefix])
compiler = 'SQLCompiler'
def __init__(self, model, where=WhereNode):
self.model = model
self.alias_refcount = {}
# alias_map is the most important data structure regarding joins.
# It's used for recording wh... |
igordejanovic/textX | setup.py | Python | mit | 1,005 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup
this_dir = os.path.abspath(os.path.dirname(__file__))
VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py")
VERSION = None
for line in open(VERSIONFILE, "r").readlines():
if line.startswith('__version__'):
... | if sys.argv[-1] == 'publishtest':
os.system("twine upload -r test dist/*")
else:
os.system("twine upload dist/*")
print("You probably want to also tag the version now:")
print(" git tag -a {0} -m 'version {0}'".format(VERSION))
print(" git push --tags")
| sys.exit()
setup(version=VERSION)
|
NeCTAR-RC/horizon | openstack_dashboard/dashboards/admin/rbac_policies/views.py | Python | apache-2.0 | 5,711 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | if p.object_type == "network":
p.object_name = network_dict.get(p.object_id, p.object_id)
elif p. | object_type == "qos_policy":
p.object_name = qos_policy_dict.get(p.object_id,
p.object_id)
return rbac_policies
class CreateView(forms.ModalFormView):
template_name = 'admin/rbac_policies/create.html'
form_id = "create_rbac_po... |
vorwerkc/pymatgen | pymatgen/analysis/structure_prediction/dopant_predictor.py | Python | mit | 7,420 | 0.001887 | """
Predicting potential dopants
"""
import warnings
import numpy as np
from pymatgen.analysis.structure_prediction.substitution_probability import (
SubstitutionPredictor,
)
from pymatgen.core.periodic_table import Element, Species
def get_dopants_from_substitution_probabilities(structure, num_dopants=5, thre... | ies": The substituted species.
"""
els_have_oxi_states = [hasattr(s, "oxi_state") for s in structure.species]
if not all(els_have_oxi_states):
raise ValueError("All sites in structure must have oxidation states to predict dopants.")
sp = SubstitutionPredictor(t | hreshold=threshold)
subs = [sp.list_prediction([s]) for s in set(structure.species)]
subs = [
{
"probability": pred["probability"],
"dopant_species": list(pred["substitutions"].keys())[0],
"original_species": list(pred["substitutions"].values())[0],
}
... |
benoitc/pywebmachine | tests/decisions/b08_test.py | Python | mit | 664 | 0.00753 | import t
class b08(t.Test):
class TestResource(t.Resource):
def is_authorized(self, req, rsp):
if req. | headers.get('authorization') == 'yay':
return True
return 'oauth'
def to_html(self, req, rsp):
return "nom nom"
def test_ok(self):
self.req.headers['authorization'] = 'yay'
self.go()
t.eq(self.rsp.status, '200 OK')
t.eq(self.rsp.b... | uth')
t.eq(self.rsp.body, '') |
mozilla/firefox-flicks | flicks/users/views.py | Python | bsd-3-clause | 2,642 | 0.000379 | from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.utils.translation import get_language
import django_browserid.views
import waffle
from flicks.base import regions
from flicks.base.util import redirect
from flicks.users.forms import UserProfileForm
from flicks.u... | in_failure(self, *args, **kwargs):
"""
Extend login failure so that if login fails, the user's attempts to
vote for a video are cancelled.
"""
try:
del self.request.session['vote_video']
except KeyError:
| pass
return super(Verify, self).login_failure(*args, **kwargs)
|
devicehive/devicehive-python | devicehive/notification.py | Python | apache-2.0 | 1,546 | 0 | # Copyright (C) 2018 DataArt
#
# 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, ... | ._timestamp = notification[self.TIMESTAMP_KEY]
@property
def device_id(self):
return self._device_id
@property
def id(self):
return self._id
@property
def notification(self):
re | turn self._notification
@property
def parameters(self):
return self._parameters
@property
def timestamp(self):
return self._timestamp
|
rfoxfa/python-utils | utils/__init__.py | Python | gpl-2.0 | 199 | 0.020101 | #!/usr/bin/env python
"""
This i | s the main module driver for Ross Flieger-Allison's
python-utils module.
"""
__author__ = "Ross Flieger-All | ison"
__date__ = "23-10-2015"
__version__ = "1.0.0"
|
rwl/muntjac | muntjac/demo/sampler/features/selects/OptionGroupsExample.py | Python | apache-2.0 | 2,051 | 0.000975 |
from muntjac.api import VerticalLayout, OptionGroup, Label
from muntjac.data.property import IValueChangeListener
class OptionGroupsExample(VerticalLayout, IValueChangeListener):
_cities = ['Berlin', 'Brussels', 'Helsinki', 'Madrid', 'Oslo',
'Paris', 'Stockholm']
def __init__(self):
sup... | v = event.getProperty().getValue()
if isinstance(v, set):
v = list(v)
self.getWindow().showNotification('Selected city: %s' % | v)
|
sjm-ec/cbt-python | Units/06-Loops/GoodExample3.py | Python | gpl-2.0 | 257 | 0.042802 | from __future__ import print_fun | ction
num = 17
test = 2
while test < num:
if num % test == 0 and num != test:
print(num,'equals',test, '*', num/test)
print(num,'is not a prime number')
break
test = test | + 1
else:
print(num,'is a prime number!')
|
stbd/stoolbox | tests/obj-to-sm-test/conversion-test.py | Python | mit | 3,598 | 0.000556 | import unittest
converter = __import__("obj-to-sm-conversion")
model = """
# Blender v2.71 (sub 0) OBJ File:
# www.blender.org
mtllib object.mtl
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.... | //11 20//11
f 16//5 14//5 18//5
f 15//3 19//3 17//3
f 13//10 17//10 18//10
f 22//5 24//5 28//5
f 15//3 21//3 23//3
f 19//11 23//11 24//11
f 16//6 22//6 21//6
f 26//12 28//12 27//12
f 23//3 21//3 25//3
f 23//13 27//13 28//13
f 22//14 26//14 25//14
f 32//5 36//5 35//5
f 3//15 31//15 30//15
f 1// | 16 29//16 32//16
f 2//17 30//17 29//17
f 34//10 35//10 36//10
f 31//11 35//11 34//11
f 29//6 33//6 36//6
f 29//3 30//3 34//3
f 3//1 4//1 31//1
f 5//2 8//2 6//2
f 2//3 1//3 6//3
f 6//4 7//4 11//4
f 3//5 7//5 4//5
f 5//6 1//6 8//6
f 11//2 12//2 15//2
f 12//7 7//7 10//7
f 9//8 2//8 11//8
f 3//9 2//9 10//9
f 22//5 16//5 24... |
rwl/PyCIM | CIM15/IEC61968/Common/Agreement.py | Python | mit | 2,456 | 0.003257 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | itialises a new 'Agreement' instance.
@param signDate: Date this agreement was c | onsummated among associated persons and/or organisations.
@param validityInterval: Date and time interval this agreement is valid (from going into effect to termination).
"""
#: Date this agreement was consummated among associated persons and/or organisations.
self.signDate = signDate
... |
maxwelld90/personal_web | django_project/personal_web/dmax_website/migrations/0010_auto_20160103_1917.py | Python | gpl-2.0 | 457 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-03 19:17
from __future__ import uni | code_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dmax_website', '0009_auto_20160103_1911'),
]
operations = [
migrations.RenameField(
model_name='projectitem',
| old_name='project_abbreviation',
new_name='abbreviation',
),
]
|
Organice/django-organice | tests/units/__init__.py | Python | apache-2.0 | 920 | 0.007609 | """
Unit te | sts and test utilities for django Organice.
NOTE: Having an __init__ file in test directories is bad practice according to
py.test recommendations:
http://pytest.org/latest/goodpractises.html#choosing-a-test-layout-import-rules
However, this makes relative imports work in test modules (e.g. helper fro | m ``utils.py``).
"""
# NOTE 1: This file makes the 'test' folder importable! (i.e. `import tests`) Not good.
# Though, the test folder is pruned by MANIFEST.in, hence it's not installed anywhere.
# TODO: Consider inlining the tests into the package, or find a solution without relative imports.
# NOTE 2: The import o... |
DrSLDR/mgmag-proj | gravitas/controller/symbolic.py | Python | mit | 7,657 | 0.007575 | """A symbolic AI that forms decisions by using a decision tree."""
import random
from .interface import IPlayerController
from model.card import Card
class SymbolicAI_PC(IPlayerController):
"""player controller that returns resolutes its choices using a decision tree.
It is called symbolic because it is n... | return orderedNormals[0]
# if there are no normal cards, use tractor or lowest repulsor
else:
if len(tractors) > 0:
# use a tractor (does not mather which one since they are similar)
return tractors[0]
# since ... | pulsors = sorted(repulsors, key = lambda x: -x.getValue() )
return orderedRepulsors[0]
# moving backward...
else: # if distance <= 0:
# so choose highest-value repulsor card
if len(repulsors) > 0:
orderedRepulsors = sorted(repulsors, key = lam... |
mhahn/stacker | stacker/actions/diff.py | Python | bsd-2-clause | 6,533 | 0 | import logging
from .. import exceptions
from ..plan import COMPLETE, Plan
from ..status import NotSubmittedStatus, NotUpdatedStatus
from . import build
import difflib
import json
logger = logging.getLogger(__name__)
def diff_dictionaries(old_dict, new_dict):
"""Diffs two single dimension dictionaries
Retu... | s):
plan.add(
stacks[stack_name],
run_func=self._diff_stack,
requires=dependencies.get(stack_name),
)
return plan
def run(self, *args, **kwargs):
plan = self._generate_plan()
debug_plan = self._generate_plan()
d... | n.execute()
"""Don't ever do anything for pre_run or post_run"""
def pre_run(self, *args, **kwargs):
pass
def post_run(self, *args, **kwargs):
pass
|
crobinso/pkgdb2 | pkgdb2/api/extras.py | Python | gpl-2.0 | 20,250 | 0.000198 | # -*- coding: utf-8 -*-
#
# Copyright © 2013-2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed... | g version: Set to a collection version to further filter results
for a single version
:kwarg eol: Set to True if you want to include end of life
distributions
:kwarg out_format: Specify if the output if text or json.
'''
packages = pkgdblib.notify(
session=SESSION,
eol=eo... | = {'packages': {},
'eol': eol,
'name': name,
'version': version,
'title': 'Fedora Package Database -- Notification List'}
for package in sorted(packages):
if out_format == 'json':
output['packages'][package] = packages[pack... |
davidmogar/quizzer-python | quizzer/deserializers/assessment_deserializer.py | Python | mit | 4,007 | 0.002496 | import json
from quizzer.domain.answer import Answer
from quizzer.domain.grade import Grade
from quizzer.domain.questions import *
__author__ = 'David Moreno García'
def deserialize_answers(json_string):
"""
Deserializes the JSON representation received as arguments to a map of student ids to Answer objects.... | if 'scores' in | data:
for grade in data['scores']:
if 'studentId' in grade and 'value' in grade:
grades[grade['studentId']] = Grade(grade['studentId'], grade['value'])
return grades
def deserialize_multichoice(hash):
"""
Deserialize a Multichoice question
:param hash:... |
karasinski/NACAFoil-OpenFOAM | plot.py | Python | gpl-3.0 | 1,969 | 0.004571 | #!/usr/bin/env python
"""
This script plots various quantities.
"""
from __future__ import division, print_function
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import argparse
ylabels = {"cl": r"$C_l$", "cd": r"$C_d$", "cl/cd": r"$C_l/C_d$", "k": "$k$",
"omega": r"$\omega$", "eps... | ebook", font_scale=1.5)
except ImportError:
print("Could not import seaborn for plot styling. Try")
| print("\n conda install seaborn\n\nor")
print("\n pip install seaborn\n")
parser = argparse.ArgumentParser(description="Plotting results")
parser.add_argument("quantity", nargs="?", default="cl/cd",
help="Which quantity to plot",
cho... |
richardjmarini/JsonSchema | manage.py | Python | gpl-2.0 | 254 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "json_schema.settings")
from django. | core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
qeedquan/misc_utilities | math/matrix-sqrt.py | Python | mit | 1,781 | 0.005053 | """
https://en.wikipedia.org/wiki/Square_root_of_a_matrix
B is the sqrt of a matrix A if B*B = A
"""
import numpy as np
from scipy.linalg import sqrtm
from scipy.stats import special_ortho_group
def denman_beaver(A, n=50):
Y = A
Z = np.eye(len(A))
for i in range(n):
Yn = 0.5*(Y + np.linalg.inv(... | X = 0.5*(X + np.dot(A, np.linalg.inv(X)))
return X
def gen_random_matrix(n):
return np.random.rand(n, n)
def gen_rotation_matrix(n):
return special_ortho_group.rvs(n)*np.random.randint(-100, 101)
def gen_symmetric_matrix(n):
A = np.random.randint(-10, 11, size=(n, n))
A = 0.5*(A + A.T)
... | range(iters):
try:
A = gen_matrix(i)
d = np.linalg.det(A)
Y, _ = denman_beaver(A)
X = babylonian(A)
Z = sqrtm(A)
print("{}x{} matrix (det {})".format(i, i, d))
print(A)
print("Denm... |
tedor/home-blog | blog/models.py | Python | bsd-3-clause | 1,381 | 0.005793 | from django.db import models
from django.db.models import permalink
from django.utils.translation import ugettext_lazy as _
from tagging.fields import TagField
from django.utils import timezone
class Post(models.Model):
STATUS_DRAFT = 1
STATUS_PUBLIC = 2
TEXT_CUT = "===cut==="
STATUS_CHOICES = (
... | ,
)
title = models.CharField(_('title'), max_length=255)
slug = models.SlugField(_('slug'), unique=True)
text = models.TextField(_('text'), help_text="<a href='http://daringfireball.net/projects/markdown/syntax'>Markdown</a>")
status = models.IntegerField(_('status'), choices=STATUS_C | HOICES, default=1)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=True)
tag = TagField()
def save(self):
if not self.created_at:
self.created_at = timezone.now()
super(Post, self).save()
... |
bitcraft/pyglet | pyglet/graphics/allocation.py | Python | bsd-3-clause | 14,197 | 0 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... | itten
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTIC | ULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HO... |
uclouvain/OSIS-Louvain | base/forms/entity.py | Python | agpl-3.0 | 1,833 | 0.001092 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | icense, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A cop... | icense - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
import django_filters
from django.forms import TextInput
from django.utils.translation import gettext_lazy as _
fro... |
TomasDuro/paparazzi | sw/tools/rtp_viewer/rtp_viewer.py | Python | gpl-2.0 | 2,844 | 0.001758 | #! /usr/bin/python
import cv2
import sys
from os import path, getenv
PPRZ_SRC = getenv("PAPARAZZI_SRC", path.normpath(path.join(path.dirname(path.abspath(__file__)), '../../../')))
sys.path.append(PPRZ_SRC + "/sw/ext/pprzlink/lib/v1.0/python")
from pprzlink.ivy import IvyMessagesInterface
from pprzlink.message impor... | :
self.mouse['start'] = None
if event == cv2.EVENT_MOUSEMOVE:
self.mouse['now'] = (x, y)
| if event == cv2.EVENT_LBUTTONUP:
# If mouse start is defined, a region has been selected
if not self.mouse.get('start'):
return
# Obtain mouse start coordinates
sx, sy = self.mouse['start']
# Create a new message
msg = PprzMess... |
beol/reviewboard | reviewboard/webapi/resources/review_screenshot_comment.py | Python | mit | 6,387 | 0 | from __future__ import unicode_literals
from django.core.exceptions import ObjectDoesNotExist
from djblets.util.decorators i | mport augment_method_from
from djblets.webapi.decorators import (webapi_login_required,
webapi_response_errors,
webapi_request_fields)
from djblets.webapi.errors import (DOES_NOT_EXIST, INVALID_FORM_DAT | A,
NOT_LOGGED_IN, PERMISSION_DENIED)
from reviewboard.reviews.models import Screenshot
from reviewboard.webapi.decorators import webapi_check_local_site
from reviewboard.webapi.resources import resources
from reviewboard.webapi.resources.base_screenshot_comment import \
BaseScree... |
vojtatranta/django-is-core | example/manage.py | Python | lgpl-3.0 | 323 | 0 | #!/usr/bin/env python
import os
import sys
PROJECT_DIR = os.path.abspath(
os.path.join | (os.path.dirname(__file__))
)
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj.settings")
from django.core.management import execute_from_command_line
execute_from_command_ | line(sys.argv)
|
moreati/u2fval | u2fval/core/api.py | Python | bsd-2-clause | 9,048 | 0 | # Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... | elf, session, memstore, metadata, allow_untrusted=False):
self._session = session
self._memstore = memstore
self._metadata | = metadata
self._require_trusted = not allow_untrusted
@wsgify
def __call__(self, request):
client_name = request.environ.get('REMOTE_USER')
if not client_name:
raise u2f_error(BadInputException('Client not specified'))
try:
resp = self.client(request, c... |
magfest/ubersystem | alembic/versions/a1a5bd54b2aa_add_autograph_interview_and_travel_plan_.py | Python | agpl-3.0 | 3,669 | 0.010902 | """Add autograph, interview, and travel plan checklist items
Revision ID: a1a5bd54b2aa
Revises: f619fbd56912
Create Date: 2017-09-21 07:17:46.817443
"""
# revision identifiers, used by Alembic.
revision = 'a1a5bd54b2aa'
down_revision = 'f619fbd56912'
branch_labels = None
depends_on = None
from alembic import op
im... | sa.Integer(), server_default='0', nullable=False),
sa.Column('length', sa.Integer() | , server_default='60', nullable=False),
sa.ForeignKeyConstraint(['guest_id'], ['guest_group.id'], name=op.f('fk_guest_autograph_guest_id_guest_group')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_guest_autograph')),
sa.UniqueConstraint('guest_id', name=op.f('uq_guest_autograph_guest_id'))
)
op.crea... |
CroissanceCommune/autonomie | autonomie/models/options.py | Python | gpl-3.0 | 5,322 | 0.000188 | # -*- coding: utf-8 -*-
# * Copyright (C) 2012-2014 Croissance Commune
# * Authors:
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
# * TJEBBES Gaston <g.t@majerti.fr>
#
# This file is part of Autonomie : Progiciel de gestion de CAE.
#
# Autonomie is free software: you can red... | TY 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 Autonomie. If not, see <http://www.gnu.org/licenses/>.
"""
Base tools for administrable options
"""
from sqlalchemy import (
C... | from sqlalchemy.util import classproperty
from sqlalchemy.sql.expression import func
from autonomie_base.utils.ascii import camel_case_to_name
from autonomie_base.models.base import (
DBBASE,
default_table_args,
DBSESSION,
)
from autonomie.forms import (
get_hidden_field_conf,
EXCLUDED,
)
class C... |
jonnybazookatone/ads | examples/journal-publications-over-time/journals.py | Python | mit | 3,651 | 0.004656 | # coding: utf-8
""" Compile publication data for astronomy journals over the last 10 years. """
from __future__ import division, print_function
__author__ = "Andy Casey <acasey@mso.anu.edu.au>"
# Standard library
import json
# Module specific
import ads
if __name__ == "__main__":
# Let's select the years and... |
# Perform the query
# We actually don't want all the results, we just want the metadata
# which tells us how many publications there were
q = ads.SearchQuery(q="pub:\"{journal}\" year:{year}".format(journal=journal, year=year), fl=['id'], rows=1)
... | } had {num} publications in {year}"
.format(journal=journal, num=num, year=year))
# Save this data
journal_data["articles"].append([year, num])
journal_data["total"] += num
# Let's only save it if there were actually any publications
if journal_dat... |
mmccollow/TSV-Convert | tsv-convert.py | Python | gpl-2.0 | 3,059 | 0.024191 | #!bin/python
# TSV to Dublin Core/McMaster Repository conversion tool
# Matt McCollow <mccollo@mcmaster.ca>, 2011
# Nick Ruest <ruestn@mcmaster.ca>, 2011
from DublinCore import DublinCore
import csv
from sys import argv
from xml.dom.minidom import Document
from os.path import basename
DC_NS = 'http://purl.org/dc/ele... | error)
raise SystemExit
fp.close()
def makedc(row):
""" Generate a Dublin Core XML file from a TSV """
metadata = DublinCore()
metadata.Contributor = row.get('dc:contributor', '')
metadata.Coverage = row.get('dc:coverage', '')
metadata.Creator = row.get('dc:creator', '')
metadata.Date = row.get('dc:date', '')... | ifier = row.get('dc:identifier', '')
metadata.Language = row.get('dc:language', '')
metadata.Publisher = row.get('dc:publisher', '')
metadata.Relation = row.get('dc:relation', '').split('|')
metadata.Rights = row.get('dc:rights', '')
metadata.Source = row.get('dc:source', '')
metadata.Subject = row.get('dc:subjec... |
anentropic/django-ebaysync | ebaysync/notifications.py | Python | lgpl-3.0 | 4,183 | 0.004542 | import base64
import hashlib
import logging
import math
import time
from django.conf import settings
from ebaysuds import TradingAPI
from suds.plugin import PluginContainer
from suds.sax.parser import Parser
logging.basicConfig()
log = logging.getLogger(__name__)
class UnrecognisedPayloadTypeError(Exception):
... | payload type: %s' % payload_type)
# don balaclava, hijack a suds SoapClient instance to decode our payload for us
sc_class = payload_method.clientclass({})
soapclient = sc_class(self.client.sudsclient, payload_method.method)
# copy+pasted from SoapClient.send :(
plugins... | plugins)
ctx = plugins.message.received(reply=message)
result = soapclient.succeeded(soapclient.method.binding.input, ctx.reply)
# `result` only contains the soap:Body of the response (parsed into objects)
# but the signature we need is in the soap:Header element
signature = sel... |
bianchimro/django-search-views | tests/settings.py | Python | mit | 289 | 0.00346 | SECRET_KEY = 'fake-ke | y'
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
INSTALLED_APPS = [
"django_nose",
"tests",
]
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-coverage',
'--cover-package=search | _views',
]
|
ets-labs/python-dependency-injector | tests/unit/providers/async/test_provided_instance_py36.py | Python | bsd-3-clause | 5,113 | 0.001565 | """ProvidedInstance provider async mode tests."""
import asyncio
from dependency_injector import containers, providers
from pytest import mark, raises
from .common import RESOURCE1, init_resource
@mark.asyncio
async def test_provided_attribute():
class TestClient:
def __init__(self, resource):
... | instance1.resource is RESOURCE1
assert instance2.resource is RESOURCE1
assert instance1.resource is instance2.resource
@mark.asyncio
async def test_provided_method_call_parent_error():
async def raise_exception():
raise RuntimeError()
class TestContainer(containers.DeclarativeContainer):
... | ion)
container = TestContainer()
with raises(RuntimeError):
await container.client.provided.method.call()()
@mark.asyncio
async def test_provided_method_call_error():
class TestClient:
def method(self):
raise RuntimeError()
class TestContainer(containers.DeclarativeConta... |
arpruss/plucker | plucker_desktop/installer/osx/application_bundle_files/Resources/parser/python/vm/PIL/CurImagePlugin.py | Python | gpl-2.0 | 2,171 | 0.00783 | #
# The Python Imaging Library.
# $Id: CurImagePlugin.py,v 1.2 2007/06/17 14:12:14 robertoconnor Exp $
#
# Windows Cursor support for PIL
#
# notes:
# uses BmpImagePlugin.py to read the bitmap data.
#
# history:
# 96-05-27 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fr... | distribution.
#
__version__ = "0.1"
import string
import Image, BmpImagePlugin
#
# --------------------------------------------------------------------
def i16(c):
return ord(c[0]) + (ord(c[1])<<8)
def i32(c):
return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) | + (ord(c[3])<<24)
def _accept(prefix):
return prefix[:4] == "\0\0\2\0"
##
# Image plugin for Windows Cursor files.
class CurImageFile(BmpImagePlugin.BmpImageFile):
format = "CUR"
format_description = "Windows Cursor"
def _open(self):
offset = self.fp.tell()
# ch... |
googleinterns/wss | third_party/deeplab/core/dense_prediction_cell.py | Python | apache-2.0 | 12,180 | 0.003859 | # Lint as: python2, 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
#
#... | e)
resize_width = utils.scale_dimension(crop_size[1], 1. / output_stride)
# If image_pooling_crop_size is not specified, use crop_size.
if image_pooling_crop_size is None:
image_pooling_crop_size = crop_size
pooled_height = utils.scale_dimension(
image_pooling_crop_size[0], 1. / (output_ | stride * image_grid[0]))
pooled_width = utils.scale_dimension(
image_pooling_crop_size[1], 1. / (output_stride * image_grid[1]))
return ([resize_height, resize_width], [pooled_height, pooled_width])
def _parse_operation(self, config, crop_size, output_stride,
image_pooling_crop... |
Mariaanisimova/pythonintask | BIZa/2015/Anisimova_M_L/task_2_1.py | Python | apache-2.0 | 574 | 0.008523 | # Задача 2. Вариант 1.
|
# Напишите программу, которая будет выводить на экр | ан наиболее понравившееся вам высказывание, автором которого является Еврипид. Не забудьте о том, что автор должен быть упомянут на отдельной строке.
# Anisimova M.L.
# 02.09.2016
print("Жизнь наша есть борьба.")
print("\t\t Еврипид")
input("Нажмите Enter для выхода.")
|
thonkify/thonkify | src/lib/sparkpost/tornado/base.py | Python | mit | 1,048 | 0.000954 | import json
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError
from .exceptions import SparkPostAPIException
class TornadoTransport(object):
@gen.coroutine
def re | quest(self, method, uri, headers, **kwargs):
if "data" in kwargs:
| kwargs["body"] = kwargs.pop("data")
client = AsyncHTTPClient()
try:
response = yield client.fetch(uri, method=method, headers=headers,
**kwargs)
except HTTPError as ex:
raise SparkPostAPIException(ex.response)
if... |
ismailsunni/f3-factor-finder | core/run_it.py | Python | gpl-2.0 | 3,452 | 0.032445 | #!/F3/core/run_it.py
# This file is used for creating a script
# Author : Ismail Sunni/@ismailsunni
# Created : 2012-04-06
import MySQLdb # accesing mysql database
from xlwt import Workbook # for writing in excel
import xlrd # for reading excel
from tempfile import TemporaryFile
import util as util
im... | )
activeSheet.write(i, 1, 'Tweet Id')
activeSheet.write(i, 2, 'Username')
activeSheet.write(i, 3, 'Created')
activeSheet.write(i, 4, 'Text')
from random import sample
result = sample(result, 3000)
i += 1
try:
for row in result:
activeSheet.write(i, 0, str(i - 1))
activeSheet.write(i, 1, ... | if i >= 50002:
break
book.save('test_data_training2.xls')
book.save(TemporaryFile())
except Exception, e:
util.debug(str(e))
def main_excel_to_sql():
book = xlrd.open_workbook('test_data_training2.xls')
sheet = book.sheet_by_name('tweets')
tweets = []
for row in range(sheet.nrows):
... |
dholl/python-sounddevice | doc/fake_cffi.py | Python | mit | 636 | 0 | """Mock module for Sphinx autodoc."""
class FFI(object):
N | ULL = NotImplemented
I_AM_FAKE = True # This is used for the d | ocumentation of "default"
def cdef(self, _):
pass
def dlopen(self, _):
return FakeLibrary()
class FakeLibrary(object):
# from portaudio.h:
paFloat32 = paInt32 = paInt24 = paInt16 = paInt8 = paUInt8 = NotImplemented
paFramesPerBufferUnspecified = 0
def Pa_Initialize(self):
... |
dinnozap/MinecraftServerMaker | launch.py | Python | apache-2.0 | 2,078 | 0.039461 | import subprocess, os, zipfile, requests
## Function Download
def download(url, fichier):
pass
fileName = fichier
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
file.write(chunk)
file.close()
print("The download is finish !")
## Function Unzip
def unzip(source , ... | "plugins")
download('https://hub.spigotmc.org/jenkins/job/Spigot-Essentials/lastSuccessfulBuild/artifact/Essentials/target/Essentials-2.x-SNAPSHOT.jar', 'plugins/essentials.jar')
download('http | s://www.spigotmc.org/resources/sexymotd.2474/download?version=73466', 'plugins/motd.jar')
subprocess.call(['java', '-jar', ServerName +'.jar'])
|
gmittal/prisma | server/src/utils.py | Python | mit | 975 | 0.017436 | import scipy.misc, numpy as np, os, sys
def save_img(out_path, img):
img = np.clip | (img, 0, 255).astype(np.uint8)
scipy.misc.imsave(out_path, img)
def scale_img(style_path, style_scale):
scale = float(style_s | cale)
o0, o1, o2 = scipy.misc.imread(style_path, mode='RGB').shape
scale = float(style_scale)
new_shape = (int(o0 * scale), int(o1 * scale), o2)
style_target = _get_img(style_path, img_size=new_shape)
return style_target
def get_img(src, img_size=False):
img = scipy.misc.imread(src, mode='RGB') ... |
Verbalist/electrum-server | src/storage.py | Python | mit | 21,577 | 0.000556 | import plyvel
import ast
import hashlib
import os
import sys
import threading
from processor import print_log, logger
from utils import (
bc_address_to_hash_160,
Hash,
bytes8_to_int,
bytes4_to_int,
int_to_bytes8,
int_to_hex8,
int_to_bytes4,
int_to_hex4
)
"""
Patricia tree for hashing u... | lock:
i = self.db.iterator(start=key)
k, _ = i.next()
return k
class Storage(object):
def __init__(self, config, shared, test_reorgs):
self.shared = shared
self.hash_list = {}
self.parents = {}
self.skip_batch = | {}
self.test_reorgs = test_reorgs
# init path
self.dbpath = config.get('leveldb', 'path')
if not os.path.exists(self.dbpath):
os.mkdir(self.dbpath)
try:
self.db_utxo = DB(self.dbpath, 'utxo',
config.getint('leveldb', 'utxo_cac... |
jgirardet/unolog | unolog/patients/models.py | Python | gpl-3.0 | 2,704 | 0.001113 | from string import capwords
from django.db import models
CAPWORDS_ATTRS = ('name', 'firstname')
class PatientManager(models.Manager):
"""
custum patient manger to modifie create and update
"""
attrs = CAPWORDS_ATTRS
# paremeter to capwords
# def create_patient(self, name=Non... | return patient
def create(self, **kwargs):
"""
enhancement
"""
# capwors certain fields
for i in self.attrs:
kwargs[i] = capwords(kwargs[i])
# recall base create
return super(PatientManager, | self).create(**kwargs)
class Patient(models.Model):
"""
ase class of patient.&
Require on ly 3 fields : name, firstname, birthdate
"""
attrs = CAPWORDS_ATTRS
# required Field
name = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
birthdate =... |
Eksmo/itunes-iap | itunesiap/utils.py | Python | bsd-2-clause | 466 | 0 | import six
def force_unicode(value):
if not isinstance(value, six.string_types):
return six.text_type(value)
try | :
return value.decode('utf-8')
except (AttributeError, UnicodeEncodeError):
return value
def force_bytes(value):
if not isinstance(value, six.string_types):
value = force_unicode(value)
try:
| return value.encode('utf-8')
except (AttributeError, UnicodeDecodeError):
return value
|
ngageoint/scale | scale/job/execution/configuration/workspace.py | Python | apache-2.0 | 653 | 0 | """Defines a workspace that is needed by a task"""
from __future__ import unicode_literals
class TaskWorkspace(object):
"""Represents a workspace needed by a task
"""
def __init__(self, name, mode, volume_name=None):
"""Creates a task workspace
:param name: The name of the workspace
... | : string
:param mode: The mode to use for the workspace, either 'ro' or 'rw'
:type mode: string
:param volume_name: The name to use for the workspace's volume
:type volume_name: string
"""
self.name = name
s | elf.mode = mode
self.volume_name = volume_name
|
Duke-GCB/DukeDSHandoverService | d4s2_api/migrations/0017_auto_20180323_1833.py | Python | mit | 944 | 0.001059 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2018-03-23 18:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('d4s2_api', '0016_email_group_to_set'),
]
operations... | name='emailtemplate',
uni | que_together=set([('template_set', 'template_type')]),
),
migrations.RemoveField(
model_name='historicalemailtemplate',
name='group',
),
migrations.AlterField(
model_name='emailtemplate',
name='template_set',
field=models.Foreig... |
nisavid/home | .config/ipython/profile_simple/ipython_notebook_config.py | Python | unlicense | 17,850 | 0.003361 | # Configuration file for ipython-notebook.
c = get_config()
#------------------------------------------------------------------------------
# NotebookApp configuration
#------------------------------------------------------------------------------
# NotebookApp will inherit config from: BaseIPythonApplication, Appli... | '
# | Set the log level by value or name.
# c.NotebookApp.log_level = 20
# Hashed password to use for web authentication.
#
# To generate, type in a python/IPython shell:
#
# from IPython.lib import passwd; passwd()
#
# The string should be of the form type:salt:hashed-password.
# c.NotebookApp.password = u''
# The Lo... |
sasha-gitg/python-aiplatform | schema/predict/prediction/scripts/fixup_prediction_v1beta1_keywords.py | Python | apache-2.0 | 5,910 | 0.001184 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# 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 requi... | does | not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1)
if os.listdir(output_dir):
print(
f"output directory '{output_dir}' is not empty",
file=sys.stderr,
)
sys.exit(-1)
fix_files(input_dir, output_dir)
|
cpausmit/Kraken | pandaf/014/mc.py | Python | mit | 129 | 0.007752 |
import PandaProd | .Producer.opts
PandaProd.Producer.opts.options.config = 'Autumn18'
from PandaProd.Producer.prod impor | t process
|
googleinterns/wss | core/train_utils_core.py | Python | apache-2.0 | 13,925 | 0.007038 | # Lint as: python2, python3
# 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 ... | shape(score)[-1]
# Only valid when we use Linformer style to reduce size for key and value
if downsample_type == 'bilinear':
resize_fn = tf.compat.v1.image.resize_bilinear
else:
resize_fn = tf.compat.v1.image.resize_nearest_neighbor
scope = 'hyper_column'
with tf.variable_scope(scope):
with slim... | activation_fn=None,
normalizer_fn=None,
biases_initializer=None,
reuse=tf.AUTO_REUSE):
k = slim.conv2d(
conv_layer_merged, attention_dim, [1, 1], scope='key')
q = slim.conv2d(
conv_layer_merged, att... |
zutshi/S3CAMX | src/graph.py | Python | bsd-2-clause | 32,399 | 0.00213 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import err
import utils as U
# needed for testing
import random as rand
import time
# FIX heap duplicates used by different ksp!
import heapq
from heapq import heappush, heappop
from itertools import count
from collections import defaultdict
from blessings import Termin... | ### KSP 1 ############################################## | ####
# https://gist.github.com/guilhermemm/d |
3YOURMIND/django-migration-linter | tests/test_project/app_make_not_null_with_django_default/migrations/0001_initial.py | Python | apache-2.0 | 661 | 0 | # Generated by Django 2.2 on 2020-06-20 15:17
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="A",
fields=[
(
"id",
| models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("col", m | odels.CharField(max_length=10, null=True)),
],
),
]
|
gingi99/research_dr | python/FPgrowth/orange_fpgrowth.py | Python | mit | 10,802 | 0.015115 | # coding: utf-8
# python 3.5
import Orange
from orangecontrib.associate.fpgrowth import *
import pandas as pd
import numpy as np
import sys
import os
from collections import defaultdict
from itertools import chain
from itertools import combinations
from itertools import compress
from itertools import product
from sklea... | #rules_orange = Orange.associate.AssociationRulesSparseInducer(data_table, support=minsup, confidence=minconf)
#rules_orange = Orange.associate.AssociationRulesSparseInducer(data_table, support = minsup, max_item_sets = 2000)
# convert Rule Class
#rules = []
| #for rule_orange in rules_orange :
# consequent = rule_orange.right.get_metas(str).keys()
# if len(consequent) == 1 and consequent[0] in classes and rule_orange.confidence >= minconf :
# rule = Rule()
# rule.setValue(rule_orange.left.get_metas(str).keys())
# rule.setConseq... |
zoofIO/flexx | flexx/ui/widgets/_lineedit.py | Python | bsd-2-clause | 7,452 | 0.001476 | """
The ``LineEdit`` and ``MultiLineEdit`` widgets provide a way for the user
to input text.
.. UIExample:: 100
from flexx import app, event, ui
class Example(ui.Widget):
def init(self):
with ui.VBox():
self.line = ui.LineEdit(placeholder_text='type here')
... | self.node.value = self.text
@event.emitter
def user_text(self, text):
""" Event emitted when the user edits the text. Has ``old_value``
and ``new_value`` attributes.
"""
d = {'old_value': self.text, 'new_value': text}
self.set_text(text)
return d
@event... | |
SlicerRt/SlicerDebuggingTools | PyDevRemoteDebug/ptvsd-4.1.3/ptvsd/_vendored/pydevd/pydevd_plugins/django_debug.py | Python | bsd-3-clause | 16,161 | 0.003589 | from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
import inspect
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, get_thread_id, dict_iter_items, DJANGO_SUSPEND, IS_PY2
from pydevd_file_utils import get_abs_path_real_path_and_base_from_file, normcase
from _pydevd_bundle.pydevd_... | tion_break[exception] = True
pydb.set_tracing_for_untraced_contexts_if_not_frame_eval()
retur | n True
return False
def _init_plugin_breaks(pydb):
pydb.django_exception_break = {}
pydb.django_breakpoints = {}
def remove_exception_breakpoint(plugin, pydb, type, exception):
if type == 'django':
try:
del pydb.django_exception_break[exception]
return True
... |
JasonKessler/scattertext | demo_tokenizer_roberta.py | Python | apache-2.0 | 1,670 | 0.003593 | from transformers import RobertaTokenizerFast
import scattertext as st
tokenizer_fast = RobertaTokenizerFast.from_pretrained(
"roberta-base", add_prefix_space=True)
tokenizer = st.RobertaTokenizerWrapper(tokenizer_fast)
df = st.SampleCorpora.ConventionData2012.get_data().assign(
parse = lambda df: df.text.app... | col='party',
parsed_col='parse',
feat_and_offset_getter=st.TokenFeatAndOffsetGetter()
).build()
# Remove words occur less than 5 times
corpus = corpus.remove_infrequent_words(5, non_text=True | )
plot_df = corpus.get_metadata_freq_df('').assign(
Y=lambda df: df.democrat,
X=lambda df: df.republican,
Ypos=lambda df: st.Scalers.dense_rank(df.Y),
Xpos=lambda df: st.Scalers.dense_rank(df.X),
SuppressDisplay=False,
ColorScore=lambda df: st.Scalers.scale_center_zero(df.Ypos - df.Xpos),
)
ht... |
justyns/home-assistant | tests/components/mqtt/test_init.py | Python | mit | 11,668 | 0 | """The tests for the MQTT component."""
from collections import namedtuple
import unittest
from unittest import mock
import socket
import homeassistant.components.mqtt as mqtt
from homeassistant.const import (
EVENT_CALL_SERVICE, ATTR_DOMAIN, ATTR_SERVICE, EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP)
... | ART)
self.hass.pool.block_till_done()
self.hass.bus.fire(EVENT_HOMEASSISTANT_STOP)
self.hass.pool.block_till_done()
self.assertTrue(mqtt.MQTT_CLIENT.stop.called)
def test_setup_fails | _if_no_connect_broker(self):
"""Test for setup failure if connection to broker is missing."""
with mock.patch('homeassistant.components.mqtt.MQTT',
side_effect=socket.error()):
self.assertFalse(mqtt.setup(self.hass, {mqtt.DOMAIN: {
mqtt.CONF_BROKER: 't... |
laenderoliveira/exerclivropy | cap09/exercicio-09-31.py | Python | mit | 192 | 0.005291 | import os.path
dir = "temp"
if os.path.isdir(dir):
print("Diretório tem | p existe")
elif os.path.isfile(dir):
print( | "Arquivo temp existe")
else:
print("Diretório temp não existe") |
RafiKueng/SteMM | model.py | Python | mit | 12,007 | 0.015658 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PHOTOMETRYDEMO - model.py
the data model
Created on Tue Sep 23 12:09:45 2014
@author: rafik
"""
import os
import math
import numpy as np
import scipy as sp
import scipy.ndimage.interpolation
import pyfits
class Model(object):
def __init__(self):
self... | /2, xx, sy, tags='roi_%i' % self.nr, fill=self.color)
el | se:
l1 = self.canv.create_line(xx, 0, xx, miny, tags='roi_%i' % self.nr, fill=self.color)
l2 = self.canv.create_line(xx, maxy, xx, sy, tags='roi_%i' % self.nr, fill=self.color)
self.lines.append((l1,l2))
def update(self):
self._update()
... |
eggplantbren/Lensing2 | src/distances.py | Python | gpl-3.0 | 4,646 | 0.020017 | """
A module to compute cosmological distances, including:
comoving_distance (Dc)
angular_diameter_distance (Da)
luminosity_distance (Dl)
comoving_volume (volume)
"""
c = 299792458.
G = 4.3e-6
from math import pi
import warnings
warnings.warn("Default cosmology is Om=0.3,Ol=0.7,h=0.7,w=-1 and distance ... | *2*Dos*Dol/(4*np.pi*Gnewton*Dls)/Msun)
# Another way of getting the mass for | a 5 arcsec Einstein ring
# Angular einstein radius (arcseconds) of a solar mass
theta_0 = np.sqrt(4.*Gnewton*Msun/c**2*Dls/Dol/Dos)*(180./np.pi)*3600.
print((5.0/theta_0)**2)
# print(1./theta_0**2./np.pi)
|
vmalloc/pydeploy | tests/test__sources.py | Python | bsd-3-clause | 10,265 | 0.005261 | import os
import tempfile
from pkg_resources import Requirement
from infi.unittest import parameters
from .test_cases import ForgeTest
from pydeploy.environment import Environment
from pydeploy.environment_utils import EnvironmentUtils
from pydeploy.checkout_cache import CheckoutCache
from pydeploy.installer import Ins... | path_mock = self.forge.create_mock(self.orig_path_class)
self.path_class(path, name=name).and_return(path_mock)
return path_mock.install(self.env, reinstall=reinstall)
class GitSourceTest(DelegateToPathInstallTest):
def setUp(self):
super(GitSourc | eTest, self).setUp()
self.repo_url = "some/repo/url"
self.branch = 'some_branch'
self.source = sources.Git(self.repo_url, self.branch)
self.forge.replace_many(git, "clone_to_or_update", "reset_submodules")
def test__master_is_default_branch(self):
self.assertEquals(sources.Gi... |
werbk/task-2.1 | tests_contract/contract_lib.py | Python | apache-2.0 | 5,896 | 0.002035 | from TestBase import BaseClass
class ContractBase(BaseClass):
def add_contract(self):
wd = self.wd
wd.find_element_by_link_text("add new").click()
wd.find_element_by_name("email").click()
wd.find_element_by_name("email").clear()
wd.find_element_by_name("email").send_keys()
... | d_element_by_name("nickname").click()
wd.find_element_by_name("nickname").clear()
wd.find_element_by_name("nickname").send_keys("%s" % nickname)
def add_title(self, title):
wd = self.wd
wd.find_element_by_name("title").click()
wd.find_element_by_name("title").clear()... | ck()
wd.find_element_by_name("company").clear()
wd.find_element_by_name("company").send_keys("%s" % company_name)
def add_address(self, address_name):
wd = self.wd
wd.find_element_by_name("address").click()
wd.find_element_by_name("address").clear()
wd.find_element_b... |
rbarlow/ari-backup | ari_backup/zfs.py | Python | bsd-3-clause | 9,110 | 0.003952 | """ZFS based backup workflows."""
import datetime
import shlex
import gflags
import lvm
import workflow
FLAGS = gflags.FLAGS
gflags.DEFINE_string('rsync_options',
'--archive --acls --numeric-ids --delete --inplace',
'rsync command options')
gflags.DEFINE_string('rsync_path'... | source_hostname, rsync_dst, zfs_hostname,
dataset_name, snapshot_expiration_days, **kwa | rgs):
"""Configure a ZFSLVMBackup object.
Args:
label: str, label for the backup job (e.g. database-server1).
source_hostname: str, the name of the host with the source data to
backup.
rsync_dst: str, the destination argument for the rsync command line
(e.g. backupbox:/backu... |
lilsweetcaligula/Online-Judges | hackerrank/algorithms/implementation/easy/kangaroo/py/solution.py | Python | mit | 215 | 0.009302 | #!/bin/python3
import sys
x1, v1, x2, v2 = map(int, input().strip() | .split(' '))
willLand = (
v1 != v2
and (x1 - x2) % (v2 - v1) == 0
and (x1 - x2) // (v2 - v1) >= 0)
print(('NO' | , 'YES')[willLand])
|
sergeneren/anima | anima/ui/ui_compiled/version_updater_UI_pyside2.py | Python | bsd-2-clause | 3,651 | 0.003835 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_files\version_updater.ui'
#
# Created: Thu Nov 10 15:32:30 2016
# by: pyside2-uic running on PySide2 2.0.0~alpha0
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_Dialo... | (self.update_pushButton)
self.cancel_pushButton = QtWidgets.QPushButton(self.horizontalWidget)
self.cancel_pushButton.setObjectName("cancel_pushButton")
self.horizontalLayout.addWidget(self.cancel_pushButton)
| self.verticalLayout.addWidget(self.horizontalWidget)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Version Updater", None, -1))
self.label.setText(QtW... |
biocore/american-gut-rest | agr/schema.py | Python | bsd-3-clause | 5,875 | 0.00034 | # ------------------------------ | ----------------------------------------------
# Copyright (c) 2011-2015, The American Gut Development Team.
#
# Distributed under the terms of the Modified BSD Licen | se.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from psycopg2 import connect
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import agr
# table definitions, these are of the form: [(table_na... |
raphui/barebox | scripts/remote/messages.py | Python | gpl-2.0 | 4,045 | 0.000247 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import struct
class BBType(object):
command = 1
command_return = 2
consolemsg = 3
ping = 4
pong = 5
getenv = 6
getenv_return = 7
fs = 8
fs_return = 9
class BBPacket(o... | f.exit_code, = struct.unpack("!L", data[:4])
def _pack_payload(self):
return struct.pack("!L", self.exit_code)
class BBPacketConsoleMsg(BBPacket):
def __init__(self, raw=None, text=None):
self.text = text
super(BBPacketConsoleMsg, self).__init__(BBType.consolemsg, raw=raw)
def __... | yload(self):
return self.text
class BBPacketPing(BBPacket):
def __init__(self, raw=None):
super(BBPacketPing, self).__init__(BBType.ping, raw=raw)
def __repr__(self):
return "BBPacketPing()"
class BBPacketPong(BBPacket):
def __init__(self, raw=None):
super(BBPacketPong, ... |
icchy/tracecorn | unitracer/lib/windows/amd64/gdi32.py | Python | mit | 12,573 | 0.021236 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain ... | = 0x012D
META | _SETTEXTALIGN = 0x012E
META_CHORD = 0x0830
META_SETMAPPERFLAGS = 0x0231
META_EXTTEXTOUT = 0x0a32
META_SETDIBTODEV = 0x0d33
META_SELECTPALETTE = 0x0234
META_REALIZEPALETTE = 0x0035
META_ANIMATEPALETTE = 0x0436
META_SETPALE... |
agusmakmun/Some-Examples-of-Simple-Python-Script | grabbing/notes.py | Python | agpl-3.0 | 5,474 | 0.011874 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import time, os
import sys, fileinput
from bs4 import BeautifulSoup
class Grabber(object):
def use(self):
print ""
print "* This just Fucking whatever for grabbing."
print "* For license just fucking to change this. ^Summon Agus Cre... | s.py listnote <file_name>"
print "[3] Delete Note : ./notes.py delnote <file_name> <numb_line>"
print "[4] Add Url to Grab : ./notes.py addurl <file_name> <url>"
print "-------------------------------------------------------------------------------------"
| print ""
def addnote(self, args):
self.help = "./notes.py addnote <file_name> <title> <content> <tag1, tag2>"
if len(sys.argv) < 5:
sys.exit("[-] Fucking Damn!!\n[?] Use similiar this: " + self.help)
f_note_out = sys.argv[2]
title = sys.argv[3]
... |
altair-viz/altair | altair/vegalite/v3/schema/channels.py | Python | bsd-3-clause | 263,403 | 0.006124 | # The contents of this file are automatically written by
# tools/generate_schema_wrapper.py. Do not modify directly.
from . import core
import pandas as pd
from altair.utils.schemapi import Undefined
from altair.utils import parse_shorthand
class FieldChannelMixin(object):
def to_dict(self, validate=True, ignore... | ring
shorthand for field, aggregate, and type |
aggregate : :class:`Aggregate`
Aggregation function for the field
(e.g., ``mean``, ``sum``, ``median``, ``min``, ``max``, ``count`` ).
**Default value:** ``undefined`` (None)
**See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__
documentation.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.