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 |
|---|---|---|---|---|---|---|---|---|
teoliphant/numpy-refactor | numpy/core/code_generators/generate_numpy_api.py | Python | bsd-3-clause | 7,203 | 0.001944 | import os
import genapi
from genapi import TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi
import numpy_api
h_template = r"""
#ifdef _MULTIARRAYMODULE
typedef struct {
PyObject_HEAD
npy_bool obval;
} PyBoolScalarObject;
extern NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type;
extern NPY_NO... | return -1;
}
/*
* Perform runtime check of endianness and check it matches the one set by
* the headers (npy_endian.h) as a safeguard
*/
st = PyArray_GetEndianness();
if (st == NPY_CPU_UNKNOWN_ENDIAN) {
PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as unknown endian");
return -... | E_ORDER == NPY_BIG_ENDIAN
if (st != NPY_CPU_BIG) {
PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as "\
"big endian, but detected different endianness at runtime");
return -1;
}
#elif NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN
if (st != NPY_CPU_LITTLE) {
PyErr_Format(PyExc_Runtim... |
activityhistory/traces | traces/recorders/scroll_recorder.py | Python | gpl-3.0 | 1,355 | 0.01551 | # -*- coding: utf-8 -*-
"""
Traces: Activity Tracker
Copyright (C) 2015 Adam Rule
with Aurélien Tabard, Jonas Keper, Azeem Ghumman, and Maxime Guyaux
Inspired by Selfspy and Burrito
https://github.com/gurgeh/sel | fspy
https://github.com/pgbovine/burrito/
You should have received a copy of the GNU General Public License
along with Traces. If not, see <http://www.gnu.org/licenses/>.
"""
import os
from Cocoa import (NSEvent, NSScrollWheel, NSScrollWheelMask)
import config as cfg
import preferences
import utils_cocoa
class Scr... | ask, self.scroll_handler)
# TODO add tracking of duration of scroll
def scroll_handler(self, event):
recording = preferences.getValueForPreference('recording')
event_screenshots = preferences.getValueForPreference('eventScreenshots')
if event_screenshots:
self.sniffer.activity_tracker.take_screenshot()
i... |
google/ftc-object-detection | training/object_detector.py | Python | apache-2.0 | 4,142 | 0.007001 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in [
'num_detections', 'detection_boxes', | 'detection_scores',
'detection_classes', 'detection_masks'
]:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
tensor_name)
if 'detection_masks' in tensor_dict:
# The following... |
gpfreitas/bokeh | bokeh/application/spellings/tests/test_script.py | Python | bsd-3-clause | 2,526 | 0.003167 | from __future__ import absolute_import, print_function
import unittest
from bokeh.application.spellings import ScriptHandler
from bokeh.document import Document
def _with_temp_file(func):
import tempfile
f = tempfile.NamedTemporaryFile()
try:
func(f)
finally:
f.close()
def _with_scri... | f test_script_bad_syntax(self):
doc = Document()
result = {}
def load(filename):
handler = ScriptHandler(filename=filename)
result['handler'] = handler
handler.modify_document(doc)
_with_script_contents("This is a syntax error", load)
handler ... | in handler.error
def test_script_runtime_error(self):
doc = Document()
result = {}
def load(filename):
handler = ScriptHandler(filename=filename)
result['handler'] = handler
handler.modify_document(doc)
_with_script_contents("raise RuntimeError('n... |
UUDigitalHumanitieslab/timealign | stats/migrations/0022_scenario_is_public.py | Python | mit | 448 | 0.002232 | # -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stats', '0021_set | _normalized_stress'),
]
operations = [
migrations.AddField(
| model_name='scenario',
name='is_public',
field=models.BooleanField(default=False, verbose_name=b'Whether this Scenario is accessible by unauthenticated users'),
),
]
|
python-poetry/poetry-core | src/poetry/core/packages/utils/utils.py | Python | mit | 10,888 | 0.000643 | import os
import posixpath
import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Dict
from typing import List
from typing import Tuple
from typing import Union
from urllib.parse import unquote
from urllib.parse import urlsplit
from urllib.request import url2pathname
if TYP... | nstraint.ranges:
parts.append(create_nested_marker(name, c))
glue = " or "
parts = [f"({part})" for part i | n parts]
marker = glue.join(parts)
elif isinstance(constraint, Version):
if name == "python_version" and constraint.precision >= 3:
name = "python_full_version"
marker = f'{name} == "{constraint.text}"'
else:
if constraint.min is not None:
op = ">="
... |
NischalLal/Humpty-Dumpty-SriGanesh | myblog/migrations/0002_contact_project_socialsite.py | Python | bsd-3-clause | 1,637 | 0.002443 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myblog', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | e, primary_key=True, serialize=False, verbose_name='ID')),
| ('title', models.CharField(max_length=50)),
('link', models.URLField()),
('image', models.ImageField(default=None, upload_to='myblog/image/project')),
('detail', models.TextField()),
('created_on', models.DateTimeField()),
],
... |
tdeck/grab-sf-votes | collect.py | Python | mit | 9,518 | 0.004728 | """
A webdriver/selenium based scraper for San Francisco Board of Supervisors
voting data.
- Troy Deck (troy.deque@gmail.com)
"""
from selenium import webdriver
from datetime import date
import argparse
import time
import db
#############
# Constants #
#############
PATIENCE = 2 # Seconds to wait after executing a... | osal
def scrape_vote_page(browser):
"""
Assuming the browser is on a page containing a grid of votes, scrapes
the vote data to populate the database.
"""
# Get the contents of the table
headers, rows = extra | ct_grid_cells(browser, VOTING_GRID_ID)
# Do a quick check to ensure our assumption about the headers is correct
assert headers[:6] == [
u'File #',
u'Action Date',
u'Title',
u'Action Details',
u'Meeting Details',
u'Tally',
]
# Go through the supervisor... |
jawilson/home-assistant | tests/components/hassio/conftest.py | Python | apache-2.0 | 2,490 | 0 | """Fixtures for Hass.io."""
import os
from unittest.mock import Mock, patch
import pytest
from homeassistant.components.hassio.handler import HassIO, HassioAPIError
from homeassistant.core import CoreState
from homeassistant.setup import async_setup_component
from . import HASSIO_TOKEN
@pytest.fixture
def hassio_e... | ",
return_value={"result": "ok"},
) as hass_api, patch(
"homeassistant.components.hassio.HassIO.update_hass_timezone",
return_value={"result": "ok"},
), patch(
"homeassistant.components.hassio.HassIO.get_info", |
side_effect=HassioAPIError(),
):
hass.state = CoreState.starting
hass.loop.run_until_complete(async_setup_component(hass, "hassio", {}))
return hass_api.call_args[0][1]
@pytest.fixture
def hassio_client(hassio_stubs, hass, hass_client):
"""Return a Hass.io HTTP client."""
ret... |
tengyifei/grpc | src/python/grpcio_tests/tests/stress/client.py | Python | bsd-3-clause | 4,801 | 0.007707 | # Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | ed fro | m
# this software without specific prior written 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 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EV... |
ColinDuquesnoy/MellowPlayer | scripts/beautify.py | Python | gpl-2.0 | 893 | 0 | import os
def c | lang_format_recursive(root_path):
for root, dirs, files in os.walk(root_path):
for file in files:
if file.endswith(".cpp") or file.endswith(".hpp"):
path = os.path.join(root, file)
print('formatting %s' % path)
os.system('clang-format -i -style=fil... | js_beautify_recursive(root_path):
for root, dirs, files in os.walk(root_path):
for file in files:
if file.endswith(".js"):
path = os.path.join(root, file)
print('formatting %s' % path)
os.system('js-beautify -f %s -o %s' % (path, path))
if __nam... |
samueldotj/TeeRISC-Simulator | src/arch/x86/isa/insts/simd128/floating_point/data_conversion/__init__.py | Python | bsd-3-clause | 2,483 | 0 | # Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implemen... | g conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in | binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived ... |
superstack/nova | nova/vnc/proxy.py | Python | apache-2.0 | 4,135 | 0.000726 | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2010 Openstack, LLC.
# 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
#
# ... | if not str(name).startswith('.'):
filename = os.path.join(root, name)
self.whitelist[filename] = True
def get_whitelist(self):
return self.whitelist.keys()
def sock2ws(self, so | urce, dest):
try:
while True:
d = source.recv(32384)
if d == '':
break
d = base64.b64encode(d)
dest.send(d)
except:
source.close()
dest.close()
def ws2sock(self, source, dest):
... |
davidharvey1986/pyRRG | unittests/bugFixPyRRG/lib/python3.7/site-packages/pip/_internal/req/req_file.py | Python | mit | 19,075 | 0.000052 | """
Requirements file parsing
"""
# The following comment should be removed at some point in the future.
# mypy: strict-optional=False
from __future__ import absolute_import
import optparse
import os
import re
import shlex
import sys
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip._internal... | ReqFileLines
"""Split, filter, an | d join lines, and return a line iterator
:param content: the content of the requirements file
"""
lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comments(lines_enum)
lines_enum = expand_env_variables(lines_enum... |
dunkhong/grr | grr/core/grr_response_core/lib/package.py | Python | apache-2.0 | 2,986 | 0.011386 | #!/usr/bin/env python
"""A module with functions for working with GRR packages."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import importlib
import inspect
import logging
import os
import sys
import pkg_resources
from typing import Text
from grr_... | ilt binary we rely on the sys.prefix
# code below and avoid running this which will generate confusing error
# messages.
if not getattr(sys, "frozen", None):
target = _GetPkgResou | rces(package_name, filepath)
if target and os.access(target, os.R_OK):
return target
# Installing from wheel places data_files relative to sys.prefix and not
# site-packages. If we can not find in site-packages, check sys.prefix
# instead.
# https://python-packaging-user-guide.readthedocs.io/en/lates... |
wannesvl/topap | pathplanning/__init__.py | Python | lgpl-3.0 | 27 | 0 | from pathplanni | ng import *
| |
leppa/home-assistant | homeassistant/components/nx584/alarm_control_panel.py | Python | apache-2.0 | 4,039 | 0 | """Support for NX584 alarm control panels."""
import logging
from nx584 import client
import requests
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel.const i... | ctionError as ex:
_LOGGER.error(
"Unable to connect to %(host)s: %(reason)s",
dict(host=self._url, reason=ex),
)
self._state = None
zones = []
except IndexError:
_LOGGER.error("NX584 reports no partitions")
s... | or zone in zones:
if zone["bypassed"]:
_LOGGER.debug(
"Zone %(zone)s is bypassed, assuming HOME",
dict(zone=zone["number"]),
)
bypassed = True
break
if not part["armed"]:
self._state ... |
misli/cmsplugin-survey | cmsplugin_survey/views.py | Python | bsd-3-clause | 659 | 0 | from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
from .models impo | rt Question, Vote
@require_POST
def vote(request, question_id):
question = get_object_or_404(Question, id=question_id)
if question.can_vote(request) or True:
prefix = request.POST.get('prefix')
form = question.answer_form_class(prefix=prefix, data=request.POST)
if form.is_valid():
... | Redirect(request.META.get('HTTP_REFERER', '/'))
|
hippojay/plugin.video.plexbmc | resources/lib/plex_signin.py | Python | gpl-2.0 | 13,463 | 0.004754 | import pyxbmct.addonwindow as pyxbmct
import plex
from common import printDebug, GLOBAL_SETUP
import xbmc
printDebug=printDebug("PleXBMC", "plex_signin")
class plex_signin(pyxbmct.AddonFullWindow):
def __init__(self, title=''):
"""Class constructor"""
# Call the base class' constructor.
su... | one')
self.placeControl(self.submit_pin_button, 5, 2, columnspan=2)
# Submit button to get token
self.connect(self.submit_button, lambda: self.submit())
self.connect(self.manual_button, lambda: self.display_manual())
self.connect(self.pin_button, lambda: self.display_pin())
... | cross = pyxbmct.Image("%s/resources/media/error.png" % GLOBAL_SETUP['__cwd__'], aspectRatio=2)
self.placeControl(self.error_cross, 4 , 2 )
self.error_message = pyxbmct.Label("Unable to Login")
self.placeControl(self.error_message, 4 , 3 , columnspan=2, rowspan=2)
self.error_cross.setVisi... |
taedori81/shoop | shoop_tests/admin/test_contact_edit.py | Python | agpl-3.0 | 1,225 | 0 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.contrib.auth import get_user_model
from shoop.adm... | t_name=printable_gibberish(),
last_name=printable_gibberish(),
)
contact_base_form = ContactBaseForm(bind_user=user, data={
"name": "herf durr",
"gender": Gender.UNDISCLOSED.value
})
assert contact_base_form.bind_user == user
assert contact_base_form.contact_class == PersonCo... | contact = contact_base_form.save()
assert isinstance(contact, PersonContact)
assert contact.user == user
assert get_person_contact(user) == contact
|
boskee/regicide | regicide.py | Python | gpl-3.0 | 8,891 | 0.005511 | import requests
import hashlib
import json
import random
import sys
class ApiItemAmount(object):
def __new__(self, item_type, amount):
return {"type": item_type, "amount": amount}
class SagaAPI(object):
secret = ""
episodeLengths = {}
apiUrl = ""
clientApi = ""
unlockLevelItemId = -1
... | oScore(episode, level, starProgressions).json()
try:
# This is not quite right but it works since LEVEL_GOLD_REWARD still has a episodeId and levelId like LEVEL_UNLOCKED
# This only beats new levels that reported back the new unlocked level
... | level = level + 1
except KeyError:
print "Next level wasn't reported, Trying to unlock episode %s..." % (episode+1)
|
modelbrouwers/django-sessionprofile | sessionprofile/settings.py | Python | mit | 140 | 0.007143 | from django.conf import settings
def _get_backend():
return getattr | (settings, 'SESSIONPROFILE_BA | CKEND', 'sessionprofile.backends.db')
|
luiscberrocal/homeworkpal | homeworkpal_project/interviews/urls.py | Python | mit | 313 | 0.00639 | from django.conf.urls import patterns, url
from interviews.views import ElegibilityCertificateDetailView
__author__ = 'LBerrocal'
urlpat | terns = patterns('',
url(r'^certificate/(?P<pk>[\d]+)/$', ElegibilityCertificateDet | ailView.as_view(), name='certificate-goal'),
) |
LittleSmaug/summercamp2k17 | src/game/animation.py | Python | gpl-3.0 | 1,129 | 0.06023 | import pygame as pg
from .sprite import Sprite
class Animation(object):
def __init__(self,
paths=None,
imgs=None,
sprites=None,
spritesheet=None,
rect=None,
count=None,
colorkey=None,
loop=False,
frame_interval=1,
size=None):
if paths:
self.frames = [Sprit... | __len__(self):
return len(self.frames)
def __get_frame(self):
if not self.loop:
return self.frames[int(min(len(self) - 1, (self.current_frame / self.frame_interval) % len(self)))]
return self.frames[int((self.current_frame / self.frame_interval) % len(self))]
def reset(self):
self.current_frame = 0
de... | ze, rot)
self.current_frame += 1
|
kyoren/https-github.com-h2oai-h2o-3 | h2o-py/tests/testdir_algos/gbm/pyunit_mnist_manyCols_largeGBM.py | Python | apache-2.0 | 564 | 0.021277 | import sys
sys.path.insert(1, "../../../")
import h2o, tests
def mnist_manyC | ols_largeGBM():
#Log.info("Importing mnist train data...\n")
train = h2o.import_file(path=tests.locate("bigdata/laptop/mnist/train.csv.gz"))
#Log.info("Check that tail works | ...")
train.tail()
#Log.info("Doing gbm on mnist training data.... \n")
gbm_mnist = h2o.gbm(x=train[0:784], y=train[784], ntrees=1, max_depth=1, min_rows=10, learn_rate=0.01)
gbm_mnist.show()
if __name__ == "__main__":
tests.run_test(sys.argv, mnist_manyCols_largeGBM)
|
Huyuwei/tvm | python/tvm/expr.py | Python | apache-2.0 | 17,385 | 0.000575 | # 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 u... | 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 distribu | ted under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Expression AST Node in TVM.
User do not need to deal with expression AST node... |
ccilab/binutils | gdb/testsuite/gdb.python/py-mi-objfile-gdb.py | Python | gpl-3.0 | 1,077 | 0 | # Copyright (C) 2015-2016 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This progr... | buted in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with th | is program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite.
import gdb
# PR 18833
# We want to have two levels of redirection while MI is current_uiout.
# This will create one for to_string=True and then another for the
# parameter change notification.
gdb.execute("set width 10... |
graphql/libgraphqlparser | ast/cxx_visitor.py | Python | mit | 1,218 | 0.009031 | # Copyright 2019-present, GraphQL Foundation
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from casing import camel, title
from license import C_LICENSE_COMMENT
class Printer(object):
def __init__(self):
pass
def start_file(self)... | pass
def start_union(self, name):
pass
def union_option(self, option):
pass
def end_unio | n(self, name):
pass
|
ralsina/urssus | urssus/ui/Ui_configdialog.py | Python | gpl-2.0 | 1,833 | 0.006001 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'urssus/ui | /configdialog.ui'
#
# Created: Fri Feb 27 23:57:10 2009
# by: PyQt4 UI code generator 4.4.4
#
# WARNING! All changes made in | this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(600, 319)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/urssus.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.... |
arush0311/coala | coalib/results/Diff.py | Python | agpl-3.0 | 18,892 | 0 | import copy
import difflib
import logging
from coalib.results.LineDiff import LineDiff, ConflictError
from coalib.results.SourceRange import SourceRange
from coalib.results.TextRange import TextRange
from coala_utils.decorators import enforce_signature, generate_eq
@generate_eq('_file', 'modified', 'rename', 'delete... | ge and line_nr > 0:
result.append(self._file[line_nr-1])
elif linediff.change:
resu | lt.append(linediff.change[1])
if linediff.add_after:
result.extend(linediff.add_after)
current_line = line_nr
result.extend(self._file[current_line:])
return result
@property
def unified_diff(self):
"""
Generates a unified diff corresp... |
loic/django | tests/serializers/test_natural.py | Python | bsd-3-clause | 2,699 | 0.002223 | from __future__ import unicode_literals
from django.core import serializers
from django.db import connection
from django.test import TestCase
from .models import FKDataNaturalKey, NaturalKeyAnchor
from .tests import register_tests
class NaturalKeySerializerTests(TestCase):
pass
def natural_key_serializer_test... | ia the
# get_natural_key manager method).
james.delete()
# Deserialize and test.
books = list(serializers.deserialize(format, string_data))
self.assertEqual(len( | books), 2)
self.assertEqual(books[0].object.title, book1['title'])
self.assertEqual(books[0].object.pk, adrian.pk)
self.assertEqual(books[1].object.title, book2['title'])
self.assertIsNone(books[1].object.pk)
# Dynamically register tests for each serializer
register_tests(NaturalKeySerializerTests, 't... |
box/box-python-sdk | test/integration/mock_network.py | Python | apache-2.0 | 1,019 | 0.000981 | from unittest.mock import Mock
import requests
from boxsdk.network.default_network import DefaultNetworkResponse
from boxsdk.network.network_interface import Network
class MockNetwork(Network):
"""Mock implementation of the network interface for testing purposes."""
def __init__(self):
super().__init... | )
self._session = Mock(requests.Session)
self._retries = []
def request(self, method, url, access_token, **kwargs):
"""Base class override.
Make a mock network request using a mock requests.Session.
"""
return DefaultNetworkResponse(self._session.request(method, url,... | (self, delay, request_method, *args, **kwargs):
"""Base class override.
Retry immediately, recording the retry request.
"""
self._retries.append((delay, request_method, args, kwargs))
return request_method(*args, **kwargs)
@property
def session(self):
return self... |
antoinecarme/pyaf | tests/artificial/transf_Logit/trend_Lag1Trend/cycle_0/ar_/test_artificial_128_Logit_Lag1Trend_0__20.py | Python | bsd-3-clause | 260 | 0.088462 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.pr | ocess_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "L | ag1Trend", cycle_length = 0, transform = "Logit", sigma = 0.0, exog_count = 20, ar_order = 0); |
lucienfostier/gaffer | python/GafferSceneUI/DeleteOptionsUI.py | Python | bsd-3-clause | 2,461 | 0.009752 | ##########################################################################
#
# Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | N ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import Gaffer
import GafferScene
##########################################################################
# Metadata
#########################... | a.registerNode(
GafferScene.DeleteOptions,
"description",
"""
A node which removes options from the globals.
""",
plugs = {
"names" : [
"description",
"""
The names of options to be removed. Names should be
separated by spaces and can use Gaffer's standard wildcards.
""",
],
"invertNam... |
kmee/odoo-brazil-banking | l10n_br_financial_payment_order/models/__init__.py | Python | agpl-3.0 | 556 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import inherited_financial_document_type
from . import inherited_financial_move
from . import | bank_payment_line
from . import payment_line
from . import payment_mode
from . import payment_mode_type
# from . import hr_payslip
#
# Manter sempre operações abaixo de payment_order
#
from . import inherited_payment_order
from . import operacoes
from . import financial_retorno_ban | cario
from . import res_bank
from . import res_partner_bank
|
ntucllab/striatum | striatum/bandit/tests/base_bandit_test.py | Python | bsd-2-clause | 7,923 | 0.000505 | """Unit test for LinUCB
"""
from striatum.storage import (
MemoryHistoryStorage,
MemoryModelStorage,
MemoryActionStorage,
Action,
Recommendation,
)
class BaseBanditTest(object):
# pylint: disable=protected-access
def setUp(self): # pylint: disable=invalid-name
self.model_storage ... | self.assertEqual(len(recommendations), 1)
self.assertIn(recommendations[0].action.id,
self.action_storage.iterids())
self.assertEqual(
policy._history_storage.get_unrewarded_histor | y(history_id).context,
context)
def test_get_action_with_n_actions_none(self):
policy = self.policy
context = {1: [1, 1], 2: [2, 2], 3: [3, 3]}
history_id, recommendations = policy.get_action(context, None)
self.assertEqual(history_id, 0)
self.assertIsInstance(re... |
pazpi/ruTorrent-bot | handleTorrent.py | Python | gpl-2.0 | 1,580 | 0.002532 | # handleTorrent.py
# function to manipulate all the torrent part
import requests
from requests.auth import HTTPBasicAuth
import ClassUsers
# file use | d to store sensible data, like API key
def hash2magnet(hashlink):
magnet = "magnet:?xt=urn:btih:" + hashlink[2:-2]
return magnet
def addmagnet(torrent, chat_id):
try:
user = ClassUsers.load(chat_id)
# http://pazpi.ecc to replace with the setting from the user
url = user.host + ":... | ame == "NULL" or user.password == "NULL"):
try:
respond = requests.post(url, auth=HTTPBasicAuth(user.username, user.password))
# If server answer correctly answer successfully
if respond.status_code == 200:
return 'Magnet added successfully... |
ydkhatri/mac_apt | plugins/safari.py | Python | mit | 30,422 | 0.008809 | '''
Copyright (c) 2017 Yogesh Khatri
This file is part of mac_apt (macOS Artifact Parsing Tool).
Usage or distribution of this software/code is subject to the
terms of the MIT License.
'''
import io
import os
import logging
import nska_deserialize as nd
from plugins.helpers import macinfo
import plu... | safari_items.append(si)
except sqlite3.Error as ex:
log.exception ("Error while fetching row data")
except sqlite3.Error as ex:
log.exception ("Db cursor error while reading file " + source_path)
conn.close()
except sqlite3.Error as ex:
l... | name:
return v
return None
def ReadCloudTabsDb(conn, safari_items, source_path, user):
try:
conn.row_factory = sqlite3.Row
cursor = conn.execute(
"""SELECT device_name, tab_uuid, t.system_fields, title, url, is_showing_reader, is_pinned
FROM cloud_tab... |
zsoltdudas/lis-tempest | tempest/api/compute/admin/test_hypervisor.py | Python | apache-2.0 | 4,953 | 0 | # Copyright 2013 IBM Corporation
# 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 ... | ibuted under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class H... | vileges"""
@classmethod
def setup_clients(cls):
super(HypervisorAdminTestJSON, cls).setup_clients()
cls.client = cls.os_adm.hypervisor_client
def _list_hypervisors(self):
# List of hypervisors
hypers = self.client.list_hypervisors()['hypervisors']
return hypers
... |
tectronics/clusterpy | clusterpy/core/toolboxes/cluster/componentsAlg/dist2Regions.py | Python | bsd-3-clause | 1,076 | 0.001859 | # encoding: latin2
"""
Distance functions from an area to a region
"""
__author__ = "Juan C. Duque"
__credits__ = "Copyright (c) 2009-11 Juan C. Duque"
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "RiSE Group"
__email__ = "contacto@rise-group.org"
import numpy
import distanceFunctions
de... | """
sumAttributes = numpy.zeros(len(area.data))
if len(areaManager.areas[areaList[0]].data) - len(area.data) == 1:
for aID in areaList:
sumAttributes += numpy.array(areaManager.areas[aID].data[0: -1])
else:
for aI | D in areaList:
sumAttributes += numpy.array(areaManager.areas[aID].data)
centroidRegion = sumAttributes/len(areaList)
regionDistance = sum((numpy.array(area.data) - centroidRegion) ** 2)
return regionDistance
distanceStatDispatcher = {}
distanceStatDispatcher["Centroid"] = getDistance2Re... |
whav/hav | src/hav/apps/sources/filesystem/api/serializers.py | Python | gpl-3.0 | 4,892 | 0.000613 | import os
import stat
from mimetypes import guess_type
from rest_framework import serializers
from hav.utils.imaginary import generate_thumbnail_url, generate_srcset_urls
from hav.utils.exif import get_exif_data
import logging
logger = logging.getLogger(__name__)
def is_hidden(fn):
return fn.startswith(".")
c... |
url = serializers.SerializerMethodField()
isFile = serializers.SerializerMethodField()
grouping = serializers.SerializerMethodField()
def get_path(self, path):
return self._config.to_url_path(path)
def get_url(self, path):
return self.request.build_absolute_uri(self._config.to_ur... | mime(self, path):
return guess_type(path.name)[0]
def get_preview_url(self, path):
rel_path = path.relative_to(self.get_root()).as_posix()
return generate_thumbnail_url(rel_path)
def get_ingestable(self, _):
return True
def get_isFile(self, _):
return True
def... |
wcmitchell/insights-core | insights/parsers/chkconfig.py | Python | apache-2.0 | 6,449 | 0.001396 | """
ChkConfig - command ``chkconfig``
=================================
"""
from collections import namedtuple
from .. import Parser, parser
import re
from insights.specs import chkconfig
@parser(chkconfig)
class ChkConfig(Parser):
"""
A parser for working with data gathered from `chkconfig` utility.
Sam... | 5:on 6:off
... kdump 0:off 1:off | 2:off 3:on 4:on 5:on 6:off
... restorecond 0:off 1:off 2:off 3:off 4:off 5:off 6:off
... xinetd: 0:off 1:off 2:on 3:on 4:on 5:on 6:off
... rexec: off
... rlogin: off
... rsh: off
... |
egabancho/invenio-oauth2server | invenio_oauth2server/forms.py | Python | gpl-2.0 | 5,319 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... | alidators=[validators.DataRequired(), validators.URL()],
widget=widgets.TextInput(),
),
)
class ClientForm(ClientFormBase):
"""Client form."""
# Trick to make redirect_uris render in the bottom of the form.
redirect_uris = RedirectURIField(
label="Redirect URI... | or all "
"hosts except localhost (for testing purposes).",
validators=[RedirectURIValidator(), validators.DataRequired()],
default='',
)
is_confidential = fields.SelectField(
label=_('Client type'),
description=_(
'Select confidential if your appl... |
jlec/coot | pyrogen/tautomer.py | Python | gpl-3.0 | 25,160 | 0.00473 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
from itertools import tee, izip
import logging
from rdkit import Chem
from rdkit.Chem.rdchem import BondType, BondStereo, BondDir
__author__ = 'Matt Swain'
__email__ = 'm.swain@me.com'
__license__ = 'MIT'
log = logging.getLogger('tautomer')
BONDMAP = {'-': B... | utomer: %s', smiles)
score = 0
# Add aromatic ring scores
ssr = Chem.GetSymmSSSR(t)
for ring in ssr:
btypes = {t.GetBondBetweenAtoms(*pair).GetBondType() for pair in _pairw | ise(ring)}
elements = {t.GetAtomWithIdx(idx).GetAtomicNum() for idx in ring}
if btypes == {BondType.AROMATIC}:
log.debug('Score +100 (aromatic ring)')
score += 100
if elements == {6}:
log.debug('Score +150 (carbocyclic aromatic ... |
cpcloud/numba | numba/tests/serialize_usecases.py | Python | bsd-2-clause | 2,317 | 0.006905 | """
Separate module with function samples for serialization tests,
to avoid issues with __main__.
"""
import math
from numba import jit, generated_jit
from numba.core import types
@jit((types.int32, types.int32))
def add_with_sig(a, b):
return a + b
@jit
def add_without_sig(a, b):
return a + b
@jit(nopyth... | th_globals(x, **jit_args):
@jit(**jit_args)
def inner(y):
# Exercise a builtin function and a module-level constant
k = max(K, K + 1)
# Exercise two functions from another module, one accessed with
# dotted notation, one imported explicitly.
return math.hypot(x, y) + sqrt... | get_global_objmode(x):
return K * x
import numpy as np
import numpy.random as nprand
@jit(nopython=True)
def get_renamed_module(x):
nprand.seed(42)
return np.cos(x), nprand.random()
def closure_calling_other_function(x):
@jit(nopython=True)
def inner(y, z):
return other_function(x, y) + ... |
mikrosimage/OpenRenderManagement | src/octopus/dispatcher/webservice/job.py | Python | bsd-3-clause | 3,190 | 0.00094 | # -*- coding: utf8 -*-
from __future__ import absolute_import
"""
"""
__author__ = "Jerome Samson"
__copyright__ = "Copyright 2014, Mikros Image"
import logging
import time
try:
import simplejson as json
except ImportError:
import json
from tornado.web import HTTPError
from octopus.core.communication.http i... | .core.framework import ResourceNotFoundError
from octopus.dispatcher.webservice import DispatcherBaseResource
from octopus.dispatcher.model.filter.node import IFilterNode
from octopus.dispatcher.model import Task as DispatcherTask
from puliclient.model.job import | Job
from puliclient.model.task import Task
class JobNotFoundError(ResourceNotFoundError):
'''
Raised when a request is sent for a node that is not a attached to root.
'''
def __init__(self, node, *args, **kwargs):
ResourceNotFoundError.__init__(self, node=node, *args, **kwargs)
class JobQuer... |
bigswitch/horizon | openstack_dashboard/dashboards/project/volumes/backups/forms.py | Python | apache-2.0 | 4,401 | 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... | return restore
except Exception:
msg = _('Unable to restore bac | kup.')
redirect = reverse('horizon:project:volumes:index')
exceptions.handle(request, msg, redirect=redirect)
|
supermanue/distributedController | clusterController/DistributedTask.py | Python | gpl-2.0 | 3,026 | 0.045935 | '''
Created on Feb 22, 2013
@author: u5682
'''
from datetime import datetime
import os, sys, pickle
import subprocess
from time import sleep
import xml.dom.minidom
from xml.dom.minidom import Node
class DistributedTask(object):
'''
classdocs
'''
def __init__(self, fileName = None):
'''
Constructor
'''... | self.outputFiles:
outputFileList.append(outputF.text)
return outputFileList
def outputFilesExist(self):
for outputF in self.outputFiles:
requiredFile = self.taskInfo.workingDirectory + "/" + outputF.text
if not os.path.exists(requiredFile):
print("OUTPUT FILE MISSING: " + requiredFile)
... | e, tagName):
L = node.getElementsByTagName(tagName)
auxText = ""
for node2 in L:
for node3 in node2.childNodes:
if node3.nodeType == Node.TEXT_NODE:
auxText +=node3.data
return auxText
def obtainTextList(node, fatherTagName, sonTagName):
L = node.getElementsByTagName(fatherTagName)
auxTextArray = []
f... |
vilobhmm/delimiter | delimiter/drivers/sql.py | Python | apache-2.0 | 715 | 0 | # -*- coding: utf-8 -*-
#
# 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 ... | 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 t | he specific language governing permissions and limitations
# under the License.
from delimiter import engine
class SqlQuotaEngine(engine.QuotaEngine):
"""Engine based on sql primitives."""
|
tuergeist/HackerRank | contests/w23/gravity1.py | Python | gpl-3.0 | 3,805 | 0.017346 | import unittest
import math
def main():
# read input
nv = int(input().strip())
tree_raw = [ int(t) for t in input().strip().split(' ')]
nexperiments = int(input().strip())
exp = []
for _ in range(nexperiments):
exp.append( [ int(t) for t in input().strip().split(' ')] )
nodes =... | getD | istance(self):
total = 0
return total
def getForcesFor(self, n):
True
def __str__(self):
snext = ""
x = ""
if self.pre is None:
x = "Root: "
if self.children:
snext = " => {%s}" % ", ".join([str(c) for c in self.chi... |
cin/spark | python/pyspark/sql/readwriter.py | Python | apache-2.0 | 49,040 | 0.005669 | #
# 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... | prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None,
multiLine=None, all... | me`.
`JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default.
For JSON (one record per file), set the ``multiLine`` parameter to ``true``.
If the ``schema`` parameter is not specified, this function goes
through the input once to determine the input schem... |
bigmlcom/python | bigml/tests/create_sample_steps.py | Python | apache-2.0 | 2,068 | 0.002418 | # -*- coding: utf-8 -*-
#
# Copyright 2015-2022 BigML
#
# 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... | ample_name(step, name):
sample_name = world.sample['name']
eq_(name, sample_name)
#@step(r'I create a sample from a dataset$')
def i_create_a_sample_from_dataset(step):
dataset = world.dataset.get('resource')
resource = world.api.cr | eate_sample(dataset, {'name': 'new sample'})
world.status = resource['code']
eq_(world.status, HTTP_CREATED)
world.location = resource['location']
world.sample = resource['object']
world.samples.append(resource['resource'])
#@step(r'I update the sample name to "(.*)"$')
def i_update_sample_name(st... |
jimpick/jaikuengine | common/user.py | Python | apache-2.0 | 6,537 | 0.014227 | # Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in | writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See | the License for the specific language governing permissions and
# limitations under the License.
import datetime
import logging
from django.conf import settings
from django.core.cache import cache
import oauth.oauth as oauth
from common import api
from common import exception
from common import legacy
from common im... |
ieeeugrsb/ieeextreme8 | Teams/MineCoders/22_Binary Matrices/Solucion.py | Python | gpl-3.0 | 2,025 | 0.011369 | # -*- coding: utf-8 -*-
class Error:
def __init__(self, tipo, bad_rows):
self.tipo = tipo
self.bad_rows = bad_rows
def get_tipo(self):
return self.tipo
def get_bad_rows(self):
return self.bad_rows
def __str__(self):
if self.tipo == "1":... | uscando que no se cumpla alguna de las condiciones
for ri in range(n-1):
# Cada fila ha de cumplir dos condiciones
cumple1 = False
cumple2 = [False, ] * (n-ri-2)
for ci in range(m):
# Condición 1
if not cumple1:
cum... | rj in range(ri+1, n-1):
if not cumple2[rj-ri-1]:
cumple2[rj-ri-1] = (t[ri][ci] != t[ri+1][ci]) and (t[ri+1][ci] == t[rj][ci]) and (t[rj][ci] == t[rj+1][ci])
# Comprueba si ha habido errores
if not cumple1:
errores.append(Error("1", ri))
... |
viggates/nova | nova/api/openstack/compute/schemas/v3/quota_sets.py | Python | apache-2.0 | 1,547 | 0 | # Copyright 2014 NEC Corporation. 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 exp... | = {
'type': ['integer', 'string'],
'pattern': '^-?[0-9]+$',
# -1 is a flag value for unlimited
'minimum': -1
}
update = {
'type': 'object',
'properties': {
'type': 'object',
'quota_set': {
'properties': {
'instances': common_quota,
'co... |
sdss/marvin | tests/tools/test_map.py | Python | bsd-3-clause | 26,199 | 0.001527 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: Brian Cherinka, José Sánchez-Gallego, and Brett Andrews
# @Date: 2017-07-02
# @Filename: test_map.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: andrews
# @Last modified time: 2019-11-22 12:11:29
import ... | ne_gflux_ha']
assert ha is not None
assert ha.unit is not None
reordered_ha = np.moveaxis(ha, 0, -1)
assert reordered_ha.unit is not None
@marvin_test_if(mark='include', maps={'plateifu': '8485-1901',
'release': 'MPL-6',
| 'bintype': ['SPX']})
def test_get_spaxel(self, maps):
"""Tests `.Map.getSpaxel`."""
ha = maps['emline_gflux_ha']
spaxel = ha.getSpaxel(x=10, y=10, xyorig='lower')
assert spaxel is not None
assert spaxel.x == 10 and spaxel.y == 10
@marvin_tes... |
alexholcombe/movingCue | helpersAOHtargetFinalCueLocatn.py | Python | mit | 32,987 | 0.030072 | from __future__ import print_function
from __future__ import division
__author__ = """Alex "O." Holcombe""" ## double-quotes will be silently removed, single quotes will be left, eg, O'Connor
import numpy as np
import itertools #to calculate all subsets
from copy import deepcopy
from math import atan, pi, cos, sin, sqr... | gColor
cueTexEachRing.append( np.ones([gratingTexPix,gratingTexPix,3])*bgColor[0] )
if patchAngle > angleSegment:
msg='Error: pa | tchAngle requested ('+str(patchAngle)+') bigger than maximum possible ('+str(angleSegment)+') numUniquePatches='+str(numUniquePatches)+' numCycles='+str(numCycles);
print(msg); ppLog.error(msg)
oneCycleAngle = 360./numCycles
segmentSizeTexture = angleSegment/oneCycleAngle *gratingTexPix #I call it s... |
Orav/kbengine | kbe/src/lib/python/Lib/plat-linux/CDROM.py | Python | lgpl-3.0 | 5,242 | 0 | # Generated by h2py from /usr/include/linux/cdrom.h
CDROMPAUSE = 0x5301
CDROMRESUME = 0x5302
CDROMPLAYMSF = 0x5303
CDROMPLAYTRKIND = 0x5304
CDROMREADTOCHDR = 0x5305
CDROMREADTOCENTRY = 0x5306
CDROMSTOP = 0x5307
CDROMSTART = 0x5308
CDROMEJECT = 0x5309
CDROMVOLCTRL = 0x530a
CDROMSUBCHNL = 0x530b
CDROMREADMO... | CMD_READ_DISC_INFO = 0x51
GPCMD_READ_DVD_STRUCTURE = 0xad
GPCMD_READ_FORMAT_CAPACITIES = 0x23
GPCMD_READ_HEADER = 0x44
GPCMD_READ_TRACK_RZONE_INFO = 0x52
GPCMD_READ_SUBCHANNEL = 0x42
GPCMD_READ_TOC_PMA_ATIP = 0x43
GPCMD_REPAIR_RZONE_TRACK = 0x58
GPCMD_REPORT_KEY = 0xa4
GPCMD_REQUEST_SENSE = 0x03
GPCMD_RESERVE... | N = 0xba
GPCMD_SEEK = 0x2b
GPCMD_SEND_DVD_STRUCTURE = 0xad
GPCMD_SEND_EVENT = 0xa2
GPCMD_SEND_KEY = 0xa3
GPCMD_SEND_OPC = 0x54
GPCMD_SET_READ_AHEAD = 0xa7
GPCMD_SET_STREAMING = 0xb6
GPCMD_START_STOP_UNIT = 0x1b
GPCMD_STOP_PLAY_SCAN = 0x4e
GPCMD_TEST_UNIT_READY = 0x00
GPCMD_VERIFY_10 = 0x2f
GPCMD_WRITE_10 = ... |
popazerty/bh1 | lib/python/Tools/Transponder.py | Python | gpl-2.0 | 7,700 | 0.032987 | from enigma import eDVBFrontendParametersSatellite, eDVBFrontendParametersCable, eDVBFrontendParametersTerrestrial
from Components.NimManager import nimmanager
def ConvertToHumanReadable(tp, type = None):
ret = { }
if type is None:
type = tp.get("tuner_type", "None")
if type == "DVB-S":
ret["tuner_type"] = _("S... | atellite.FEC_3_4 : "3/4",
eDVBFrontendParametersSatellite.FEC_5_6 : "5/6",
eDVBFrontendParametersSatellite.FEC_7_8 : "7/8",
eDVBFrontendParam | etersSatellite.FEC_3_5 : "3/5",
eDVBFrontendParametersSatellite.FEC_4_5 : "4/5",
eDVBFrontendParametersSatellite.FEC_8_9 : "8/9",
eDVBFrontendParametersSatellite.FEC_9_10 : "9/10"}.get(tp.get("fec_inner", _("Auto")))
ret["modulation"] = {
eDVBFrontendParametersSatellite.Modulation_Auto : _("Auto"),
eDV... |
NorbertAgoston3pg/PythonLearning | DemoProject/src/input_output.py | Python | mit | 3,588 | 0.000279 | import os
# import json
# 1
def extract_users_from_file(file_name):
fn = os.path.join(os.path.dirname(__file__), file_name)
users = {}
with open(fn) as f:
for line in f:
row_elements = line.split(":")
if len(row_elements) > 0 and "#" not in row_elements[0]:
... | :
for line in f:
print("Original Line - {0}".format(line))
words_on_line = [s.lower() for s in line.split()]
table = str.maketrans("", "", "!?;.,1234567890'")
words_on_line = [s.translate(table) for s in words_on_line]
words += words_on_line
retur... | tistics
# 5.2
def word_with_max_occurence(info_dict):
max_occurence = -1
popular_word = ""
for key, value in info_dict.items():
if max_occurence < value:
max_occurence = value
popular_word = key
return popular_word
|
rodm/osx-vm-templates | scripts/support/plistutils.py | Python | mit | 1,198 | 0.001669 | '''plist utility functions'''
from Foundation import NSPropertyListSerialization
from Foundation import NSPropertyListXMLFormat_v1_0
from Foundation import NSPropertyListBinaryFormat_v1_0
class FoundationPlistException(Exception):
"""Basic exception for plist errors"""
pass
def write_plist(dataObject, pathn... | tion.
dataFromPropertyList_form | at_errorDescription_(
dataObject, plist_format, None))
if plistData is None:
if error:
error = error.encode('ascii', 'ignore')
else:
error = "Unknown error"
raise FoundationPlistException(error)
if pathname:
if plistData.writeToFile_atomically_... |
watchdogpolska/feder | feder/domains/migrations/0002_initial-domain.py | Python | mit | 454 | 0 | # Generated by Django 1.11.11 on 2018-08-27 21:51
from django.db import migrations
def update_domain_forward(apps, schema_editor):
"""Set site domain and name."""
Domain = apps.get_model("domains", "Domain")
Domain.objects.update_or_create(pk=1, name="fedrowanie.siecobywatelska.pl")
class Migration(mig... | (update_domain_forward)]
| |
rainaashutosh/MyTestRekall | rekall-core/rekall/registry.py | Python | gpl-2.0 | 5,183 | 0.000193 | # Rekall Memory Forensics
# Copyright (C) 2011
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Michael Cohen <scudette@gmail.com>
#
# ******************************************************
#
# * This program is free software; you can redistribute it and/or
# * modify it under the terms of the GNU General Public... | metaclasses."""
def __init__(cls, name, bases, env_dict):
super(MetaclassRegistry, cls).__init__(name, bases, env_dict)
cls._install_constructors(cls)
# Attach the classes dict to the baseclass and have all derived classes
# use the same one:
for base in base | s:
try:
cls.classes = base.classes
cls.classes_by_name = base.classes_by_name
cls.plugin_feature = base.plugin_feature
cls.top_level_class = base.top_level_class
break
except AttributeError:
cls.class... |
GunnerJnr/_CodeInstitute | Stream-2/Back-End-Development/1.Installing-Python/3.Using-IDLE/challenge-solution/vacation.py | Python | mit | 629 | 0.007949 | def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car | _cost(days):
total_car = days * 40
if days >= 7:
total_car -= 50
elif days >= 3:
total_car -= 20
return total_car
def trip_cost(city, days):
return rental_car_cost(days) + plane_ride_cost(city) + hotel_cost(days)
#invoke function here
print "The total cost for your trip com | es to : ", trip_cost("Tampa", 7)
|
gregorlarson/loxodo | src/frontends/ppygui/ppygui_winxp/converttonwin32.py | Python | gpl-2.0 | 1,317 | 0.009871 | import re
def convert(path):
f = open(path)
FUNCTION_RE = re.compile(r'(\S*?)\s*=\s*\w+dll.\w+.(\S*)')
import ctypes
dlls = \
|
{
'user32' : ctypes.windll.user32,
'shell32' : ctypes.windll.shell32,
'kernel32' : ctypes.windll.kernel32,
'gdi32' : ctypes.windll.gdi32,
'comctl32' : ctypes.windll.comctl32,
}
dlls_items = dlls.items()
buffer = []
for line in f.readlines():
... | ch:
function_name, function_w32_name = match.groups()
#print function_name, function_w32_name
dll_found = False
for dll_name, dll in dlls_items:
try:
getattr(dll, function_w32_name)
except AttributeError:
... |
ranji2612/leetCode | validPalindrome.py | Python | gpl-2.0 | 215 | 0.013953 | class Solution(object):
def isPalindrome(self, s):
| """
:type s: | str
:rtype: bool
"""
s = re.sub('[^a-zA-Z0-9]','',s.lower())
return True if s == s[::-1] else False |
fiete201/qutebrowser | tests/test_conftest.py | Python | gpl-3.0 | 1,648 | 0.000607 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | ithout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURP | OSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""Various meta-tests for conftest.py."""
import os
import sys
import warnings
import pytest
import qutebrowser
... |
thaim/ansible | test/units/modules/network/netvisor/test_pn_vrouter_pim_config.py | Python | mit | 2,463 | 0.002842 | # Copyright: (c) 2018, Pluribus Networks
# 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
from units.compat.mock import patch
from ansible.modules.network.netvisor import pn_vrouter_pim_... | n_nvos_commands.start()
self.mock_run_check_cli = patch('ansible.modules.network.netvisor.pn_vrouter_pim_config.check_cli')
self.run_check_cli = self.mock_run_check_cli.start()
| def tearDown(self):
self.mock_run_nvos_commands.stop()
self.mock_run_check_cli.stop()
def run_cli_patch(self, module, cli, state_map):
if state_map['update'] == 'vrouter-pim-config-modify':
results = dict(
changed=True,
cli_cmd=cli
)
... |
enthought/etsproxy | enthought/block_canvas/app/workbench_app/application_editor_manager.py | Python | bsd-3-clause | 125 | 0 | # proxy module
from __future__ import absolute_import
from blockcanvas.app.workbenc | h_app.application_editor_manager imp | ort *
|
tpokorra/pykolab | pykolab/xml/attendee.py | Python | gpl-3.0 | 9,223 | 0.002927 | import kolabformat
from pykolab.translate import _
from pykolab.translate import N_
from contact_reference import ContactReference
participant_status_labels = {
"NEEDS-ACTION": N_("Needs Action"),
"ACCEPTED": N_("Accepted"),
"DECLINED": N_("Declined"),
"TENTATIVE": N_("Tentatively Acc... | valid delegatee references found")
else:
crefs += self.get_delegated_ | to()
self.setDelegatedTo(list(set(crefs)))
def get_cutype(self, translated=False):
cutype = self.cutype()
if translated:
return self._translate_value(cutype, self.cutype_map)
return cutype
def get_delegated_from(self, translated=False):
delegators = []
... |
sphereflow/space_combat | src/pixel_collidable.py | Python | mit | 152 | 0.052632 | from collidable import *
from math_3d import *
class PixelCol | lidable( Collidable ) :
| def __init__(self) :
self.spm = None
self.r = None
|
IlyaGusev/PoetryCorpus | poetry/apps/accounts/forms.py | Python | apache-2.0 | 2,884 | 0.003124 | # -*- coding: utf-8 -*-
import re
from django.forms import ValidationError, ModelForm, Form, CharField, PasswordInput, TextInput
from django.utils.translation import | ugettext_lazy as _
from accounts.models import MyUser
class SignUpForm(ModelForm):
"""
Регистрационная форма.
"""
password = CharField(label=_('Пароль'), widget=PasswordInput(attrs={'placeholder': _('Пароль')}))
| password_repeat = CharField(label=_('Пароль ещё раз'), widget=PasswordInput(attrs={'placeholder': _('Пароль ещё раз')}))
class Meta:
model = MyUser
fields = ('email', 'organisation', 'last_name', 'first_name')
labels = {
'email': _('E-mail'),
'first_name': _('Имя'),... |
cpaulik/pyscaffold | src/pyscaffold/extensions/cookiecutter.py | Python | mit | 5,160 | 0 | # -*- coding: utf-8 -*-
"""
Extension that integrates cookiecutter templates into PyScaffold.
"""
from __future__ import absolute_import
import argparse
from ..api.helpers import register, logger
from ..api import Extension
from ..contrib.six import raise_from
class Cookiecutter(Extension):
"""Additionally appl... | """Create a Cookiecutter parser.
Args:
obj_ref (Extension): object reference to the actual extension
Returns:
NamespaceParser: parser for namespace cli argument
"""
class CookiecutterParser(argparse.Action):
"""Consumes the values provided, but also append the extension | function
to the extensions list.
"""
def __call__(self, parser, namespace, values, option_string=None):
# First ensure the extension function is stored inside the
# 'extensions' attribute:
extensions = getattr(namespace, 'extensions', [])
extensio... |
kaqfa/supervise_backend | progress/migrations/0004_auto_20161227_0542.py | Python | apache-2.0 | 1,355 | 0.002214 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-26 22:42
| from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrati | ons.Migration):
dependencies = [
('progress', '0003_auto_20161227_0401'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='student_task',
),
migrations.AddField(
model_name='studenttask',
name='comments',
... |
jabooth/menpo-archive | menpo/shape/mesh/__init__.py | Python | bsd-3-clause | 1,181 | 0.00254 | from cpptrimesh import CppTriMesh
from menpo.shape.mesh.base import TriMesh
from menpo.shape.mesh.coloured import ColouredTriMesh
from menpo.shape.pointcloud import PointCloud
class FastTriMesh(TriMesh, CppTriMesh):
"""A TriMesh with an underlying C++ data structure, allowing for efficient
iterations around m... | __init__(self, points, trilist)
TriMesh.__init__(self, points, trilist)
class PolyMesh(PointCloud):
"""A 3D shape which has a notion of a manifold built from piecewise planar
polyhedrons with vertices indexed from p | oints. This is largely a stub that
can be expanded later on if we need arbitrary polymeshes.
"""
def __init__(self, points, polylist):
PointCloud.__init__(self, points)
self.polylist = polylist
@property
def n_polys(self):
return len(self.polylist)
from .textured import T... |
tkw1536/GitManager | tests/repo/test_finder.py | Python | mit | 9,603 | 0 | import unittest
import unittest.mock
from GitManager.repo import finder, description
class TestFinder(unittest.TestCase):
""" Tests that the Finder() class works correctly """
@ | unittest.mock.patch("os.listdir")
@unittest.mock.patch("os.path")
@unittest.mock.patch("GitManager.repo.finder.Finder.get_from_path")
def test_find_recursive(self,
Finder_get_from_path: unittest.mock.Mock,
os_path: unittest.mock.Mock,
... | ecursive method works correctly """
# Setup all the mocks
links = ['/link']
dirs = ['/link', '/link/a', '/link/b', '/folder', '/folder/a',
'/folder/b']
listings = {
'/': ['link', 'file.txt', 'folder', 'folder.txt'],
'/link': ['a', 'a.txt', 'b', 'b... |
0x1306e6d/Baekjoon | baekjoon/1001.py | Python | gpl-2.0 | 191 | 0.005236 | """
1001 : A - B
URL : https://www.acmicpc.net/problem/1001
Input :
| 3 2
Output :
1
"""
input = input | ().split()
a = int(input[0])
b = int(input[1])
print(a - b) |
mdanielwork/intellij-community | python/testData/refactoring/rename/renameSelfAndParameterAttribute.py | Python | apache-2.0 | 460 | 0.00655 | class С:
def __init__(self, x=None):
if x is None:
self.foo = {
'A': {
'x': 0,
'y': 0,
},
}
else: # | init was given the previous state |
assert isinstance(x, С)
self.foo = {
'A': {
'x': x.f<caret>oo['A']['x'],
'y': x.foo['A']['y'],
},
} |
SauloAislan/ironic | ironic/objects/node.py | Python | apache-2.0 | 29,894 | 0 | # coding=utf-8
#
#
# 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 writi... | : self.uuid, 'msgs': ', '.join(invalid_msgs_list)})
raise exception.InvalidParameterValue(msg)
# NOTE(xek): We don't want to enable RPC on this call just yet. Remotable
# methods can be used in the future to replace current explicit RPC calls.
# Implications of calling new remote | procedures should be thought through.
# @object_base.remotable_classmethod
@classmethod
def get(cls, context, node_id):
"""Find a node based on its id or uuid and return a Node object.
:param context: Security context
:param node_id: the id *or* uuid of a node.
:returns: a :... |
stevemarple/AuroraWatchNet | software/magnetometer/sketches/RioLog/mkfwimage.py | Python | gpl-2.0 | 2,395 | 0.003758 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import binascii
import os
import struct
import subprocess
import aurorawatchnet as awn
import aurorawatchnet.message
# Parse command line options
parser = argparse.ArgumentParser(description='Make firmware image files')
parser.add_argumen... | ',
required=True,
help='firmware version',
metavar='version')
options = parser.parse_args()
if not os.path.exists(options.elf_filename):
print(options.elf_filename + ' does not exist')
os.sys.exit(1)
fw_path = os.path.dirname(options.elf_filename)
... | = os.path.join(fw_path, options.firmware_version + '.bin')
crc_filename = os.path.join(fw_path, options.firmware_version + '.crc')
if os.path.exists(bin_filename) or os.path.exists(crc_filename):
bin_filename
try:
cmd = ['avr-objcopy', '-O', 'binary', options.elf_filename, bin_filename]
subprocess.check_ca... |
edderick/E0_Python | pystruct.py | Python | mit | 1,485 | 0.03771 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import struct
import array
import os
def pack_neg(ID):
type = 0
id = ID
data = struct.pack('>II', type, id)
return data
def unpack_neg(data):
type,id = struct.unpack('>II', data)
return (type,id)
print "negotiation", unpack_neg(pack_neg(16))
d... |
#link key - | 128 bit
if len(RAND) != 16:
raise Exception("rand key not 128 bit")
if len(link_key) != 16:
raise Exception("link key not 128 bit")
type = 1
data = struct.pack('>II', type, clock)
r = array.array('B', RAND).tostring()
l = array.array('B', link_key).tostring()
return data + r + l
def unpack_ini... |
ryan-roemer/django-cloud-browser | setup.py | Python | mit | 2,485 | 0 | """Cloud browser package."""
from __future__ import with_statement
import os
from sys import version_info
from setuptools import find_packages, setup
from cloud_browser import __version__
###############################################################################
# Environment and Packages.
####################... | ) to string."""
cur_path = os.path.dirname(__file__)
exts = ("txt", "rst")
for ext in exts:
path = os.path.join(cur_path, ".".join((name, ext)))
if os.path.exists(path):
with open(path, "r") as file_obj:
return file_obj.read()
return ""
####################... | o-cloud-browser",
version=__version__,
description="Django Cloud Browser application.",
long_description=read_file("README"),
url="http://ryan-roemer.github.com/django-cloud-browser",
author="Ryan Roemer",
author_email="ryan@loose-bits.com",
classifiers=[
"Development Status :: 4 - B... |
csutherl/sos | sos/plugins/openstack_cinder.py | Python | gpl-2.0 | 3,713 | 0 | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This pr... | _option("log_size")
if self.get_option("all_log | s"):
self.add_copy_spec_limit("/var/log/cinder/",
sizelimit=self.limit)
else:
self.add_copy_spec_limit("/var/log/cinder/*.log",
sizelimit=self.limit)
def postproc(self):
protect_keys = [
"a... |
AlanZatarain/opencamlib | scripts/batchdropcutter_mtrush.py | Python | gpl-3.0 | 2,327 | 0.026214 | import ocl
import pyocl
import camvtk
import time
import vtk
import datetime
import math
if __name__ == "__main__":
print ocl.revision()
myscreen = camvtk.VTKScreen()
#stl = camvtk.STLSurf("../stl/gnu | _tux_mod.stl")
| stl = camvtk.STLSurf("../stl/mount_rush.stl")
myscreen.addActor(stl)
stl.SetWireframe()
stl.SetColor((0.5,0.5,0.5))
polydata = stl.src.GetOutput()
s = ocl.STLSurf()
camvtk.vtkPolyData2OCLSTL(polydata, s)
print "STL surface with", s.size(), "triangles read"
# define a cutter... |
ChantyTaguan/zds-site | zds/tutorialv2/factories.py | Python | gpl-3.0 | 8,840 | 0.002263 | from datetime import datetime
import factory
from zds.forum.factories import PostFactory, TopicFactory
from zds.gallery.factories import GalleryFactory, UserGalleryFactory
from zds.utils.factories import LicenceFactory, SubCategoryFactory
from zds.utils.models import Licence
from zds.tutorialv2.models.database import... | ic = beta_topic
publishable_content.save()
PostFactory(topic=beta_t | opic, position=1, author=publishable_content.authors.first())
beta_topic.save()
return publishable_content
class PublishedContentFactory(PublishableContentFactory):
"""
Factory that creates a PublishableContent and the publish it.
"""
@classmethod
def _generate(cls, create, at... |
deevarvar/myLab | baidu_code/soap_mockserver/spyne/test/test_sqlalchemy.py | Python | mit | 25,512 | 0.002861 | #!/usr/bin/env python
#
# spyne - Copyright (C) Spyne contributors.
#
# 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 the License, or (at your option) any later ve... | Class(TableModel):
__tablename__ = 'some_class'
__ | table_args__ = {"sqlite_autoincrement": True}
id = Integer32(primary_key=True, autoincrement=False)
s = Unicode(64, unique=True)
i = Integer32(64, index=True)
t = SomeClass.__table__
self.metadata.create_all() # not needed, just nice to see.
assert t.c.id.p... |
freedomtan/tensorflow | tensorflow/compiler/tests/qr_op_test.py | Python | apache-2.0 | 5,667 | 0.006529 | # 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 required by applica... | dom.uniform(
low=-1.0, high=1.0, size=np.prod(shape)).reshape(shape).astype(dtype)
x_np = rng()
if np.issubdtype(dtype, np.complexfloating):
x_np += rng() * dtype(1j)
return x_np
def _test(self, x_np, full_matrices, full_rank=True):
dtype = x_np.dtype
shape = | x_np.shape
with self.session() as sess:
x_tf = array_ops.placeholder(dtype)
with self.device_scope():
q_tf, r_tf = linalg_ops.qr(x_tf, full_matrices=full_matrices)
q_tf_val, r_tf_val = sess.run([q_tf, r_tf], feed_dict={x_tf: x_np})
q_dims = q_tf_val.shape
np_q = np.ndarray(q_d... |
gerald-yang/ubuntu-iotivity-demo | snappy/grovepi/pygrovepi/grove_vibration_motor.py | Python | apache-2.0 | 2,209 | 0.00498 | #!/usr/bin/env python
#
# GrovePi Example for using the Grove Vibration Motor (http://www.seeedstudio.com/wiki/Grove_-_Vibration_Motor)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? A... | rovepi.digitalWrite(vibra | tion_motor,0)
break
except IOError:
print ("Error")
|
kubernetes-client/python | kubernetes/client/models/v1beta1_flow_distinguisher_method.py | Python | apache-2.0 | 3,838 | 0 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | efinition.
"""
openapi_types = {
'type': 'str'
}
attribute_map = {
'type': 'type'
}
def __init__(self, type=None, local_vars_configuration=None): # noqa: E501
"""V1beta1FlowDistinguisherMethod - | a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._type = None
self.discriminator = None
self.type = type
@property
def t... |
jgcaaprom/android_external_chromium_org | tools/cygprofile/mergetraces.py | Python | bsd-3-clause | 8,029 | 0.011957 | #!/usr/bin/python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Use: ../mergetraces.py `ls cyglog.* -Sr` > merged_cyglog
""""Merge multiple logs files from different processes into a single log.
Give... | ace.
Merging will use timestamps (i.e. the first two columns of logged calls) to
create a single log that is an ordered trace of calls by both processes.
"""
import optparse
import string
import sys
def ParseLogLines(lines):
"""Parse log file lines.
Args:
lines: lines from log file produced by profiled run
... | :
5086e000-52e92000 r-xp 00000000 b3:02 51276 libchromeview.so
secs usecs pid:threadid func
START
1314897086 795828 3587:1074648168 0x509e105c
1314897086 795874 3587:1074648168 0x509e0eb4
1314897086 796326 3587:1074648168 0x509e0e3c
1314897086 796552 3587:1... |
Nikita1710/ANUFifty50-Online-Mentoring-Platform | project/fifty_fifty/webcore/migrations/0004_auto_20170428_0228.py | Python | apache-2.0 | 459 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-28 02:28
from __futu | re__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webcore', '0003_auto_20170427_1825'),
]
operations = [
migrations.RemoveField(
model_name=' | postad',
name='user',
),
migrations.DeleteModel(
name='PostAd',
),
]
|
netgroup/Dreamer-Mininet-Deployer | deployer_configuration_utils.py | Python | apache-2.0 | 1,593 | 0.011927 | #!/usr/bin/python
##############################################################################################
# Copyright (C) 2014 Pier Luigi Ventre - (Consortium GARR and University of Rome "Tor Vergata")
# Copyright (C) 2014 Giuseppe Siracusano, Stefano Salsano - (CNIT and University of Rome "Tor Vergata")
# www.... | 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 ... | mitations under the License.
#
# Deployer Configuration Utils.
#
# @author Pier Luigi Ventre <pl.ventre@gmail.com>
# @author Giuseppe Siracusano <a_siracusano@tin.it>
# @author Stefano Salsano <stefano.salsano@uniroma2.it>
#
#
from mininet.node import Node
def convert_port_name_to_number(oshi, port):
p = oshi.cmd("o... |
akrzos/cfme_tests | sprout/appliances/migrations/0010_appliance_power_state_changed.py | Python | gpl-2.0 | 511 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_l | iterals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('appliances', '0009_appliancepool_provider'),
]
operations = [
migrations.AddField(
| model_name='appliance',
name='power_state_changed',
field=models.DateTimeField(default=django.utils.timezone.now),
preserve_default=True,
),
]
|
rdhyee/oauth-flask-examples | evernote_sdk/evernote_oauth1a.py | Python | apache-2.0 | 3,694 | 0.001083 | # https://requests-oauthlib.readthedocs.org/en/latest/examples/real_world_example.html#real-example
import os
from flask import Flask, request, redirect, session, url_for
from flask.json import jsonify
# import hashlib
# import binascii
import evernote.edam.userstore.constants as UserStoreConstants
# import evernote... | tore()
# List all of the notebooks in the user's account
notebooks = note_store.listNotebooks()
return "<br/>" .join([notebook.name for notebook in notebooks])
if __name__ == "_ | _main__":
# This allows us to use a plain HTTP callback
os.environ['DEBUG'] = "1"
app.secret_key = os.urandom(24)
app.run(host="0.0.0.0", port=5000, debug=True)
|
queria/my-tempest | tempest/api/compute/v3/admin/test_quotas_negative.py | Python | apache-2.0 | 4,153 | 0 | # Copyright 2013 OpenStack Foundation
# Copyright 2014 NEC Corporation
# 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/licens... | self.create_test_server)
@test.attr(type=['negative', 'gate'])
def test_create_server_when | _memory_quota_is_full(self):
# Disallow server creation when tenant's memory quota is full
resp, quota_set = self.adm_client.get_quota_set(self.demo_tenant_id)
default_mem_quota = quota_set['ram']
mem_quota = 0 # Set the quota to zero to conserve resources
self.adm_client.updat... |
sergeyf/scikit-learn | sklearn/neighbors/_regression.py | Python | bsd-3-clause | 16,414 | 0.000244 | """Nearest Neighbor Regression."""
# Authors: Jake Vanderplas <vanderplas@astro.washington.edu>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Sparseness support by Lars Buitinck
# Multi-output support by Arnaud Joly <a.joly@ulg.a... |
must be square during fit. X may be a :term:`sparse graph`,
in which case only "nonzero" elements may be considered neighbors.
metric_params : dict, default=None
| Additional keyword arguments for the metric function.
n_jobs : int, default=None
The number of parallel jobs to run for neighbors search.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more de... |
shawncaojob/LC | PY/514_freedom_trial.py | Python | gpl-3.0 | 4,396 | 0.007962 | # 514. Freedom Trail
# DescriptionHintsSubmissionsDiscussSolution
# DiscussPick One
# In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedo | m Trail Ring", and use the dial to spell a specific keyword in order to open the door.
#
# Given a string ring, which represents the code | engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.
#
# Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in th... |
jalanb/jab | src/python/__init__.py | Python | mit | 48 | 0 | #! /user/bin/env | python
__version__ = '0.8.5 | 4'
|
iurykrieger96/morpy | app/api/services/UserMetadataService.py | Python | gpl-3.0 | 546 | 0.005495 | from database.db import db
import pymongo
class UserMetadataService(object):
def __init__(self):
self.user_meta = db.user_metadata
def get_active(self):
| return self.user_meta.find_one({'active': True})
def insert(self, user_meta_dict):
return self.user_meta.insert(user_meta_dict)
def disable_all(self):
return self.user_meta.update({'active': True}, {'$set': {'active': False}})
def get_all(self):
return self.user... | pymongo.DESCENDING)]) |
yutakakn/MyScript | Python/thanks.py | Python | bsd-3-clause | 534 | 0.009524 | #!/usr/bin/env python3
# - | *- coding: utf-8 -*-
from time import sleep
msg = [u'あ', u'り', u'が', u'う']
wait = 0.7
for m in msg:
print(m, end="", flush=True)
sleep(wait)
print('\b', end="", flush=True)
sleep(wait)
print(u'と', end="", flush=True)
sleep(wait)
print(u'う', end="", flush=True)
sleep(wait)
print("""
Q.「IEEE」の読みを答えよ
_人人人人人人人_
>イ... | \\ ( ‘-^ )
\ ̄ ̄ )
7 /
""") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.