code stringlengths 3 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int64 3 1.05M |
|---|---|---|---|---|---|
"""
sentry.utils.strings
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import base64
import codecs
import re
import six
import string
import zlib
from django.utils.encoding impor... | looker/sentry | src/sentry/utils/strings.py | Python | bsd-3-clause | 5,551 |
from datetime import timedelta, datetime
from config.config import CONFIG_VARS as cvar
import github_api
import send_response
import util
def manage_needs_reply_issue(repo_username, repo_id, issue):
if not issue:
return
number = issue.get('number')
if not number:
return
if not has_ne... | driftyco/ionitron-issues | tasks/needs_reply.py | Python | mit | 6,314 |
rooms = []
def shift_characters(room, shift_num):
shift_num = shift_num % 26
words = room.split('-')[0:-1]
new_words = []
for word in words:
new_word = []
index = 0
while index < len(word):
new_num = shift_num + ord(word[index])
if new_num > 122:
new_num = 122 - 97
new... | thatguyandy27/advent-of-code-2016 | problem8.py | Python | mit | 50,759 |
from django.db import models
class AbstractDnDModel(models.Model):
"""
A model for the Dnd tables
"""
class Meta:
abstract = True
app_label = 'webdnd' | Saevon/webdnd | dnd/models/abstract.py | Python | mit | 184 |
import argparse
from sqlalchemy import create_engine
from irco import models
from irco.logging import sentry
def main():
argparser = argparse.ArgumentParser('irco-init')
argparser.add_argument('-v', '--verbose', action='store_true')
argparser.add_argument('database')
args = argparser.parse_args()
... | GaretJax/irco | irco/scripts/init.py | Python | mit | 553 |
def ip_to_long(ip):
"""Converts a dotted-quad IP to a long.
Input: "192.168.0.1"
Output: 3232235521L
"""
import struct, socket
return struct.unpack(">L", socket.inet_aton(ip))[0]
def long_to_ip(long):
"""Converts a long IP to a dotted-quad string.
Input: 323223... | EBNull/py-wol | ip.py | Python | gpl-3.0 | 2,810 |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
class Parser:
"""
Abstract class of parser
"""
__metaclass__ = ABCMeta
def __init__(self, config):
"""
Initialized by config dictionary
"""
@abstractmethod
def find_headers(self, source):
"""
... | ukatama/seminarnotifier | seminarnotifier/seminarparser.py | Python | mit | 3,451 |
import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: sequence identifier
# value: neucleotide sequence
key = record[0]
value = record[1][:-... | okkhoy/pyDataAnalysis | dataAnalysis/take3/unique_trims.py | Python | mit | 1,422 |
# -*- coding: utf-8 -*-
"""Compute resolution matrix for linear estimators."""
# Authors: olaf.hauk@mrc-cbu.cam.ac.uk
#
# License: BSD-3-Clause
from copy import deepcopy
import numpy as np
from .. import pick_channels_forward, EvokedArray, SourceEstimate
from ..io.constants import FIFF
from ..utils import logger, ver... | bloyl/mne-python | mne/minimum_norm/resolution_matrix.py | Python | bsd-3-clause | 14,150 |
import json
from websocket import create_connection
class Connection(object):
def __init__(self, socket_url, api_key, client_name):
url = '{0}?clientName={1}'.format(socket_url, client_name)
self._conn = create_connection(
url=url,
header=["X-API-Key: {0}".format(api_key)]... | exitcodezero/picloud-client-python | picloud_client/connection.py | Python | mit | 515 |
from mock import Mock
from zeit.cms.checkout.helper import checked_out
from zeit.cms.testcontenttype.testcontenttype import ExampleContentType
import gocept.lxml.objectify
import zeit.cms.content.sources
import zeit.cms.interfaces
import zeit.cms.testing
import zope.interface
class ExampleSource(zeit.cms.content.sour... | ZeitOnline/zeit.cms | src/zeit/cms/content/tests/test_sources.py | Python | bsd-3-clause | 4,893 |
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class FenxiaoDealerRequisitionorderRefuseRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.dealer_order_id = None
self.reason = None
self.reason_detail = ... | CooperLuan/devops.notes | taobao/top/api/rest/FenxiaoDealerRequisitionorderRefuseRequest.py | Python | mit | 410 |
"""
Internal utility functions.
`htmlentitydecode` came from here:
http://wiki.python.org/moin/EscapingHtml
"""
from __future__ import print_function
import contextlib
import re
import sys
import time
try:
from html.entities import name2codepoint
unichr = chr
import urllib.request as urllib2
imp... | shepdl/stream-daemon | twitter_local/util.py | Python | mit | 3,963 |
from .search_products_request import SearchProductsRequest
from .search_products_schema import SearchProductsSchema
| willrp/willbuyer | backend/util/request/store/search_products_request/__init__.py | Python | mit | 116 |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
class ExternalPlugin(object):
schema = {'type': 'boolean'}
def on_task_input... | qvazzler/Flexget | tests/external_plugins/external_plugin.py | Python | mit | 508 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (C) 2012 OpenERP S.A. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | inovtec-solutions/OpenERP | openerp/addons/mail/mail_alias.py | Python | agpl-3.0 | 11,521 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Includes the HRV stitcher data source class
"""
import pandas as pd
import numpy as np
from scipy.io import loadmat
from scipy.interpolate import UnivariateSpline
from data_source import DataSource
from schema import Schema, Or, Optional
def _val(x, pos, label_bin):
... | janmtl/pypsych | pypsych/data_sources/hrvstitcher.py | Python | bsd-3-clause | 10,502 |
from abc import ABC, abstractmethod
from typing import Any, Dict, Type
import datahub.emitter.mce_builder as builder
from datahub.configuration.common import ConfigModel
from datahub.configuration.import_resolver import pydantic_resolve_key
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestio... | linkedin/WhereHows | metadata-ingestion/src/datahub/ingestion/transformer/add_dataset_properties.py | Python | apache-2.0 | 3,309 |
#!/usr/bin/python
#
# 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
# "Lice... | Karm/qpid-proton | examples/python/reactor/reactor-logger.py | Python | apache-2.0 | 1,713 |
import collections
import datetime
import json
import logging
import requests
logger = logging.getLogger(__name__)
__all__ = ['WaniKani', 'Radical', 'Kanji', 'Vocabulary']
WANIKANI_BASE = 'https://www.wanikani.com/api/v1.4/user/{0}/{1}'
def split(func):
# From http://stackoverflow.com/a/21767522/622650
de... | kfdm/wanikani | wanikani/core.py | Python | mit | 8,225 |
import cgi
import datetime
import urllib
import webapp2
import jinja2
import os
from google.appengine.ext import ndb
from google.appengine.api import users
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
def userproofs_key(email=None):
return ndb.Key('userp... | rcxking/pierce_logic_reloaded | appengine/main.py | Python | bsd-3-clause | 2,440 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import unittest
if sys.version_info >= (3, 0):
from unittest.mock import MagicMock, patch
from urllib.error import HTTPError
else:
from mock import MagicMock, patch
from urllib2 import HTTPError
from shellfoundry.exceptions import FatalError
from s... | QualiSystems/shellfoundry | tests/test_utilities/test_cloudshell_api/test_client_wrapper.py | Python | apache-2.0 | 3,577 |
#!/usr/bin/env python
import rospy
from std_msgs.msg import UInt16
def recv_buzzer(data):
rospy.loginfo(type(data))
rospy.loginfo(data.data)
if __name__ == '__main__':
rospy.init_node('buzzer')
rospy.Subscriber("buzzer", UInt16, recv_buzzer)
rospy.spin()
| Sourpomelo-Y6/pimouse_ros | scripts/buzzer2.py | Python | gpl-3.0 | 262 |
import codecs
import os
from hashlib import sha512
import config
# Generate random bytes for the salt
thebytes = os.urandom(100)
hexstr = str(codecs.encode(thebytes, 'hex'))
salt = hexstr[3:14]
# Hash the password with the salt
tohash = config.password + salt
tohash = tohash.encode("utf8")
hashed = sha512(tohash).h... | sixhobbits/jupyter-setup | hash_password.py | Python | apache-2.0 | 581 |
import sys
import time
from mpi4py.futures import MPICommExecutor
x0 = -2.0
x1 = +2.0
y0 = -1.5
y1 = +1.5
w = 1600
h = 1200
dx = (x1 - x0) / w
dy = (y1 - y0) / h
def julia(x, y):
c = complex(0, 0.65)
z = complex(x, y)
n = 255
while abs(z) < 3 and n > 1:
z = z**2 + c
n -= 1
retur... | mpi4py/mpi4py | demo/futures/run_julia.py | Python | bsd-2-clause | 1,252 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and Contributors
# License: MIT. See LICENSE
# import frappe
import unittest
class TestModuleOnboarding(unittest.TestCase):
pass
| frappe/frappe | frappe/desk/doctype/module_onboarding/test_module_onboarding.py | Python | mit | 197 |
#===============================================================================
#
# ELL.py
#
# This file is part of ANNarchy.
#
# Copyright (C) 2021 Helge Uelo Dinkelbach <helge.dinkelbach@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | vitay/ANNarchy | ANNarchy/generator/Projection/SingleThread/ELL.py | Python | gpl-2.0 | 8,508 |
import pytest
import audioset.util as util
@pytest.fixture()
def tf_bytestring():
return (b"\nv\n\x19\n\x06labels\x12\x0f\x1a\r\n\x0b\x00\xac\x02\xb4\x02"
b"\xb5\x02\xbc\x02\xc7\x02\n\x1b\n\x08video_id\x12\x0f\n\r\n\x0b"
b"rmLnozgTQMY\n\x1e\n\x12start_time_seconds\x12\x08\x12\x06\n\x04"
... | cosmir/dev-set-builder | tests/test_audioset_util.py | Python | mit | 1,694 |
from common import * # NOQA
from cattle import ApiError
RESOURCE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'resources/certs')
def test_create_cert_basic(client):
cert = _read_cert("san_domain_com.crt")
key = _read_cert("san_domain_com.key")
cert1 = clie... | Cerfoglg/cattle | tests/integration-v1/cattletest/core/test_cert.py | Python | apache-2.0 | 3,961 |
# https://www.w3resource.com/python-exercises/
# 54. Write a Python program to get the current username
import getpass
print(getpass.getuser())
| dadavidson/Python_Lab | Python-w3resource/Python_Basic/ex54.py | Python | mit | 145 |
#!/usr/bin/python
from __future__ import division
from __future__ import with_statement
import numpy
import os
import sys
import toolbox_basic
import toolbox_results
import toolbox_schematic_new as toolbox_schematic
pi = numpy.pi
class SimulationDirectory:
def __init__(self, path):
self.path = toolbox_bas... | roughhawkbit/robs-python-scripts | toolbox_idynomics.py | Python | mit | 13,823 |
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import api, SUPERUSER_ID
_logger = logging.getLogger(__name__)
def post_init_hook(cr, registry):
"""
Create a payment group for every existint payment
"""
env = api.Environment(cr, SUPERUSER_ID, {})
# payments... | ingadhoc/account-payment | account_payment_group/hooks.py | Python | agpl-3.0 | 1,366 |
#!/usr/bin/env python
#
# Generate pnSeed[] from Pieter's DNS seeder
#
NSEEDS=600
import re
import sys
from subprocess import check_output
def main():
lines = sys.stdin.readlines()
ips = []
pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):8334")
for line in lines:
m = patte... | shillingcoins/source | contrib/seeds/makeseeds.py | Python | mit | 708 |
# -*- encoding: utf-8 -*-
import pytest
from abjad import *
def test_scoretools_GraceContainer_01():
r'''Grace music is a container.
'''
gracecontainer = scoretools.GraceContainer(
[Note(0, (1, 16)), Note(2, (1, 16)), Note(4, (1, 16))])
assert systemtools.TestManager.compare(
graceco... | mscuthbert/abjad | abjad/tools/scoretools/test/test_scoretools_GraceContainer.py | Python | gpl-3.0 | 3,332 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 22:03:21 2017
@author: p
"""
import numpy as np
a=np.ones((33))
with open('/home/p/ABC/abc/Epics/test','a+') as f:
f.writelines(str(a))
A=str(a).replace('\n','')[1:-1:]+' '
print A
if True:
pass
elif True:
pass
... | iABC2XYZ/abc | Epics/testWrite.py | Python | gpl-3.0 | 322 |
'''
Created on Dec 26, 2012
@author: dstrauss
Copyright 2013 David Strauss
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... | daStrauss/sparseConv | src/lassoUpdate.py | Python | apache-2.0 | 5,313 |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | DolphinDream/sverchok | nodes/number/number_range.py | Python | gpl-3.0 | 8,373 |
# -*- coding: utf-8 -*-
# Copyright © 2012-2015 Roberto Alsina and others.
# 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 t... | agustinhenze/nikola.debian | nikola/plugins/command/bootswatch_theme.py | Python | mit | 4,155 |
import re
from functools import partial
from urllib.parse import urlencode
from geopy import exc
from geopy.geocoders.base import DEFAULT_SENTINEL, Geocoder
from geopy.location import Location
from geopy.util import logger
__all__ = ("What3Words", "What3WordsV3")
_MULTIPLE_WORD_RE = re.compile(
r"[^\W\d\_]+\.{1,... | geopy/geopy | geopy/geocoders/what3words.py | Python | mit | 14,218 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/load_balancer_py3.py | Python | mit | 5,752 |
import csv
import sys
import re
import datetime, time
csv.field_size_limit( 1000000 )
input_date_format = '%Y-%m-%d %H:%M:%S.%f'
input_date_format_alt = '%Y-%m-%d %H:%M:%S'
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
errors_file = sys.argv[3]
except IndexError:
errors_file = 'errors.csv'
print "%s ---... | zygmuntz/kaggle-jobs | test_jobs/job_times.py | Python | bsd-3-clause | 1,521 |
#!/usr/bin/env python
# vim: expandtab tabstop=4 shiftwidth=4
class InvalidBlogUrl(Exception):
def __str__(self):
return 'invalid blog url'
class FileExists(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return 'file exists: {0}'.format(repr(self.value... | Leryan/pytumblder | tumblder/exceptions.py | Python | bsd-2-clause | 682 |
#!/usr/bin/python
import sqlite3
import os.path
from os import makedirs
import sys
import re
from subprocess import call
import argparse
import textwrap
import csv
import StringIO
def list_tasks(dbname = "results.db"):
"""Return a list of all task names in a database"""
db = connect_db(dbname)
cursor = db... | UGent-HES/ConnectionRouter | vtr_flow/scripts/benchtracker/interface_db.py | Python | mit | 7,881 |
from django.test import TestCase
from diffanalysis.models import ActionReport
import osmdata
from osmdata.filters import IgnoreUsers, IgnoreElementsCreation, IgnoreElementsModification, AbstractActionFilter
from osmdata.importers import AdiffImporter
from osmdata.exporters import CSVExporter
from osmdata.models import... | Cartocite/osmada | workflows/tests.py | Python | agpl-3.0 | 5,183 |
#!/usr/bin/env python
# encoding: utf-8
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
dp = [0 for _ in range(n)]
ans = 0
if n >= 2 and s[0] == '(' and s[1] == ')':
dp[1] = 2
... | ShengRang/c4f | leetcode/longest-valid-parentheses.py | Python | gpl-3.0 | 931 |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from . impor... | superdesk/superdesk-core | superdesk/macros/imperial/length_nautical_miles_to_metric.py | Python | agpl-3.0 | 1,339 |
#!/usr/bin/env python
# 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 ma... | Peddle/hue | desktop/libs/notebook/src/notebook/decorators.py | Python | apache-2.0 | 3,947 |
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the ... | andrewsomething/digitalocean-indicator | digitalocean_indicator_lib/helpers.py | Python | gpl-3.0 | 3,770 |
# coding: utf-8
import matplotlib.pyplot as plt
def generate_boxplot(data, title, datasets_small_name):
fig = plt.figure(figsize=(8, 6))
bplot = plt.boxplot(data,
notch=False, # box instead of notch shape
# sym='rs', # red squares for outliers
... | owen198/kslab-atrisk-prediction | box_plot/func.py | Python | apache-2.0 | 660 |
#!/usr/bin/env python
import sys
from glob import glob
def ArgvToDict(argv_list=sys.argv, required=[], optional={}, verbose=True):
assert type(argv_list) == list and type(required) == list and type(optional) == dict
argv_dict = {}
if '-h' not in argv_list and '--help' not in argv_list:
if len(argv_list) > 1:
a... | yangwu91/fastx_subseq | Argv.py | Python | mit | 2,581 |
# Copyright (c) 2009, 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... | danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/Tools/Scripts/webkitpy/common/config/committers.py | Python | gpl-3.0 | 22,137 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2019-01-20 18:43
from __future__ import unicode_literals
import api.models
from django.db import migrations, models
import django.db.models.deletion
def fix_status(apps, schema_editor):
db_alias = schema_editor.connection.alias
AstronautType = apps.get... | ItsCalebJones/SpaceLaunchNow-Server | api/migrations/0061_astronaut_type.py | Python | apache-2.0 | 980 |
from django.core.management import call_command
from django.test import TestCase
from councils.tests.factories import CouncilFactory
class HomeViewTestCase(TestCase):
@classmethod
def setUpTestData(cls):
CouncilFactory(
council_id="X01",
identifiers=["X01"],
geogra... | DemocracyClub/UK-Polling-Stations | polling_stations/apps/data_finder/tests/test_views.py | Python | bsd-3-clause | 6,487 |
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://root:@127.0.0.1:3306/unrealknights', echo=True)
| HueyPark/Unreal-Knights | Server/Code/database/engine.py | Python | mit | 126 |
import numpy as np
import copy
def main(cl_reg_fit, max_mag):
"""
Reject stars beyond the maximum magnitude given.
"""
# Maximum observed (main) magnitude.
max_mag_obs = np.max(list(zip(*list(zip(*cl_reg_fit))[1:][2]))[0])
if max_mag == 'max':
# No magnitude cut applied.
cl_... | asteca/ASteCA | packages/best_fit/max_mag_cut.py | Python | gpl-3.0 | 1,440 |
# -*- coding: utf-8 -*-
# This file is part of OpenHatch.
# Copyright (C) 2010 Parker Phinney
# Copyright (C) 2011 Krzysztof Tarnowski (krzysztof.tarnowski@ymail.com)
# Copyright (C) 2009, 2010, 2011 OpenHatch, Inc.
# Copyright (C) 2011 Jairo E. Lopez
#
# This program is free software: you can redistribute it and/or m... | campbe13/openhatch | mysite/base/views.py | Python | agpl-3.0 | 10,109 |
from sympy.core import Add, S, C, sympify
from sympy.core.function import Function
from zeta_functions import zeta
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.miscellaneous import sqrt
###############################################################################
###########... | tovrstra/sympy | sympy/functions/special/gamma_functions.py | Python | bsd-3-clause | 6,564 |
import pytest
import sqlparse
from sqlparse import sql, tokens as T
def test_grouping_parenthesis():
s = 'select (select (x3) x2) and (y2) bar'
parsed = sqlparse.parse(s)[0]
assert str(parsed) == s
assert len(parsed.tokens) == 7
assert isinstance(parsed.tokens[2], sql.Parenthesis)
assert isin... | andialbrecht/sqlparse | tests/test_grouping.py | Python | bsd-3-clause | 22,563 |
# -*- coding: utf-8 -*-
import datetime as dt
from flask.ext.login import UserMixin
from fpage.database import db, CRUDMixin
from fpage.extensions import bcrypt
class User(UserMixin, CRUDMixin, db.Model):
__tablename__ = 'users'
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.... | Nikola-K/fpage | fpage/user/models.py | Python | apache-2.0 | 1,704 |
#!/usr/bin/env python3
#
# Copyright (c) 2021, The OpenThread Authors.
# 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
# ... | openthread/openthread | tests/scripts/thread-cert/border_router/MATN/MATN_09_DefaultBRMulticastForwarding.py | Python | bsd-3-clause | 6,962 |
from model import *
import parse
import tensorflow as tf
import numpy as np
import os
import random
import time
data, vocab = parse.get_vocab('essay')
onehot = parse.embed_to_onehot(data, vocab)
# hyperparameters
## learning rate for both discriminator and generator
learning_rate = 0.0001
## sequence length for RNN m... | huseinzol05/Deep-Learning-Tensorflow | hybrid/GAN-Sentence/main.py | Python | mit | 2,758 |
import os
import sys
import glob
import time
from subprocess import check_output
from collections import OrderedDict
from googleapiclient.discovery import build
from leviathan_config import GOOGLE_API_KEY, GOOGLE_CSE_ID, USER_AGENT, BASE_DIR
from utils import id_generator, timeout, printProgressBar
def google_sear... | leviathan-framework/leviathan | lib/sqli_scanner.py | Python | gpl-3.0 | 3,321 |
from __future__ import division
import abc
import numpy as np
import operator
from parameters import Parameter
"""Geometry classes."""
class Primitive(object):
"""Abstract class representing a primitive shape."""
__metaclass__ = abc.ABCMeta
points = None
"""Points associated with this primitive.""... | SeanDS/pygeosolve | pygeosolve/geometry.py | Python | gpl-3.0 | 4,739 |
# -*- coding: utf-8; -*-
"""
Copyright (C) 2013 - Arnaud SOURIOUX <six.dsn@gmail.com>
Copyright (C) 2012 - Ozcan ESEN <ozcanesen~gmail.com>
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 vers... | Sixdsn/terra-terminal | terra/VteObjectContainer.py | Python | gpl-3.0 | 2,212 |
# -*- coding: iso-8859-1 -*-
"""A lexical analyzer class for simple shell-like syntaxes."""
# Module and documentation by Eric S. Raymond, 21 Dec 1998
# Input stacking and error message cleanup added by ESR, March 2000
# push_source() and pop_source() made explicit by ESR, January 2001.
# Posix compliance, split... | nmercier/linux-cross-gcc | win32/bin/Lib/shlex.py | Python | bsd-3-clause | 11,429 |
from __future__ import unicode_literals
import re
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
from django.utils.encoding import force_text
from django.utils.ipv6 import is_valid_ipv6_address
from django.utils import six
from django.utils.s... | redhat-openstack/django | django/core/validators.py | Python | bsd-3-clause | 8,147 |
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 t... | schumi2004/NOT_UPDATED_Sick-Beard-Dutch | autoProcessTV/autoProcessTV.py | Python | gpl-3.0 | 3,185 |
import json
from django.http import HttpResponse
from django.template import loader, Template
from django.utils.datastructures import SortedDict
from urllib import urlencode
from tiote import forms, utils
def browse(request):
conn_params = utils.fns.get_conn_params(request)
# row(s) deletion request handling... | joskid/tiote | tiote/views/tbl.py | Python | mit | 9,570 |
# pylint: skip-file
#
# 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 "Licen... | iemejia/incubator-beam | sdks/python/apache_beam/ml/gcp/visionml_test.py | Python | apache-2.0 | 9,377 |
# Copyright (c) 2011 X.commerce, a business unit of eBay 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/LICENS... | vmthunder/nova | nova/tests/api/openstack/compute/contrib/test_floating_ip_pools.py | Python | apache-2.0 | 3,128 |
# -*- coding: utf-8 -*-
from __future__ import division
from materials.ec2 import EC2_materials
import os
from miscUtils import LogMessages as lmsg
__author__= "Ana Ortega (AO_O) "
__copyright__= "Copyright 2015, AO_O"
__license__= "GPL"
__version__= "3.0"
__email__= "ana.ortega@ciccp.es "
fckDat=[12,16,20,25,30,35,... | lcpt/xc | verif/tests/materials/ec2/test_EC2Concrete.py | Python | gpl-3.0 | 5,205 |
# Copyright 2015 Red Hat, 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 ... | openstack/tripleo-common | tripleo_common/image/exception.py | Python | apache-2.0 | 991 |
# proxy module
from __future__ import absolute_import
from scimath.units.smart_unit import *
| enthought/etsproxy | enthought/units/smart_unit.py | Python | bsd-3-clause | 93 |
import pytest
from pymoku.instruments import Oscilloscope
from pymoku import _oscilloscope
try:
from unittest.mock import patch, ANY
except ImportError:
from mock import patch, ANY
@pytest.fixture
def dut(moku):
with patch('pymoku._frame_instrument.FrameBasedInstrument._set_running'):
i = Oscill... | liquidinstruments/pymoku | tests/test_oscilloscope.py | Python | mit | 2,175 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2020-03-22 00:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... | carlosp420/VoSeq | public_interface/migrations/0001_initial.py | Python | bsd-3-clause | 11,529 |
from decimal import *
from matrix import Matrix
import copy
matrnr = 12345678
x7 = Decimal(int((matrnr / 1) % 10))
x6 = Decimal(int((matrnr / 10) % 10))
x5 = Decimal(int((matrnr / 100) % 10))
x4 = Decimal(int((matrnr / 1000) % 10))
x3 = Decimal(int((matrnr / 10000) % 10))
x2 = Decimal(int((matrnr / 100000) % 10))
x1 =... | DominikHorn/MatrixCalc | main.py | Python | mit | 1,197 |
from __future__ import print_function
import sys
import traceback
import urllib
import urllib2
import json
import re
import UserDict
from bs4 import BeautifulSoup
from untwisted.magic import sign
from runtime import later
import util
import runtime
import identity
STATE_FILE = 'state/qdbs.json'
BS4_PARSER = 'html5l... | joodicator/PageBot | page/qdbs.py | Python | lgpl-3.0 | 8,387 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
print('{1}:{0}'.format(2, 1))
# out: 1:2
# 精度控制
print('[{0:.3}]'.format(1/3))
# out: [0.333]
# 宽度控制
print('[{0:7}]'.format('hello'))
# out: [hello ]
# <codecell>
# 居左
print('[{0:<7.3}]'.format(1/3))
# out: [0.333 ]
# <codecell>
# 居右
print('[{0:>7.3}]'.format(1/3))
# out... | qrsforever/workspace | python/learn/base/string/format_.py | Python | mit | 1,644 |
""" Ban factory """
from smserver import models
from test.factories import base
class BanFactory(base.BaseFactory):
""" Classic user name """
class Meta(base.BaseMeta):
model = models.Ban
fixed = False
| ningirsu/stepmania-server | test/factories/ban_factory.py | Python | mit | 226 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# coding=utf-8
# Copyright 2012 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 NTT DOCOMO, INC.
# Copyright (c) 2011 University of Southern California / ISI
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
... | DirectXMan12/nova-hacking | nova/tests/virt/baremetal/test_driver.py | Python | apache-2.0 | 14,537 |
import os.path
import numpy
from scipy import interpolate
import inspect
# Hardcode the paths of the delay and gain files
file_dir=os.path.dirname(inspect.getfile(inspect.currentframe()))
MEAS_DELAYS=os.path.join(file_dir,'meas_delays.txt')
MEAS_GAINS=os.path.join(file_dir,'meas_gain_db.txt')
########################... | ryandougherty/mwa-capstone | MWA_Tools/mwapy/pb/measured_beamformer.py | Python | gpl-2.0 | 3,586 |
## simplexml.py based on Mattew Allum's xmlstream.py
##
## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2, or (... | sgala/gajim | src/common/xmpp/simplexml.py | Python | gpl-3.0 | 18,852 |
from subprocess import Popen, PIPE
from music_crawler import MusicCrawler
from playlist import Playlist
from song import Song
import sys
def play(mp3Path):
p = Popen(["mpg123", mp3Path], stdout=PIPE, stderr=PIPE)
return p
def stop(process):
process.kill()
print (10 * '-')
print ("Menu:")
print ("1. Ge... | pepincho/Python101-and-Algo1-Courses | Programming-101-v3/week4/1-Music-Library/music_player.py | Python | mit | 1,058 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Third Party Stuff
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('proposals', '0012_auto_20150709_0842'),
]
operations = [
migrations.AddField(
model_name='pr... | ChillarAnand/junction | junction/proposals/migrations/0013_proposalcomment_vote.py | Python | mit | 501 |
from __future__ import absolute_import
from django.contrib.admin.helpers import InlineAdminForm
from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
# local test models
from .admin import InnerInline
from .models import (Ho... | mixman/djangodev | tests/regressiontests/admin_inlines/tests.py | Python | bsd-3-clause | 19,368 |
# Copyright (C) 2010-2014 GRNET S.A.
#
# 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 program is distributed i... | grnet/synnefo | snf-astakos-app/astakos/quotaholder_app/commission.py | Python | gpl-3.0 | 4,226 |
#!/usr/bin/env python
import biggles
import numpy
#
# Create example 2-dimensional data set of two solitons colliding.
#
n = 64
x = numpy.arange( -10., 10., 20./n )
t = numpy.arange( -1., 1., 2./n )
z = numpy.zeros( (len(x),len(t)) )
for i in range(len(x)):
for j in range(len(t)):
z[i,j] = -12. * (3. + 4... | kstory8/biggles | examples/example8.py | Python | gpl-2.0 | 1,668 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013, Big Switch Networks, 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... | ikargis/horizon_fod | openstack_dashboard/api/fwaas.py | Python | apache-2.0 | 8,043 |
# Django settings for aeSupernova project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('admin', 'admin@gmail.com')
)
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '111.111.111.111']
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'users',
... | SuperNovaPOLIUSP/supernova | .django-settings.py | Python | agpl-3.0 | 7,079 |
#
# subunit: extensions to python unittest to get test results from subprocesses.
# Copyright (C) 2005 Robert Collins <robertc@robertcollins.net>
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project sour... | zarboz/XBMC-PVR-mac | tools/darwin/depends/samba/samba-3.6.6/lib/subunit/python/subunit/tests/test_details.py | Python | gpl-2.0 | 4,148 |
from hearthstone.enums import GameTag
from . import enums
class Manager(object):
def __init__(self, obj):
self.obj = obj
self.observers = []
def __getitem__(self, tag):
if self.map.get(tag):
return getattr(self.obj, self.map[tag], 0)
raise KeyError
def __setitem__(self, tag, value):
setattr(self.obj... | smallnamespace/fireplace | fireplace/managers.py | Python | agpl-3.0 | 7,099 |
# -*- coding: utf-8 -*-
"""
flask.ext.babelex
~~~~~~~~~~~~~~~~~
Implements i18n/l10n support for Flask applications based on Babel.
:copyright: (c) 2013 by Serge S. Koval, Armin Ronacher and contributors.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
impor... | initNirvana/Easyphotos | env/lib/python3.4/site-packages/flask_babelex/__init__.py | Python | mit | 22,503 |
#!/usr/bin/env python
__author__ = 'ilkin safarli'
import unittest
from Classifier import Classifier
class TestClassifier(unittest.TestCase):
def test_predict(self):
x = Classifier()
x.train()
predicted = x.predict("train", "directory")
actual = [(u'intermediate test', 2), (u'elementary test', 1), (u'advan... | kinimesi/rscore | unit_tests/test_Classifier.py | Python | apache-2.0 | 419 |
# coding: utf-8
from fabkit import env, sudo, filer
from fablib.python import Python
from fablib.base import SimpleBase
import utils
class Barbican(SimpleBase):
def __init__(self):
self.data_key = 'barbican'
self.data = {
}
self.services = [
'barbican-api',
]
... | fabrickit-fablib/openstack | barbican.py | Python | mit | 1,614 |
# Copyright (c) 2020, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
from erpnext.regional.address_template.setup import set_up_address_templates
def execute():
if frappe.db.get_value('Company', {'country': 'India'}, 'name'):
address_template = frappe.db.get_va... | frappe/erpnext | erpnext/patches/v12_0/update_address_template_for_india.py | Python | gpl-3.0 | 480 |
#Задача 5. Вариант 48
#Напишите программу, которая бы при запуске случайным образом отображала
#название одного из восьми категорий, на которые разделяются дорожные знаки в
#соответствии с Венской конвенцией о дорожных знаках и сигналах.
#Generalov K. A.
import random
a = random.choice(['Предупреждающие знаки.','Знак... | Mariaanisimova/pythonintask | PINp/2014/Generalov_K_A/task_5_48.py | Python | apache-2.0 | 1,127 |
import string
__doc__ = """
label = iolabel(itracer)
maps integers 1..3843 to length-two strings:
1..99 => 01..99
100..619 => 0a..0Z,1a..9Z
620..3843 => aa..ZZ
itracer = iolabel2num(label)
does the inverse.
"""
_iolabel_set10 = string.digits
_iolabel_set52 = string.ascii_letters
_iol... | altMITgcm/MITgcm66h | utils/python/MITgcmutils/MITgcmutils/ptracers.py | Python | mit | 1,321 |
import os
import socket
import config
def handle_cipher():
# msg is the orignal login msg
f = open('data/msg.txt', 'r')
msg = f.read()
f.close()
# write the cipher info, remove the header info
cipherText = msg[8:] # first 8 char is header
f = open('data/ciphertext.txt', 'w')
f.write(... | Plummy-Panda/MITM-V | mitm.py | Python | mit | 2,562 |
#! /usr/bin/python
# photoBooth1
# Samir Saidi, Momona Yamagami
import time
#import numpy as np
#import cv2
import picamera
import datetime
from time import strftime
#import
name2 = raw_input("Enter your NetID (ex. aaa1): ")
#Time1= strftime("%Y-%m-%d-%H_%M_%S")
with picamera.PiCamera() as camera:
camera.resolutio... | PictureYo-self/Picture-Yo-self | code/useless/capture.py | Python | gpl-2.0 | 698 |
"""
Django settings for hashhacks2 project.
Generated by 'django-admin startproject' using Django 1.11.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import... | papajijaat/HashHacks2.0-methOD | backend/hashhacks2/hashhacks2/settings.py | Python | mit | 3,183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.