commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
f681f6ac7764b0944434c69febb2b3b778f2aad7
|
add 2
|
leetcode/2.py
|
leetcode/2.py
|
Python
| 0.999999 |
@@ -0,0 +1,1277 @@
+# Definition for singly-linked list.%0A# class ListNode(object):%0A# def __init__(self, x):%0A# self.val = x%0A# self.next = None%0A%0Aclass Solution(object):%0A def addTwoNumbers(self, l1, l2):%0A %22%22%22%0A :type l1: ListNode%0A :type l2: ListNode%0A :rtype: ListNode%0A %22%22%22%0A %0A if l1 == None: return l2%0A if l2 == None: return l1%0A %0A head = res = ListNode(0)%0A carrier = 0%0A %0A while l1 != None and l2 != None:%0A val = l1.val + l2.val + carrier%0A carrier = val / 10%0A val = val %25 10%0A head.next = ListNode(val)%0A head = head.next%0A l1 = l1.next%0A l2 = l2.next%0A %0A while l1 != None:%0A val = l1.val + carrier%0A carrier = val / 10%0A val = val %25 10%0A head.next = ListNode(val)%0A head = head.next%0A l1 = l1.next%0A %0A while l2 != None:%0A val = l2.val + carrier%0A carrier = val / 10%0A val = val %25 10%0A head.next = ListNode(val)%0A head = head.next%0A l2 = l2.next%0A %0A if carrier != 0:%0A head.next = ListNode(carrier)%0A %0A return res.next
|
|
45686564547ccf1f40516d2ecbcf550bb904d59c
|
Create lc1032.py
|
LeetCode/lc1032.py
|
LeetCode/lc1032.py
|
Python
| 0.000002 |
@@ -0,0 +1,2663 @@
+import queue %0A%0Aclass Node:%0A def __init__(self, s=''):%0A self.s = s%0A self.end = False%0A self.fail = None%0A self.children = None%0A def get(self, index):%0A if self.children == None:%0A return None%0A return self.children%5Bindex%5D%0A def set(self, index, node):%0A if self.children == None:%0A self.children = %5BNone for _ in range(26)%5D%0A self.children%5Bindex%5D = node%0A def add(self, index):%0A if self.children == None:%0A self.children = %5BNone for _ in range(26)%5D%0A if self.children%5Bindex%5D == None: %0A self.children%5Bindex%5D = Node(self.s + chr(ord('a') + index))%0A return self.children%5Bindex%5D%0A def next(self, index):%0A p = self%0A while p.get(index) == None:%0A #print(%22fail%22, p, p.fail)%0A p = p.fail%0A #print(p, p.get(index))%0A return p.get(index)%0A%0Adef buildFail(root):%0A q = queue.Queue()%0A q.put(root)%0A while not q.empty():%0A node = q.get()%0A #print(%22node%22, node.s)%0A if node.children == None:%0A continue%0A for i in range(26):%0A cnode = node.get(i)%0A if cnode == None:%0A continue%0A #print(%22cnode:%22, cnode.s)%0A if node == root:%0A cnode.fail = root%0A else:%0A p = node.fail%0A while p != None:%0A if p.get(i) == None:%0A p = p.fail%0A else:%0A break%0A if p == None:%0A cnode.fail = root%0A else:%0A cnode.fail = p.get(i)%0A #print(%22cnode fail:%22, cnode.s, cnode.fail.s)%0A if cnode.end == False and cnode.fail.end == True:%0A cnode.end = True%0A q.put(cnode)%0A for i in range(26):%0A if root.get(i) == None:%0A root.set(i, root)%0A root.fail = root%0A %0A %0Adef c2i(c):%0A return ord(c) - ord('a')%0A%0Aclass StreamChecker:%0A def __init__(self, words: List%5Bstr%5D):%0A self.words = words%0A root = Node()%0A for i in range(len(words)):%0A p = root%0A for j in range(len(words%5Bi%5D)):%0A p = p.add(c2i(words%5Bi%5D%5Bj%5D))%0A p.end = True%0A #print(root)%0A buildFail(root)%0A self.cur = root%0A def query(self, letter: str) -%3E bool:%0A #print('cur', self.cur, letter)%0A self.cur = self.cur.next(c2i(letter))%0A #print(%22end%22, self.cur.end)%0A return self.cur.end%0A%0A%0A# Your StreamChecker object will be instantiated and called as such:%0A# obj = StreamChecker(words)%0A# param_1 = obj.query(letter)%0A
|
|
4df1339140dfe7491058fa4ff6ed6a0be82d4cab
|
Add "time" role to the mixpanel time dimension
|
cubes/backends/mixpanel/store.py
|
cubes/backends/mixpanel/store.py
|
# -*- coding=utf -*-
from ...model import Cube, create_dimension
from ...model import aggregate_list
from ...browser import *
from ...stores import Store
from ...errors import *
from ...providers import ModelProvider
from ...logging import get_logger
from .mixpanel import *
from .mapper import cube_event_key
from string import capwords
import pkgutil
import time, pytz
DIMENSION_COUNT_LIMIT = 100
DEFAULT_TIME_HIERARCHY = "ymdh"
MXP_TIME_DIM_METADATA = {
"name": "time",
"levels": [
{ "name": "year", "label": "Year" },
{ "name": "month", "label": "Month", "info": { "aggregation_units": 3 }},
{ "name": "day", "label": "Day", "info": { "aggregation_units": 7 } },
{ "name": "hour", "label": "Hour", "info": { "aggregation_units": 6 } },
{ "name": "week", "label": "Week", "info": { "aggregation_units": 4 } },
{ "name": "date", "label": "Date", "info": { "aggregation_units": 7 } }
],
"hierarchies": [
{"name": "ymdh", "levels": ["year", "month", "day", "hour"]},
{"name": "wdh", "levels": ["week", "date", "hour"]}
],
"default_hierarchy_name": "ymdh",
"info": {"is_date": True}
}
MXP_AGGREGATES_METADATA = [
{
"name": "total",
"label": "Total"
},
{
"name": "total_sma",
"label": "Total Moving Average",
"function": "sma",
"measure": "total"
},
{
"name": "unique",
"label": "Unique"
},
{
"name": "unique_sma",
"label": "Unique Moving Average",
"function": "sma",
"measure": "unique"
},
]
_time_dimension = create_dimension(MXP_TIME_DIM_METADATA)
def _mangle_dimension_name(name):
"""Return a dimension name from a mixpanel property name."""
fixed_name = name.replace("$", "_")
fixed_name = fixed_name.replace(" ", "_")
return fixed_name
class MixpanelModelProvider(ModelProvider):
def __init__(self, *args, **kwargs):
super(MixpanelModelProvider, self).__init__(*args, **kwargs)
# TODO: replace this with mixpanel mapper
# Map properties to dimension (reverse mapping)
self.property_to_dimension = {}
self.event_to_cube = {}
self.cube_to_event = {}
mappings = self.metadata.get("mappings", {})
# Move this into the Mixpanel Mapper
for name in self.dimensions_metadata.keys():
try:
prop = mappings[name]
except KeyError:
pass
else:
self.property_to_dimension[prop] = name
for name in self.cubes_metadata.keys():
try:
event = mappings[cube_event_key(name)]
except KeyError:
pass
else:
self.cube_to_event[name] = event
self.event_to_cube[event] = name
def default_metadata(self, metadata=None):
"""Return Mixpanel's default metadata."""
model = pkgutil.get_data("cubes.backends.mixpanel", "mixpanel_model.json")
metadata = json.loads(model)
return metadata
def requires_store(self):
return True
def public_dimensions(self):
"""Return an empty list. Mixpanel does not export any dimensions."""
return []
def cube(self, name):
"""Creates a mixpanel cube with following variables:
* `name` – cube name
* `measures` – cube measures: `total` and `uniques`
* `linked_dimensions` – list of linked dimension names
* `mappings` – mapping of corrected dimension names
Dimensions are Mixpanel's properties where ``$`` character is replaced
by the underscore ``_`` character.
"""
params = {
"event": self.cube_to_event.get(name, name),
"limit": DIMENSION_COUNT_LIMIT
}
result = self.store.request(["events", "properties", "top"], params)
if not result:
raise NoSuchCubeError("Unknown Mixpanel cube %s" % name, name)
try:
metadata = self.cube_metadata(name)
except NoSuchCubeError:
metadata = {}
options = self.cube_options(name)
allowed_dims = options.get("allowed_dimensions", [])
denied_dims = options.get("denied_dimensions", [])
dims = ["time"]
mappings = {}
for prop in result.keys():
try:
dim_name = self.property_to_dimension[prop]
except KeyError:
dim_name = _mangle_dimension_name(prop)
# Skip not allowed dimensions
if (allowed_dims and dim_name not in allowed_dims) or \
(denied_dims and dim_name in denied_dims):
continue
if dim_name != prop:
mappings[dim_name] = prop
dims.append(dim_name)
aggregates = aggregate_list(MXP_AGGREGATES_METADATA)
label = metadata.get("label", capwords(name.replace("_", " ")))
category = metadata.get("category", self.store.category)
cube = Cube(name=name,
aggregates=aggregates,
label=label,
description=category,
info=metadata.get("info"),
linked_dimensions=dims,
datastore=self.store_name,
mappings=mappings,
category=category)
# TODO: required_drilldowns might be a cube's attribute (fixed_dd?)
cube.info = {
"required_drilldowns": ["time"]
}
return cube
def dimension(self, name, dimensions=[]):
if name == "time":
return _time_dimension
try:
metadata = self.dimension_metadata(name)
except KeyError:
metadata = {"name": name}
return create_dimension(metadata)
def list_cubes(self):
result = self.store.request(["events", "names"], {"type": "general", })
cubes = []
for event in result:
name = self.event_to_cube.get(event, event)
try:
metadata = self.cube_metadata(name)
except NoSuchCubeError:
metadata = {}
label = metadata.get("label", capwords(name.replace("_", " ")))
category = metadata.get("category", self.store.category)
cube = {
"name": name,
"label": label,
"category": category
}
cubes.append(cube)
return cubes
class MixpanelStore(Store):
def __init__(self, api_key, api_secret, category=None, tz=None):
self.mixpanel = Mixpanel(api_key, api_secret)
self.category = category or "Mixpanel Events"
if tz is not None:
tz = pytz.timezone(tz)
else:
tz = pytz.timezone(time.strftime('%Z', time.localtime()))
self.tz = tz
self.logger = get_logger()
def request(self, *args, **kwargs):
"""Performs a mixpanel HTTP request. Raises a BackendError when
mixpanel returns `error` in the response."""
self.logger.debug("Mixpanel request: %s" % (args,))
try:
response = self.mixpanel.request(*args, **kwargs)
except MixpanelError as e:
raise BackendError("Mixpanel request error: %s" % str(e))
return response
|
Python
| 0.000004 |
@@ -469,24 +469,44 @@
e%22: %22time%22,%0A
+ %22role%22: %22time%22,%0A
%22levels%22
|
2c2d594b7d8d5d74732e30c46859779b88621baa
|
Create __init__.py
|
FireModules/__init__.py
|
FireModules/__init__.py
|
Python
| 0.000429 |
@@ -0,0 +1 @@
+%0A
|
|
54a10f78a6c71d88e1c2441bb636e6b636f74613
|
add unit test
|
rstem/led2/test_unittest.py
|
rstem/led2/test_unittest.py
|
Python
| 0.000001 |
@@ -0,0 +1,3120 @@
+#!/usr/bin/python3%0A%0Aimport unittest%0Aimport os%0Afrom rstem import led2%0A%0A# TODO: single setup for all testcases????%0A# TODO: make hardware versions that you can optionally skip%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A %0Adef query(question):%0A ret = int(input(question + %22 %5Byes=1,no=0%5D: %22))%0A if ret == 1:%0A return True%0A elif ret == 0:%0A return False%0A else:%0A raise ValueError(%22Please only provide 1 or 0. Thank You!%22)%0A%0Aclass PrivateFunctions(unittest.TestCase):%0A %0A def test_valid_color(self):%0A for i in range(16):%0A self.assertTrue(led2._valid_color(i))%0A self.assertTrue(led2._valid_color(hex(i)%5B2:%5D))%0A self.assertTrue(led2._valid_color('-'))%0A self.assertFalse(led2._valid_color(17))%0A self.assertFalse(led2._valid_color(-1))%0A # random invalid characters%0A self.assertFalse(led2._valid_color('j'))%0A self.assertFalse(led2._valid_color('%25'))%0A self.assertFalse(led2._valid_color('10')) #TODO : should we allow none hex versions?%0A %0A def test_convert_color(self):%0A self.assertRaises(ValueError, led2._convert_color('J')) # FIXME: syntax correct?%0A for i in range(16):%0A self.assertEquals(led2._convert_color(hex(i)%5B2:%5D), i)%0A self.assertEquals(led2._convert_color(i), i)%0A%0Aclass PrimativeFunctions(unittest.TestCase):%0A %0A def setUp(self):%0A led2.initGrid(1,2)%0A %0A def tearDown(self):%0A led2.close()%0A %0A def test_point(self):%0A for y in range(8):%0A for x in range(16):%0A # test without a color%0A self.assertEquals(led2.point(x,y), 1)%0A self.assertEquals(led2.point((x,y)), 1)%0A # test with all the colors%0A for color in range(17):%0A self.assertEquals(led2.point(x,y), 1)%0A self.assertEquals(led2.point((x,y)), 1)%0A self.assertEquals(led2.show(), 1)%0A self.assertTrue(query(%22Is the entire matrix at full brightness?%22))%0A %0A def test_line(self):%0A self.assertEquals(led2.point((0,0),(15,7)), 1)%0A self.assertEquals(led2.show(), 1)%0A self.assertTrue(query(%22Is there a line from (0,0) to (15,7)?%22))%0A %0Aclass TestingSprites(unittest.TestCase):%0A %0A def setUp(self):%0A led2.initGrid(1,2)%0A %0A def tearDown(self):%0A led2.close()%0A %0A def test_init_sprite(self):%0A if font_path is None: # if none, set up default font location%0A this_dir, this_filename = os.path.split(__file__)%0A self.assertEquals(led2.sprite(this_dir + %22/test_sprite%22), 1)%0A self.assertEquals(led2.show(), 1)%0A self.assertTrue(query(%22Do you see the test pattern on the left led matrix?%22))%0A self.assertEquals(led2.fill(0), 1)%0A self.assertEquals(led2.show(), 1)%0A self.assertFalse(query(%22What about now?%22))%0A %0A def test_text(self):%0A self.assertNotEquals(led2.text(%22jon%22), 0)%0A self.assertEquals(led2.show(), 1)%0A self.assertTrue(query(%22Is 'jon' displayed with large font?%22))%0A %0A %0A
|
|
f0587e44be1c7f85dbbf54e1d6c47458a4960d7c
|
Create date_time.py
|
date_time.py
|
date_time.py
|
Python
| 0.000939 |
@@ -0,0 +1,1032 @@
+#!/usr/bin/env python%0A# -*_ coding: utf-8 -*-%0Aimport datetime%0Aimport sys%0A%0A%0Adef main():%0A%0A now = datetime.datetime.now()%0A%0A while True:%0A user_request = input(%22%5CnCurrent %5Btime, day, date%5D: %22)%0A%0A if user_request == %22quit%22:%0A sys.exit()%0A%0A if user_request == %22time%22:%0A second = str(now.second)%0A time_request = (str(now.hour)%0A + %22:%22%0A + str(now.minute)%0A + %22:%22%0A + str(now.second))%0A print(%22%5CnIt is: %22 + time_request)%0A%0A if user_request == %22day%22:%0A day_request = str(now.strftime(%22%25A%22))%0A print(%22%5CnIt is %22 + day_request)%0A%0A if user_request == %22date%22:%0A date_request = (str(now.year)%0A + %22-%22%0A + str(now.month)%0A + %22-%22%0A + str(now.day))%0A print(%22%5CnIt is: %22 + date_request)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
c15f8805d3ce5eab9f46dc24a6845ce27b117ac3
|
Add TeamTest
|
dbaas/account/tests/test_team.py
|
dbaas/account/tests/test_team.py
|
Python
| 0 |
@@ -0,0 +1,720 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import absolute_import, unicode_literals%0Afrom django.test import TestCase%0Afrom django.db import IntegrityError%0Afrom . import factory%0Afrom ..models import Team%0Afrom drivers import base%0A%0Aimport logging%0A%0ALOG = logging.getLogger(__name__)%0A%0Aclass TeamTest(TestCase):%0A%0A def setUp(self):%0A self.new_team = factory.TeamFactory()%0A%0A def test_create_new_team(self):%0A %22%22%22 %0A Test new Team creation %0A %22%22%22%0A self.assertTrue(self.new_team.pk) %0A%0A def test_cant_create_a_new_user(self):%0A self.team = Team()%0A self.team.name = %22Team1%22%0A self.team.role_id = factory.RoleFactory().pk%0A %0A self.assertFalse(self.team.save())%0A
|
|
264863c1a8d60dd35babec22470626d13ebf3e66
|
Remove unused import.t
|
debug_toolbar/panels/__init__.py
|
debug_toolbar/panels/__init__.py
|
from __future__ import absolute_import, unicode_literals
import warnings
from django.template.defaultfilters import slugify
from django.template.loader import render_to_string
class Panel(object):
"""
Base class for panels.
"""
# name = 'Base'
# template = 'debug_toolbar/panels/base.html'
# If content returns something, set to True in subclass
has_content = False
# We'll maintain a local context instance so we can expose our template
# context variables to panels which need them:
context = {}
# Panel methods
def __init__(self, toolbar, context={}):
self.toolbar = toolbar
self.context.update(context)
def content(self):
if self.has_content:
context = self.context.copy()
context.update(self.get_stats())
return render_to_string(self.template, context)
@property
def panel_id(self):
return self.__class__.__name__
@property
def enabled(self):
return self.toolbar.request.COOKIES.get('djdt' + self.panel_id, 'on') == 'on'
# URLs for panel-specific views
@classmethod
def get_urls(cls):
return []
# Titles and subtitles
def nav_title(self):
"""Title showing in sidebar"""
raise NotImplementedError
def nav_subtitle(self):
"""Subtitle showing under title in sidebar"""
return ''
def title(self):
"""Title showing in panel"""
raise NotImplementedError
# Enable and disable (expensive) instrumentation, must be idempotent
def enable_instrumentation(self):
pass
def disable_instrumentation(self):
pass
# Store and retrieve stats (shared between panels for no good reason)
def record_stats(self, stats):
self.toolbar.stats.setdefault(self.panel_id, {}).update(stats)
def get_stats(self):
return self.toolbar.stats.get(self.panel_id, {})
# Standard middleware methods
def process_request(self, request):
pass
def process_view(self, request, view_func, view_args, view_kwargs):
pass
def process_response(self, request, response):
pass
# Backward-compatibility for 1.0, remove in 2.0.
class DebugPanel(Panel):
def __init__(self, *args, **kwargs):
warnings.warn("DebugPanel was renamed to Panel.", DeprecationWarning)
super(DebugPanel, self).__init__(*args, **kwargs)
|
Python
| 0 |
@@ -72,59 +72,8 @@
gs%0A%0A
-from django.template.defaultfilters import slugify%0A
from
|
4bfd69bc49b17e7844077949560bd6259ea33e9b
|
test the root scrubadub api
|
tests/test_api.py
|
tests/test_api.py
|
Python
| 0.000007 |
@@ -0,0 +1,1963 @@
+import unittest%0Aimport scrubadub%0A%0A%0Aclass APITestCase(unittest.TestCase):%0A%0A def test_clean(self):%0A %22%22%22Test the top level clean api%22%22%22%0A self.assertEqual(%0A scrubadub.clean(%22This is a test message for [email protected]%22),%0A %22This is a test message for %7B%7BEMAIL%7D%7D%22,%0A )%0A%0A def test_clean_docuemnts(self):%0A %22%22%22Test the top level clean_docuemnts api%22%22%22%0A self.assertEqual(%0A scrubadub.clean_documents(%0A %7B%0A %22first.txt%22: %22This is a test message for [email protected]%22,%0A %22second.txt%22: %22Hello Jane I am Tom.%22,%0A %7D%0A ),%0A %7B%0A %22first.txt%22: %22This is a test message for %7B%7BEMAIL%7D%7D%22,%0A %22second.txt%22: %22Hello %7B%7BNAME%7D%7D I am %7B%7BNAME%7D%7D.%22,%0A %7D%0A )%0A%0A def test_list_filth(self):%0A %22%22%22Test the top level list_filth api%22%22%22%0A filths = scrubadub.list_filth(%22This is a test message for [email protected]%22)%0A self.assertEqual(%0A filths,%0A %5Bscrubadub.filth.EmailFilth(text='[email protected]', detector_name='email', beg=27, end=46)%5D,%0A )%0A%0A def test_list_filth_docuemnts(self):%0A %22%22%22Test the top level list_filth_docuemnts api%22%22%22%0A filths = scrubadub.list_filth_documents(%0A %7B%0A %22first.txt%22: %22This is a test message for [email protected]%22,%0A %22second.txt%22: %22Hello Jane I am Tom.%22,%0A %7D%0A )%0A print(filths)%0A self.assertEqual(%0A filths,%0A %5B%0A scrubadub.filth.EmailFilth(text='[email protected]', document_name='first.txt', detector_name='email', beg=27, end=46),%0A scrubadub.filth.NameFilth(text='Jane', document_name='second.txt', detector_name='name', beg=6, end=10),%0A scrubadub.filth.NameFilth(text='Tom', document_name='second.txt', detector_name='name', beg=16, end=19)%0A %5D%0A )%0A
|
|
cd906789b4ed339542722c04dd09f8aca04fd7ff
|
add missing revision
|
crowdsourcing/migrations/0170_task_price.py
|
crowdsourcing/migrations/0170_task_price.py
|
Python
| 0.000004 |
@@ -0,0 +1,446 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9 on 2017-05-24 00:15%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('crowdsourcing', '0169_auto_20170524_0002'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='task',%0A name='price',%0A field=models.FloatField(null=True),%0A ),%0A %5D%0A
|
|
369dff642883ded68eca98754ce81369634da94d
|
Add box tests
|
tests/test_box.py
|
tests/test_box.py
|
Python
| 0.000001 |
@@ -0,0 +1,811 @@
+import pytest%0A%0Afrom rich.box import ASCII, DOUBLE, ROUNDED, HEAVY%0A%0A%0Adef test_str():%0A assert str(ASCII) == %22+--+%5Cn%7C %7C%7C%5Cn%7C-+%7C%5Cn%7C %7C%7C%5Cn%7C-+%7C%5Cn%7C-+%7C%5Cn%7C %7C%7C%5Cn+--+%5Cn%22%0A%0A%0Adef test_repr():%0A assert repr(ASCII) == %22Box(...)%22%0A%0A%0Adef test_get_top():%0A top = HEAVY.get_top(widths=%5B1, 2%5D)%0A assert top == %22%E2%94%8F%E2%94%81%E2%94%B3%E2%94%81%E2%94%81%E2%94%93%22%0A%0A%0Adef test_get_row():%0A head_row = DOUBLE.get_row(widths=%5B3, 2, 1%5D, level=%22head%22)%0A assert head_row == %22%E2%95%A0%E2%95%90%E2%95%90%E2%95%90%E2%95%AC%E2%95%90%E2%95%90%E2%95%AC%E2%95%90%E2%95%A3%22%0A%0A row = ASCII.get_row(widths=%5B1, 2, 3%5D, level=%22row%22)%0A assert row == %22%7C-+--+---%7C%22%0A%0A foot_row = ROUNDED.get_row(widths=%5B2, 1, 3%5D, level=%22foot%22)%0A assert foot_row == %22%E2%94%9C%E2%94%80%E2%94%80%E2%94%BC%E2%94%80%E2%94%BC%E2%94%80%E2%94%80%E2%94%80%E2%94%A4%22 %0A%0A with pytest.raises(ValueError):%0A ROUNDED.get_row(widths=%5B1, 2, 3%5D, level=%22FOO%22)%0A%0A%0Adef test_get_bottom():%0A bottom = HEAVY.get_bottom(widths=%5B1, 2, 3%5D)%0A assert bottom == %22%E2%94%97%E2%94%81%E2%94%BB%E2%94%81%E2%94%81%E2%94%BB%E2%94%81%E2%94%81%E2%94%81%E2%94%9B%22%0A
|
|
dbaad481ab9ddbdccd4430765e3eee0d0433fbd8
|
Create doc_check.py
|
doc_check.py
|
doc_check.py
|
Python
| 0.000001 |
@@ -0,0 +1,1500 @@
+import requests,json,ctypes,time%0A%0Atasks = %5B%0A # speciality_id, clinic_id, name '' - for any name, description%0A (40,279,'','%D0%9D%D0%B5%D0%B2%D1%80%D0%BE%D0%BB%D0%BE%D0%B3'),%0A (2122,314,'%D0%93%D1%83%D1%81%D0%B0%D1%80%D0%BE%D0%B2','%D0%94%D0%B5%D1%80%D0%BC%D0%B0%D1%82%D0%BE%D0%BB%D0%BE%D0%B3'),%0A %5D%0A%0A %0Ah = %7B 'Host': 'gorzdrav.spb.ru',%0A'Connection': 'keep-alive',%0A'Accept': '*/*',%0A'X-Requested-With': 'XMLHttpRequest',%0A'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',%0A'Sec-Fetch-Mode': 'cors',%0A'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',%0A'Origin': 'https://gorzdrav.spb.ru',%0A'Sec-Fetch-Site': 'same-origin',%0A'Referer': 'https://gorzdrav.spb.ru/signup/free/',%0A'Accept-Encoding': 'gzip, deflate, br',%0A'Accept-Language': 'ru-RU,ru;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6'%7D%0A%0Adef doc_check():%0A for task in tasks:%0A r = requests.post(%22https://gorzdrav.spb.ru/api/doctor_list/%22,%0A data=%22speciality_form-speciality_id=%22+str(task%5B0%5D)+%22&speciality_form-clinic_id=+%22+str(task%5B1%5D)+%22&speciality_form-patient_id=&speciality_form-history_id=%22,%0A headers=h)%0A resp = json.loads(r.text)%0A for doc in resp%5B'response'%5D:%0A if doc%5B'CountFreeTicket'%5D is not 0 and task%5B2%5D in doc%5B'Name'%5D:%0A ctypes.windll.user32.MessageBoxW(0, %22New ticket avalible!%5Cn%22+task%5B3%5D+%22 match: %22 + task%5B2%5D, time.ctime(), 4096)%0A if task%5B2%5D is '':%0A break%0A %0A %0A %0A%0A%0Awhile True:%0A doc_check()%0A time.sleep(65)%0A
|
|
8eec6e7596e8a5bd8159753be2aeaaffb53f613b
|
Add Python version
|
Python/shorturl.py
|
Python/shorturl.py
|
Python
| 0.000023 |
@@ -0,0 +1,938 @@
+class ShortURL:%0A%09%22%22%22%0A%09ShortURL: Bijective conversion between natural numbers (IDs) and short strings%0A%0A%09ShortURL.encode() takes an ID and turns it into a short string%0A%09ShortURL.decode() takes a short string and turns it into an ID%0A%0A%09Features:%0A%09+ large alphabet (51 chars) and thus very short resulting strings%0A%09+ proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u')%0A%09+ unambiguous (removed 'I', 'l', '1', 'O' and '0')%0A%0A%09Example output:%0A%09123456789 %3C=%3E pgK8p%0A%0A%09Source: https://github.com/delight-im/ShortURL (Apache License 2.0)%0A%09%22%22%22%0A%0A%09_alphabet = '23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_'%0A%09_base = len(_alphabet)%0A%0A%09def encode(self, number):%0A%09%09string = ''%0A%09%09while(number %3E 0):%0A%09%09%09string = self._alphabet%5Bnumber %25 self._base%5D + string%0A%09%09%09number //= self._base%0A%09%09return string%0A%0A%09def decode(self, string):%0A%09%09number = 0%0A%09%09for char in string:%0A%09%09%09number = number * self._base + self._alphabet.index(char)%0A%09%09return number%0A
|
|
7a5ca2f63dab36664ace637b713d7772870a800a
|
Create make-fingerprint.py
|
make-fingerprint.py
|
make-fingerprint.py
|
Python
| 0.000102 |
@@ -0,0 +1 @@
+%0A
|
|
cd7187dc916ebbd49a324f1f43b24fbb44e9c9dc
|
Create afstand_sensor.py
|
afstand_sensor.py
|
afstand_sensor.py
|
Python
| 0.000011 |
@@ -0,0 +1,317 @@
+import gpiozero%0Afrom time import sleep%0A%0Asensor = gpiozero.DistanceSensor(echo=18,trigger=17,max_distance=2, threshold_distance=0.5)%0Aled = gpiozero.LED(22)%0A%0Awhile True:%0A afstand = round(sensor.distance*100)%0A print('obstakel op', afstand, 'cm')%0A if sensor.in_range:%0A led.on()%0A sleep(1)%0A led.off()%0A
|
|
f1bda6deeb97c50a5606bea59d1684d6d96b10b4
|
Create api_call.py
|
PYTHON/api_call.py
|
PYTHON/api_call.py
|
Python
| 0.000002 |
@@ -0,0 +1,1475 @@
+def product_import_tme(request):%0A # /product/product_import_tme/%0A%0A token = '%3Cyour's token(Anonymous key:)%3E'%0A app_secret = '%3CApplication secret%3E'%0A%0A params = %7B%0A 'SymbolList%5B0%5D': '1N4007',%0A 'Country': 'PL',%0A 'Currency': 'PLN',%0A 'Language': 'PL',%0A %7D%0A%0A response = api_call('Products/GetPrices', params, token, app_secret, True);%0A response = json.loads(response)%0A print response%0A%0Adef api_call(action, params, token, app_secret, show_header=False):%0A api_url = u'https://api.tme.eu/' + action + '.json';%0A params%5B'Token'%5D = token;%0A%0A params = collections.OrderedDict(sorted(params.items()))%0A%0A encoded_params = urllib.urlencode(params, '')%0A signature_base = 'POST' + '&' + urllib.quote(api_url, '') + '&' + urllib.quote(encoded_params, '')%0A%0A api_signature = base64.encodestring(hmac.new(app_secret, signature_base, hashlib.sha1).digest()).rstrip()%0A params%5B'ApiSignature'%5D = api_signature%0A%0A opts = %7B'http' :%0A %7B%0A 'method' : 'POST',%0A 'header' : 'Content-type: application/x-www-form-urlencoded',%0A 'content' : urllib.urlencode(params)%0A %7D%0A %7D%0A%0A http_header = %7B%0A %22Content-type%22: %22application/x-www-form-urlencoded%22,%0A %7D%0A # create your HTTP request%0A req = urllib2.Request(api_url, urllib.urlencode(params), http_header)%0A # submit your request%0A res = urllib2.urlopen(req)%0A html = res.read()%0A return html%0A
|
|
1166ef7520ee26836402f028cb52ed95db7173e6
|
Add CTC_new_refund_limited_all_payroll migration file
|
webapp/apps/taxbrain/migrations/0058_taxsaveinputs_ctc_new_refund_limited_all_payroll.py
|
webapp/apps/taxbrain/migrations/0058_taxsaveinputs_ctc_new_refund_limited_all_payroll.py
|
Python
| 0 |
@@ -0,0 +1,503 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('taxbrain', '0057_jsonreformtaxcalculator_errors_warnings_text'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='taxsaveinputs',%0A name='CTC_new_refund_limited_all_payroll',%0A field=models.CharField(default=b'False', max_length=50, null=True, blank=True),%0A ),%0A %5D%0A
|
|
fc1a9b7870f4d7e789c3968df6ddda698a7c4d62
|
update to search all the TEMPLATES configurations
|
django_extensions/compat.py
|
django_extensions/compat.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from io import BytesIO
import csv
import six
import codecs
import importlib
import django
from django.conf import settings
#
# Django compatibility
#
def load_tag_library(libname):
"""Load a templatetag library on multiple Django versions.
Returns None if the library isn't loaded.
"""
if django.VERSION < (1, 9):
from django.template.base import get_library, InvalidTemplateLibrary
try:
lib = get_library(libname)
return lib
except InvalidTemplateLibrary:
return None
else:
from django.template.backends.django import get_installed_libraries
from django.template.library import InvalidTemplateLibrary
try:
lib = get_installed_libraries()[libname]
lib = importlib.import_module(lib).register
return lib
except (InvalidTemplateLibrary, KeyError):
return None
def get_template_setting(template_key, default=None):
""" Read template settings pre and post django 1.8 """
templates_var = getattr(settings, 'TEMPLATES', None)
if templates_var is not None and template_key in templates_var[0]:
return templates_var[0][template_key]
if template_key == 'DIRS':
pre18_template_key = 'TEMPLATES_%s' % template_key
value = getattr(settings, pre18_template_key, default)
return value
return default
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
We are using this custom UnicodeWriter for python versions 2.x
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
self.queue = BytesIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
from csv import writer # noqa
# Default csv.writer for PY3 versions
csv_writer = writer
if six.PY2:
# unicode CSVWriter for PY2
csv_writer = UnicodeWriter # noqa
|
Python
| 0 |
@@ -1177,40 +1177,60 @@
_var
- is not None and template_key in
+:%0A for tdict in templates_var:%0A if
tem
@@ -1238,26 +1238,33 @@
late
-s_var%5B0%5D:%0A
+_key in tdict:%0A
retu
@@ -1263,16 +1263,22 @@
+
return t
empl
@@ -1277,23 +1277,12 @@
rn t
-emplates_var%5B0%5D
+dict
%5Btem
|
55d9610f519713b889ffb68daa3c72ef6c349d3d
|
Add ExportPPMs.py script.
|
TrueType/ExportPPMs.py
|
TrueType/ExportPPMs.py
|
Python
| 0 |
@@ -0,0 +1,1471 @@
+#FLM: Export PPMs%0A%0A%22%22%22%0AThis script will write (or overwrite) a 'ppms' file in the same directory %0Aas the opened VFB file. This 'ppms' file contains the TrueType stem values %0Aand the ppm values at which the pixel jumps occur. These values can later %0Abe edited as the 'ppms' file is used as part of the conversion process.%0A%22%22%22%0A%0Aimport os%0Afrom FL import fl%0A%0AkPPMsFileName = %22ppms%22%0A%0A%0Adef collectPPMs():%0A%09ppmsList = %5B%22#Name%5CtWidth%5Ctppm2%5Ctppm3%5Ctppm4%5Ctppm5%5Ctppm6%5Cn%22%5D%0A%09for x in fl.font.ttinfo.hstem_data:%0A%09%09hstem = '%25s%5Ct%25d%5Ct%25d%5Ct%25d%5Ct%25d%5Ct%25d%5Ct%25d%5Cn' %25 (%0A%09%09%09x.name, x.width, x.ppm2, x.ppm3, x.ppm4, x.ppm5, x.ppm6)%0A%09%09ppmsList.append(hstem)%0A%0A%09for y in fl.font.ttinfo.vstem_data:%0A%09%09vstem = '%25s%5Ct%25d%5Ct%25d%5Ct%25d%5Ct%25d%5Ct%25d%5Ct%25d%5Cn' %25 (%0A%09%09%09y.name, y.width, y.ppm2, y.ppm3, y.ppm4, y.ppm5, y.ppm6)%0A%09%09ppmsList.append(vstem)%0A%0A%09return ppmsList%0A%0A%0Adef writePPMsFile(content):%0A%09# path to the folder where the font is contained and the font's file name:%0A%09folderPath, fontFileName = os.path.split(fl.font.file_name)%0A%09filePath = os.path.join(folderPath, kPPMsFileName)%0A%09outfile = open(filePath, 'w')%0A%09outfile.writelines(content)%0A%09outfile.close()%0A%0A%0Adef run():%0A%09if len(fl):%0A%09%09if (fl.font.file_name is None):%0A%09%09%09print %22ERROR: You must save the VFB first.%22%0A%09%09%09return%0A%0A%09%09if len(fl.font.ttinfo.hstem_data):%0A%09%09%09ppmsList = collectPPMs()%0A%09%09%09writePPMsFile(ppmsList)%0A%09%09%09print %22Done!%22%0A%09%09else:%0A%09%09%09print %22ERROR: The font has no TT stems data.%22%0A%0A%09else:%0A%09%09print %22ERROR: No font opened.%22%0A%09%0A%0Aif __name__ == %22__main__%22:%0A%09run()%0A
|
|
5aff575cec6ddb10cba2e52ab841ec2197a0e172
|
Add SignalTimeout context manager
|
Utils/SignalTimeout.py
|
Utils/SignalTimeout.py
|
Python
| 0.000001 |
@@ -0,0 +1,1375 @@
+# Taken from https://gist.github.com/ekimekim/b01158dc36c6e2155046684511595d57%0Aimport os%0Aimport signal%0Aimport subprocess%0A%0A%0Aclass Timeout(Exception):%0A %22%22%22This is raised when a timeout occurs%22%22%22%0A%0A%0Aclass SignalTimeout(object):%0A %22%22%22Context manager that raises a Timeout if the inner block takes too long.%0A Will even interrupt hard loops in C by raising from an OS signal.%22%22%22%0A%0A def __init__(self, timeout, signal=signal.SIGUSR1, to_raise=Timeout):%0A self.timeout = float(timeout)%0A self.signal = signal%0A self.to_raise = to_raise%0A self.old_handler = None%0A self.proc = None%0A%0A def __enter__(self):%0A self.old_handler = signal.signal(self.signal, self._on_signal)%0A self.proc = subprocess.Popen('sleep %7Btimeout%7D && kill -%7Bsignal%7D %7Bpid%7D'.format(%0A timeout = self.timeout,%0A signal = self.signal,%0A pid = os.getpid(),%0A ),%0A shell = True,%0A )%0A%0A def __exit__(self, *exc_info):%0A if self.proc.poll() is None:%0A self.proc.kill()%0A my_handler = signal.signal(self.signal, self.old_handler)%0A assert my_handler == self._on_signal, %22someone else has been fiddling with our signal handler?%22%0A%0A def _on_signal(self, signum, frame):%0A if self.old_handler:%0A self.old_handler(signum, frame)%0A raise self.to_raise%0A
|
|
e18ee4aacd42ec28b2d54437f61d592b1cfaf594
|
Create national_user_data_pull.py
|
custom/icds_reports/management/commands/national_user_data_pull.py
|
custom/icds_reports/management/commands/national_user_data_pull.py
|
Python
| 0.000125 |
@@ -0,0 +1,1769 @@
+import csv%0A%0Afrom django.core.management.base import BaseCommand%0Afrom corehq.apps.reports.util import get_all_users_by_domain%0Afrom custom.icds_reports.const import INDIA_TIMEZONE%0Afrom custom.icds_reports.models import ICDSAuditEntryRecord%0Afrom django.db.models import Max%0A%0A%0Aclass Command(BaseCommand):%0A help = %22Custom data pull%22%0A%0A def convert_to_ist(self, date):%0A if date is None:%0A return 'N/A'%0A date = date.astimezone(INDIA_TIMEZONE)%0A date_formatted = date.strftime(date, %22%25d/%25m/%25Y, %25I:%25M %25p%22)%0A return date_formatted%0A%0A def handle(self, *args, **options):%0A users = get_all_users_by_domain('icds-cas')%0A usernames = %5B%5D%0A for user in users:%0A if user.has_permission('icds-cas', 'access_all_locations'):%0A usernames.append(user.username)%0A usage_data = ICDSAuditEntryRecord.objects.filter(username__in=usernames).values('username').annotate(time=Max('time_of_use'))%0A headers = %5B%22S.No%22, %22username%22, %22time%22%5D%0A count = 1%0A rows = %5Bheaders%5D%0A usernames_usage = %5B%5D%0A for usage in usage_data:%0A row_data = %5B%0A count,%0A usage.username,%0A self.convert_to_ist(usage.time)%0A %5D%0A usernames_usage.append(usage.username)%0A rows.append(row_data)%0A count = count + 1%0A for user in usernames:%0A if user not in usernames_usage:%0A row_data = %5B%0A count,%0A user,%0A %22N/A%22%0A %5D%0A rows.append(row_data)%0A count = count + 1%0A fout = open('/home/cchq/National_users_data.csv', 'w')%0A writer = csv.writer(fout)%0A writer.writerows(rows)%0A
|
|
ed157602d965be952aadc9fe33b2e517c7f98ccf
|
Add urls
|
dumpling/urls.py
|
dumpling/urls.py
|
Python
| 0.000013 |
@@ -0,0 +1,199 @@
+from django.conf.urls import include, url%0A%0Afrom . import views%0A%0Aurlpatterns = %5B%0A url(r'css/(?P%3Cname%3E.*)%5C.css$', views.styles, name='styles'),%0A url(r'(?P%3Cpath%3E.*)', views.PageView.as_view()),%0A%5D%0A
|
|
380178c585d4b9e2689ffdd72c9fa80be94fe3a9
|
add more calculation
|
examples/ingap_gaas_radeta_paper.py
|
examples/ingap_gaas_radeta_paper.py
|
Python
| 0 |
@@ -0,0 +1,1196 @@
+__author__ = 'kanhua'%0A%0A%0Aimport numpy as np%0Afrom scipy.interpolate import interp2d%0Aimport matplotlib.pyplot as plt%0Afrom scipy.io import savemat%0Afrom iii_v_si import calc_2j_si_eta, calc_3j_si_eta%0A%0A%0Aif __name__==%22__main__%22:%0A algaas_top_ere=np.logspace(-7,0,num=50)%0A algaas_mid_ere=np.logspace(-7,0,num=50)%0A%0A eta_array=np.zeros((algaas_top_ere.shape%5B0%5D,algaas_mid_ere.shape%5B0%5D))%0A%0A for i,teg in enumerate(algaas_top_ere):%0A for j,meg in enumerate(algaas_mid_ere):%0A eta,_,_,_= calc_3j_si_eta(teg, meg, 1, top_band_gap=1.87, top_cell_qe=0.75, mid_band_gap=1.42,%0A mid_cell_qe=0.75,bot_cell_qe=0.75,bot_cell_eta=5e-4)%0A eta_array%5Bi,j%5D=eta%0A%0A%0A np.savez(%22ingap_gaas_ere_3J_paper.npz%22,tbg=algaas_top_ere,mbg=algaas_mid_ere,eta=eta_array)%0A%0A plt.pcolormesh(algaas_mid_ere,algaas_top_ere,eta_array)%0A plt.colorbar()%0A plt.xlabel(%22ERE of middle cell (eV)%22)%0A plt.ylabel(%22ERE of top cell (eV)%22)%0A plt.xlim(%5Bnp.min(algaas_mid_ere),np.max(algaas_mid_ere)%5D)%0A plt.ylim(%5Bnp.min(algaas_top_ere),np.max(algaas_top_ere)%5D)%0A plt.xscale(%22log%22)%0A plt.yscale(%22log%22)%0A%0A plt.savefig(%22ingap_gaas_ere_3J_paper.pdf%22)%0A plt.show()
|
|
93b38901b25f6c5db4700343050c5bb2fc6ef7e6
|
add utility to make digraph out of router
|
emit/graphviz.py
|
emit/graphviz.py
|
Python
| 0 |
@@ -0,0 +1,322 @@
+def make_digraph(router, name='router'):%0A header = 'digraph %25s %7B%5Cn' %25 name%0A footer = '%5Cn%7D'%0A%0A lines = %5B%5D%0A for origin, destinations in router.routes.items():%0A for destination in destinations:%0A lines.append('%22%25s%22 -%3E %22%25s%22;' %25 (origin, destination))%0A%0A return header + '%5Cn'.join(lines) + footer%0A
|
|
c16620dffd2cd6396eb6b7db76a9c29849a16500
|
Add support for cheminformatics descriptors
|
components/lie_structures/lie_structures/cheminfo_descriptors.py
|
components/lie_structures/lie_structures/cheminfo_descriptors.py
|
Python
| 0 |
@@ -0,0 +1,702 @@
+# -*- coding: utf-8 -*-%0A%0A%22%22%22%0Afile: cheminfo_molhandle.py%0A%0ACinfony driven cheminformatics fingerprint functions%0A%22%22%22%0A%0Aimport logging%0A%0Afrom twisted.logger import Logger%0A%0Afrom . import toolkits%0A%0Alogging = Logger()%0A%0A%0Adef available_descriptors():%0A %22%22%22%0A List available molecular descriptors for all active cheminformatics%0A packages%0A%0A The webel toolkit has a descriptor service but the supported%0A descriptors are not listed in Cinfony. The toolkit is available%0A however.%0A%0A :rtype: :py:dict%0A %22%22%22%0A%0A available_descs = %7B'webel': None%7D%0A for toolkit, obj in toolkits.items():%0A if hasattr(obj, 'descs'):%0A available_descs%5Btoolkit%5D = obj.descs%0A%0A return available_descs
|
|
718b8dcb87ae2b78e5ce0aded0504a81d599daf7
|
Create envToFish.py
|
envToFish.py
|
envToFish.py
|
Python
| 0 |
@@ -0,0 +1,496 @@
+#!/usr/bin/env python%0A%0Aimport os%0Aimport subprocess%0A%0AbadKeys = %5B'HOME', 'PWD', 'USER', '_', 'OLDPWD'%5D%0Awith open('profile.fish', 'w') as f:%0A for key, val in os.environ.items():%0A if key in badKeys:%0A continue%0A if key == 'PATH':%0A f.write(%22set -e PATH%5Cn%22)%0A pathUnique = set(val.split(':'))%0A for elem in pathUnique:%0A f.write(%22set -gx PATH $PATH %25s%5Cn%22 %25 elem)%0A else:%0A f.write(%22set -gx %25s '%25s'%5Cn%22 %25 (key, val))%0A
|
|
01328db808d3f5f1f9df55117ef70924fb615a6a
|
Create config reader
|
escpos/config.py
|
escpos/config.py
|
Python
| 0.000001 |
@@ -0,0 +1,2043 @@
+from __future__ import absolute_import%0A%0Aimport os%0Aimport appdirs%0Afrom localconfig import config%0A%0Afrom . import printer%0Afrom .exceptions import *%0A%0Aclass Config(object):%0A%0A _app_name = 'python-escpos'%0A _config_file = 'config.ini'%0A%0A def __init__(self):%0A self._has_loaded = False%0A self._printer = None%0A%0A self._printer_name = None%0A self._printer_config = None%0A%0A def load(self, config_path=None):%0A # If they didn't pass one, load default%0A if not config_path:%0A config_path = os.path.join(%0A appdirs.user_config_dir(self._app_name),%0A self._config_file%0A )%0A%0A # Deal with one config or a list of them%0A # Configparser does this, but I need it for the list in the error message%0A if isinstance(config_path, basestring):%0A config_path = %5Bconfig_path%5D%0A%0A files_read = config.read(config_path)%0A if not files_read:%0A raise ConfigNotFoundError('Couldn%5C't read config at one or more of %7Bconfig_path%7D'.format(%0A config_path=%22%5Cn%22.join(config_path),%0A ))%0A%0A if 'printer' in config:%0A # For some reason, dict(config.printer) raises%0A # TypeError: attribute of type 'NoneType' is not callable%0A self._printer_config = dict(list(config.printer))%0A self._printer_name = self._printer_config.pop('type').title()%0A%0A if not self._printer_name or not hasattr(printer, self._printer_name):%0A raise ConfigSyntaxError('Printer type %22%7Bprinter_name%7D%22 is invalid'.format(%0A printer_name=self._printer_name,%0A ))%0A%0A self._has_loaded = True%0A%0A def printer(self):%0A if not self._has_loaded:%0A self.load()%0A%0A if not self._printer:%0A # We could catch init errors and make them a ConfigSyntaxError, %0A # but I'll just let them pass%0A self._printer = getattr(printer, self._printer_name)(**self._printer_config)%0A%0A return self._printer%0A%0A
|
|
0f43f3bdc9b22e84da51e490664aeedc4295c8c9
|
Add test for ELB
|
tests/test_elb.py
|
tests/test_elb.py
|
Python
| 0.000001 |
@@ -0,0 +1,347 @@
+# -*- coding: utf-8 -*-%0Afrom jungle import cli%0A%0A%0Adef test_elb_ls(runner, elb):%0A %22%22%22test for elb ls%22%22%22%0A result = runner.invoke(cli.cli, %5B'elb', 'ls'%5D)%0A assert result.exit_code == 0%0A%0A%0Adef test_elb_ls_with_l(runner, elb):%0A %22%22%22test for elb ls -l%22%22%22%0A result = runner.invoke(cli.cli, %5B'elb', 'ls', '-l'%5D)%0A assert result.exit_code == 0%0A
|
|
c1bf53c5c278cafa3b1c070f8a232d5820dcb7a4
|
add elb list test.
|
tests/test_elb.py
|
tests/test_elb.py
|
Python
| 0 |
@@ -0,0 +1,1412 @@
+from __future__ import (absolute_import, print_function, unicode_literals)%0Afrom acli.output.elb import (output_elb_info, output_elbs)%0Afrom acli.services.elb import (elb_info, elb_list)%0Afrom acli.config import Config%0Afrom moto import mock_elb%0Aimport pytest%0Afrom boto3.session import Session%0Asession = Session(region_name=%22eu-west-1%22)%0A%0A%[email protected]_fixture(scope='function')%0Adef elb_instances():%0A %22%22%22ELB mock service%22%22%22%0A mock = mock_elb()%0A mock.start()%0A client = session.client('elb')%0A zones = %5B'eu-west-1a', 'eu-west-1b'%5D%0A listeners = %5B%7B%0A 'Protocol': 'string',%0A 'LoadBalancerPort': 123,%0A 'InstanceProtocol': 'string',%0A 'InstancePort': 123,%0A 'SSLCertificateId': 'string'%7D%5D%0A client.create_load_balancer(LoadBalancerName='my-lb', AvailabilityZones=zones, Listeners=listeners)%0A yield client.describe_load_balancers()%0A mock.stop()%0A%0A%0Aconfig = Config(cli_args=%7B'--region': 'eu-west-1',%0A '--access_key_id': 'AKIAIOSFODNN7EXAMPLE',%0A '--secret_access_key': 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'%7D)%0A%0A%0Adef test_elb_list_service(elb_instances):%0A with pytest.raises(SystemExit):%0A assert elb_list(aws_config=config)%0A%0A%0A# def test_elb_info_service(ec2_instances):%0A# with pytest.raises(SystemExit):%0A# assert elb_info(aws_config=config, elb_name=list(ec2_instances)%5B0%5D.id)%0A%0A
|
|
ee3e04d32e39d6ac7ef4ac7abc2363a1ac9b8917
|
Add an example for the music module
|
example_music.py
|
example_music.py
|
Python
| 0.000002 |
@@ -0,0 +1,308 @@
+from screenfactory import create_screen%0Afrom modules.music import Music%0Aimport config%0Aimport time%0Aimport pygame%0A%0Ascreen = create_screen()%0A%0Amusic = Music(screen)%0Amusic.start()%0A%0Awhile True:%0A%09if config.virtual_hardware:%0A%09%09pygame.time.wait(10)%0A%09%09for event in pygame.event.get():%0A%09%09%09pass%0A%09else:%0A%09%09time.sleep(0.01)
|
|
4be66a6e7a9852b59fb3a18e6bd85c6b6734be83
|
add index back
|
billy/bin/commands/ensure_indexes.py
|
billy/bin/commands/ensure_indexes.py
|
from __future__ import print_function
from billy.core import db
from billy.bin.commands import BaseCommand
from billy.core import settings
import pymongo
class MongoIndex(BaseCommand):
name = 'mongo-index'
help = '''make indexes'''
def add_args(self):
self.add_argument(
'collections', nargs='*',
help='collection(s) to run matching for (defaults to all)'
)
self.add_argument('--purge', action='store_true', default=False,
help='purge old indexes')
def handle(self, args):
all_indexes = {
'popularity_counts': [
[('type', pymongo.ASCENDING), ('date', pymongo.ASCENDING),
('obj_id', pymongo.ASCENDING)],
],
'committees': [
[('_all_ids', pymongo.ASCENDING)],
[(settings.LEVEL_FIELD, pymongo.ASCENDING),
('chamber', pymongo.ASCENDING)],
[(settings.LEVEL_FIELD, pymongo.ASCENDING),
('committee', pymongo.ASCENDING),
('subcommittee', pymongo.ASCENDING)
]
],
'events': [
[('when', pymongo.ASCENDING),
(settings.LEVEL_FIELD, pymongo.ASCENDING),
('type', pymongo.ASCENDING)],
[('when', pymongo.DESCENDING),
(settings.LEVEL_FIELD, pymongo.ASCENDING),
('type', pymongo.ASCENDING)],
[ (settings.LEVEL_FIELD, pymongo.ASCENDING),
('related_bills.bill_id', pymongo.ASCENDING),
('when', pymongo.DESCENDING) ],
],
'legislators': [
[('_all_ids', pymongo.ASCENDING)],
[('boundary_id', pymongo.ASCENDING)],
[(settings.LEVEL_FIELD, pymongo.ASCENDING),
('active', pymongo.ASCENDING),
('chamber', pymongo.ASCENDING)],
#[('roles.' + settings.LEVEL_FIELD, pymongo.ASCENDING),
# ('roles.type', pymongo.ASCENDING),
# ('roles.term', pymongo.ASCENDING),
# ('roles.chamber', pymongo.ASCENDING),
# ('roles.district', pymongo.ASCENDING)],
{'role_and_name_parts': [
('roles.' + settings.LEVEL_FIELD, pymongo.ASCENDING),
('roles.type', pymongo.ASCENDING),
('roles.term', pymongo.ASCENDING),
('roles.chamber', pymongo.ASCENDING),
('_scraped_name', pymongo.ASCENDING),
('first_name', pymongo.ASCENDING),
('last_name', pymongo.ASCENDING),
('middle_name', pymongo.ASCENDING),
('suffixes', pymongo.ASCENDING)],
},
],
'bills': [
# bill_id is used for search in conjunction with ElasticSearch
# sort field (date) comes first
# followed by field that we do an $in on
[('_all_ids', pymongo.ASCENDING)],
[('created_at', pymongo.DESCENDING),
('bill_id', pymongo.ASCENDING)],
[('updated_at', pymongo.DESCENDING),
('bill_id', pymongo.ASCENDING)],
[('action_dates.last', pymongo.DESCENDING),
('bill_id', pymongo.ASCENDING)],
# primary sponsors index
[('sponsors.leg_id', pymongo.ASCENDING),
('sponsors.type', pymongo.ASCENDING),
(settings.LEVEL_FIELD, pymongo.ASCENDING)
],
# for distinct queries
#[(settings.LEVEL_FIELD, pymongo.ASCENDING),
# ('type', pymongo.ASCENDING),
#],
],
'subjects': [
[('abbr', pymongo.ASCENDING)],
],
'manual.name_matchers': [
[('abbr', pymongo.ASCENDING)],
],
'votes': [
[('bill_id', pymongo.ASCENDING), ('date', pymongo.ASCENDING)],
[('_voters', pymongo.ASCENDING), ('date', pymongo.ASCENDING)]
]
}
# add a plethora of bill indexes
search_indexes = [
('sponsors.leg_id', settings.LEVEL_FIELD),
('chamber', settings.LEVEL_FIELD),
('session', settings.LEVEL_FIELD),
('session', 'chamber', settings.LEVEL_FIELD),
('_term', 'chamber', settings.LEVEL_FIELD),
('status', settings.LEVEL_FIELD),
('subjects', settings.LEVEL_FIELD),
('type', settings.LEVEL_FIELD),
(settings.LEVEL_FIELD,),
]
for index_keys in search_indexes:
sort_indexes = ['action_dates.first', 'action_dates.last',
'updated_at']
# chamber-abbr gets indexed w/ every possible sort
if (index_keys == ('chamber', settings.LEVEL_FIELD) or
index_keys == (settings.LEVEL_FIELD,)):
sort_indexes += ['action_dates.passed_upper',
'action_dates.passed_lower']
for sort_index in sort_indexes:
index = [(ikey, pymongo.ASCENDING) for ikey in index_keys]
index += [(sort_index, pymongo.DESCENDING)]
all_indexes['bills'].append(index)
collections = args.collections or all_indexes.keys()
for collection in collections:
print('indexing', collection, '...')
current = set(db[collection].index_information().keys())
current.discard('_id_')
if collection == 'bills':
# basic lookup / unique constraint on abbr/session/bill_id
current.discard('%s_1_session_1_chamber_1_bill_id_1' %
settings.LEVEL_FIELD)
db.bills.ensure_index([
(settings.LEVEL_FIELD, pymongo.ASCENDING),
('session', pymongo.ASCENDING),
('chamber', pymongo.ASCENDING),
('bill_id', pymongo.ASCENDING)
], unique=True)
print('creating level-session-chamber-bill_id index')
print('currently has', len(current), 'indexes (not counting _id)')
print('ensuring', len(all_indexes[collection]), 'indexes')
ensured = set()
for index in all_indexes[collection]:
if isinstance(index, list):
ensured.add(db[collection].ensure_index(index))
elif isinstance(index, dict):
name, index_spec = index.items()[0]
ensured.add(
db[collection].ensure_index(index_spec, name=name))
else:
raise ValueError(index)
new = ensured - current
old = current - ensured
if len(new):
print(len(new), 'new indexes:', ', '.join(new))
if len(old):
print(len(old), 'indexes deprecated:', ', '.join(old))
if args.purge:
print('removing deprecated indexes...')
for index in old:
db[collection].drop_index(index)
|
Python
| 0.000001 |
@@ -3704,17 +3704,16 @@
-#
%5B(settin
@@ -3764,17 +3764,16 @@
-#
('type'
@@ -3810,17 +3810,16 @@
-#
%5D,%0A
|
54718d95c4398d816546b45ed3f6a1faf2cdace8
|
add modules/flexins/nsversion.py
|
modules/flexins/nsversion.py
|
modules/flexins/nsversion.py
|
Python
| 0 |
@@ -0,0 +1,1963 @@
+%22%22%22Analysis and Check the FlexiNS software version.%0A%0A%22%22%22%0Aimport re%0Afrom libs.checker import ResultInfo,CheckStatus%0Afrom libs.log_spliter import LogSpliter,LOG_TYPE_FLEXI_NS%0Afrom libs.tools import read_cmdblock_from_log%0A%0A## Mandatory variables %0A##--------------------------------------------%0Amodule_id = 'fnsbase.01'%0Atag = %5B'flexins','base'%5D%0Apriority = 'normal'%0Aname = %22Check the FNS software version%22%0Adesc = __doc__%0Acriteria = %22FNS version is %5B'N5 1.19-3'%5D.%22%0Aresult = ResultInfo(name)%0A##--------------------------------------------%0A%0A## Optional variables%0A##--------------------------------------------%0Atarget_version = %5B'N5 1.19-3'%5D %0Aversion_info = %22Packages Info:%5Cn %25s%22%0Apat_pkgid= re.compile(%22%5Cs+(BU%7CFB%7CNW)%5Cs+.*?%5Cn%5Cs+(%5Cw%5Cd %5B%5Cd%5C.-%5D+)%22)%0Acheck_commands = %5B%0A (%22ZWQO:CR;%22,%22show the NS packages information%22),%0A%5D%0A##%0Adef check_version(logtxt):%0A error = ''%0A info = ''%0A status = ''%0A%0A pkgid = dict(pat_pkgid.findall(str(logtxt)))%0A%0A try:%0A if pkgid%5B'BU'%5D in target_version:%0A status = CheckStatus.PASSED%0A else:%0A status = CheckStatus.FAILED%0A info = str(pkgid)%0A except (KeyError,ValueError) as e:%0A status = CheckStatus.UNKNOWN%0A info = e %0A %0A return status,info,error %0A##--------------------------------------------%0A## Mandatory function: run%0A##-------------------------------------------- %0Adef run(logfile):%0A %22%22%22The 'run' function is a mandatory fucntion. and it must return a ResultInfo.%0A %22%22%22%0A ns_command_end_mark = %22COMMAND EXECUTED%22 %0A logtxt = read_cmdblock_from_log(logfile,'ZWQO:CR;',ns_command_end_mark)%0A if logtxt:%0A status,info,error = check_version(logtxt)%0A result.update(status=status,info=(version_info %25 info).split('%5Cn'),error=error)%0A else:%0A status = CheckStatus.UNKNOWN%0A error = %22Can't find the version info in the log.%22%0A result.update(status=status,info='',error=error)%0A %0A return result%0A
|
|
ec41564bb99c8e79bcee1baabd75d2282601415c
|
add refund
|
shopify/resources/refund.py
|
shopify/resources/refund.py
|
Python
| 0 |
@@ -0,0 +1,116 @@
+from ..base import ShopifyResource%0A%0A%0Aclass Refund(ShopifyResource):%0A _prefix_source = %22/admin/orders/$order_id/%22%0A
|
|
e7247c8c70a8cfefaee057e0c731aa5dab41ca9a
|
Create Contours.py
|
Contours.py
|
Contours.py
|
Python
| 0 |
@@ -0,0 +1,283 @@
+from PIL import Image%0Afrom pylab import *%0A%0A#read image into an array%0Aim = array(Image.open('s9.jpg').convert('L'))%0A%0A#create a new figure%0Afigure()%0A%0A#don't use colors%0Agray()%0A%0A#show contours%0Acontour(im,origin = 'image')%0Aaxis('equal')%0Aaxis('off')%0A%0Afigure()%0Ahist(im.flatten(),128)%0Ashow()%0A
|
|
9315c59746e2be9f2f15ff2bae02e1b481e9a946
|
Create mr.py
|
mr.py
|
mr.py
|
Python
| 0.000004 |
@@ -0,0 +1,512 @@
+Mapper:%0A%0A#!/usr/bin/python%0A%0Aimport sys%0A%0Awhile 1:%0A line = sys.stdin.readline()%0A if line == %22%22:%0A break%0A fields = line.split(%22,%22)%0A year = fields%5B1%5D%0A runs = fields%5B8%5D%0A%0A if year == %221956%22:%0A print runs%0A%0A%0AReducer: %0A#!/usr/bin/python%0A%0Aimport sys%0Atotal_count = 0%0Afor line in sys.stdin:%0A try:%0A count = int(line)%0A total_count += count%0A except ValueError:%0A # count was not a number, so silently%0A # ignore/discard this line%0A continue%0A%0Aprint total_count%0A
|
|
c91e231c8d71458a7c347088ad7ec6431df234d7
|
add ss.py to update proxy automatically
|
ss.py
|
ss.py
|
Python
| 0 |
@@ -0,0 +1,149 @@
+# -*- coding:utf8 -*-%0A%0Aimport urllib2%0A%0Aresponse = urllib2.urlopen(%22http://boafanx.tabboa.com/boafanx-ss/%22)%0Ahtml = response.read()%0Aprint(html%5B:20000%5D)
|
|
4015a16ec32660d25646f62772876d53166f46f2
|
Add files via upload
|
PEP.py
|
PEP.py
|
Python
| 0 |
@@ -0,0 +1,2064 @@
+#-*- coding: utf-8 -*- %0Afrom optparse import OptionParser%0Aimport genLabelData,genUnlabelData,mainEdit,genVecs%0Aimport os.path%0A%0Adef parse_args():%0A%09parser = OptionParser(usage=%22RNA editing prediction%22, add_help_option=False)%0A%09parser.add_option(%22-f%22, %22--feature%22, default=%22300%22, help=%22Set the number of features of Word2Vec model%22)%0A%09parser.add_option(%22-g%22,%22--generate%22,default=%22true%22, help=%22Generate the Data or Use the ones before%22)%0A%09parser.add_option(%22-t%22,%22--type%22,default=%22ep%22,help=%22eep data or ep data%22)%0A%09parser.add_option(%22-c%22,%22--cell%22,default = %22GM12878%22,help=%22Cell Line%22)%0A%09parser.add_option(%22-k%22,%22--k%22,default=%221%22,help=%22k%22)%0A%09parser.add_option(%22-w%22,%22--word%22,default = %226%22)%0A%09parser.add_option(%22-i%22,%22--integrate%22,default=%22false%22, help=%22Use integrated features or not%22)%0A%09parser.add_option(%22-s%22,%22--sel%22,default=50, help=%22The number of motif feature to be used in the combination mode%22)%0A%09parser.add_option(%22-e%22,%22--thresh_mode%22,default=1,help=%22The mode of estimating threshold:0-default;1-simple mode;2-cv mode%22)%0A%0A%09(opts, args) = parser.parse_args()%0A%09return opts%0A%0A%0Adef run(word,num_features,generate,type,cell,k,integrate,sel):%0A%0A%09if(os.path.exists(%22./Data/Learning%22)==False):%0A%09%09os.makedirs(%22./Data/Learning%22)%0A%0A%09print %22parameters are as followed%5Cn%22 %5C%0A%09%09 %22feature=%25r%5Ctgenerate=%25r%5Cn%22 %5C%0A%09%09 %22type=%25r%5Ctcell=%25r%5Cn%22 %5C%0A%09%09 %22k=%25r%5Cn%22%5C%0A%09%09 %25(num_features,generate,type,cell,k)%0A%0A%09if generate == %22true%22:%0A%09%09if not os.path.isfile(%22./Data/Learning/supervised_%22+str(cell)+%22_%22+str(type)):%0A%09%09%09genLabelData.run(type,cell)%0A%09%09if not os.path.isfile(%22./Data/Learning/unlabeled_train_promoter_%22+str(cell)+%22_%22+str(type)):%0A%09%09%09genUnlabelData.run(type,cell,word)%0A%09%09if not os.path.isfile(%22./Datavecs/datavecs_%22+str(cell)+%22_%22+str(type)+%22.npy%22):%0A%09%09%09genVecs.run(word,num_features,k,type,cell)%0A%09%0A%09if integrate == %22false%22:%0A%09%09mainPEP.run_word(word,num_features,k,type,cell)%0A%09else:%0A%09%09mainPEP.run_shuffle(word,num_features,k,type,cell,sel)%0A%0A%0Adef main():%0A%09opts = parse_args()%0A%09run(opts.word,opts.feature,opts.generate,opts.type,opts.cell,opts.k,opts.integrate,opts.sel)%0A%0Aif __name__ == '__main__':%0A%09main()%0A
|
|
8016dbc50238d2baf5f89c191ec3355df63af1a2
|
Implement basic flask app to add subscribers
|
app.py
|
app.py
|
Python
| 0.000001 |
@@ -0,0 +1,425 @@
+import iss%0A%0Afrom flask import Flask, request, render_template%0A%0A%0Aapp = Flask(__name__)%0A%0A%[email protected]('/', methods=%5B'GET'%5D)%0Adef index():%0A return render_template()%0A%0A%[email protected]('/subscribe', methods=%5B'POST'%5D)%0Adef subscribe():%0A number = request.form%5B'number'%5D%0A lat = request.form%5B'latitude'%5D%0A lon = request.form%5B'longitude'%5D%0A iss.add_to_queue(number, lat, lon)%0A return render_template()%0A%0Aapp.run(host='0.0.0.0')%0A
|
|
341890bfff2d8a831e48ebb659ce7f31d4918773
|
Update utils.py
|
tendrl/commons/central_store/utils.py
|
tendrl/commons/central_store/utils.py
|
from tendrl.commons.etcdobj import fields
def to_etcdobj(cls_etcd, obj):
for attr, value in vars(obj).iteritems():
if not attr.startswith("_"):
setattr(cls_etcd, attr, to_etcd_field(attr, value))
return cls_etcd
def to_etcd_field(name, value):
type_to_etcd_fields_map = {dict: fields.DictField,
str: fields.StrField,
int: fields.IntField,
bool: fields.StrField}
return type_to_etcd_fields_map[type(value)](name)
|
Python
| 0.000001 |
@@ -129,12 +129,8 @@
if
-not
attr
@@ -147,24 +147,146 @@
h(%22_%22):%0A
+ continue%0A if attr in %5B%22attrs%22, %22enabled%22, %22obj_list%22, %22obj_value%22, %22atoms%22, %22flows%22%5D:%0A continue%0A
seta
|
9d41eba840f954595a5cebbacaf56846cd52c1f4
|
add new file
|
functions.py
|
functions.py
|
Python
| 0.000006 |
@@ -0,0 +1,15 @@
+def add(a,b):%0A%0A
|
|
3000a9c0b7213a3aeb9faa0c01e5b779b2db36d4
|
add a noisy bezier example (todo: should noise be part of the animation, or stay out of it?)
|
examples/example_bezier_noise.py
|
examples/example_bezier_noise.py
|
Python
| 0 |
@@ -0,0 +1,2081 @@
+if __name__ == %22__main__%22:%0A import gizeh%0A import moviepy.editor as mpy%0A%0A from vectortween.BezierCurveAnimation import BezierCurveAnimation%0A from vectortween.SequentialAnimation import SequentialAnimation%0A%0A import noise%0A%0A def random_color():%0A import random%0A return (random.uniform(0, 1) for _ in range(3))%0A%0A%0A W, H = 250, 250 # width, height, in pixels%0A duration = 5 # duration of the clip, in seconds%0A fps = 25%0A%0A controlpoints_collections = %5B%0A %5B(120, 160), (35, 200), (220, 240), (220, 40)%5D,%0A %5B(220, 40), (120, 40), (10, 200)%5D%0A %5D%0A b1 = BezierCurveAnimation(controlpoints=controlpoints_collections%5B0%5D,tween=%5B%22easeOutBounce%22%5D)%0A b2 = BezierCurveAnimation(controlpoints=controlpoints_collections%5B1%5D,tween=%5B%22easeOutBounce%22%5D)%0A b = SequentialAnimation(%5Bb1,b2%5D)%0A%0A colors = ((0,1,1),(1,1,0))%0A%0A def make_frame(t):%0A surface = gizeh.Surface(W, H)%0A%0A xy = b.make_frame(t, 0, 0, duration - 1, duration)%0A curve_points = b.curve_points(0, t, 0.01, 0, 0, duration - 1, duration)%0A # print (curve_points)%0A%0A xnoise = %5B%5D%0A ynoise = %5B%5D%0A result = %5B%5D%0A for i,c in enumerate(curve_points):%0A xnoise.append(2*noise.snoise3(c%5B0%5D,c%5B1%5D,0))%0A ynoise.append(2*noise.snoise3(c%5B0%5D,c%5B1%5D,1))%0A result.append(%5B(c%5B0%5D + xnoise%5Bi%5D), (c%5B1%5D + ynoise%5Bi%5D)%5D)%0A if xy is not None and None not in xy:%0A gizeh.circle(5, xy=%5Bxy%5B0%5D+xnoise%5Bi%5D,xy%5B1%5D+ynoise%5Bi%5D%5D, fill=(0, 1, 0)).draw(surface)%0A curve_points = result%0A gizeh.polyline(curve_points, stroke=(0, 0, 1), stroke_width=2).draw(surface)%0A for i, controlpoints in enumerate(controlpoints_collections):%0A gizeh.polyline(controlpoints, stroke=colors%5Bi%5D, stroke_width=2).draw(surface)%0A for cp in controlpoints:%0A gizeh.circle(5, xy=cp, fill=(1, 1, 1)).draw(surface)%0A%0A return surface.get_npimage()%0A%0A%0A clip = mpy.VideoClip(make_frame, duration=duration)%0A clip.write_videofile(%22example_bezier_noise.mp4%22, fps=fps, codec=%22libx264%22)%0A
|
|
510fad764abd26e76d130dfa6d9b053709cd149e
|
Add and correct some comments and docstrings.
|
examples/julia-set/bench_dist.py
|
examples/julia-set/bench_dist.py
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Benchmark calculating the Julia set with Distarray for various array
distributions and number of engines.
Usage:
$ dacluster start -n20
...
$ python bench_dist.py
"""
from timeit import default_timer as clock
from matplotlib import pyplot
from distarray.dist import Context, Distribution
from distarray.dist.decorators import local, vectorize
# Make an empty distributed array
def make_empty_da(resolution, dist, context):
"""Create the arr we will build the fractal with."""
distribution = Distribution(context, (resolution[0], resolution[1]),
dist=dist)
out = context.empty(distribution, dtype=complex)
return out
# Drawing the coordinate plane directly like this is currently much
# faster than trying to do it by indexing a distarray.
def draw_coord(arr, re_ax, im_ax, resolution):
"""Draw the complex coordinate plane"""
re_step = float(re_ax[1] - re_ax[0]) / resolution[0]
im_step = float(im_ax[1] - im_ax[0]) / resolution[1]
for i in arr.distribution[0].global_iter:
for j in arr.distribution[1].global_iter:
arr.global_index[i, j] = complex(re_ax[0] + re_step*i,
im_ax[0] + im_step*j)
return arr
# This exactly the same function as the one in julia_numpy.py, but here
# we use distarray's vectorize decorator.
def julia(z, c, z_max, n_max):
n = 0
fn = lambda z, c: z**2 + c
while abs(z) < z_max and n < n_max:
z = fn(z, c)
n += 1
return n
def test_distarray(dist, context, resolution, c, re_ax, im_ax, z_max, n_max):
local_draw_coord = local(draw_coord)
vect_julia = vectorize(julia)
darr = make_empty_da(resolution, dist, context)
darr = local_draw_coord(darr, re_ax, im_ax, resolution)
start = clock()
darr = vect_julia(darr, c, z_max, n_max)
stop = clock()
return stop - start
def plot_results(dist_data, dists, engines):
try: # nicer plotting defaults
import seaborn
except ImportError:
pass
for i, data in enumerate(dist_data):
pyplot.plot(list(engines), data, label=dists[i].__repr__(), lw=2)
pyplot.title('Julia set benchmark - array distribution type vs number of '
'engines')
pyplot.xticks(list(engines), list(engines))
pyplot.xlabel('number of engines')
pyplot.ylabel('time (s)')
pyplot.legend(loc='upper right')
pyplot.savefig("julia_timing.png", dpi=100)
pyplot.show()
def main():
# Grid parameters
re_ax = (-1., 1.)
im_ax = (-1., 1.)
resolution = (480, 480)
# Julia set parameters, changing these is fun.
c = complex(0., .75)
z_max = 20
n_max = 100
# benchmark parameters
# number of engines
#engines = range(1, 20, 1)
engines = range(1, 3)
# array distributions
dists = ['bn', 'cn', 'bc', 'cb', 'bb', 'cc']
dist_data = [[] for i in range(len(dists))]
for num_engines in engines:
targets = list(range(num_engines))
context = Context(targets=targets)
print(num_engines)
for i, dist in enumerate(dists):
print(dist)
time = test_distarray(dist, context, resolution,
c, re_ax, im_ax, z_max, n_max)
dist_data[i].append(time)
plot_results(dist_data, dists, engines)
if __name__ == '__main__':
main()
|
Python
| 0 |
@@ -1208,20 +1208,21 @@
te plane
+.
%22%22%22%0A
-
re_s
@@ -1581,16 +1581,19 @@
%0A# This
+is
exactly
@@ -1928,24 +1928,56 @@
ax, n_max):%0A
+ %22%22%22Time a function call.%22%22%22%0A
local_dr
@@ -2261,16 +2261,16 @@
start%0A%0A%0A
-
def plot
@@ -2302,24 +2302,61 @@
, engines):%0A
+ %22%22%22Plot the computed timings.%22%22%22%0A
try: #
|
05c7d62e0e26000440e72d0700c9806d7a409744
|
Add migrations for game change suggestions
|
games/migrations/0023_auto_20171104_2246.py
|
games/migrations/0023_auto_20171104_2246.py
|
Python
| 0 |
@@ -0,0 +1,888 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.10.2 on 2017-11-04 21:46%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Aimport django.db.models.deletion%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('games', '0022_installer_reason'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='game',%0A name='change_for',%0A field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='games.Game'),%0A ),%0A migrations.AddField(%0A model_name='gamesubmission',%0A name='reason',%0A field=models.TextField(blank=True, null=True),%0A ),%0A migrations.AlterField(%0A model_name='game',%0A name='slug',%0A field=models.SlugField(blank=True, null=True, unique=True),%0A ),%0A %5D%0A
|
|
ad073b043b2965fb6a1939682aeca8ac90259210
|
add daily import to database
|
daily.py
|
daily.py
|
Python
| 0 |
@@ -0,0 +1,1753 @@
+import datetime%0Aimport httplib%0Aimport urllib%0Aimport redis%0Aimport json%0Afrom datetime import timedelta%0A%0A#now = datetime.datetime.now();%0A#today = now.strftime('%25Y-%25m-%25d')%0A#print today%0Ardb = redis.Redis('localhost')%0A%0A%0Adef isfloat(value):%0A%09try:%0A%09%09float(value)%0A%09%09return True%0A%09except ValueError:%0A%09%09return False%0A%0Adef convfloat(value):%0A%09try:%0A%09%09return float(value)%0A%09except ValueError:%0A%09%09return -1%0A%0Adef convint(value):%0A%09try:%0A%09%09return int(value)%0A%09except ValueError:%0A%09%09return 0%0A%0A%0Adef save2redis(key, value):%0A%09old = rdb.get(%22TW%22 + key)%0A%09if old is None:%0A%09%09val = %5B%5D%0A%09%09val.append(value)%0A%09%09rdb.set(%22TW%22+key ,json.dumps(val))%0A%09else:%0A%09%09l = json.loads(old)%0A%09%09l.append(value)%0A%09%09rdb.set(%22TW%22+key ,json.dumps(l))%0A%0A%0Atoday = datetime.date.today()%0A#today = datetime.date(2015, 5, 15)%0Aone_day = timedelta(days=1)%0Adl_date = today%0A%0Ahttpreq = httplib.HTTPConnection('www.twse.com.tw')%0Aheaders = %7B%22Content-type%22: %22application/x-www-form-urlencoded%22, %22Accept%22: %22text/plain%22%7D%0Adate_str = str(dl_date.year - 1911 ) + dl_date.strftime(%22/%25m/%25d%22)%0Aform = urllib.urlencode(%7B'download': 'csv', 'qdate': date_str, 'selectType': 'ALLBUT0999'%7D)%0Ahttpreq.request(%22POST%22, %22/ch/trading/exchange/MI_INDEX/MI_INDEX.php%22, form, headers);%0Ahttpres = httpreq.getresponse()%0Astock_csv = httpres.read()%0A%0Alines = stock_csv.split(%22%5Cn%22)%0Afor line in lines:%0A%09r = line.split('%22,%22')%0A%09if len(r) == 16:%0A%09%09head = r%5B0%5D.split(%22%5C%22%22)%0A%09%09sid = head%5B1%5D.strip(%22 %22)%0A%09%09obj = %7B%22volume%22: convint(r%5B2%5D), %22open%22: convfloat(r%5B5%5D), %22high%22: convfloat(r%5B6%5D), %22low%22: convfloat(r%5B7%5D), %22val%22: convfloat(r%5B8%5D), %22date%22: dl_date.strftime(%22%25Y-%25m-%25d%22), %22per%22: convfloat(r%5B15%5D), %22buyQuantity%22: convint(r%5B12%5D), %22buyPrice%22: convint(r%5B11%5D), %22saleQuantity%22: convint(r%5B14%5D), %22salePrice%22: convint(r%5B13%5D)%7D%0A%09%09print sid%0A%09%09print obj%0A%09%09save2redis(sid, obj)%0A
|
|
09d51aef1127b55fdc6bf595ca85285d9d7d64d1
|
Add wrapwrite utility method
|
gignore/utils.py
|
gignore/utils.py
|
Python
| 0.000001 |
@@ -0,0 +1,235 @@
+import sys%0A%0A%0Adef wrapwrite(text):%0A %22%22%22%0A :type text: str%0A%0A :rtype: str%0A %22%22%22%0A text = text.encode('utf-8')%0A try: # Python3%0A sys.stdout.buffer.write(text)%0A except AttributeError:%0A sys.stdout.write(text)%0A
|
|
617a44bcce3e6e19383065f7fcab5b44ceb82714
|
add logger
|
log.py
|
log.py
|
Python
| 0.000026 |
@@ -0,0 +1,240 @@
+import logging%0D%0Aimport sys%0D%0A%0D%0Alogger = logging.getLogger('micro-meta')%0D%0Alogger.setLevel(logging.DEBUG)%0D%0Afh = logging.StreamHandler(sys.stdout)%0D%0Afh.setLevel(logging.DEBUG)%0D%0A%0D%0Alogger.addHandler(fh)%0D%0A%0D%0Alogger.debug('test')%0D%0Alogger.info('test')
|
|
a38b313799b7c0cdc25ff68161c2b2890db8e16d
|
Create log.py
|
log.py
|
log.py
|
Python
| 0.000002 |
@@ -0,0 +1,728 @@
+import glob%0Aimport pandas as pd%0A%0Alogs = %5Blog for log in glob.glob(%22*.log%22)%5D%0A%0Adataset = %7B%22id%22: %5B%5D,%0A %22pos%22: %5B%5D,%0A %22affinity (kcal/mol)%22: %5B%5D,%0A %22rmsd l.b.%22: %5B%5D,%0A %22rmsd u.b.%22: %5B%5D%7D%0A%0Afor log in logs:%0A with open(log) as dock:%0A for line in dock.readlines():%0A if line.startswith(%22 %22) and line.split()%5B0%5D != %22%7C%22:%0A dataset%5B%22id%22%5D.append(log%5B:-4%5D)%0A dataset%5B%22pos%22%5D.append(line.split()%5B0%5D)%0A dataset%5B%22affinity (kcal/mol)%22%5D.append(line.split()%5B1%5D)%0A dataset%5B%22rmsd l.b.%22%5D.append(line.split()%5B2%5D)%0A dataset%5B%22rmsd u.b.%22%5D.append(line.split()%5B3%5D)%0A%0Adataframe = pd.DataFrame(data=dataset)%0Adataframe.to_csv(%22docks.csv%22)%0A
|
|
7263d7546aec62834fa19f20854522eba4916159
|
add simple http server
|
run.py
|
run.py
|
Python
| 0 |
@@ -0,0 +1,500 @@
+import sys%0Aimport BaseHTTPServer%0Afrom SimpleHTTPServer import SimpleHTTPRequestHandler%0A%0A%0AHandlerClass = SimpleHTTPRequestHandler%0AServerClass = BaseHTTPServer.HTTPServer%0AProtocol = %22HTTP/1.0%22%0A%0Aif sys.argv%5B1:%5D:%0A port = int(sys.argv%5B1%5D)%0Aelse:%0A port = 8000%0Aserver_address = ('127.0.0.1', port)%0A%0AHandlerClass.protocol_version = Protocol%0Ahttpd = ServerClass(server_address, HandlerClass)%0A%0Asa = httpd.socket.getsockname()%0Aprint %22Serving HTTP on%22, sa%5B0%5D, %22port%22, sa%5B1%5D, %22...%22%0Ahttpd.serve_forever()
|
|
e6d420296b3f2234382bdcdf1122abc59af148ed
|
add plot function for classification
|
mousestyles/visualization/plot_classification.py
|
mousestyles/visualization/plot_classification.py
|
Python
| 0.000009 |
@@ -0,0 +1,1291 @@
+import numpy as np%0Aimport pandas as pd%0Aimport matplotlib.pyplot as plt%0A%0A%0Adef plot_performance(model):%0A %22%22%22%0A Plots the performance of classification model.It%0A is a side-by-side barplot. For each strain, it plots%0A the precision, recall and F-1 measure.%0A Parameters%0A ----------%0A model: string%0A The model used to classify the strain%0A Returns%0A -------%0A None%0A %22%22%22%0A if model is 'SVM':%0A result = pd.DataFrame(np.load('SVM_result.npy'))%0A elif model is 'RF':%0A result = pd.DataFrame(np.load('RF_result.npy'))%0A elif model is 'GB':%0A result = pd.DataFrame(np.load('GB_result.npy'))%0A N = 16%0A ind = np.arange(N) # the x locations for the groups%0A width = 0.2%0A fig = plt.figure()%0A ax = fig.add_subplot(111)%0A precision = result.iloc%5B:, 0%5D%0A rects1 = ax.bar(ind, precision, width, color='Coral')%0A recall = result.iloc%5B:, 1%5D%0A rects2 = ax.bar(ind+width, recall, width, color='LightSeaGreen')%0A f1 = result.iloc%5B:, 2%5D%0A rects3 = ax.bar(ind+width*2, f1, width, color='DodgerBlue')%0A ax.set_ylabel('Accuracy')%0A ax.set_xlabel('Strains')%0A ax.set_xticks(ind+width)%0A ax.set_xticklabels(range(16))%0A ax.legend((rects1%5B0%5D, rects2%5B0%5D, rects3%5B0%5D), ('precision', 'recall', 'F1'))%0A plt.show()%0A return()%0A
|
|
a1ec669f4c494709dc9b8f3e47ff4f84b189b2e9
|
add get_workflow_name.py
|
.circleci/get_workflow_name.py
|
.circleci/get_workflow_name.py
|
Python
| 0.000002 |
@@ -0,0 +1,1987 @@
+# Copyright 2018 Google LLC%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A%22%22%22%0AGet workflow name for the current build using CircleCI API.%0AWould be great if this information is available in one of%0ACircleCI environment variables, but it's not there.%0Ahttps://circleci.ideas.aha.io/ideas/CCI-I-295%0A%22%22%22%0A%0Aimport json%0Aimport os%0Aimport sys%0Aimport urllib2%0A%0A%0Adef main():%0A try:%0A username = os.environ%5B'CIRCLE_PROJECT_USERNAME'%5D%0A reponame = os.environ%5B'CIRCLE_PROJECT_REPONAME'%5D%0A build_num = os.environ%5B'CIRCLE_BUILD_NUM'%5D%0A except:%0A sys.stderr.write(%0A 'Looks like we are not inside CircleCI container. Exiting...%5Cn')%0A return 1%0A%0A try:%0A request = urllib2.Request(%0A %22https://circleci.com/api/v1.1/project/github/%25s/%25s/%25s%22 %25%0A (username, reponame, build_num),%0A headers=%7B%22Accept%22: %22application/json%22%7D)%0A contents = urllib2.urlopen(request).read()%0A except:%0A sys.stderr.write('Cannot query CircleCI API. Exiting...%5Cn')%0A return 1%0A%0A try:%0A build_info = json.loads(contents)%0A except:%0A sys.stderr.write(%0A 'Cannot parse JSON received from CircleCI API. Exiting...%5Cn')%0A return 1%0A%0A try:%0A workflow_name = build_info%5B'workflows'%5D%5B'workflow_name'%5D%0A except:%0A sys.stderr.write(%0A 'Cannot get workflow name from CircleCI build info. Exiting...%5Cn')%0A return 1%0A%0A print workflow_name%0A return 0%0A%0A%0Aretval = main()%0Aexit(retval)%0A
|
|
3abf7e60d3bd028f86cb6aa2e1e1f3d4fff95353
|
Create BinaryTreeMaxPathSum_001.py
|
leetcode/124-Binary-Tree-Maximum-Path-Sum/BinaryTreeMaxPathSum_001.py
|
leetcode/124-Binary-Tree-Maximum-Path-Sum/BinaryTreeMaxPathSum_001.py
|
Python
| 0.000023 |
@@ -0,0 +1,1315 @@
+# Definition for a binary tree node.%0A# class TreeNode(object):%0A# def __init__(self, x):%0A# self.val = x%0A# self.left = None%0A# self.right = None%0A%0Aclass Solution(object):%0A def maxPathSum(self, root):%0A %22%22%22%0A :type root: TreeNode%0A :rtype: int%0A %22%22%22%0A totMax, branchMax = self.maxBranchandPathSum(root)%0A return totMax%0A%0A def maxBranchandPathSum(self, root):%0A if root is None:%0A return 0, 0%0A l, r = root.left, root.right%0A if l is None and r is None:%0A return root.val, root.val%0A%0A lTotMax, lBranchMax = self.maxBranchandPathSum(root.left)%0A rTotMax, rBranchMax = self.maxBranchandPathSum(root.right)%0A %0A lRootBranchMax = root.val + max(lBranchMax, 0)%0A rRootBranchMax = root.val + max(rBranchMax, 0)%0A%0A if l is None:%0A rootTotMax = max(rTotMax, rRootBranchMax)%0A return rootTotMax, rRootBranchMax%0A%0A if r is None:%0A rootTotMax = max(lTotMax, lRootBranchMax)%0A return rootTotMax, lRootBranchMax%0A%0A rootTreeMax = root.val + max(lBranchMax, 0) + max(rBranchMax, 0)%0A rootTotMax = max(lTotMax, rTotMax, rootTreeMax)%0A%0A rootBranchMax = max(lRootBranchMax, rRootBranchMax)%0A%0A return rootTotMax, rootBranchMax%0A
|
|
59fd4bf04c8c89cdc87673de94788c5d34d4e5fe
|
Create Goldbach.py
|
Goldbach.py
|
Goldbach.py
|
Python
| 0 |
@@ -0,0 +1,811 @@
+import math%0A#Funcion para saber si un numero es 3 o no%0Adef es_primo(a):%0A contador = 0%0A verificar= False%0A for i in range(1,a+1):%0A if (a%25 i)==0:%0A contador = contador + 1%0A if contador %3E= 3:%0A verificar=True%0A break%0A if contador==2 or verificar==False:%0A return True%0A return False%0A%0A%0A#Creacion de un lista con todos los primos del 1 al 10,000%0Adef lista_primos():%0A%09primos = list();%0A%09for i in range (1,10000):%0A%09%09if es_primo(i):%0A%09%09%09primos.append(i)%0A%09return primos%0A%0Adef lista_impares():%0A%09impares = list();%0A%09for i in range (1,10000,2):%0A%09%09if not es_primo(i):%0A%09%09%09impares.append(i)%0A%0Aprimos = lista_primos()%0Aimpares = lista_impares()%0Aa = 0%0Aimpar = 1%0Afor primo in primos:%0A%09for n in range (1,10000):%0A%09%09a = primo + (2)*(math.pow(n,2))%0A%09%09if a != impar and n %3E 500000:%0A%09%09%09print (impar)%0A%09%09impar += 2%0A
|
|
e33774beb2f2b1264f654605294f0ad837fa7e8b
|
Add message_link function
|
utils/backends.py
|
utils/backends.py
|
Python
| 0.000001 |
@@ -0,0 +1,614 @@
+%22%22%22%0AHandle backend specific implementations.%0A%22%22%22%0A%0Adef message_link(bot, msg):%0A %22%22%22%0A :param bot: Plugin instance.%0A :param msg: Message object.%0A :returns: Message link.%0A %22%22%22%0A backend = bot.bot_config.BACKEND.lower()%0A if backend == 'gitter':%0A return 'https://gitter.im/%7Buri%7D?at=%7Bidd%7D'.format(msg.frm.room.uri,%0A msg.extras%5B'id'%5D)%0A elif backend == 'slack':%0A return msg.extras%5B'url'%5D%0A elif backend == 'telegram':%0A return ''%0A elif backend == 'text':%0A return ''%0A else:%0A raise NotImplementedError%0A
|
|
f509d556cc4a20b55be52f505fcee200c5d44ef2
|
add rehex util
|
scripts/rehex.py
|
scripts/rehex.py
|
Python
| 0.000001 |
@@ -0,0 +1,500 @@
+import simplejson%0Aimport binascii%0Aimport sys%0Aimport pdb%0Afrom pprint import pprint%0Aimport sys, os%0Asys.path.append( os.path.join( os.path.dirname(__file__), '..' ) )%0Asys.path.append( os.path.join( os.path.dirname(__file__), '..', 'lib' ) )%0Aimport dashlib%0A# ============================================================================%0Ausage = %22%25s %3Chex%3E%22 %25 sys.argv%5B0%5D%0A%0Aobj = None%0Aif len(sys.argv) %3C 2:%0A print(usage)%0A sys.exit(2)%0Aelse:%0A obj = dashlib.deserialise(sys.argv%5B1%5D)%0A%0Apdb.set_trace()%0A1%0A
|
|
cf881dd1ba8c98dd116f2269bf0cfd38f14a7b40
|
add a reel OVSFtree
|
OVSFTree.py
|
OVSFTree.py
|
Python
| 0.000001 |
@@ -0,0 +1,1198 @@
+import math%0AnumberOfMobile=512%0Aclass Node:%0A def __init__(self, val):%0A self.l = None%0A self.r = None%0A self.v = val%0A%0Aclass Tree:%0A def __init__(self):%0A self.root = None%0A self.root=Node(1)%0A thislevel = %5Bself.root%5D%0A for i in range(0,math.ceil(math.log(numberOfMobile,2))):%0A nextlevel=%5B%5D%0A xornumber=pow(2,pow(2,i))-1%0A for n in thislevel:%0A codesize=n.v.bit_length()%0A n.l=Node((n.v%3C%3Ccodesize)+n.v)%0A n.r=Node((n.v%3C%3Ccodesize)+(n.v%5Exornumber))%0A nextlevel.append(n.l)%0A nextlevel.append(n.r)%0A thislevel=nextlevel%0A%0A def getRoot(self):%0A return self.root%0A%0A def deleteTree(self):%0A # garbage collector will do this for us. %0A self.root = None%0A%0A def traverse(self):%0A thislevel = %5Bself.root%5D%0A while thislevel:%0A nextlevel = %5B%5D %0A for n in thislevel:%0A print( str(bin(n.v)), end=%22 %22)%0A if n.l: nextlevel.append(n.l)%0A if n.r: nextlevel.append(n.r)%0A print(%22 %22)%0A thislevel = nextlevel%0A%0Atree1=Tree()%0Atree1.traverse()%0A
|
|
632c4dffe8a217ca07410d0a353455a4c6142d39
|
Solve problem 29
|
problem029.py
|
problem029.py
|
Python
| 0.99998 |
@@ -0,0 +1,92 @@
+#!/usr/bin/env python3%0A%0Aprint(len(set(a**b for a in range(2, 101) for b in range(2, 101))))%0A
|
|
b1815075ac1a1697c99a6293c8cc7719060ab9b2
|
Add cpuspeed sensor
|
homeassistant/components/sensor/cpuspeed.py
|
homeassistant/components/sensor/cpuspeed.py
|
Python
| 0.000001 |
@@ -0,0 +1,1984 @@
+%22%22%22%0Ahomeassistant.components.sensor.cpuspeed%0A~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%0AShows the current CPU speed.%0A%0AFor more details about this platform, please refer to the documentation at%0Ahttps://home-assistant.io/components/sensor.cpuspeed.html%0A%22%22%22%0Aimport logging%0A%0Afrom homeassistant.helpers.entity import Entity%0A%0AREQUIREMENTS = %5B'py-cpuinfo==0.1.6'%5D%0A%0A_LOGGER = logging.getLogger(__name__)%0A%0ADEFAULT_NAME = %22CPU speed%22%0A%0AATTR_VENDOR = 'Vendor ID'%0AATTR_BRAND = 'Brand'%0AATTR_HZ = 'GHz Advertised'%0A%0A%0A# pylint: disable=unused-variable%0Adef setup_platform(hass, config, add_devices, discovery_info=None):%0A %22%22%22 Sets up the CPU speed sensor. %22%22%22%0A%0A try:%0A import cpuinfo # noqa%0A except ImportError:%0A _LOGGER.exception(%0A %22Unable to import cpuinfo. %22%0A %22Did you maybe not install the 'py-cpuinfo' package?%22)%0A return False%0A%0A add_devices(%5BCpuSpeedSensor(config.get('name', DEFAULT_NAME))%5D)%0A%0A%0Aclass CpuSpeedSensor(Entity):%0A %22%22%22 A CPU info sensor. %22%22%22%0A%0A def __init__(self, name):%0A self._name = name%0A self._state = None%0A self._unit_of_measurement = 'GHz'%0A self.update()%0A%0A @property%0A def name(self):%0A return self._name%0A%0A @property%0A def state(self):%0A %22%22%22 Returns the state of the device. %22%22%22%0A return self._state%0A%0A @property%0A def unit_of_measurement(self):%0A return self._unit_of_measurement%0A%0A @property%0A def state_attributes(self):%0A %22%22%22 Returns the state attributes. %22%22%22%0A if self.info is not None:%0A return %7B%0A ATTR_VENDOR: self.info%5B'vendor_id'%5D,%0A ATTR_BRAND: self.info%5B'brand'%5D,%0A ATTR_HZ: round(self.info%5B'hz_advertised_raw'%5D%5B0%5D/10**9, 2)%0A %7D%0A%0A def update(self):%0A %22%22%22 Gets the latest data and updates the state. %22%22%22%0A from cpuinfo import cpuinfo%0A%0A self.info = cpuinfo.get_cpu_info()%0A self._state = round(float(self.info%5B'hz_actual_raw'%5D%5B0%5D)/10**9, 2)%0A
|
|
0ba15652a5624cf8fa42f4caf603d84c09a0698b
|
Add kata: 6 kyu
|
6_kyu/Decode_the_Morse_code.py
|
6_kyu/Decode_the_Morse_code.py
|
Python
| 0.999999 |
@@ -0,0 +1,288 @@
+# @see: https://www.codewars.com/kata/decode-the-morse-code%0Adef decodeMorse(morseCode):%0A return ' '.join(%0A map(lambda m_word: ''.join(%0A map(lambda m_symbol: MORSE_CODE%5Bm_symbol%5D,%0A m_word.split())),%0A morseCode.strip().split(' ')))%0A%0A
|
|
6837bbf2a1816d97b6c517bcb244aa51cf1eb7ba
|
Create robots_txt.py
|
robots_txt.py
|
robots_txt.py
|
Python
| 0.000064 |
@@ -0,0 +1,161 @@
+import urlib.request%0Aimport io%0A%0Adef ger_robots_txt(url):%0A if url.endswith('/')%0A path = url%0A else: %0A path - url + '/'%0A%0A# https://reddit.com/%0A%0A
|
|
b36192eec53664f9178bfc4000d89b8ca9be1544
|
Add merge migration
|
osf/migrations/0030_merge.py
|
osf/migrations/0030_merge.py
|
Python
| 0 |
@@ -0,0 +1,331 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9 on 2017-01-24 18:57%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('osf', '0029_merge'),%0A ('osf', '0029_externalaccount_date_last_refreshed'),%0A %5D%0A%0A operations = %5B%0A %5D%0A
|
|
db41bce3d90cfada9916baa8f9267cd9e6160a94
|
Add an example for opening a file.
|
examples/open_file.py
|
examples/open_file.py
|
Python
| 0 |
@@ -0,0 +1,170 @@
+import numpy as np%0Aimport pyh5md%0A%0Af = pyh5md.H5MD_File('poc.h5', 'r')%0A%0Aat = f.trajectory('atoms')%0A%0Aat_pos = at.data('position')%0A%0Ar = at_pos.v.value%0A%0Aprint r%0A%0Af.f.close()%0A
|
|
2cd57876c72d5c941bcb1ae497df48dbbc943ba9
|
Create new package. (#6213)
|
var/spack/repos/builtin/packages/r-forecast/package.py
|
var/spack/repos/builtin/packages/r-forecast/package.py
|
Python
| 0 |
@@ -0,0 +1,2298 @@
+##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, [email protected], All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass RForecast(RPackage):%0A %22%22%22Methods and tools for displaying and analysing univariate time%0A series forecasts including exponential smoothing via state space%0A models and automatic ARIMA modelling.%22%22%22%0A%0A homepage = %22https://cran.r-project.org/package=forecast%22%0A url = %22https://cran.r-project.org/src/contrib/forecast_8.2.tar.gz%22%0A list_url = %22https://cran.r-project.org/src/contrib/Archive/forecast%22%0A%0A version('8.2', '3ef095258984364c100b771b3c90d15e')%0A%0A depends_on('r-magrittr', type=('build', 'run'))%0A depends_on('r-ggplot2', type=('build', 'run'))%0A depends_on('r-colorspace', type=('build', 'run'))%0A depends_on('r-nnet', type=('build', 'run'))%0A depends_on('r-rcpp', type=('build', 'run'))%0A depends_on('r-fracdiff', type=('build', 'run'))%0A depends_on('r-tseries', type=('build', 'run'))%0A depends_on('r-lmtest', type=('build', 'run'))%0A depends_on('r-zoo', type=('build', 'run'))%0A depends_on('r-timedate', type=('build', 'run'))%0A depends_on('r-rcpparmadillo', type=('build', 'run'))%0A
|
|
c192042bbaf9060ce3a76f1cbabc5f380fa4bfd6
|
Adding uppercase character
|
src/Character.py
|
src/Character.py
|
Python
| 0.999723 |
@@ -0,0 +1,799 @@
+import pygame%0Afrom sprite import *%0Afrom constants import *%0A%0Aclass Character:%0A%09def __init__(self):%0A%09%09self.sprite = Sprite('../resources/char.png')%0A%09%09self.health = 10%0A%09%09self.speed = 40%0A%0A%09def move(self, direction):%0A%09%09#pos = self.sprite.getPosition()%0A%09%09charWidth = self.sprite.rect.width%0A%09%09charHeight = self.sprite.rect.height%0A%09%09curX = self.sprite.rect.x%0A%09%09curY = self.sprite.rect.y%0A%09%09newX = curX + (direction%5B0%5D * self.speed)%0A%09%09newY = curY + (direction%5B1%5D * self.speed)%0A%0A%09%09# Detect if near any edges/walls%0A%09%09if newX %3C= 0:%0A%09%09%09newX = 0 %0A%09%09elif newX %3E= WIDTH - charWidth:%0A%09%09%09newX = WIDTH - charWidth%0A%0A%09%09if newY %3C= 0:%0A%09%09%09newY = 0 %0A%09%09elif newY %3E= HEIGHT - charHeight:%0A%09%09%09newY = HEIGHT - charHeight%0A%0A%09%09self.sprite.set_position(newX, newY)%0A%0A%09def draw(self, window_surface):%0A%09%09self.sprite.draw(window_surface)%0A
|
|
10eb703867fd10df543a141837c2a57d1052ba2c
|
Rename file with correct pattern
|
ideascube/conf/kb_civ_babylab.py
|
ideascube/conf/kb_civ_babylab.py
|
Python
| 0.000001 |
@@ -0,0 +1,1248 @@
+# -*- coding: utf-8 -*-%0A%22%22%22KoomBook conf%22%22%22%0Afrom .kb import * # noqa%0Afrom django.utils.translation import ugettext_lazy as _%0A%0ALANGUAGE_CODE = 'fr'%0AIDEASCUBE_NAME = 'BabyLab'%0AHOME_CARDS = STAFF_HOME_CARDS + %5B%0A %7B%0A 'id': 'blog',%0A %7D,%0A %7B%0A 'id': 'mediacenter',%0A %7D,%0A %7B%0A 'id': 'bsfcampus',%0A %7D,%0A %7B%0A 'id': 'khanacademy',%0A %7D,%0A %7B%0A 'id': 'wikistage',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'wikimooc',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'vikidia',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'universcience',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'e-penser',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'deus-ex-silicium',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'cest-pas-sorcier',%0A %7D,%0A %7B%0A 'id': 'wikipedia',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'wikiversity',%0A 'languages': %5B'fr'%5D%0A %7D,%0A %7B%0A 'id': 'ted',%0A 'sessions': %5B%0A ('tedxgeneva2014.fr', 'Geneva 2014'),%0A ('tedxlausanne2012.fr', 'Lausanne 2012'),%0A ('tedxlausanne2013.fr', 'Lausanne 2013'),%0A ('tedxlausanne2014.fr', 'Lausanne 2014'),%0A %5D%0A %7D,%0A%5D%0A
|
|
f31fcd789254f95b311f4fa4009a04ad919c2027
|
add url update migration
|
accelerator/migrations/0049_update_fluent_redirect_url.py
|
accelerator/migrations/0049_update_fluent_redirect_url.py
|
Python
| 0.000001 |
@@ -0,0 +1,1302 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.18 on 2019-04-11 11:35%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0Afrom accelerator.sitetree_navigation.sub_navigation import (%0A create_directory_subnav,%0A create_events_subnav,%0A create_home_subnav,%0A create_judging_subnav,%0A create_resources_subnav,%0A create_startup_dashboard_subnav,%0A delete_directory_subnav,%0A delete_events_subnav,%0A delete_home_subnav,%0A delete_judging_subnav,%0A delete_resources_subnav,%0A delete_startup_dashboard_subnav%0A)%0A%0A%0Adef create_subnav_trees_and_items(apps, schema_editor):%0A create_directory_subnav()%0A create_events_subnav()%0A create_home_subnav()%0A create_judging_subnav()%0A create_resources_subnav()%0A create_startup_dashboard_subnav()%0A%0A%0Adef delete_subnav_trees_and_items(apps, schema_editor):%0A delete_directory_subnav()%0A delete_events_subnav()%0A delete_home_subnav()%0A delete_judging_subnav()%0A delete_resources_subnav()%0A delete_startup_dashboard_subnav()%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('accelerator', '0048_create_sub_navigation_objects'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(%0A create_subnav_trees_and_items,%0A delete_subnav_trees_and_items),%0A %5D%0A
|
|
96ba88c74a77f3b71ef4a8b51c29013d16e23973
|
Create tofu/plugins/MISTRAL/Inputs with empty __init__.py
|
tofu/plugins/MISTRAL/Inputs/__init__.py
|
tofu/plugins/MISTRAL/Inputs/__init__.py
|
Python
| 0.000017 |
@@ -0,0 +1 @@
+%0A
|
|
1ca7e5f02f095c4a5164c2e9e0f939e67853966f
|
Fix get_solution_path in UserSolution
|
problems/models.py
|
problems/models.py
|
from base.util import with_timestamp, with_author
from django.db import models
from djangoratings.fields import RatingField
from base.models import MediaRemovalMixin
from competitions.models import Competition
# Solution-related models
@with_author
@with_timestamp
class UserSolution(MediaRemovalMixin, models.Model):
'''
Represents a user submitted solution of a given problem.
'''
def get_solution_path(self):
return 'solutions/{user}-{problem}.pdf'.format(
user=unicode(self.user),
problem=self.problem.pk,
)
# Keep an explicit reference to an User, since somebody else might
# be entering the solution on the user's behalf
user = models.ForeignKey('auth.User')
problem = models.ForeignKey('problems.Problem')
solution = models.FileField(upload_to=get_solution_path)
def __unicode__(self):
return (self.user.__unicode__() + u":'s solution of " +
self.problem.__unicode__())
class Meta:
order_with_respect_to = 'problem'
verbose_name = 'User solution'
verbose_name_plural = 'User solutions'
@with_author
@with_timestamp
class OrgSolution(models.Model):
'''
Represents an ideal solution of a problem. There can be multiple ideal
solutions (more organizers trying to solve it, more ways of solving).
'''
# Keep an explicit reference to an Organizer, since somebody else might
# be entering the solution on the organizer's behalf
organizer = models.ForeignKey('auth.User')
problem = models.ForeignKey('problems.Problem')
def __unicode__(self):
return (self.user.__unicode__() + u":'s ideal solution of " +
self.problem.__unicode__())
class Meta:
order_with_respect_to = 'problem'
verbose_name = 'Organizer solution'
verbose_name_plural = 'Organizer solutions'
# Problem-related models
@with_author
@with_timestamp
class Problem(models.Model):
'''
Represents a problem.
'''
def get_rating(self):
return self.rating.get_rating()
get_rating.short_description = 'Rating'
def get_usages(self):
#FIXME: problemsets that have no event will not be displayed
sets = self.problemset_set.order_by('-event__start_time')\
.filter(event__isnull=False)
if sets.exists():
return sets
else:
return []
def last_used_at(self):
usages = self.get_usages()
if usages:
if usages[0].event:
return usages[0].event
def last_five_usages(self):
usages = self.get_usages()[:5]
if usages:
return ', '.join([str(problemset.event) for problemset in usages])
else:
return ''
def times_used(self):
return len(self.get_usages())
text = models.TextField(help_text='The problem itself. Please insert it '
'in a valid TeX formatting.')
rating = RatingField(range=5)
severity = models.ForeignKey('problems.ProblemSeverity')
category = models.ForeignKey('problems.ProblemCategory')
competition = models.ForeignKey('competitions.Competition')
# Fields added via foreign keys:
# orgsolution_set
# problemset_set
# user_set
# usersolution_set
def __unicode__(self):
return self.text
class Meta:
verbose_name = 'Problem'
verbose_name_plural = 'Problems'
class ProblemInSet(models.Model):
problem = models.ForeignKey('problems.Problem')
problemset = models.ForeignKey('problems.ProblemSet')
position = models.PositiveSmallIntegerField("Position")
def get_rating(self):
return self.problem.get_rating()
def get_usages(self):
return self.problem.get_usages()
def last_used_at(self):
return self.problem.last_used_at()
def last_five_usages(self):
return self.problem.last_five_usages()
def times_used(self):
return self.problem.times_used()
def get_category(self):
return self.problem.category
def get_severity(self):
return self.problem.severity
def get_competition(self):
return self.problem.competition
get_rating.short_description = 'Rating'
get_usages.short_description = 'Usages'
last_used_at.short_description = 'Last used at'
last_five_usages.short_description = 'Last five usages'
times_used.short_description = 'Times used'
get_category.short_description = 'Category'
get_severity.short_description = 'Severity'
get_competition.short_description = 'Competition'
def __unicode__(self):
return self.problem.__unicode__()
class Meta:
verbose_name = 'Problem'
verbose_name_plural = 'Problems'
ordering = ['position']
unique_together = ['problem', 'problemset']
@with_author
@with_timestamp
class ProblemSet(models.Model):
'''
Represents a collections of problems. This can (optionally) be used at
event or competition, which organizer should mark here.
'''
name = models.CharField(max_length=100)
description = models.CharField(max_length=400, blank=True, null=True)
competition = models.ForeignKey('competitions.Competition')
leaflet = models.ForeignKey('leaflets.Leaflet',
blank=True, null=True)
event = models.ForeignKey('events.Event', blank=True, null=True)
problems = models.ManyToManyField(Problem, through='problems.ProblemInSet')
def average_severity(self):
problemset = self.problems.filter(competition=self.competition)
average = problemset.aggregate(
models.Avg('severity__level'))['severity__level__avg']
return average
def average_severity_by_competition(self):
averages = dict()
for competition in Competition.objects.all():
problemset = self.problems.filter(competition=competition)
average = problemset.aggregate(
models.Avg('severity__level'))['severity__level__avg']
if average:
key = unicode(competition)
averages[key] = average
return averages
def __unicode__(self):
return self.name
def get_problem_count(self):
return self.problems.count()
get_problem_count.short_description = "Problems"
def get_average_severity_by_competition(self):
averages = self.average_severity_by_competition()
reports = []
for competition, average in averages.iteritems():
reports.append("%s (%s)" % (competition, average))
return ', '.join(reports)
get_average_severity_by_competition.short_description = "Average difficulty"
class Meta:
verbose_name = 'Set'
verbose_name_plural = 'Sets'
class ProblemCategory(models.Model):
'''
Represents a category of problems, like geometry or functional equations.
'''
name = models.CharField(max_length=50)
# Fields added via foreign keys:
# problem_set
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class ProblemSeverity(models.Model):
'''
Lets you define custom levels of severity for problems.
Severity level is represented by its name and level, e.g.:
easy - 1
medium -2
hard - 3
godlike - 4
This is not hardcoded so that every organization can use their own
levels of severity to categorize their problems.
'''
name = models.CharField(max_length=50)
level = models.IntegerField()
def __unicode__(self):
return unicode(self.level) + ' - ' + self.name
class Meta:
ordering = ['level']
verbose_name = 'Severity'
verbose_name_plural = 'Severities'
|
Python
| 0 |
@@ -419,24 +419,41 @@
on_path(self
+, *args, **kwargs
):%0A r
|
35317e778b2fe1d238e21954df1eac0c5380b00b
|
Add corpus fetch from database
|
generate_horoscope.py
|
generate_horoscope.py
|
Python
| 0 |
@@ -0,0 +1,2354 @@
+#!/usr/bin/env python3%0A# encoding: utf-8%0A%0Aimport argparse%0Aimport sqlite3%0Aimport sys%0A%0A%22%22%22generate_horoscope.py: Generates horoscopes based provided corpuses%22%22%22%0A%0A__author__ = %22Project Zodiacy%22%0A__copyright__ = %22Copyright 2015, Project Zodiacy%22%0A%0A_parser = argparse.ArgumentParser(description=%22Awesome SQLite importer%22)%0A_parser.add_argument('-d', '--database', dest='database', required=True, help='sqlite database file')%0A_parser.add_argument('-s', '--sign', dest='sign', help='zodiac sign to generate', default=None)%0A_parser.add_argument('-k', '--keyword', dest='keyword', help='keyword for the horoscope', default=None)%0A_parser.add_argument('-t', '--threshold', dest='threshold', help='minimum count of horoscopes for the given filters', default=10)%0A%0Adef keyword_valid(cursor, keyword, threshold=10):%0A %22%22%22 Checks whether enough horoscopes are present for the keyword %22%22%22%0A # TODO implement%0A return True%0A%0Adef get_corpuses(cursor, with_rating=False, zodiac_sign=None, keyword=None):%0A %22%22%22 Returns a cursor with all horoscopes for the given parameters %22%22%22%0A # ugly code =(%0A zodiac_signs = dict(zip(%5B'general', 'aries', 'taurus', 'gemini', 'cancer', 'leo', 'virgo', 'libra', 'scorpio', 'sagittarius', 'capricorn', 'aquarius', 'pisces'%5D, range(13)))%0A if zodiac_sign not in zodiac_signs:%0A if zodiac_sign is not None:%0A raise ValueError('Invalid zodiac sign')%0A else:%0A zodiac_sign_ordinal = zodiac_signs%5Bzodiac_sign%5D%0A%0A base_stmt = 'SELECT interp%25s from horoscopes' %25 (',rating' if with_rating else '')%0A if zodiac_sign is None:%0A if keyword is None:%0A return cursor.execute(base_stmt)%0A else:%0A return cursor.execute(base_stmt + ' WHERE keyword=?', (keyword,))%0A else:%0A if keyword is None:%0A return cursor.execute(base_stmt + ' WHERE sign=?', (str(zodiac_sign_ordinal),))%0A else:%0A return cursor.execute(base_stmt + ' WHERE sign=? and keyword=?', (str(zodiac_sign_ordinal), keyword))%0A%0Aif __name__ == '__main__':%0A args = _parser.parse_args()%0A%0A with sqlite3.connect(args.database) as conn:%0A if not keyword_valid: %0A print('Not enough horoscopes for the given keyword', sys.stderr)%0A sys.exit(1)%0A corpuses = get_corpuses(conn.cursor(), zodiac_sign=None, keyword='enthusiasm')%0A print(corpuses.fetchone())%0A
|
|
0b03dd638dd5ac3358d89a5538c707d5412b84ae
|
Add basic network broker state machine
|
broker/network.py
|
broker/network.py
|
Python
| 0 |
@@ -0,0 +1,1949 @@
+from hypothesis.stateful import GenericStateMachine%0A%0Aclass NetworkBroker(GenericStateMachine):%0A %22%22%22%0A Broker to coordinate network traffic%0A%0A nodes = A map of node ids to node objects.%0A network = An adjacency list of what nodes can talk to each other. If a is%0A in network%5Bb%5D than b -%3E a communcation is allowed. This is a map of%0A id type -%3E set(id type)%0A messages = A queue of messages. messages%5B0%5D is the head, where messages are%0A sent from. Messages are tuples in the form of (from, to, data).%0A %22%22%22%0A def __init__(self, nodes):%0A self.nodes = nodes%0A self.network = dict(%5B(i, set(nodes.keys())) for i in nodes.keys()%5D)%0A self.messages = %5B%5D%0A%0A def steps(self):%0A pass%0A%0A def execute_step(self, step):%0A %22%22%22%0A Actions:%0A DeliverMsg%0A If next message is deliverable, deliver it. Otherwise, drop it.%0A DropMsg%0A Drop the next message.%0A DestroyEdge (from, to)%0A Destroys the edge from -%3E to, causing any packets sent along it to be dropped.%0A HealEdge (from, to)%0A Heal the edge from -%3E to, allowing packets to be sent along it.%0A DuplicateMsg%0A Create a copy of the message at the front of the queue%0A DelayMsg n%0A Push the message at the front of the queue back by n slots%0A %22%22%22%0A action, value = step%0A if action == %22DeliverMsg%22:%0A message = self.messages.pop(0)%0A self.nodes%5Bmessage%5B1%5D%5D.recv(message%5B0%5D, message%5B2%5D)%0A if action == %22DropMsg%22:%0A self.messages.pop(0)%0A if action == %22DestroyEdge%22:%0A self.network%5Bstep%5B0%5D%5D.remove(step%5B1%5D)%0A if action == %22HealEdge%22:%0A self.network%5Bstep%5B0%5D%5D.add(step%5B1%5D)%0A if action == %22DuplicateMsg%22:%0A self.messages.insert(0, self.messages%5B0%5D)%0A if action == %22DelayMsg%22:%0A self.messages.insert(value, self.messages.pop(0))%0A%0A
|
|
c48be39a1f04af887349ef7f19ecea4312425cf9
|
initialize for production
|
shoppley.com/shoppley/apps/offer/management/commands/initialize.py
|
shoppley.com/shoppley/apps/offer/management/commands/initialize.py
|
Python
| 0.000001 |
@@ -0,0 +1,986 @@
+from django.core.management.base import NoArgsCommand%0Afrom shoppleyuser.models import Country, Region, City, ZipCode, ShoppleyUser%0Aimport os, csv%0Afrom googlevoice import Voice%0A%0AFILE_ROOT = os.path.abspath(os.path.dirname(__file__))%0A%0Aclass Command(NoArgsCommand):%0A%09def handle_noargs(self, **options):%0A%09%09f = open(FILE_ROOT+%22/../../../shoppleyuser/data/US.txt%22, %22r%22)%0A%09%09zip_reader = csv.reader(f, delimiter=%22%5Ct%22)%0A%09%09for row in zip_reader:%0A%09%09%09country_obj, created = Country.objects.get_or_create(name=%22United States%22, code=row%5B0%5D)%0A%09%09%09zip_code = row%5B1%5D%0A%09%09%09city = row%5B2%5D%0A%09%09%09region = row%5B3%5D%0A%09%09%09region_code = row%5B4%5D%0A%09%09%09latitude = row%5B9%5D%0A%09%09%09longitude = row%5B10%5D%0A%09%09%09region_obj, created = Region.objects.get_or_create(name=region,%0A%09%09%09%09%09%09code=region_code, country=country_obj)%0A%09%09%09city_obj, created = City.objects.get_or_create(name=city, region=region_obj)%0A%09%09%09zip_obj, created = ZipCode.objects.get_or_create(code=zip_code,%0A%09%09%09%09%09%09city=city_obj, latitude=latitude, longitude=longitude)%0A%0A%09%09print %22done%22%0A
|
|
00f3e74387fc7a215af6377cb90555d142b81d74
|
Add acoustics module with class AcousticMaterial.
|
pyfds/acoustics.py
|
pyfds/acoustics.py
|
Python
| 0 |
@@ -0,0 +1,1053 @@
+class AcousticMaterial:%0A %22%22%22Class for specification of acoustic material parameters.%22%22%22%0A%0A def __init__(self, sound_velocity, density,%0A shear_viscosity=0, bulk_viscosity=0,%0A thermal_conductivity=0, isobaric_heat_cap=1, isochoric_heat_cap=1):%0A %22%22%22Default values for optional parameters create lossless medium.%22%22%22%0A%0A self.sound_velocity = sound_velocity%0A self.density = density%0A self.shear_viscosity = shear_viscosity%0A self.bulk_viscosity = bulk_viscosity%0A self.thermal_conductivity = thermal_conductivity%0A self.isobaric_heat_cap = isobaric_heat_cap%0A self.isochoric_heat_cap = isochoric_heat_cap%0A%0A @property%0A def absorption_coef(self):%0A %22%22%22This is a helper variable that sums up all losses into a single quantity.%22%22%22%0A%0A return (4/3 * self.shear_viscosity + self.bulk_viscosity + self.thermal_conductivity *%0A (self.isobaric_heat_cap - self.isochoric_heat_cap) /%0A (self.isobaric_heat_cap * self.isochoric_heat_cap))%0A
|
|
0d097139d62afa05a2af099ea2e83ddd4bb6344d
|
Move common segment imports
|
powerline/segments/common.py
|
powerline/segments/common.py
|
# -*- coding: utf-8 -*-
import os
import re
import socket
from powerline.lib.vcs import guess
from powerline.lib import memoize
# Weather condition code descriptions available at http://developer.yahoo.com/weather/#codes
weather_conditions_codes = {
u'〇': [25, 34],
u'⚑': [24],
u'☔': [5, 6, 8, 9, 10, 11, 12, 35, 40, 45, 47],
u'☁': [26, 27, 28, 29, 30, 44],
u'❅': [7, 13, 14, 15, 16, 17, 18, 41, 42, 43, 46],
u'☈': [0, 1, 2, 3, 4, 37, 38, 39],
u'〰': [19, 20, 21, 22, 23],
u'☼': [32, 36],
u'☾': [31, 33],
}
def hostname():
if not os.environ.get('SSH_CLIENT'):
return None
return socket.gethostname()
def user():
user = os.environ.get('USER')
euid = os.geteuid()
return {
'contents': user,
'highlight': 'user' if euid != 0 else ['superuser', 'user'],
}
def branch():
repo = guess(os.path.abspath(os.getcwd()))
if repo:
return repo.branch()
return None
def cwd(dir_shorten_len=None, dir_limit_depth=None):
cwd = os.getcwdu()
home = os.environ.get('HOME')
if home:
cwd = re.sub('^' + re.escape(home), '~', cwd, 1)
cwd_split = cwd.split(os.sep)
cwd_split_len = len(cwd_split)
if cwd_split_len > dir_limit_depth + 1:
del(cwd_split[0:-dir_limit_depth])
cwd_split.insert(0, u'⋯')
cwd = [i[0:dir_shorten_len] if dir_shorten_len and i else i for i in cwd_split[:-1]] + [cwd_split[-1]]
cwd = os.path.join(*cwd)
return cwd
def date(format='%Y-%m-%d'):
from datetime import datetime
return datetime.now().strftime(format)
@memoize(600, persistent=True)
def external_ip(query_url='http://ipv4.icanhazip.com/'):
import urllib2
try:
return urllib2.urlopen(query_url).read().strip()
except urllib2.HTTPError:
return
def system_load(format='{avg[0]:.1f}, {avg[1]:.1f}, {avg[2]:.1f}'):
from multiprocessing import cpu_count
averages = os.getloadavg()
normalized = averages[1] / cpu_count()
if normalized < 1:
gradient = 'system_load_good'
elif normalized < 2:
gradient = 'system_load_bad'
else:
gradient = 'system_load_ugly'
return {
'contents': format.format(avg=averages),
'highlight': [gradient, 'system_load']
}
def uptime(format='{days:02d}d {hours:02d}h {minutes:02d}m'):
# TODO: make this work with operating systems without /proc/uptime
try:
with open('/proc/uptime', 'r') as f:
seconds = int(float(f.readline().split()[0]))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
return format.format(days=int(days), hours=hours, minutes=minutes)
except IOError:
pass
@memoize(600, persistent=True)
def weather(unit='c', location_query=None):
import json
import urllib
import urllib2
if not location_query:
try:
location = json.loads(urllib2.urlopen('http://freegeoip.net/json/' + external_ip()).read())
location_query = ','.join([location['city'], location['region_name'], location['country_name']])
except ValueError:
return None
query_data = {
'q':
'use "http://github.com/yql/yql-tables/raw/master/weather/weather.bylocation.xml" as we;'
'select * from we where location="{0}" and unit="{1}"'.format(location_query, unit),
'format': 'json'
}
url = 'http://query.yahooapis.com/v1/public/yql?' + urllib.urlencode(query_data)
response = json.loads(urllib2.urlopen(url).read())
condition = response['query']['results']['weather']['rss']['channel']['item']['condition']
condition_code = int(condition['code'])
icon = u'〇'
for icon, codes in weather_conditions_codes.items():
if condition_code in codes:
break
return u'{0} {1}°{2}'.format(icon, condition['temp'], unit.upper())
def network_load(interface='eth0', measure_interval=1, suffix='B/s', binary_prefix=False):
import time
from powerline.lib import humanize_bytes
def get_bytes():
try:
with open('/sys/class/net/{interface}/statistics/rx_bytes'.format(interface=interface), 'rb') as file_obj:
rx = int(file_obj.read())
with open('/sys/class/net/{interface}/statistics/tx_bytes'.format(interface=interface), 'rb') as file_obj:
tx = int(file_obj.read())
return (rx, tx)
except IOError:
return (0, 0)
b1 = get_bytes()
time.sleep(measure_interval)
b2 = get_bytes()
return u'⬇ {rx_diff} ⬆ {tx_diff}'.format(
rx_diff=humanize_bytes((b2[0] - b1[0]) / measure_interval, suffix, binary_prefix),
tx_diff=humanize_bytes((b2[1] - b1[1]) / measure_interval, suffix, binary_prefix),
)
|
Python
| 0.000001 |
@@ -32,68 +32,8 @@
os%0A
-import re%0Aimport socket%0A%0Afrom powerline.lib.vcs import guess
%0Afro
@@ -469,16 +469,31 @@
name():%0A
+%09import socket%0A
%09if not
@@ -744,16 +744,53 @@
anch():%0A
+%09from powerline.lib.vcs import guess%0A
%09repo =
@@ -926,16 +926,27 @@
=None):%0A
+%09import re%0A
%09cwd = o
|
60e65d31c943f63e646b39350f18e6d177fbb66b
|
Add okupy.common.test_helpets.set_request
|
okupy/common/test_helpers.py
|
okupy/common/test_helpers.py
|
# vim:fileencoding=utf8:et:ts=4:sts=4:sw=4:ft=python
from django.test import TestCase
from django.contrib.messages.storage.cookie import CookieStorage
class OkupyTestCase(TestCase):
def _get_matches(self, response, text):
""" Get messages that match the given text """
messages = self._get_messages(response)
if messages:
matches = [m for m in messages if text == m.message]
return matches
else:
self.fail('No messages found')
def _get_messages(self, response):
""" Get all messages from the context or the CookieStorage """
try:
messages = response.context['messages']
except (TypeError, KeyError):
try:
messages = CookieStorage(response)._decode(
response.cookies['messages'].value)
except KeyError:
return
return messages
def assertMessageCount(self, response, expect_num):
"""
Asserts that exactly the given number of messages have been sent.
"""
messages = self._get_messages(response)
if messages:
actual_num = len(messages)
else:
actual_num = 0
if actual_num != expect_num:
self.fail('Message count was %d, expected %d' %
(actual_num, expect_num))
def assertMessage(self, response, text, level=None):
"""
Asserts that there is exactly one message containing the given text.
"""
matches = self._get_matches(response, text)
if len(matches) == 1:
msg = matches[0]
if level is not None and msg.level != level:
self.fail('There was one matching message but with different '
'level: %s != %s' % (msg.level, level))
elif len(matches) == 0:
messages_str = ", ".join(
'"%s"' % m for m in self._get_messages(response))
self.fail('No message contained text "%s", messages were: %s' %
(text, messages_str))
else:
self.fail('Multiple messages contained text "%s": %s' %
(text, ", ".join(('"%s"' % m) for m in matches)))
def assertNotMessage(self, response, text):
""" Assert that no message contains the given text. """
matches = self._get_matches(response, text)
if len(matches) > 0:
self.fail('Message(s) contained text "%s": %s' %
(text, ", ".join(('"%s"' % m) for m in matches)))
|
Python
| 0.000007 |
@@ -63,20 +63,96 @@
ngo.
-test
+contrib.auth.models import AnonymousUser%0Afrom django.contrib.messages.middleware
import
Test
@@ -151,81 +151,740 @@
ort
-TestCase%0Afrom django.contrib.messages.storage.cookie import CookieStorage
+MessageMiddleware%0Afrom django.contrib.sessions.middleware import SessionMiddleware%0Afrom django.contrib.messages.storage.cookie import CookieStorage%0Afrom django.test import TestCase, RequestFactory%0A%0A%0Adef set_request(uri, post=False, user=False, messages=False):%0A if post:%0A if type(post) == bool:%0A post = %7B%7D%0A request = RequestFactory().post(uri, post)%0A else:%0A request = RequestFactory().get(uri)%0A if user:%0A request.user = user%0A else:%0A request.user = AnonymousUser()%0A request.user.is_verified = lambda: True%0A request.session = %7B%7D%0A if messages:%0A SessionMiddleware().process_request(request)%0A MessageMiddleware().process_request(request)%0A return request
%0A%0A%0Ac
@@ -913,17 +913,16 @@
tCase):%0A
-%0A
def
|
b25a172cd89e8811e5cb38414bdf86ef5a5afaee
|
fix ABC for py2.7
|
rhea/system/cso.py
|
rhea/system/cso.py
|
from __future__ import absolute_import
from abc import ABCMeta, abstractclassmethod
from myhdl import Signal, SignalType, always_comb
class ControlStatusBase(metaclass=ABCMeta):
def __init__(self):
self._isstatic = False
@property
def isstatic(self):
return self._isstatic
@isstatic.setter
def isstatic(self, val):
self._isstatic = val
def get_config_bits(self):
attrs = vars(self)
cfgbits = {}
for k, v in attrs.items():
if isinstance(v, SignalType) and v.config and not v.driven:
cfgbits[k] = v.initial_value
return cfgbits
@abstractclassmethod
def default_assign(self):
raise NotImplemented
def get_register_file(self):
""" get the register-file for this control-status object"""
# @todo: this function currently lives in memmap.regfile
# @todo: return build_register_file(self)
return None
@abstractclassmethod
def get_generators(self):
""" get any hardware logic associated with the cso"""
return None
def assign_config(sig, val):
"""
Arguments:
sig (Signal): The signals to be assigned to a constant value
val (int): The constant value
"""
keep = Signal(bool(0))
keep.driven = 'wire'
@always_comb
def beh_assign():
sig.next = val if keep else val
return beh_assign
|
Python
| 0.99992 |
@@ -156,16 +156,31 @@
tusBase(
+object):%0A __
metaclas
@@ -184,18 +184,21 @@
lass
-=
+__ =
ABCMeta
-):
+%0A
%0A
@@ -230,490 +230,1573 @@
-self._isstatic = False%0A%0A @property%0A def isstatic(self):%0A return self._isstatic%0A%0A @isstatic.setter%0A def isstatic(self, val):%0A self._isstatic = val%0A%0A def get_config_bits(self):%0A attrs = vars(self)%0A cfgbits = %7B%7D%0A for k, v in attrs.items():%0A if isinstance(v, SignalType) and v.config and not v.driven:%0A cfgbits%5Bk%5D = v.initial_value%0A return cfgbits%0A%0A @abstractclassmethod%0A def default_assign(self):
+%22%22%22 Base class for control and status classes%0A Many complex digital block have control and status interfaces.%0A The base class is the base class for the specific control and%0A status objects (typically %60%60ControlStatus%60%60) in a block, the%0A control-status-objects (CSO) can be used to dynamically%0A interact with the block from other blocks, statically configure,%0A or assign to a register-file that can be accessed from a%0A memory-mapped bus.%0A %22%22%22%0A self._isstatic = False%0A%0A @property%0A def isstatic(self):%0A return self._isstatic%0A%0A @isstatic.setter%0A def isstatic(self, val):%0A self._isstatic = val%0A%0A def get_config_bits(self):%0A attrs = vars(self)%0A cfgbits = %7B%7D%0A for k, v in attrs.items():%0A if isinstance(v, SignalType) and v.config and not v.driven:%0A cfgbits%5Bk%5D = v.initial_value%0A return cfgbits%0A%0A @abstractclassmethod%0A def default_assign(self):%0A %22%22%22 A myhdl.block that assigns the control-status defaults.%0A For certain synthesis tools the static values of the signals%0A need to be assigned. This will return generators to keep%0A the default signals. If the synthesis tool supports initial%0A values, initial values should be used otherwise this can be%0A used to assign a static value to a signal. Note, the synthesis%0A tool will generate warnings that the signal is stuck at a%0A value - this is desired.%0A %0A Returns:%0A myhdl generators%0A %22%22%22
%0A
|
682b52e3f5b1f1de5009e7fc7fac95f453dbe631
|
Enable more content in header/footer
|
rinohlib/templates/manual.py
|
rinohlib/templates/manual.py
|
from rinoh.document import Document, DocumentPart, Page, PORTRAIT
from rinoh.dimension import PT, CM
from rinoh.layout import Container, FootnoteContainer, Chain
from rinoh.paper import A4
from rinoh.structure import Section, Heading, TableOfContents, Header, Footer
# page definition
# ----------------------------------------------------------------------------
class SimplePage(Page):
topmargin = bottommargin = 3*CM
leftmargin = rightmargin = 2*CM
def __init__(self, chain, paper, orientation, header_footer=True):
super().__init__(chain.document, paper, orientation)
body_width = self.width - (self.leftmargin + self.rightmargin)
body_height = self.height - (self.topmargin + self.bottommargin)
self.body = Container('body', self, self.leftmargin, self.topmargin,
body_width, body_height)
self.footnote_space = FootnoteContainer('footnotes', self.body, 0*PT,
body_height)
self.content = Container('content', self.body, 0*PT, 0*PT,
bottom=self.footnote_space.top,
chain=chain)
self.content._footnote_space = self.footnote_space
if header_footer:
self.header = Container('header', self, self.leftmargin,
self.topmargin / 2, body_width, 12*PT)
footer_vpos = self.topmargin + body_height + self.bottommargin / 2
self.footer = Container('footer', self, self.leftmargin,
footer_vpos, body_width, 12*PT)
header_text = chain.document.options['header_text']
footer_text = chain.document.options['footer_text']
self.header.append_flowable(Header(header_text))
self.footer.append_flowable(Footer(footer_text))
# document parts
# ----------------------------------------------------------------------------
# class TitlePart(DocumentPart)
class ManualPart(DocumentPart):
def __init__(self, document):
super().__init__(document)
self.chain = Chain(document)
def init(self):
self.new_page([self.chain])
def new_page(self, chains):
assert (len(chains) == 1)
page = SimplePage(next(iter(chains)),
self.document.options['page_size'],
self.document.options['page_orientation'],
header_footer=self.header_footer)
self.page_count += 1
self.add_page(page, self.page_count)
return page.content
class TableOfContentsPart(ManualPart):
header_footer = False
def __init__(self, document):
super().__init__(document)
self.chain << Section([Heading('Table of Contents', style='unnumbered'),
TableOfContents()])
class ContentsPart(ManualPart):
header_footer = True
def __init__(self, document, content_tree):
super().__init__(document)
for child in content_tree.getchildren():
self.chain << child.flowable()
# main document
# ----------------------------------------------------------------------------
class Manual(Document):
def __init__(self, rinoh_tree, stylesheet, options=None, backend=None,
title=None):
super().__init__(stylesheet, backend=backend, title=title)
self.options = options or ManualOptions()
self.add_part(TableOfContentsPart(self))
self.add_part(ContentsPart(self, rinoh_tree))
class ManualOptions(dict):
options = {'page_size': A4,
'page_orientation': PORTRAIT,
'header_text': None,
'footer_text': None}
def __init__(self, **options):
for name, value in options.items():
if name not in self.options:
raise ValueError("Unknown option '{}'".format(name))
self[name] = value
def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
return self.options[key]
|
Python
| 0 |
@@ -156,17 +156,69 @@
r, Chain
+, %5C%0A UpExpandingContainer, DownExpandingContainer
%0A
-
from rin
@@ -512,16 +512,52 @@
= 2*CM%0A%0A
+ header_footer_distance = 14*PT%0A%0A
def
@@ -1361,16 +1361,88 @@
footer:%0A
+ header_bottom = self.body.top - self.header_footer_distance%0A
@@ -1455,24 +1455,35 @@
lf.header =
+UpExpanding
Container('h
@@ -1499,82 +1499,200 @@
elf,
- self.leftmargin,%0A self.topmargin / 2,
+%0A left=self.leftmargin,%0A bottom=header_bottom,%0A width=
body
@@ -1689,39 +1689,32 @@
width=body_width
-, 12*PT
)%0A fo
@@ -1734,55 +1734,49 @@
elf.
-topmargin + body_height + self.bottommargin / 2
+body.bottom + self.header_footer_distance
%0A
@@ -1798,16 +1798,29 @@
ooter =
+DownExpanding
Containe
@@ -1840,75 +1840,201 @@
elf,
- self.leftmargin,%0A footer_vpos,
+%0A left=self.leftmargin,%0A top=footer_vpos,%0A width=
body
@@ -2043,15 +2043,8 @@
idth
-, 12*PT
)%0A
|
c0ab9b755b4906129988348b2247452b6dfc157f
|
Add a module to set the "display name" of a dedicated server
|
plugins/modules/dedicated_server_display_name.py
|
plugins/modules/dedicated_server_display_name.py
|
Python
| 0 |
@@ -0,0 +1,2408 @@
+#!/usr/bin/python%0A# -*- coding: utf-8 -*-%0A%0Afrom __future__ import (absolute_import, division, print_function)%0A%0Afrom ansible.module_utils.basic import AnsibleModule%0A%0A__metaclass__ = type%0A%0ADOCUMENTATION = '''%0A---%0Amodule: dedicated_server_display_name%0Ashort_description: Modify the server display name in ovh manager%0Adescription:%0A - Modify the server display name in ovh manager, to help you find your server with your own naming%0Aauthor: Synthesio SRE Team%0Arequirements:%0A - ovh %3E= 0.5.0%0Aoptions:%0A service_name:%0A required: true%0A description: The service name%0A display_name:%0A required: true%0A description: The display name to set%0A%0A'''%0A%0AEXAMPLES = '''%0Asynthesio.ovh.display_name%0A service_name: %22%7B%7B ovhname %7D%7D%22%0A display_name: %22%7B%7B ansible_hostname %7D%7D%22%0Adelegate_to: localhost%0A'''%0A%0ARETURN = ''' # '''%0A%0Afrom ansible_collections.synthesio.ovh.plugins.module_utils.ovh import ovh_api_connect, ovh_argument_spec%0A%0Atry:%0A from ovh.exceptions import APIError%0A HAS_OVH = True%0Aexcept ImportError:%0A HAS_OVH = False%0A%0A%0Adef run_module():%0A module_args = ovh_argument_spec()%0A module_args.update(dict(%0A display_name=dict(required=True),%0A service_name=dict(required=True)%0A ))%0A%0A module = AnsibleModule(%0A argument_spec=module_args,%0A supports_check_mode=True%0A )%0A client = ovh_api_connect(module)%0A%0A display_name = module.params%5B'display_name'%5D%0A service_name = module.params%5B'service_name'%5D%0A%0A if module.check_mode:%0A module.exit_json(msg=%22display_name has been set to %7B%7D ! - (dry run mode)%22.format(display_name), changed=True)%0A%0A try:%0A result = client.get('/dedicated/server/%25s/serviceInfos' %25 service_name)%0A except APIError as api_error:%0A return module.fail_json(msg=%22Failed to call OVH API: %7B0%7D%22.format(api_error))%0A%0A service_id = result%5B%22serviceId%22%5D%0A resource = %7B%0A %22resource%22: %7B%0A 'displayName': display_name,%0A 'name': service_name%7D%7D%0A try:%0A client.put(%0A '/service/%25s' %25 service_id,%0A **resource%0A )%0A module.exit_json(%0A msg=%22displayName succesfully set to %7B%7D for %7B%7D !%22.format(display_name, service_name),%0A changed=True)%0A except APIError as api_error:%0A return module.fail_json(msg=%22Failed to call OVH API: %7B0%7D%22.format(api_error))%0A%0A%0Adef main():%0A run_module()%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
ffdee2f18d5e32c2d0b4f4eb0cebe8b63ee555f7
|
Document tools/mac/dump-static-initializers.py more.
|
tools/mac/dump-static-initializers.py
|
tools/mac/dump-static-initializers.py
|
#!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import re
import subprocess
import sys
# Matches for example:
# [ 1] 000001ca 64 (N_SO ) 00 0000 0000000000000000 'test.cc'
dsymutil_file_re = re.compile("N_SO.*'([^']*)'")
# Matches for example:
# [ 2] 000001d2 66 (N_OSO ) 00 0001 000000004ed856a0 '/Volumes/MacintoshHD2/src/chrome-git/src/test.o'
dsymutil_o_file_re = re.compile("N_OSO.*'([^']*)'")
# Matches for example:
# [ 8] 00000233 24 (N_FUN ) 01 0000 0000000000001b40 '__GLOBAL__I_s'
# [185989] 00dc69ef 26 (N_STSYM ) 02 0000 00000000022e2290 '__GLOBAL__I_a'
dsymutil_re = re.compile(r"(?:N_FUN|N_STSYM).*\s[0-9a-f]*\s'__GLOBAL__I_")
def ParseDsymutil(binary):
"""Given a binary, prints source and object filenames for files with
static initializers.
"""
child = subprocess.Popen(['dsymutil', '-s', binary], stdout=subprocess.PIPE)
for line in child.stdout:
file_match = dsymutil_file_re.search(line)
if file_match:
current_filename = file_match.group(1)
else:
o_file_match = dsymutil_o_file_re.search(line)
if o_file_match:
current_o_filename = o_file_match.group(1)
else:
match = dsymutil_re.search(line)
if match:
print current_filename
print current_o_filename
print
def main():
parser = optparse.OptionParser(usage='%prog filename')
opts, args = parser.parse_args()
if len(args) != 1:
parser.error('missing filename argument')
return 1
binary = args[0]
ParseDsymutil(binary)
return 0
if '__main__' == __name__:
sys.exit(main())
|
Python
| 0.000002 |
@@ -182,16 +182,330 @@
file.%0A%0A
+%22%22%22%0ADumps a list of files with static initializers. Use with release builds.%0A%0AUsage:%0A tools/mac/dump-static-initializers.py out/Release/Chromium%5C Framework.framework.dSYM/Contents/Resources/DWARF/Chromium%5C Framework %0A%0ADo NOT use mac_strip_release=0 or component=shared_library if you want to use%0Athis script.%0A%22%22%22%0A
%0Aimport
|
8fbc5877fa97b6b8df621ff7afe7515b501660fc
|
Convert string to camel case
|
LeetCode/ConvertStringToCamelCase.py
|
LeetCode/ConvertStringToCamelCase.py
|
Python
| 0.999999 |
@@ -0,0 +1,246 @@
+def to_camel_case(text):%0A if len(text) %3C 2:%0A return text%0A capped_camel = %22%22.join(%5Bword.title() for word in text.replace('-','_').split('_')%5D)%0A return capped_camel if text%5B0%5D.isupper() else capped_camel%5B0%5D.lower()+capped_camel%5B1:%5D%0A
|
|
98abb69d2c5cd41e9cdf9decc1180fe35112bc28
|
Add initial base for the feed handler
|
backend/feed_daemon.py
|
backend/feed_daemon.py
|
Python
| 0 |
@@ -0,0 +1,3073 @@
+import feedparser%0Aimport psycopg2%0Aimport sys%0Aimport configparser%0Aimport logging%0A%0Aclass FeedHandler():%0A def __init__(self):%0A self.config = configparser.ConfigParser(interpolation=None)%0A self.config.read(('config.ini',))%0A %0A logging.basicConfig(format='%25(asctime)s %25(levelname)s %25(message)s', level=logging.INFO)%0A %0A self.con = None%0A%0A try:%0A self.con = psycopg2.connect(%0A database=self.config.get('database', 'database'), %0A user=self.config.get('database', 'user'),%0A password=self.config.get('database', 'password'),%0A host=self.config.get('database', 'host'), %0A async=False)%0A except psycopg2.OperationalError as e:%0A logging.error('Database: %7B%7D'.format(str(e).split('%5Cn')%5B0%5D))%0A%0A def update_feed(self, feed_id, feed_url=None):%0A if feed_url == None:%0A cur = self.con.cursor()%0A cur.execute('SELECT url FROM lysr_feed WHERE id=%25s', (feed_id,))%0A self.con.commit()%0A feed_url = cur.fetchone()%5B0%5D%0A%0A logging.info('Updating feed %7B%7D: %7B%7D'.format(feed_id, feed_url))%0A%0A feed = feedparser.parse(feed_url)%0A %0A new_entries = 0%0A if feed.status is 200:%0A try:%0A cur = self.con.cursor()%0A %0A for entry in feed.entries:%0A # Bad HTML is removed by default :D%0A cur.execute('SELECT id FROM lysr_feed_entry WHERE feed = %25s AND guid = %25s', (feed_id, entry.link))%0A self.con.commit()%0A %0A if cur.rowcount is 0:%0A new_entries += 1%0A cur.execute('INSERT INTO lysr_feed_entry (feed, guid, content, title) VALUES (%25s, %25s, %25s, %25s)',%0A (feed_id, entry.link, entry.description, entry.title))%0A self.con.commit()%0A%0A %0A logging.info('Fetched feed %7B%7D, %7B%7D new entries found'.format(feed_id, new_entries))%0A %0A except Exception as e:%0A logging.error('Database: %7B%7D'.format(str(e).split('%5Cn')%5B0%5D))%0A else:%0A logging.info('Failed to fetch feed %7B%7D, status %7B%7D'.format(feed_id, feed.status))%0A%0A cur = self.con.cursor()%0A%0A cur.execute('UPDATE lysr_feed SET last_check=NOW() WHERE id=%25s', (feed_id,))%0A self.con.commit()%0A%0A if new_entries:%0A cur.execute('UPDATE lysr_feed SET last_update=NOW() WHERE id=%25s', (feed_id,))%0A else:%0A cur.execute('UPDATE lysr_feed SET update_interval=2*update_interval WHERE id=%25s', (feed_id,))%0A self.con.commit()%0A%0A%0A def parse_feeds(self):%0A cur = self.con.cursor()%0A cur.execute('SELECT id, url FROM lysr_feed WHERE NOW() %3E last_check + update_interval')%0A self.con.commit()%0A%0A for feed in cur:%0A self.update_feed(*feed)%0A%0A%0A%0Adef main(args):%0A fh = FeedHandler()%0A #fh.update_feed(1)%0A fh.parse_feeds()%0A%0Aif __name__ == '__main__':%0A main(sys.argv)%0A%0A
|
|
c684ab17fc83242ee32db4b4c4bf57a7798acae4
|
Add ordering prefix
|
examples/00_empty_window.py
|
examples/00_empty_window.py
|
Python
| 0.000114 |
@@ -0,0 +1,306 @@
+import ModernGL%0Afrom ModernGL.ext.examples import run_example%0A%0A%0Aclass Example:%0A def __init__(self, wnd):%0A self.wnd = wnd%0A self.ctx = ModernGL.create_context()%0A%0A def render(self):%0A self.ctx.viewport = self.wnd.viewport%0A self.ctx.clear(0.2, 0.4, 0.7)%0A%0A%0Arun_example(Example)%0A
|
|
c660de10b58b985273675396a214a3f4bf968a20
|
Fix credentials initialization.
|
tools/telemetry/telemetry/core/backends/chrome/cros_test_case.py
|
tools/telemetry/telemetry/core/backends/chrome/cros_test_case.py
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import unittest
from telemetry.core import browser_finder
from telemetry.core import extension_to_load
from telemetry.core import util
from telemetry.core.backends.chrome import cros_interface
from telemetry.unittest import options_for_unittests
class CrOSTestCase(unittest.TestCase):
def setUp(self):
options = options_for_unittests.GetCopy()
self._cri = cros_interface.CrOSInterface(options.cros_remote,
options.cros_ssh_identity)
self._is_guest = options.browser_type == 'cros-chrome-guest'
self._username = options.browser_options.username
self._password = options.browser_options.password
self._load_extension = None
def _CreateBrowser(self, autotest_ext=False, auto_login=True,
gaia_login=False, username=None, password=None):
"""Finds and creates a browser for tests. if autotest_ext is True,
also loads the autotest extension"""
options = options_for_unittests.GetCopy()
if autotest_ext:
extension_path = os.path.join(util.GetUnittestDataDir(), 'autotest_ext')
assert os.path.isdir(extension_path)
self._load_extension = extension_to_load.ExtensionToLoad(
path=extension_path,
browser_type=options.browser_type,
is_component=True)
options.extensions_to_load = [self._load_extension]
browser_to_create = browser_finder.FindBrowser(options)
self.assertTrue(browser_to_create)
options.browser_options.create_browser_with_oobe = True
options.browser_options.auto_login = auto_login
options.browser_options.gaia_login = gaia_login
if username is not None:
options.browser_options.username = username
if password is not None:
options.browser_options.password = password
return browser_to_create.Create()
def _GetAutotestExtension(self, browser):
"""Returns the autotest extension instance"""
extension = browser.extensions[self._load_extension]
self.assertTrue(extension)
return extension
def _IsCryptohomeMounted(self):
"""Returns True if cryptohome is mounted. as determined by the cmd
cryptohome --action=is_mounted"""
return self._cri.RunCmdOnDevice(
['/usr/sbin/cryptohome', '--action=is_mounted'])[0].strip() == 'true'
def _GetLoginStatus(self, browser):
extension = self._GetAutotestExtension(browser)
self.assertTrue(extension.EvaluateJavaScript(
"typeof('chrome.autotestPrivate') != 'undefined'"))
extension.ExecuteJavaScript('''
window.__login_status = null;
chrome.autotestPrivate.loginStatus(function(s) {
window.__login_status = s;
});
''')
return util.WaitFor(
lambda: extension.EvaluateJavaScript('window.__login_status'), 10)
def _Credentials(self, credentials_path):
"""Returns credentials from file."""
credentials_path = os.path.join(os.path.dirname(__file__),
credentials_path)
credentials = []
if os.path.isfile(credentials_path):
with open(credentials_path) as f:
credentials = f.read().rstrip().split(':')
return credentials
|
Python
| 0.999998 |
@@ -3147,29 +3147,8 @@
th)%0A
- credentials = %5B%5D%0A
@@ -3232,27 +3232,34 @@
-credentials
+username, password
= f.rea
@@ -3282,16 +3282,20 @@
it(':')%0A
+
retu
@@ -3297,20 +3297,53 @@
return
-credentials
+(username, password)%0A return (None, None)
%0A
|
35a683738f00a67b88f26fdc2453a29777fe7f82
|
Add raw outputter
|
salt/output/raw.py
|
salt/output/raw.py
|
Python
| 0.002716 |
@@ -0,0 +1,133 @@
+'''%0APrint out the raw python data, the original outputter%0A'''%0A%0Adef ouput(data):%0A '''%0A Rather basic....%0A '''%0A print(data)%0A
|
|
ad284dfe63b827aaa1ca8d7353e1bf1a54ea4fdf
|
Change arduino board from first example from mega to nano
|
src/arduino_sourcecodes/src/arduino_serial_nodes/connect_arduino_nano1.py
|
src/arduino_sourcecodes/src/arduino_serial_nodes/connect_arduino_nano1.py
|
Python
| 0.000005 |
@@ -0,0 +1,3410 @@
+#!/usr/bin/env python%0A%0A#####################################################################%0A# Software License Agreement (BSD License)%0A#%0A# Copyright (c) 2011, Willow Garage, Inc.%0A# All rights reserved.%0A#%0A# Redistribution and use in source and binary forms, with or without%0A# modification, are permitted provided that the following conditions%0A# are met:%0A#%0A# * Redistributions of source code must retain the above copyright%0A# notice, this list of conditions and the following disclaimer.%0A# * Redistributions in binary form must reproduce the above%0A# copyright notice, this list of conditions and the following%0A# disclaimer in the documentation and/or other materials provided%0A# with the distribution.%0A# * Neither the name of Willow Garage, Inc. nor the names of its%0A# contributors may be used to endorse or promote products derived%0A# from this software without specific prior written permission.%0A#%0A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS%0A# %22AS IS%22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT%0A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS%0A# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE%0A# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,%0A# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,%0A# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;%0A# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER%0A# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT%0A# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN%0A# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE%0A# POSSIBILITY OF SUCH DAMAGE.%0A%0A__author__ = %[email protected] (Michael Ferguson)%22%0A%0Aimport rospy%0Afrom rosserial_python import SerialClient, RosSerialServer%0Aimport multiprocessing%0A%0Aimport sys%0A %0Aif __name__==%22__main__%22:%0A%0A rospy.init_node(%22serial_node_arduinoNano1%22)%0A rospy.loginfo(%22ROS Serial Python Node%22)%0A%0A port_name = rospy.get_param('~port','/dev/ttyUSB0')%0A baud = int(rospy.get_param('~baud','57600'))%0A%0A # TODO: should these really be global?%0A tcp_portnum = int(rospy.get_param('/rosserial_embeddedlinux/tcp_port', '11411'))%0A fork_server = rospy.get_param('/rosserial_embeddedlinux/fork_server', False)%0A%0A # TODO: do we really want command line params in addition to parameter server params?%0A sys.argv = rospy.myargv(argv=sys.argv)%0A if len(sys.argv) == 2 :%0A port_name = sys.argv%5B1%5D%0A if len(sys.argv) == 3 :%0A tcp_portnum = int(sys.argv%5B2%5D)%0A %0A if port_name == %22tcp%22 :%0A server = RosSerialServer(tcp_portnum, fork_server)%0A rospy.loginfo(%22Waiting for socket connections on port %25d%22 %25 tcp_portnum)%0A try:%0A server.listen()%0A except KeyboardInterrupt:%0A rospy.loginfo(%22got keyboard interrupt%22)%0A finally:%0A rospy.loginfo(%22Shutting down%22)%0A for process in multiprocessing.active_children():%0A rospy.loginfo(%22Shutting down process %25r%22, process)%0A process.terminate()%0A process.join()%0A rospy.loginfo(%22All done%22)%0A%0A else : # Use serial port %0A rospy.loginfo(%22Connecting to %25s at %25d baud%22 %25 (port_name,baud) )%0A client = SerialClient(port_name, baud)%0A try:%0A client.run()%0A except KeyboardInterrupt:%0A pass%0A
|
|
821d21b3c98c18bc96e65651266ca69e58cfa2ee
|
test caching on heroku
|
src/viz/views.py
|
src/viz/views.py
|
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.core import serializers
from viz.models import PollingStationResult, PartyResult, PollingStation, Election, Municipality, RegionalElectoralDistrict, District, State, Party, RawData
from django.http import JsonResponse
from django.views.decorators.cache import cache_page
import json
def index(request):
return render(request, 'viz/index_viz.dtl')
def viz(request):
return render(request, 'viz/index_viz.dtl')
def waiting(request):
return render(request, 'viz/index_waiting.dtl')
def computing(request):
return render(request, 'viz/index_computing.dtl')
def test(request):
return render(request, 'viz/index_test.dtl')
def api(request):
return render(request, 'viz/index_api.dtl')
def api_result(request):
data = {}
psr_query = PollingStationResult.objects.select_related().all()
for psr in psr_query:
gkz = str(psr.polling_station.municipality.kennzahl)
data[gkz] = {}
data[gkz]['gemeinde_name'] = psr.polling_station.municipality.name
data[gkz]['gemeinde_code'] = psr.polling_station.municipality.code
data[gkz]['eligible_voters'] = psr.eligible_voters
data[gkz]['votes'] = psr.votes
data[gkz]['valid'] = psr.valid
data[gkz]['invalid'] = psr.invalid
data[gkz]['ts'] = psr.ts_result
data[gkz]['election'] = psr.election.short_name
pr_query = psr.partyresult_set.select_related().all()
for pr in pr_query:
data[gkz][str(pr.party)] = pr.votes
return JsonResponse(data, safe=False)
@cache_page(60 * 60) # 60mins
def api_result_nrw13(request):
data = {}
psr_query = PollingStationResult.objects.select_related().filter(election__short_name='nrw13').all()
for psr in psr_query:
gkz = str(psr.polling_station.municipality.kennzahl)
data[gkz] = {}
data[gkz]['gemeinde_name'] = psr.polling_station.municipality.name
data[gkz]['gemeinde_code'] = psr.polling_station.municipality.code
data[gkz]['eligible_voters'] = psr.eligible_voters
data[gkz]['votes'] = psr.votes
data[gkz]['valid'] = psr.valid
data[gkz]['invalid'] = psr.invalid
data[gkz]['ts'] = psr.ts_result
data[gkz]['election'] = psr.election.short_name
pr_query = psr.partyresult_set.select_related().all()
for pr in pr_query:
data[gkz][str(pr.party)] = pr.votes
return JsonResponse(data, safe=False)
@cache_page(60 * 60) # 60mins
def api_result_nrw17(request):
data = {}
psr_query = PollingStationResult.objects.select_related().filter(election__short_name='nrw17').all()
for psr in psr_query:
gkz = str(psr.polling_station.municipality.kennzahl)
data[gkz] = {}
data[gkz]['gemeinde_name'] = psr.polling_station.municipality.name
data[gkz]['gemeinde_code'] = psr.polling_station.municipality.code
data[gkz]['eligible_voters'] = psr.eligible_voters
data[gkz]['votes'] = psr.votes
data[gkz]['valid'] = psr.valid
data[gkz]['invalid'] = psr.invalid
data[gkz]['ts'] = psr.ts_result
data[gkz]['election'] = psr.election.short_name
pr_query = psr.partyresult_set.select_related().all()
for pr in pr_query:
data[gkz][str(pr.party)] = pr.votes
return JsonResponse(data, safe=False)
def api_base_election(request):
result = Election.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_base_list(request):
result = List.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_base_municipality(request):
result = Municipality.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_base_pollingstation(request):
result = PollingStation.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_base_red(request):
result = RegionalElectoralDistrict.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_base_district(request):
result = District.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_base_state(request):
result = State.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_base_party(request):
result = Party.objects.values()
data = [entry for entry in result]
return JsonResponse(data, safe=False)
def api_geom(request):
with open('data/setup/municipalities_topojson_999_20170101.json') as data_file:
data = data_file.read()
geom_data = json.loads(data)
return JsonResponse(geom_data, safe=False)
def api_rawdata(request):
result = RawData.objects.values()
rd_data = [entry for entry in result]
return JsonResponse(rd_data, safe=False)
|
Python
| 0 |
@@ -802,24 +802,54 @@
_api.dtl')%0A%0A
+@cache_page(60 * 60) # 60mins%0A
def api_resu
@@ -1575,38 +1575,8 @@
e)%0A%0A
-@cache_page(60 * 60) # 60mins%0A
def
|
07528bd828c28a18f3118481d1cdb9cf1287fd0b
|
Revert "don't track django.wsgi". It is part of the documentation.
|
railroad/sample/django.wsgi
|
railroad/sample/django.wsgi
|
Python
| 0 |
@@ -0,0 +1,1044 @@
+# Copyright 2010 ITA Software, Inc.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Aimport os%0Aimport sys%0A%0A# Describes the location of our Django configuration file. Unless you move the%0A# settings file this default should be fine%0Aos.environ%5B'DJANGO_SETTINGS_MODULE'%5D = 'railroad.settings'%0A%0A# These should correspond to the paths of your railroad and nagcat%0A# installation%0Asys.path.append('/var/lib/nagcat/railroad')%0Asys.path.append('/var/lib/nagcat/python')%0A%0Aimport django.core.handlers.wsgi%0Aapplication = django.core.handlers.wsgi.WSGIHandler()%0A
|
|
2d65862d77338dc503e34f389de1dc3bc553b6cd
|
Add DomainCaseRuleRun to admin site
|
corehq/apps/data_interfaces/admin.py
|
corehq/apps/data_interfaces/admin.py
|
Python
| 0 |
@@ -0,0 +1,532 @@
+from django.contrib import admin%0Afrom corehq.apps.data_interfaces.models import DomainCaseRuleRun%0A%0A%0Aclass DomainCaseRuleRunAdmin(admin.ModelAdmin):%0A%0A list_display = %5B%0A 'domain',%0A 'started_on',%0A 'finished_on',%0A 'status',%0A 'cases_checked',%0A 'num_updates',%0A 'num_closes',%0A 'num_related_updates',%0A 'num_related_closes',%0A %5D%0A%0A search_fields = %5B%0A 'domain',%0A %5D%0A%0A ordering = %5B'-started_on'%5D%0A%0A%0Aadmin.site.register(DomainCaseRuleRun, DomainCaseRuleRunAdmin)%0A
|
|
017f276bb9544578417444c34ce2c04d87bb5852
|
Fix zds #323
|
markdown/extensions/emoticons.py
|
markdown/extensions/emoticons.py
|
# Emoticon extension for python-markdown
# Original version :
# https://gist.github.com/insin/815656/raw/a68516f1ffc03df465730b3ddef6de0a11b7e9a5/mdx_emoticons.py
#
# Patched by cgabard for supporting newer python-markdown version and extend for support multi-extensions
import re
import markdown
from markdown.inlinepatterns import Pattern
from markdown.util import etree
class EmoticonExtension(markdown.Extension):
def __init__ (self, configs):
self.config = {
'EMOTICONS': [{
":)" : "test.png",
}, 'A mapping from emoticon symbols to image names.'],
}
for key, value in configs.iteritems() :
self.config[key][0] = value
def extendMarkdown(self, md, md_globals):
self.md = md
EMOTICON_RE = '(?P<emoticon>%s)' % '|'.join(
[re.escape(emoticon) for emoticon in self.getConfig('EMOTICONS').keys()])
md.inlinePatterns.add('emoticons', EmoticonPattern(EMOTICON_RE, self),">not_strong")
class EmoticonPattern(Pattern):
def __init__ (self, pattern, emoticons):
Pattern.__init__(self, pattern)
self.emoticons = emoticons
def handleMatch(self, m):
emoticon = m.group('emoticon')
el = etree.Element('img')
el.set('src', '%s' % (self.emoticons.getConfig('EMOTICONS')[emoticon],))
el.set('alt', emoticon)
return el
def makeExtension(configs=None) :
return EmoticonExtension(configs=configs)
|
Python
| 0 |
@@ -798,17 +798,28 @@
ON_RE =
-'
+r'(?=(%5E%7C%5CW))
(?P%3Cemot
@@ -826,16 +826,26 @@
icon%3E%25s)
+(?=(%5CW%7C$))
' %25 '%7C'.
|
56ee8843c355ffa56f7c2583d8d524e1ecfd29c3
|
Create __init__.py
|
module/submodule/tests/__init__.py
|
module/submodule/tests/__init__.py
|
Python
| 0.000429 |
@@ -0,0 +1,2 @@
+ %0A
|
|
5e1d5644b2279b31191870b4a8099f3f6f31e851
|
Enable admin for Project, Platform, Dataset
|
ncharts/admin.py
|
ncharts/admin.py
|
Python
| 0 |
@@ -0,0 +1,364 @@
+from django.contrib import admin%0Afrom ncharts.models import Project, Platform, Dataset%0A%0Aclass ProjectAdmin(admin.ModelAdmin):%0A pass%0A%0Aclass PlatformAdmin(admin.ModelAdmin):%0A pass%0A%0Aclass DatasetAdmin(admin.ModelAdmin):%0A pass%0A%0Aadmin.site.register(Project,ProjectAdmin)%0A%0Aadmin.site.register(Platform,PlatformAdmin)%0A%0Aadmin.site.register(Dataset,DatasetAdmin)%0A%0A
|
|
23808a3d65db23163969aeb08adaa29f6403e720
|
Fix a test
|
test/lib/lint/policy/test_abstract_policy.py
|
test/lib/lint/policy/test_abstract_policy.py
|
import unittest
from lib.lint.policy.abstract_policy import AbstractPolicy
class ConcretePolicy(AbstractPolicy):
def __init__(self):
super().__init__()
self.description = 'Found something invalid'
self.reference = 'http://example.com'
self.level = 0
class TestAbstractPolicy(unittest.TestCase):
def test_listen_node_types(self):
policy = AbstractPolicy()
self.assertEqual(policy.listen_node_types(), [])
def test_create_violation_report(self):
pos = {
'col': 3,
'i': 24,
'lnum': 3,
}
env = {'path': 'path/to/file.vim'}
expected_violation = {
'name': 'ConcretePolicy',
'level': 0,
'description': 'Found something invalid',
'reference': 'http://example.com',
'path': 'path/to/file.vim',
'position': pos,
}
policy = ConcretePolicy()
self.assertEqual(
policy.create_violation_report(pos, env),
expected_violation)
if __name__ == '__main__':
unittest.main()
|
Python
| 0.999999 |
@@ -587,32 +587,60 @@
: 3,%0A %7D%0A%0A
+ node = %7B'pos': pos%7D%0A
env = %7B'
@@ -666,16 +666,16 @@
e.vim'%7D%0A
-
%0A
@@ -857,24 +857,110 @@
ample.com',%0A
+ 'position': %7B%0A 'column': 3,%0A 'line': 3,%0A
@@ -1003,23 +1003,9 @@
-'position': pos
+%7D
,%0A
@@ -1116,19 +1116,20 @@
_report(
-pos
+node
, env),%0A
|
e1c6f344e804f0d972dbc685b9492a126d74a7d3
|
Create new management app
|
usingnamespace/management/__init__.py
|
usingnamespace/management/__init__.py
|
Python
| 0.000001 |
@@ -0,0 +1,2824 @@
+from pyramid.config import Configurator%0Afrom pyramid.session import SignedCookieSessionFactory%0Afrom pyramid.settings import asbool%0Afrom pyramid.wsgi import wsgiapp2%0A%0Adefault_settings = (%0A ('route_path', str, '/management'),%0A ('domain', str, ''),%0A)%0A%0A# Stolen from pyramid_debugtoolbar%0Adef parse_settings(settings):%0A parsed = %7B%7D%0A%0A def populate(name, convert, default):%0A name = '%25s%25s' %25 ('usingnamespace.management.', name)%0A value = convert(settings.get(name, default))%0A parsed%5Bname%5D = value%0A for name, convert, default in default_settings:%0A populate(name, convert, default)%0A return parsed%0A%0Adef includeme(config):%0A # Go parse the settings%0A settings = parse_settings(config.registry.settings)%0A%0A # Update the config%0A config.registry.settings.update(settings)%0A%0A # Create the application%0A application = make_application(config.registry.settings, config.registry)%0A%0A # Add the API route%0A route_kw = %7B%7D%0A%0A if config.registry.settings%5B'usingnamespace.management.domain'%5D != '':%0A route_kw%5B'is_management_domain'%5D = config.registry.settings%5B'usingnamespace.management.domain'%5D%0A%0A config.add_route_predicate('is_management_domain', config.maybe_dotted('.predicates.route.Management'))%0A config.add_route('usingnamespace.management',%0A config.registry.settings%5B'usingnamespace.management.route_path'%5D + '/*subpath', %0A **route_kw)%0A%0A # Add the API view%0A config.add_view(wsgiapp2(application), route_name='usingnamespace.management')%0A%0Adef make_application(settings, parent_registry):%0A config = Configurator()%0A config.registry.settings.update(settings)%0A%0A config.registry.parent_registry = parent_registry%0A%0A config.include('pyramid_mako')%0A%0A # Create the session factory, we are using the stock one%0A _session_factory = SignedCookieSessionFactory(%0A settings%5B'pyramid.secret.session'%5D,%0A httponly=True,%0A max_age=864000%0A )%0A%0A config.set_session_factory(_session_factory)%0A%0A config.include('..security')%0A%0A config.add_static_view('static', 'usingnamespace:static/', cache_max_age=3600)%0A%0A def is_management(request):%0A if request.matched_route is not None and request.matched_route.name == 'usingnamespace.management.main':%0A return True%0A return False%0A%0A config.add_request_method(callable=is_management, name='is_management', reify=True)%0A config.add_subscriber_predicate('is_management', config.maybe_dotted('.predicates.subscriber.IsManagement'))%0A%0A config.add_route('management',%0A '/*traverse',%0A factory='.traversal.Root',%0A use_global_views=False,%0A )%0A%0A config.scan('.views')%0A config.scan('.subscribers')%0A%0A return config.make_wsgi_app()%0A%0Adef main(global_config, **settings):%0A pass%0A%0A
|
|
4fbb9ca1b055b040214c82dc307f69793947b800
|
Add handler for syncing wallets to server
|
api/sync_wallet.py
|
api/sync_wallet.py
|
Python
| 0 |
@@ -0,0 +1,1114 @@
+import urlparse%0Aimport os, sys%0Aimport json%0Atools_dir = os.environ.get('TOOLSDIR')%0Alib_path = os.path.abspath(tools_dir)%0Asys.path.append(lib_path)%0Afrom msc_apps import *%0A%0Adata_dir_root = os.environ.get('DATADIR')%0A%0Adef sync_wallet_response(request_dict):%0A if not request_dict.has_key('type'):%0A return (None, 'No field type in response dict '+str(request_dict))%0A print request_dict %0A req_type = request_dict%5B'type'%5D%5B0%5D.upper() %0A if req_type == %22SYNCWALLET%22:%0A response_data = syncWallets(request_dict%5B'masterWallets'%5D%5B0%5D)%0A else:%0A return (None, req_type + ' is not supported')%0A%0A response = %7B 'status': 'OK', 'data': response_data %7D%0A return (json.dumps(response), None)%0A%0A%0Adef syncWallets(master_wallets_json):%0A master_wallets = json.loads(master_wallets_json)%0A print master_wallets%0A%0A for wallet in master_wallets:%0A uuid = wallet%5B'uuid'%5D%0A filename = data_dir_root + '/wallets/' + uuid + '.json'%0A with open(filename, 'w') as f:%0A json.dump(wallet, f)%0A%0A return %22OK%22%0A%0Adef sync_wallet_handler(environ, start_response):%0A return general_handler(environ, start_response, sync_wallet_response)%0A%0A
|
|
eefa26090a4ff8fc23908afa83c87c2d54568929
|
add pager duty sample alert plugin, closes #249
|
alerts/plugins/pagerDutyTriggerEvent.py
|
alerts/plugins/pagerDutyTriggerEvent.py
|
Python
| 0 |
@@ -0,0 +1,2607 @@
+# This Source Code Form is subject to the terms of the Mozilla Public%0A# License, v. 2.0. If a copy of the MPL was not distributed with this%0A# file, You can obtain one at http://mozilla.org/MPL/2.0/.%0A# Copyright (c) 2014 Mozilla Corporation%0A#%0A# Contributors:%0A# Jeff Bryner [email protected]%0A%0Aimport requests%0Aimport json%0Aimport os%0Aimport sys%0Afrom configlib import getConfig, OptionParser%0A%0A%0Aclass message(object):%0A def __init__(self):%0A '''%0A takes an incoming alert%0A and uses it to trigger an event using%0A the pager duty event api%0A '''%0A %0A self.registration = %5B'bro'%5D%0A self.priority = 2%0A%0A # set my own conf file%0A # relative path to the rest index.py file%0A self.configfile = './plugins/pagerDutyTriggerEvent.conf'%0A self.options = None%0A if os.path.exists(self.configfile):%0A sys.stdout.write('found conf file %7B0%7D%5Cn'.format(self.configfile))%0A self.initConfiguration()%0A %0A def initConfiguration(self):%0A myparser = OptionParser()%0A # setup self.options by sending empty list %5B%5D to parse_args%0A (self.options, args) = myparser.parse_args(%5B%5D)%0A %0A # fill self.options with plugin-specific options%0A # change this to your default zone for when it's not specified%0A self.options.serviceKey = getConfig('serviceKey', 'APIKEYHERE', self.configfile)%0A %0A%0A def onMessage(self, message):%0A # here is where you do something with the incoming alert message%0A if 'summary' in message.keys() :%0A print message%5B'summary'%5D%0A%0A headers = %7B%0A 'Content-type': 'application/json',%0A %7D%0A payload = json.dumps(%7B%0A %22service_key%22: %22%7B0%7D%22.format(self.options.serviceKey),%0A %22incident_key%22: %22bro%22,%0A %22event_type%22: %22trigger%22,%0A %22description%22: %22%7B0%7D%22.format(message%5B'summary'%5D),%0A %22client%22: %22mozdef%22,%0A %22client_url%22: %22http://mozdef.rocks%22,%0A %22details%22: message%5B'events'%5D%0A %7D)%0A r = requests.post(%0A 'https://events.pagerduty.com/generic/2010-04-15/create_event.json',%0A headers=headers,%0A data=payload,%0A )%0A print r.status_code%0A print r.text %0A # you can modify the message if needed%0A # plugins registered with lower (%3E2) priority%0A # will receive the message and can also act on it%0A # but even if not modified, you must return it%0A return message
|
|
32ea116ff172da3e7f0eeb7d9dea6b9a0378be08
|
Add persistance
|
persistance.py
|
persistance.py
|
Python
| 0.998588 |
@@ -0,0 +1,1594 @@
+import numpy as np%0Aimport os%0A%0Afrom itertools import izip%0A%0A%0AT_FILE = %22t.npy%22%0AC_FILE = %22c.npy%22%0AK_FILE = %22k.npy%22%0AU_FILE = %22u.npy%22%0AFP_FILE = %22fp.npy%22%0AIER_FILE = %22ier.npy%22%0AMSG_FILE = %22msg.txt%22%0A%0Adef saveSplines(directory, splines):%0A%09((t, c, k), u), fp, ier, msg = splines%5B0%5D%0A%09tlst = %5B%5D%0A%09clst = %5B%5D%0A%09klst = %5B%5D%0A%09ulst = %5B%5D%0A%09fplst = %5B%5D%0A%09ierlst = %5B%5D%0A%09msglst = %5B%5D%0A%09for ((t, c, k), u), fp, ier, msg in splines:%0A%09%09tlst.append(t)%0A%09%09clst.append(c)%0A%09%09klst.append(k)%0A%09%09ulst.append(u)%0A%09%09fplst.append(fp)%0A%09%09ierlst.append(ier)%0A%09%09msglst.append(msg + '%5Cn')%0A%09tarr = np.array(tlst)%0A%09carr = np.array(clst)%0A%09karr = np.array(klst)%0A%09uarr = np.array(ulst)%0A%09fparr = np.array(fplst)%0A%09ierarr = np.array(ierlst)%0A%09%0A%09np.save(os.path.join(directory, T_FILE), tarr)%0A%09np.save(os.path.join(directory, C_FILE), carr)%0A%09np.save(os.path.join(directory, K_FILE), karr)%0A%09np.save(os.path.join(directory, U_FILE), uarr)%0A%09np.save(os.path.join(directory, FP_FILE), fparr)%0A%09np.save(os.path.join(directory, IER_FILE), ierarr)%0A%09%0A%09with open(os.path.join(directory, MSG_FILE), 'w') as f:%0A%09%09f.writelines(msglst)%0A%0A%0Adef loadSplines(directory):%0A%09tarr = np.load(os.path.join(directory, T_FILE))%0A%09carr = np.load(os.path.join(directory, C_FILE))%0A%09karr = np.load(os.path.join(directory, K_FILE))%0A%09uarr = np.load(os.path.join(directory, U_FILE))%0A%09fparr = np.load(os.path.join(directory, FP_FILE))%0A%09ierarr = np.load(os.path.join(directory, IER_FILE))%0A%09with open(os.path.join(directory, MSG_FILE)) as f:%0A%09%09msglst = f.readlines()%0A%0A%09return %5B((%5Bt, c, k%5D, u), fp, ier, msg) for t, c, k, u, fp, ier, msg in izip(tarr, carr, karr, uarr, fparr, ierarr, msglst)%5D%0A%0A%0A%0A%0A
|
|
a34318312199e6dab8ca3db92f247f0bda369e17
|
Add missing testcase file
|
exercises/tests/testcase.py
|
exercises/tests/testcase.py
|
Python
| 0.000003 |
@@ -0,0 +1,1060 @@
+# This file is part of Workout Manager.%0A# %0A# Workout Manager is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as published by%0A# the Free Software Foundation, either version 3 of the License, or%0A# (at your option) any later version.%0A# %0A# Workout Manager is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU General Public License for more details.%0A# %0A# You should have received a copy of the GNU Affero General Public License%0A%0Afrom django.test import TestCase%0A%0Aclass WorkoutManagerTestCase(TestCase):%0A fixtures = %5B'tests-user-data', 'test-exercises', %5D%0A %0A def user_login(self, user='admin'):%0A %22%22%22Login the user, by default as 'admin'%0A %22%22%22%0A self.client.login(username=user, password='%25(user)s%25(user)s' %25 %7B'user': user%7D)%0A %0A def user_logout(self):%0A %22%22%22Visit the logout page%0A %22%22%22%0A self.client.logout()%0A
|
|
ac8c78682e77d77be44910c36057e0217477b0a4
|
Test OAI endpoint model
|
tests/test_models/test_oai_endpoint.py
|
tests/test_models/test_oai_endpoint.py
|
Python
| 0 |
@@ -0,0 +1,849 @@
+from django.test import TestCase%0Afrom core.models import OAIEndpoint%0A%0A%0Aclass OAIEndpointTestCase(TestCase):%0A @classmethod%0A def setUpTestData(cls):%0A cls.attributes = %7B%0A 'name': 'Test OAI Endpoint',%0A 'endpoint': 'http://oai.example.com',%0A 'verb': 'ListRecords',%0A 'metadataPrefix': 'mods',%0A 'scope_type': 'setList',%0A 'scope_value': 'someset, anotherset'%0A %7D%0A cls.oai_endpoint = OAIEndpoint(**cls.attributes)%0A cls.oai_endpoint.save()%0A%0A def test_str(self):%0A self.assertEqual('OAI endpoint: Test OAI Endpoint', format(OAIEndpointTestCase.oai_endpoint))%0A%0A def test_as_dict(self):%0A as_dict = OAIEndpointTestCase.oai_endpoint.as_dict()%0A for k, v in OAIEndpointTestCase.attributes.items():%0A self.assertEqual(as_dict%5Bk%5D, v)
|
|
613a0056e12a28232542aaf561831d276868e413
|
Add parametric map generator, good for wrinkles
|
programs/kinbody-creator/openraveMapGenerator.py
|
programs/kinbody-creator/openraveMapGenerator.py
|
Python
| 0 |
@@ -0,0 +1,1854 @@
+#!/usr/bin/python%0A%0A#import lxml.etree%0A#import lxml.builder%0Afrom lxml import etree%0A%0A#E = lxml.builder.ElementMaker()%0A%0A#KINBODY=E.KinBody%0A#BODY=E.Body%0A#GEOM=E.Geom%0A#EXTENTS=E.Extents%0A#TRANSLATION=E.Translation%0A#DIFUSSECOLOR=E.diffuseColor%0A%0A# User variables%0AnX = 3%0AnY = 2%0AboxHeight = 1.0%0A%0Aresolution = 2.0 # Just to make similar to MATLAB %5Bpixel/meter%5D%0AmeterPerPixel = 1 / resolution # %5Bmeter/pixel%5D%0A%0A# Program%0AEz = boxHeight / 2.0 # Box size is actually double the extent%0A%0AEx = meterPerPixel / 2.0%0AEy = meterPerPixel / 2.0%0A%0AKinBody = etree.Element(%22KinBody%22, name=%22map%22)%0A%0Afor iY in range(nY):%0A # print %22iY:%22,iY%0A for iX in range(nX):%0A # print %22* iX:%22,iX%0A #-- Add E___ to each to force begin at 0,0,0 (centered by default)%0A x = Ex + iX*meterPerPixel%0A y = Ey + iY*meterPerPixel%0A z = Ez # Add this to raise to floor level (centered by default)%0A Number = iX + (iY * nX)%0A%0A #Create pixel%0A Body = etree.SubElement(KinBody, %22Body%22, name=%22square%22+str(Number), type=%22static%22)%0A Geom = etree.SubElement(Body, %22Geom%22, type=%22box%22)%0A Extents = etree.SubElement(Geom, %22Extents%22).text= str(Ex)+%22 %22+ str(Ey)+%22 %22+str(Ez)%0A Translation = etree.SubElement(Geom, %22Translation%22).text= str(x)+%22 %22+str(y)+%22 %22+str(z)%0A DifusseColor = etree.SubElement(Geom, %22diffuseColor%22).text= %22.5 .5 .5%22%0A%0A'''%0Athe_doc = KINBODY(%0A BODY(%0A GEOM(%0A EXTENTS(%220.001 0.115 0.065%22),%0A TRANSLATION(%220.6 %22+ %22-0.8 0.32%22),%0A DIFUSSECOLOR(%22.5 .5 .5%22),%0A type=%22box%22,%0A ),%0A name=%22square%22+str(i), type=%22static%22%0A ),%0A name=%22wall%22,%0A )%0A'''%0A%0AmyStr = etree.tostring(KinBody, pretty_print=True)%0A%0AoutFile = open('map.kinbody.xml', 'w')%0AoutFile.write(myStr)%0AoutFile.close()%0A
|
|
668c28fd55daa93e0024e14e7137f78919e93e2c
|
Add python client script
|
docs/basement_weather.py
|
docs/basement_weather.py
|
Python
| 0.000003 |
@@ -0,0 +1,1073 @@
+#!/usr/bin/python%0Aimport sys%0Aimport commands%0Aimport Adafruit_DHT%0Aimport twitter%0Aimport requests%0Aimport json%0A%0Adate = commands.getoutput('TZ=%22:Canada/Atlantic%22 date')%0A%0A#Get temp and humidity%0Ahumidity, temperature = Adafruit_DHT.read_retry(11, 4)%0Amessage = 'Temp: %7B0:0.1f%7D C Humidity: %7B1:0.1f%7D %25'.format(temperature, humidity)%0A%0A%0A#send to basementweather API%0Aurl = 'https://basementweather.herokuapp.com/readings.json'%0Apayload = %7B'temperature': '%7B0:0.1f%7D'.format(temperature), 'humidity': '%7B0:0.1f%7D'.format(humidity)%7D%0Aheaders = %7B'content-type': 'application/json'%7D%0Ar = requests.post(url, data=json.dumps(payload), headers=headers)%0A%0A#send to twitter%0Aapi = twitter.Api(consumer_key=%22QeT4mgIqGqAi6y7sKEgkcR8HQ%22,%0A consumer_secret=%22zM2dFpIk3YojKBdlZOwTCC82tEP3RxffLZG6MQJQwTBeckG8Pk%22,%0A access_token_key=%22771330006068830209-4QTn99ThbM6V2DT0hxlNymQOLykbmMM%22,%0A access_token_secret=%22akoFlkoNgov5aDJrmkCJTtSqQgvs2Q2Phl0rjVgVjh9Zi%22)%0A%0Astatus = api.PostUpdate(message+%22 %22+date)%0Aprint %22%25s just posted: %25s%22 %25 (status.user.name, status.text)
|
|
5a221296e9e7cc59e4fe4c85b178db06c1376f13
|
Add product streamfield migrations
|
demo/apps/catalogue/migrations/0012_auto_20160617_1115.py
|
demo/apps/catalogue/migrations/0012_auto_20160617_1115.py
|
Python
| 0 |
@@ -0,0 +1,940 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Aimport wagtail.wagtailcore.fields%0Aimport wagtail.wagtailcore.blocks%0Aimport wagtail.wagtailimages.blocks%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('catalogue', '0011_auto_20160616_1335'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='category',%0A name='body',%0A field=wagtail.wagtailcore.fields.StreamField(%5B(b'heading', wagtail.wagtailcore.blocks.CharBlock(classname=b'full title')), (b'paragraph', wagtail.wagtailcore.blocks.RichTextBlock()), (b'image', wagtail.wagtailimages.blocks.ImageChooserBlock())%5D),%0A preserve_default=False,%0A ),%0A migrations.AlterField(%0A model_name='category',%0A name='name',%0A field=models.CharField(max_length=255, verbose_name='Name', db_index=True),%0A ),%0A %5D%0A
|
|
a9b35aff92c099aa52ce9e1ca1cb0df169a54ef5
|
Add author to header.
|
publisher/writer.py
|
publisher/writer.py
|
__all__ = ['writer']
import docutils.core as dc
import docutils.writers
from docutils import nodes
from docutils.writers.latex2e import (Writer, LaTeXTranslator,
PreambleCmds)
class Translator(LaTeXTranslator):
def __init__(self, *args, **kwargs):
LaTeXTranslator.__init__(self, *args, **kwargs)
# Handle author declarations
current_field = ''
def visit_docinfo(self, node):
pass
def depart_docinfo(self, node):
pass
def visit_author(self, node):
self.author_stack.append([self.encode(node.astext())])
raise nodes.SkipNode
def depart_author(self, node):
pass
def visit_classifier(self, node):
pass
def depart_classifier(self, node):
pass
def visit_field_name(self, node):
self.current_field = node.astext()
raise nodes.SkipNode
def visit_field_body(self, node):
if self.current_field == 'email':
pass
elif self.current_field == 'institution':
institute = '\\thanks{%s}' % self.encode(node.astext())
self.author_stack[-1].append(institute)
self.current_field = ''
raise nodes.SkipNode
def depart_field_body(self, node):
raise nodes.SkipNode
def depart_document(self, node):
LaTeXTranslator.depart_document(self, node)
doc_title = r'\title{Test 1 2 3}\author{Me}\maketitle'
self.body_pre_docinfo = [doc_title]
writer = Writer()
writer.translator_class = Translator
|
Python
| 0 |
@@ -397,24 +397,99 @@
field = ''%0A%0A
+ author_names = %5B%5D%0A author_institutions = %5B%5D%0A author_emails = %5B%5D%0A%0A
def visi
@@ -633,21 +633,21 @@
hor_
-stack
+names
.append(
%5Bsel
@@ -642,17 +642,16 @@
.append(
-%5B
self.enc
@@ -668,17 +668,16 @@
stext())
-%5D
)%0A
@@ -995,32 +995,75 @@
dy(self, node):%0A
+ text = self.encode(node.astext())%0A%0A
if self.
@@ -1100,20 +1100,47 @@
-pass
+self.author_emails.append(text)
%0A
@@ -1198,114 +1198,44 @@
-institute = '%5C%5Cthanks%7B%25s%7D' %25 self.encode(node.astext())%0A self.author_stack%5B-1%5D.append(institute
+self.author_institutions.append(text
)%0A%0A
@@ -1475,18 +1475,18 @@
title =
-r
'
+%5C
%5Ctitle%7BT
@@ -1499,19 +1499,100 @@
2 3%7D
-%5Cauthor%7BMe%7D
+'%0A doc_title += '%5C%5Cauthor%7B%25s%7D' %25 ', '.join(self.author_names)%0A doc_title += '%5C
%5Cmak
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.