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
unnikrishnankgs/va
venv/lib/python3.5/site-packages/nbformat/_version.py
Python
bsd-2-clause
113
0
# Make sure t
o update package.json, too! version_info = (4, 3, 0) __version__ = '.'.join
(map(str, version_info))
timtadh/PyOhio2011
t_predictive.py
Python
bsd-3-clause
562
0.007117
#!/usr/bin/env python # -*- coding: utf-8 -*- #Author: Tim Henderson #Email: tim.tadh@hackthology.com #For licensing see the LICENSE file in the top level directory. from predictive import parse def t_expr_compound(): assert (4*3/2) == parse('4*3/2') assert (4/2*3) == parse('4/2*3') assert ((3+9)*4/8) == ...
t (((9-3)*(5-3))/2 + 2) == parse('((9-3)*(5-3))/2 + 2') assert (5 * 4 / 2 - 10 + 5 - 2 + 3) == parse('5 * 4 / 2 - 10 + 5 - 2 + 3') assert (5 /
4 * 2 + 10 - 5 * 2 / 3) == parse('5 / 4 * 2 + 10 - 5 * 2 / 3')
praneetmehta/FSMD
ID3update.py
Python
mit
3,922
0.031362
import urllib2 import eyed3 import mechanize import os from bs4 import BeautifulSoup as bs import unicodedata as ud import sys import string reload(sys) sys.setdefaultencoding('utf-8') class Song: def __init__(self, keyword, filename, albumart, aaformat, dd='/home/praneet/Music/'): self.info = keyword.split('@') ...
list[i].get_text().split(':')[0].lower() == 'featured artist' or souplist[i].get_text().split(':')[0].lower() == 'featured artists': self.feat = souplist[i].get_text().split(':')[1] print 'featured artist ',souplist[i].get_text().split(':')[1] else: pass self.fetchalbum() def fetchalbum(self): ...
')] searchURL = "https://www.google.co.in/search?site=imghp&source=hp&biw=1414&bih=709&q="+urllib2.quote(self.title+' '+self.artist+' album name') html = browser.open(searchURL) soup = bs(html, 'html.parser') for i in soup.findAll(attrs={'class':'_B5d'}): if self.album == '': self.album = i.get_text() ...
hzlf/openbroadcast
website/cms/tests/apphooks.py
Python
gpl-3.0
9,529
0.006716
# -*- coding: utf-8 -*- from __future__ import with_statement from cms.api import create_page, create_title from cms.apphook_pool import apphook_pool from cms.appresolver import (applications_page_check, clear_app_resolvers, get_app_patterns) from cms.test_utils.testcases import CMSTestCase from cms.test_utils.uti...
) page = create_page("home", "nav_playground.html", "en", created_by=superus
er, published=True) create_title('de', page.get_title(), page) child_page = create_page("child_page", "nav_playground.html", "en", created_by=superuser, published=True, parent=page) create_title('de', child_page.get_title(), child_page) child_chil...
ilendl2/chrisdev-cookiecutter
{{cookiecutter.repo_name}}/{{cookiecutter.project_name}}/photos/urls.py
Python
bsd-3-clause
387
0.002584
from django.con
f.urls import patterns, url, include from .views import GalleryListView, GalleryDetailView urlpatterns = patterns("", url( regex=r"^gallery_list/$", view=GalleryListView.as_view(), name="gallery_list", ), url( regex=r"^gallery/(?P<pk>\d+)/$", view=GalleryDetail
View.as_view(), name="gallery_detail", ), )
Sorsly/subtle
google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/sole_tenancy/sole_tenancy_hosts/flags.py
Python
mit
967
0
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Li
cense 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 go...
ompute_flags from googlecloudsdk.command_lib.compute import scope as compute_scope SOLE_TENANCY_HOST_TYPE_RESOLVER = compute_flags.ResourceResolver.FromMap( 'sole tenancy host type', { compute_scope.ScopeEnum.ZONE: 'compute.hostTypes'})
rowhit/h2o-2
py/testdir_single_jvm/test_NN2_twovalues.py
Python
apache-2.0
5,312
0.012236
import unittest, time, sys, re sys.path.extend(['.','..','../..','py']) import h2o, h2o_nn, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_gbm def write_syn_dataset(csvPathname, rowCount, rowDataTrue, rowDataFalse, outputTrue, outputFalse): dsf = open(csvPathname, "w+") for i in range(int(rowCount/2)): ...
alidation_key, 'destination_key': predict_key, 'model_key': model_key } predictResult = h2o_cmd.runPredict(timeoutSecs=timeoutSecs, **kwargs) h2o_cmd.runInspect(key=predict_key, verbose=True) kwargs = { } predictCM...
nfusion_matrix( actual=validation_key, vactual=response, predict=predict_key, vpredict='predict', timeoutSecs=timeoutSecs, **kwargs) cm = predictCMResult['cm'] print h2o_gbm.pp_cm(cm) actualErr = h2o_gb...
040medien/furnaceathome
furnace_client.py
Python
gpl-2.0
15,051
0.011694
#! /usr/bin/env python import bluetoot
h import subprocess import re import time import string import pywapi import httplib import ast import socket import ConfigParser import io from da
tetime import datetime, date from time import mktime from urllib import urlencode from urllib2 import Request, urlopen, URLError, HTTPError from ssl import SSLError from socket import error as SocketError class Config: """Holds basic settings as well as current state""" def __init__(self): c = Con...
anhstudios/swganh
data/scripts/templates/object/mobile/shared_dressed_binayre_ruffian_trandoshan_male_01.py
Python
mit
472
0.04661
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def cr
eate(kernel): result = Creature() result.template = "object/mobile/shared_dressed_binayre_ruffian_trandoshan_male_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","trandoshan_base_male") #### BEGIN MODIFICATIONS #### ####
END MODIFICATIONS #### return result
rebase-helper/rebase-helper
rebasehelper/helpers/input_helper.py
Python
gpl-2.0
3,222
0.000622
# -*- coding: utf-8 -*- # # This tool helps you rebase your package to the latest version # Copyright (C) 2013-2019 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version...
ate. Returns: bool: True on 'y', 'yes', 't', 'true', 'on' and '1'. False on 'n', 'no', 'f', 'false', 'off' and '0'. Raises: ValueError: On any other value. """ message = message.lower() if message in ('y', 'yes', 't', 'true', 'on', '1')...
r "{}"'.format(message)) @classmethod def get_message(cls, message, default_yes=True, any_input=False): """Prompts a user with yes/no message and gets the response. Args: message (str): Prompt string. default_yes (bool): If the default value should be YES. a...
ptphp/PtPy
pttornado/src/handler/user.py
Python
bsd-3-clause
712
0.018786
#!/usr/bin/env python #coding=utf8 import datetime import logging from handler import UserBaseHandler from lib.route import route from lib.util import vmobile @route(r'/user', name='user') #用户后台首页 class UserHandler(UserBaseHandler): def get(self): user =
self.get_current_user() try: self.session['user'] = user self.session.save() except: pass self.render('user/index.html')
@route(r'/user/profile', name='user_profile') #用户资料 class ProfileHandler(UserBaseHandler): def get(self): self.render('user/profile.html') def post(self): self.redirect('/user/profile')
googleapis/python-translate
samples/generated_samples/translate_v3beta1_generated_translation_service_get_glossary_sync.py
Python
apache-2.0
1,480
0.000676
# -*- 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...
# 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. # # Generated code. DO NOT EDIT! # # Snippet for GetGlossary # NOTE: This...
t may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-translate # [START translate_v3beta1_generated_TranslationService_GetGlossary_sync] from google.cloud import translate_v3beta1 def sample_get...
jmchilton/galaxy-central
galaxy/test/functional/test_3B_GetEncodeData.py
Python
mit
1,185
0.01097
from galaxy.test.base.twilltestcase import TwillTestCase #from twilltestcase import TwillTestCase class EncodeTests(TwillTestCase): def test_00_first(self): # will run first due to its name """3B_GetEncodeData: Clearing history""" self.clear_history() def test_10_Encode_Data(self): ...
20051216.gencode_partitioned.bed", "cc.MidRepSeg.20051216.bed", "cc.MidRepSeg.20051216.gencode_partitioned.bed" ] ) self.wait() self.check_data('cc.EarlyRepSeg.20051216.bed', hid=1) # self.check_data('cc.EarlyRepSeg.20051216.gencode_partitioned.bed', hid=2) # self.check_data('cc.L...
d=3) # self.check_data('cc.LateRepSeg.20051216.gencode_partitioned.bed', hid=4) # self.check_data('cc.MidRepSeg.20051216.bed', hid=5) # self.check_data('cc.MidRepSeg.20051216.gencode_partitioned.bed', hid=6)
t104801/webapp
security/urls.py
Python
gpl-3.0
1,479
0.004057
from django.conf.urls import url from django.c
ontrib.
auth.views import login, \ logout, \ logout_then_login, \ password_change, \ password_change_done, \ password_reset, \ ...
tmtowtdi/MontyLacuna
lib/lacuna/buildings/boring/fission.py
Python
mit
219
0.031963
from lacuna.building import MyBuilding class fission(MyBuilding):
path = 'fission' def __init__( self, client, body_id:int = 0, building_id:int = 0 ): super().__
init__( client, body_id, building_id )
fingeronthebutton/RIDE
utest/controller/test_tablecontrollers.py
Python
apache-2.0
2,586
0.004254
import unittest from nose.tools import assert_equals from robotide.robotapi import TestCaseFile, TestCaseFileSettingTable from robotide.controller.filecontrollers import TestCaseFileController from robotide.controller.tablecontrollers import ImportSettingsController VALID_NAME = 'Valid name' class TestCaseNameVali...
rl) def _validate_name(self, name, expected_valid, named_ctrl=None): valid = not bool(self.ctrl.validate_name(name, named_ctrl).error_message) assert_equals(valid, expected_valid) class TestCaseCreationTest(unittest.TestCase): def setUp(self): self.ctrl = TestCaseFileController(TestC...
itespace_is_stripped(self): test = self.ctrl.new(' ' + VALID_NAME + '\t \n') assert_equals(test.name, VALID_NAME) class LibraryImportListOperationsTest(unittest.TestCase): def setUp(self): self._parent = lambda:0 self._parent.mark_dirty = lambda:0 self._parent.datafile...
HuaweiSwitch/ansible
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_launch.py
Python
gpl-3.0
4,901
0.000816
#!/usr/bin/python # coding: utf-8 -*- # (c) 2017, Wayne Witzel III <wayne@riotousliving.com> # # This module 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 opti...
p_fields:
try: name = params.pop(field) result = tower_cli.get_resource(field).get(name=name) params[field] = result['id'] except exc.NotFound as excinfo: module.fail_json(msg='Unable to launch job, {0}/{1} was not found: {2...
kobox/achilles.pl
src/static/fm/views.py
Python
mit
4,377
0.000457
# coding: utf-8 from django.views.generic import CreateView, UpdateView, DeleteView from django.http import HttpResponse, HttpResponseRedirect from django.template.loader import render_to_string from django.template import RequestContext from django.core.serializers.json import DjangoJSONEncoder from django.conf import...
eturn self.render_json_response(self.get_success_result()) success_url = self.get_success_url() return
HttpResponseRedirect(success_url)
LoRexxar/Cobra-W
web/index/apps.py
Python
mit
89
0
from django.apps import AppConfig class IndexConfig(AppConf
ig): name = 'web.index'
Evfro/fifty-shades
polara/tools/movielens.py
Python
mit
2,538
0.006304
import pandas as pd from requests import get from StringIO import StringIO from pandas.io.common import ZipFile def get_movielens_data(local_file=None, get_genres=False): '''Downloads movielens data and stores it in pandas dataframe. ''' if not local_file: #print 'Downloading data...' zip_...
es']) ml_genres = split_genres(genres_data) ml_data = (ml_data, ml_genres) return ml_data def s
plit_genres(genres_data): genres_data.index.name = 'movie_idx' genres_stacked = genres_data.genres.str.split('|', expand=True).stack().to_frame('genreid') ml_genres = genres_data[['movieid', 'movienm']].join(genres_stacked).reset_index(drop=True) return ml_genres def filter_short_head(data, threshold=...
BambooHR/rapid
rapid/master/controllers/api/upgrade_controller.py
Python
apache-2.0
1,295
0.002317
""" Copyright (c) 2015 Michael Bright and Bamboo HR LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed...
): worked = UpgradeUtil.upgrade_version(version, self.flask_app.rapid_config) return Response("It worked!" if worked else "It didn't work, version {} restored!".format(Version.get_version()), status=200 if worked else 5
05)
Secretmapper/updevcamp-session-2-dist
form/cgi-bin/lectures/simple/python.py
Python
mit
272
0
#!/usr/local/bin/p
ython3 import cgi print("Content-type: text/html") print(''' <!DOCTYPE html> <html> <head> <title>Python</title> </head> <body> <h1>Python</h1> <p>Python</p> <p>This is the article for Python</p> </body> </html> '
'')
openstack/oslo.service
oslo_service/tests/test_systemd.py
Python
apache-2.0
2,580
0
# Copyright 2014 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 agre...
d_results = [0, 1, 2] for recv, expected in zip(recv_results, expected_results): if recv == socket.timeout: sock_mock.return_value.recv.side_effect = recv else: sock_mock.return_value.recv.return_value = recv actual = systemd.onready('@fake_soc...
self.assertEqual(expected, actual)
sbadia/pkg-python-eventlet
eventlet/event.py
Python
mit
7,095
0.000423
from __future__ import print_function from eventlet import hubs from eventlet.support import greenlets as greenlet __all__ = ['Event'] class NOT_USED: def __repr__(self): return 'NOT_USED' NOT_USED = NOT_USED() class Event(object): """An abstraction where an arbitrary number of coroutines can...
if self.ready(): return self.wait() return notready # QQQ make it return tuple (type, value, tb) instead of raising # because # 1) "
poll" does not imply raising # 2) it's better not to screw up caller's sys.exc_info() by default # (e.g. if caller wants to calls the function in except or finally) def poll_exception(self, notready=None): if self.has_exception(): return self.wait() return notready def po...
canvasnetworks/canvas
website/drawquest/economy.py
Python
bsd-3-clause
1,765
0.007365
from canvas.exceptions import ServiceError, ValidationError from canvas.economy import InvalidPurchase from drawquest import knobs from drawquest.apps.palettes.models import get_palette_by_name, all_palettes from drawquest.signals import balance_changed def balance(user): return int(user.kv.stickers.currency.get()...
ived_quest']) def credit_personal_share(user): credit(user, knobs.REWARDS['personal_share']) def credit_streak(user, streak): credit(user, knobs.REWARDS['streak_{}'.format(streak)]) def credit_star(user): user.kv.stickers_received.increment(1) credit(user, knobs.REWARDS['st
ar']) def purchase_palette(user, palette): if isinstance(palette, basestring): palette = get_palette_by_name(palette_name) if palette in user.redis.palettes: raise InvalidPurchase("You've already bought this palette.") debit(user, palette.cost) user.redis.palettes.unlock(palette)
daboross/cardapio
src/plugins/duckduck.py
Python
gpl-3.0
8,409
0.002259
# # Copyright (C) 2010 Cardapio Team (tvst@hotmail.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 3 of the License, or # (at your option) any later version. # # ...
RL'], 'context menu': None, } parsed_results.append(item) result_count += 1 except KeyError: pass # check for a related topics section try: if raw_results['RelatedTopics']: for raw_result...
'Topics' sub list try: for result in raw_result['Topics']: if result_count >= self.result_limit: break item = { 'name': result['Text'], 'tooltip': result[...
Elandril/SickRage
sickbeard/clients/transmission_client.py
Python
gpl-3.0
5,249
0.00362
# Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # 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 Free Software Foundation, either version 3 of the Lic...
, 'download-dir': sickbeard.TORRENT_PATH } post_data = json.dumps({'arguments': arguments, 'method': 'torrent-add', }) self._request(method='post', data=post_data) return self.response.json()['result'] == "success" def _s...
ne if result.ratio: ratio = result.ratio mode = 0 if ratio: if float(ratio) == -1: ratio = 0 mode = 2 elif float(ratio) >= 0: ratio = float(ratio) mode = 1 # Stop seeding at seedRatioLimit ...
fcauwe/brother-scan
sendfile.py
Python
gpl-3.0
1,234
0.016207
#!/usr/bin/python import sys,os from email.Utils import COMMASPACE, formatdate from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage from email.M
IMEImage import MIMEImage from email.MIMEBase import MIMEBase from email import Encoders import smtplib import XmlDict function=sys.
argv[1] user=sys.argv[2] filename=sys.argv[3] conf = XmlDict.loadXml("global.xml") for option in conf["menu"]["option"]: if ((option["type"].lower()==function.lower()) and (option["name"]==user)): option_selected = option msg = MIMEMultipart() msg['Subject'] = conf["subject"] msg['From'] = conf["source"] msg['...
Reigel/kansha
kansha/checklist/view.py
Python
bsd-3-clause
7,405
0.003106
#-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- from nagare import presentation, security, var, ajax from nagare.i18n import _ from comp import N...
n-list') h << _('Checklist') return h.root @presentation.render_for(Checklists) def render_Checklists(self, h, comp, model): if security.has_permissions('checklist', se
lf.parent): # On drag and drop action = ajax.Update(action=self.reorder) action = '%s;_a;%s=' % (h.add_sessionid_in_url(sep=';'), action._generate_replace(1, h)) h.head.javascript(h.generate_id(), '''function reorder_checklists(data) { nagare_getAndEval(%s + YAHOO.lang.JSON....
saltstack/salt
tests/unit/states/test_x509.py
Python
apache-2.0
5,661
0
import tempfile import salt.utils.files from salt.modules import x509 as x509_mod from salt.states import x509 from tests.support.helpers import dedent from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock from tests.support.unit import TestCase, skipIf try: import M2Cryp...
aged_mock.return_value = {"changes": True} return { x509: { "__opts__": {"fips_mode": True}, "__salt__": { "x509.get_pem_entry": x509_mod.get_pem_entry, "x509.get_private_key_size": x509_mod.get_private_key_size, ...
"__states__": {"file.managed": self.file_managed_mock}, } } @skipIf(not HAS_M2CRYPTO, "Skipping, M2Crypto is unavailable") def test_private_key_fips_mode(self): """ :return: """ test_key = dedent( """ -----BEGIN PRIVATE KEY-----...
ActiveState/code
recipes/Python/578947_Validate_product/recipe-578947.py
Python
mit
281
0.017794
import re print " Write product name : " nume_produs = raw_input() print
" Write product price : " cost_produs = input() if (nume_produs == re.sub('[^a-z]',"",nume_produs)): print ('%s %d'%(nume_produs,cost_produs)) else: print "Error
! You must tape letters" input()
evernym/zeno
plenum/test/buy_handler.py
Python
apache-2.0
1,707
0.001172
from _sha256 import sha256 from typing import Optional from common.serializers.serialization import domain_state_serializer from plenum.common.constants import DOMAIN_LEDGER_ID from plenum.common.request import Request from plenum.common.txn_util import get_payload_data, get_from, get_req_id from plenum.server.databas...
er): super().__init__(database_manager, BUY, DOMAIN_LEDGER_ID) def static_validation(self, request: Request): self._validate_request_type(request) def dynamic_validation(self, request: Request, req_pp_time: Optional[int]): self._validate_request_type(request) def update_
state(self, txn, prev_result, request, is_committed=False): self._validate_txn_type(txn) key = self.gen_state_key(txn) value = domain_state_serializer.serialize({"amount": get_payload_data(txn)['amount']}) self.state.set(key, value) logger.trace('{} after adding to state, headhas...
toontownfunserver/Panda3D-1.9.0
direct/pyinst/tocfilter.py
Python
bsd-3-clause
4,386
0.007068
import os import finder import re import sys def makefilter(name, xtrapath=None): typ, nm, fullname = finder.identify(name, xtrapath) if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE): return ModFilter([os.path.splitext(nm)[0]]) if typ == finder.PACKAGE: return PkgFilter([fullname]) ...
f, filelist): self.elements = {} for f in filelist: self.elements[f] = 1 class ModFilter(_NameFilter): """ A filter for Python modules. ModFilter(modlist) where modlist is eg ['macpath', 'dospath'] """ def __init__(self, modlist): self.elements = {} ...
self.elements[mod] = 1 class DirFilter(_PathFilter): """ A filter based on directories. DirFilter(dirlist) dirs may be relative and will be normalized. Subdirectories of dirs will be excluded. """ def __init__(self, dirlist): self.elements = {} for pth...
kermitfr/kermit-webui
src/webui/progress/views.py
Python
gpl-3.0
1,766
0.007361
''' Created on Nov 17, 2011 @author: mmornati ''' from django.http import HttpResponse from django.utils import simplejson as json import logging from celery.result import AsyncResult from webui.restserver.template import render_agent_template import sys logger = logging.getLogger(__name__) def get_progress(request,...
d): logger.info("Requesting taskid: %s"%taskid) result = AsyncResult(taskid, backend=None, task_name=taskname) logger.info("TASKID: %s"%result.task_id) dict = {} if (result.state == 'PENDING'): dict
['state'] = 'Waiting for worker to execute task...' elif (result.state == 'PROGRESS'): dict['state'] = 'Operation in progress..' else: dict['state'] = result.state backend_response = None try: backend_response = result.result except: logger.warn(sys.exc_info()) if...
oguzy/ovizart
ovizart/pcap/models.py
Python
gpl-3.0
5,743
0.003657
from django.db import models from djangotoolbox.fields import EmbeddedModelField, ListField from django_mongodb_engine.contrib import MongoDBManager import os # Create your models here. # save the created json file name path # only one file for summary should be kept here class UserJSonFile(models.Model): user_id ...
or path in self.attachment_path: tmp = dict() r = path.split("uploads") file_name = os.path.basename(r[1]) tmp['file_name'] = file_nam
e tmp['path'] = r[1] result.append(tmp) return result
DigitalCampus/django-oppia
tests/oppia/test_context_processors.py
Python
gpl-3.0
2,547
0
from django.urls import reverse from oppia.test import OppiaTestCase from reports.models import DashboardAccessLog class ContextProcessorTest(OppiaTestCase): fixtures = ['tests/test_user.json', 'tests/test_oppia.json', 'tests/test_quiz.json', 'tests/test_permissio...
x'), follow=True) dal_end_count = DashboardAccessLog.objects.all().count()
self.assertEqual(dal_start_count+1, dal_end_count) # home page - all users - post def test_post_home_logged_in(self): for user in (self.admin_user, self.normal_user, self.teacher_user, self.staff_user): self.client.force_l...
tmtowtdi/MontyLacuna
lib/lacuna/captcha.py
Python
mit
5,055
0.017013
import os, requests, tempfile, time, webbrowser import lacuna.bc import lacuna.exceptions as err ### Dev notes: ### The tempfile containing the captcha image is not deleted until solveit() ### has been called. ### ### Allowing the tempfile to delete itself (delete=True during tempfile ### creation), or using the...
: raise EnvironmentError("Unable to find a browser to show the captcha image. Captcha solution is required.") def prompt_user(self): """ Prompts the user to solve the displayed captcha. It's not illegal to call this without first calling :meth:`solveit`, but doing so makes no...
self.resp = input("Enter the solution to the captcha here: ") return self.resp def solveit(self): """ Sends the user's response to the server to check for accuracy. Returns True if the user's response was correct. Raises :class:`lacuna.exceptions.CaptchaResponseError` ot...
Teino1978-Corp/pre-commit
tests/commands/clean_test.py
Python
mit
711
0
from __future__ import unicode_literals import os.path from pre_commit.commands.clean import clean from pre_commit.util import rmtree def test_clean(runner_with_mocked_store): assert os.path.exists(runner_with_mocked_store.store.directory) clean(runner_with_mocked_store) assert not os.path.exists(runner...
't exist.""" rmtree(runner_with_mocked_store.store.directory) assert not os.p
ath.exists(runner_with_mocked_store.store.directory) clean(runner_with_mocked_store) assert not os.path.exists(runner_with_mocked_store.store.directory)
benpicco/mate-deskbar-applet
deskbar/interfaces/Controller.py
Python
gpl-2.0
1,455
0.010309
class Controller(object): def __init__(self, model): self._model = model self._view = None def register_view(self, view): self._view = view def on_quit(self, *args): raise NotImplementedError def on_keybinding_activated(self, core, time): raise...
der): raise NotImplementedError def on_query_entry_changed(self, entry): raise NotImplementedError def on_query_entry_key_press_event(self, entry, event): raise NotImplementedError def on_query_entry_activate(self, entry): raise NotImplementedError ...
treeview, text, match_obj, event): raise NotImplementedError def on_do_default_action(self, treeview, text, match_obj, event): raise NotImplementedError def on_action_selected(self, treeview, text, action, event): raise NotImplementedError def on_clear_history(self,...
NejcZupec/ggrc-core
test/integration/ggrc/converters/test_import_delete.py
Python
apache-2.0
744
0.002688
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc.converters import errors
from integration.ggrc import converters class TestBasicCsvImport(converters.TestCase): def setUp(self): converters.TestCase.setUp(self) self.client.get("/login") def test_policy_basic_import(self): filename = "ca_setup_for_deletion.csv" self.import_file(filename) filename = "ca_deletion.csv...
chriswmackey/UWG_Python
setup.py
Python
gpl-3.0
1,278
0.000782
import setuptools with open("README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as f: requirements = f.read().splitlines() with open('cli-requirements.txt') as f: cli_requirements = f.read().splitlines() setuptools.setup( name="uwg", use_scm_version=True, setu...
6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating Sy
stem :: OS Independent" ], )
Rosslaew/OptiGear
gear/gear.py
Python
mit
2,681
0.012309
from collections import UserList from gear import ffxiv, xivdb from gear import power as p """Class representing a simple gear element. """ class Gear(object): """Gear(slot, item_id, **attributes) slot : in which slot of the gearset is this precise gear, as defined in ffxiv.slots. item_id : ide...
""" def __init__(self, data=[]): super().__init__(data) """maxPower(job,consraintList) Returns the best gearset for job given a list of constraints. """ def maxPower(self,job, constraintList=None): pass """Function to calculate the power of a gear for job. """ def power(gear, job)...
nt(gear.attributes.get(k,0))*v for k,v in ffxiv.weights[job].items()])
ChristosChristofidis/h2o-3
h2o-py/tests/testdir_munging/binop/pyunit_binop2_plus.py
Python
apache-2.0
3,072
0.008138
import sys sys.path.insert(1, "../../../") import h2o def binop_plus(ip,port): # Connect to h2o h2o.init(ip,port) iris = h2o.import_frame(path=h2o.locate("smalldata/iris/iris_wheader_65_rows.csv")) rows, cols = iris.dim() iris.show() ###########################################################...
res.show() # assert False, "expected error. objects of different dimensions not supported." #except EnvironmentError: # pass # LHS: H2OFrame, RHS: scaler res = 1.2 + iris[2] res2 = iris + res[21,:] res2.show() # LHS: H2OFrame, RHS: scaler res = iris + 2 res_rows, res_c...
== rows and res_cols == cols, "dimension mismatch" for x, y in zip([res[c].sum() for c in range(cols-1)], [469.9, 342.6, 266.9, 162.2]): assert abs(x - y) < 1e-1, "expected same values" ################################################################### if __name__ == "__main__": h2o.run_test(sy...
py-in-the-sky/challenges
codility/equi_leader.py
Python
mit
707
0.007072
""" https://codility.com/programmers/task/equi_leader/ """ from collections import Counter, defaultdict def solution(A): def _is_
equi_leader(i): prefix_count_top = running_counts[top] suffix_count_top = total_counts[top] - prefix_count_top return (prefix_count_top * 2 > i + 1) and (suffix_count_top * 2 > len(A) - i - 1) total_counts = Counter(A) running_counts = defaultdict(int) top = A[0] result = 0 ...
for i in xrange(len(A) - 1): n = A[i] running_counts[n] += 1 top = top if running_counts[top] >= running_counts[n] else n if _is_equi_leader(i): result += 1 return result
kdheepak89/pypdevs
pypdevs/schedulers/schedulerNA.py
Python
apache-2.0
7,125
0.002947
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # 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...
tains small tuples. Duplicates of these will also be reduced to a single element, thus memory consu
mption should not be a problem in most cases. This scheduler is ideal in situations where most transitions happen at exactly the same time, as we can then profit from the internal structure and simply return the mapped elements. It results in sufficient efficiency in most other cases, mainly due to the code base being...
WesleyyC/Restaurant-Revenue-Prediction
Ari/needs_work/GridSearch.py
Python
mit
1,295
0.018533
# Grid Search for Algorithm Tuning import numpy as np import pandas as pd from sklearn import datasets from sklearn.linear_model import Ridge from sklearn.grid_search import GridSearchCV ### Plotting function ### from matplotlib import pyplot as plt from sklearn.metrics import r2_score def plot_r2(y, y_pred, titl...
se = sqrt
(mean_squared_error(y, y_pred)) print rmse
msosvi/flask-pyco
flask_pyco/__init__.py
Python
bsd-3-clause
23
0
from
.site
import Site
eddiep1101/python-astm
build/lib/astm/client.py
Python
bsd-3-clause
12,288
0.000488
# -*- coding: utf-8 -*- # # Copyright (C) 2013 Alexander Shorin # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # import logging import socket from .asynclib import loop from .codec import encode from .constants impor...
f self.bulk_mode: records = [record] while True: record = self._get_record(True) records.append(record) if record[0] == 'L': break chunks = encode(records, self.encoding, self.chunk_size) else:
self.last_seq += 1 chunks = encode([record], self.encoding, self.chunk_size, self.last_seq) self.buffer.extend(chunks) data = self.buffer.pop(0) self.last_seq += len(self.buffer) if record[0] == 'L': self.last_seq = 0 s...
burlog/py-static-callgraph
callgraph/builder.py
Python
mit
5,632
0.002308
# -*- coding: utf-8 -*- # # LICENCE MIT # # DESCRIPTION Callgraph builder. # # AUTHOR Michal Bukovsky <michal.bukovsky@trilogic.cz> # from operator import attrgetter from inspect import signature from callgraph.hooks import Hooks from callgraph.utils import AuPair from callgraph.symbols import Symbol, ...
nter, node) # magic follows with self.printer as printer: self.inject_arguments(printer, node, args, kwargs) self.process_function(printer, node, args, kwargs) return node def process_function(self, printer, node, args, kwargs): for expr in n...
self.process(callee, node, args.copy(), kwargs.copy()) def inject_arguments(self, printer, node, args, kwargs): sig = signature(node.symbol.value) self.inject_self(printer, node, sig, args, kwargs) bound = sig.bind_partial(*args, **self.polish_kwargs(sig, kwargs)) s...
formiano/enigma2
lib/python/Screens/InfoBar.py
Python
gpl-2.0
33,112
0.029899
from Tools.Profile import profile from Tools.BoundFunction import boundFunction # workaround for required config entry dependencies. import Screens.MovieSelection from Components.PluginComponent import plugins from Plugins.Plugin import PluginDescriptor from Screens.Screen import Screen from Screens.MessageBox import ...
lselectio
n.value: self.onShown.append(self.showMenu) self.zoomrate = 0 self.zoomin = 1 self.onShow.append(self.doButtonsCheck) def showMenu(self): self.onShown.remove(self.showMenu) config.misc.initialchannelselection.value = False config.misc.initialchannelselection.save() self.mainMenu() def doButtonsCh...
AechPro/Machine-Learning
Partners Healthcare/2016 Breast Cancer/dev/ReconNet/optimization/targets/Card_Problem_Target.py
Python
apache-2.0
1,157
0.012965
class target(object): def __init__(self): self.encodingString = "1,10 1,10 1,10 1,10 1,10 1.0 p1-1,10 1,10 1,10 1,10 1,10 1.0 p2" self.canAdd = False self.canRemove = False self.initializationType = "sequential" self.encodingTable = None self.group1 = [] ...
s+=arg genes.append(arg) for arg in self.group2: m*=arg genes.append(arg) duplicateCount = len(genes) - len(set(genes)) m-=360 s-=36 fitness = -(abs(m) + abs(s)) - duplicateCount #print("\nFITNESS:",fitness,"\n") retu...
genome(self,genome): return True
vdrhtc/Measurement-automation
drivers/IQVectorGenerator.py
Python
gpl-3.0
12,060
0.001244
from math import ceil import numpy as np from ipywidgets import widgets from tqdm.notebook import tqdm from matplotlib import pyplot as plt import lib.iq_mixer_calibration from drivers import IQAWG from lib.data_management import load_IQMX_calibration_database, \ save_IQMX_calibration from lib.iq_mixer_calibratio...
ible by the IF period ''' self._requested_marker_period = marker_period correct_marker_period = ceil( marker_period / self._marker_period_divisor) * \ self._marker_period_divisor if correct_marker_period != self._marker_period: sel...
quested_cal is not None: self._current_cal = None self._output_SSB() for slave_iqvg in self._slave_iqvgs: slave_iqvg.set_marker_period(self._marker_period) def _output_SSB(self): if self._requested_cal != self._current_cal: # print(f"IQVG {se...
qk4l/Flexget
flexget/plugins/clients/rtorrent.py
Python
mit
26,286
0.001902
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from future.moves.xmlrpc import client as xmlrpc_client from future.moves.urllib.parse import urlparse, urljoin from future.utils import native_str import logging import os...
nsport(xmlrpc_client.Transport): """ Used to override the default xmlrpclib transport to support SCGI """ def __init__(self, *args, **kwargs): self.verbose = 0 xmlrpc_client.Transport.__init__(self, *args, **kwargs) def request(self, host, handler, requ
est_body, verbose=False): return self.single_request(host, handler, request_body, verbose) def single_request(self, host, handler, request_body, verbose=0): # Add SCGI headers to the request. headers = [('CONTENT_LENGTH', native_str(len(request_body))), ('SCGI', '1')] header = '\x00...
rs2/pandas
pandas/tests/io/parser/test_python_parser_only.py
Python
bsd-3-clause
9,378
0.000746
""" Tests that apply specifically to the Python parser. Unless specifically stated as a Python-specific issue, the goal is to eventually move as many of these tests out of this module as soon as the C parser can accept further arguments when parsing. """ import csv from io import ( BytesIO, StringIO, ) import...
" parser = pyt
hon_parser_only result = parser.read_csv(StringIO(data), index_col=0, **kwargs) expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"], index=Index(["foo", "bar", "baz"], name="index"), ) tm.assert_frame_equal(result, expected) def test_sniff_delimiter...
dit/dit
dit/pid/measures/iskar.py
Python
bsd-3-clause
4,845
0.001032
""" The I_downarrow unique measure, proposed by Griffith et al, and shown to be inconsistent. The idea is to measure unique information as the intrinsic mutual information between and source and the target, given the other sources. It turns out that these unique values are inconsistent, in that they produce differing ...
- d : Distribution The distribution to compute I_SKAR for. sources : iterable
of iterables The source variables. target : iterable The target variable. Returns ------- i_skar_owb : dict The value of I_SKAR_owb for each individual source. """ uniques = {} for source in sources: others = list(...
scholer/cadnano2.5
cadnano/tests/functionaltest_gui.py
Python
mit
1,997
0.001502
# To run: # pytest -c cadnano/tests/pytestgui.ini cadnano/tests/ import pytest from PyQt5.QtCore import Qt, QPointF from PyQt5.QtTest import QTest from cadnano.fileio.lattice import HoneycombDnaPart from cadnano.views.sliceview import slicestyles from cnguitestcase import GUITestApp @pytest.fixture() def cnapp(): ...
, col) x, y = HoneycombDnaPart.latticeCoordToModelXY(RADIUS, row, col) pt = QPointF(x, y) cnapp.graphicsI
temClick(slice_part_item, Qt.LeftButton, pos=pt, delay=DELAY) cmd_count += 1 cnapp.processEvents() vh_count = len(cnapp.document.activePart().getidNums()) # undo and redo all for i in range(cmd_count): cnapp.document.undoStack().undo() cnapp.processEvents() for i in range(c...
aferr/LatticeMemCtl
src/arch/x86/isa/insts/general_purpose/control_transfer/xreturn.py
Python
bsd-3-clause
3,641
0
# Copyright (c) 2007-2008 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware imp...
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRI...
R TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Gabe Black microcode = ''' def macroop RET_NEAR { # Make the default data size of rets 64 bits in 64 bit mode .adjust_env oszIn64Override ld t1...
veloutin/plow
plow/tests/test_dn_compare.py
Python
lgpl-3.0
1,458
0.003429
import unittest from plow.ldapadaptor import LdapAdaptor class FakeLA(LdapAdaptor): def bind(self, *args): """ Nothing to see here move along """ initialize = bind class Test_Ldap_DN_Compare(unittest.TestCase): def setUp(self): self.ldap_case_i = FakeLA("uri", "base", case_insensitive_dn...
are("CN=Test, OU=Base", "CN=Test,OU=Base", True) self._do_compare(" CN = Test,OU = Base ", "CN=Test,OU=Base", True) self._do_compare(" CN = Te st ", "CN=Te
st", True) if __name__ == '__main__': unittest.main()
Sumukh/ParallelRF
mnist.py
Python
gpl-3.0
959
0.01147
# Script used to create Mnist_mini and Mnist_full datasets. import numpy as np from sklearn.datasets import fetch_mldata from pandas import DataFrame # Default download location for caching is # ~/scikit_learn_da
ta/mldata/mnist-original.mat unless specified otherwise. mnist = fetch_mldata('MNIST original') # Create DataFrame, group data by class. df = DataFrame(mnist.data) df['class'] = mnist.target grouped = df.groupby('class') # Write data feature values to file in Dataset d
irectory by class. for name, group in grouped: # Create mini binary MNIST classification dataset for faster testing. if int(name) < 2: fname = 'Dataset/Mnist_mini/Class' + str(int(name)) + '.txt' np.savetxt(fname=fname, X=group[:200], fmt='%d',delimiter='\t',newline='\n') # Create full MNIST classification for ...
NatLibFi/Skosify
skosify/check.py
Python
mit
8,938
0.000224
# -*- coding: utf-8 -*- """Checks/fixes are bundled in one namespace.""" import logging from rdflib.namespace import RDF, SKOS from .rdftools.namespace import SKOSEXT from .rdftools import localname, find_prop_overlap def _hierarchy_cycles_visit(rdf, node, parent, break_cycles, status): if status.get(node) is No...
_objects(SKOS.related)): if conc2 in sorted(rdf.transitive_objects(conc1, SKOS.broader)): if fix: logging.warning( "Concepts %s and %s connected by both " "skos:broaderTransitive and skos:related, " "removing skos:related", ...
.related, conc2)) rdf.remove((conc2, SKOS.related, conc1)) else: logging.warning( "Concepts %s and %s connected by both " "skos:broaderTransitive and skos:related, " "but keeping it because keep_related is enabled", ...
integeruser/on-pwning
2017-hitcon-quals/Impeccable-Artifact/artifact.py
Python
mit
3,733
0.001072
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from pwn import * context(arch='amd64', os='linux', aslr=False, terminal=['tmux', 'neww']) env = {'LD_PRELOAD': './libc.so.6'} if args['GDB']: io = gdb.debug( './artifact-amd64-2.24-9ubuntu2.2', env=env, gdbscript='''\ set follow-fork-...
ELF('libs/amd64/2.24/9ubuntu2.2/libc-2.24.so') elif args['REMOTE']: io = remote('52.192.178.153', 31337) elf, libc = ELF('./artifact'), ELF('libs/amd64/2.24/9ubuntu2.2/libc-2.24.so') else: io = process('./artifact-amd64-2.24-9ubuntu2.2', env=env) elf, libc = io.elf, ELF('libs/amd64/2.24/9ubuntu2.2/libc...
finding how to bypass the seccomp rules # enforced with prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, ...), since # the "official" tool to disassemble BPF bytecode provided by libseccomp doesn't handle # the BPF_X opcode correctly (and shows wrong rules) # luckily, https://github.com/niklasb/dump-seccomp seems to extract...
mitnk/letsencrypt
letsencrypt-apache/letsencrypt_apache/tests/parser_test.py
Python
apache-2.0
8,205
0.000122
"""Tests for letsencrypt_apache.parser.""" import os import shutil import unittest import augeas import mock from letsencrypt import errors from letsencrypt_apache.tests import util class BasicParserTest(util.ParserTest): """Apache Parser Test.""" def setUp(self): # pylint: disable=arguments-differ ...
pacheParser." "update_runtime_variables"): parser = A
pacheParser( self.aug, self.config_path + os.path.sep, "/dummy/vhostpath") self.assertEqual(parser.root, self.config_path) if __name__ == "__main__": unittest.ma
gnarula/eden_deployment
modules/unit_tests/s3/s3fields.py
Python
mit
47,235
0.001651
# -*- coding: utf-8 -*- # # s3fields unit tests # # To run this script use: # python web2py.py -S eden -M -R applications/eden/modules/unit_tests/s3/s3fields.py # import unittest from gluon.languages import lazyT from gluon.dal import Query from s3.s3fields import * # ==================================================...
elf.assertTrue(self.name2 in result) # Test bulk result = r.bulk(None, rows=[org1, org2]) self.assertTrue(len(result), 3) self.assertEqual(r
esult[self.id1], self.name1) self.assertEqual(result[self.id2], self.name2) self.assertTrue(None in result) result = r.bulk([self.id1], rows=[org1, org2]) self.assertTrue(len(result), 3) self.assertEqual(result[self.id1], self.name1) self.assertEqual(result[self.id2], se...
d0u9/youtube-dl-webui
youtube_dl_webui/__init__.py
Python
gpl-2.0
755
0.005298
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from argparse import ArgumentParser from .core import Core def getopt
(argv): parser = ArgumentParser(description='Another webui for youtube-dl') parser.add_argument('-c', '--config', metavar="CONFIG_FILE", help="config file") parser.add_argument('--host'
, metavar="ADDR", help="the address server listens on") parser.add_argument('--port', metavar="PORT", help="the port server listens on") return vars(parser.parse_args()) def main(argv=None): from os import getpid print("pid is {}".format(getpid())) print("-----------------------------------") ...
okuta/chainer
chainermn/communicators/mpi_communicator_base.py
Python
mit
26,362
0
import mpi4py import numpy import chainer import chainer.backends import chainer.utils from chainer.utils import collections_abc from chainermn.communicators import _communication_utility from chainermn.communicators._communication_utility import chunked_bcast_obj from chainermn.communicators import _memory_utility fr...
eturn cupy class MpiCommunicatorBase(communicator_base.CommunicatorBase): '''MpiCommunicatorBase Implementation of communicator interface defined by :class:`CommunicatorBase`. This communicator assumes MPI4py and all ChainerMN processes are invoked by ``mpirun`` (``mpiexec``) command. Although th...
rcical communicator or pure_nccl communicator for example. ''' def __init__(self, mpi_comm): self.mpi_comm = mpi_comm self._init_ranks() @property def rank(self): return self.mpi_comm.rank @property def size(self): return self.mpi_comm.size @property ...
gratipay/gratipay.com
tests/py/test_security.py
Python
mit
5,176
0.002705
from __future__ import absolute_import, division, print_function, unicode_literals import struct import datetime from aspen import Response from aspen.http.request import Request from base64 import urlsafe_b64decode from cryptography.fernet import Fernet, InvalidToken from gratipay import security from gratipay.model...
' def test_sets_strict_transport_security(self): headers = self.client.GET('/about/').headers assert headers['strict-transport-security'] == 'max-age=31536000
' def test_doesnt_set_content_security_policy_by_default(self): assert 'content-security-policy-report-only' not in self.client.GET('/about/').headers def test_sets_content_security_policy(self): with self.setenv(CSP_REPORT_URI='http://cheese/'): headers = self.client.GET('/about/'...
echopen/PRJ-medtec_sigproc
echopen-leaderboard/bootcamp/leaderboard/urls.py
Python
mit
466
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.conf.urls i
mport url from .views import HomePageView, LeaderboardView, MiscView, Sign_upView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^misc$', Mi
scView.as_view(), name='misc'), url(r'^leaderboard$', LeaderboardView.as_view(), name='leaderboard'), url(r'^login$', Sign_upView.as_view(), name='login'), ]
zlatozar/pytak
pytak/tests/call_test.py
Python
bsd-3-clause
2,316
0.018566
# -*- coding: utf-8 -*- from __future__ import print_function import pytak.call as call import pytak.runners.tools as tools from fakeapi import
CreateTag from fakeapi import GetInformationAboutYourself from fakeapi import CreateAPost new_request_body = { "title" : "New Employee [XXXXX]", "body" : "Please welcome our new employee. Pytak tag - [DDDD]", "type" : "TEXT", "permissions" : { "principal" : { "id" : "12345"...
: "false", "comment" : "true", "share" : "true", "authorize" :"false" } }, "tags" : [ {"name" : "tag2" }, { "name" : "tag3" }, { "name" : "tag4" } ] } def test_randomize_text(): txt = "JSON value with [XXXX] and [DDDD]" assert txt != call.randomize_...
rx2130/Leetcode
python/220 Contains Duplicate III.py
Python
apache-2.0
777
0.001287
class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): ...
< t: return True if m + 1 in dic and abs(nums[i] - dic[m
+ 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1))
leppa/home-assistant
homeassistant/components/wirelesstag/__init__.py
Python
apache-2.0
9,650
0.000415
"""Support for Wireless Sensor Tags.""" import logging from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from wirelesstagpy import NotificationConfig as NC from homeassistant import util from homeassistant.const import ( ATTR_BATTERY_LEVEL, ATTR_VOLTAGE, CONF_PASSWORD, ...
tag manager.""" _LOGGER.info("Registering local push notifications.") for mac in self.tag_manager_macs: configs = self.make_notifications(binary_sensors, mac) # install notifications for all tags in tag manager # specified by mac result = self.api.inst
all_push_notification(0, configs, True, mac) if not result: self.hass.components.persistent_notification.create( "Error: failed to install local push notifications <br />", title="Wireless Sensor Tag Setup Local Push Notifications", ...
tannmay/Algorithms-1
Sorting/Codes/mergeSort.py
Python
gpl-3.0
1,313
0.007616
''' Python program for implementation of Merge Sort l is left index, m is middle index and r is right index L[l...m] and R[m+1.....r] are respective left and right sub-arrays ''' def merge(arr, l, m, r): n1 = m - l + 1 n2 = r-m #create temporary arrays L = [0]*(n1) R = [0]*(n2) #Copy data to temp arrays L[...
def mergeSort(arr, l, r): if l < r
: #Same as (l+r)/2, but avoid overflow for large l and h m = (l+(r-1))/2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r)
israeltobias/DownMedia
youtube-dl/youtube_dl/extractor/go.py
Python
gpl-3.0
6,104
0.002457
# coding: utf-8 from __future__ import unicode_literals import re from .adobepass import AdobePassIE from ..utils import ( int_or_none, determine_ext, parse_age_limit, urlencode_postdata, ExtractorError, ) class GoIE(AdobePassIE): _SITE_INFO = { 'abc': { 'brand': '001', ...
uration': int_or_none(video_data.get('duration', {}).get('value'), 1000), 'age_limit': parse_age_limit(video_data.g
et('tvrating', {}).get('rating')), 'episode_number': int_or_none(video_data.get('episodenumber')), 'series': video_data.get('show', {}).get('title'), 'season_number': int_or_none(video_data.get('season', {}).get('num')), 'thumbnails': thumbnails, 'formats': fo...
jtvaughan/oboeta
oboeta.py
Python
cc0-1.0
6,217
0.009356
#!/usr/bin/env python3 # Review Lines from the Selected Deck in Random Order Until All Pass # Written in 2012 by 伴上段 # # To the extent possible under law, the author(s) have dedicated all copyright # and related and neighboring rights to this software to the public domain # worldwide. This software is distributed with...
ogf.flush() return 0 if __name__ == "__main__": parser = ArgumentParser(formatter_class=Ra
wDescriptionHelpFormatter, description=""" Review lines from standard input as though they were flashcards and log the results. Both standard input and the specified log file must be CSV files with the same field separator character, which is specified via -s. This program works with either the Leitner system ...
MCGallaspy/pymc3
pymc3/examples/LKJ_correlation.py
Python
apache-2.0
1,729
0.00694
from pymc3 import * import theano.tensor as t from theano.tensor.nlinalg import matrix_inverse as inv from numpy import array, diag, linspace from numpy.random import multivariate_normal # Generate some multivariate normal data: n_obs = 1000 # Mean values: mu = linspace(0, 2, num=4) n_var = len(mu) # Standard devia...
', n=1, p=n_var) corr_matrix = corr_triangle[tri_index] corr_matrix = t.fill_diagonal(corr_matrix, 1) cov_matrix = t.diag(sigma).dot(corr_matrix.dot(t.diag(sigma))) like = MvNormal('likelihood', mu=mu, tau=inv(cov_matrix), observed=dataset) def run(n=1000): if n == "short": n = 50 wi...
_ == '__main__': run()
prasannav7/ggrc-core
src/ggrc/models/revision.py
Python
apache-2.0
4,093
0.008063
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: vraj@reciprocitylabs.com # Maintained By: vraj@reciprocitylabs.com """Defines a Revision model for storing snapshots.""" from ggrc import db from ...
ent['display_name'] source, destination = display_name.split('<->')[:2] mapping_verb = "linked" if self.resource_type in link_objects else "mapped" if self.action == 'created': result = u"{1} {2} to {0}".format(source, destination, mapping_verb) elif self.action == 'deleted': result = u"{1} ...
result = u"{0} {1}".format(display_name, self.action) return result @computed_property def description(self): """Compute a human readable description from action and content.""" link_objects = ['ObjectDocument'] if 'display_name' not in self.content: return '' display_name = self.co...
shafiquejamal/socialassistanceregistry
nr/nr/settings/testinserver.py
Python
bsd-3-clause
88
0.011364
f
rom .base import * DEBUG = True EMAIL_BACKEND = 'nr.sendmailemailbackend.EmailBackend'
lipis/the-smallest-creature
main/api/v1/song.py
Python
mit
1,226
0.006525
# coding: utf-8 from google.appengine.ext import ndb from flask.ext import restful import flask from api import helpers impo
rt auth import model import util from main import api_v1 ############################################################################### # Admin ############################################################################### @api_v1.resource('/admin/song/', endpoint='api.admin.song.list') class AdminSongListAPI(rest...
= util.param('song_keys', list) if song_keys: song_db_keys = [ndb.Key(urlsafe=k) for k in song_keys] song_dbs = ndb.get_multi(song_db_keys) return helpers.make_response(song_dbs, model.song.FIELDS) song_dbs, song_cursor = model.Song.get_dbs() return helpers.make_response(song_dbs, model....
ovnicraft/server-tools
module_auto_update/tests/test_module_deprecated.py
Python
agpl-3.0
8,365
0
# -*- coding: utf-8 -*- # Copyright 2017 LasLabs Inc. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import os import mock from odoo.modules import get_module_path from odoo.tests.common import TransactionCase from odoo.tools import mute_logger from odoo.addons.module_auto_update.addon_hash import ...
o.addons.module_auto_update.models.module' class EndTestE
xception(Exception): pass class TestModule(TransactionCase): def setUp(self): super(TestModule, self).setUp() module_name = 'module_auto_update' self.env["ir.config_parameter"].set_param(PARAM_DEPRECATED, "1") self.own_module = self.env['ir.module.module'].search([ ...
alerta/python-alerta
alertaclient/commands/cmd_notes.py
Python
mit
1,034
0.004836
import json import click from tabulate import tabulate @click.command('notes', short_help='List notes') @click.option('--alert-id', '-i', metavar='UUID', help='alert IDs (can use short 8-char id)') @click.pass_obj def cli(obj, alert_id): """List notes.""" client = obj['client'] if alert_id: if ob...
click.echo(tabulate([n.tabular(timezone) for n in client.get_alert_notes(ale
rt_id)], headers=headers, tablefmt=obj['output'])) else: raise click.UsageError('Need "--alert-id" to list notes.')
1065865483/0python_script
test/imag_test.py
Python
mit
3,355
0.001257
# -*- coding: utf-8 -*- # python+selenium识别验证码 # import re import requests import pytesseract from selenium import webdriver from PIL import Image,Image import time # driver = webdriver.Chrome() driver.maximize_window() driver.get("https://higo.flycua.com/hp/html/login.html") driver.implicitly_wait(30) # 下面用户名和密码涉及到我个...
creenImg.png" # 浏览器页面截屏 driver.get_screenshot_as_file(screenImg) # 定位验证码位置及大小 location = driver.find_element_by_name('authImage').location size = driver.find_element_by_name('authImage').size   # 下面四行我都在后面加了数字,理论上是不用加的,但是不加我这截的不是验证码那一块的图,可以看保存的截图,根据截图修改截图位置 left = location['x'] + 530
top = location['y'] + 175 right = location['x'] + size['width'] + 553 bottom = location['y'] + size['height'] + 200 # 从文件读取截图,截取验证码位置再次保存 img = Image.open(screenImg).crop((left, top, right, bottom))   # 下面对图片做了一些处理,能更好识别一些,相关处理再百度看吧 img = img.convert('RGBA') # 转换模式:L | RGB img = img.conver...
Distrotech/bzr
bzrlib/tests/test_bzrdir.py
Python
gpl-2.0
68,233
0.001597
# Copyright (C) 2006-2011 Canonical Ltd # # 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 distribute...
'Format using knits', ) my_format_registry.set_default('knit')
bzrdir.register_metadir(my_format_registry, 'branch6', 'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3', 'Experimental successor to knit. Use at your own risk.', branch_format='bzrlib.branch.BzrBranchFormat6', experimental=True) bzrdir.register_...
GeorgiaTechDHLab/TOME
news/migrations/0004_auto_20170307_0605.py
Python
bsd-3-clause
1,746
0.004009
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-07 06:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('news', '0003_auto_20170228_2249'), ] operations = ...
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='news.Newspaper'), ), migrations.AlterField( model_name='newspaper', name='date_ended', field=models.DateField(blank=True, null=True, verbose_name='date e...
model_name='newspaper', name='location', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='news.Location'), ), ]
Bismarrck/pymatgen
pymatgen/io/aseio.py
Python
mit
594
0.003367
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. #!/usr/bin/env python from __future__ i
mport division, unicode_literals """ #TODO: Write module doc. """ __author__ = 'Shyue Ping Ong' __copyright__ = 'Copyright 2013, The Materials Virtual Lab' __version__ = '0.1' __maintainer__ = 'Shyue Ping Ong' __email_
_ = 'ongsp@ucsd.edu' __date__ = '8/1/15' import warnings warnings.warn("pymatgen.io.aseio has been moved pymatgen.io.ase. This stub " "will be removed in pymatgen 4.0.", DeprecationWarning) from .ase import *
jlanga/exfi
tests/test_io/test_read_gfa.py
Python
mit
2,975
0.000672
#!/usr/bin/env python3 """tests.test_io.test_read_gfa.py: tests for exfi.io.read_gfa.py""" from unittest import TestCase, main from exfi.io.read_gfa import read_gfa1 from tests.io.gfa1 import \ HEADER, \ SEGMENTS_EMPTY, SEGMENTS_SIMPLE, SEGMENTS_COMPLEX, \ SEGMENTS_COMPLEX_SOFT, SEGMENTS_COMPLEX_HARD, ...
PLE
X_HARD_FN class TestReadGFA1(TestCase): """Tests for exfi.io.read_gfa.read_gfa1""" def test_empty(self): """exfi.io.read_gfa.read_gfa1: empty case""" gfa1 = read_gfa1(GFA1_EMPTY_FN) self.assertTrue(gfa1['header'].equals(HEADER)) self.assertTrue(gfa1['segments'].equals(SEGMENTS_...
nextgis/nextgisweb_compulink
nextgisweb_compulink/db_migrations/update_actual_lyr_names.py
Python
gpl-2.0
1,646
0.003645
# coding=utf-8 import json import codecs import os import transaction from nextgisweb import DBSession from nextgisweb.vector_layer import VectorLayer from nextgisweb_compulink.compulink_admin.model import BASE_PATH def update_actual_lyr_names(args): db_session = DBSession() transaction.manager.begin() ...
} # new names (already in templates!) real_layers_template_path = os.path.join(BASE_PATH, 'real_layers_templates/') for up_lyr_name in upd_real_layers: with codecs.open(os.path.join(real_layers_template_path, up_lyr_name + '.json'), encoding='utf-8') as json_file: json_layer_struct = js...
upd_real_lyr_names[up_lyr_name] = new_name # update now resources = db_session.query(VectorLayer).filter(VectorLayer.keyname.like('real_%')).all() for vec_layer in resources: lyr_name = vec_layer.keyname if not lyr_name: continue for up_lyr_name in upd_real_lyr_name...
schleichdi2/OPENNFR-6.3-CORE
opennfr-openembedded-core/meta/lib/oeqa/sdk/cases/gcc.py
Python
gpl-2.0
1,658
0.009047
# # SPDX-License-Identifier: MIT # import os import shutil import unittest from oeqa.core.utils.path import remove_safe from oeqa.sdk.case import OESDKTestCase from oeqa.utils.subprocesstweak import errors_have_output errors_have_output() class GccCompileTest(OESDKTestCase): td_vars = ['MACHINE'] @classmet...
'test.cpp' : self.tc.files_dir, 'testsdkmakefile' : self.tc.sdk_files_dir} for f in files: shutil.copyfile(os.path.join(files[f], f), os.path.join(self.tc.sdk_dir, f)) def setUp(self): machine = self.td.get("MACHINE") if not (self.tc.hasHostP...
raise unittest.SkipTest("GccCompileTest class: SDK doesn't contain a cross-canadian toolchain") def test_gcc_compile(self): self._run('$CC %s/test.c -o %s/test -lm' % (self.tc.sdk_dir, self.tc.sdk_dir)) def test_gpp_compile(self): self._run('$CXX %s/test.c -o %s/test -lm' % (self.tc.sdk_dir, s...
JulianNicholls/Complete-Web-Course-2.0
13-Python/challenge2.py
Python
mit
249
0.012048
#!
/usr/bin/env python3 print('Content-type: text/html') print() primes = [2, *range(3, 10001, 2)] for div in primes: idx = div + 1 while(idx < len(primes)): if (primes[idx] % div == 0): del primes
[idx] idx += 1 print(primes)
EmanueleCannizzaro/scons
test/SWIG/SWIGOUTDIR.py
Python
mit
2,897
0.005178
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
, SWIGOUTDIR = 'java/build dir', SWIGFLAGS = '-c++ -java -Wall', SWIGCXXFILES
UFFIX = "_wrap.cpp") """ % locals()) test.write('Java_foo_interface.i', """\ %module foopack """) # SCons should realize that it needs to create the "java/build dir" # subdirectory to hold the generated .java files. test.run(arguments = '.') test.must_exist('java/build dir/foopackJNI.java') test.must_exist('java/bui...
jerome-jacob/selenium
py/test/selenium/webdriver/firefox/ff_select_support_class_tests.py
Python
apache-2.0
1,419
0.002819
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC
licenses this file # to you 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 dist...
# KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from selenium import webdriver from selenium.test.selenium.webdriver.common import select_class_tests from selenium.test.selenium.webdriver.common.webserver import SimpleWebServe...
billychow/simplelifestream
worker.py
Python
mit
1,047
0.029608
from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.api.labs import taskqueue from google.appengine.api import memcache from lifestream import * class LifeStr
eamQueueWorker(webapp.RequestHandler): def get(self): memcache.set('fresh_count', 0) indexes = LifeStream.instance().indexes
for index in indexes: taskqueue.add(url='/app_worker/task', method='GET', params={'index':index}) taskqueue.add(url='/app_worker/refresh', method='GET', countdown=10) class LifeStreamTaskWorker(webapp.RequestHandler): def get(self): index = int(self.request.get('index')) LifeStream.update_feed(index) cla...
saagie/jupyter-saagie-plugin
saagie/server_extension.py
Python
apache-2.0
16,090
0.00174
from functools import wraps import json import os import traceback import validators from jinja2 import Environment, PackageLoader from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler import requests from requests.auth import HTTPBasicAuth env = Environment( loader=PackageLo...
def check_xsrf_cookie(self): return
class SaagieCheckHandler(IPythonHandler): def get(self): self.finish() class SaagieJobRun: def __init__(self, job, run_data): self.job = job self.id = run_data['id'] self.status = run_data['status'] self.stderr = run_data.get('logs_err', '') self.stdout = run...
pinax/pinax-blog
pinax/blog/migrations/0007_auto_20161223_1013.py
Python
mit
752
0.00266
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-23 10:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0006_auto_20160321_1527'), ] operations = ...
ed=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.AddField( model_name='post', name='blog', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='blog.Blog'), ),
]
watchdogpolska/feder
feder/cases/migrations/0016_auto_20211021_0245.py
Python
mit
423
0
# Generated by Django 2.2.24 on 2021-1
0-21 02:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("cases", "0015_case_is_quarantied"), ] operations = [ migrations.AddIndex( model_name="case", index=models.Index(
fields=["created"], name="cases_case_created_a615f3_idx" ), ), ]
daynesh/ffstats
ffstats/wsgi.py
Python
apache-2.0
1,422
0.000703
""" WSGI config for ffstats project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` ...
to replace the whole Dja
ngo WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running mult...
danmar/cppcheck
tools/listErrorsWithoutCWE.py
Python
gpl-3.0
710
0.005634
#!/usr/bin/env python from __future__ import print_function import argparse import xml.etree.ElementTree as ET def main(): parser = argparse.ArgumentParser(description="List all error without a CWE assigned in CSV format") parser.add_argument("-F", metavar="filename", required=True, he...
d in root.iter("error"): if "cwe" not in child.attrib: print(child.attrib["id"], c
hild.attrib["severity"], child.attrib["verbose"], sep=", ") if __name__ == "__main__": main()
evildmp/django-curated-resources
curated_resources/filters.py
Python
bsd-2-clause
336
0.02381
import django_filters from .models import Resource class Reso
urceFilter(django_filters.FilterSet): class Meta: model = Resource fields = [ 'title', 'description', 'domains', 'topics', 'resource_type', 'suitable_for',
]
jonathansick/Ssstat
ssstat/download.py
Python
bsd-2-clause
1,488
0.008065
#!/usr/bin/env python # encoding: utf-8 """ Download command for ssstat--download logs without adding to MongoDB. 2012-11-18 - Created by Jonathan Sick """ import os import logging from cliff.command import Command import ingest_core class DownloadCommand(Command): """ssstat download""" log = logging.ge...
where logs are cached') parser.add_argument('--delete', dest='delete', default=True, type=bool, help='Delete downloaded logs from S3') return parser def take_action(self, parsedArgs): """Runs the `ssstat do
wnload` command pipeline.""" self.log.debug("Running ssstat download") # Downloads logs into root of cache directory ingest_core.download_logs(parsedArgs.log_bucket, parsedArgs.prefix, parsedArgs.cache_dir, delete=parsedArgs.delete) def main(): pass if __name__ =...
zeptonaut/catapult
perf_insights/perf_insights/local_directory_corpus_driver_unittest.py
Python
bsd-3-clause
531
0.003766
# Copyright (c) 2015 The Chromium Authors. Al
l rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from perf_insights import local_directory_corpus_driver class LocalDirectoryCorpusDriverTests(unittest.TestCase): def testTags(self): self.assertEquals( local_director...
river._GetTagsForRelPath('a.json'), []) self.assertEquals( local_directory_corpus_driver._GetTagsForRelPath('/b/c/a.json'), ['b', 'c'])
alexryndin/ambari
ambari-server/src/main/resources/stacks/ADH/1.0/services/HDFS/package/scripts/utils.py
Python
apache-2.0
16,170
0.013296
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
ment.core.resources.system import Directory, File, Execute from resource_management.libraries.functions.format import format from resource_management
.libraries.functions import check_process_status from resource_management.libraries.functions import StackFeature from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.core import shell from resource_management.core.shell import as_user, as_sudo from resource_ma...
arasmus/ladder
utils.py
Python
mit
5,079
0.000788
import os import logging import numpy as np import theano from pandas import DataFrame, read_hdf from blocks.extensions import Printing, SimpleExtension from blocks.main_loop import MainLoop from blocks.roles import add_role logger = logging.getLogger('main.utils') def shared_param(init, name, cast_float32, role, ...
ve(self, which_callback, *args): if self.var_name is None: self.to_save = {v.name: v.get_value() for v in self.params} path = self.save_path + '/trained_params' logger.info('Saving to %s' % path) np.savez_compressed(path, **self.to_save) def do(self, w
hich_callback, *args): if self.var_name is None: return val = self.main_loop.log.current_row[self.var_name] if self.best_value is None or val < self.best_value: self.best_value = val self.to_save = {v.name: v.get_value() for v in self.params} class SaveExpParams...