commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
0728e6a4f8f06e1d4d137259f76796d1dbfa1a9d | add a wsgi.py that eagerly reads in POSTdata | edx/edx-ora,edx/edx-ora,edx/edx-ora,edx/edx-ora | edx_ora/wsgi_eager.py | edx_ora/wsgi_eager.py | """
WSGI config for ora 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`` sett... | agpl-3.0 | Python | |
fb336764f1a95d591e04f0061009c555b7217274 | Create FoodDiversity.py | LAMakerspce/Economics | FoodDiversity.py | FoodDiversity.py | import csv
import math
import collections
from collections import Counter
# EntFunc calculates the Shannon index for the diversity of venues in a given zip code.
def EntFunc(list,list2):
k = 0
Entropy = 0
for k in range(0, len(BusinessName)):
if BusinessName[k] != BusinessName[k - 1]:
p... | cc0-1.0 | Python | |
388a7eea596fdbcd79005b06d26d54b182b75696 | add package | kokokele/packageSpineAtlas,kokokele/packageSpineAtlas,kokokele/packageSpineAtlas,kokokele/packageSpineAtlas | package.py | package.py | # coding=UTF-8
#!/usr/bin/python
'''
文件夹结构 --zip
animate
unzip.py
release
'''
import os, sys, zipfile
import shutil
import commands
# Config
dir = "equip"
output = "output"
def texturePacker(floder, oriName):
'''
打包图片
'''
target = "../" + floder + "/"
#pwd... | apache-2.0 | Python | |
40d687be843e3de56eb00a028e07866391593315 | Add defaults.py | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/defaults.py | salt/defaults.py | # -*- coding: utf-8 -*-
'''
Default values, to be imported elsewhere in Salt code
Do NOT, import any salt modules (salt.utils, salt.config, etc.) into this file,
as this may result in circular imports.
'''
# Default delimiter for multi-level traversal in targeting
DEFAULT_TARGET_DELIM = ':'
| apache-2.0 | Python | |
26db82fd8560d54b1f385814b8871e6fba42fa91 | Add Linked List (#71) | yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook | utilities/python/linked_list.py | utilities/python/linked_list.py | # Singly-Linked List
#
# The linked list is passed around as a variable pointing to the
# root node of the linked list, or None if the list is empty.
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def linked_list_append(linked_list, value):
'''Appends a va... | mit | Python | |
43510585fcf2d9bd3953f3a4948f3aaebbc00e10 | Add pyglet.info | Alwnikrotikz/pyglet,gdkar/pyglet,xshotD/pyglet,gdkar/pyglet,qbektrix/pyglet,arifgursel/pyglet,mpasternak/michaldtz-fixes-518-522,google-code-export/pyglet,odyaka341/pyglet,mpasternak/michaldtz-fix-552,qbektrix/pyglet,Alwnikrotikz/pyglet,cledio66/pyglet,qbektrix/pyglet,mpasternak/pyglet-fix-issue-552,mpasternak/michaldt... | pyglet/info.py | pyglet/info.py | #!/usr/bin/env python
'''Get environment information useful for debugging.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
_first_heading = True
def _heading(heading):
global _first_heading
if not _first_heading:
print
else:
_first_heading = False
print heading
print... | bsd-3-clause | Python | |
52dc608438940e098900e1380f11ee3094c118ae | Add log file in script higher_education and add download by year. | DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site | scripts/data_download/higher_education/create_files.py | scripts/data_download/higher_education/create_files.py | # -*- coding: utf-8 -*-
'''
python scripts/data_download/higher_education/create_files.py en scripts/data/higher_education/en/ 2009
'''
from collections import namedtuple
from datetime import datetime
import pandas as pd
import os
import bz2
import sys
import logging
import imp
def local_imports():
global comm... | mit | Python | |
3de2e625af9047b64cc2718e6e79be0c428b6ae7 | Solve Code Fights extract each kth problem | HKuz/Test_Code | CodeFights/extractEachKth.py | CodeFights/extractEachKth.py | #!/usr/local/bin/python
# Code Fights Extract Each Kth Problem
def extractEachKth(inputArray, k):
return [e for i, e in enumerate(inputArray) if (i + 1) % k != 0]
def main():
tests = [
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, [1, 2, 4, 5, 7, 8, 10]],
[[1, 1, 1, 1, 1], 1, []],
[[1, 2, 1, ... | mit | Python | |
0f1f96ce23ab89c8de3cf24645c4ea77fa2a9196 | add first test with random data | MaxNoe/cta_event_viewer | test_window.py | test_window.py | from telescope import LST
from windows import TelescopeEventView
import tkinter as tk
import numpy as np
lst = LST(0, 0, 0)
root = tk.Tk()
viewer1 = TelescopeEventView(root, lst, np.random.normal(size=lst.n_pixel))
viewer2 = TelescopeEventView(root, lst, np.random.normal(size=lst.n_pixel))
viewer1.pack(side=tk.LEFT, ... | mit | Python | |
60b5948508a67cb213ca04b5faacb77e27d8f84c | Add fields expicitly declared in form | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys,gcrsaldanha/fiocruz,gcrsaldanha/fiocruz | samples/forms.py | samples/forms.py | import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
from fioc... | import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
from fioc... | mit | Python |
5ca9e468b9709ae2c7358551a19e668e580ea396 | add deserialized json object validation functions | JDReutt/BayesDB,poppingtonic/BayesDB,mit-probabilistic-computing-project/crosscat,JDReutt/BayesDB,mit-probabilistic-computing-project/crosscat,probcomp/crosscat,mit-probabilistic-computing-project/crosscat,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,probcomp/crosscat,JDReutt/BayesDB,probcomp/crosscat,... | src/validate.py | src/validate.py | from collections import Counter
modeltypes = set(["asymmetric_beta_bernoulli", "normal_inverse_gamma", "pitmanyor_atom", "symmetric_dirichlet_discrete", "poisson_gamma"])])
def assert_map_consistency(map_1, map_2):
assert(len(map_1)==len(map_2))
for key in map_1:
assert(key == map_2[map_1[key]])
def ... | apache-2.0 | Python | |
827828dc479f295e6051d69c919f5f1c97dcb6e2 | Add management command to verify MOTECH connection certificates. | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/motech/management/commands/verify_motech_connection_certs.py | corehq/motech/management/commands/verify_motech_connection_certs.py | from urllib.parse import urlparse, urlunparse
import requests
from django.core.management.base import BaseCommand
from requests.exceptions import SSLError
from corehq.motech.models import ConnectionSettings
from corehq.util.log import with_progress_bar
IMPLICIT_HTTPS_PORT = 443
class Command(BaseCommand):
he... | bsd-3-clause | Python | |
fc017a578a402b3d24523d1a41b7a4fdc0b107ef | add a starter proxy script | kmacrow/jquery.instagram.js,kmacrow/jquery.instagram.js | scripts/proxy.py | scripts/proxy.py | #!/usr/bin/env python
'''
Copyright (C) Kalan MacRow, 2013
This code is distributed with jquery.instagram.js
under the MIT license.
https://github.com/kmacrow/jquery.instagram.js
'''
import os
import cgi
import sys
import cgitb
import urllib2
# Base URL for Instagram API endpoints
INSTAGRAM_BASE = 'https://... | mit | Python | |
a319f2f1606a5c4d33e846b496e555140607c98d | Add track_name script | haldean/midigen | track_names.py | track_names.py | import midi
import sys
def track_name(track):
for ev in track:
if isinstance(ev, midi.TrackNameEvent):
return ''.join(map(chr, ev.data))
name = 'no name, first 6 events:'
for ev in track[:6]:
name += '\n %s' % ev
return name
def main(argv):
if len(argv) < 2:
print 'usage: track_names.py... | mit | Python | |
877a7b7449a1d88c14633376a2dfaca8c619c26a | Add solution to exercis 3.6. | HenrikSamuelsson/python-crash-course | exercises/chapter_03/exercise_03_06/exercise_03_06.py | exercises/chapter_03/exercise_03_06/exercise_03_06.py | # 3-6 Guest List
guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_l... | mit | Python | |
5c7538ca1e43eb4529c04169a9a15c513bc3e659 | Add segment_tangent_angle tests module | danforthcenter/plantcv,danforthcenter/plantcv,danforthcenter/plantcv | tests/plantcv/morphology/test_segment_tangent_angle.py | tests/plantcv/morphology/test_segment_tangent_angle.py | import pytest
import cv2
from plantcv.plantcv import outputs
from plantcv.plantcv.morphology import segment_tangent_angle
@pytest.mark.parametrize("size", [3, 100])
def test_segment_tangent_angle(size, morphology_test_data):
# Clear previous outputs
outputs.clear()
skel = cv2.imread(morphology_test_data.s... | mit | Python | |
6d2d224d246569a35a7b4ae5d8086e83bbb67155 | move server.py to project dir | youngam/LearningAndroid,youngam/LearningAndroid,youngam/LearningAndroid | server/server.py | server/server.py | from datetime import datetime
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
SERVER_PORT = 90
HOST_ADDRESS = ''
def save_data(user_email):
file = open('users.txt', 'a+')
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write("{}, {}".format(user_email, current_time... | mit | Python | |
a8db8c0448d98e2de0e662581542bd644e673c7c | Add migration removing generated objects with factories | makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin | geotrek/core/migrations/0018_remove_other_objects_from_factories.py | geotrek/core/migrations/0018_remove_other_objects_from_factories.py | # Generated by Django 2.0.13 on 2020-04-06 13:40
from django.conf import settings
from django.contrib.gis.geos import Point, LineString
from django.db import migrations
def remove_generated_objects_factories(apps, schema_editor):
ComfortModel = apps.get_model('core', 'Comfort')
PathSourceModel = apps.get_mod... | bsd-2-clause | Python | |
3ddf1f4a2bcae247978b66fd63848b3ed9782234 | add donwloader | Menooker/MistMusic | MistDownloader.py | MistDownloader.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import os
import time
import sys
import traceback
cnt=0
least_cnt=0
if len(sys.argv)==2:
least_cnt=int(sys.argv[1])
print least_cnt
if not os.path.exists("mp3"):
os.mkdir("mp3")
for path,dirname,filenames in os.walk("outdir"):
for filename in... | apache-2.0 | Python | |
54e3d3147feb33f21c5bc78a8f3b4721574fcbb9 | Create A.py | Pouf/CodingCompetition,Pouf/CodingCompetition | Google-Code-Jam/2017-1B/A.py | Google-Code-Jam/2017-1B/A.py | import os
import sys
script = __file__
scriptPath = os.path.dirname(script)
scriptFile = os.path.basename(script)[0]
files = [f for f in os.listdir(scriptPath) if scriptFile in f and '.in' in f]
if '{}-large'.format(scriptFile) in str(files):
size = 'large'
elif '{}-small'.format(scriptFile) in str(files):
size =... | mit | Python | |
28e113daa5bd9080f772a30807a930070871aaea | clone del main | meraz1990/TheIoTLearningInitiative | InternetOfThings101/main1.py | InternetOfThings101/main1.py | #!/usr/bin/python
import psutil
import signal
import sys
import time
from threading import Thread
def interruptHandler(signal, frame):
sys.exit(0)
def dataNetwork():
netdata = psutil.net_io_counters()
return netdata.packets_sent + netdata.packets_recv
def dataNetworkHandler():
idDevice = "IoT101Dev... | apache-2.0 | Python | |
607bd42a40b8f9909e3d889b6b9011b4d14a4e52 | add nexpose.py | liberza/python-nexpose | nexpose.py | nexpose.py | #!/usr/bin/python3
import xml.etree.ElementTree as etree
import urllib.request
import urllib.parse
import sys
import ssl
__author__ = 'Nick Levesque <nick@portcanary.com>'
# Nexpose API wrapper.
class Nexpose:
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self.url = 'https://%s:... | apache-2.0 | Python | |
a067c18f8534d79a85538eaf11e34e99f9e17286 | develop update to pair master, going to rename master now | rkk09c/Broadcast | oh_shit.py | oh_shit.py | from app import app, db
from app.mod_sms.models import *
ug1 = UserGroup(name='Canyon Time', phone='+17868378095', active=True)
ug2 = UserGroup(name='test', phone='+18503783607', active=True)
ryan = User(fname='Ryan', lname='Kuhl', phone='+13058985985', active=True)
simon = User(fname='Simon', lname='', phone='+1310... | apache-2.0 | Python | |
01c98087541828421da49295abedd3d894cdb3b5 | Create luz.py | bettocr/rpi-proyecto-final,bettocr/rpi-proyecto-final,bettocr/rpi-proyecto-final,bettocr/rpi-proyecto-final | opt/luz.py | opt/luz.py | #!/usr/bin/env python
# Realizado por: Roberto Arias (@bettocr)
#
# Permite encender y apagar luces leds
#
import RPi.GPIO as GPIO, time, os
GPIO.setmode(GPIO.BCM)
on = 0 # luces encendidas
MAX=5200 # luminocidad maxima antes de encender el led, entre mayor mas oscuro
PIN=23 # pin al relay
PINRC=24 #pin qu... | bsd-3-clause | Python | |
87af377fab216e3db9ad700e124b356b15da492f | add form_register.py | EscapeLife/web_crawler | 7.验证码处理/1.form_register.py | 7.验证码处理/1.form_register.py | #!/usr/bin/env python
# coding:utf-8
import csv
import string
import urllib
import urllib2
import cookielib
import lxml.html
import pytesseract
from PIL import Image
from io import BytesIO
REGISTER_URL = 'http://example.webscraping.com/places/default/user/register'
def parse_form(html):
"""从表单中找到所有的隐匿的input变量属... | mit | Python | |
fe186bf85472cf4e683d9838e36e60c680e6dc77 | Add test | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | python/ql/test/library-tests/PointsTo/new/code/w_function_values.py | python/ql/test/library-tests/PointsTo/new/code/w_function_values.py | def test_conditoinal_function(cond):
def foo():
return "foo"
def bar():
return "bar"
if cond:
f = foo
else:
f = bar
sink = f()
return sink
f_false = test_conditoinal_function(False)
f_true = test_conditoinal_function(True)
def foo():
return "foo"
def ... | mit | Python | |
1afb7bb7b1f3e8ef3070f1100dac683b2b8254ee | remove unused table | macarthur-lab/seqr,ssadedin/seqr,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,ssadedin/seqr,macarthur-lab/xbrowse,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr | xbrowse_server/base/migrations/0003_delete_xhmmfile.py | xbrowse_server/base/migrations/0003_delete_xhmmfile.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0002_auto_20160117_1843'),
]
operations = [
migrations.DeleteModel(
name='XHMMFile',
),
]
| agpl-3.0 | Python | |
49c673c5c8374867fc9bf026717fe137bdba84bc | Add test file for graph.py and add test of Greengraph class constructor | MikeVasmer/GreenGraphCoursework | greengraph/test/test_graph.py | greengraph/test/test_graph.py | from greengraph.map import Map
from greengraph.graph import Greengraph
from mock import patch
import geopy
from nose.tools import assert_equal
start = "London"
end = "Durham"
def test_Greengraph_init():
with patch.object(geopy.geocoders,'GoogleV3') as mock_GoogleV3:
test_Greengraph = Greengraph(start,end)... | mit | Python | |
54553efa024d74ec60647ea7616191a52fe9948f | Add a command to create collaborator organisations | akvo/akvo-rsr,akvo/akvo-rsr,akvo/akvo-rsr,akvo/akvo-rsr | akvo/rsr/management/commands/create_collaborator_organisation.py | akvo/rsr/management/commands/create_collaborator_organisation.py | # -*- coding: utf-8 -*-
# Akvo Reporting is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
"""Create a collaborator organis... | agpl-3.0 | Python | |
6318c1dd7d3c942bc7702402eb6ae50a86c023b7 | add hastad | JustHitTheCore/ctf_workshops,disconnect3d/jhtc_ctf_workshops,GrosQuildu/jhtc_ctf_workshops,JustHitTheCore/ctf_workshops,GrosQuildu/jhtc_ctf_workshops | lab3/hastad/code.py | lab3/hastad/code.py | # https://id0-rsa.pub/problem/11/
import gmpy2
def crt(a, n):
"""Chinese remainder theorem
from: http://rosettacode.org/wiki/Chinese_remainder_theorem#Python
x = a[0] % n[0]
x = a[1] % n[1]
x = a[2] % n[2]
Args:
a(list): remainders
n(list): modules
Returns:
lo... | mit | Python | |
0fce5f54490d9ae9014280a5e0e96fd53128d299 | Add kubevirt_preset module (#52498) | thaim/ansible,thaim/ansible | lib/ansible/modules/cloud/kubevirt/kubevirt_preset.py | lib/ansible/modules/cloud/kubevirt/kubevirt_preset.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | mit | Python | |
a3d837afe6662edb10395baa8851de551d0915a5 | add email templates tests | auth0/auth0-python,auth0/auth0-python | auth0/v3/test/management/test_email_endpoints.py | auth0/v3/test/management/test_email_endpoints.py | import unittest
import mock
from ...management.email_templates import EmailTemplates
class TestClients(unittest.TestCase):
@mock.patch('auth0.v3.management.email_templates.RestClient')
def test_create(self, mock_rc):
mock_instance = mock_rc.return_value
c = EmailTemplates(domain='domain', to... | mit | Python | |
9fe4ce918456a3470cf4eb50212af9a487c03ce4 | add tests for utils | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/apps/auditcare/tests/test_auditcare_migration.py | corehq/apps/auditcare/tests/test_auditcare_migration.py | from django.test.testcases import TransactionTestCase
from corehq.apps.auditcare.models import AuditcareMigrationMeta
from datetime import datetime
from unittest.mock import patch
from django.test import SimpleTestCase
from corehq.apps.auditcare.management.commands.copy_events_to_sql import Command
from corehq.apps.au... | bsd-3-clause | Python | |
cee2683d3c0a60739b8e4f1c1dbaa74981a42392 | add class skeleton for schedule generator | ahoskins/Winston,rosshamish/classtime,rosshamish/classtime,ahoskins/Winston | angular_flask/classtime/scheduler.py | angular_flask/classtime/scheduler.py | class Scheduler(object):
"""
Helper class which builds optimal schedules out of
class listings.
Use static methods only - do not create instances of
the class.
"""
def __init__(self):
pass
@staticmethod
def generate_schedule(classtimes):
"""
Generates one g... | agpl-3.0 | Python | |
82e4c67bd7643eed06e7cd170ca1d0de41c70912 | Add a data analyzer class. | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | core/data/DataAnalyzer.py | core/data/DataAnalyzer.py | """
DataAnalyzer
:Authors:
Berend Klein Haneveld
"""
class DataAnalyzer(object):
"""
DataAnalyzer
"""
def __init__(self):
super(DataAnalyzer, self).__init__()
@classmethod
def histogramForData(cls, data, nrBins):
"""
Samples the image data in order to create bins
for making a histogram of the data.
... | mit | Python | |
3f85610873d88592970c64661e526b2a576e300f | Add new sms message generator | bsharif/SLOT,nhshd-slot/SLOT,bsharif/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT,bsharif/SLOT | sms_generator.py | sms_generator.py | def generate_new_procedure_message(procedure, ward, timeframe, doctor):
unique_reference = str(1)
message = str.format("{0} is available on {1}. Attend the ward in {2} and meet {3} in the junior doctors' office. "
"To accept this opportunity reply with {4}",
pro... | mit | Python | |
926631d068a223788714cd645ae5336881c6853f | Update messageable.py | gschizas/praw,gschizas/praw,praw-dev/praw,praw-dev/praw | praw/models/reddit/mixins/messageable.py | praw/models/reddit/mixins/messageable.py | """Provide the MessageableMixin class."""
from ....const import API_PATH
class MessageableMixin:
"""Interface for classes that can be messaged."""
def message(self, subject, message, from_subreddit=None):
"""
Send a message to a redditor or a subreddit's moderators (mod mail).
:param... | """Provide the MessageableMixin class."""
from ....const import API_PATH
class MessageableMixin:
"""Interface for classes that can be messaged."""
def message(self, subject, message, from_subreddit=None):
"""
Send a message to a redditor or a subreddit's moderators (mod mail).
:param... | bsd-2-clause | Python |
73bd8200f6ad23c60a05831e3b79497b830f19cd | Update old lithium comments about llvm-symbolizer 3.6 to 3.8 versions. | nth10sd/lithium,nth10sd/lithium,MozillaSecurity/lithium,MozillaSecurity/lithium | interestingness/envVars.py | interestingness/envVars.py | #!/usr/bin/env python
#
# 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/.
import copy
import os
import platform
isLinux = (platform.system() == 'Linux')
isMac = (platfor... | #!/usr/bin/env python
#
# 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/.
import copy
import os
import platform
isLinux = (platform.system() == 'Linux')
isMac = (platfor... | mpl-2.0 | Python |
378cb69d413eb8ffaf811b607fc037be923a2aba | Write tests for SSLRedirectMiddleware | praekelt/molo-iogt,praekelt/molo-iogt,praekelt/molo-iogt | iogt/tests/test_middleware.py | iogt/tests/test_middleware.py | from django.test import (
TestCase,
Client,
RequestFactory,
override_settings,
)
from molo.core.tests.base import MoloTestCaseMixin
from molo.core.models import Main
from iogt.middleware import SSLRedirectMiddleware
PERMANENT_REDIRECT_STATUS_CODE = 301
@override_settings(HTTPS_PATHS=['admin'])
cla... | bsd-2-clause | Python | |
e0ac456eae45a1b7e1482ff712be600b384f94b3 | Include new example to show group circle connectivity. | pravsripad/jumeg,jdammers/jumeg | examples/connectivity/plot_custom_grouped_connectivity_circle.py | examples/connectivity/plot_custom_grouped_connectivity_circle.py | #!/usr/bin/env python
"""
Example how to create a custom label groups and plot grouped connectivity
circle with these labels.
Author: Praveen Sripad <pravsripad@gmail.com>
Christian Kiefer <ch.kiefer@fz-juelich.de>
"""
import matplotlib.pyplot as plt
from jumeg import get_jumeg_path
from jumeg.connectivity i... | bsd-3-clause | Python | |
f50efeb78d9b503a7d6e97db8b1cd68b429aa2c4 | allow to run tox as 'python -m tox', which is handy on Windoze | jcb91/tox | tox/__main__.py | tox/__main__.py | from tox._cmdline import main
main()
| mit | Python | |
f7e504652707b09c0a0b7e7b1691094ef6d35509 | add proper tomography example | aringh/odl,odlgroup/odl,kohr-h/odl,aringh/odl,kohr-h/odl,odlgroup/odl | examples/solvers/conjugate_gradient_tomography.py | examples/solvers/conjugate_gradient_tomography.py | # Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL 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.
#... | mpl-2.0 | Python | |
236d7d885dadcb681357212a5c6b53c28eac0aa1 | Create d1-1.py | chazzam/adventofcode | 2018/d1-1.py | 2018/d1-1.py | with open("completed/input_c1-1.txt", "r") as f:
line = "0"
sum = 0
while line:
sum += int(line)
line = f.readline()
print("Final Frequency: {}", sum)
| apache-2.0 | Python | |
8de92e74317a74b53991bdcbb3594f0e94e4cf17 | Add Monty Hall simulation | martindisch/pytry | montyhall.py | montyhall.py | import random
import sys
def game():
# Place car behind one door
car = random.randint(1, 3)
# Player selects a door
first_choice = random.randint(1, 3)
reveal_options = [1, 2, 3]
# Don't reveal the car
reveal_options.remove(car)
# Don't reveal the player's choice
if first_choice in... | mit | Python | |
b177a0f2e9b42347f56c4499aaa080af97e0e530 | add validity check | Yokan-Study/study,Yokan-Study/study,Yokan-Study/study | 2018/04.10/python/jya_gAPIclass.2.py | 2018/04.10/python/jya_gAPIclass.2.py | import requests, base64
import config
id = config.GAPI_CONFIG['client_id']
secret = config.GAPI_CONFIG['client_secret']
type = config.GAPI_CONFIG['grant_type']
class GapiClass:
def __init__(self, host='https://gapi.gabia.com'):
self.__host = host
self.__headers = self.__encoded_token()
sel... | mit | Python | |
8e8e11990e430302eca24d32ba0b88dcc66233d6 | Add connect2 wifi via pyobjc | clburlison/scripts,clburlison/scripts,clburlison/scripts | clburlison_scripts/connect2_wifi_pyobjc/connect2_wifi_pyobjc.py | clburlison_scripts/connect2_wifi_pyobjc/connect2_wifi_pyobjc.py | #!/usr/bin/python
"""
I didn't create this but I'm storing it so I can reuse it.
http://stackoverflow.com/a/34967364/4811765
"""
import objc
SSID = "MyWifiNetwork"
PASSWORD = "MyWifiPassword"
objc.loadBundle('CoreWLAN',
bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
modul... | mit | Python | |
a6d6b833e33dc465b0fa828018e2cbba748f8282 | Add utility class for evaluation | studiawan/pygraphc | pygraphc/evaluation/EvaluationUtility.py | pygraphc/evaluation/EvaluationUtility.py |
class EvaluationUtility(object):
@staticmethod
def convert_to_text(graph, clusters):
# convert clustering result from graph to text
new_clusters = {}
for cluster_id, nodes in clusters.iteritems():
for node in nodes:
members = graph.node[node]['member']
... | mit | Python | |
a2a2d6ab7edaa6fab9d2fb95586fde8f1f74b1cc | add new package (#24672) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/py-aniso8601/package.py | var/spack/repos/builtin/packages/py-aniso8601/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyAniso8601(PythonPackage):
"""A library for parsing ISO 8601 strings."""
homepage = ... | lgpl-2.1 | Python | |
0ee3990781488c54b3d45c722b843a06a28da235 | Add test that explores exploitability of tilted agents | JakubPetriska/poker-cfr,JakubPetriska/poker-cfr | verification/action_tilted_agents_exploitability_test.py | verification/action_tilted_agents_exploitability_test.py | import unittest
import numpy as np
import os
import matplotlib.pyplot as plt
import acpc_python_client as acpc
from tools.constants import Action
from weak_agents.action_tilted_agent import create_agent_strategy_from_trained_strategy, TiltType
from tools.io_util import read_strategy_from_file
from evaluation.exploita... | mit | Python | |
0c9c3a801077c241cc32125ab520746935b04f89 | Create LAElectionResults.py | ahplummer/ElectionUtilities | LAElectionResults.py | LAElectionResults.py | # The MIT License (MIT)
# Copyright (C) 2014 Allen Plummer, https://www.linkedin.com/in/aplummer
#
# 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 limit... | mit | Python | |
6a6abadc2395810076b89fb38c759f85426a0304 | Add framework for own SVM from scratch | a-holm/MachinelearningAlgorithms,a-holm/MachinelearningAlgorithms | supportVectorMachine/howItWorksSupportVectorMachine.py | supportVectorMachine/howItWorksSupportVectorMachine.py | # -*- coding: utf-8 -*-
"""Support Vector Machine (SVM) classification for machine learning.
SVM is a binary classifier. The objective of the SVM is to find the best
separating hyperplane in vector space which is also referred to as the
decision boundary. And it decides what separating hyperplane is the 'best'
because... | mit | Python | |
2e1c257c0215f398e4ac5cc7d2d20ffa62492817 | Create NewChatAlert.pyw | Grezzo/TeamSupportChatAlert | NewChatAlert.pyw | NewChatAlert.pyw | # TODO: Check for cookie expiration
# TODO: Check for failed request
# TODO: Check for rejected cookie
# TODO: Get Cookie from other browsers (IE and Firefox)
# - See https://bitbucket.org/richardpenman/browser_cookie (and perhaps contribute)?
from os import getenv
from sqlite3 import connect
from win32crypt imp... | mit | Python | |
1d4938232aa103ea2a919796e9fa35e2699d41d9 | Create PythonAnswer2.py | GBarrett18/dt211-cloud-repo | PythonAnswer2.py | PythonAnswer2.py | def fibonacci(x):
a = 0 #first number
b = 1 #second number
for x in range(x - 1):
a, b = b, a + b #a becomes b and b becomes a and b added together
return a #returns the next number in the sequence
print "Fibonacci Answer"
for x in range(1, 35): #number of times I need the sequenc... | mit | Python | |
5c60be411e61d5edfbf658509b437973d596a3ba | Create server.py | adrien-bellaiche/Interceptor,adrien-bellaiche/Interceptor,adrien-bellaiche/Interceptor | Networking/server.py | Networking/server.py | # -*- coding: utf-8 -*-
import socket, math
# demarrage du serveur
server = "127.0.0.1"
port = 55042
mysock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mysock.bind((server, port))
JOG_IP = [None,None,None,None,None,None,None,None,None,None]
JOG_coordinates= [None,None,None,None,None,None,None,None,None,None]
... | apache-2.0 | Python | |
92ec849fc18d7cb610839abe2213ce30ceced46b | Add ci settings file for postgresql database | inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree | InvenTree/InvenTree/ci_postgresql.py | InvenTree/InvenTree/ci_postgresql.py | """
Configuration file for running tests against a MySQL database.
"""
from InvenTree.settings import *
# Override the 'test' database
if 'test' in sys.argv:
eprint('InvenTree: Running tests - Using MySQL test database')
DATABASES['default'] = {
# Ensure postgresql backend is being used
'... | mit | Python | |
f7db5d9cac80432a7016043a1b2781fbaa7f040e | Create new package. (#6891) | matthiasdiener/spack,EmreAtes/spack,matthiasdiener/spack,iulian787/spack,iulian787/spack,EmreAtes/spack,LLNL/spack,LLNL/spack,matthiasdiener/spack,tmerrick1/spack,tmerrick1/spack,mfherbst/spack,LLNL/spack,mfherbst/spack,krafczyk/spack,matthiasdiener/spack,iulian787/spack,krafczyk/spack,krafczyk/spack,iulian787/spack,tm... | var/spack/repos/builtin/packages/r-rappdirs/package.py | var/spack/repos/builtin/packages/r-rappdirs/package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | lgpl-2.1 | Python | |
6d2efcea281775c31cd1df29eac63054e3fe51df | Create solution.py | lilsweetcaligula/Algorithms,lilsweetcaligula/Algorithms,lilsweetcaligula/Algorithms | data_structures/linked_list/problems/delete_n_after_m/py/solution.py | data_structures/linked_list/problems/delete_n_after_m/py/solution.py | import LinkedList
# Problem description:
# Solution time complexity:
# Comments:
# Linked List Node inside the LinkedList module is declared as:
#
# class Node:
# def __init__(self, val, nxt=None):
# self.val = val
# self.nxt = nxt
#
def DeleteNAfterMNodes(head: Li... | mit | Python | |
c84ce4b2494771c48890c122420e4665828ac4f8 | Solve Code Fights different rightmost bit problem | HKuz/Test_Code | CodeFights/differentRightmostBit.py | CodeFights/differentRightmostBit.py | #!/usr/local/bin/python
# Code Different Right-most Bit (Core) Problem
def differentRightmostBit(n, m):
return (n ^ m) & -(n ^ m)
def main():
tests = [
[11, 13, 2],
[7, 23, 16],
[1, 0, 1],
[64, 65, 1],
[1073741823, 1071513599, 131072],
[42, 22, 4]
]
f... | mit | Python | |
8d0d564eae53a10b98b488b8c13eb952134cfc5e | Create 0408_country_body_part.py | boisvert42/npr-puzzle-python | 2018/0408_country_body_part.py | 2018/0408_country_body_part.py | #!/usr/bin/python
'''
NPR 2018-04-08
http://www.npr.org/puzzle
Name part of the human body, insert a speech hesitation, and you'll name a country — what is it?
'''
from nltk.corpus import gazetteers
import nprcommontools as nct
#%%
BODY_PARTS = nct.get_category_members('body_part')
# COUNTRIES
COUNTRIES = frozenset... | cc0-1.0 | Python | |
61ec74a685deec0b1ddc0a9274e5df0a597c6b6b | Create TweetStreamer.py | nremynse/Automation-Scripts | TweetStreamer.py | TweetStreamer.py | import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
from elasticsearch import Elasticsearch
import datetime
from watson_developer_cloud import NaturalLanguageUnderstandingV1
import watson_developer_cloud.natural_language_understanding.features.... | mit | Python | |
3345dc2f1ac15f06d3e95b5ead894ee9d3a27d9e | Add file writer utility script | rbuchmann/pivicl | piwrite.py | piwrite.py | #!/bin/env python
import argparse
import sys
import os
parser = argparse.ArgumentParser(description="Write multiple svgs from stdin to files")
parser.add_argument('-o', '--outfile', metavar='OUTFILE', default='output.svg')
args = parser.parse_args()
base, extension = os.path.splitext(args.outfile)
def write_files... | epl-1.0 | Python | |
7147dfc237acb64a8e655e63681a387282043994 | Add lc0031_next_permutation.py | bowen0701/algorithms_data_structures | lc0031_next_permutation.py | lc0031_next_permutation.py | """Leetcode 31. Next Permutation
Medium
URL: https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically
next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible
order (ie, sorted in ascen... | bsd-2-clause | Python | |
46d5b197e022815c2074fbc94ca324d31d470dd0 | Implement a fasttext example (#3446) | dolaameng/keras,keras-team/keras,DeepGnosis/keras,nebw/keras,keras-team/keras,kemaswill/keras,kuza55/keras | examples/imdb_fasttext.py | examples/imdb_fasttext.py | '''This example demonstrates the use of fasttext for text classification
Based on Joulin et al's paper:
Bags of Tricks for Efficient Text Classification
https://arxiv.org/abs/1607.01759
Can achieve accuracy around 88% after 5 epochs in 70s.
'''
from __future__ import print_function
import numpy as np
np.random.see... | apache-2.0 | Python | |
dde0efeec1aca8ed3ec2e444bbb4c179be89fec5 | Create MooreNeightbourhood.py | Oscarbralo/TopBlogCoder,Oscarbralo/TopBlogCoder,Oscarbralo/TopBlogCoder | Checkio/MooreNeightbourhood.py | Checkio/MooreNeightbourhood.py | def count_neighbours(grid, row, col):
neig = 0
if (col - 1 >= 0):
if (grid[row][col - 1] == 1):
neig += 1
if (col - 1 >= 0 and row - 1 >= 0):
if (grid[row - 1][col -1] == 1):
neig += 1
if (row - 1 >= 0):
if (grid[row - 1][col] == 1):
neig += 1
... | mit | Python | |
a3df0567c295f0b2879c9a4f095a31108359d531 | Add missing migration for invoice status | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | nodeconductor/billing/migrations/0003_invoice_status.py | nodeconductor/billing/migrations/0003_invoice_status.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('billing', '0002_pricelist'),
]
operations = [
migrations.AddField(
model_name='invoice',
name='statu... | mit | Python | |
269a34e87797a3271013e23d504a6f6a159ae48e | Index testgroup_test.test_id | bowlofstew/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes | migrations/versions/3a3366fb7822_index_testgroup_test.py | migrations/versions/3a3366fb7822_index_testgroup_test.py | """Index testgroup_test.test_id
Revision ID: 3a3366fb7822
Revises: 139e272152de
Create Date: 2014-01-02 22:20:55.132222
"""
# revision identifiers, used by Alembic.
revision = '3a3366fb7822'
down_revision = '139e272152de'
from alembic import op
def upgrade():
op.create_index('idx_testgroup_test_test_id', 'tes... | apache-2.0 | Python | |
7b40a4902d1dc43c73a7858fc9286a641b3a9666 | Add validation function removed from main script. | COMBINE-lab/piquant,lweasel/piquant,lweasel/piquant | assess_isoform_quantification/options.py | assess_isoform_quantification/options.py | from schema import Schema
def validate_file_option(file_option, msg):
msg = "{msg} '{file}'.".format(msg=msg, file=file_option)
return Schema(open, error=msg).validate(file_option)
| mit | Python | |
d04118acc5421d4b48e31c78874a740eb469c3d7 | fix boan1244 'Boëng' | clld/glottolog3,clld/glottolog3 | migrations/versions/506dcac7d75_fix_boan1244_mojibake.py | migrations/versions/506dcac7d75_fix_boan1244_mojibake.py | # coding=utf-8
"""fix boan1244 mojibake
Revision ID: 506dcac7d75
Revises: 4513ba6253e1
Create Date: 2015-04-15 19:20:59.059000
"""
# revision identifiers, used by Alembic.
revision = '506dcac7d75'
down_revision = '4513ba6253e1'
import datetime
from alembic import op
import sqlalchemy as sa
def upgrade():
id,... | mit | Python | |
85e4a327ba641fbe9c275b4760c60683ca215d61 | Add unit tests. | gthank/pto,gthank/pto | test_pto.py | test_pto.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for PTO."""
import unittest
import pto
import time
_TIMEOUT = 5
_FUZZ_FACTOR = 1
class SlowClass(object):
@pto.timeout(_TIMEOUT)
def slow_instance_method(self):
cut_off = time.time() + _TIMEOUT
while time.time() < cut_off + _FUZZ_FACTO... | mit | Python | |
2067bdb9d0f9947a674cb94d0c988049f3038ea4 | create test stubs | BMJHayward/navtome,BMJHayward/navtome,BMJHayward/navtome,BMJHayward/navtome | test_viz.py | test_viz.py | def test_create_distance_matrix():
pass
def test_get_translation_table():
pass
def test_naive_backtranslate():
pass
def test_get_peptide_index():
pass
def test_demo_dna_features_viewer():
pass
def test_ngrams():
pass
def test_make_trigrams():
pass
def test_nucleotide_distribution():
... | mit | Python | |
e304aae71617cdba0ffcb720a24406375fb866a1 | Copy of Ryan's PCMToWave component. | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia | Sketches/MH/audio/ToWAV.py | Sketches/MH/audio/ToWAV.py | from Axon.Component import component
import string
import struct
from Axon.Ipc import producerFinished, shutdown
class PCMToWave(component):
def __init__(self, bytespersample, samplingfrequency):
super(PCMToWave, self).__init__()
self.bytespersample = bytespersample
self.samplingfrequency =... | apache-2.0 | Python | |
16275938769c16c79b89349612e8e7b2891de815 | Add migration for user manager | benjaoming/kolibri,jonboiser/kolibri,christianmemije/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,DXCanas/kolibri,mrpau/kolibri,benjaoming/kolibri,lyw07/kolibri,mrpau/kolibri,christianmemije/kolibri,learningequality/kolibri,jonboiser/kolibri,learningequality/kolibri,lyw07/kolibri,indirectlylit/kolibri,DXCanas/koli... | kolibri/auth/migrations/0008_auto_20180222_1244.py | kolibri/auth/migrations/0008_auto_20180222_1244.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-02-22 20:44
from __future__ import unicode_literals
import kolibri.auth.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0007_auto_20171226_1125'),
]
operations = [
... | mit | Python | |
74450edae5d327659ec618f7e160bc5dd37bd512 | 添加在Python2DWrapper中使用的Python文件 | MR-algorithms/YAP,MR-algorithms/YAP,MR-algorithms/YAP | PluginSDK/BasicRecon/Python/Py2C.py | PluginSDK/BasicRecon/Python/Py2C.py | from PIL import Image
import numpy as np
import matplotlib
"""
This is Module Py2C for c++
"""
class A: pass
class B: pass
def ShowImage(image, width, height):
img = [[]] * width
for x in range(width):
for y in range(height):
img[x] = img[x] + [image[x*width... | mit | Python | |
883aac8a282d4525e82d3eb151ea293c5577424c | Add data migration to create gesinv | tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador | core/migrations/0002_auto_20141008_0853.py | core/migrations/0002_auto_20141008_0853.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def create_extra_users(apps, schema_editor):
user = apps.get_model("auth.User").objects.create(username='GesInv-ULL')
apps.get_model("core", "UserProfile").objects.create(user=user,
... | agpl-3.0 | Python | |
e6181c5d7c95af23ee6d51d125642104782f5cf1 | Add solution for 136_Single Number with XOR operation. | comicxmz001/LeetCode,comicxmz001/LeetCode | Python/136_SingleNumber.py | Python/136_SingleNumber.py | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#Using XOR to find the single number.
#Because every number appears twice, while N^N=0, 0^N=N,
#XOR is cummutative, so the order of elements does not matter.
... | mit | Python | |
83ebfe1ff774f8d5fb5ae610590ca8fca1c87100 | add migration for on_delete changes | bcgov/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells | app/backend/wells/migrations/0034_auto_20181127_0230.py | app/backend/wells/migrations/0034_auto_20181127_0230.py | # Generated by Django 2.1.3 on 2018-11-27 02:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wells', '0033_auto_20181119_1857'),
]
operations = [
migrations.AlterField(
model_name='activit... | apache-2.0 | Python | |
59c62bb0f13be7910bf2280126a0909ffbe716f0 | Create simple_trie.py | nik-hil/scripts | simple_trie.py | simple_trie.py | class Trie:
def __init__(self):
self.node = {}
self.word = None
def add(self,string):
node = self.node
currentNode = None
for char in string:
currentNode = node.get(char, None)
if not currentNode:
node[char] = Trie()
... | mit | Python | |
983f041b25b0de77f3720378e12b22e7d8f2e040 | Create same_first_last.py | dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey | Python/CodingBat/same_first_last.py | Python/CodingBat/same_first_last.py | # http://codingbat.com/prob/p179078
def same_first_last(nums):
return ( len(nums) >= 1 and nums[0] == nums[-1] )
| mit | Python | |
ae6c6f3aa0863b919e0f00543cab737ae9e94129 | Add bubblesort as a placeholder for a refactored implementation | jonspeicher/blinkyfun | bubblesort.py | bubblesort.py | #!/usr/bin/env python
# TBD: Sort animation could take a pattern that it assumed to be "final",
# shuffle it, then take a sort generator that produced a step in the sort
# algorithm at every call. It would be sorting shuffled indices that the
# animation would use to construct each frame.
from blinkytape import blink... | mit | Python | |
3852ae6fcf6271ef19a182e5dfb199e4539536a1 | Create 6kyu_spelling_bee.py | Orange9000/Codewars,Orange9000/Codewars | Solutions/6kyu/6kyu_spelling_bee.py | Solutions/6kyu/6kyu_spelling_bee.py | from itertools import zip_longest as zlo
def how_many_bees(hive):
return sum(''.join(x).count('bee') + ''.join(x).count('eeb') for x in hive) + \
sum(''.join(y).count('bee') + ''.join(y).count('eeb') for y in zlo(*hive, fillvalue = '')) if hive else 0
| mit | Python | |
ddb58206a52ef46f5194bf6f5c11ac68b16ab9a8 | Create minimum-window-subsequence.py | tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode | Python/minimum-window-subsequence.py | Python/minimum-window-subsequence.py | # Time: O(S * T)
# Space: O(S)
class Solution(object):
def minWindow(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
dp = [[None for _ in xrange(len(S))] for _ in xrange(2)]
for i, c in enumerate(S):
if c == T[0]:
dp[0]... | mit | Python | |
eaca815937ebd1fbdd6ec5804dc52257d2775181 | Create time-gui.py | oriwen/time-check | time-gui.py | time-gui.py | from tkinter import *
import time
import sys
import datetime as dt
from datetime import timedelta
def validateTextInputSize(event):
""" Method to Validate Entry text input size """
global TEXT_MAXINPUTSIZE
if (event.widget.index(END) >= TEXT_MAXINPUTSIZE - 1):
event.widget.delete(TEXT_MAX... | unlicense | Python | |
077d4b8954918ed51c43429efd74b4911083c4f4 | Add instance_id field. | indirectlylit/kolibri,jtamiace/kolibri,lyw07/kolibri,mrpau/kolibri,learningequality/kolibri,rtibbles/kolibri,benjaoming/kolibri,mrpau/kolibri,jtamiace/kolibri,indirectlylit/kolibri,MingDai/kolibri,benjaoming/kolibri,jayoshih/kolibri,jtamiace/kolibri,christianmemije/kolibri,rtibbles/kolibri,jonboiser/kolibri,benjaoming/... | kolibri/content/migrations/0002_auto_20160630_1959.py | kolibri/content/migrations/0002_auto_20160630_1959.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-06-30 19:59
from __future__ import unicode_literals
from django.db import migrations, models
import kolibri.content.models
import uuid
class Migration(migrations.Migration):
dependencies = [
('content', '0001_initial'),
]
operations = ... | mit | Python | |
48172fa94043fb004dfaf564afac42e632be2bc0 | add test for DataManager | missionpinball/mpf,missionpinball/mpf | mpf/tests/test_DataManager.py | mpf/tests/test_DataManager.py | """Test the bonus mode."""
import time
from unittest.mock import mock_open, patch
from mpf.file_interfaces.yaml_interface import YamlInterface
from mpf.core.data_manager import DataManager
from mpf.tests.MpfTestCase import MpfTestCase
class TestDataManager(MpfTestCase):
def testSaveAndLoad(self):
YamlIn... | mit | Python | |
8d0f6ed81377e516c5bb266894a8cf39b6852383 | add multiple rsi sample | xclxxl414/rqalpha,xclxxl414/rqalpha | examples/multi_rsi.py | examples/multi_rsi.py | # 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。
import talib
import numpy as np
import math
import pandas
# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
#选择我们感兴趣的股票
context.s1 = "000001.XSHE"
context.s2 = "601988.XSHG"
context.s3 = "000068.XSHE"
context.stocks = [context.s1,con... | apache-2.0 | Python | |
859b3de112549f070e7b56901b86d40e8b8c1f51 | update scorer | MultimediaSemantics/entity2vec,MultimediaSemantics/entity2vec | lib/scorer.py | lib/scorer.py | import numpy as np
import pandas as pd
import json
#from SPARQLWrapper import SPARQLWrapper, JSON
from collections import defaultdict
from operator import itemgetter
from sklearn.metrics.pairwise import cosine_similarity, linear_kernel
import optparse
from ranking import ndcg_at_k, average_precision
def scorer(embed... | apache-2.0 | Python | |
3dcfc2f7e9a2ed696a2b4a006e4d8a233a494f2f | move sitemap to core | agepoly/DjangoBB,slav0nic/DjangoBB,slav0nic/DjangoBB,hsoft/DjangoBB,saifrahmed/DjangoBB,agepoly/DjangoBB,saifrahmed/DjangoBB,agepoly/DjangoBB,hsoft/DjangoBB,hsoft/DjangoBB,hsoft/slimbb,hsoft/slimbb,slav0nic/DjangoBB,hsoft/slimbb,saifrahmed/DjangoBB | djangobb_forum/sitemap.py | djangobb_forum/sitemap.py | from django.contrib.sitemaps import Sitemap
from djangobb_forum.models import Forum, Topic
class SitemapForum(Sitemap):
priority = 0.5
def items(self):
return Forum.objects.all()
class SitemapTopic(Sitemap):
priority = 0.5
def items(self):
return Topic.objects.all() | bsd-3-clause | Python | |
a6f26893189376f64b6be5121e840acc4cfeebae | ADD utils.py : model_to_json / expand_user_database methods | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | packages/syft/src/syft/core/node/common/tables/utils.py | packages/syft/src/syft/core/node/common/tables/utils.py | # grid relative
from .groups import Group
from .usergroup import UserGroup
from .roles import Role
def model_to_json(model):
"""Returns a JSON representation of an SQLAlchemy-backed object."""
json = {}
for col in model.__mapper__.attrs.keys():
if col != "hashed_password" and col != "salt":
... | apache-2.0 | Python | |
d7d0af678a52b357ecf479660ccee1eab43c443f | Add gender choices model | masschallenge/django-accelerator,masschallenge/django-accelerator | accelerator/models/gender_choices.py | accelerator/models/gender_choices.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from accelerator_abstract.models import BaseGenderChoices
class GenderChoices(BaseGenderChoices):
class Meta(BaseGenderChoices.Meta):
swappable = swapper.swappable_setting(
BaseGen... | mit | Python | |
95edeaa711e8c33e1b431f792e0f2638126ed461 | Add test case for dynamic ast | cornell-brg/pymtl,cornell-brg/pymtl,cornell-brg/pymtl | pymtl/tools/translation/dynamic_ast_test.py | pymtl/tools/translation/dynamic_ast_test.py | #=======================================================================
# verilog_from_ast_test.py
#=======================================================================
# This is the test case that verifies the dynamic AST support of PyMTL.
# This test is contributed by Zhuanhao Wu through #169, #170 of PyMTL v2.
#... | bsd-3-clause | Python | |
49cab51aa8697a56c7cf74e45b77d9a20ad1a178 | add topk/gen.py | chenshuo/recipes,chenshuo/recipes,chenshuo/recipes,chenshuo/recipes,chenshuo/recipes,chenshuo/recipes | topk/gen.py | topk/gen.py | #!/usr/bin/python
import random
word_len = 5
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-'
output = open('word_count', 'w')
words = set()
N = 1000*1000
for x in xrange(N):
arr = [random.choice(alphabet) for i in range(word_len)]
words.add(''.join(arr))
print len(words)
for wo... | bsd-3-clause | Python | |
c5da52c38d280873066288977f021621cb9653d0 | Apply orphaned migration | barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api | project/apps/api/migrations/0010_remove_chart_song.py | project/apps/api/migrations/0010_remove_chart_song.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0009_auto_20150722_1041'),
]
operations = [
migrations.RemoveField(
model_name='chart',
name=... | bsd-2-clause | Python | |
ab5d1fd5728b9c2f27d74c2896e05a94b061f3f9 | add config.py | Plantain/sms-mailinglist,Plantain/sms-mailinglist,Plantain/sms-mailinglist,Plantain/sms-mailinglist | config.py | config.py | # twilio account details
account = ""
token = ""
| apache-2.0 | Python | |
42cc2864f03480e29e55bb0ef0b30e823c11eb2f | complete check online window | misterlihao/network-programming-project | check_online_window.py | check_online_window.py | import tkinter as tk
import tkinter.messagebox as tkmb
from online_check import CheckSomeoneOnline
class open_check_online_window():
def __init__(self, x, y):
self.co = tk.Tk()
self.co.title('enter ip to check')
self.co.resizable(False, False)
self.co.wm_attributes("-toolwindow", 1)... | mit | Python | |
05b9859fb7d4577dfa95ec9edd3a6f16bf0fd86e | Create __init__.py | rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python | fade/fade/__init__.py | fade/fade/__init__.py | bsd-3-clause | Python | ||
1b6fecb5819fbead0aadcc1a8669e915542c5ea0 | Add script for gameifying testing | spotify/testing-game,spotify/testing-game,spotify/testing-game,spotify/testing-game | other/testing-game.py | other/testing-game.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import os
import subprocess
import re
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory', help='The directory to search for files in', required=False, default=os.getcwd())
args = parser.parse_args()
names = {}
for root, dirs, files in... | apache-2.0 | Python | |
908013aa5e64589b6c1c6495812a13109244a69a | add dottests testconfig, but leave it deactivted yet. lots of import failures, since no imports are declared explicitly | nylas/icalendar,geier/icalendar,untitaker/icalendar | src/icalendar/tests/XXX_test_doctests.py | src/icalendar/tests/XXX_test_doctests.py | from interlude import interact
import doctest
import os.path
import unittest
OPTIONFLAGS = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
DOCFILES = [
'example.txt',
'groupscheduled.txt',
'multiple.txt',
'recurrence.txt',
'small.txt'
]
DOCMODS = [
'icalendar.caselessdict',
'icalendar.cal... | bsd-2-clause | Python | |
4a99dcd629a830ad1ec0c658f312a4793dec240b | add basic file for parser | SamuraiT/RedBlue,SamuraiT/RedBlue | RedBlue/Parser3.py | RedBlue/Parser3.py |
class Parser(object):
@classmethod
def read_html(cls, html):
pass
| bsd-3-clause | Python | |
0648ca26ba195e4d5ce55d801975a161907e655f | Add test for translation | czpython/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq | aldryn_faq/tests/test_aldryn_faq.py | aldryn_faq/tests/test_aldryn_faq.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase # , TransactionTestCase
# from django.utils import translation
from hvad.test_utils.context_managers import LanguageOverride
from aldryn_faq.models import Category, Question
EN_CAT_NAME = "Example"
EN_CAT_SLUG = "examp... | bsd-3-clause | Python | |
d1f71e1c6468799247d07d810a6db7d0ad5f89b0 | add support for jinja2 template engine | PythonZone/PyAlaOCL,megaplanet/PyAlaOCL | alaocl/jinja2.py | alaocl/jinja2.py | from alaocl import *
#__all__ = (
# 'addOCLtoEnvironment',
#)
_FILTERS = {
'asSet': asSet,
'asBag': asBag,
'asSeq': asSeq,
}
_GLOBALS = {
'floor': floor,
'isUndefined': isUndefined,
'oclIsUndefined': oclIsUndefined,
'oclIsKindOf': oclIsKindOf,
'oclIsTypeOf': oclIsTypeOf,
'isColl... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.