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 |
|---|---|---|---|---|---|---|---|---|
MarkusH/talk-django-elasticsearch | blog/views.py | Python | bsd-3-clause | 2,259 | 0.001771 | from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render
from django.utils.timezone import now
from django.views.generic import DetailView, ListView
from .models import Article, Category
from .search import Article as SearchArticle
def index(request):
return redirect(reverse('bl... | 'author', 'category')
if not self.request.user.is_authenticated():
qs = qs.filter(is_public=True, publish_datetime__lte=now())
return qs
article_detail = ArticleDetailView.as_view()
class ArticleListView(ListView):
model = Article
def get_queryset(self):
qs = super(Articl... | datetime__lte=now())
return qs
article_list = ArticleListView.as_view()
class CategoryDetailView(DetailView):
model = Category
def get_context_data(self, **kwargs):
ctx = super(CategoryDetailView, self).get_context_data(**kwargs)
articles = self.object.article_set
if not self... |
aknh9189/code | physicsScripts/flotation/flotation.py | Python | mit | 1,813 | 0.04909 | # coding: utf-8
# In[1]:
import matplotlib.pyplot as plt #import modules
import matplotlib.patches as mpatches
import numpy as np
#get_ipython().magic(u'matplotlib inline') # set to inline for ipython
# In[2]:
water = [0,2,2,3,1.5,1.5,3,2,2,2,2,2.5,2] #arrange data from lab
alc = [0,2.5,2.5,2.5,2.5,3,2.5,2.5]
wei... | cent errors in densities kg/m^3
actualAlc = 789
pErrorWater = (abs(actualWater-densityWater)/actualWater) * 100 #find percent errors
pErrorAlc = (abs(actualAlc-densityAlc)/actualAlc) *100
print pErrorWater, pErrorAlc #print percent errors
# In[4]:
plt.figure() #create figure
plt.plot(weight,actWater,"o") # plot sca... | ,"o") #plot scatter of actcalc
plt.xlabel("Mass (g)") #add labels
plt.ylabel("Displacement (mL)") #add labels
plt.show() #show figure
# In[5]:
x = [0,1,2,3,4] ##TESTING np.polyfit
y = [0,0.5,1,1.5,2]
plt.figure()
plt.plot(y,x)
slope,inter = np.polyfit(y,x,1)
print slope
# In[9]:
densityAlc * (1/100.0**3) *1000 ##T... |
ep1cman/workload-automation | wlauto/utils/fps.py | Python | apache-2.0 | 4,301 | 0.00186 | # Copyright 2016 ARM Limited
#
# 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 writin... | _to_compose.sum()
frame_count = filtered_vsyncs_to_compose.size
if total_vsyncs:
fps = 1e9 * frame_count / (vsync_interval * total_vsyncs)
janks = self._calc_janks(filtered_vsyncs_to_compose)
not_at_vsync = self._calc_not_at_vsync(vsyncs_to_compose)
... | metrics
@staticmethod
def _calc_janks(filtered_vsyncs_to_compose):
"""
Internal method for calculating jank frames.
"""
pause_latency = 20
vtc_deltas = filtered_vsyncs_to_compose - filtered_vsyncs_to_compose.shift()
vtc_deltas.index = range(0, vtc_deltas.size)
... |
aequorea/gly | versions/gly19.py | Python | gpl-2.0 | 8,326 | 0.036872 | #!/usr/bin/python
# gly19.py -- protein glycosylator
# 2016.10.05 -- first version -- John Saeger
# gly19 -- 2017.5.27
# This version complains about incomplete sidechains. You must fix them up.
# I use pymol's mutate wizard to mutate a residue to itself.
# This version has a slightly more sophisticated solvent exp... | singles, pairs
def g | et_residues(fn, chain):
pdb = read_pdb(fn, chain)
residues = []
for l in pdb:
if int(l[5]) not in residues:
residues.append(int(l[5]))
return residues
def get_random_coil(input_file, chain, sheet, helix):
all = get_residues(input_file, chain)
coil = []
for res in all:
if res not in sheet and res not in ... |
kiyoto/statsmodels | statsmodels/datasets/cancer/data.py | Python | bsd-3-clause | 1,743 | 0.010901 | """Breast Cancer Data"""
__docformat__ = 'restructuredtext'
CO | PYRIGHT = """???"""
TITLE = """Breast Cancer Data"""
SOURCE = """
This is the breast cancer data used in Owen's empirical likelihood. It is taken from
Rice, J.A. Mathematical Sta | tistics and Data Analysis.
http://www.cengage.com/statistics/discipline_content/dataLibrary.html
"""
DESCRSHORT = """Breast Cancer and county population"""
DESCRLONG = """The number of breast cancer observances in various counties"""
#suggested notes
NOTE = """::
Number of observations: 301
Number... |
bitrat/alarm-fingerprint | AlarmGnuRadioFiles/Spectra_FileInput_To_BinarySlice_Local_only.py | Python | gpl-2.0 | 10,425 | 0.011415 | #!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Top Block
# Generated: Thu Oct 8 20:41:39 2015
##################################################
from datetime import datetime
from gnuradio import blocks
from gnuradio import digital
from gnuradio import e... | lf.decimation) / self.symb_rate))
def g | et_channel_spacing(self):
return self.channel_spacing
def set_channel_spacing(self, channel_spacing):
self.channel_spacing = channel_spacing
self.set_freq_offset((self.channel_spacing/2)+(self.channel_spacing * .1))
self.freq_xlating_fir_filter_xxx_0.set_taps((firdes.low_pass(1, sel... |
gliheng/Mojo | mojo/scripts/dump_blog_data.py | Python | gpl-2.0 | 1,041 | 0.001921 | import os
import sys
import transaction
from pyramid.paster import bootstrap
import transaction
from mojo.models import root_factory
from mojo.blog.models import get_blogroot
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % ( | cmd, cmd))
sys.exit(1)
def dump(root):
root = get_blogroot(root)
for blog in root.blogs.itervalues():
file = | open('data/' + blog.__name__ + '.md', 'w+')
file.write('---\n')
file.write('title: ' + blog.title.encode('utf-8'))
file.write('timestamp: ' + blog.timestamp.ctime())
file.write('tags: ' + str(blog.tags))
file.write('category: ' + blog.category)
file.write('---\n')
... |
pythonlittleboy/python_gentleman_crawler | util/ImageSimilar.py | Python | apache-2.0 | 3,416 | 0.005423 | from PIL import Image
from PIL import ImageDraw
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def make_regalur_image(img, size=(256, 256)):
return img.resize(size).convert('RGB')
# 几何转变,全部转化为256*256像素大小
def split_image(img, part_size=(64, 64)):
w, h = img.size
pw, ph = part_size
... | th=1)
| li.save(lf + '_lines.png')
'''
if __name__ == '__main__':
path = r'testpic/TEST%d/%d.JPG'
for i in xrange(1, 7):
print ('test_case_%d: %.3f%%' % (i, \
calc_similar_by_path('testpic/TEST%d/%d.JPG' % (i, 1),
... |
twizoo/semantic | semantic/test/testDates.py | Python | mit | 6,209 | 0.000161 | import datetime
import unittest
from freezegun import freeze_time
from semantic.dates import DateService
@freeze_time('2014-01-01 00:00')
class TestDate(unittest.TestCase):
def compareDate(self, input, target):
service = DateService()
result = service.extractDate(input)
self.assertEqual(t... | target_time)
self.compareDate(input, target_date)
def testNoTime(self):
input = "It's a very nice day."
target = None
self.compareTime(input, target)
|
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(TestDate)
unittest.TextTestRunner(verbosity=2).run(suite)
|
STIXProject/python-stix | stix/extensions/marking/simple_marking.py | Python | bsd-3-clause | 780 | 0.002564 | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import stix
from | stix.data_marking import MarkingStructure
import stix.bindings.extensions.marking.simple_marking as simple_marking_binding
@stix.register_extension
class SimpleMarkingStructure(MarkingStructure):
_binding = simple_marking_binding
_binding_class = simple_marking_binding.SimpleMarkingStructureType
_namespac... | )
def __init__(self, statement=None):
super(SimpleMarkingStructure, self).__init__()
self.statement = statement
|
KlubJagiellonski/pola-backend | pola/product/migrations/0015_remove_product_company.py | Python | bsd-3-clause | 330 | 0 | # Generated by Django 3.1.2 on 2021-01-13 17 | :11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0014_auto_20210113_1803'),
]
operations = [
migrations.RemoveField(
model_name='product',
| name='company',
),
]
|
tensorflow/tensorflow | tensorflow/python/data/experimental/kernel_tests/auto_shard_dataset_test.py | Python | apache-2.0 | 27,708 | 0.004547 | # Copyright 2019 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... | errors
from tensorflow.python.lib.io import python_io
from tensorflow.python.ops import parsing_ops
from tensorflow.python.ops import string_ops
from tensorflow.python.platform import test
def chunk(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
class AutoShardDatasetTest(tf_record_test_base.TFRecordTe... | :
super(AutoShardDatasetTest, self).setUp()
self._num_files = 10
self._num_records = 10
self._filenames = self._createFiles()
def getAllDatasetElements(self, dataset):
actual = []
next_fn = self.getNext(dataset)
while True:
try:
actual.append(self.evaluate(next_fn()))
... |
kaedroho/wagtail | wagtail/core/migrations/0027_fix_collection_path_collation.py | Python | bsd-3-clause | 906 | 0.003311 | # -*- coding: utf-8 -*-
from django.db import migrations
def set_collection_path_collation( | apps, schema_editor):
"""
Treebeard's path comparison logic can fail on certain locales such as sk_SK, which
sort numbers after letters. To avoid this, we explicitly set the collation for the
'path' column to the (non-locale-specific) 'C' collation.
See: https://groups | .google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ
"""
if schema_editor.connection.vendor == 'postgresql':
schema_editor.execute("""
ALTER TABLE wagtailcore_collection ALTER COLUMN path TYPE VARCHAR(255) COLLATE "C"
""")
class Migration(migrations.Migration):
dependencies = [
... |
SilentObserver/mangafox_rippers | mangafox_ripper.py | Python | lgpl-3.0 | 3,898 | 0.001283 | import os
import time
from urllib.parse import urljoin
import requests as rq
from bs4 import BeautifulSoup as bs
current_page_url = 0
page_soup = 0
def download_file(file_url, file_path):
if os.path.exists(file_path):
print(file_path, "already exists")
return False
i = 0
while i <= 30:
... | r(dir_path)
except:
print("Error creating", dir_path)
return False
return True
def prepare_file_path(base_path, image_name):
return base_path + image_name
def download_chapter(start_page, base_path=''):
global current_page_url
global page_soup
current_page_url... | chapter_name(start_page_soup) + "/"
page_soup = start_page_soup
page_link = start_page
while True:
image_url = get_image_url(page_soup)
# image_name = get_image_name(image_url)
image_count += 1
image_name = prepare_image_name(image_count)
... |
lowRISC/ot-sca | cw/cw305/ceca.py | Python | apache-2.0 | 23,127 | 0.001254 | #!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import argparse
import enum
import logging
import sys
import chipwhisperer as cw
import chipwhisperer.analyzer as cwa
import codetiming
import more_... | s)
cnt, sum_, sum_dev_prods = ray.get(done[0])
if running_cnt == 0:
running_sum_dev_prods = np.copy(sum_dev_prods)
running_sum = np.copy(sum_)
running_cnt += cnt
else:
running_sum_dev_prods += sum_dev_prods + (
(cnt * running_sum - ... | _cnt * sum_) ** 2
/ (cnt * running_cnt * (cnt + running_cnt))
)
running_sum += sum_
running_cnt += cnt
return running_sum / running_cnt, np.sqrt(running_sum_dev_prods / running_cnt)
def filter_noisy_traces(workers, mean_trace, std_trace, max_std):
"""Signals... |
spaceone/httoop | httoop/status/redirect.py | Python | mit | 3,015 | 0.021891 | # -*- coding: utf-8 -*-
from httoop.status.types import StatusException
from httoop.uri import URI
class RedirectStatus(StatusException):
u"""REDIRECTIONS = 3xx
A redirection to other URI(s) which are set in the Location-header.
"""
location = None
def __init__(self, location, *args, **kwargs):
if not isin... | "Content-Language",
"Content-Length", "Content-MD5", "Content-Range",
"Content-Type", "Expires", "Location"
)
class USE_PROXY(RedirectStatus):
code = 305
class TEMPORARY_REDIRECT(RedirectStatus):
u"""The request has not processed because the requested
resource is located at a different URI.
The client s... | t to the URI given in the Location-header.
for GET this is the same as 303 but for POST, PUT and DELETE it is
important that the request was not processed."""
code = 307
cacheable = True
class PERMANENT_REDIRECT(RedirectStatus):
code = 308
cacheable = True
|
archerda/gkcx | Admit/HttpRequestTool.py | Python | apache-2.0 | 2,421 | 0.004131 | import urllib.request
import urllib.parse
import json
from Admit import Data
# number:the number of a student
# birthday: the student's birthday, like 9301
# try_time: the request reconnect times when it broken.
def get_admit_result_by_number_and_birthday(number, birthday, try_times=3):
if try_times == 0:
... | request.add_header("Accept-Language", "zh-CN,zh;q=0.8")
| request.add_header("Cookie", cookie)
try:
f = urllib.request.urlopen(request, post_data)
r_data = f.read().decode('utf-8')
except:
get_admit_result_by_number_and_birthday(number, birthday, try_times - 1)
result_json = json.loads(r_data)
if result_json['flag'] == 1:
r... |
ltb-project/white-pages | docs/conf.py | Python | gpl-3.0 | 5,250 | 0 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | aster_doc, 'whitepages.tex', u'white-pages Documentation',
u'Clément OUDOT', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file | , name, description, authors, manual section).
man_pages = [
(master_doc, 'whitepages', u'white-pages Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target nam... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractXvvCpuMybluehostMe.py | Python | bsd-3-clause | 553 | 0.034358 |
def extractXvvCpuMybluehostMe(item):
'''
Parser fo | r 'xvv.cpu.mybluehost.me'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagnam... | l_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
VlachosGroup/VlachosGroupAdditivity | pgradd/RINGParser/Reader.py | Python | mit | 2,491 | 0 | # -*- coding: utf-8 -*-
from .. Error import RINGError
class Reader(object):
"""
Reader reads the parsed RING input, and returns the RDkit wrapper objects
in pgradd.RDkitWrapper.
Attributes
----------
ast : abstract syntax tree obtrained from parser
"""
def __init__(self, ast):
... | tree[0][0].name in ('Fragment',
'ReactionRule',
'EnumerationQuery')
# if fragment, molquery is returned
if tree[0][0].name | == 'Fragment':
from . MolQueryRead import MolQueryReader
self.type = 'MolQuery'
return MolQueryReader(tree[0][1:]).Read()
# if reaction rule, reacitonquery is returned
elif tree[0][0].name == 'ReactionRule':
from . ReactionQueryRead import ReactionQueryRe... |
Vayne-Lover/Effective | Python/Effective Python/item6.py | Python | mit | 211 | 0.085308 | #!/us | r/local/bin/python
a=['red','orange','yellow','green','blue','purple']
odds=a[::2]
evens=a[1::2]
print odds
print evens
x=b'abcdefg'
y=x[::-1]
print y
c=['a','b','c','d','e','f']
d=c[::2]
e=d[1:-1]
print | e
|
pragya1990/pox_whole_code | pox/misc/videoSlice1.py | Python | gpl-3.0 | 10,272 | 0.012169 | '''
Coursera:
- Software Defined Networking (SDN) course
-- Network Virtualization
Professor: Nick Feamster
Teaching Assistant: Arpit Gupta
'''
from pox.core import core
from collections import defaultdict
import pox.openflow.libopenflow_01 as of
import pox.openflow.discovery
import pox.openflow.spanning_tree
from ... | ('00-00-00-00-00-01', EthAddr('00:00:00:00:00:01'),
EthAddr('00:00:00:00:00:03'), 80): '00-00-00-00-00-03',
# """ Add your mapping logic here"""
('00-00-00-00-00-03', EthAddr('00:00:00:00:00:01'),
EthAdd... | EthAddr('00:00:00:00:00:01'), 80): '00-00-00-00-00-01',
('00-00-00-00-00-04', EthAddr('00:00:00:00:00:03'),
EthAddr('00:00:00:00:00:01'), 80): '00-00-00-00-00-03',
#port 22
('00-00-00-00-00-01... |
johnbachman/indra | indra/assemblers/tsv/assembler.py | Python | bsd-2-clause | 8,109 | 0.00037 | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import logging
from copy import copy
from indra.databases import get_identifiers_url
from indra.statements import *
from indra.util import write_unicode_csv
logger = logging.getLogger(__name__)
class TsvAssembler... | NKS', 'AG_B_STR',
'PMID', 'TEXT', 'IS_HYP', 'IS_DIRECT']
if add_curation_cols:
stmt_header = stmt_header + \
['AG_A_IDS_CORRECT', 'AG_A_STATE_CORRECT',
'AG_B_IDS_CORRECT', 'AG_B_ST | ATE_CORRECT',
'EVENT_CORRECT',
'RES_CORRECT', 'POS_CORRECT', 'SUBJ_ACT_CORRECT',
'OBJ_ACT_CORRECT', 'HYP_CORRECT', 'DIRECT_CORRECT']
rows = [stmt_header]
for ix, stmt in enumerate(self.statements):
# Complexes
... |
rbreitenmoser/snapcraft | snapcraft/tests/test_yaml.py | Python | gpl-3.0 | 25,577 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015-2016 Canonical Ltd
#
# 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 ... | eption.message,
'\'name\' is a required property')
@unittest.mock.patch('snapcraft.yaml.Config.load_plugin')
def test_invalid_yaml_invalid_name_as_number(self, mock_loadPlugin):
fake_logger = fixtures.FakeLogger(level=logging.ERROR)
self.useFixture(fake_logger)
... | gin: go
stage-packages: [fswebcam]
""")
with self.assertRaises(snapcraft.yaml.SnapcraftSchemaError) as raised:
snapcraft.yaml.Config()
self.assertEqual(raised.exception.message,
'1 is not of type \'string\'')
@unittest.mock.patch('snapcraft.yaml.Config.load... |
mschon314/pyamazonclouddrive | bin/acdsession.py | Python | mit | 3,367 | 0.017226 | #!/usr/bin/env python
#
# Copyright (c) 2011 anatanokeitai.com(sakurai_youhei)
#
# 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 right... | ssing (%s)\n"%m
parser.print_help()
exit(2)
if not opts.password:
opts.password = getpass.getpass()
if os.path.isdir(opts.session):
print > | >sys.stderr, "%s should not be directory."%s
exit(2)
if opts.verbose:
print >>sys.stderr, "Loading previous session...",
try:
s=pyacd.Session.load_from_file(opts.session)
if opts.verbose:
print >>sys.stderr, "Done."
except:
s=pyacd.Session()
if opts.verbose:
print >>sys.stderr... |
tensorflow/recommenders-addons | demo/embedding_variable/ev-keras-eager.py | Python | apache-2.0 | 3,467 | 0.002019 | import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
import tensorflow_datasets as tfds
import tensorflow_recommenders_addons as tfra
ratings = tfds.load("movielens/100k-ratings", split="train")
ratings = ratings.map(
lambda x: {
"movie_id": tf.strings.to_number(x["movie_i... | name="user-id-weights")
user_id_weights = tf.gather(user_id_weights, user_id_idx)
movie_id_val, movie_id_idx = np.unique(movie_id, return_inv | erse=True)
movie_id_weights = tf.nn.embedding_lookup(params=self.movie_embeddings,
ids=movie_id_val,
name="movie-id-weights")
movie_id_weights = tf.gather(movie_id_weights, movie_id_idx)
embeddings = tf.concat([user... |
python-thumbnails/python-thumbnails | tests/utils.py | Python | mit | 814 | 0 | # -*- coding: utf-8 -*-
import importlib
import json
import os
def has_installed(dependency):
try:
importlib.import_module(dependency)
return True
except ImportError:
return False
def is_tox_env(env):
if 'VIRTUAL_ENV' in os.environ:
return env in os.environ['VIRTUAL_ENV']... | f has_django():
return has_installed('django')
|
def has_pillow():
return has_installed('PIL.Image')
def has_redis():
return has_installed('redis')
class OverrideSettings(object):
def __init__(self, **settings):
self.settings = settings
def __enter__(self):
os.environ['overridden_settings'] = json.dumps(self.settings)
def _... |
BartDeCaluwe/925r | ninetofiver/serializers.py | Python | gpl-3.0 | 422 | 0 | """ninetofiver serializers."""
from django.contrib.auth import models as auth_models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django_countries.serializers import CountryFieldMixin
from django.db.models import Q
from rest_framework | import serializ | ers
import logging
import datetime
from ninetofiver import models
logger = logging.getLogger(__name__)
|
mrawls/apVisitproc | apvisitproc/tests/test_despike.py | Python | mit | 2,736 | 0.002558 | import numpy as np
from apvisitproc import despike
import pytest
import os
DATAPATH = os.path.dirname(__file__)
FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt')
FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt')
@pytest.fixture
def wave_spec_generate():
'''
Read in three small chunks... | assert list(np.sort(wave)) == list(wave)
assert all(np.equal(np.sort(wave), wave))
def test_simpledespike(wave_spec_generate):
'''
spike condition is met at pixels 15, 16, 17 and 18
so indices 9 through 24, inclusive, should be removed
'''
wave, spec = wave_spec_generate[0], wave_spec_... | newspec = despike.simpledespike(wave, spec, delwindow=6,
stdfactorup=0.7, stdfactordown=3,
plot=False)
assert len(newwave) == len(newspec)
assert len(newwave) <= len(wave)
assert len(newspec) <= len(spec)
assert al... |
alex-dot/upwdchg | tests/python-tokenreader-test.py | Python | gpl-3.0 | 7,822 | 0.003328 | #!/usr/bin/env python3
# -*- mode:python; tab-width:4; c-basic-offset:4; intent-tabs-mode:nil; -*-
# ex: filetype=python tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent smartindent
#
# Universal Password Changer (UPwdChg)
# Copyright (C) 2014-2018 Cedric Dufour <http://cedric.dufour.name>
# Author: Cedric Du... | lf.assertIn('timestamp', self.oToken.keys())
self.assertRegex(self.oToken['timestamp'], '^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z$')
def testUsername(self):
self.assertIn('username', self.oToken.keys())
self.assertEqua | l(self.oToken['username'], 'test-Benützername')
def testPasswordNew(self):
self.assertIn('password-new', self.oToken.keys())
self.assertEqual(self.oToken['password-new'], 'test-Paßw0rt_new')
def testPasswordNonce(self):
self.assertIn('password-nonce', self.oToken.keys())
self.a... |
michkol/prx | prx_aplikacja/apps.py | Python | gpl-3.0 | 258 | 0.003876 | from django.apps import AppConfig
from django.template.base import add_to_builtins
class PrxAppConfig(AppConfig):
| name = 'p | rx_aplikacja'
verbose_name = 'prx_aplikacja'
def ready(self):
add_to_builtins('prx_aplikacja.templatetags.tagi')
|
blazek/lrs | lrs/ui/lrscombomanagerbase.py | Python | gpl-2.0 | 5,538 | 0.002167 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
LrsPlugin
A QGIS plugin
Linear reference system builder and editor
-------------------
begin : 2013-10-02
copyright ... | *
********************************** | *****************************************/
"""
# Import the PyQt and QGIS libraries
from ..lrs.utils import *
from qgis.PyQt.QtGui import *
# combo is QComboBox or list of QComboBox
class LrsComboManagerBase(QObject):
def __init__(self, comboOrList, **kwargs):
super(LrsComboManagerBase, self).__init__()
... |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/metacritic.py | Python | gpl-3.0 | 2,280 | 0.025877 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
fix_xml_ampersands,
)
class MetacriticIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?metacritic\.com/.+?/trailers/(?P<id>\d+)'
_TESTS = [{
'url': 'http://www.metacritic.com/game/playstation-4/infamo... | o = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id,
video_id, 'Downloading info xml' | , transform_source=fix_xml_ampersands)
clip = next(c for c in info.findall('playList/clip') if c.find('id').text == video_id)
formats = []
for videoFile in clip.findall('httpURI/videoFile'):
rate_str = videoFile.find('rate').text
video_url = videoFile.find('filePath').text
formats.append({
'url': vi... |
softlayer/stack-dev-tools | platforms/softlayer.py | Python | mit | 4,908 | 0 | from os import getenv
from time import time, sleep
from core import Platform, Instance
from SoftLayer import Client
from SoftLayer.CCI import CCIManager
from paramiko import SSHClient
class _SuppressPolicy(object):
def missing_host_key(self, client, hostname, key):
pass
class CCIPlatform(Platform):
... | sleep_secs=2)
def _cci_await_delete(self, cci):
| return self._cci_await_state(cci,
lambda c: c and 'id' in c,
sleep_secs=2)
def _get_cci_root_password(self, cci):
passwords = self._manager.get_instance_passwords(cci['id'])
password = None
for p in passwords:
... |
Elima85/bccfccraycaster | data/scripts/loadvolume.py | Python | gpl-2.0 | 213 | 0.004695 | # Sample script for loading volume data.
impor | t voreen
# usage: voreen.loadVolume(filepath, [name of VolumeSource processor])
voreen.loadVolume(voreen.getBasePath() + "/d | ata/volumes/nucleon.dat", "VolumeSource")
|
olga121/Selenium_Webdriver | test_sticker.py | Python | apache-2.0 | 496 | 0.010081 | import pytest
from selenium import webdriver
@pytest.fixture
def driver(request):
wd = webdriver.Chrome()
request.addfinalizer(wd.qui | t)
return wd
def test_example(driver):
driver.get("http://localhost/litecart/")
driver.implicitly_wait(10)
sticker_number = len(driver.find_elements_by_xpath("//div[contains(@class,'sticker')]"))
product_number = len(driver.fin | d_elements_by_xpath("//*[contains(@href,'products')]"))
assert sticker_number == product_number
|
alfa-addon/addon | plugin.video.alfa/servers/youdbox.py | Python | gpl-3.0 | 822 | 0.008516 | # -*- coding: utf-8 -*-
# import | re
from core import httptools
fro | m core import scrapertools
from platformcode import logger
import codecs
def get_video_url(page_url, video_password):
logger.info("(page_url='%s')" % page_url)
video_urls = []
data = httptools.downloadpage(page_url).data
list = scrapertools.find_single_match(data, 'var urK4Ta4 = ([^\]]+)').replace(... |
birkenfeld/elpy | elpy/tests/test_server.py | Python | gpl-3.0 | 14,270 | 0 | # coding: utf-8
"""Tests for the elpy.server module"""
import os
import tempfile
import unittest
import mock
from elpy import rpc
from elpy import server
from elpy.tests import compat
from elpy.tests.support import BackendTestCase
import elpy.refactor
class ServerTestCase(unittest.TestCase):
def setUp(self):
... | nd, JediBackend):
self.srv.rpc_init({"project_root": "/project/root",
"backend": "jedi"})
JediBackend.assert_called_with("/project/root")
@mock.patch("elpy.jedibackend.JediBackend")
@mock.patch("elpy.ropebackend.RopeBackend")
def test_should_use_rope_if_available... | ckend.return_value.name = "rope"
JediBackend.return_value.name = "jedi"
self.srv.rpc_init({"project_root": "/project/root",
"backend": "rope"})
self.assertEqual("rope", self.srv.backend.name)
@mock.patch("elpy.jedibackend.JediBackend")
@mock.patch("elpy.rope... |
TsinghuaX/edx-platform | common/lib/xmodule/xmodule/tests/test_crowdsource_hinter.py | Python | agpl-3.0 | 22,068 | 0.001042 | """
Tests the crowdsourced hinter xmodule.
"""
from mock import Mock, MagicMock
import unittest
import copy
from xmodule.crowdsource_hinter import CrowdsourceHinterModule
from xmodule.vertical_module import VerticalModule, VerticalDescriptor
from xblock.field_data import DictFieldData
from xblock.fragment import Frag... | user_voted=None,
moderate=None,
mod_queue=None):
"""
A factory method for making CHM's
"""
# Should have a single child, but it doesn't matter what that child is
field_data = {'data': CHModuleFactory.sample_problem_xml, 'children': [None]}
... | |
pydcs/dcs | dcs/terrain/thechannel.py | Python | lgpl-3.0 | 165,474 | 0.006986 | # flake8: noqa
import dcs.mapping as mapping
from dcs.terrain.terrain import Airport, Runway, ParkingSlot, Terrain, MapView
from .projections.thechannel import PARAMETERS
class Abbeville_Drucat(Airport):
id = 1
name = "Abbeville Drucat"
tacan = None
unit_zones = []
civilian = False
slot_versio... | pend(ParkingSlot(
crossroad_idx=15, position=mapping.Point(-80572.734375, 17265.576171875, self._terrain), large=False, heli=True,
airplanes=True, slot_name='05', length=26.0, width=22.0, height=11.0, shelter=False))
self.parking_s | lots.append(ParkingSlot(
crossroad_idx=16, position=mapping.Point(-80796.953125, 17540.17578125, self._terrain), large=False, heli=True,
airplanes=True, slot_name='08', length=26.0, width=22.0, height=11.0, shelter=False))
self.parking_slots.append(ParkingSlot(
cr... |
anhaidgroup/py_entitymatching | py_entitymatching/feature/autofeaturegen.py | Python | bsd-3-clause | 34,022 | 0.001323 | """
This module contains functions for auto feature generation.
"""
import logging
import pandas as pd
import six
from py_entitymatching.utils.validation_helper import validate_object_type
from IPython.display import display
import py_entitymatching as em
import py_entitymatching.feature.attributeutils as au
import ... | `r_attr_types` is not of type
python dictionary.
AssertionError: If `attr_corres` is not of type
python dictionary.
AssertionError: If `sim_funcs` is not of type
python dictionary.
AssertionError: If `tok_funcs` is not of type
python dictionary.
... | same as mentioned
in the `l_attr_types`/`r_attr_types` and `attr_corres`.
Examples:
>>> import py_entitymatching as em
>>> A = em.read_csv_metadata('path_to_csv_dir/table_A.csv', key='ID')
>>> B = em.read_csv_metadata('path_to_csv_dir/table_B.csv', key='ID')
>>> match_t... |
saebyn/django-classifieds | classifieds/forms/fields.py | Python | bsd-3-clause | 1,278 | 0.005477 |
from django.forms import CharField, ValidationError
from django.forms.fields import EMPTY_VALUES
import re, string
class TinyMCEField(CharField):
def clean(self, value):
"Validates max_length and min_length. Returns a Unicode object."
if value in EMPTY_VALUES:
return u''
... | ng.replace(stripped_value, '&', '&')
stripped_value = str | ing.replace(stripped_value, '\n', '')
stripped_value = string.replace(stripped_value, '\r', '')
value_length = len(stripped_value)
value_length -= 1
if self.max_length is not None and value_length > self.max_length:
raise ValidationError(self.error_messages['max_leng... |
anhstudios/swganh | data/scripts/templates/object/tangible/scout/trap/shared_trap_webber.py | Python | mit | 444 | 0.047297 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DO | NE IMPROPE | RLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/scout/trap/shared_trap_webber.iff"
result.attribute_template_id = -1
result.stfName("item_n","trap_webber")
#### BEGIN MODIFICATIONS ####
#### EN... |
mmllnr/plugin.video.xstream | resources/lib/gui/hoster.py | Python | gpl-3.0 | 8,657 | 0.005198 | # -*- coding: utf-8 -*-
from resources.lib.handler.jdownloaderHandler import cJDownloaderHandler
from resources.lib.download import cDownload
from resources.lib.handler.hosterHandler import cHosterHandler
from resources.lib.gui.gui import cGui
from resources.lib.gui.guiElement import cGuiElement
from resources.lib.hand... | ream wurde hinzugefügt', 5);
return
oGui.showError('Playlist', 'Stream wurde nicht hinzugefügt', 5);
return False
#except:
# logger.fatal('could not load plugin: ' + sHosterFileName)
#oGui.setEndOfDirectory()
def download(self):
oGui = cGui()
... | = oInputParameterHandler.getValue('bGetRedirectUrl')
sFileName = oInputParameterHandler.getValue('sFileName')
if (bGetRedirectUrl == 'True'):
sMediaUrl = self.__getRedirectUrl(sMediaUrl)
logger.info('call download: ' + sMediaUrl)
sLink = urlresolver.resolve(sMediaUrl)
... |
schwardo/chicago47-sms | tests/test_core.py | Python | mit | 2,358 | 0.004665 | import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from datetime import datetime
from datetime import date
from twilio.rest.resources import parse_date
from twilio.rest.resources import transform_params
from twilio.rest.resources import convert_keys
from twilio.rest.reso... | 3, "Activated": False}
ed = {"YOU":3, "Activated": "false"}
self.assertEquals(transform_params(d), ed)
def test_normalize_dates(self):
@normalize_dates
def foo(on=None, before=None, after=None):
return {
"on": on,
"before": before,
... | ))
self.assertEquals(d["on"], "2009-10-10")
self.assertEquals(d["after"], "2009-10-10")
self.assertEquals(d["before"], "2009-10-10")
def test_convert_case(self):
self.assertEquals(convert_case("from_"), "From")
self.assertEquals(convert_case("to"), "To")
self.assert... |
skyoo/jumpserver | apps/terminal/migrations/0025_auto_20200810_1735.py | Python | gpl-2.0 | 543 | 0.001842 | # Generated by Django 2.2.13 on 2020-08-10 09:35
from django.db import migrati | ons, models
class Migration(migrations.Migration):
dependencies = [
('terminal', '0024_auto_20200715_1713'),
]
operations = [
migrations.AlterField(
model_name='session',
name='protocol',
field=models.CharField(choices=[('ssh', 'ssh'), ('rdp', 'rdp'), ... | |
indexofire/gork | src/gork/application/know/plugins/attachments/views.py | Python | mit | 13,497 | 0.003853 | # -*- coding: utf-8 -*-
from django.contrib import messages
from django.db.models import Q
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import redirect, get_object_or_404
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.vi... | kwargs['selected_tab'] = 'attachments'
return super(AttachmentReplaceView, self).get_context_data(**kwargs)
class AttachmentDownloadView(ArticleMixin, View):
@method_decorator(get_article(can_read=True))
def dispatch(self, request, article, attachment_id, *args, **kwargs):
if article.can_mod... | st.user):
self.attachment = get_object_or_404(models.Attachment, id=attachment_id, articles=article)
else:
self.attachment = get_object_or_404(models.Attachment.objects.active(), id=attachment_id, articles=article)
revision_id = kwargs.get('revision_id', None)
if revision... |
haaspt/whatsnew | main.py | Python | mit | 2,815 | 0.006039 | import click
import newsfeeds
import random
import sys
from config import GlobalConfig
def mixer(full_story_list, sample_number):
"""Selects a random sample of stories from the full list to display to the user.
Number of stories is set in config.py
Todo: Add argument support for number of stories to displ... | ", fg=option.prompt_color, bold=True, nl=False)
raw_selection = input()
if raw_selection.isdigit():
selection = int(raw_selection) - 1
if selection <= index_num - 1:
story = mixed_story_list[selection]
click.launch(story.ur... | return exit_now == True
else:
click.secho("Invalid entry", fg='red')
if option.prompt_until_exit == True:
pass
else:
return exit_now == True
elif raw_selection == '':
... |
rtulke/ceph-deploy | ceph_deploy/tests/test_install.py | Python | mit | 1,312 | 0 | from mock import Mock
from ceph_deploy import install
class TestSanitizeArgs(object):
def setup(self):
| self.args = Mock()
# set the default behavior we set in cli.py
self.args.default_release = False
self.args.stable = None
def t | est_args_release_not_specified(self):
self.args.release = None
result = install.sanitize_args(self.args)
# XXX
# we should get `args.release` to be the latest release
# but we don't want to be updating this test every single
# time there is a new default value, and we can... |
cstipkovic/spidermonkey-research | testing/mozharness/scripts/gaia_unit.py | Python | mpl-2.0 | 4,408 | 0.004537 | #!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
import os
import sys
import glob... | arg('--browser-arg', self.config.get('browser_arg')))
# Add support for chunking
if self.config.get('total_chunks') and self.config.get('this_chunk'):
chunker = [ os.path.join(dirs['abs_gaia_dir'], 'bin', 'chunk'),
self.config.get('total_chunks'), self.config... | .join(dirs['abs_runner_dir'],
'gaia_unit_test',
'disabled.json')
with open(disabled_manifest, 'r') as m:
try:
disabled_tests = json.loads(m.read())
... |
invenia/shepherd | shepherd/common/exceptions.py | Python | mpl-2.0 | 911 | 0 |
class LoggingException(Exception):
def __init__(self, message, logger):
Exception.__init__(self, message)
if logger:
logger.error(message)
class ConfigError(LoggingException):
def __init__(self, message, error=None, logger=None):
LoggingException.__init__(self, message, ... | elf, message, errors=None, logger=None):
LoggingException.__init__(self, message, logge | r)
self.errors = errors
|
kpi-web-guild/django-girls-blog-DrEdi | main/tests/test_models.py | Python | mit | 2,406 | 0.002909 | """Tests for models."""
from unittest.mock import patch
from datetime import datetime
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
from main.models import Post, Comment
class ModelPostTest(TestCase):
"""Main class for testing Post models of this ... | _post_rendering(self):
"""Post is rendered as its title."""
self.assertEqual(str(self.test_post), self.test_post.title)
@patch('django.utils.timezone.now', lambda: datetime(day=1, month=4, year=2016,
tzinfo=timezone.get_current_timezone()))
... | self.assertEqual(self.test_post.published_date, datetime(day=1, month=4, year=2016,
tzinfo=timezone.get_current_timezone()))
def tearDown(self):
"""Clean data for new test."""
del self.user
del self.test_post
class ModelC... |
erikaklein/algoritmo---programas-em-Python | GerarNumeroNoIntervalo.py | Python | mit | 251 | 0.032389 | #Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo compreendido por eles.
a=int(input('valor incial'))
print (a)
b=int(input('valor final | '))
print (b)
|
while a<b:
print(a)
a=a+1
|
drayanaindra/inasafe | safe/messaging/styles.py | Python | gpl-3.0 | 2,016 | 0.000496 | """
InaSAFE Disaster risk assessment tool developed by AusAid **Messaging styles.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 ... | ROGRESS_UPDATE_STYLE)
This will result in some standardised styling being applied to the important
text element.
"""
__author__ = 'tim@linfiniti.com'
__revision__ = '$Format:%H$'
__date__ = '06/06/2013'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for | '
'Disaster Reduction')
# These all apply to heading elements
PROGRESS_UPDATE_STYLE = {
'level': 5,
'icon': 'icon-cog icon-white',
'style_class': 'info'}
INFO_STYLE = {
'level': 5,
'icon': 'icon-info-sign icon-white',
'style_class': 'info'}
WARNING_STYLE = {
'level': 5,
... |
Arcanemagus/SickRage | sickbeard/providers/scc.py | Python | gpl-3.0 | 7,234 | 0.002903 | # coding=utf-8
# Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sick-rage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the F... | : 'https://www.sceneaccess.eu/details?id=%s',
'search': 'https://sceneaccess.e | u/all?search=%s&method=1&%s',
'download': 'https://www.sceneaccess.eu/%s'
}
self.url = self.urls['base_url']
self.categories = {
'Season': 'c26=26&c44=44&c45=45', # Archive, non-scene HD, non-scene SD; need to include non-scene because WEB-DL packs get added to those c... |
carolinehardin/learnProgrammingByForums | countReddit.py | Python | gpl-2.0 | 5,525 | 0.029864 | import os, logging, praw, HTMLParser, ConfigParser, pprint, csv
from bs4 import BeautifulSoup
from urlparse import urlparse
from tldextract import tldextract
print "Reddit Research Scraper v0.1"
print "============================"
'''
Grab the config file (we're gonna need it later on)
'''
try:
config ... | ttingsR.conf')
assert(config.get('global', 'outputCSV'))
print "Settings parsed correctly."
except ConfigParser.NoSectionError:
print "Your config file does not appear to be valid. Please verify that settings.conf exists."
#make a pretty printer for use later
pp = pprint.PrettyPrinter(indent=4)
# log... | onfig.get('global', 'loglevel')
logging.basicConfig(filename=LOG_FILENAME, level=LOG_LEVEL)
# we need this to unescape the escaped characters
redditParse = HTMLParser.HTMLParser()
# create files for saving the reddit stuff to
outputCSV = config.get('global', 'outputCSV')
commentsCSV = config.get('global', '... |
imclab/confer | server/recommender.py | Python | mit | 741 | 0.017544 | import sys, os, operator, json
from py4j.java_gateway import JavaGateway
from py4j.java_collections import ListConverter
'''
@author: Anant Bhardwaj
@date: Nov 1, 2013
'''
class Recommender:
def __init__(self):
self.gateway = JavaGateway()
def get_item_based_recommendations(self, paper_id_list):
java_p... | list, self.gateway._gateway_client)
recs = self.gateway.entry_point.recommend(java_paper_id_list)
res=[]
for rec in recs:
r = rec.split(',')
res.append({'id': r[0], 'score': float | (r[1])})
return res
def main():
r = Recommender()
res = r.get_item_based_recommendations(['pn1460'])
print res
if __name__ == "__main__":
main()
|
rajalokan/keystone | keystone/tests/hacking/checks.py | Python | apache-2.0 | 14,985 | 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... | keystone.i18n._',
)
TRANS_HELPER_MAP = {
'debug': None,
'info': '_LI',
'warning': '_LW',
'error': '_LE',
'exception': '_LE',
'critical': '_LC',
}
def __init__(self, tree, filename):
super(CheckForTranslationIssues, self).__init_ | _(tree, filename)
self.logger_names = []
self.logger_module_names = []
self.i18n_names = {}
# NOTE(dstanek): this kinda accounts for scopes when talking
# about only leaf node in the graph
self.assignments = {}
def generic_visit(self, node):
"""Called if no... |
390910131/Misago | misago/conf/defaults.py | Python | gpl-2.0 | 12,306 | 0 | """
Misago default settings
This fille sets everything Misago needs to run.
If you want to add custom app, middleware or path, please update setting vallue
defined in this file instead of copying setting from here to your settings.py.
Yes:
#yourproject/settings.py
INSTALLED_APPS += (
'myawesomeapp',
)
No:
#yo... | uthMiddleware should protect
MISAGO_ADMIN_NAMESPACES = (
'admin',
'misago:admin',
)
# How long (in minutes) since previous request to admin namespace should
# admin session last.
MISAGO_ADMIN_SESSION_EXPIRATION | = 60
# Max age of notifications in days
# Notifications older than this are deleted
# On very a |
fxia22/ASM_xf | PythonD/lib/python2.4/site-packages/display/cursing/ScrollBar.py | Python | gpl-2.0 | 5,591 | 0.023609 | #
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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 (at your option) any later version.
#
# GNU Enterprise is distributed ... | hod("LOSTFOCUS", self.__LostFocus)
self.SetMethod("CLICK", self._ChangePos)
self._max = 1
self._val = 0
self.stepsize = 1
self.__initButtons()
def __initButtons(self):
if string.find(str(self.__class__), '.ScrollBar') != -1:
Y = self.Y
X = self.X
W = self.W
... | NT
self.rightarrow = Button(Parent,'rightarrow',Y,X+W - 3,3,'>')
self.rightarrow.SetMethod("CLICK",self._Inc)
Parent.AddControl(self.rightarrow)
self.left2arrow = Button(Parent,'left2arrow',Y,X+W - 6,3,'<')
self.left2arrow.SetMethod("CLICK",self._Dec)
Parent.AddControl(self.lef... |
twrightsman/advent-of-code-2015 | advent_day7_pt2.py | Python | unlicense | 2,686 | 0.004468 | import re
import sys
def get_wire(input_value):
try:
int(input_value)
return int(input_value)
except ValueError:
if callable(wires[input_value]):
wires[input_value] = wires[input_value]()
return wires[input_value]
class Gate:
def __init__(self, first_input, oper... | self.first_input) << int(self.shift_bits)) & 0xFFFF
def logic_JOIN(self):
print('Getting signal of wire',self.f | irst_input)
return wires[self.first_input]()
def logic_CONST(self):
print('Consant signal', self.first_input)
return int(self.first_input)
wires = {}
def get_signal(wire_id):
return wires[wire_id]()
'''
Group 1: first input to gate (wire id OR constant)
Group 2: operator, if given
Gr... |
eyaler/tensorpack | examples/basics/mnist-visualizations.py | Python | apache-2.0 | 4,834 | 0.002069 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: mnist-visualizations.py
"""
The same MNIST ConvNet example, but with weights/activations visualization.
"""
import tensorflow as tf
from tensorpack import *
from tensorpack.dataflow import dataset
IMAGE_SIZE = 28
def visualize_conv_weights(filters, name):
"... | c1 = Conv2D('conv1', p0)
c2 = Conv2D('conv2', c1)
p1 = MaxPooling('pool1', c2, 2)
c3 = Conv2D('conv3', p1)
fc1 = FullyCo | nnected('fc0', c3, 512, nl=tf.nn.relu)
fc1 = Dropout('dropout', fc1, 0.5)
logits = FullyConnected('fc1', fc1, out_dim=10, nl=tf.identity)
with tf.name_scope('visualizations'):
visualize_conv_weights(c0.variables.W, 'conv0')
visualize_conv_activations(c0, 'conv0')... |
PuZheng/cloud-dashing | cloud_dashing/default_settings.py | Python | gpl-2.0 | 618 | 0 | # -*- coding: UTF-8 -*-
"""
this is the default settings, don't insert into your customized settings!
"""
DEBUG = True
TESTING = True
SECRET_KEY = "5L)0K%,i.;*i/s("
| SECURITY_SALT = "sleiuyyao"
# DB config
SQLALCHEMY_DATABASE_URI = "sqlite:///dev.db"
SQLALCHEMY_ECHO = True
UPLOADS_DEFAULT_DEST = 'uploads'
LOG_FILE = 'log.txt'
ERROR_LOG_RECIPIENTS = []
# Flask-Mail related configuration, refer to
# `http://pythonhosted.org/flask-mail/#configuring-flask-mail`
MAIL_SERVER = 'smtp... | MAIL_DEFAULT_SENDER = 'user@foo.com'
FREEZER_RELATIVE_URLS = False
|
DLR-SC/DataFinder | src/datafinder/core/configuration/properties/domain.py | Python | bsd-3-clause | 6,707 | 0.00999 | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... | 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 Ge | rman Aerospace Center nor the names of
# its contributors may be used to endorse or promote products derived
# from 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 NO... |
ajhager/copycat | copycat/slipnet/sliplink.py | Python | gpl-2.0 | 1,760 | 0.001705 | # Copyright (c) 2007-2017 Joseph Hager.
#
# Copycat is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License,
# as published by the Free Software Foundation.
#
# Copycat is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; with... | iplink is a link between two nod | es in the slipnet.
Attributes:
from_node: The node this link starts at.
to_node: The node this link ends at.
label: The node that labels this link.
fixed_length: A static length of the link has no label."""
def __init__(self, from_node, to_node, label, fixed_length):
""... |
omat/django-timeline | timeline/views.py | Python | mit | 4,465 | 0.002917 | # -*- coding: utf-8 -*-
from time import strftime
from django.db.models import Max
from django.shortcuts import render_to_response, get_object_or_404
from django.core.paginator import QuerySetPaginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Rss201rev... | , {'item': tl_item,
'current_site': current_site}),
description=render_to_string('timeline/item.html', | {'item': tl_item,
'current_site': current_site}),
link=render_to_string('timeline/feed_item_link.html', {'item': tl_item,
'current_site': current_s... |
kaiix/schematics | schematics/types/base.py | Python | bsd-3-clause | 28,230 | 0.001594 | import uuid
import re
import datetime
import decimal
import itertools
import functools
import random
import string
import six
from six import iteritems
from ..exceptions import (
StopValidation, ValidationError, ConversionError, MockCreationError
)
try:
from string import ascii_letters # PY3
except ImportErr... | SSAGES = {
'required': u"This field is required.",
'choices': u"Value must be one of {0}.",
}
def __init__(self, required=False, default=None, serialized_name=No | ne,
choices=None, validators=None, deserialize_from=None,
serialize_when_none=None, messages=None):
super(BaseType, self).__init__()
self.required = required
self._default = default
self.serialized_name = serialized_name
if choices and not isinst... |
Nic30/hwtHls | tests/utils/alapAsapDiffExample.py | Python | mit | 2,761 | 0.002898 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwt.interfaces.std import VectSignal
from hwt.interfaces.utils import addClkRstn
from hwt.simulator.simTestCase import SimTestCase
from hwt.synthesizer.unit import Unit
from hwtHls.hlsStreamProc.streamProc import HlsStreamProc
from hwtHls.platform.virtual import Virt... | Example(Unit):
def _config(self):
self.CLK_FREQ = int(400e6)
def _declr(self):
addClkRstn(self)
self.clk.FREQ = self.CLK_FREQ
self.a = VectSignal(8)
self.b = VectSignal(8)
self.c = VectSignal(8)
self.d = VectSignal(8)._m()
def _impl(self):
h... | hls scope
# (without read() operation will not be schedueled by HLS
# but they will be directly synthesized)
a, b, c = [hls.read(intf) for intf in [self.a, self.b, self.c]]
# depending on target platform this expresion
# can be mapped to DPS, LUT, etc...
# no constrains ... |
Eloston/mipybot | mipybot/world/world.py | Python | gpl-3.0 | 626 | 0 | '''
MiPyBot 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.
MiPyBot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or ... |
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MiPyBot. If not, see {http://www.gnu.org/licenses/}.
'''
# To be implemented
|
jbjornson/SublimeGMail | GMail.py | Python | mit | 4,056 | 0.003205 | # Loosely based on https://github.com/Skarlso/SublimeGmailPlugin by Skarlso
import sublime
import sublime_plugin
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
# from email.headerregistry import Address
# from email.utils import parseaddr, formataddr
config = {
# TO... | lently use the default_value from above
"interactive": {
"smtp_login": False,
"smtp_passwd": False,
"from": False,
"display_name": True,
"recipients": False,
"subject": True
},
| # The prompt message to the user for each field
"prompt": {
"smtp_login": "GMail User ID",
"smtp_passwd": "GMail Password",
"from": "Sender e-mail address",
"display_name": "Sender's display name",
"recipients": "Recipients (semicolon or comma separated list)",
"sub... |
vivsh/django-ginger | ginger/middleware.py | Python | mit | 3,073 | 0.000976 |
from ginger import utils
from datetime import datetime, timedelta
from django.core.cache import cache
from django.conf import settings
from django.utils import timezone
import pytz
__all__ = ['CurrentRequestMiddleware',
'MultipleProxyMiddleware',
'ActiveUserMiddleware',
'LastLoginMi... | ctx.request = request
def process_response(self, request, response):
ctx = utils.context()
ctx.request = None
return response
|
class MultipleProxyMiddleware(object):
"""
https://docs.djangoproject.com/en/dev/ref/request-response/
"""
FORWARDED_FOR_FIELDS = [
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED_HOST',
'HTTP_X_FORWARDED_SERVER',
]
def process_request(self, request):
"""
Rewr... |
blitzmann/Pyfa | eos/db/gamedata/group.py | Python | gpl-3.0 | 1,802 | 0.002775 | # ===============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of eos.
#
# eos 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, ... | ID")),
Column("iconID", Integer))
mapper(Group, groups_table,
properties={
"category" : relation(Category, backref=backref("groups", cascade="all,delete")),
"ID" : synonym("groupID"),
| "name" : synonym("groupName"),
"description": deferred(groups_table.c.description)
})
|
ncclient/ncclient | ncclient/devices/junos.py | Python | apache-2.0 | 6,467 | 0.002783 | """
Handler for Juniper device specific information.
Note that for proper import, the classname has to be:
"<Devicename>DeviceHandler"
...where <Devicename> is something like "Default", "Junos", etc.
All device-specific handlers derive from the DefaultDeviceHandler, which implements the
generic information need... | kind="session")
c.set_name("netconf-command-" + str(sshsession._channel_id))
c.exec_command("xml-mode netconf need-trailer")
return True
def reply_parsing_error_transform(self, reply_cls):
# return transform function if found, else None
return self.__reply_parsing_e... | rm_by_cls.get(reply_cls)
def transform_reply(self):
reply = '''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:appl... |
SaikWolf/gnuradio | grc/gui/Port.py | Python | gpl-3.0 | 10,040 | 0.003586 | """
Copyright 2007, 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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... | relative to its sibling ports
try:
index = ports.index(self)
except:
if hasattr(self, '_connector_length'):
del self._connector_length
return
length = len(filter(lambda p: not p.get_hide(), ports))
| #reverse the order of ports for these rotations
if rotation in (180, 270):
index = length-index-1
port_separation = PORT_SEPARATION \
if not self.get_parent().has_busses[self.is_source] \
else max([port.H for port in ports]) + PORT_SPACING
offset = (s... |
pandas-dev/pandas | pandas/tests/test_take.py | Python | bsd-3-clause | 11,995 | 0.000417 | from datetime import datetime
import re
import numpy as np
import pytest
from pandas._libs import iNaT
import pandas._testing as tm
import pandas.core.algorithms as algos
@pytest.fixture(params=[True, False])
def writeable(request):
return request.param
# Check that take_nd works both with writeable arrays
#... |
assert result.dtype == dtype
def test_2d_fill_nonna(self, dtype_fill_out_dtype):
dtype, fill_value, out_dtype = dtype_fill_out_dtype
data = np.random.randint(0, 2, (5, 3)).astype(dtype)
indexer = [2, 1, 0, -1]
result = algos.take_nd(data, indexer, axis=0, fill_value=fill_v... | assert (result[3, :] == fill_value).all()
assert result.dtype == out_dtype
result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value)
assert (result[:, [0, 1, 2]] == data[:, [2, 1, 0]]).all()
assert (result[:, 3] == fill_value).all()
assert result.dtype == out_dtype
... |
gitsimon/tq_website | partners/migrations/0001_initial.py | Python | gpl-2.0 | 1,987 | 0.003523 | # Generated by Django 2.2.12 on 2020-04-25 15:53
from django.db import migrations, models
import django.db.models.deletion
import djangocms_text_ckeditor.fields
import parler.fields
import parler.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... | ('description', djangocms_text | _ckeditor.fields.HTMLField(blank=True, null=True, verbose_name='Description')),
('master', parler.fields.TranslationsForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='translations', to='partners.Partner')),
],
options={
... |
FireCARES/firecares | firecares/firecares_core/migrations/0009_registrationwhitelist.py | Python | mit | 576 | 0.003472 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('firecares_core', '0008_auto_20161122_1420'),
]
operations = [
migrations.CreateMode | l(
name='RegistrationWhitelist',
fields=[
('id', m | odels.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('email_or_domain', models.CharField(unique=True, max_length=254)),
],
),
]
|
lreis2415/AutoFuzSlpPos | autofuzslppos/FuzzySlpPosInference.py | Python | gpl-2.0 | 6,208 | 0.003222 | # -*- coding: utf-8 -*-
"""Prepare configure file for fuzzy slope position inference program.
@author : Liangjun Zhu
@changelog:
- 15-09-08 lj - initial implementation.
- 17-07-30 lj - reorganize and incorporate with pygeoc.
"""
from __future__ import absolute_import, unicode_literals
import time
... | config_info.write('ParametersNUM\t%d\n' % len(cfg.inferparam[slppos]))
for name, param in list(cfg.inferparam[slppos].items()):
config_info.write('Parameters\t%s\t%s\t%s\t%f\t%f\t%f\t%f\t%f\t%f\n' % (
name, cfg.selectedtopo[name], param[0], param[1], param[2],
p... | t%s\n' % cfg.singleslpposconf[slppos].fuzslppos)
config_info.close()
TauDEMExtension.fuzzyslpposinference(cfg.proc,
cfg.singleslpposconf[slppos].infconfig,
cfg.ws.output_dir, cfg.mpi_dir, cfg.bin_dir,
... |
wadobo/socializa | backend/editor/urls.py | Python | agpl-3.0 | 775 | 0.00129 | from dj | ango.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.editor, name="editor"),
url(r'^game/$', views.edit_game, name="add_game"),
url(r'^game/(?P<gameid>\d+)/$', views.edit_game, name="edit_game"),
url(r'^event/$', views.edit_event, name="add_event"),
url(r'^event/(?P<ev... | ews.ajax_player_search, name="ajax_player_search"),
url(r'^api/game/(?P<game_id>\d+)/$', views.gameview, name='get_game'),
url(r'^api/game/$', views.gameview, name='new_game'),
url(r'^api/games/$', views.gamelist, name='get_games'),
url(r'^api/ev/(?P<ev_id>\d+)/$', views.evview, name='get_ev'),
ur... |
maikodaraine/EnlightenmentUbuntu | bindings/python/python-efl/examples/elementary/test_spinner.py | Python | unlicense | 2,598 | 0.005774 | #!/usr/bin/env python
# encoding: utf-8
from efl.evas import EVAS_HINT_EXPAND, EVAS_HINT_FILL
from efl import elementary
from efl.elementary.window import StandardWindow
from efl.elementary.box import Box
from efl.elementary.spinner import Spinner
EXPAND_BOTH = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND
EXPAND_HORIZ = EVAS_H... | ue_add(2, "February")
sp.special_value_add(3, "March")
sp.special_value_add(4, "April")
sp.special_value_add(5, "May")
sp.special_value_add(6, "June")
sp.special_value_add(7, "July")
sp.special_value_add(8, "August")
sp.special_value_add(9, "September")
sp.special_value_add(10, "October"... | ue_add(11, "November")
sp.special_value_add(12, "December")
bx.pack_end(sp)
sp.show()
win.show()
if __name__ == "__main__":
elementary.init()
spinner_clicked(None)
elementary.run()
elementary.shutdown()
|
gVallverdu/pymatgen | pymatgen/command_line/__init__.py | Python | mit | 237 | 0 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distri | buted under the terms of the MIT License.
"""
This package contains various command line wrappers to programs used in
pymatgen that do not have Python equivalents.
| """
|
o-kei/design-computing-aij | ch3_2/bezier_2D.py | Python | mit | 1,190 | 0 | import numpy as np # モジュールnumpyを読み込み
import matplotlib.pyplot as plt # モジュールmatplotlibのpylab関数を読み込み
def bernstein(t, n, i): # bernstein基底関数の定義
cn, ci, cni = 1.0, 1.0, 1.0
for k in range(2, n, 1):
cn = cn * k
for k in range(1, i, 1):
if i == 1:
break
ci = ci * k
f... | r[k, :] = [sum1, sum2]
return np.array(r)
cp = np.array([[0, -2], [1, -3], [2, -2], [3, 2], [4, 2], [5, 0]]) # 制御点座標
t = np.arange(0, 1 + 0.01, 0.01) # パラメータ生成
p = bezierplot(t, cp) # bezier曲線生成
plt.figure()
plt.plot(p[:, 0], p[:, | 1])
plt.plot(cp[:, 0], cp[:, 1], ls=':', marker='o')
plt.show()
|
deavid/bjsonrpc | bjsonrpc/main.py | Python | bsd-3-clause | 2,824 | 0.01204 | """
bjson/main.py
Copyright (c) 2010 David Martinez Marti
All rights reserved.
Licensed under 3-clause BSD License.
See LICENSE.txt for the full license text.
"""
import socket
import bjsonrpc.server
import bjsonrpc.connection
import bjsonrpc.handlers
__all__ = [
"createserver",
"... | ce or raises an exception.
Servers are usually created this way::
import bjsonrpc
server = bjsonrpc.createserver("0.0.0.0")
server.serve()
Check :ref:`bjsonrpc.server` documentation
"""
if sock is None:
sock ... | ket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(3)
return bjsonrpc.server.Server(sock, handler_factory=handler_factory, http=http)
def connect(host="127.0.0.1", port=10123,
sock=None, handler_factory=bjsonrpc.handlers.NullHandler):
"""
Creates a *bjson.connection.Connection* obje... |
travispavek/testrail-python | tests/test_api.py | Python | mit | 31,201 | 0.000128 | import ast
import copy
from datetime import datetime, timedelta
import mock
import os
import shutil
import util
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
from itertools import ifilter as filter
except ImportError:
pass
from testrail.api import API
from testrail.helper... | self.assertEqual(config['email'], 'user@yourdomain.com')
self.assert | Equal(config['key'], 'your_api_key')
self.assertEqual(config['url'], url)
def test_ssl_env(self):
os.environ['TESTRAIL_VERIFY_SSL'] = 'False'
client = API()
self.assertEqual(client.verify_ssl, False)
def test_no_config_file(self):
os.remove(self.config_path)
key... |
simbha/mAngE-Gin | lib/django/contrib/auth/tests/test_context_processors.py | Python | mit | 7,020 | 0.000142 | import os
from django.contrib.auth import authenticate
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.context_processors import PermWrapper, PermLookupDict
from djan... | in pldict
@skipIfCustomUser
@override_settings(
TEMPLATE_LOADERS=('django.template.loaders.filesystem.Loader',),
TEMPLATE_DIRS=(
os.path.join(os.path.dirname(upath(__file__)), 'templates'),
),
ROOT_URLCONF='django.contrib.auth.tests.urls' | ,
USE_TZ=False, # required for loading the fixture
PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
)
class AuthContextProcessorTests(TestCase):
"""
Tests for the ``django.contrib.auth.context_processors.auth`` processor
"""
fixtures = ['context-pro... |
pierg75/pier-sosreport | sos/plugins/distupgrade.py | Python | gpl-2.0 | 1,902 | 0 | # Copyright (C) 2014 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.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 version 2 of the License, or
# (at your option) any later version.
# ... | ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public | License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from sos.plugins import Plugin, RedHatPlugin
class DistUpgrade(Plugin):
"""... |
sdpython/ensae_teaching_cs | src/ensae_teaching_cs/td_1a/flask_helper.py | Python | mit | 1,966 | 0.001526 | # -*- coding: utf-8 -*-
"""
@file
@brief Helpers for :epkg:`Flask`.
"""
import traceback
import threading
from flask import Response
def Text2Response(text):
"""
convert a text into plain text
@param text text to convert
@return textReponse
"""
return Response(text... | port = port
self.daemon = True
def run(self):
"""
Starts the server.
"""
self._app.run(host=self._h | ost, port=self._port)
def shutdown(self):
"""
Shuts down the server, the function could work if:
* method run keeps a pointer on a server instance
(the one owning method
`serve_forever <https://docs.python.org/3/library/socketserver.html#socketserver.BaseServer.serve_fo... |
citrix-openstack-build/nova | nova/consoleauth/manager.py | Python | apache-2.0 | 5,195 | 0.000577 | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
... | s_str = self.mc.get(instance_uuid.encode('UTF-8'))
if not tokens_str:
tokens = []
else:
tokens = jsonutils.loads(tokens_str)
return tokens
def authorize_console(self, context, token, console_type, host, port,
in | ternal_access_path, instance_uuid=None):
token_dict = {'token': token,
'instance_uuid': instance_uuid,
'console_type': console_type,
'host': host,
'port': port,
'internal_access_path': internal_access_... |
vnsofthe/odoo-dev | addons/rhwl/rhwl_project.py | Python | agpl-3.0 | 1,119 | 0.040991 | # -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp. | osv import fields, osv
import openerp.addons.decimal_precision as dp
import datetime
import re
class rhwl_project(osv.osv):
_name = "rhwl.project"
_columns = {
"name":fields.char(u"项目名称"),
"catelog":fields.char(u"类别"),
"process":fiel | ds.char(u"进度"),
"user_id":fields.many2one("res.users",u"负责人"),
"content1":fields.char(string = u"12月5"),
"content2":fields.char(string = u"12月12"),
"content3":fields.char(string = u"12月19"),
"content4":fields.char(string = u"12月26"),
"content5":fields.char(string = u"01月2... |
googleapis/python-dialogflow-cx | samples/generated_samples/dialogflow_v3beta1_generated_sessions_detect_intent_async.py | Python | apache-2.0 | 1,676 | 0.000597 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | g permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DetectIntent
# NOTE: This snippet has been automatically generated for illus | trative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-dialogflowcx
# [START dialogflow_v3beta1_generated_Sessions_DetectIntent_async]
from google.cloud import dialogflowcx... |
SIU-CS/J-JAM-production | mhapsite/mhap/migrations/0004_delete_quote.py | Python | gpl-3.0 | 354 | 0 | # -*- coding: utf-8 -*-
# Generated | by Django 1.10 on 2017-04-02 19:34
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
| ('mhap', '0003_auto_20170402_1906'),
]
operations = [
migrations.DeleteModel(
name='Quote',
),
]
|
scibi/django-teryt | teryt/south_migrations/0002_auto__add_field_miejscowosc_aktywny__add_field_ulica_aktywny__add_fiel.py | Python | mit | 4,805 | 0.005411 | # coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(... | miejscowosc': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['teryt.Miejscowosc']"}),
'nazwa_1': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'nazwa_2': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
... | ('django.db.models.fields.CharField', [], {'max_length': '10'})
}
}
complete_apps = ['teryt']
|
simplegeo/sqlalchemy | test/engine/test_pool.py | Python | mit | 25,148 | 0.003141 | import threading, time
from sqlalchemy import pool, interfaces, create_engine, select
import sqlalchemy as tsa
from sqlalchemy.test import TestBase, testing
from sqlalchemy.test.util import gc_collect, lazy_gc
from sqlalchemy.test.testing import eq_
mcid = 1
class MockDBAPI(object):
def __init__(self):
sel... | p.recreate()
def testthreadlocal_del(self):
self._do_testthreadlocal(useclose=False)
def testthreadlocal_close(self):
self._do_testthreadlocal(useclose=True)
def _do_testthreadlocal(self, useclose=False):
for p in pool.QueuePool(creator=mock_dbapi... | e=3, max_overflow=-1,
use_threadlocal=True), \
pool.SingletonThreadPool(creator=mock_dbapi.connect,
use_threadlocal=True):
c1 = p.connect()
c2 = p.connect()
self.assert_(c1 is c2)
c3 = p.unique_connection()
... |
calandryll/transcriptome | scripts/old/quality_stats.py | Python | gpl-2.0 | 685 | 0.00438 | #!/usr/bin/python -tt
# Quality scores from fastx
# Website: http://hannonlab.cshl.edu/fastx_toolkit/
# Import OS features to run external programs
import os
import glob
v = "Version 0.1"
# Versions:
# 0.1 - Simple script to run cutadapt on all of the files
fastq_indir = "/home/chris/transcriptome/fastq/trimmed/"
fa... | stem("fastx_quality_stats -i %s/Sample_1_L001_trimmed.fastq %s/Sample_1_L001_trimmed.txt" % (fastq_indir, fastq_outdir))
os.system("fastx | _quality_stats -i %s/Sample_1_L002_trimmed.fastq %s/Sample_1_L002_trimmed.txt" % (fastq_indir, fastq_outdir))
|
baidubce/bce-sdk-python | baidubce/services/tsdb/tsdb_handler.py | Python | apache-2.0 | 1,744 | 0.006881 | # Copyright 2014 Baidu, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
# except in compliance with th | e 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.
"""
This module provides general http handler functions for processing http responses from TSDB services.
"""
import http.client
import json
from baidubce import ut... |
sbmlteam/deviser | deviser/code_files/cpp_functions/Constructors.py | Python | lgpl-2.1 | 42,243 | 0.001349 | #!/usr/bin/env python
#
# @file Constructors.py
# @brief class for constructors for c++ and c
# @author Frank Bergmann
# @author Sarah Keating
#
# <!--------------------------------------------------------------------------
#
# Copyright (c) 2013-2018 by the California Institute of Technology
# (California, USA)... | ractice
return_lines = ['@copydetails doc_note_setting_lv_pkg']
# return_lines = ['@throws {0}Constructor'
# 'Exception'.format(self.cap_language),
# 'Thrown if the given @p level and @p version '
# 'combination, or this kind of {0... | .'.format(self.cap_language,
# global_variables.document_class),
# '@copydetails doc_note_setting_lv']
additional = []
if not self.is_cpp_api:
additional.append('@copydetails doc_returned_owned_pointer')
# create ... |
FloBay/PyOmics | setup.py | Python | bsd-3-clause | 1,788 | 0.003356 | from setuptools import | setup
def setup_package():
# PyPi doesn't accept markdown as HTML output for long_description
# Pypan | doc is only required for uploading the metadata to PyPi and not installing it by the user
# Try to covert Mardown to RST file for long_description
try:
import pypandoc
long_description = pypandoc.convert_file('README.md', 'rst')
# Except ImportError then read in the Markdown file for long_... |
smartbgp/libbgp | libbgp/bmp/termination.py | Python | apache-2.0 | 1,910 | 0.001571 | # Copyright 2015-2017 Cisco Systems, 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 Licens | e. 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 struct
from .message import Message
@Message.register
c... |
mhils/pytest | testing/python/metafunc.py | Python | mit | 36,868 | 0.001302 | import re
import pytest, py
from _pytest import python as funcargs
class TestMetafunc:
def Metafunc(self, func):
# the unit tests of this class check if things work correctly
# on the funcarg level, so we don't need a full blown
# initiliazation
class FixtureInfo:
name2... | ,6]))
def test_parametrize_and_id(self):
def func | (x, y): pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1,2], ids=['basic', 'advanced'])
metafunc.parametrize("y", ["abc", "def"])
ids = [x.id for x in metafunc._calls]
assert ids == ["basic-abc", "basic-def", "advanced-abc", "advanced-def"]
def test_parametr... |
uannight/reposan | plugin.video.tvalacarta/channels/ecuadortv.py | Python | gpl-2.0 | 5,395 | 0.007987 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# tvalacarta - XBMC Plugin
# Canal para Ecuador TV
# http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/
#------------------------------------------------------------
import urlparse,re
import urllib
import os
from core import logger... | lass="lineage-item lineage-item-level-0">8</span></div></div></div> </div>
'''
'''
| <div class="slider_caption display_none">
<div class="field field-name-title field-type-ds field-label-hidden">
<div class="field-items">
<div class="field-item even" property="dc:title">
<h2>Ecuador Multicolor
</h2>
</div>
</div>
</div>
<div class="field field-name-rtv-descripti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.