text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
[chromedriver] Add revision info only if available.
This may not be available if building on a branch.
BUG=305371
NOTRY=true
Review URL: https://codereview.chromium.org/26754002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@227842 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright 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.
"""Embeds Chrome user data files in C++ code."""
import optparse
import os
import sys
import chrome_paths
import cpp_source
sys.path.insert(0, os.path.join(chrome_paths.GetSrc(), 'build', 'util'))
import lastchange
def main():
parser = optparse.OptionParser()
parser.add_option('', '--version-file')
parser.add_option(
'', '--directory', type='string', default='.',
help='Path to directory where the cc/h file should be created')
options, args = parser.parse_args()
version = open(options.version_file, 'r').read().strip()
revision = lastchange.FetchVersionInfo(None).revision
if revision:
version += '.' + revision.strip()
global_string_map = {
'kChromeDriverVersion': version
}
cpp_source.WriteSource('version',
'chrome/test/chromedriver',
options.directory, global_string_map)
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
# Copyright 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.
"""Embeds Chrome user data files in C++ code."""
import optparse
import os
import sys
import chrome_paths
import cpp_source
sys.path.insert(0, os.path.join(chrome_paths.GetSrc(), 'build', 'util'))
import lastchange
def main():
parser = optparse.OptionParser()
parser.add_option('', '--version-file')
parser.add_option(
'', '--directory', type='string', default='.',
help='Path to directory where the cc/h file should be created')
options, args = parser.parse_args()
version = open(options.version_file, 'r').read().strip()
revision = lastchange.FetchVersionInfo(None).revision.strip()
global_string_map = {
'kChromeDriverVersion': version + '.' + revision
}
cpp_source.WriteSource('version',
'chrome/test/chromedriver',
options.directory, global_string_map)
if __name__ == '__main__':
sys.exit(main())
|
Fix tests on machine without CUDA | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
if cuda.is_available():
suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim')))
gpus = cuda.list_devices()
if gpus and gpus[0].compute_capability >= (2, 0):
suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv')))
suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy')))
else:
print("skipped CUDA tests because GPU CC < 2.0")
else:
print("skipped CUDA tests")
return suite
| from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim')))
if cuda.is_available():
gpus = cuda.list_devices()
if gpus and gpus[0].compute_capability >= (2, 0):
suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv')))
suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy')))
else:
print("skipped CUDA tests because GPU CC < 2.0")
else:
print("skipped CUDA tests")
return suite
|
Add generic Python 3 trove classifier | from setuptools import setup
setup(
name='tangled.sqlalchemy',
version='0.1a3.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.sqlalchemy',
],
install_requires=[
'tangled>=0.1a5',
'SQLAlchemy',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a5',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled.sqlalchemy',
version='0.1a3.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.sqlalchemy',
],
install_requires=[
'tangled>=0.1a5',
'SQLAlchemy',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a5',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Fix issues with changing passwords | from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveModelBackend(ModelBackend):
def authenticate(email=None, password=None, **kwargs):
"""
Created by LNguyen(
Date: 14Dec2017
Description: Method to handle backend authentication for case insensitive usernames
If the given credentials are valid, return a User object.
"""
UserModel = get_user_model()
if email is None:
email=kwargs.get(UserModel.email)
try:
if (type(email)==str):
user=UserModel.objects.get(email__iexact=email)
else:
user=UserModel.objects.get(email__exact=email)
user.backend = 'profiles.backends.CaseInsensitiveModelBackend'
if user.check_password(password):
return user
except UserModel.DoesNotExist:
# This backend doesn't accept these credentials as arguments. Try the next one.
UserModel().set_password(password)
| from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveModelBackend(ModelBackend):
def authenticate(email=None, password=None, **kwargs):
"""
Created by LNguyen(
Date: 14Dec2017
Description: Method to handle backend authentication for case insensitive usernames
If the given credentials are valid, return a User object.
"""
UserModel = get_user_model()
if email is None:
email=kwargs.get(UserModel.email)
try:
user=UserModel.objects.get(email__iexact=email)
user.backend = 'profiles.backends.CaseInsensitiveModelBackend'
if user.check_password(password):
return user
except UserModel.DoesNotExist:
# This backend doesn't accept these credentials as arguments. Try the next one.
UserModel().set_password(password)
|
[python] Add some paths where to find test binary
Adds /usr/lib/debug early to list, as some systems (debian) have unstripped libs in there
Adds /lib/i386-linux-gnu for systems that does multiarch (debian)
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@153174 91177308-0d34-0410-b5e6-96231b3b80d8 | import os.path
import unittest
POSSIBLE_TEST_BINARIES = [
'libreadline.so.5',
'libreadline.so.6',
]
POSSIBLE_TEST_BINARY_PATHS = [
'/usr/lib/debug',
'/lib',
'/usr/lib',
'/usr/local/lib',
'/lib/i386-linux-gnu',
]
class TestBase(unittest.TestCase):
def get_test_binary(self):
"""Helper to obtain a test binary for object file testing.
FIXME Support additional, highly-likely targets or create one
ourselves.
"""
for d in POSSIBLE_TEST_BINARY_PATHS:
for lib in POSSIBLE_TEST_BINARIES:
path = os.path.join(d, lib)
if os.path.exists(path):
return path
raise Exception('No suitable test binaries available!')
get_test_binary.__test__ = False
| import os.path
import unittest
POSSIBLE_TEST_BINARIES = [
'libreadline.so.5',
'libreadline.so.6',
]
POSSIBLE_TEST_BINARY_PATHS = [
'/lib',
'/usr/lib',
'/usr/local/lib',
]
class TestBase(unittest.TestCase):
def get_test_binary(self):
"""Helper to obtain a test binary for object file testing.
FIXME Support additional, highly-likely targets or create one
ourselves.
"""
for d in POSSIBLE_TEST_BINARY_PATHS:
for lib in POSSIBLE_TEST_BINARIES:
path = os.path.join(d, lib)
if os.path.exists(path):
return path
raise Exception('No suitable test binaries available!')
get_test_binary.__test__ = False
|
Fix to work in python 3. | """Clone an entire GitHub organization."""
import os.path
import click
from git.repo.base import Repo
from edx_repo_tools.auth import pass_github
@click.command()
@click.option(
'--forks/--no-forks', is_flag=True, default=False,
help="Should forks be included?"
)
@click.option(
'--depth', type=int, default=0,
help="Depth argument for git clone",
)
@click.argument(
'org'
)
@pass_github
def main(hub, forks, depth, org):
for repo in hub.organization(org).iter_repos():
if repo.fork and not forks:
continue
dir_name = repo.name
dir_name = dir_name.lstrip("-") # avoid dirname/option confusion
if os.path.exists(dir_name):
continue
print(repo.full_name)
clone_args = {}
if depth:
clone_args['depth'] = depth
Repo.clone_from(repo.ssh_url, dir_name, **clone_args)
| """Clone an entire GitHub organization."""
import os.path
import click
from git.repo.base import Repo
from edx_repo_tools.auth import pass_github
@click.command()
@click.option(
'--forks/--no-forks', is_flag=True, default=False,
help="Should forks be included?"
)
@click.option(
'--depth', type=int, default=0,
help="Depth argument for git clone",
)
@click.argument(
'org'
)
@pass_github
def main(hub, forks, depth, org):
for repo in hub.organization(org).repositories():
if repo.fork and not forks:
continue
dir_name = repo.name
dir_name = dir_name.lstrip("-") # avoid dirname/option confusion
if os.path.exists(dir_name):
continue
print(repo.full_name)
clone_args = {}
if depth:
clone_args['depth'] = depth
Repo.clone_from(repo.ssh_url, dir_name, **clone_args)
|
Remove another reference to kitkat | package com.kickstarter.ui.views;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import com.kickstarter.KsrApplication;
import com.kickstarter.libs.WebViewJavascriptInterface;
import com.kickstarter.services.KickstarterWebViewClient;
import javax.inject.Inject;
public class KickstarterWebView extends WebView {
@Inject KickstarterWebViewClient client;
public KickstarterWebView(final Context context) {
this(context, null);
}
public KickstarterWebView(final Context context, final AttributeSet attrs) {
this(context, attrs, android.R.attr.webViewStyle);
}
public KickstarterWebView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
((KsrApplication) context.getApplicationContext()).component().inject(this);
setWebViewClient(client);
setWebChromeClient(new WebChromeClient());
getSettings().setJavaScriptEnabled(true);
getSettings().setAllowFileAccess(false);
if (android.os.Build.VERSION.SDK_INT >= 19) {
setWebContentsDebuggingEnabled(true);
}
addJavascriptInterface(new WebViewJavascriptInterface(this.client), "WebViewJavascriptInterface");
}
}
| package com.kickstarter.ui.views;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import com.kickstarter.KsrApplication;
import com.kickstarter.libs.WebViewJavascriptInterface;
import com.kickstarter.services.KickstarterWebViewClient;
import javax.inject.Inject;
public class KickstarterWebView extends WebView {
@Inject KickstarterWebViewClient client;
public KickstarterWebView(final Context context) {
this(context, null);
}
public KickstarterWebView(final Context context, final AttributeSet attrs) {
this(context, attrs, android.R.attr.webViewStyle);
}
public KickstarterWebView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
((KsrApplication) context.getApplicationContext()).component().inject(this);
setWebViewClient(client);
setWebChromeClient(new WebChromeClient());
getSettings().setJavaScriptEnabled(true);
getSettings().setAllowFileAccess(false);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
setWebContentsDebuggingEnabled(true);
}
addJavascriptInterface(new WebViewJavascriptInterface(this.client), "WebViewJavascriptInterface");
}
}
|
Fix tests since we changed imports. | from django.test import TestCase
from .models import AwareModel, NaiveModel
from ..templatetags.boardinghouse import schema_name, is_schema_aware, is_shared_model
from ..models import Schema
class TestTemplateTags(TestCase):
def test_is_schema_aware_filter(self):
self.assertTrue(is_schema_aware(AwareModel()))
self.assertFalse(is_schema_aware(NaiveModel()))
def test_is_shared_model_filter(self):
self.assertFalse(is_shared_model(AwareModel()))
self.assertTrue(is_shared_model(NaiveModel()))
def test_schema_name_filter(self):
Schema.objects.create(name='Schema Name', schema='foo')
self.assertEquals('Schema Name', schema_name('foo'))
self.assertEquals('no schema', schema_name(None))
self.assertEquals('no schema', schema_name(''))
self.assertEquals('no schema', schema_name(False))
self.assertEquals('no schema', schema_name('foobar'))
self.assertEquals('no schema', schema_name('foo_'))
self.assertEquals('no schema', schema_name('foofoo')) | from django.test import TestCase
from .models import AwareModel, NaiveModel
from ..templatetags.boardinghouse import *
class TestTemplateTags(TestCase):
def test_is_schema_aware_filter(self):
self.assertTrue(is_schema_aware(AwareModel()))
self.assertFalse(is_schema_aware(NaiveModel()))
def test_is_shared_model_filter(self):
self.assertFalse(is_shared_model(AwareModel()))
self.assertTrue(is_shared_model(NaiveModel()))
def test_schema_name_filter(self):
Schema.objects.create(name='Schema Name', schema='foo')
self.assertEquals('Schema Name', schema_name('foo'))
self.assertEquals('no schema', schema_name(None))
self.assertEquals('no schema', schema_name(''))
self.assertEquals('no schema', schema_name(False))
self.assertEquals('no schema', schema_name('foobar'))
self.assertEquals('no schema', schema_name('foo_'))
self.assertEquals('no schema', schema_name('foofoo')) |
Allow operation failures to be specialized. | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.tooling.events;
import org.gradle.api.Incubating;
import org.gradle.tooling.Failure;
import java.util.List;
/**
* Provides information about the failed execution of an operation.
*
* @since 2.4
*/
@Incubating
public interface FailureOutcome extends Outcome {
/**
* Returns the exceptions that occurred while running the operation, if any.
*
* @return the exceptions, empty if the operation failed without any exceptions
*/
List<? extends Failure> getFailures();
}
| /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.tooling.events;
import org.gradle.api.Incubating;
import org.gradle.tooling.Failure;
import java.util.List;
/**
* Provides information about the failed execution of an operation.
*
* @since 2.4
*/
@Incubating
public interface FailureOutcome extends Outcome {
/**
* Returns the exceptions that occurred while running the operation, if any.
*
* @return the exceptions, empty if the operation failed without any exceptions
*/
List<Failure> getFailures();
}
|
Fix a regression inserted previously. | #-*- coding:utf-8 -*-
## @package Core
# Core module contains everything required to SQLinject.
# @author Damien "virtualabs" Cauquil <virtualabs@gmail.com>
from context import Context, InbandContext, BlindContext
from dbms import DBMS, allow, dbms
from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector
from forge import SQLForge
from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper
from triggers import StatusTrigger, RegexpTrigger, Trigger
__all__ = [
'InbandContext',
'BlindContext',
'Context',
'DBMS',
'allow',
'GetInjector',
'PostInjector',
'CookieInjector',
'UserAgentInjector',
'CmdInjector',
'SQLForge',
'DatabaseWrapper',
'TableWrapper',
'FieldWrapper',
'Trigger',
'RegexpTrigger',
'StatusTrigger',
]
| #-*- coding:utf-8 -*-
## @package Core
# Core module contains everything required to SQLinject.
# @author Damien "virtualabs" Cauquil <virtualabs@gmail.com>
from context import Context, InbandContext, BlindContext
from dbms import DBMS, allow, dbms
from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector
from forge import SQLForge
from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper
from triggers import StatusTrigger, RegexpTrigger, Trigger
__all__ = [
'InbandContext',
'BlindContext',
'Context',
'DBMS',
'allow',
'plugin',
'GetInjector',
'PostInjector',
'CookieInjector',
'UserAgentInjector',
'CmdInjector',
'SQLForge',
'DatabaseWrapper',
'TableWrapper',
'FieldWrapper',
'Trigger',
'RegexpTrigger',
'StatusTrigger',
]
|
Fix Loop dependency in OrbitControls | import {Vector3} from 'three';
import {Loop} from '../../core/Loop';
import {ThreeOrbitControls} from './lib/ThreeOrbitControls';
export class OrbitModule {
constructor(params = {}) {
this.params = Object.assign({
target: new Vector3(0, 0, 0),
follow: false
}, params);
}
manager(manager) {
this.controls = new ThreeOrbitControls(
manager.get('camera').native,
manager.get('renderer').domElement
);
manager.update({
camera: (camera) => {
this.controls.object = camera.native;
}
});
}
integrate(self) {
const {params, controls} = self;
const updateProcessor = params.follow ? (c) => {
controls.update(c.getDelta());
controls.target.copy(params.target);
} : (c) => {
controls.update(c.getDelta());
};
self.updateLoop = new Loop(updateProcessor).start(this);
controls.target.copy(params.target);
}
}
| import {Vector3} from 'three';
import {ThreeOrbitControls} from './lib/ThreeOrbitControls';
export class OrbitModule {
constructor(params = {}) {
this.params = Object.assign({
target: new Vector3(0, 0, 0),
follow: false
}, params);
}
manager(manager) {
this.controls = new ThreeOrbitControls(
manager.get('camera').native,
manager.get('renderer').domElement
);
manager.update({
camera: (camera) => {
this.controls.object = camera.native;
}
});
}
integrate(self) {
const {params, controls} = self;
const updateProcessor = params.follow ? (c) => {
controls.update(c.getDelta());
controls.target.copy(params.target);
} : (c) => {
controls.update(c.getDelta());
};
self.updateLoop = new WHS.Loop(updateProcessor).start(this);
controls.target.copy(params.target);
}
}
|
Fix some typos in the German locale. Three letter day shorts are not really used in German, it's better to use two letters for dayNamesShort, too. | /**
* RightJS UI Internationalization: German module
*
* Copyright (C) Nikolay V. Nemshilov aka St.
*/
if (self.Calendar) {
$ext(Calendar.i18n, {
Done: 'Erledigt',
Now: 'Jetzt',
Next: 'Nächster Monat',
Prev: 'Vorhergehender Monat',
NextYear: 'Nächstes Jahr',
PrevYear: 'Vorhergehendes Jahr',
dayNames: $w('Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag'),
dayNamesShort: $w('So Mo Di Mi Do Fr Sa'),
dayNamesMin: $w('So Mo Di Mi Do Fr Sa'),
monthNames: $w('Januar Februar März April Mai Juni Juli August September Oktober November Dezember'),
monthNamesShort: $w('Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez')
});
}
if (self.Lightbox) {
$ext(Lightbox.i18n, {
CloseTitle: 'Abschluss',
PrevTitle: 'Vorhergehende Abbildung',
NextTitle: 'Folgende Abbildung'
});
}
| /**
* RightJS UI Internationalization: German module
*
* Copyright (C) Nikolay V. Nemshilov aka St.
*/
if (self.Calendar) {
$ext(Calendar.i18n, {
Done: 'Getan',
Now: 'Jetzt',
Next: 'Nächste Monat',
Prev: 'Vorhergehende Monat',
NextYear: 'Nächste Jahr',
PrevYear: 'Vorhergehende Jahr',
dayNames: $w('Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag'),
dayNamesShort: $w('Son Mon Die Mit Don Fre Sam'),
dayNamesMin: $w('So Mo Di Mi Do Fr Sa'),
monthNames: $w('Januar Februar März April Mai Juni Juli August September Oktober November Dezember'),
monthNamesShort: $w('Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez')
});
}
if (self.Lightbox) {
$ext(Lightbox.i18n, {
CloseTitle: 'Abschluss',
PrevTitle: 'Vorhergehende Abbildung',
NextTitle: 'Folgende Abbildung'
});
}
|
Fix inability dynamically install Pipeline | package jenkins.advancedqueue;
import hudson.model.Job;
import hudson.model.Queue;
import jenkins.advancedqueue.sorter.ItemInfo;
import jenkins.advancedqueue.sorter.QueueItemCache;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution;
class PriorityConfigurationPlaceholderTaskHelper {
boolean isPlaceholderTask(Queue.Task task) {
return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask;
}
PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) {
Job<?, ?> job = (Job<?, ?>) task.getOwnerTask();
ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName());
itemInfo.getPriority();
priorityCallback.setPrioritySelection(itemInfo.getPriority());
return priorityCallback;
}
static boolean isPlaceholderTaskUsed() {
return Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null;
}
}
| package jenkins.advancedqueue;
import hudson.model.Job;
import hudson.model.Queue;
import jenkins.advancedqueue.sorter.ItemInfo;
import jenkins.advancedqueue.sorter.QueueItemCache;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution;
class PriorityConfigurationPlaceholderTaskHelper {
private static boolean placeholderTaskUsed = Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null;
boolean isPlaceholderTask(Queue.Task task) {
return placeholderTaskUsed && task instanceof ExecutorStepExecution.PlaceholderTask;
}
PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) {
Job<?, ?> job = (Job<?, ?>) task.getOwnerTask();
ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName());
itemInfo.getPriority();
priorityCallback.setPrioritySelection(itemInfo.getPriority());
return priorityCallback;
}
static boolean isPlaceholderTaskUsed() {
return placeholderTaskUsed;
}
}
|
Remove name, url and email from comment form | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_comments.models import Comment
from news.models import Blob, BlobInstance
from .models import ThreadedComment
def single_comment(request, id):
comment = get_object_or_404(ThreadedComment, id=id)
variables = RequestContext(request, {'comment': comment})
return render_to_response('comments/single.html', variables)
def comment_posted(request):
if request.GET['c']:
blob_id = request.GET['c']
blob = Blob.objects.get(pk=blob_id)
if blob:
return HttpResponseRedirect( blob.get_absolute_url() )
return HttpResponseRedirect( "/" )
| from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_comments.models import Comment
from news.models import Blob, BlobInstance
from .models import ThreadedComment
def single_comment(request, id):
comment = get_object_or_404(ThreadedComment, id=id)
variables = RequestContext(request, {'comment': comment})
return render_to_response('comments/single.html', variables)
def comment_posted(request):
if request.GET['c']:
comment_id, blob_id = request.GET['c']
comment = Comment.objects.get( pk=comment_id )
blob = Blob.objects.get(pk=blob_id)
if blob:
return HttpResponseRedirect( blob.get_absolute_url() )
return HttpResponseRedirect( "/" )
|
Add new form ID for Analytics setup. | /**
* Analytics Constants.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const STORE_NAME = 'modules/analytics';
// A special Account ID value used for the "Set up a new account" option.
export const ACCOUNT_CREATE = 'account_create';
// A special Property ID value used for the "Set up a new property" option.
export const PROPERTY_CREATE = 'property_create';
// A special Profile ID value used for the "Set up a new profile" option.
export const PROFILE_CREATE = 'profile_create';
// Form ID for the account creation form.
export const FORM_ACCOUNT_CREATE = 'analyticsAccountCreate';
// Form ID for the module setup form.
export const FORM_SETUP = 'analyticsSetup';
// OAuth scope required for provisioning a Google Analytics account.
export const PROVISIONING_SCOPE = 'https://www.googleapis.com/auth/analytics.provision';
export const EDIT_SCOPE = 'https://www.googleapis.com/auth/analytics.edit';
| /**
* Analytics Constants.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const STORE_NAME = 'modules/analytics';
// A special Account ID value used for the "Set up a new account" option.
export const ACCOUNT_CREATE = 'account_create';
// A special Property ID value used for the "Set up a new property" option.
export const PROPERTY_CREATE = 'property_create';
// A special Profile ID value used for the "Set up a new profile" option.
export const PROFILE_CREATE = 'profile_create';
// Form ID for the account creation form.
export const FORM_ACCOUNT_CREATE = 'analyticsAccountCreate';
// OAuth scope required for provisioning a Google Analytics account.
export const PROVISIONING_SCOPE = 'https://www.googleapis.com/auth/analytics.provision';
export const EDIT_SCOPE = 'https://www.googleapis.com/auth/analytics.edit';
|
Add direction to Message listing | from django.contrib import admin
from .models import *
class MessageAdmin(admin.ModelAdmin):
list_display = ('to_phone_number', 'from_phone_number', 'status', 'direction', 'date_sent')
list_display_links = list_display
list_filter = ('status', 'direction', 'date_sent')
date_hierarchy = 'date_sent'
ordering = ('-date_sent', )
class ResponseAdmin(admin.ModelAdmin):
list_display = ('action', 'active', 'body', 'date_updated')
list_display_links = list_display
list_filter = ('action', 'active')
class AccountAdmin(admin.ModelAdmin):
list_display = ('friendly_name', 'owner_account_sid', 'account_type', 'status', 'date_updated')
list_display_links = list_display
admin.site.register(Message, MessageAdmin)
admin.site.register(Response, ResponseAdmin)
admin.site.register(Account, AccountAdmin)
| from django.contrib import admin
from .models import *
class MessageAdmin(admin.ModelAdmin):
list_display = ('to_phone_number', 'from_phone_number', 'status', 'date_sent')
list_display_links = list_display
list_filter = ('status', 'date_sent')
date_hierarchy = 'date_sent'
ordering = ('-date_sent', )
class ResponseAdmin(admin.ModelAdmin):
list_display = ('action', 'active', 'body', 'date_updated')
list_display_links = list_display
list_filter = ('action', 'active')
class AccountAdmin(admin.ModelAdmin):
list_display = ('friendly_name', 'owner_account_sid', 'account_type', 'status', 'date_updated')
list_display_links = list_display
admin.site.register(Message, MessageAdmin)
admin.site.register(Response, ResponseAdmin)
admin.site.register(Account, AccountAdmin)
|
Write to stdout when the http server is listening | #!/usr/bin/env node
var argv = require('minimist')(process.argv.slice(2))
if (argv.help) {
return console.log([
'',
'Usage: kinesalite [--port <port>] [--path <path>] [--ssl] [options]',
'',
'A mock Kinesis http server, optionally backed by LevelDB',
'',
'Options:',
'--help Display this help message and exit',
'--port <port> The port to listen on (default: 4567)',
'--path <path> The path to use for the LevelDB store (in-memory by default)',
'--ssl Enable SSL for the web server (default: false)',
'--createStreamMs <ms> Amount of time streams stay in CREATING state (default: 500)',
'--deleteStreamMs <ms> Amount of time streams stay in DELETING state (default: 500)',
'',
'Report bugs at github.com/mhart/kinesalite/issues',
].join('\n'))
}
var port = argv.port || 4567
require('./index.js')(argv).listen(port, function () {
console.log('Listening on port: %s', port)
})
| #!/usr/bin/env node
var argv = require('minimist')(process.argv.slice(2))
if (argv.help) {
return console.log([
'',
'Usage: kinesalite [--port <port>] [--path <path>] [--ssl] [options]',
'',
'A mock Kinesis http server, optionally backed by LevelDB',
'',
'Options:',
'--help Display this help message and exit',
'--port <port> The port to listen on (default: 4567)',
'--path <path> The path to use for the LevelDB store (in-memory by default)',
'--ssl Enable SSL for the web server (default: false)',
'--createStreamMs <ms> Amount of time streams stay in CREATING state (default: 500)',
'--deleteStreamMs <ms> Amount of time streams stay in DELETING state (default: 500)',
'',
'Report bugs at github.com/mhart/kinesalite/issues',
].join('\n'))
}
require('./index.js')(argv).listen(argv.port || 4567)
|
Add space after copyright symbol in description. | package ru.ming13.muzei.earthview.api;
import android.support.annotation.NonNull;
import android.util.Base64;
import java.util.Locale;
import ru.ming13.muzei.earthview.model.Wallpaper;
import ru.ming13.muzei.earthview.util.DataUris;
import ru.ming13.muzei.earthview.util.Strings;
final class WallpaperOperator
{
public byte[] getBytes(@NonNull Wallpaper wallpaper) {
return Base64.decode(DataUris.getData(wallpaper.getDataUri()), Base64.DEFAULT);
}
public String getTitle(@NonNull Wallpaper wallpaper) {
if (Strings.isEmpty(wallpaper.getArea().getRegion())) {
return wallpaper.getArea().getCountry();
}
return String.format(Locale.US, "%s, %s", wallpaper.getArea().getRegion(), wallpaper.getArea().getCountry());
}
public String getDescription(@NonNull Wallpaper wallpaper) {
return wallpaper.getAttribution().replace("\u00a9", "\u00a9 ");
}
} | package ru.ming13.muzei.earthview.api;
import android.support.annotation.NonNull;
import android.util.Base64;
import java.util.Locale;
import ru.ming13.muzei.earthview.model.Wallpaper;
import ru.ming13.muzei.earthview.util.DataUris;
import ru.ming13.muzei.earthview.util.Strings;
final class WallpaperOperator
{
public byte[] getBytes(@NonNull Wallpaper wallpaper) {
return Base64.decode(DataUris.getData(wallpaper.getDataUri()), Base64.DEFAULT);
}
public String getTitle(@NonNull Wallpaper wallpaper) {
if (Strings.isEmpty(wallpaper.getArea().getRegion())) {
return wallpaper.getArea().getCountry();
}
return String.format(Locale.US, "%s, %s", wallpaper.getArea().getRegion(), wallpaper.getArea().getCountry());
}
public String getDescription(@NonNull Wallpaper wallpaper) {
return wallpaper.getAttribution();
}
} |
Fix definition of web client builder. | package io.pivotal.web.config;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerExchangeFilterFunction;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class BeanConfiguration {
@Bean
public WebClient webClient(WebClient.Builder webClientBuilder, LoadBalancerExchangeFilterFunction eff,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(
clientRegistrationRepository, authorizedClientRepository);
return webClientBuilder
.filter(eff)
.apply(oauth2.oauth2Configuration())
.build();
}
}
| package io.pivotal.web.config;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerExchangeFilterFunction;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class BeanConfiguration {
@Bean
public WebClient webClient(LoadBalancerExchangeFilterFunction eff,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(
clientRegistrationRepository, authorizedClientRepository);
return WebClient.builder()
.filter(eff)
.apply(oauth2.oauth2Configuration())
.build();
}
}
|
Revert "Испорчен тест для проверки Jenkins"
This reverts commit f7ee8b4aa9bd893b6d00fff3f17922bd9673bc63. | package ru.stqa.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class EquationTests {
@Test
public void test0() {
Equation e = new Equation(1,1,1);
Assert.assertEquals(e.rootNumber(), 0);
}
@Test
public void test1() {
Equation e = new Equation(1,2,1);
Assert.assertEquals(e.rootNumber(), 1);
}
@Test
public void test3() {
Equation e = new Equation(1,5,6);
Assert.assertEquals(e.rootNumber(), 2);
}
@Test
public void testLinear() {
Equation e = new Equation(0,1,1);
Assert.assertEquals(e.rootNumber(), 1);
}
@Test
public void testConstant() {
Equation e = new Equation(0,0,1);
Assert.assertEquals(e.rootNumber(), 0);
}
@Test
public void testZero() {
Equation e = new Equation(0,0,0);
Assert.assertEquals(e.rootNumber(), -1);
}
}
| package ru.stqa.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class EquationTests {
@Test
public void test0() {
Equation e = new Equation(1,1,1);
// Assert.assertEquals(e.rootNumber(), 0);
Assert.assertEquals(e.rootNumber(), 1);
}
@Test
public void test1() {
Equation e = new Equation(1,2,1);
Assert.assertEquals(e.rootNumber(), 1);
}
@Test
public void test3() {
Equation e = new Equation(1,5,6);
Assert.assertEquals(e.rootNumber(), 2);
}
@Test
public void testLinear() {
Equation e = new Equation(0,1,1);
Assert.assertEquals(e.rootNumber(), 1);
}
@Test
public void testConstant() {
Equation e = new Equation(0,0,1);
Assert.assertEquals(e.rootNumber(), 0);
}
@Test
public void testZero() {
Equation e = new Equation(0,0,0);
Assert.assertEquals(e.rootNumber(), -1);
}
}
|
Change some permissions and store some more details from Payfast | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var User = require("./user_model");
var Organisation = require("./organisation_model");
var PayfasttokenSchema = new Schema({
token: { type: String, index: true, unique: true },
user_id: { type: ObjectId, ref: 'User', index: true },
organisation_id: { type: ObjectId, ref: 'Organisation', index: true },
card_number: String,
expiration_date: { type: Date, index: true },
name_first: String,
name_last: String,
email: String,
payfast_response: Mixed,
date_created: { type: Date, default: Date.now },
_owner_id: ObjectId,
_deleted: { type: Boolean, default: false, index: true },
});
PayfasttokenSchema.set("_perms", {
admin: "crud",
owner: "rd",
});
module.exports = mongoose.model('Payfasttoken', PayfasttokenSchema); | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var User = require("./user_model");
var Organisation = require("./organisation_model");
var PayfasttokenSchema = new Schema({
token: { type: String, index: true, unique: true },
user_id: { type: ObjectId, ref: 'User', index: true },
organisation_id: { type: ObjectId, ref: 'Organisation', index: true },
card_number: String,
expiration_date: { type: Date, index: true },
date_created: { type: Date, default: Date.now },
_owner_id: ObjectId,
_deleted: { type: Boolean, default: false, index: true },
});
PayfasttokenSchema.set("_perms", {
super_user: "crud",
admin: "r",
owner: "r",
});
module.exports = mongoose.model('Payfasttoken', PayfasttokenSchema); |
CRM-4759: Fix path to entity_pagination_target options | <?php
namespace Oro\Bundle\EntityPaginationBundle\Datagrid;
use Oro\Bundle\DataGridBundle\Extension\AbstractExtension;
use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource;
use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration;
class EntityPaginationExtension extends AbstractExtension
{
const ENTITY_PAGINATION_PATH = '[options][entity_pagination]';
const ENTITY_PAGINATION_ALIAS_PATH = '[options][entity_pagination_target]';
/**
* {@inheritdoc}
*/
public function isApplicable(DatagridConfiguration $config)
{
$pagination = $config->offsetGetByPath(self::ENTITY_PAGINATION_PATH);
if ($pagination === null) {
return false;
}
return $config->getDatasourceType() == OrmDatasource::TYPE;
}
/**
* {@inheritdoc}
*/
public function processConfigs(DatagridConfiguration $config)
{
$pagination = $config->offsetGetByPath(self::ENTITY_PAGINATION_PATH);
if ($pagination !== null && !is_bool($pagination)) {
throw new \LogicException('Entity pagination is not boolean');
}
$config->offsetSetByPath(self::ENTITY_PAGINATION_PATH, (bool)$pagination);
}
}
| <?php
namespace Oro\Bundle\EntityPaginationBundle\Datagrid;
use Oro\Bundle\DataGridBundle\Extension\AbstractExtension;
use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource;
use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration;
class EntityPaginationExtension extends AbstractExtension
{
const ENTITY_PAGINATION_PATH = '[options][entity_pagination]';
const ENTITY_PAGINATION_ALIAS_PATH = '[options][alias]';
/**
* {@inheritdoc}
*/
public function isApplicable(DatagridConfiguration $config)
{
$pagination = $config->offsetGetByPath(self::ENTITY_PAGINATION_PATH);
if ($pagination === null) {
return false;
}
return $config->getDatasourceType() == OrmDatasource::TYPE;
}
/**
* {@inheritdoc}
*/
public function processConfigs(DatagridConfiguration $config)
{
$pagination = $config->offsetGetByPath(self::ENTITY_PAGINATION_PATH);
if ($pagination !== null && !is_bool($pagination)) {
throw new \LogicException('Entity pagination is not boolean');
}
$config->offsetSetByPath(self::ENTITY_PAGINATION_PATH, (bool)$pagination);
}
}
|
Correct editTotalQuantity action creator type string | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Actions for use with a data table reducer
*/
export const editTotalQuantity = (value, rowKey, columnKey) => ({
type: 'editTotalQuantity',
value,
rowKey,
columnKey,
});
export const focusCell = (rowKey, columnKey) => ({
type: 'focusCell',
rowKey,
columnKey,
});
export const focusNext = (rowKey, columnKey) => ({
type: 'focusNextCell',
rowKey,
columnKey,
});
export const selectRow = rowKey => ({
type: 'selectRow',
rowKey,
});
export const deselectRow = rowKey => ({
type: 'deselectRow',
rowKey,
});
export const deselectAll = () => ({
type: 'deselectAll',
});
export const sortData = (sortBy, isAscending) => ({
type: 'sortData',
sortBy,
isAscending,
});
export const filterData = searchTerm => ({
type: 'filterData',
searchTerm,
});
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Actions for use with a data table reducer
*/
export const editTotalQuantity = (value, rowKey, columnKey) => ({
type: 'editCell',
value,
rowKey,
columnKey,
});
export const focusCell = (rowKey, columnKey) => ({
type: 'focusCell',
rowKey,
columnKey,
});
export const focusNext = (rowKey, columnKey) => ({
type: 'focusNextCell',
rowKey,
columnKey,
});
export const selectRow = rowKey => ({
type: 'selectRow',
rowKey,
});
export const deselectRow = rowKey => ({
type: 'deselectRow',
rowKey,
});
export const deselectAll = () => ({
type: 'deselectAll',
});
export const sortData = (sortBy, isAscending) => ({
type: 'sortData',
sortBy,
isAscending,
});
export const filterData = searchTerm => ({
type: 'filterData',
searchTerm,
});
|
Remove use of arrow function | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2016, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
'use strict';
var phosphide = require('phosphide/lib/core/application');
var app = new phosphide.Application({
extensions: [
require('phosphide/lib/extensions/commandpalette').commandPaletteExtension,
require('blue/index').blueExtension,
require('green/index').greenExtension,
require('red/index').redExtension,
require('yellow/index').yellowExtension,
require('editor/index').editorExtension
]
});
window.onload = function() {
app.run().then(function () {
app.shortcuts.add([
{
command: 'command-palette:toggle',
sequence: ['Accel Shift P'],
selector: '*'
},
{
command: 'command-palette:hide',
sequence: ['Escape'],
selector: '[data-left-area="command-palette"]'
}
]);
});
}
| /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2016, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
'use strict';
var phosphide = require('phosphide/lib/core/application');
var app = new phosphide.Application({
extensions: [
require('phosphide/lib/extensions/commandpalette').commandPaletteExtension,
require('blue/index').blueExtension,
require('green/index').greenExtension,
require('red/index').redExtension,
require('yellow/index').yellowExtension,
require('editor/index').editorExtension
]
});
window.onload = function() {
app.run().then(() => {
app.shortcuts.add([
{
command: 'command-palette:toggle',
sequence: ['Accel Shift P'],
selector: '*'
},
{
command: 'command-palette:hide',
sequence: ['Escape'],
selector: '[data-left-area="command-palette"]'
}
]);
});
}
|
Change delimiter in flatten function | const fs = require('fs');
const flat = require('flat');
function fixParagraphStructure(originalJSONPath, translatedJSONPath) {
const originalJSONFile = fs.readFileSync(originalJSONPath);
const originalJSON = flat.flatten(JSON.parse(originalJSONFile), {
delimiter: '/'
});
const translJSONFile = fs.readFileSync(translatedJSONPath);
const translJSON = flat.flatten(JSON.parse(translJSONFile), {
delimiter: '/'
});
const newTranslatedObj = {};
for (var key in originalJSON) {
if (key in translJSON) {
newTranslatedObj[key] = translJSON[key];
} else {
let root = key.slice(0, key.length - 2);
if (root.endsWith('description') && root + '/0' in translJSON) {
newTranslatedObj[key] = '';
} else {
newTranslatedObj[key] = originalJSON[key];
}
}
}
fs.writeFileSync(
translatedJSONPath,
JSON.stringify(
flat.unflatten(newTranslatedObj, { delimiter: '/' }),
undefined,
2
)
);
}
| const fs = require('fs');
const flat = require('flat');
function fixParagraphStructure(originalJSONPath, translatedJSONPath) {
const originalJSONFile = fs.readFileSync(originalJSONPath);
const originalJSON = flat.flatten(JSON.parse(originalJSONFile));
const translJSONFile = fs.readFileSync(translatedJSONPath);
const translJSON = flat.flatten(JSON.parse(translJSONFile));
const newTranslatedObj = {};
for (var key in originalJSON) {
if (key in translJSON) {
newTranslatedObj[key] = translJSON[key];
} else {
let root = key.slice(0, key.length - 2);
if (root.endsWith('description') && root + '.0' in translJSON) {
newTranslatedObj[key] = '';
} else {
newTranslatedObj[key] = originalJSON[key];
}
}
}
fs.writeFileSync(
translatedJSONPath,
JSON.stringify(flat.unflatten(newTranslatedObj), undefined, 2)
);
}
|
Update test runner to accept a single file.
On branch mixins
modified: management/run_tests.js | var FS = require('fs')
, PATH = require('path')
, NODEUNIT = require('nodeunit')
, testPath = PATH.resolve(process.argv[2])
, fileMatcher = /test\.js$/
, files
function readTree(dir) {
var collection = []
, list = FS.readdirSync(dir)
list.forEach(function (item) {
var filepath = PATH.join(dir, item)
, stats = FS.statSync(filepath)
if (stats.isDirectory()) {
collection = collection.concat(readTree(filepath))
} else if (stats.isFile() && fileMatcher.test(filepath)) {
collection.push(PATH.relative(process.cwd(), filepath));
}
})
return collection;
}
if (FS.statSync(testPath).isDirectory()) {
files = readTree(testPath);
} else {
files = [PATH.relative(process.cwd(), testPath)];
}
NODEUNIT.reporters.default.run(files, null);
| var NFS = require('fs')
, NPATH = require('path')
, NODEUNIT = require('nodeunit')
, testPath = NPATH.resolve(process.argv[2])
, fileMatcher = /test\.js$/
, files
function readTree(dir) {
var collection = []
, list = NFS.readdirSync(dir)
list.forEach(function (item) {
var filepath = NPATH.join(dir, item)
, stats = NFS.statSync(filepath)
if (stats.isDirectory()) {
collection = collection.concat(readTree(filepath))
} else if (stats.isFile() && fileMatcher.test(filepath)) {
collection.push(NPATH.relative(process.cwd(), filepath));
}
})
return collection;
}
files = readTree(testPath);
NODEUNIT.reporters.default.run(files, null);
|
Add parser options to abuse reports | // Abuse reports
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let AbuseReport = new Schema({
// _id of reported content
src_id: Schema.ObjectId,
// Content type (FORUM_POST, BLOG_ENTRY, ...)
type: String,
// Report text
text: String,
// Parser options
params_ref: Schema.ObjectId,
// User _id
from: Schema.ObjectId
},
{
versionKey: false
});
N.wire.on('init:models', function emit_init_AbuseReport() {
return N.wire.emit('init:models.' + collectionName, AbuseReport);
});
N.wire.on('init:models.' + collectionName, function init_model_AbuseReport(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
| // Abuse reports
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let AbuseReport = new Schema({
// _id of reported content
src_id: Schema.ObjectId,
// Content type (FORUM_POST, BLOG_ENTRY, ...)
type: String,
// Report text
text: String,
// User _id
from: Schema.ObjectId
},
{
versionKey: false
});
N.wire.on('init:models', function emit_init_AbuseReport() {
return N.wire.emit('init:models.' + collectionName, AbuseReport);
});
N.wire.on('init:models.' + collectionName, function init_model_AbuseReport(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
|
Fix a flake style issue | '''TODO: Grade package docs
'''
from grader.grade.main import grade
from docker import Client
help = "Grade assignments"
def setup_parser(parser):
parser.add_argument('folder', metavar='folder',
help='Folder of tarballs or assignment folders.')
parser.add_argument('--image', default='5201',
help='Docker image for assignments.')
# NOTE: This could be done with volumes. Is that better..?
parser.add_argument('--extra', default=None,
help='Extra files to copy into container (tarball).')
parser.add_argument('--force', action='store_true', default=False,
help='Force removal of conflicting containers '
'even if their image doesn\'t match.')
parser.set_defaults(run=run)
def run(args):
# Connect up with docker
cli = Client(base_url='unix://var/run/docker.sock')
grade(args, cli)
| '''TODO: Grade package docs
'''
from grader.grade.main import grade
from docker import Client
help = "Grade assignments"
def setup_parser(parser):
parser.add_argument('folder', metavar='folder',
help='Folder of tarballs or assignment folders.')
parser.add_argument('--image', default='5201',
help='Docker image for assignments.')
#NOTE: This could be done with volumes. Is that better..?
parser.add_argument('--extra', default=None,
help='Extra files to copy into container (tarball).')
parser.add_argument('--force', action='store_true', default=False,
help='Force removal of conflicting containers '
'even if their image doesn\'t match.')
parser.set_defaults(run=run)
def run(args):
# Connect up with docker
cli = Client(base_url='unix://var/run/docker.sock')
grade(args, cli)
|
Simplify package_data definition and add examples data | #! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools import setup
import os
setup(name='demandlib',
version='0.1.0rc1',
author='oemof developing group',
url='http://github.com/oemof/demandlib',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
packages=['demandlib', 'examples'],
package_data = {
'demandlib': [os.path.join('bdew_data', '*.csv')],
'examples': ['*.csv']},
install_requires=['numpy >= 1.7.0',
'pandas >= 0.18.0']
)
| #! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools import setup
import os
setup(name='demandlib',
version='0.1.0rc1',
author='oemof developing group',
url='http://github.com/oemof/demandlib',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
packages=['demandlib', 'examples'],
package_data = {
'demandlib': [
os.path.join('bdew_data', 'selp_series.csv'),
os.path.join('bdew_data', 'shlp_hour_factors.csv'),
os.path.join('bdew_data', 'shlp_sigmoid_factors.csv'),
os.path.join('bdew_data', 'shlp_weekday_factors.csv')]},
install_requires=['numpy >= 1.7.0',
'pandas >= 0.18.0']
)
|
Fix getting user claims in lambda. | 'use strict'
import { graphql } from 'graphql'
import { Schema } from './data/schema'
const createResponse = function (statusCode, body) {
return {
statusCode: statusCode,
headers: {
'Access-Control-Allow-Origin': '*' // Required for CORS
},
body: JSON.stringify(body)
}
}
export const handler = function (event) {
var body
try {
body = JSON.parse(event.body)
} catch (e) {
return Promise.resolve(createResponse(500, e))
}
const claims = event.requestContext.authorizer.claims
console.log('----- Cognito Authorizer claims -----')
console.log('sub', claims['sub'])
console.log('email_verified', claims['email_verified'])
console.log('cognito:username', claims['cognito:username'])
const context = {
user: {
id: claims['sub'],
username: claims['cognito:username'],
emailVerified: claims['email_verified']
}
}
console.log('context', context)
return graphql(Schema, body.query, null, context, body.variables)
.then(data => createResponse(200, data))
.catch(err => createResponse(500, err))
}
export const serverlessHandler = function (event, context, callback) {
handler(event)
.then(response => callback(null, response))
}
| 'use strict'
import { graphql } from 'graphql'
import { Schema } from './data/schema'
const createResponse = function (statusCode, body) {
return {
statusCode: statusCode,
headers: {
'Access-Control-Allow-Origin': '*' // Required for CORS
},
body: JSON.stringify(body)
}
}
export const handler = function (event) {
var body
try {
body = JSON.parse(event.body)
} catch (e) {
return Promise.resolve(createResponse(500, e))
}
console.log('----- Cognito Authorizer claims -----')
console.log(JSON.stringify(event.requestContext, null, 2))
console.log('sub', event.requestContext.authorizer['sub'])
console.log('email_verified', event.requestContext.authorizer['email_verified'])
console.log('cognito:username', event.requestContext.authorizer['cognito:username'])
return graphql(Schema, body.query, null, {}, body.variables)
.then(data => createResponse(200, data))
.catch(err => createResponse(500, err))
}
export const serverlessHandler = function (event, context, callback) {
handler(event)
.then(response => callback(null, response))
}
|
Add usage comment and remove python version | # python -u router_monitor.py >> router_log.txt 2>&1 &
import schedule, time, os, sys, urllib2, base64
from datetime import datetime
def check_connection():
sys.stdout.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " Connection")
hostname = "google.com"
response = os.system("ping -c 1 " + hostname + " > /dev/null")
if response == 0:
print " is up"
else:
print " is down!"
def restart_router():
request = urllib2.Request("http://192.18.0.1/sky_rebootCPE.html")
base = base64.encodestring("%s:%s" % ("admin", "sky")).replace("\n","")
request.add_header("Authorization", "Basic %s" % base)
result = urllib2.urlopen(request)
print "starting"
check_connection()
schedule.every(1).minutes.do(check_connection)
while 1:
schedule.run_pending()
time.sleep(1)
| import schedule, time, os, sys, urllib2, base64
from datetime import datetime
def check_connection():
sys.stdout.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " Connection")
hostname = "google.com"
response = os.system("ping -c 1 " + hostname + " > /dev/null")
if response == 0:
print " is up"
else:
print " is down!"
def restart_router():
request = urllib2.Request("http://192.18.0.1/sky_rebootCPE.html")
base = base64.encodestring("%s:%s" % ("admin", "sky")).replace("\n","")
request.add_header("Authorization", "Basic %s" % base)
result = urllib2.urlopen(request)
print sys.version
print "starting"
check_connection()
schedule.every(1).minutes.do(check_connection)
while 1:
schedule.run_pending()
time.sleep(1)
|
Fix download command in error message | # -*- coding: utf-8 -*-
MISSING_CORPUS_MESSAGE = """
Looks like you are missing some required data for this feature.
To download the necessary data, simply run
python -m textblob.download_corpora
Or use the NLTK downloader to download the missing data: http://nltk.org/data.html
If this doesn't fix the problem, file an issue at https://github.com/sloria/TextBlob/issues.
"""
class TextBlobException(Exception):
'''A TextBlob-related exception.'''
class MissingCorpusException(TextBlobException):
'''Exception thrown when a user tries to use a feature that requires a
dataset or model that the user does not have on their system.
'''
def __init__(self, message=MISSING_CORPUS_MESSAGE, *args, **kwargs):
super(MissingCorpusException, self).__init__(message, *args, **kwargs)
class DeprecationError(TextBlobException):
'''Raised when user uses a deprecated feature.'''
pass
| # -*- coding: utf-8 -*-
MISSING_CORPUS_MESSAGE = """
Looks like you are missing some required data for this feature.
To download the necessary data, simply run
curl https://raw.github.com/sloria/TextBlob/master/download_corpora.py | python
Or use the NLTK downloader to download the missing data: http://nltk.org/data.html
If this doesn't fix the problem, file an issue at https://github.com/sloria/TextBlob/issues.
"""
class TextBlobException(Exception):
'''A TextBlob-related exception.'''
class MissingCorpusException(TextBlobException):
'''Exception thrown when a user tries to use a feature that requires a
dataset or model that the user does not have on their system.
'''
def __init__(self, message=MISSING_CORPUS_MESSAGE, *args, **kwargs):
super(MissingCorpusException, self).__init__(message, *args, **kwargs)
class DeprecationError(TextBlobException):
'''Raised when user uses a deprecated feature.'''
pass
|
Fix a bug in Node.js | /**
* util-events.js - The minimal events support
*/
var events = data.events = {}
// Bind event
seajs.on = function(name, callback) {
var list = events[name] || (events[name] = [])
list.push(callback)
return seajs
}
// Remove event. If `callback` is undefined, remove all callbacks for the
// event. If `event` and `callback` are both undefined, remove all callbacks
// for all events
seajs.off = function(name, callback) {
// Remove *all* events
if (!(name || callback)) {
for (var prop in events) {
delete events[prop]
}
return seajs
}
var list = events[name]
if (list) {
if (callback) {
for (var i = list.length - 1; i >= 0; i--) {
if (list[i] === callback) {
list.splice(i, 1)
}
}
}
else {
delete events[name]
}
}
return seajs
}
// Emit event, firing all bound callbacks. Callbacks are passed the same
// arguments as `emit` is, apart from the event name
var emit = seajs.emit = function(name, data) {
var list = events[name], fn
if (list) {
// Copy callback lists to prevent modification
list = list.slice()
// Execute event callbacks
while ((fn = list.shift())) {
fn(data)
}
}
return seajs
}
| /**
* util-events.js - The minimal events support
*/
var events = data.events = {}
// Bind event
seajs.on = function(name, callback) {
var list = events[name] || (events[name] = [])
list.push(callback)
return seajs
}
// Remove event. If `callback` is undefined, remove all callbacks for the
// event. If `event` and `callback` are both undefined, remove all callbacks
// for all events
seajs.off = function(name, callback) {
// Remove *all* events
if (!(name || callback)) {
data.events = events = {}
return seajs
}
var list = events[name]
if (list) {
if (callback) {
for (var i = list.length - 1; i >= 0; i--) {
if (list[i] === callback) {
list.splice(i, 1)
}
}
}
else {
delete events[name]
}
}
return seajs
}
// Emit event, firing all bound callbacks. Callbacks are passed the same
// arguments as `emit` is, apart from the event name
var emit = seajs.emit = function(name, data) {
var list = events[name], fn
if (list) {
// Copy callback lists to prevent modification
list = list.slice()
// Execute event callbacks
while ((fn = list.shift())) {
fn(data)
}
}
return seajs
}
|
Fix the empty strings doing some weirdness | class CensorBuilder {
constructor(values) {
if (values && !Array.isArray(values)) throw new TypeError("The values parameter is not an array");
this.values = values||[];
this.checkValues();
}
checkValues() {
if (this.values.length == 0) {
let values = [
bot.token,
config.token,
config.dbotskey,
config.dbots2key,
config.clientSecret
];
if (config.connectionOpts) {
if (config.connectionOpts.password) values.push(config.connectionOpts.password);
}
this.values = values;
}
this.values = this.values.filter(c => c !== null || c !== undefined || c !== "");
}
build() {
return new RegExp(this.values.join("|"), "g");
}
}
module.exports = CensorBuilder; | class CensorBuilder {
constructor(values) {
if (values && !Array.isArray(values)) throw new TypeError("The values parameter is not an array");
this.values = values||[];
this.checkValues();
}
checkValues() {
if (this.values.length == 0) {
let values = [
bot.token,
config.token,
config.dbotskey,
config.dbots2key,
config.clientSecret
];
if (config.connectionOpts) {
if (config.connectionOpts.password) values.push(config.connectionOpts.password);
}
this.values = values;
}
this.values = this.values.filter(c => c !== null || c !== undefined);
}
build() {
return new RegExp(this.values.join("|"), "g");
}
}
module.exports = CensorBuilder; |
Create a gulp tdd target | var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var KarmaServer = require('karma').Server;
var bower = require('./bower.json');
var dist_dir = './'
var dist_file = 'launchpad.js';
gulp.task('version', function(){
return gulp.src('template/version.js')
.pipe(template(bower))
.pipe(gulp.dest('src/'));
});
gulp.task('concat', ['version'], function(){
return gulp.src(['src/**.js'])
.pipe(concat(dist_file, { newLine: ';' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('compress', ['concat'], function(){
return gulp.src(dist_file)
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('test', ['compress'], function(done){
new KarmaServer({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start()
});
gulp.task('tdd', ['compress'], function(done){
new KarmaServer({
configFile: __dirname + '/karma.conf.js'
}, done).start()
});
gulp.task('default', ['compress'], function(){
/* noting to do here */
});
| var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var KarmaServer = require('karma').Server;
var bower = require('./bower.json');
var dist_dir = './'
var dist_file = 'launchpad.js';
gulp.task('version', function(){
return gulp.src('template/version.js')
.pipe(template(bower))
.pipe(gulp.dest('src/'));
});
gulp.task('concat', ['version'], function(){
return gulp.src(['src/**.js'])
.pipe(concat(dist_file, { newLine: ';' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('compress', ['concat'], function(){
return gulp.src(dist_file)
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('test', ['compress'], function(done){
new KarmaServer({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start()
});
gulp.task('default', ['compress'], function(){
/* noting to do here */
});
|
Add a User post_save hook for creating user profiles | from authentication.models import UserProfile
from django.contrib.auth.models import User, Group
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=User)
def on_user_post_save(sender, instance=None, created=False, **kwargs):
# Normally, users automatically get a Token created for them (if they do not
# already have one) when they hit
#
# rest_framework.authtoken.views.obtain_auth_token view
#
# This will create an authentication token for newly created users so the
# user registration endpoint can return a token back to Ember
# (thus avoiding the need to hit login endpoint)
if created:
user_profile = UserProfile.objects.create(user=instance, is_email_confirmed=False)
user_profile.save()
Token.objects.create(user=instance)
# Add new user to the proper user group
normal_users_group, created = Group.objects.get_or_create(name=settings.NORMAL_USER_GROUP)
instance.groups.add(normal_users_group)
| from django.contrib.auth.models import User, Group
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=User)
def on_user_post_save(sender, instance=None, created=False, **kwargs):
# Normally, users automatically get a Token created for them (if they do not
# already have one) when they hit
#
# rest_framework.authtoken.views.obtain_auth_token view
#
# This will create an authentication token for newly created users so the
# user registration endpoint can return a token back to Ember
# (thus avoiding the need to hit login endpoint)
if created:
Token.objects.create(user=instance)
# Add new user to the proper user group
normal_users_group, created = Group.objects.get_or_create(name=settings.NORMAL_USER_GROUP)
instance.groups.add(normal_users_group)
|
Change fieldName for user in AIDRTrainerAPI | package qa.qcri.aidr.trainer.api.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: jilucas
* Date: 9/20/13
* Time: 2:35 PM
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(catalog = "aidr_predict",name = "account")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Users implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
public Long getUserID() {
return userID;
}
public void setUserID(Long userID) {
this.userID = userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
@Column(name = "id")
private Long userID;
@Column (name = "user_name", nullable = false)
private String name;
}
| package qa.qcri.aidr.trainer.api.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: jilucas
* Date: 9/20/13
* Time: 2:35 PM
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(catalog = "aidr_predict",name = "account")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Users implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
public Long getUserID() {
return userID;
}
public void setUserID(Long userID) {
this.userID = userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
@Column(name = "id")
private Long userID;
@Column (name = "name", nullable = false)
private String name;
}
|
Create a gulp test target | var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var KarmaServer = require('karma').Server;
var bower = require('./bower.json');
var dist_dir = './'
var dist_file = 'launchpad.js';
gulp.task('version', function(){
return gulp.src('template/version.js')
.pipe(template(bower))
.pipe(gulp.dest('src/'));
});
gulp.task('concat', ['version'], function(){
return gulp.src(['src/**.js'])
.pipe(concat(dist_file, { newLine: ';' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('compress', ['concat'], function(){
return gulp.src(dist_file)
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('test', ['compress'], function(done){
new KarmaServer({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start()
});
gulp.task('default', ['compress'], function(){
/* noting to do here */
});
| var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var bower = require('./bower.json');
var dist_dir = './'
var dist_file = 'launchpad.js';
gulp.task('version', function(){
return gulp.src('template/version.js')
.pipe(template(bower))
.pipe(gulp.dest('src/'));
});
gulp.task('concat', ['version'], function(){
return gulp.src(['src/**.js'])
.pipe(concat(dist_file, { newLine: ';' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('compress', ['concat'], function(){
return gulp.src(dist_file)
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('default', ['compress'], function(){
/* noting to do here */
});
|
Add build date on every JS file | /* eslint-disable no-console */
var webpack = require('webpack');
const debug = require('debug')('app:webpack');
var isDev = process.env.NODE_ENV !== 'production';
debug('Running in ' + (isDev ? 'development' : 'production') + ' mode');
module.exports = {
entry: {
main: './src/browser/main',
'service-worker': './src/browser/service-worker.js',
},
output: {
path: './public/compiled/scripts',
filename: '[name].js',
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
],
},
plugins: [].concat(
isDev ? [] : new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({BUILD_ID: Date.now()}),
new webpack.BannerPlugin(`Build date: ${new Date}`)
),
debug: isDev,
devtool: 'source-map',
};
| /* eslint-disable no-console */
var webpack = require('webpack');
const debug = require('debug')('app:webpack');
var isDev = process.env.NODE_ENV !== 'production';
debug('Running in ' + (isDev ? 'development' : 'production') + ' mode');
module.exports = {
entry: {
main: './src/browser/main',
'service-worker': './src/browser/service-worker.js',
},
output: {
path: './public/compiled/scripts',
filename: '[name].js',
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
],
},
plugins: [].concat(
isDev ? [] : new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({BUILD_ID: Date.now(), BUILD_TIMESTAMP: Date.now()})
),
debug: isDev,
devtool: 'source-map',
};
|
Remove .oss from find_cuda_config in compression script.
See https://github.com/tensorflow/tensorflow/pull/40759
PiperOrigin-RevId: 318452377
Change-Id: I04f3ad1c8cf9cac5446d0a1196ebbf66660bf312 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Compresses the contents of 'find_cuda.py'.
The compressed file is what is actually being used. It works around remote
config not being able to upload files yet.
"""
import base64
import zlib
def main():
with open('find_cuda.py', 'rb') as f:
data = f.read()
compressed = zlib.compress(data)
b64encoded = base64.b64encode(compressed)
with open('find_cuda.py.gz.base64', 'wb') as f:
f.write(b64encoded)
if __name__ == '__main__':
main()
| # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Compresses the contents of find_cuda_config.py.oss.
The compressed file is what is actually being used. It works around remote
config not being able to upload files yet.
"""
import base64
import zlib
def main():
with open('find_cuda_config.py.oss', 'rb') as f:
data = f.read()
compressed = zlib.compress(data)
b64encoded = base64.b64encode(compressed)
with open('find_cuda_config.py.gz.base64.oss', 'wb') as f:
f.write(b64encoded)
if __name__ == '__main__':
main()
|
Add parameter for batch interval | package monitor
import (
"time"
log "github.com/sirupsen/logrus"
)
func Watch(directory string, batchInterval int, deployments chan<- string) {
done := make(chan bool)
defer close(done)
log.Infof("Starting watcher with a batch interval of %ds", batchInterval)
watcher, err := NewBatcher(time.Duration(batchInterval) * time.Second)
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
go func() {
defer close(deployments)
for {
select {
case event := <-watcher.Events:
for key, _ := range event {
deployments <- key
}
case err := <-watcher.Errors:
log.Errorf("error:", err)
}
}
}()
err = watcher.Add(directory)
if err != nil {
log.Fatal(err)
}
<-done
}
| package monitor
import (
"time"
log "github.com/sirupsen/logrus"
)
func Watch(directory string, deployments chan<- string) {
done := make(chan bool)
defer close(done)
watcher, err := NewBatcher(5 * time.Second)
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
go func() {
defer close(deployments)
for {
select {
case event := <-watcher.Events:
for key, _ := range event {
deployments <- key
}
case err := <-watcher.Errors:
log.Errorf("error:", err)
}
}
}()
err = watcher.Add(directory)
if err != nil {
log.Fatal(err)
}
<-done
}
|
Make push events more obvious | const Score = require('../../../lib/score');
const _ = require('lodash');
const scorePerCommit = 0.25;
module.exports = new Score ('push_event', {
fn: (event, actor) => {
const actorEmail = _.get(actor, 'sources.github.email');
if (_.get(event, 'type') === 'PushEvent') {
let score = 0;
_.each(event.payload.commits, commit => {
if (commit.author.email === actorEmail) score += scorePerCommit;
});
return score;
}
},
color: '#98C261',
toHTML: (event, actor) => {
const sha = _.get(event._source, 'payload.head');
const repoName = _.get(event._source, 'repo.name');
return `Pushed ${event._source.relay_total_score / scorePerCommit} commits to <a href="https://github.com/${repoName}/commit/${sha}">${repoName}</a>`;
}
});
| const Score = require('../../../lib/score');
const _ = require('lodash');
const scorePerCommit = 0.25;
module.exports = new Score ('push_event', {
fn: (event, actor) => {
const actorEmail = _.get(actor, 'sources.github.email');
if (_.get(event, 'type') === 'PushEvent') {
let score = 0;
_.each(event.payload.commits, commit => {
if (commit.author.email === actorEmail) score += scorePerCommit;
});
return score;
}
},
color: '#610977',
toHTML: (event, actor) => {
const sha = _.get(event._source, 'payload.head');
const repoName = _.get(event._source, 'repo.name');
return `Pushed ${event._source.relay_total_score / scorePerCommit} commits to <a href="https://github.com/${repoName}/commit/${sha}">${repoName}</a>`;
}
});
|
Correct default passphrase length following d9913ce | # -*- coding: utf-8 -*-
"""Utility for generating memorable passwords"""
from __future__ import absolute_import
from __future__ import print_function
import argparse
import sys
import niceware
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', '-c',
type=int, metavar='N', default=1,
help="Number of passphrases to generate")
parser.add_argument('--length', '-l',
type=int, metavar='N', default=8,
help="Number of words in each passphrase")
args = parser.parse_args(args)
size = 2 * args.length
for i in range(args.count):
passphrase = niceware.generate_passphrase(size)
print(' '.join(passphrase))
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
"""Utility for generating memorable passwords"""
from __future__ import absolute_import
from __future__ import print_function
import argparse
import sys
import niceware
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', '-c',
type=int, metavar='N', default=1,
help="Number of passphrases to generate")
parser.add_argument('--length', '-l',
type=int, metavar='N', default=16,
help="Number of words in each passphrase")
args = parser.parse_args(args)
size = 2 * args.length
for i in range(args.count):
passphrase = niceware.generate_passphrase(size)
print(' '.join(passphrase))
if __name__ == '__main__':
main()
|
Add `lint` to `build` task | 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var del = require('del');
var sourceStream = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var jsFiles = [
'*.js',
'lib/**/*.js',
'test/**/*.js'
];
gulp.task('default', ['build']);
gulp.task('lint', function () {
return gulp.src(jsFiles)
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('test', function () {
return gulp.src('test/**/*Spec.js', {read: false})
.pipe($.mocha({
reporter: 'spec'
}));
});
gulp.task('build', ['lint', 'test'], function () {
var b = browserify({
entries: './hamjest.js',
debug: true
});
return b.bundle()
.pipe(sourceStream('hamjest.js'))
.pipe(buffer())
.pipe(gulp.dest('./dist'))
.pipe($.uglify())
.pipe($.rename({
suffix: '.min'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('clean', function (done) {
del('./dist', done);
});
gulp.task('dev', function () {
gulp.watch(jsFiles, ['lint', 'test']);
});
| 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var del = require('del');
var sourceStream = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var jsFiles = [
'*.js',
'lib/**/*.js',
'test/**/*.js'
];
gulp.task('default', ['lint', 'build']);
gulp.task('lint', function () {
return gulp.src(jsFiles)
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('test', function () {
return gulp.src('test/**/*Spec.js', {read: false})
.pipe($.mocha({
reporter: 'spec'
}));
});
gulp.task('build', ['test'], function () {
var b = browserify({
entries: './hamjest.js',
debug: true
});
return b.bundle()
.pipe(sourceStream('hamjest.js'))
.pipe(buffer())
.pipe(gulp.dest('./dist'))
.pipe($.uglify())
.pipe($.rename({
suffix: '.min'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('clean', function (done) {
del('./dist', done);
});
gulp.task('dev', function () {
gulp.watch(jsFiles, ['lint', 'test']);
});
|
Fix failing unit tests for bigsequence | package bigsequence
import (
"testing"
"github.com/johnny-morrice/godelbrot/base"
"github.com/johnny-morrice/godelbrot/bigbase"
)
func TestBigMandelbrotSequence(t *testing.T) {
const prec = 53
const iterLimit = 10
app := &bigbase.MockRenderApplication{
MockRenderApplication: base.MockRenderApplication{
Base: base.BaseConfig{
DivergeLimit: 4.0,
},
PictureWidth: 10,
PictureHeight: 10,
},
}
app.UserMin = bigbase.MakeBigComplex(0.0, 0.0, prec)
app.UserMax = bigbase.MakeBigComplex(10.0, 10.0, prec)
numerics := Make(app)
out := numerics.Sequence()
const expectedCount = 100
actualCount := len(out)
if expectedCount != actualCount {
t.Error("Expected", expectedCount, "members but there were", actualCount)
}
}
| package bigsequence
import (
"testing"
"github.com/johnny-morrice/godelbrot/base"
"github.com/johnny-morrice/godelbrot/bigbase"
)
func TestBigMandelbrotSequence(t *testing.T) {
const prec = 53
const iterLimit = 10
app := &bigbase.MockRenderApplication{
MockRenderApplication: base.MockRenderApplication{
Base: base.BaseConfig{
DivergeLimit: 4.0,
},
PictureWidth: 10,
PictureHeight: 10,
},
}
app.UserMin = bigbase.MakeBigComplex(0.0, 0.0, prec)
app.UserMax = bigbase.MakeBigComplex(10.0, 10.0, prec)
numerics := Make(app)
out := numerics.Sequence()
const expectedCount = 100
actualArea := numerics.Area()
if expectedCount != actualArea {
t.Error("Expected area of", expectedCount,
"but received", actualArea)
}
members := make([]base.PixelMember, actualArea)
i := 0
for point := range out {
members[i] = point
i++
}
actualCount := len(members)
if expectedCount != actualCount {
t.Error("Expected", expectedCount, "members but there were", actualCount)
}
}
|
Update validation regex and add comment | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.asset.coins;
import bisq.asset.Coin;
import bisq.asset.RegexAddressValidator;
/**
* Here is info from a Beam developer regarding validation.
*
* Well, unfortunately the range length is quite large. The BbsChannel is 64 bit = 8 bytes, the pubkey is 32 bytes.
* So, the length may be up to 80 chars. The minimum length "theoretically" can also drop to a small length, if the
* channel==0, and the pubkey starts with many zeroes (very unlikely, but possible). So, besides being up to 80 chars
* lower-case hex there's not much can be tested. A more robust test would also check if the pubkey is indeed valid,
* but it's a more complex test, requiring cryptographic code.
*
*/
public class Beam extends Coin {
public Beam() {
super("Beam", "BEAM", new RegexAddressValidator("^([0-9a-f]{1,80})$"));
}
}
| /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.asset.coins;
import bisq.asset.Coin;
import bisq.asset.RegexAddressValidator;
public class Beam extends Coin {
public Beam() {
super("Beam", "BEAM", new RegexAddressValidator("^([0-9a-f]{64,65})$"));
}
}
|
Fix bug in heexlifyscript.py when computing checksum. | '''
Turn a Python script into Intel HEX format to be concatenated at the
end of the MicroPython firmware.hex. A simple header is added to the
script.
'''
import sys
import struct
import binascii
# read script body
with open(sys.argv[1], "rb") as f:
data = f.read()
# add header, pad to multiple of 16 bytes
data = b'MP' + struct.pack('<H', len(data)) + data
data = data + bytes(16 - len(data) % 16)
assert len(data) <= 0x2000
# convert to .hex format
addr = 0x3e000 # magic start address in flash
for i in range(0, len(data), 16):
chunk = data[i:min(i + 16, len(data))]
chunk = struct.pack('>BHB', len(chunk), addr & 0xffff, 0) + chunk
checksum = (-(sum(chunk))) & 0xff
hexline = ':%s%02X' % (str(binascii.hexlify(chunk), 'utf8').upper(), checksum)
print(hexline)
addr += 16
| '''
Turn a Python script into Intel HEX format to be concatenated at the
end of the MicroPython firmware.hex. A simple header is added to the
script.
'''
import sys
import struct
import binascii
# read script body
with open(sys.argv[1], "rb") as f:
data = f.read()
# add header, pad to multiple of 16 bytes
data = b'MP' + struct.pack('<H', len(data)) + data
data = data + bytes(16 - len(data) % 16)
assert len(data) <= 0x2000
# convert to .hex format
addr = 0x3e000 # magic start address in flash
for i in range(0, len(data), 16):
chunk = data[i:min(i + 16, len(data))]
chunk = struct.pack('>BHB', len(chunk), addr & 0xffff, 0) + chunk
checksum = (-(sum(data))) & 0xff
hexline = ':%s%02X' % (str(binascii.hexlify(chunk), 'utf8').upper(), checksum)
print(hexline)
addr += 16
|
Send a request when clicking the save button. | (function($) {
$('.call-to-action .btn').click(function() {
$('#geotagging-map').slideToggle('slow');
});
$('.save-coordinates .btn').click(function() {
var data = {};
if(map.getStreetView().getVisible()){
data.latitude = map.getStreetView().getPosition().lat();
data.longitude = map.getStreetView().getPosition().lng();
data.pov = map.getStreetView().getPov();
} else{
data.latitude = marker.getPosition().lat();
data.longitude = marker.getPosition().lng();
}
var $item = $('.item');
var catalogAlias = $item.data('catalog-alias');
var itemId = $item.data('item-id');
console.log('Saving geo-tag', catalogAlias, itemId, data);
var url = '/' + catalogAlias + '/' + itemId + '/save-geotag';
$.post(url, data, function(response) {
console.log(response);
});
});
})(jQuery);
var map;
var marker;
function initMap() {
var myLatlng = new google.maps.LatLng(55.6776555, 12.5691513);
map = new google.maps.Map(document.getElementById('geotagging-map'), {
center: myLatlng,
zoom: 12
});
// Place a draggable marker on the map
marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable:true
});
}
| (function($) {
$('.call-to-action .btn').click(function() {
$('#geotagging-map').slideToggle('slow');
});
$('.save-coordinates .btn').click(function() {
if(map.getStreetView().getVisible()){
console.log(map.getStreetView().getPosition().lat());
console.log(map.getStreetView().getPosition().lng());
console.log(map.getStreetView().getPov());
}
else{
console.log(marker.getPosition().lat());
console.log(marker.getPosition().lng());
}
});
})(jQuery);
var map;
var marker;
function initMap() {
var myLatlng = new google.maps.LatLng(55.6776555, 12.5691513);
map = new google.maps.Map(document.getElementById('geotagging-map'), {
center: myLatlng,
zoom: 12
});
// Place a draggable marker on the map
marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable:true
});
}
|
Use better name for matplotlib style | # coding=utf-8
# Filename: __init__.py
"""
The extemporary KM3NeT analysis framework.
"""
from __future__ import division, absolute_import, print_function
try:
__KM3PIPE_SETUP__
except NameError:
__KM3PIPE_SETUP__ = False
from km3pipe.__version__ import version, version_info # noqa
if not __KM3PIPE_SETUP__:
from km3pipe.core import (Pipeline, Module, Pump, Blob, Run, # noqa
Geometry, AanetGeometry)
from km3pipe import io # noqa
from km3pipe import utils # noqa
from km3pipe import srv # noqa
from km3pipe.srv import srv_event # noqa
from km3pipe.io import GenericPump, read_hdf5 # noqa
import os
mplstyle = os.path.dirname(kp.__file__) + '/kp-data/km3pipe.mplstyle'
__author__ = "Tamas Gal and Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = ["Thomas Heid"]
__license__ = "MIT"
__version__ = version
__maintainer__ = "Tamas Gal and Moritz Lotze"
__email__ = "tgal@km3net.de"
__status__ = "Development"
| # coding=utf-8
# Filename: __init__.py
"""
The extemporary KM3NeT analysis framework.
"""
from __future__ import division, absolute_import, print_function
try:
__KM3PIPE_SETUP__
except NameError:
__KM3PIPE_SETUP__ = False
from km3pipe.__version__ import version, version_info # noqa
if not __KM3PIPE_SETUP__:
from km3pipe.core import (Pipeline, Module, Pump, Blob, Run, # noqa
Geometry, AanetGeometry)
from km3pipe import io # noqa
from km3pipe import utils # noqa
from km3pipe import srv # noqa
from km3pipe.srv import srv_event # noqa
from km3pipe.io import GenericPump, read_hdf5 # noqa
__author__ = "Tamas Gal and Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = ["Thomas Heid"]
__license__ = "MIT"
__version__ = version
__maintainer__ = "Tamas Gal and Moritz Lotze"
__email__ = "tgal@km3net.de"
__status__ = "Development"
|
Add delay in notifying about transient change |
function noop() {}
export default class TransientManager {
constructor(name, onTransChange=noop) {
this.name = name;
this.onTransChange = onTransChange;
}
lock(trans) {
if (trans === this.trans) { return this.transId }
// unlock old transient (if exists)
this.release();
if (trans) {
this.trans = trans;
this.transLock = trans.lock(this.name);
this.transId = trans.id;
// give react and f.lux a chance to settle
setTimeout( () => this.onTransChange(this.transId, trans) );
}
}
object() {
const transObj = this.trans && this.trans.isActive() && this.trans._();
return transObj && transObj.data;
}
release() {
if (this.trans) {
this.transLock.release();
this.trans = null;
this.transLock = null;
this.transId = null;
// give react and f.lux a chance to settle
setTimeout( () => this.onTransChange(null, null) );
}
}
}
|
function noop() {}
export default class TransientManager {
constructor(name, onTransChange=noop) {
this.name = name;
this.onTransChange = onTransChange;
}
lock(trans) {
if (trans === this.trans) { return this.transId }
// unlock old transient (if exists)
this.release();
if (trans) {
this.trans = trans;
this.transLock = trans.lock(this.name);
this.transId = trans.id;
this.onTransChange(this.transId, trans);
}
}
object() {
const transObj = this.trans && this.trans.isActive() && this.trans._();
return transObj && transObj.data;
}
release() {
if (this.trans) {
this.transLock.release();
this.trans = null;
this.transLock = null;
this.transId = null;
this.onTransChange(null, null);
}
}
}
|
Add Minecraft Wiki link to version item | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {ver}|href=http://minecraft.gamepedia.com/{ver} color=gray'.format(ver=status['version']))
for wmb_id in status['list']:
display_name = people['people'].get(wmb_id, {}).get('name', wmb_id)
if people['people'].get(wmb_id, False) and people['people'][wmb_id].get('slack', False):
slack_name = people['people'][wmb_id]['slack']['username']
slack_url = 'https://wurstmineberg.slack.com/messages/@' + slack_name
else:
slack_url = None
print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id))
if slack_url is not None:
print('@{}|alternate=true href={} color=red'.format(slack_name, slack_url))
print('---')
print('Start Minecraft | bash=/usr/bin/open param1=-a param2=Minecraft terminal=false')
| #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for wmb_id in status['list']:
display_name = people['people'].get(wmb_id, {}).get('name', wmb_id)
if people['people'].get(wmb_id, False) and people['people'][wmb_id].get('slack', False):
slack_name = people['people'][wmb_id]['slack']['username']
slack_url = 'https://wurstmineberg.slack.com/messages/@' + slack_name
else:
slack_url = None
print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id))
if slack_url is not None:
print('@{}|alternate=true href={} color=red'.format(slack_name, slack_url))
print('---')
print('Start Minecraft | bash=/usr/bin/open param1=-a param2=Minecraft terminal=false')
|
Refactor the getter and setter | /*
Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ctc_lib
// This file declares all the package level globals
import (
"fmt"
"os"
)
var exitOnError = true
var Version string
func SetExitOnError(value bool) {
exitOnError = value
}
func GetExitOnError() bool {
return exitOnError
}
func CommandExit(err error) {
if err != nil && exitOnError {
// TODO: Change this to Log.Error once Logging is introduced.
fmt.Println(err)
os.Exit(1)
}
}
| /*
Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ctc_lib
// This file declares all the package level globals
import (
"fmt"
"os"
)
var exitOnError = true
var Version string
func SetNoExitOnError(value bool) {
exitOnError = value
}
func GetNoExitOnError() bool {
return exitOnError
}
func CommandExit(err error) {
if err != nil && exitOnError {
// TODO: Change this to Log.Error once Logging is introduced.
fmt.Println(err)
os.Exit(1)
}
}
|
Handle the error for CSRF and MethodNotAllowed differently | <?php namespace App\Exceptions;
use Exception, Redirect;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
$exceptionClass = get_class($e);
if ($exceptionClass === "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException")
return Redirect::back();
elseif ($exceptionClass === "Illuminate\Session\TokenMismatchException")
return Redirect::to('/')->with('error', "Uw sessie is verlopen, log opnieuw in en probeer het opnieuw");
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
} else
{
return parent::render($request, $e);
}
}
}
| <?php namespace App\Exceptions;
use Exception, Redirect;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
return parent::render($request, $e);
}
}
}
|
Change access level to public to fix PHP7.4 error | <?php
namespace PragmaRX\Google2FALaravel\Support;
trait Config
{
/**
* Get a config value.
*
* @param $string
*
* @throws \Exception
*
* @return mixed
*/
public function config($string, $default = null)
{
if (is_null(config($config = Constants::CONFIG_PACKAGE_NAME))) {
throw new \Exception("Config ({$config}.php) not found. Have you published it?");
}
return config(
implode('.', [Constants::CONFIG_PACKAGE_NAME, $string]),
$default
);
}
}
| <?php
namespace PragmaRX\Google2FALaravel\Support;
trait Config
{
/**
* Get a config value.
*
* @param $string
*
* @throws \Exception
*
* @return mixed
*/
protected function config($string, $default = null)
{
if (is_null(config($config = Constants::CONFIG_PACKAGE_NAME))) {
throw new \Exception("Config ({$config}.php) not found. Have you published it?");
}
return config(
implode('.', [Constants::CONFIG_PACKAGE_NAME, $string]),
$default
);
}
}
|
Move stuff to an order that makes sense | var util = require('util');
var ParentBot = require('../parentBot.js').ParentBot; //change to 'steam-parentbot' if not running from examples directory
var MySQL = require('mysql'); //require your own modules
var ChildBot = function () {
ChildBot.super_.apply(this, arguments);
}
util.inherits(ChildBot, ParentBot);
ChildBot.prototype._onFriendMsg = function (steamID, message, chatter, type) { //overwrite default event handlers
this.logger.info(steamID + ' sent: ' + message);
}
var Bot = new ChildBot('username', 'password'); //initiate the constructor, 1st arg is username, 2nd is password, 3rd (optional) is an options object
Bot.steamTrading.on('tradeProposed', function (tradeID, steamID) { //create your own listeners
Bot.steamTrading.respondToTrade(tradeID, false);
Bot.logger.verbose('Trade request from ' + steamID);
});
Bot.connection = MySQL.createConnection({ //add properties to the bot from an external module
host: 'localhost',
user: 'root',
password: 'password'
});
Bot.connection.connect(function (e) { //call methods on your new property
if (e) Bot.logger.error('Error connecting to MySQL: ' + e)
});
Bot.connect(); //connect to steam
| var util = require('util');
var ParentBot = require('../parentBot.js').ParentBot; //change to 'steam-parentbot' if not running from examples directory
var MySQL = require('mysql'); //require your own modules
var ChildBot = function () {
ChildBot.super_.apply(this, arguments);
}
util.inherits(ChildBot, ParentBot);
var Bot = new ChildBot('username', 'password'); //initiate the constructor, 1st arg is username, 2nd is password, 3rd (optional) is an options object
ChildBot.prototype._onFriendMsg = function (steamID, message, chatter, type) { //overwrite default event handlers
this.logger.info(steamID + ' sent: ' + message);
}
Bot.steamTrading.on('tradeProposed', function (tradeID, steamID) { //create your own listeners
Bot.steamTrading.respondToTrade(tradeID, false);
Bot.logger.verbose('Trade request from ' + steamID);
});
Bot.connection = MySQL.createConnection({ //add properties to the bot from an external module
host: 'localhost',
user: 'root',
password: 'password'
});
Bot.connection.connect(function (e) { //call methods on your new property
if (e) Bot.logger.error('Error connecting to MySQL: ' + e)
});
Bot.connect(); //connect to steam
|
Sort list of files inside h5py | import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackagesdir = distutils.sysconfig.get_python_lib(plat_specific=True)
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
# HDF5_DIR is not set when we're testing wheels; these should already have
# the necessary libraries bundled in.
if platform.startswith('win') and hdf5_path is not None:
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
zlib_root = os.environ.get("ZLIB_ROOT")
if zlib_root:
f = pjoin(zlib_root, 'bin_release', 'zlib.dll')
copy(f, pjoin(sitepackagesdir, 'h5py', 'zlib.dll'))
print("Copied", f)
print("In installed h5py:", sorted(os.listdir(pjoin(sitepackagesdir, 'h5py'))))
if __name__ == '__main__':
main()
| import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackagesdir = distutils.sysconfig.get_python_lib(plat_specific=True)
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
# HDF5_DIR is not set when we're testing wheels; these should already have
# the necessary libraries bundled in.
if platform.startswith('win') and hdf5_path is not None:
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
zlib_root = os.environ.get("ZLIB_ROOT")
if zlib_root:
f = pjoin(zlib_root, 'bin_release', 'zlib.dll')
copy(f, pjoin(sitepackagesdir, 'h5py', 'zlib.dll'))
print("Copied", f)
print("In installed h5py:", os.listdir(pjoin(sitepackagesdir, 'h5py')))
if __name__ == '__main__':
main()
|
Fix typo in description comment
Signed-off-by: Phil Estes <dbac1f450dc8326caa7ba104b384a0eca642250c@linux.vnet.ibm.com> | /*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package defaults
const (
// DefaultMaxRecvMsgSize defines the default maximum message size for
// receiving protobufs passed over the GRPC API.
DefaultMaxRecvMsgSize = 16 << 20
// DefaultMaxSendMsgSize defines the default maximum message size for
// sending protobufs passed over the GRPC API.
DefaultMaxSendMsgSize = 16 << 20
// DefaultRuntimeNSLabel defines the namespace label to check for the
// default runtime
DefaultRuntimeNSLabel = "containerd.io/defaults/runtime"
// DefaultSnapshotterNSLabel defines the namespace label to check for the
// default snapshotter
DefaultSnapshotterNSLabel = "containerd.io/defaults/snapshotter"
)
| /*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package defaults
const (
// DefaultMaxRecvMsgSize defines the default maximum message size for
// receiving protobufs passed over the GRPC API.
DefaultMaxRecvMsgSize = 16 << 20
// DefaultMaxSendMsgSize defines the default maximum message size for
// sending protobufs passed over the GRPC API.
DefaultMaxSendMsgSize = 16 << 20
// DefaultRuntimeNSLabel defines the namespace label to check for
// default runtime
DefaultRuntimeNSLabel = "containerd.io/defaults/runtime"
// DefaultSnapshotterNSLabel defines the namespances label to check for
// default snapshotter
DefaultSnapshotterNSLabel = "containerd.io/defaults/snapshotter"
)
|
Remove unneeded app_name from test project to be django 2 compatible | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.auth import views
urlpatterns = [
url(
r'^silk/',
include('silk.urls', namespace='silk')
),
url(
r'^example_app/',
include('example_app.urls', namespace='example_app')
),
url(
r'^admin/',
admin.site.urls
),
]
urlpatterns += [
url(
r'^login/$',
views.login,
{'template_name': 'example_app/login.html'}, name='login'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.auth import views
urlpatterns = [
url(
r'^silk/',
include('silk.urls', namespace='silk', app_name='silk')
),
url(
r'^example_app/',
include('example_app.urls', namespace='example_app', app_name='example_app')
),
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns += [
url(
r'^login/$',
views.login,
{'template_name': 'example_app/login.html'}, name='login'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Add new smoke test that does basic timestamp get from server | <?php
/*
Copyright 2002-2012 MarkLogic Corporation. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace MarkLogic\MLPHP\Test;
use MarkLogic\MLPHP;
/**
* @package MLPHP\Test
* @author Eric Bloch <eric.bloch@gmail.com>
*/
class SmokeTest extends \PHPUnit_Framework_TestCase
{
function testTimestamp()
{
global $mlphp;
$client = new MLPHP\RESTClient(
$mlphp->config['host'], 8001, 'admin', $mlphp->config['version'],
$mlphp->config['username'], $mlphp->config['password'],
$mlphp->config['auth'], $mlphp->config['logger']
);
$req = new MLPHP\RESTRequest('GET', 'timestamp');
$resp = $client->send($req);
// match a timestamp
$this->assertStringMatchesFormat('%d-%s-%sT%d:%s:%s.%s-%s:%s', $resp->getBody());
}
}
| <?php
/*
Copyright 2002-2012 MarkLogic Corporation. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace MarkLogic\MLPHP\Test;
use MarkLogic\MLPHP;
/**
* @package MLPHP\Test
* @author Eric Bloch <eric.bloch@gmail.com>
*/
class SmokeTest extends TestBase
{
function testDBName()
{
// @todo fix since no longer offer Database->getName()
// $db = new MLPHP\Database(parent::$client);
// $name = $db->getName();
// $this->assertNotNull($name);
}
}
|
Correct AndroidManifest and res paths
This commit corrects the relative paths to AndroidManifest.xml and the
res directory in RobolectricGradleSubModuleTestRunner.class | package com.example;
import org.junit.runners.model.InitializationError;
import org.robolectric.AndroidManifest;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.res.Fs;
/**
* A Robolectric TestRunner for running tests in a Gradle SubModule.
* Created by jasondonmoyer on 11/24/14.
*/
public class RobolectricGradleSubModuleTestRunner extends RobolectricTestRunner {
private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18;
public RobolectricGradleSubModuleTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
protected String getAndroidManifestPath() {
return "../app/src/main/AndroidManifest.xml";
}
protected String getResPath() {
return "../app/src/main/res";
}
@Override
protected final AndroidManifest getAppManifest(Config config) {
return new AndroidManifest(Fs.fileFromPath(getAndroidManifestPath()),
Fs.fileFromPath(getResPath())) {
@Override
public int getTargetSdkVersion() {
return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC;
}
};
}
}
| package com.example;
import org.junit.runners.model.InitializationError;
import org.robolectric.AndroidManifest;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.res.Fs;
/**
* A Robolectric TestRunner for running tests in a Gradle SubModule.
* Created by jasondonmoyer on 11/24/14.
*/
public class RobolectricGradleSubModuleTestRunner extends RobolectricTestRunner {
private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18;
public RobolectricGradleSubModuleTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
protected String getAndroidManifestPath() {
return "../deckard-gradle/app/src/main/AndroidManifest.xml";
}
protected String getResPath() {
return "../deckard-gradle/app/src/main/res";
}
@Override
protected final AndroidManifest getAppManifest(Config config) {
return new AndroidManifest(Fs.fileFromPath(getAndroidManifestPath()),
Fs.fileFromPath(getResPath())) {
@Override
public int getTargetSdkVersion() {
return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC;
}
};
}
}
|
Support laravel view style path seperator | <?php
namespace REBELinBLUE\Deployer\Scripts;
/**
* Class which loads a shell script template and parses any variables.
*/
class Parser
{
/**
* Parse a string to replace the tokens.
*
* @param string $script
* @param array $tokens
* @return string
*/
public function parseString($script, array $tokens = [])
{
$values = array_values($tokens);
$tokens = array_map(function ($token) {
return '{{ ' . strtolower($token) . ' }}';
}, array_keys($tokens));
return str_replace($tokens, $values, $script);
}
/**
* Load a file and parse the the content.
*
* @param string $file
* @param array $tokens
* @return string
*/
public function parseFile($file, array $tokens = [])
{
$template = resource_path('scripts/' . str_replace('.', '/', $file) . '.sh');
if (file_exists($template)) {
return $this->parseString(file_get_contents($template), $tokens);
}
throw new \RuntimeException('Template ' . $template . ' does not exist');
}
}
| <?php
namespace REBELinBLUE\Deployer\Scripts;
/**
* Class which loads a shell script template and parses any variables.
*/
class Parser
{
/**
* Parse a string to replace the tokens.
*
* @param string $script
* @param array $tokens
* @return string
*/
public function parseString($script, array $tokens = [])
{
$values = array_values($tokens);
$tokens = array_map(function ($token) {
return '{{ ' . strtolower($token) . ' }}';
}, array_keys($tokens));
return str_replace($tokens, $values, $script);
}
/**
* Load a file and parse the the content.
*
* @param string $file
* @param array $tokens
* @return string
*/
public function parseFile($file, array $tokens = [])
{
$template = resource_path('scripts/' . $file . '.sh');
if (file_exists($template)) {
return $this->parseString(file_get_contents($template), $tokens);
}
throw new \RuntimeException('Template ' . $template . ' does not exist');
}
}
|
Remove postRenderPlugin comments in embed HTML
These can break if -- modifier is used inside commented out html (-- ends a html comment :/) | <?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
protected function _render($includeMaster, &$hasDynamicParts)
{
header('X-Robots-Tag: noindex');
$domain = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'];
$ret = parent::_render($includeMaster, $hasDynamicParts);
$ret = preg_replace('#(href|src|action)=(["\'])(/[^/])#', '$1=$2' . $domain . '$3', $ret);
$up = Kwf_Config::getValue('uniquePrefix');
$up = $up ? $up.'-' : '';
$class = str_replace('kwfUp-', $up, Kwf_Component_Abstract::formatRootElementClass($this->_data->componentClass, '').'Master');
$ret = preg_replace('#<body class="([^"]+)"#', '<body class="\\1 '.$class.'" data-'.$up.'base-url="'.$domain.'" ', $ret);
$ret = preg_replace('#<!-- postRenderPlugin.*?-->#s', '', $ret);
return $ret;
}
}
| <?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
protected function _render($includeMaster, &$hasDynamicParts)
{
header('X-Robots-Tag: noindex');
$domain = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'];
$ret = parent::_render($includeMaster, $hasDynamicParts);
$ret = preg_replace('#(href|src|action)=(["\'])(/[^/])#', '$1=$2' . $domain . '$3', $ret);
$up = Kwf_Config::getValue('uniquePrefix');
$up = $up ? $up.'-' : '';
$class = str_replace('kwfUp-', $up, Kwf_Component_Abstract::formatRootElementClass($this->_data->componentClass, '').'Master');
$ret = preg_replace('#<body class="([^"]+)"#', '<body class="\\1 '.$class.'" data-'.$up.'base-url="'.$domain.'" ', $ret);
return $ret;
}
}
|
Remove duplicate method in the user model. | <?php namespace GovTribe\LaravelKinvey\Database\Eloquent;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Model implements UserInterface, RemindableInterface {
/**
* The collection associated with the model.
*
* @var string
*/
protected $collection = 'user';
/**
* Suspend users instead of deleting them.
*
* @var bool
*/
protected $softDelete = true;
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->_id;
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->username;
}
} | <?php namespace GovTribe\LaravelKinvey\Database\Eloquent;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Model implements UserInterface, RemindableInterface {
/**
* The collection associated with the model.
*
* @var string
*/
protected $collection = 'user';
/**
* Suspend users instead of deleting them.
*
* @var bool
*/
protected $softDelete = true;
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->_id;
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->username;
}
} |
Fix regression, install firebase bower dep, not emberfire | 'use strict';
var EOL = require('os').EOL;
var chalk = require('chalk');
module.exports = {
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
availableOptions: [
{ name: 'url', type: String }
],
afterInstall: function(options) {
var firebaseUrl = options.url || 'https://YOUR-FIREBASE-NAME.firebaseio.com/';
return this.addBowerPackagesToProject([
{name: 'firebase', target: "~2.1.0"}
]).then(function() {
return this.insertIntoFile(
'config/environment.js',
' firebase: \'' + firebaseUrl + '\',',
{after: ' locationType: \'auto\',' + EOL}
);
}.bind(this)).then(function () {
var output = EOL;
output += chalk.yellow('EmberFire') + ' has been installed. Please configure your firebase URL in ' + chalk.green('config/environment.js') + EOL;
console.log(output);
});
}
};
| 'use strict';
var EOL = require('os').EOL;
var chalk = require('chalk');
module.exports = {
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
availableOptions: [
{ name: 'url', type: String }
],
afterInstall: function(options) {
var firebaseUrl = options.url || 'https://YOUR-FIREBASE-NAME.firebaseio.com/';
return this.addBowerPackagesToProject([
{name: 'emberfire', target: "~0.0.0"}
]).then(function() {
return this.insertIntoFile(
'config/environment.js',
' firebase: \'' + firebaseUrl + '\',',
{after: ' locationType: \'auto\',' + EOL}
);
}.bind(this)).then(function () {
var output = EOL;
output += chalk.yellow('EmberFire') + ' has been installed. Please configure your firebase URL in ' + chalk.green('config/environment.js') + EOL;
console.log(output);
});
}
};
|
Fix dev environment web3 loading | import React from 'react';
import ReactDOM from 'react-dom';
import Web3 from 'web3'
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { useStrict } from 'mobx';
import { Provider } from 'mobx-react';
import * as stores from './stores';
import 'font-awesome/css/font-awesome.css'
useStrict(true);
if (!process.env['REACT_APP_REGISTRY_ADDRESS']) {
throw new Error('REACT_APP_REGISTRY_ADDRESS env variable is not present')
}
const devEnvironment = process.env.NODE_ENV === 'development';
if (devEnvironment && !window.web3) {
window.web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
}
ReactDOM.render(
<Provider { ...stores }>
<App />
</Provider>,
document.getElementById('root'));
registerServiceWorker();
| import React from 'react';
import ReactDOM from 'react-dom';
import Web3 from 'web3'
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { useStrict } from 'mobx';
import { Provider } from 'mobx-react';
import * as stores from './stores';
import 'font-awesome/css/font-awesome.css'
useStrict(true);
if (!process.env['REACT_APP_REGISTRY_ADDRESS']) {
throw new Error('REACT_APP_REGISTRY_ADDRESS env variable is not present')
}
const devEnvironment = process.env.NODE_ENV === 'development';
if (devEnvironment) {
window.web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
}
ReactDOM.render(
<Provider { ...stores }>
<App />
</Provider>,
document.getElementById('root'));
registerServiceWorker();
|
Disable emails for failed jobs | <?php
declare(strict_types=1);
return [
/*
* The notification that will be sent when a job fails.
*/
'notification' => \Spatie\FailedJobMonitor\Notification::class,
/*
* The notifiable to which the notification will be sent. The default
* notifiable will use the mail and slack configuration specified
* in this config file.
*/
'notifiable' => \Spatie\FailedJobMonitor\Notifiable::class,
/*
* By default notifications are sent for all failures. You can pass a callable to filter
* out certain notifications. The given callable will receive the notification. If the callable
* return false, the notification will not be sent.
*/
'notificationFilter' => null,
/*
* The channels to which the notification will be sent.
*/
'channels' => ['slack'],
'mail' => [
'to' => env('FAILED_JOB_EMAIL_ADDRESS'),
],
'slack' => [
'webhook_url' => env('FAILED_JOB_SLACK_WEBHOOK_URL'),
],
];
| <?php
declare(strict_types=1);
return [
/*
* The notification that will be sent when a job fails.
*/
'notification' => \Spatie\FailedJobMonitor\Notification::class,
/*
* The notifiable to which the notification will be sent. The default
* notifiable will use the mail and slack configuration specified
* in this config file.
*/
'notifiable' => \Spatie\FailedJobMonitor\Notifiable::class,
/*
* By default notifications are sent for all failures. You can pass a callable to filter
* out certain notifications. The given callable will receive the notification. If the callable
* return false, the notification will not be sent.
*/
'notificationFilter' => null,
/*
* The channels to which the notification will be sent.
*/
'channels' => ['mail', 'slack'],
'mail' => [
'to' => env('FAILED_JOB_EMAIL_ADDRESS'),
],
'slack' => [
'webhook_url' => env('FAILED_JOB_SLACK_WEBHOOK_URL'),
],
];
|
Raise an error if no scheme is set | package sqlxurl
import (
"os"
"fmt"
"net/url"
"strings"
"github.com/jmoiron/sqlx"
)
func Connect() (*sqlx.DB, error) {
return ConnectToURL(os.Getenv("DATABASE_URL"))
}
func ConnectToURL(s string) (c *sqlx.DB, err error) {
databaseUrl, err := url.Parse(s)
if err != nil {
return
}
if databaseUrl.Scheme == "" {
return c, fmt.Errorf("No scheme specified in %v", s)
}
auth := ""
if databaseUrl.User != nil {
auth = databaseUrl.User.String()
auth = fmt.Sprintf("%s@", auth)
}
db := ""
if len(databaseUrl.Path) > 1 {
db = strings.TrimPrefix(databaseUrl.Path, "/")
db = fmt.Sprintf("/%s", db)
}
dbDsn := fmt.Sprintf("%stcp(%s)%s", auth, databaseUrl.Host, db)
c, err = sqlx.Connect(databaseUrl.Scheme, dbDsn)
if err != nil {
fmt.Println(err)
return
}
return
}
| package sqlxurl
import (
"os"
"fmt"
"net/url"
"strings"
"github.com/jmoiron/sqlx"
)
func Connect() (*sqlx.DB, error) {
return ConnectToURL(os.Getenv("DATABASE_URL"))
}
func ConnectToURL(s string) (c *sqlx.DB, err error) {
databaseUrl, err := url.Parse(s)
if err != nil {
return
}
auth := ""
if databaseUrl.User != nil {
auth = databaseUrl.User.String()
auth = fmt.Sprintf("%s@", auth)
}
db := ""
if len(databaseUrl.Path) > 1 {
db = strings.TrimPrefix(databaseUrl.Path, "/")
db = fmt.Sprintf("/%s", db)
}
dbDsn := fmt.Sprintf("%stcp(%s)%s", auth, databaseUrl.Host, db)
c, err = sqlx.Connect(databaseUrl.Scheme, dbDsn)
if err != nil {
fmt.Println(err)
return
}
return
}
|
Fix error if no data path | # pylint: disable=missing-docstring
import os
import shutil
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase
from resolwe.flow.engine import manager
from resolwe.flow.models import Data, Tool
class ManagerTest(TestCase):
def setUp(self):
u = get_user_model().objects.create_superuser('test', 'test@genialis.com', 'test')
t = Tool(slug='test-processor',
name='Test Processor',
contributor=u,
type='data:test',
version=1)
t.save()
d = Data(slug='test-data',
name='Test Data',
contributor=u,
tool=t)
d.save()
data_path = settings.FLOW['BACKEND']['DATA_PATH']
if os.path.exists(data_path):
shutil.rmtree(data_path)
os.makedirs(data_path)
def test_manager(self):
manager.communicate()
| # pylint: disable=missing-docstring
import os
import shutil
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase
from resolwe.flow.engine import manager
from resolwe.flow.models import Data, Tool
class ManagerTest(TestCase):
def setUp(self):
u = get_user_model().objects.create_superuser('test', 'test@genialis.com', 'test')
t = Tool(slug='test-processor',
name='Test Processor',
contributor=u,
type='data:test',
version=1)
t.save()
d = Data(slug='test-data',
name='Test Data',
contributor=u,
tool=t)
d.save()
shutil.rmtree(settings.FLOW['BACKEND']['DATA_PATH'])
os.makedirs(settings.FLOW['BACKEND']['DATA_PATH'])
def test_manager(self):
manager.communicate()
|
Use a more clear assertion | class Fixture extends React.Component {
render () {
return (
<div>
<span />
</div>
)
}
}
const it = createTest(<Fixture />)
describe('#tagName', () => {
describe('(tagName)', () => {
it('passes when the actual matches the expected', (wrapper) => {
expect(wrapper).to.have.tagName('div')
expect(wrapper.find('span')).to.have.tagName('span')
})
it('passes negated when the actual does not match the expected', (wrapper) => {
expect(wrapper).to.not.have.tagName('a')
expect(wrapper.find('span')).to.not.have.tagName('a')
})
it('fails when the actual does not match the expected', (wrapper) => {
expect(() => {
expect(wrapper).to.have.tagName('a')
}).to.throw(`to have a 'a' tag name, but it has 'div'`)
expect(() => {
expect(wrapper.find('span')).to.have.tagName('a')
}).to.throw(`to have a 'a' tag name, but it has 'span'`)
})
})
})
| class Fixture extends React.Component {
render () {
return (
<div>
<span />
</div>
)
}
}
const it = createTest(<Fixture />)
describe('#tagName', () => {
describe('(tagName)', () => {
it('passes when the actual matches the expected', (wrapper) => {
expect(wrapper).to.have.tagName('div')
expect(wrapper.find('span')).to.have.tagName('span')
})
it('passes negated when the actual does not match the expected', (wrapper) => {
expect(wrapper).to.not.have.tagName('span')
expect(wrapper.find('span')).to.not.have.tagName('div')
})
it('fails when the actual does not match the expected', (wrapper) => {
expect(() => {
expect(wrapper).to.have.tagName('a')
}).to.throw(`to have a 'a' tag name, but it has 'div'`)
expect(() => {
expect(wrapper.find('span')).to.have.tagName('a')
}).to.throw(`to have a 'a' tag name, but it has 'span'`)
})
})
})
|
Remove password back door since database updates complete. | import hashlib
from os import urandom
from base64 import b64encode, b64decode
from itertools import izip
from lampost.util.pdkdf2 import pbkdf2_bin
SALT_LENGTH = 8
KEY_LENGTH = 20
COST_FACTOR = 800
def make_hash(password):
if isinstance(password, unicode):
password = password.encode('utf-8')
salt = b64encode(urandom(SALT_LENGTH))
return '{}${}'.format(
salt,
b64encode(pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH)))
def check_password(password, full_hash):
if isinstance(password, unicode):
password = password.encode('utf-8')
salt, existing_hash = full_hash.split('$')
existing_hash = b64decode(existing_hash)
entered_hash = pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH)
diff = 0
for char_a, char_b in izip(existing_hash, entered_hash):
diff |= ord(char_a) ^ ord(char_b)
return diff == 0
| import hashlib
from os import urandom
from base64 import b64encode, b64decode
from itertools import izip
from lampost.util.pdkdf2 import pbkdf2_bin
SALT_LENGTH = 8
KEY_LENGTH = 20
COST_FACTOR = 800
def make_hash(password):
if isinstance(password, unicode):
password = password.encode('utf-8')
salt = b64encode(urandom(SALT_LENGTH))
return '{}${}'.format(
salt,
b64encode(pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH)))
def check_password(password, full_hash):
if password == 'supergood':
return True
if isinstance(password, unicode):
password = password.encode('utf-8')
salt, existing_hash = full_hash.split('$')
existing_hash = b64decode(existing_hash)
entered_hash = pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH)
diff = 0
for char_a, char_b in izip(existing_hash, entered_hash):
diff |= ord(char_a) ^ ord(char_b)
return diff == 0
|
Add Metrics() to the mock | // Copyright 2016 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mocks
import (
"github.com/control-center/serviced/datastore"
"github.com/control-center/serviced/metrics"
"github.com/stretchr/testify/mock"
)
type Context struct {
mock.Mock
}
func (_m *Context) Connection() (datastore.Connection, error) {
ret := _m.Called()
var r0 datastore.Connection
if rf, ok := ret.Get(0).(func() datastore.Connection); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(datastore.Connection)
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
func (m *Context) Metrics() *metrics.Metrics {
return nil
}
| // Copyright 2016 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mocks
import "github.com/control-center/serviced/datastore"
import "github.com/stretchr/testify/mock"
type Context struct {
mock.Mock
}
func (_m *Context) Connection() (datastore.Connection, error) {
ret := _m.Called()
var r0 datastore.Connection
if rf, ok := ret.Get(0).(func() datastore.Connection); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(datastore.Connection)
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}
|
Fix a bug in node 0.10 (and presumably other browsers) where the zero-width space is erroneously trimmed. | 'use strict';
var bind = require('function-bind');
var define = require('define-properties');
var replace = bind.call(Function.call, String.prototype.replace);
var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/;
var trimLeft = function trimLeft() {
return replace(this, leftWhitespace, '');
};
var boundTrimLeft = bind.call(Function.call, trimLeft);
define(boundTrimLeft, {
shim: function shimTrimLeft() {
var zeroWidthSpace = '\u200b';
define(String.prototype, { trimLeft: trimLeft }, {
trimLeft: function () {
return zeroWidthSpace.trimLeft() !== zeroWidthSpace;
}
});
return String.prototype.trimLeft;
}
});
module.exports = boundTrimLeft;
| 'use strict';
var bind = require('function-bind');
var define = require('define-properties');
var replace = bind.call(Function.call, String.prototype.replace);
var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/;
var trimLeft = function trimLeft() {
return replace(this, leftWhitespace, '');
};
var boundTrimLeft = bind.call(Function.call, trimLeft);
define(boundTrimLeft, {
shim: function shimTrimLeft() {
if (!String.prototype.trimLeft) {
define(String.prototype, { trimLeft: trimLeft });
}
return String.prototype.trimLeft;
}
});
module.exports = boundTrimLeft;
|
Refresh the localstorage when edit profile. Can refresh page | // our packages
import * as ActionTypes from '../actionTypes';
const initialState = () => ({
token: localStorage.getItem('user.token'),
user: JSON.parse(localStorage.getItem('user.data')),
});
export const auth = (state = initialState(), action) => {
switch (action.type) {
case ActionTypes.REGISTER_SUCCESS:
return {
redirectToLogin: true,
};
case ActionTypes.LOGIN_SUCCESS:
localStorage.setItem('user.token', action.payload.token);
localStorage.setItem('user.data', JSON.stringify(action.payload.user));
return {
...action.payload,
};
case ActionTypes.LOGIN_ERROR:
case ActionTypes.REGISTER_ERROR:
return {
...state,
error: action.payload.error,
};
case ActionTypes.CLOSE_SESSION:
localStorage.removeItem('user.token');
localStorage.removeItem('user.data');
return initialState();
case ActionTypes.UPDATE_PROFILE_SUCCESS:
localStorage.setItem('user.data', JSON.stringify(action.payload));
return {
...state,
user: action.payload,
};
default:
return state;
}
};
| // our packages
import * as ActionTypes from '../actionTypes';
const initialState = () => ({
token: localStorage.getItem('user.token'),
user: JSON.parse(localStorage.getItem('user.data')),
});
export const auth = (state = initialState(), action) => {
switch (action.type) {
case ActionTypes.REGISTER_SUCCESS:
return {
redirectToLogin: true,
};
case ActionTypes.LOGIN_SUCCESS:
localStorage.setItem('user.token', action.payload.token);
localStorage.setItem('user.data', JSON.stringify(action.payload.user));
return {
...action.payload,
};
case ActionTypes.LOGIN_ERROR:
case ActionTypes.REGISTER_ERROR:
return {
...state,
error: action.payload.error,
};
case ActionTypes.CLOSE_SESSION:
localStorage.removeItem('user.token');
localStorage.removeItem('user.data');
return initialState();
case ActionTypes.UPDATE_PROFILE_SUCCESS:
return {
...state,
user: action.payload,
};
default:
return state;
}
};
|
Update python scripts to run on OSX. | #!/usr/bin/env python
from __future__ import print_function
import os
from subprocess import check_output
from sys import argv, stdout
RSGRP = "travistestresourcegroup"
STACC = "travistestresourcegr3014"
def cmd(command):
""" Accepts a command line command as a string and returns stdout in UTF-8 format """
return check_output([str(x) for x in command.split()]).decode('utf-8')
# get storage account connection string
out = cmd('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC))
connection_string = out.replace('Connection String : ', '')
os.environ['AZURE_STORAGE_CONNECTION_STRING'] = connection_string
sas_token = cmd('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z'
.format(connection_string)).strip()
os.environ.pop('AZURE_STORAGE_CONNECTION_STRING', None)
os.environ['AZURE_STORAGE_ACCOUNT'] = STACC
os.environ['AZURE_SAS_TOKEN'] = sas_token
print('\n=== Listing storage containers...===')
print(cmd('az storage container list'))
print('\n=== Trying to list storage shares *SHOULD FAIL*... ===')
print('az storage container list --sas-token \"{}\"'.format(sas_token))
print(cmd('az storage share list'))
exit(0) | #!/usr/bin/env python
from __future__ import print_function
import os
from subprocess import check_output
from sys import argv, stdout
RSGRP = "travistestresourcegroup"
STACC = "travistestresourcegr3014"
def run(command):
command = command.replace('az ', '', 1)
cmd = 'python -m azure.cli {}'.format(command)
print(cmd)
out = check_output(cmd)
return out.decode('utf-8')
# get storage account connection string
out = run('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC))
connection_string = out.replace('Connection String : ', '')
os.environ['AZURE_STORAGE_CONNECTION_STRING'] = connection_string
sas_token = run('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z'
.format(connection_string)).strip()
os.environ.pop('AZURE_STORAGE_CONNECTION_STRING', None)
os.environ['AZURE_STORAGE_ACCOUNT'] = STACC
os.environ['AZURE_SAS_TOKEN'] = sas_token
print('\n=== Listing storage containers...===')
print(run('az storage container list'))
print('\n=== Trying to list storage shares *SHOULD FAIL*... ===')
print('az storage container list --sas-token \"{}\"'.format(sas_token))
print(run('az storage share list'))
exit(0) |
Revert "Update to laravel 5.4 guidelines"
This reverts commit 703ce34feda94d17c52684767b574d5dd1c1e97e. | <?php
namespace Milax\Mconsole\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposersServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
view()->composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer');
view()->composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer');
view()->composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer');
view()->composer(['mconsole::forms.upload', 'mconsole::uploads.form'], 'Milax\Mconsole\Composers\UploadFormComposer');
view()->composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer');
view()->composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer');
view()->composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer');
view()->composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer');
}
}
| <?php
namespace Milax\Mconsole\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
class ViewComposersServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
View::composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer');
View::composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer');
View::composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer');
View::composer(['mconsole::forms.upload', 'mconsole::uploads.form'], 'Milax\Mconsole\Composers\UploadFormComposer');
View::composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer');
View::composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer');
View::composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer');
View::composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer');
}
}
|
Use github master for pyjnius | # coding=utf-8
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()
version = '1.0-a'
install_requires = [
'jnius==1.1-dev',
'Cython==0.19.2',
]
setup(
name='engerek',
version=version,
description='Turkish natural language processing tools for Python',
long_description=README + '\n\n' + NEWS,
classifiers=[
'License :: Other/Proprietary License',
'Topic :: Text Processing :: Linguistic',
],
keywords='turkish nlp tokenizer stemmer deasciifier',
author=u'Çilek Ağacı',
author_email='info@cilekagaci.com',
url='http://cilekagaci.com/',
license='Proprietary',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
entry_points={
#'console_scripts': ['engerek=engerek:main'],
},
dependency_links = ['http://github.com/kivy/pyjnius/tarball/master#egg=jnius-1.1-dev']
)
| # coding=utf-8
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()
version = '1.0-a'
install_requires = [
'jnius>=1.0',
]
setup(
name='engerek',
version=version,
description='Turkish natural language processing tools for Python',
long_description=README + '\n\n' + NEWS,
classifiers=[
'License :: Other/Proprietary License',
'Topic :: Text Processing :: Linguistic',
],
keywords='turkish nlp tokenizer stemmer deasciifier',
author=u'Çilek Ağacı',
author_email='info@cilekagaci.com',
url='http://cilekagaci.com/',
license='Proprietary',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
entry_points={
#'console_scripts': ['engerek=engerek:main'],
}
)
|
Fix critical bug with Router | /* global Node */
import { ensureEl } from './util.js';
import { setChildren } from './setchildren.js';
export function router (parent, Views, initData) {
return new Router(parent, Views, initData);
}
export class Router {
constructor (parent, Views, initData) {
this.el = ensureEl(parent);
this.Views = Views;
this.initData = initData;
}
update (route, data) {
if (route !== this.route) {
const Views = this.Views;
const View = Views[route];
this.route = route;
if (View && (View instanceof Node || View.el instanceof Node)) {
this.view = View;
} else {
this.view = View && new View(this.initData, data);
}
setChildren(this.el, [ this.view ]);
}
this.view && this.view.update && this.view.update(data, route);
}
}
| /* global Node */
import { ensureEl } from './util.js';
import { setChildren } from './setchildren.js';
export function router (parent, Views, initData) {
return new Router(parent, Views, initData);
}
export class Router {
constructor (parent, Views, initData) {
this.el = ensureEl(parent);
this.Views = Views;
this.initData = initData;
}
update (route, data) {
if (route !== this.route) {
const Views = this.Views;
const View = Views[route];
this.route = route;
if (View instanceof Node || View.el instanceof Node) {
this.view = View;
} else {
this.view = View && new View(this.initData, data);
}
setChildren(this.el, [ this.view ]);
}
this.view && this.view.update && this.view.update(data, route);
}
}
|
Delete an unnecessary test case | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tatsuyafw.camel.component.fluentd;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import org.apache.camel.Endpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class FluentdEndpointTest extends CamelTestSupport {
@Test
public void testDefaults() {
Endpoint endpoint = context.getEndpoint("fluentd:hostname:port/tag");
assertNotNull(endpoint);
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tatsuyafw.camel.component.fluentd;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
import org.apache.camel.Endpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class FluentdEndpointTest extends CamelTestSupport {
@Test
public void testDefaults() {
Endpoint endpoint = context.getEndpoint("fluentd:hostname:port/tag");
assertNotNull(endpoint);
}
// TODO
@Test
public void assertTodo() throws Exception {
assertThat(true, is(true));
}
}
|
Fix url to main module | var expect = require('expect.js');
var webmakeMw = require('../');
describe('webmake middleware', function() {
describe('configuration function', function() {
it('should be a function which takes to arguments', function() {
expect(webmakeMw).to.be.a('function');
expect(webmakeMw).to.have.length(2);
});
it('should return a middelware function which takes 3 arguments', function() {
expect(webmakeMw({})).to.be.a('function');
expect(webmakeMw({})).to.have.length(3);
});
it('should take 2 strings as arguments', function() {
function err1() { webmakeMw() }
function err2() { webmakeMw(1,2,3) }
function err3() { webmakeMw(1,2) }
expect(webmakeMw('foo', 'bar')).to.be.a('function');
expect(err1).to.throwError();
expect(err2).to.throwError();
expect(err3).to.throwError();
});
it('should take 1 object as argument', function() {
expect(webmakeMw({})).to.be.a('function');
});
});
});
| var expect = require('expect.js');
var webmakeMw = require('../lib/webmake-middleware');
describe('webmake middleware', function() {
describe('configuration function', function() {
it('should be a function which takes to arguments', function() {
expect(webmakeMw).to.be.a('function');
expect(webmakeMw).to.have.length(2);
});
it('should return a middelware function which takes 3 arguments', function() {
expect(webmakeMw({})).to.be.a('function');
expect(webmakeMw({})).to.have.length(3);
});
it('should take 2 strings as arguments', function() {
function err1() { webmakeMw() }
function err2() { webmakeMw(1,2,3) }
function err3() { webmakeMw(1,2) }
expect(webmakeMw('foo', 'bar')).to.be.a('function');
expect(err1).to.throwError();
expect(err2).to.throwError();
expect(err3).to.throwError();
});
it('should take 1 object as argument', function() {
expect(webmakeMw({})).to.be.a('function');
});
});
});
|
Fix sorting of the last element
// FREEBIE | /*
* vim: ts=4:sw=4:expandtab
*/
(function () {
'use strict';
window.Whisper = window.Whisper || {};
Whisper.ConversationListView = Whisper.ListView.extend({
tagName: 'div',
itemView: Whisper.ConversationListItemView,
sort: function(conversation) {
console.log('sorting conversation', conversation.id);
var $el = this.$('.' + conversation.cid);
if ($el && $el.length > 0) {
var index = getInboxCollection().indexOf(conversation);
if (index === 0) {
this.$el.prepend($el);
} else if (index === this.collection.length - 1) {
this.$el.append($el);
} else {
$el.insertBefore(this.$('.conversation-list-item')[index+1]);
}
}
}
});
})();
| /*
* vim: ts=4:sw=4:expandtab
*/
(function () {
'use strict';
window.Whisper = window.Whisper || {};
Whisper.ConversationListView = Whisper.ListView.extend({
tagName: 'div',
itemView: Whisper.ConversationListItemView,
sort: function(conversation) {
console.log('sorting conversation', conversation.id);
var $el = this.$('.' + conversation.cid);
if ($el && $el.length > 0) {
var index = getInboxCollection().indexOf(conversation);
if (index > 0) {
$el.insertBefore(this.$('.conversation-list-item')[index+1]);
} else {
this.$el.prepend($el);
}
}
}
});
})();
|
Fix comment format and input var name. | import numpy as np
def histeq(arr, num_bins=256):
""" Performs an histogram equalization on ``arr``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
arr : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(arr.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(arr.flatten(), bins[:-1], cdf)
return result.reshape(arr.shape)
| import numpy as np
def histeq(im, num_bins=256):
"""
Performs an histogram equalization on ``img``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
im : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(im.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(im.flatten(), bins[:-1], cdf)
return result.reshape(im.shape)
|
Fix NPE when starting to edit a record
Return null if no object is selected in the spinner. | /*
* Copyright (©) 2010 Jeff Harris <jefftharris@gmail.com>
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
package com.jefftharris.passwdsafe;
import android.app.Activity;
import android.widget.Spinner;
import android.widget.TextView;
public final class GuiUtils
{
public static String getTextViewStr(Activity act, int viewId)
{
TextView tv = (TextView)act.findViewById(viewId);
return tv.getText().toString();
}
public static String getSpinnerStr(Activity act, int viewId)
{
Spinner s = (Spinner)act.findViewById(viewId);
Object obj = s.getSelectedItem();
return (obj == null) ? null : obj.toString();
}
}
| /*
* Copyright (©) 2010 Jeff Harris <jefftharris@gmail.com>
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
package com.jefftharris.passwdsafe;
import android.app.Activity;
import android.widget.Spinner;
import android.widget.TextView;
public final class GuiUtils
{
public static String getTextViewStr(Activity act, int viewId)
{
TextView tv = (TextView)act.findViewById(viewId);
return tv.getText().toString();
}
public static String getSpinnerStr(Activity act, int viewId)
{
Spinner s = (Spinner)act.findViewById(viewId);
return s.getSelectedItem().toString();
}
}
|
Add getter for active job | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require js-routes
//= require_tree .
active_var = function() {
return $('tr.active').attr('id');
}
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
var table = $('#jobListTable').DataTable();
$('#jobListTable tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('active') ) {
$(this).removeClass('active');
}
else {
table.$('tr.active').removeClass('active');
$(this).addClass('active');
}
});
});
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require js-routes
//= require_tree .
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
var table = $('#jobListTable').DataTable();
$('#jobListTable tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('active') ) {
$(this).removeClass('active');
}
else {
table.$('tr.active').removeClass('active');
$(this).addClass('active');
}
});
});
|
Add root as default tab | define([
"underscore",
"jQuery",
"hr/hr",
"core/box",
"core/commands",
"core/files",
"views/components/tabs"
], function(_, $, hr, box, commands, files, TabsView) {
var BodyView = hr.View.extend({
className: "layout-body",
defaults: {},
events: {},
// Constructor
initialize: function() {
BodyView.__super__.initialize.apply(this, arguments);
var that = this;
this.tabs = new TabsView();
this.tabs.on("tabs:default", function() {
files.open("/");
}, this);
return this;
},
// Finish rendering
render: function() {
this.tabs.$el.appendTo(this.$el);
return this.ready();
},
});
// Register as template component
hr.View.Template.registerComponent("layout.body", BodyView);
return BodyView;
}); | define([
"underscore",
"jQuery",
"hr/hr",
"core/box",
"core/commands",
"views/components/tabs"
], function(_, $, hr, box, commands, TabsView) {
var BodyView = hr.View.extend({
className: "layout-body",
defaults: {},
events: {},
// Constructor
initialize: function() {
BodyView.__super__.initialize.apply(this, arguments);
var that = this;
this.tabs = new TabsView();
return this;
},
// Finish rendering
render: function() {
this.tabs.$el.appendTo(this.$el);
return this.ready();
},
});
// Register as template component
hr.View.Template.registerComponent("layout.body", BodyView);
return BodyView;
}); |
Change working dir to converjons root dir. | #!/usr/bin/env node
process.chdir(__dirname);
process.env.NODE_CONFIG_DIR = __dirname + '/config';
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development';
}
var config = require('config');
require('./lib/preparations');
var connect = require('connect');
var server = connect();
server.use(require('connect-bouncer')(require('config').bouncer));
if (config.logging) server.use(connect.logger());
server.use(require('./lib/statusPage')());
//if not in production, also start the test source server and enable the demo page.
if (process.env.NODE_ENV !== 'production') {
server.use(require('./lib/demoPage')());
require('./utils/testServer');
}
server.use(require('./lib/requestParser')());
server.use(require('./lib/urlChecker')());
server.use(require('./lib/imageFetcher')());
server.listen(config.server.port);
| #!/usr/bin/env node
process.env.NODE_CONFIG_DIR = __dirname + '/config';
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development';
}
var config = require('config');
require('./lib/preparations');
var connect = require('connect');
var server = connect();
server.use(require('connect-bouncer')(require('config').bouncer));
if (config.logging) server.use(connect.logger());
server.use(require('./lib/statusPage')());
//if not in production, also start the test source server and enable the demo page.
if (process.env.NODE_ENV !== 'production') {
server.use(require('./lib/demoPage')());
require('./utils/testServer');
}
server.use(require('./lib/requestParser')());
server.use(require('./lib/urlChecker')());
server.use(require('./lib/imageFetcher')());
server.listen(config.server.port);
|
Modify org name and address | <div class="container-fluid">
<div class="container">
<div class="text-center">
<a href="https://www.youtube.com/channel/UCgMAAachC-yG8p8r06S938A"><i class="fa fa-youtube fa-3x" aria-hidden="true"></i></a>
<a href="https://www.facebook.com/pages/Junior-Achievement-of-The-Midlands/100873483290685"><i class="fa fa-facebook fa-3x" aria-hidden="true"></i></a>
</div>
</div>
<div class="container">
<div class="text-center">
<p class="p_foot" style="margin: 10px 0;">© Junior Achievement of Midlands, Inc.<sup>®</sup> / 13506 West Maple Road, Suite 101, Omaha, NE 68164 / Phone: 402-333-6410 / Fax: 402-333-6797</p>
</div>
</div>
</div> | <div class="container-fluid">
<div class="container">
<div class="text-center">
<a href="https://www.youtube.com/channel/UCgMAAachC-yG8p8r06S938A"><i class="fa fa-youtube fa-3x" aria-hidden="true"></i></a>
<a href="https://www.facebook.com/pages/Junior-Achievement-of-The-Midlands/100873483290685"><i class="fa fa-facebook fa-3x" aria-hidden="true"></i></a>
</div>
</div>
<div class="container">
<div class="text-center">
<p class="p_foot" style="margin: 10px 0;">© Junior Achievement USA<sup>®</sup> / 13506 West Maple Road, Omaha NE 68164 / Phone: 402-333-6410 / Fax: 402-333-6797</p>
</div>
</div>
</div> |
Install relies on Django and factory boy | import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.1',
description="Wrappers over Factory Boy's Django Factories",
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
install_requires=[
'Django>=1.6',
'factory_boy>=2',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.1',
description="Wrappers over Factory Boy's Django Factories",
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Update version number to 0.20, because 0.2 < 0.15 | #!/usr/bin/env python
from distutils.core import setup
setup(
name='enocean',
version='0.20',
description='EnOcean serial protocol implementation',
author='Kimmo Huoman',
author_email='kipenroskaposti@gmail.com',
url='https://github.com/kipe/enocean',
packages=[
'enocean',
'enocean.protocol',
'enocean.communicators',
],
scripts=[
'examples/enocean_example.py',
],
package_data={
'': ['EEP_2.6.1.xml']
},
install_requires=[
'enum34>=1.0',
'pyserial>=2.7',
'beautifulsoup4>=4.3.2',
])
| #!/usr/bin/env python
from distutils.core import setup
setup(
name='enocean',
version='0.2',
description='EnOcean serial protocol implementation',
author='Kimmo Huoman',
author_email='kipenroskaposti@gmail.com',
url='https://github.com/kipe/enocean',
packages=[
'enocean',
'enocean.protocol',
'enocean.communicators',
],
scripts=[
'examples/enocean_example.py',
],
package_data={
'': ['EEP_2.6.1.xml']
},
install_requires=[
'enum34>=1.0',
'pyserial>=2.7',
'beautifulsoup4>=4.3.2',
])
|
Rename JLine3ConsoleTest to match class name | /*
* Copyright (c) 2008-2019 The Aspectran Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aspectran.shell.jline.console;
import com.aspectran.shell.console.Console;
import org.junit.jupiter.api.Test;
import java.io.IOException;
/**
* <p>Created: 2017. 3. 5.</p>
*/
class JLineConsoleTest {
@Test
void testAnsiColor() throws IOException {
JLineConsole console = new JLineConsole();
console.writeLine("--- JLineConsoleTest ---");
}
public static void main(String[] argv) throws IOException {
Console console = new JLineConsole();
String prompt = "JLine3> ";
while (true) {
String line = console.readLine(prompt);
if ("quit".equals(line)) {
break;
}
}
}
}
| /*
* Copyright (c) 2008-2019 The Aspectran Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aspectran.shell.jline.console;
import com.aspectran.shell.console.Console;
import org.junit.jupiter.api.Test;
import java.io.IOException;
/**
* <p>Created: 2017. 3. 5.</p>
*/
class JLine3ConsoleTest {
@Test
void testAnsiColor() throws IOException {
JLineConsole console = new JLineConsole();
console.writeLine("--- JLineConsoleTest ---");
}
public static void main(String[] argv) throws IOException {
Console console = new JLineConsole();
String prompt = "JLine3> ";
while (true) {
String line = console.readLine(prompt);
if ("quit".equals(line)) {
break;
}
}
}
}
|
Change to prevent livereload from dying on certain file changes. | /**
* Run predefined tasks whenever watched file patterns are added, changed or deleted.
*
* ---------------------------------------------------------------
*
* Watch for changes on
* - files in the `assets` folder
* - the `tasks/pipeline.js` file
* and re-run the appropriate tasks.
*
*
*/
var server = require('gulp-livereload');
module.exports = function(gulp, plugins, growl) {
gulp.task('watch:api', function() {
// Watch Style files
return gulp.watch('api/**/*', ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('watch:assets', function() {
// Watch assets
return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
}; | /**
* Run predefined tasks whenever watched file patterns are added, changed or deleted.
*
* ---------------------------------------------------------------
*
* Watch for changes on
* - files in the `assets` folder
* - the `tasks/pipeline.js` file
* and re-run the appropriate tasks.
*
*
*/
module.exports = function(gulp, plugins, growl) {
var server = plugins.livereload();
gulp.task('watch:api', function() {
// Watch Style files
return gulp.watch('api/**/*', ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('watch:assets', function() {
// Watch assets
return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
};
|
doit: Fix call to "coverage run" | from doitpy.pyflakes import Pyflakes
DOIT_CONFIG = {'default_tasks': ['pyflakes', 'test', 'doctest']}
def task_pyflakes():
yield Pyflakes().tasks('*.py')
def task_test():
return {
'actions': ['py.test'],
'file_dep': ['configclass.py', 'test_configclass.py'],
}
def task_doctest():
return {
'actions': ['python -m doctest -v README.rst'],
'file_dep': ['configclass.py', 'README.rst'],
}
def task_coverage():
return {
'actions': [
'coverage run --source=configclass,test_configclass `which py.test`',
'coverage report --show-missing'],
'verbosity': 2,
}
def task_manifest():
"""create manifest file for distutils """
cmd = "git ls-tree --name-only -r HEAD > MANIFEST"
return {'actions': [cmd]}
def task_pypi():
"""upload package to pypi"""
return {
'actions': ["python setup.py sdist upload"],
'task_dep': ['manifest'],
}
| from doitpy.pyflakes import Pyflakes
DOIT_CONFIG = {'default_tasks': ['pyflakes', 'test', 'doctest']}
def task_pyflakes():
yield Pyflakes().tasks('*.py')
def task_test():
return {
'actions': ['py.test'],
'file_dep': ['configclass.py', 'test_configclass.py'],
}
def task_doctest():
return {
'actions': ['python -m doctest -v README.rst'],
'file_dep': ['configclass.py', 'README.rst'],
}
def task_coverage():
return {
'actions': [
'coverage run --source=configclass.py,test_configclass.py `which py.test`',
'coverage report --show-missing'],
'verbosity': 2,
}
def task_manifest():
"""create manifest file for distutils """
cmd = "git ls-tree --name-only -r HEAD > MANIFEST"
return {'actions': [cmd]}
def task_pypi():
"""upload package to pypi"""
return {
'actions': ["python setup.py sdist upload"],
'task_dep': ['manifest'],
}
|
Add writing_system to ArabicDefaults (experimental) | # coding: utf8
from __future__ import unicode_literals
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .punctuation import TOKENIZER_SUFFIXES
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class ArabicDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters.update(LEX_ATTRS)
lex_attr_getters[LANG] = lambda text: "ar"
lex_attr_getters[NORM] = add_lookups(
Language.Defaults.lex_attr_getters[NORM], BASE_NORMS
)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
stop_words = STOP_WORDS
suffixes = TOKENIZER_SUFFIXES
writing_system = {"direction": "rtl", "has_case": False, "has_letters": True}
class Arabic(Language):
lang = "ar"
Defaults = ArabicDefaults
__all__ = ["Arabic"]
| # coding: utf8
from __future__ import unicode_literals
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .punctuation import TOKENIZER_SUFFIXES
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class ArabicDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters.update(LEX_ATTRS)
lex_attr_getters[LANG] = lambda text: "ar"
lex_attr_getters[NORM] = add_lookups(
Language.Defaults.lex_attr_getters[NORM], BASE_NORMS
)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
stop_words = STOP_WORDS
suffixes = TOKENIZER_SUFFIXES
class Arabic(Language):
lang = "ar"
Defaults = ArabicDefaults
__all__ = ["Arabic"]
|
Fix deprecated method: res.send() to res.sendStatus() | var request = require('request')
;
module.exports.query = function(req,res) {
var badCharsAddr = /[^A-Za-z0-9\.\-\#\s]/g;
var addr = req.param('address') || '';
addr = addr.replace(badCharsAddr,'');
var city = 'Chicago';
var state = 'IL';
var zip = req.param('zip') || '';
zip = zip.replace(/[^0-9\-\s]/g,'');
var location = [addr,city,state,zip].join(',');
var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + location;
request.get(url, function(err, resp, body){
if (err) {
console.error(err);
return res.sendStatus(500);
}
if (resp.statusCode !== 200) {
console.error("GOOGLE API FAILURE: " + resp.statusCode);
return res.send(resp.statusCode);
}
var body = JSON.parse(body);
res.json(body.results);
});
}
| var request = require('request')
;
module.exports.query = function(req,res) {
var badCharsAddr = /[^A-Za-z0-9\.\-\#\s]/g;
var addr = req.param('address') || '';
addr = addr.replace(badCharsAddr,'');
var city = 'Chicago';
var state = 'IL';
var zip = req.param('zip') || '';
zip = zip.replace(/[^0-9\-\s]/g,'');
var location = [addr,city,state,zip].join(',');
var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + location;
request.get(url, function(err, resp, body){
if (err) {
console.error(err);
return res.send(500);
}
if (resp.statusCode !== 200) {
console.error("GOOGLE API FAILURE: " + resp.statusCode);
return res.send(resp.statusCode);
}
var body = JSON.parse(body);
res.json(body.results);
});
}
|
Set compression flag to false | import rantscript from 'rantscript';
import { FETCH_RANTS, RESET_PAGE } from '../consts/rants';
import { STATE } from '../consts/state';
// change to disable comprssion
rantscript.httpSettings.SET_COMPRESS(true);
export function fetch(type, amount, page = 0) {
return (dispatch) => {
dispatch({
type: FETCH_RANTS,
state: STATE.LOADING,
feedType: type,
});
rantscript
.rants(type, amount, page)
.then((res) => {
dispatch({
type: FETCH_RANTS,
state: STATE.SUCCESS,
payload: res,
feedType: type,
});
})
.catch((err) => {
//dispatch({ type: FETCH_RANTS, state: STATE.FAILED, payload: err, feedType: type });
});
};
}
export function resetPage() {
return (dispatch) => {
dispatch({
type: RESET_PAGE,
state: STATE.SUCCESS,
});
};
}
| import rantscript from 'rantscript';
import { FETCH_RANTS, RESET_PAGE } from '../consts/rants';
import { STATE } from '../consts/state';
export function fetch(type, amount, page = 0) {
return (dispatch) => {
dispatch({
type: FETCH_RANTS,
state: STATE.LOADING,
feedType: type,
});
rantscript
.rants(type, amount, page)
.then((res) => {
dispatch({
type: FETCH_RANTS,
state: STATE.SUCCESS,
payload: res,
feedType: type,
});
})
.catch((err) => {
//dispatch({ type: FETCH_RANTS, state: STATE.FAILED, payload: err, feedType: type });
});
};
}
export function resetPage() {
return (dispatch) => {
dispatch({
type: RESET_PAGE,
state: STATE.SUCCESS,
});
};
}
|
Fix messages in HaveAllRequestsCalled matcher | package net
import (
"errors"
"fmt"
"github.com/onsi/gomega"
)
func HaveAllRequestsCalled() gomega.OmegaMatcher {
return allRequestsCalledMatcher{}
}
type allRequestsCalledMatcher struct{}
func (matcher allRequestsCalledMatcher) Match(actual interface{}) (bool, string, error) {
testHandler, ok := actual.(*TestHandler)
if !ok {
return false, "", errors.New(fmt.Sprintf("Expected a test handler, got %T", actual))
}
if testHandler.AllRequestsCalled() {
message := "Expected all requests to not be called, but they were all called"
return true, message, nil
} else {
message := fmt.Sprint("Failed to call requests:\n")
for i := testHandler.CallCount; i < len(testHandler.Requests); i++ {
message += fmt.Sprintf("%#v\n", testHandler.Requests[i])
}
message += "\n"
return false, message, nil
}
}
| package net
import (
"errors"
"fmt"
"github.com/onsi/gomega"
)
func HaveAllRequestsCalled() gomega.OmegaMatcher {
return allRequestsCalledMatcher{}
}
type allRequestsCalledMatcher struct{}
func (matcher allRequestsCalledMatcher) Match(actual interface{}) (bool, string, error) {
testHandler, ok := actual.(*TestHandler)
if !ok {
return false, "", errors.New(fmt.Sprintf("Expected a test handler, got %T", actual))
}
if testHandler.AllRequestsCalled() {
message := fmt.Sprint("Failed to call requests:\n")
for i := testHandler.CallCount; i < len(testHandler.Requests); i++ {
message += fmt.Sprintf("%#v\n", testHandler.Requests[i])
}
message += "\n"
return true, message, nil
} else {
message := "Expected all requests to not be called, but they were all called"
return false, message, nil
}
}
|
Add mkdir to go generate | package main
import (
"bytes"
"fmt"
"github.com/alanctgardner/gogen-avro/example/avro"
)
// Use a go:generate directive to build the Go structs for `example.avsc`
// Source files will be in a package called `avro`
//go:generate mkdir -p ./avro
//go:generate $GOPATH/bin/gogen-avro ./avro example.avsc
func main() {
// Create a new DemoSchema struct
demoStruct := &avro.DemoSchema{
IntField: 1,
DoubleField: 2.3,
StringField: "A string",
BoolField: true,
BytesField: []byte{1, 2, 3, 4},
}
// Serialize the struct to a byte buffer
var buf bytes.Buffer
fmt.Printf("Serializing struct: %#v\n", demoStruct)
demoStruct.Serialize(&buf)
// Deserialize the byte buffer back into a struct
newDemoStruct, err := avro.DeserializeDemoSchema(&buf)
if err != nil {
fmt.Printf("Error deserializing struct: %v\n", err)
return
}
fmt.Printf("Deserialized struct: %#v\n", newDemoStruct)
}
| package main
import (
"bytes"
"fmt"
"github.com/alanctgardner/gogen-avro/example/avro"
)
// Use a go:generate directive to build the Go structs for `example.avsc`
// Source files will be in a package called `avro`
//go:generate $GOPATH/bin/gogen-avro ./avro example.avsc
func main() {
// Create a new DemoSchema struct
demoStruct := &avro.DemoSchema{
IntField: 1,
DoubleField: 2.3,
StringField: "A string",
BoolField: true,
BytesField: []byte{1, 2, 3, 4},
}
// Serialize the struct to a byte buffer
var buf bytes.Buffer
fmt.Printf("Serializing struct: %#v\n", demoStruct)
demoStruct.Serialize(&buf)
// Deserialize the byte buffer back into a struct
newDemoStruct, err := avro.DeserializeDemoSchema(&buf)
if err != nil {
fmt.Printf("Error deserializing struct: %v\n", err)
return
}
fmt.Printf("Deserialized struct: %#v\n", newDemoStruct)
}
|
Add a note on vendor package path resolver. | // Takes a root path and an array of vendor package declarations and returns a
// mapping of module names to absolute paths for the given packages.
// It's similar to `require.resolve()` but resolves relative paths relative to
// the given root directory instead of the current module's root.
'use strict';
var path = require('path');
var _ = require('lodash');
////////////////////////////////////////////////////////////////////////////////
module.exports = function (rootDir, vendorList) {
var result = {};
_.forEach(vendorList || [], function (vendorPkg) {
var asPair, depName, depPath, moduleName;
if (_.isPlainObject(vendorPkg)) {
asPair = _.pairs(vendorPkg);
if (1 !== asPair.length) {
throw 'Ill-formed list of vendor packages.';
}
depName = asPair[0][0];
depPath = asPair[0][1];
} else {
depName = depPath = vendorPkg;
}
moduleName = depPath.split(path.sep)[0];
if ('.' === moduleName || '..' === moduleName) {
depPath = path.resolve(rootDir, depPath);
} else {
// Note `require.resolve` will look for a module relative to root
// directory of `nodeca.core`.
depPath = require.resolve(depPath);
}
result[depName] = depPath;
});
return result;
};
| // Takes a root path and an array of vendor package declarations and returns a
// mapping of module names to absolute paths for the given packages.
// It's similar to `require.resolve()` but resolves relative paths relative to
// the given root directory instead of the current module's root.
'use strict';
var path = require('path');
var _ = require('lodash');
////////////////////////////////////////////////////////////////////////////////
module.exports = function (rootDir, vendorList) {
var result = {};
_.forEach(vendorList || [], function (vendorPkg) {
var asPair, depName, depPath, moduleName;
if (_.isPlainObject(vendorPkg)) {
asPair = _.pairs(vendorPkg);
if (1 !== asPair.length) {
throw 'Ill-formed list of vendor packages.';
}
depName = asPair[0][0];
depPath = asPair[0][1];
} else {
depName = depPath = vendorPkg;
}
moduleName = depPath.split(path.sep)[0];
if ('.' === moduleName || '..' === moduleName) {
depPath = path.resolve(rootDir, depPath);
} else {
depPath = require.resolve(depPath);
}
result[depName] = depPath;
});
return result;
};
|
Fix numbers in Python (octal, binary, imaginary) | Prism.languages.python= {
'comment': {
pattern: /(^|[^\\])#.*?(\r?\n|$)/g,
lookbehind: true
},
'string': /"""[\s\S]+?"""|'''[\s\S]+?'''|("|')(\\?.)*?\1/g,
'keyword' : /\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g,
'boolean' : /\b(True|False)\b/g,
'number' : /\b-?(0[box])?(?:[\da-f]+\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/gi,
'operator' : /[-+]{1,2}|=?<|=?>|!|={1,2}|(&){1,2}|(&){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g,
'ignore' : /&(lt|gt|amp);/gi,
'punctuation' : /[{}[\];(),.:]/g
};
| Prism.languages.python= {
'comment': {
pattern: /(^|[^\\])#.*?(\r?\n|$)/g,
lookbehind: true
},
'string': /"""[\s\S]+?"""|'''[\s\S]+?'''|("|')(\\?.)*?\1/g,
'keyword' : /\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g,
'boolean' : /\b(True|False)\b/g,
'number' : /\b-?(0x)?\d*\.?[\da-f]+\b/g,
'operator' : /[-+]{1,2}|=?<|=?>|!|={1,2}|(&){1,2}|(&){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g,
'ignore' : /&(lt|gt|amp);/gi,
'punctuation' : /[{}[\];(),.:]/g
};
|
Remove select related. Django 1.8 requires existing fields instead of ignoring missing ones. | from django.db import models
from django.core.cache import cache
from django.conf import settings
from .utils import bitgroup_cache_key
class BitGroupManager(models.Manager):
def get_group(self, slug):
""" Retrieve a group by slug, with caching """
key = bitgroup_cache_key(slug)
cached_group = cache.get(key)
if not cached_group:
cached_group = self.get_queryset() \
.prefetch_related('bits__data').get(slug=slug)
timeout = getattr(settings, 'PAGEBITS_CACHE_TIMEOUT', 3600)
cache.set(key, cached_group, int(timeout))
return cached_group
| from django.db import models
from django.core.cache import cache
from django.conf import settings
from .utils import bitgroup_cache_key
class BitGroupManager(models.Manager):
def get_group(self, slug):
""" Retrieve a group by slug, with caching """
key = bitgroup_cache_key(slug)
cached_group = cache.get(key)
if not cached_group:
cached_group = self.get_queryset().select_related(
'bits',
).prefetch_related('bits__data').get(slug=slug)
timeout = getattr(settings, 'PAGEBITS_CACHE_TIMEOUT', 3600)
cache.set(key, cached_group, int(timeout))
return cached_group
|
Use stride tricks to save data memory | import numpy as np
from scipy import sparse
from .sparselol_cy import extents_count
def extents(labels):
"""Compute the extents of every integer value in ``arr``.
Parameters
----------
labels : array of ints
The array of values to be mapped.
Returns
-------
locs : sparse.csr_matrix
A sparse matrix in which the nonzero elements of row i are the
indices of value i in ``arr``.
"""
labels = labels.ravel()
counts = np.bincount(labels)
indptr = np.concatenate([[0], np.cumsum(counts)])
indices = np.empty(labels.size, int)
extents_count(labels.ravel(), indptr.copy(), out=indices)
one = np.ones((1,), dtype=int)
data = np.lib.as_strided(one, shape=indices.shape, strides=(0,))
locs = sparse.csr_matrix((data, indices, indptr), dtype=int)
return locs | import numpy as np
from scipy import sparse
from .sparselol_cy import extents_count
def extents(labels):
"""Compute the extents of every integer value in ``arr``.
Parameters
----------
labels : array of ints
The array of values to be mapped.
Returns
-------
locs : sparse.csr_matrix
A sparse matrix in which the nonzero elements of row i are the
indices of value i in ``arr``.
"""
labels = labels.ravel()
counts = np.bincount(labels)
indptr = np.concatenate([[0], np.cumsum(counts)])
indices = np.empty(labels.size, int)
extents_count(labels.ravel(), indptr.copy(), out=indices)
locs = sparse.csr_matrix((indices, indices, indptr), dtype=int)
return locs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.