text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change subd to require TLS v1.2 or greater. | package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/Symantec/Dominator/lib/srpc"
"io/ioutil"
"os"
)
func setupTls() {
if *caFile == "" || *certFile == "" || *keyFile == "" {
return
}
caData, err := ioutil.ReadFile(*caFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to load CA file\t%s\n",
err)
os.Exit(1)
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caData) {
fmt.Fprintln(os.Stderr, "Unable to parse CA file")
os.Exit(1)
}
serverConfig := new(tls.Config)
serverConfig.ClientAuth = tls.RequireAndVerifyClientCert
serverConfig.MinVersion = tls.VersionTLS12
serverConfig.ClientCAs = caCertPool
cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to load keypair\t%s\n",
err)
os.Exit(1)
}
serverConfig.Certificates = append(serverConfig.Certificates, cert)
srpc.RegisterServerTlsConfig(serverConfig, false)
}
| package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/Symantec/Dominator/lib/srpc"
"io/ioutil"
"os"
)
func setupTls() {
if *caFile == "" || *certFile == "" || *keyFile == "" {
return
}
caData, err := ioutil.ReadFile(*caFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to load CA file\t%s\n",
err)
os.Exit(1)
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caData) {
fmt.Fprintln(os.Stderr, "Unable to parse CA file")
os.Exit(1)
}
serverConfig := new(tls.Config)
serverConfig.ClientAuth = tls.RequireAndVerifyClientCert
serverConfig.ClientCAs = caCertPool
cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to load keypair\t%s\n",
err)
os.Exit(1)
}
serverConfig.Certificates = append(serverConfig.Certificates, cert)
srpc.RegisterServerTlsConfig(serverConfig, false)
}
|
Include Bubble dropdown in navigation | //@flow
import React from "react";
import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../../../../elements/linkedin-icon";
import { OctocatIcon } from "../../../../elements/octocat-icon";
import { Highlight } from "../../../../elements/highlight";
import { Chevron } from "../../../../elements/chevron";
import Bubble from "../../../../elements/bubble";
import theme from "../../../../global/style/mainTheme";
export const MainNav = (props: {}) => (
<Nav>
<Ul>
<Li><Highlight {...props} url="/">Projects</Highlight></Li>
<Li><Highlight {...props}>About</Highlight></Li>
<Li>
<Highlight highlightColor="transparent" {...props}>
<Chevron {...props}>Download</Chevron>
<Bubble
{...props}
textItems={[
{ label: "Resume", target: "#" },
{ label: "Portfoliontopolov", target: "#" }
]}
/>
</Highlight>
</Li>
<Li><Highlight {...props}>Contact</Highlight></Li>
</Ul>
<Ul>
<Li><LinkedInIcon /></Li>
<Li><OctocatIcon /></Li>
</Ul>
</Nav>
);
| //@flow
import React from "react";
import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../../../../elements/linkedin-icon";
import { OctocatIcon } from "../../../../elements/octocat-icon";
import { Highlight } from "../../../../elements/highlight";
import { Chevron } from "../../../../elements/chevron";
import theme from "../../../../global/style/mainTheme";
export const MainNav = (props: {}) => (
<Nav>
<Ul>
<Li><Highlight {...props} url="/">Projects</Highlight></Li>
<Li><Highlight {...props}>About</Highlight></Li>
<Li>
<Highlight highlightColor="transparent" {...props}>
<Chevron {...props}>Download</Chevron>
</Highlight>
</Li>
<Li><Highlight {...props}>Contact</Highlight></Li>
</Ul>
<Ul>
<Li><LinkedInIcon /></Li>
<Li><OctocatIcon /></Li>
</Ul>
</Nav>
);
|
Fix args manipulation in when translating ksdefs | class APIMismatch(Exception):
pass
def translateArgs(request, api_version):
args = request.args
if request.method == 'system_add_keyspace' \
or request.method == 'system_update_keyspace':
adapted_ksdef = adapt_ksdef_rf(args[0])
args = (adapted_ksdef,) + args[1:]
return args
def postProcess(results, method):
if method == 'describe_keyspace':
results = adapt_ksdef_rf(results)
elif method == 'describe_keyspaces':
results = map(adapt_ksdef_rf, results)
return results
def adapt_ksdef_rf(ksdef):
"""
try to always have both KsDef.strategy_options['replication_factor'] and
KsDef.replication_factor available, and let the thrift api code and client
code work out what they want to use.
"""
if getattr(ksdef, 'strategy_options', None) is None:
ksdef.strategy_options = {}
if 'replication_factor' in ksdef.strategy_options:
if ksdef.replication_factor is None:
ksdef.replication_factor = int(ksdef.strategy_options['replication_factor'])
elif ksdef.replication_factor is not None:
ksdef.strategy_options['replication_factor'] = str(ksdef.replication_factor)
return ksdef
| class APIMismatch(Exception):
pass
def translateArgs(request, api_version):
args = request.args
if request.method == 'system_add_keyspace' \
or request.method == 'system_update_keyspace':
args = adapt_ksdef_rf(args[0]) + args[1:]
return args
def postProcess(results, method):
if method == 'describe_keyspace':
results = adapt_ksdef_rf(results)
elif method == 'describe_keyspaces':
results = map(adapt_ksdef_rf, results)
return results
def adapt_ksdef_rf(ksdef):
"""
try to always have both KsDef.strategy_options['replication_factor'] and
KsDef.replication_factor available, and let the thrift api code and client
code work out what they want to use.
"""
if getattr(ksdef, 'strategy_options', None) is None:
ksdef.strategy_options = {}
if 'replication_factor' in ksdef.strategy_options:
if ksdef.replication_factor is None:
ksdef.replication_factor = int(ksdef.strategy_options['replication_factor'])
elif ksdef.replication_factor is not None:
ksdef.strategy_options['replication_factor'] = str(ksdef.replication_factor)
return ksdef
|
Remove unnecessary check, used to re functions returning different types | import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
matches += IP_REGEX.findall(line)
return set(sorted(matches)) if matches else set()
def store_ips(cache_path, ips):
"""Stores the IPs into a cache for later retrieval."""
cache = []
if os.path.exists(cache_path):
with open(cache_path, 'rb') as f:
cache = json.loads(f.read())
new_ips = 0
existing_ips = [i['ip'] for i in cache]
for ip in ips:
if ip not in existing_ips:
cache.append({'ip': ip})
new_ips += 1
with open(cache_path, 'wb') as f:
f.write(json.dumps(cache))
return new_ips
| import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
match = IP_REGEX.findall(line)
if match:
matches += match
return set(sorted(matches)) if matches else set()
def store_ips(cache_path, ips):
"""Stores the IPs into a cache for later retrieval."""
cache = []
if os.path.exists(cache_path):
with open(cache_path, 'rb') as f:
cache = json.loads(f.read())
new_ips = 0
existing_ips = [i['ip'] for i in cache]
for ip in ips:
if ip not in existing_ips:
cache.append({'ip': ip})
new_ips += 1
with open(cache_path, 'wb') as f:
f.write(json.dumps(cache))
return new_ips
|
Fix runtime JavaScript errors in chrome://options.
With chrome built with CHROMEOS=1, the following error occurs
in in chrome://options as sync-button and dummy-button don't exist.
Remove the binding code to fix the error.
[28843:28843:611993994873:INFO:CONSOLE(0)] "Uncaught TypeError: Cannot set property 'onclick' of null," source: chrome://options/system (528)
TEST=manually on ubuntu by "out/Release/chrome --test-type"
BUG=none
Review URL: http://codereview.chromium.org/2900008
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@52281 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright (c) 2010 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.
///////////////////////////////////////////////////////////////////////////////
// SystemOptions class:
/**
* Encapsulated handling of ChromeOS system options page.
* @constructor
*/
function SystemOptions(model) {
OptionsPage.call(this, 'system', templateData.systemPage, 'systemPage');
}
SystemOptions.getInstance = function() {
if (SystemOptions.instance_)
return SystemOptions.instance_;
SystemOptions.instance_ = new SystemOptions(null);
return SystemOptions.instance_;
}
// Inherit SystemOptions from OptionsPage.
SystemOptions.prototype = {
__proto__: OptionsPage.prototype,
/**
* Initializes SystemOptions page.
* Calls base class implementation to starts preference initialization.
*/
initializePage: function() {
OptionsPage.prototype.initializePage.call(this);
var timezone = $('timezone-select');
if (timezone) {
timezone.initializeValues(templateData.timezoneList);
}
$('language-button').onclick = function(event) {
// TODO: Open ChromeOS language settings page.
};
},
};
| // Copyright (c) 2010 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.
///////////////////////////////////////////////////////////////////////////////
// SystemOptions class:
/**
* Encapsulated handling of ChromeOS system options page.
* @constructor
*/
function SystemOptions(model) {
OptionsPage.call(this, 'system', templateData.systemPage, 'systemPage');
}
SystemOptions.getInstance = function() {
if (SystemOptions.instance_)
return SystemOptions.instance_;
SystemOptions.instance_ = new SystemOptions(null);
return SystemOptions.instance_;
}
// Inherit SystemOptions from OptionsPage.
SystemOptions.prototype = {
__proto__: OptionsPage.prototype,
/**
* Initializes SystemOptions page.
* Calls base class implementation to starts preference initialization.
*/
initializePage: function() {
OptionsPage.prototype.initializePage.call(this);
var timezone = $('timezone-select');
if (timezone) {
timezone.initializeValues(templateData.timezoneList);
}
$('language-button').onclick = function(event) {
// TODO: Open ChromeOS language settings page.
};
$('sync-button').onclick = function(event) {
OptionsPage.showPageByName('sync');
}
$('dummy-button').onclick = function(event) {
OptionsPage.showOverlay('dummy');
}
},
};
|
Fix exception test to handle system exceptions | import os
from unittest.mock import MagicMock
import pytest
from isort import setuptools_commands
def test_isort_command_smoke(src_dir):
"""A basic smoke test for the setuptools_commands command"""
from distutils.dist import Distribution
command = setuptools_commands.ISortCommand(Distribution())
command.distribution.packages = ["isort"]
command.distribution.package_dir = {"isort": src_dir}
command.initialize_options()
command.finalize_options()
try:
command.run()
except BaseException:
pass
command.distribution.package_dir = {"": "isort"}
command.distribution.py_modules = ["one", "two"]
command.initialize_options()
command.finalize_options()
command.run()
command.distribution.packages = ["not_a_file"]
command.distribution.package_dir = {"not_a_file": src_dir}
command.initialize_options()
command.finalize_options()
try:
command.run()
except BaseException:
pass
| import os
from unittest.mock import MagicMock
import pytest
from isort import setuptools_commands
def test_isort_command_smoke(src_dir):
"""A basic smoke test for the setuptools_commands command"""
from distutils.dist import Distribution
command = setuptools_commands.ISortCommand(Distribution())
command.distribution.packages = ["isort"]
command.distribution.package_dir = {"isort": src_dir}
command.initialize_options()
command.finalize_options()
try:
command.run()
except Exception:
pass
command.distribution.package_dir = {"": "isort"}
command.distribution.py_modules = ["one", "two"]
command.initialize_options()
command.finalize_options()
command.run()
command.distribution.packages = ["not_a_file"]
command.distribution.package_dir = {"not_a_file": src_dir}
command.initialize_options()
command.finalize_options()
try:
command.run()
except Exception:
pass
|
Remove unnecessary Thread objects creation in ExecutorService | package edu.javacourse.threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Artem Pronchakov | email/xmpp: artem.pronchakov@calisto.email
*/
public class ExecutorServiceExample {
public static void main(String[] args) {
Worker worker1 = new Worker("worker1");
Worker worker2 = new Worker("worker2");
Worker worker3 = new Worker("worker3");
Worker worker4 = new Worker("worker4");
Worker worker5 = new Worker("worker5");
// ExecutorService executorService = Executors.newSingleThreadExecutor();
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(worker1);
executorService.execute(worker2);
executorService.execute(worker3);
executorService.execute(worker4);
executorService.execute(worker5);
executorService.shutdown();
}
}
| package edu.javacourse.threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Artem Pronchakov | email/xmpp: artem.pronchakov@calisto.email
*/
public class ExecutorServiceExample {
public static void main(String[] args) {
Thread worker1 = new Thread(new Worker("worker1"));
Thread worker2 = new Thread(new Worker("worker2"));
Thread worker3 = new Thread(new Worker("worker3"));
Thread worker4 = new Thread(new Worker("worker4"));
Thread worker5 = new Thread(new Worker("worker5"));
// ExecutorService executorService = Executors.newSingleThreadExecutor();
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(worker1);
executorService.execute(worker2);
executorService.execute(worker3);
executorService.execute(worker4);
executorService.execute(worker5);
executorService.shutdown();
}
}
|
Fix smoke tests for browsers without innerText support | import Ember from 'ember';
import startApp from '../helpers/start-app';
var application;
function contains(selector, string) {
var element = find(selector)[0];
if (!element) {
return ok(false, 'can\'t find element: ' + selector);
}
var text = element.textContent || element.innerText;
return equal(text.replace(/^\s+|\s+$/g, ''), string);
}
module('Acceptance: Smoke', {
setup: function() {
application = startApp();
},
teardown: function() {
Ember.run(application, 'destroy');
}
});
test('format-number', function() {
visit('/smoke');
andThen(function() {
contains('.format-number', '€1,000.00');
});
});
test('format-date', function() {
visit('/smoke');
andThen(function() {
contains('.format-date', '1/23/2014');
});
});
test('format-time', function() {
visit('/smoke');
andThen(function() {
contains('.format-time', '18:00:44');
});
});
test('format-relative', function() {
visit('/smoke');
andThen(function() {
contains('.format-relative', 'yesterday');
});
});
| import Ember from 'ember';
import startApp from '../helpers/start-app';
var application;
function contains(selector, string) {
var element = find(selector)[0];
if (!element) {
return ok(false, 'can\'t find element: ' + selector);
}
return equal(element.innerText.replace(/^\s+|\s+$/g, ''), string);
}
module('Acceptance: Smoke', {
setup: function() {
application = startApp();
},
teardown: function() {
Ember.run(application, 'destroy');
}
});
test('format-number', function() {
visit('/smoke');
andThen(function() {
contains('.format-number', '€1,000.00');
});
});
test('format-date', function() {
visit('/smoke');
andThen(function() {
contains('.format-date', '1/23/2014');
});
});
test('format-time', function() {
visit('/smoke');
andThen(function() {
contains('.format-time', '18:00:44');
});
});
test('format-relative', function() {
visit('/smoke');
andThen(function() {
contains('.format-relative', 'yesterday');
});
});
|
Fix build error due to replacing zero_point_celsius by scipy equivalent | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities regarding NTC thermistors
See http://www.vishay.com/docs/29053/ntcintro.pdf for details
"""
from UliEngineering.Physics.Temperature import normalize_temperature
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
import numpy as np
from scipy.constants import zero_Celsius
__all__ = ["ntc_resistance"]
def ntc_resistance(r25, b25, t) -> Unit("Ω"):
"""
Compute the NTC resistance by temperature and NTC parameters
Parameters
----------
r25 : float or EngineerIO string
The NTC resistance at 25°C, sometimes also called "nominal resistance"
b25: float or EngineerIO string
The NTC b-constant (e.g. b25/50, b25/85 or b25/100)
t : temperature
The temperature. Will be interpreted using normalize_temperature()
"""
# Normalize inputs
r25 = normalize_numeric(r25)
b25 = normalize_numeric(b25)
t = normalize_temperature(t) # t is now in Kelvins
# Compute resistance
return r25 * np.exp(b25 * (1./t - 1./(25. + zero_Celsius)))
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities regarding NTC thermistors
See http://www.vishay.com/docs/29053/ntcintro.pdf for details
"""
from UliEngineering.Physics.Temperature import zero_point_celsius, normalize_temperature
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
import numpy as np
__all__ = ["ntc_resistance"]
def ntc_resistance(r25, b25, t) -> Unit("Ω"):
"""
Compute the NTC resistance by temperature and NTC parameters
Parameters
----------
r25 : float or EngineerIO string
The NTC resistance at 25°C, sometimes also called "nominal resistance"
b25: float or EngineerIO string
The NTC b-constant (e.g. b25/50, b25/85 or b25/100)
t : temperature
The temperature. Will be interpreted using normalize_temperature()
"""
# Normalize inputs
r25 = normalize_numeric(r25)
b25 = normalize_numeric(b25)
t = normalize_temperature(t) # t is now in Kelvins
# Compute resistance
return r25 * np.exp(b25 * (1./t - 1./(25. + zero_point_celsius)))
|
Move errant variable away from require block | var TruffleError = require("truffle-error");
var inherits = require("util").inherits;
var web3 = require("web3");
inherits(StatusError, TruffleError);
var defaultGas = 90000;
function StatusError(args, tx, receipt) {
var message;
var gasLimit = parseInt(args.gas) || defaultGas;
if(receipt.gasUsed === gasLimit){
message = "Transaction: " + tx + " exited with an error (status 0 - invalid opcode).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `assert` statements.\n" +
" - has enough gas to execute all internal Solidity function calls.\n";
} else {
message = "Transaction: " + tx + " exited with an error (status 0 - revert).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `require` statements.\n" +
" - does not trigger a Solidity `revert` statement.\n";
}
StatusError.super_.call(this, message);
this.tx = tx;
this.receipt = receipt;
}
module.exports = StatusError; | var TruffleError = require("truffle-error");
var inherits = require("util").inherits;
var defaultGas = 90000;
var web3 = require("web3");
inherits(StatusError, TruffleError);
function StatusError(args, tx, receipt) {
var message;
var gasLimit = parseInt(args.gas) || defaultGas;
if(receipt.gasUsed === gasLimit){
message = "Transaction: " + tx + " exited with an error (status 0 - invalid opcode).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `assert` statements.\n" +
" - has enough gas to execute all internal Solidity function calls.\n";
} else {
message = "Transaction: " + tx + " exited with an error (status 0 - revert).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `require` statements.\n" +
" - does not trigger a Solidity `revert` statement.\n";
}
StatusError.super_.call(this, message);
this.tx = tx;
this.receipt = receipt;
}
module.exports = StatusError; |
Clean up closed state form. | @if(!setting('enable_voting'))
<div class="wrapper">
<h1 class="highlighted">Sign up for updates!</h1>
<p>Voting is closed, but sign up to be notified when we're ready!</p>
{!! Form::open(['route' => 'users.store']) !!}
@include('auth.form')
{!! Form::submit('Send me updates!', ['class' => 'button -primary']) !!}
{!! Form::close() !!}
@if(is_domestic_session() || should_collect_international_phone())
<p class="legal">
By signing up for updates, you agree to receive future updates from DoSomething.org (duh!).<br/>
Message & data rates may apply. Text STOP to opt-out, HELP for help.
</p>
@endif
</div>
@endif
| @if(!setting('enable_voting'))
<div class="wrapper">
<h1 class="highlighted">Sign up for updates!</h1>
<p>Voting is closed, but sign up to be notified when we're ready!</p>
</div>
<div class="wrapper">
{!! Form::open(['route' => 'users.store']) !!}
@include('auth.form')
{!! Form::submit('Send me updates!', ['class' => 'button -primary']) !!}
{!! Form::close() !!}
@if(is_domestic_session() || should_collect_international_phone())
<p class="legal">
By signing up for updates, you agree to receive future updates from DoSomething.org (duh!).<br/>
Message & data rates may apply. Text STOP to opt-out, HELP for help.
</p>
@endif
</div>
@endif
|
Fix exception when creating new challenge from outside category. | /**
* Copyright 2016 David Tomaschik <david@systemoverlord.com>
*
* 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.
*/
/* Admin-only services */
var adminServices = angular.module('adminServices', []);
adminServices.service('adminStateService', [
function() {
this.cid = null;
this.saveCategory = function(cat) {
this.cid = (cat && cat.cid) || cat;
};
this.getCategory = function() {
return this.cid;
};
}]);
| /**
* Copyright 2016 David Tomaschik <david@systemoverlord.com>
*
* 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.
*/
/* Admin-only services */
var adminServices = angular.module('adminServices', []);
adminServices.service('adminStateService', [
function() {
this.cid = null;
this.saveCategory = function(cat) {
this.cid = cat.cid || cat;
};
this.getCategory = function() {
return this.cid;
};
}]);
|
Add version constraing to bootstrap use | Package.describe({
summary: "Run tests interactively in the browser",
version: '1.0.5-pre.2'
});
Package.on_use(function (api) {
// XXX this should go away, and there should be a clean interface
// that tinytest and the driver both implement?
api.use('tinytest');
api.use('bootstrap@1.0.1');
api.use('underscore');
api.use('session');
api.use('reload');
api.use(['blaze', 'templating', 'spacebars',
'ddp', 'tracker'], 'client');
api.add_files('diff_match_patch_uncompressed.js', 'client');
api.add_files('diff_match_patch_uncompressed.js', 'client');
api.add_files([
'driver.css',
'driver.html',
'driver.js'
], "client");
api.use('autoupdate', 'server', {weak: true});
api.use('random', 'server');
api.add_files('autoupdate.js', 'server');
});
| Package.describe({
summary: "Run tests interactively in the browser",
version: '1.0.5-pre.2'
});
Package.on_use(function (api) {
// XXX this should go away, and there should be a clean interface
// that tinytest and the driver both implement?
api.use('tinytest');
api.use('bootstrap');
api.use('underscore');
api.use('session');
api.use('reload');
api.use(['blaze', 'templating', 'spacebars',
'ddp', 'tracker'], 'client');
api.add_files('diff_match_patch_uncompressed.js', 'client');
api.add_files('diff_match_patch_uncompressed.js', 'client');
api.add_files([
'driver.css',
'driver.html',
'driver.js'
], "client");
api.use('autoupdate', 'server', {weak: true});
api.use('random', 'server');
api.add_files('autoupdate.js', 'server');
});
|
Fix formatRelative in Latvian locale | import isSameUTCWeek from '../../../../_lib/isSameUTCWeek/index.js'
var weekdays = [
'svētdienā',
'pirmdienā',
'otrdienā',
'trešdienā',
'ceturtdienā',
'piektdienā',
'sestdienā'
]
var formatRelativeLocale = {
lastWeek: function(date, baseDate, options) {
if (isSameUTCWeek(date, baseDate, options)) {
return "eeee 'plkst.' p"
}
var weekday = weekdays[date.getUTCDay()]
return "'Pagājušā " + weekday + " plkst.' p"
},
yesterday: "'Vakar plkst.' p",
today: "'Šodien plkst.' p",
tomorrow: "'Rīt plkst.' p",
nextWeek: function(date, baseDate, options) {
if (isSameUTCWeek(date, baseDate, options)) {
return "eeee 'plkst.' p"
}
var weekday = weekdays[date.getUTCDay()]
return "'Nākamajā " + weekday + " plkst.' p"
},
other: 'P'
}
export default function formatRelative(token, date, baseDate, options) {
var format = formatRelativeLocale[token]
if (typeof format === 'function') {
return format(date, baseDate, options)
}
return format
}
| import isSameUTCWeek from '../../../../_lib/isSameUTCWeek/index.js'
var weekdays = [
'svētdienā',
'pirmdienā',
'otrdienā',
'trešdienā',
'ceturtdienā',
'piektdienā',
'sestdienā'
]
var formatRelativeLocale = {
lastWeek: function(date, baseDate, options) {
if (isSameUTCWeek(date, baseDate, options)) {
return "eeee 'plkst.' p"
}
var weekday = weekdays[date.getUTCDay()]
return "'Pagājušā' " + weekday + " 'plkst.' p"
},
yesterday: "'Vakar plkst.' p",
today: "'Šodien plkst.' p",
tomorrow: "'Rīt plkst.' p",
nextWeek: function(date, baseDate, options) {
if (isSameUTCWeek(date, baseDate, options)) {
return "eeee 'plkst.' p"
}
var weekday = weekdays[date.getUTCDay()]
return "'Nākamajā' " + weekday + " 'plkst.' p"
},
other: 'P'
}
export default function formatRelative(token, date, baseDate, options) {
var format = formatRelativeLocale[token]
if (typeof format === 'function') {
return format(date, baseDate, options)
}
return format
}
|
[2.0] Fix bug in detection of global Doctrine Cli Configuration finding the empty replacement configuration before the correct one.
git-svn-id: c8c49e1140e1cd2a8fb163f3c2b0f6eec231a71d@7322 625475ce-881a-0410-a577-b389adb331d8 | <?php
require_once 'Doctrine/Common/ClassLoader.php';
$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();
$configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php';
$configuration = null;
if (file_exists($configFile)) {
if ( ! is_readable($configFile)) {
trigger_error(
'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR
);
}
require $configFile;
foreach ($GLOBALS as $configCandidate) {
if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) {
$configuration = $configCandidate;
break;
}
}
}
$configuration = ($configuration) ?: new \Doctrine\Common\Cli\Configuration();
$cli = new \Doctrine\Common\Cli\CliController($configuration);
$cli->run($_SERVER['argv']); | <?php
require_once 'Doctrine/Common/ClassLoader.php';
$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();
$configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php';
$configuration = new \Doctrine\Common\Cli\Configuration();
if (file_exists($configFile)) {
if ( ! is_readable($configFile)) {
trigger_error(
'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR
);
}
require $configFile;
foreach ($GLOBALS as $configCandidate) {
if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) {
$configuration = $configCandidate;
break;
}
}
}
$cli = new \Doctrine\Common\Cli\CliController($configuration);
$cli->run($_SERVER['argv']); |
Remove winston log in uncaught exception handler | // index
// ========
// Pulls in everything needed for use via npm.
'use strict';
var LastDitch = require('./last_ditch.js');
var singleton = new LastDitch();
// The result of requiring this modules is a method that can be called directly with an
// Error object.
module.exports = singleton.go;
// Make the full class available as well as the singleton's `send` method
module.exports.LastDitch = LastDitch;
// `setupTopLevelHandler` makes it very easy to set up a top-level exception handler.
// Set `options.go` to provide your own `LastDitch` instance's `go()` method, or really
// any other method you'd like called (of the signature `function(err, cb)`)
module.exports.setupTopLevelHandler = function setupTopLevelHandler(options) {
options = options || {};
options.go = options.go || singleton.go;
process.on('uncaughtException', function(err) {
options.go(err, function() {
process.exit(1);
});
});
};
| // index
// ========
// Pulls in everything needed for use via npm.
'use strict';
var winston = require('winston');
var LastDitch = require('./last_ditch.js');
var singleton = new LastDitch();
// The result of requiring this modules is a method that can be called directly with an
// Error object.
module.exports = singleton.go;
// Make the full class available as well as the singleton's `send` method
module.exports.LastDitch = LastDitch;
// `setupTopLevelHandler` makes it very easy to set up a top-level exception handler.
// Set `options.go` to provide your own `LastDitch` instance's `go()` method, or really
// any other method you'd like called (of the signature `function(err, cb)`)
module.exports.setupTopLevelHandler = function setupTopLevelHandler(options) {
options = options || {};
options.go = options.go || singleton.go;
process.on('uncaughtException', function(err) {
options.go(err, function() {
winston.info('Error saved! Exiting...');
process.exit(1);
});
});
};
|
Add better docstring to simple_discovery | try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(name, var=None, secure=True):
'''Perform simple discovery and save the discovered ACI locally.
:param name: Name of app.
:type name: str.
:param var: Directory to save app to.
:type var: str.
:param secure: Choose to use HTTPS or HTTP.
:type secure: bool.
:returns: str -- the name of the ACI.
'''
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
| try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(path, var=None, secure=True):
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
|
fix(test-config): Change browser-name case, add browser list | /**
* From where to look for files, starting with the location of this file.
*/
basePath = '../';
/**
* This is the list of file patterns to load into the browser during testing.
*/
files = [
JASMINE,
JASMINE_ADAPTER,
'vendor/angular/angular.js',
'vendor/angular/angular-mocks.js',
'src/**/*.js',
'dist/tmp/**/*.js'
];
/**
* How to report, by default.
*/
reporters = 'dots';
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port = 9018;
runnerPort = 9100;
urlRoot = '/';
/**
* Log at a very low level, but not quite debug.
*/
logLevel = LOG_INFO;
/**
* Disable file watching by default.
*/
autoWatch = false;
/**
* The list of browsers to launch to test on. This is empty by default, so you
* will need to manually open your browser to http://localhot:9018/ for the
* tests to work. Currently available browser names:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*/
browsers = [
'Firefox'
];
| /**
* From where to look for files, starting with the location of this file.
*/
basePath = '../';
/**
* This is the list of file patterns to load into the browser during testing.
*/
files = [
JASMINE,
JASMINE_ADAPTER,
'vendor/angular/angular.js',
'vendor/angular/angular-mocks.js',
'src/**/*.js',
'dist/tmp/**/*.js'
];
/**
* How to report, by default.
*/
reporters = 'dots';
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port = 9018;
runnerPort = 9100;
urlRoot = '/';
/**
* Log at a very low level, but not quite debug.
*/
logLevel = LOG_INFO;
/**
* Disable file watching by default.
*/
autoWatch = false;
/**
* The list of browsers to launch to test on. This is empty by default, so you
* will need to manually open your browser to http://localhot:9018/ for the
* tests to work. You can also just add the executable name of your browser(s)
* here, e.g. 'firefox', 'chrome', 'chromium'.
*/
browsers = [
'firefox'
];
|
Make MNIST inherit from object for py2k. | '''Helper code for theanets unit tests.'''
import numpy as np
import skdata.mnist
class MNIST(object):
NUM_DIGITS = 100
DIGIT_SIZE = 784
def setUp(self):
np.random.seed(3)
mnist = skdata.mnist.dataset.MNIST()
mnist.meta # trigger download if needed.
def arr(n, dtype):
arr = mnist.arrays[n]
return arr.reshape((len(arr), -1)).astype(dtype)
self.images = arr('train_images', 'f')[:MNIST.NUM_DIGITS] / 255.
self.labels = arr('train_labels', 'b')[:MNIST.NUM_DIGITS]
| '''Helper code for theanets unit tests.'''
import numpy as np
import skdata.mnist
class MNIST:
NUM_DIGITS = 100
DIGIT_SIZE = 784
def setUp(self):
np.random.seed(3)
mnist = skdata.mnist.dataset.MNIST()
mnist.meta # trigger download if needed.
def arr(n, dtype):
arr = mnist.arrays[n]
return arr.reshape((len(arr), -1)).astype(dtype)
self.images = arr('train_images', 'f')[:MNIST.NUM_DIGITS] / 255.
self.labels = arr('train_labels', 'b')[:MNIST.NUM_DIGITS]
|
Fix yet another double-pointer bug | package intern
import (
"bufio"
"io"
"sync/atomic"
"unsafe"
)
type sbwriter interface {
WriteByte(byte) error
WriteString(string) (int, error)
}
func (ctx *Context) WriteTo(rawwr io.Writer) error {
w, ok := rawwr.(sbwriter)
var bwr *bufio.Writer
if !ok {
bwr = bufio.NewWriter(rawwr)
w = bwr
}
c := (*state)(atomic.LoadPointer(&ctx.p))
for _, s := range c.r {
_, e := w.WriteString(s)
if e != nil {
return e
}
e = w.WriteByte('\n')
if e != nil {
return e
}
}
if bwr != nil {
return bwr.Flush()
}
return nil
}
func ReadContext(rawrd io.Reader) (Context, error) {
rd := bufio.NewReader(rawrd)
st := newst()
for {
line, _, err := rd.ReadLine()
if err != nil {
if err == io.EOF {
return Context{unsafe.Pointer(st)}, nil
}
return Context{}, err
}
st.addMissing(string(line))
}
}
| package intern
import (
"bufio"
"io"
"sync/atomic"
"unsafe"
)
type sbwriter interface {
WriteByte(byte) error
WriteString(string) (int, error)
}
func (ctx *Context) WriteTo(rawwr io.Writer) error {
w, ok := rawwr.(sbwriter)
var bwr *bufio.Writer
if !ok {
bwr = bufio.NewWriter(rawwr)
w = bwr
}
c := (*state)(atomic.LoadPointer(&ctx.p))
for _, s := range c.r {
_, e := w.WriteString(s)
if e != nil {
return e
}
e = w.WriteByte('\n')
if e != nil {
return e
}
}
if bwr != nil {
return bwr.Flush()
}
return nil
}
func ReadContext(rawrd io.Reader) (Context, error) {
rd := bufio.NewReader(rawrd)
st := newst()
for {
line, _, err := rd.ReadLine()
if err != nil {
if err == io.EOF {
return Context{unsafe.Pointer(&st)}, nil
}
return Context{}, err
}
st.addMissing(string(line))
}
}
|
Improve test coverage of util class. | package uk.me.mjt.ch;
import org.junit.Test;
import static org.junit.Assert.*;
public class UtilTest {
public UtilTest() {
}
@Test
public void testDeepEquals_HashMap_HashMap() {
System.out.println("deepEquals");
MapData a = MakeTestData.makeSimpleThreeEntry();
MapData b = MakeTestData.makeSimpleThreeEntry();
assertTrue(Util.deepEquals(a, b, true));
Node n = a.getNodeById(2L);
n.edgesFrom.remove(0);
assertFalse(Util.deepEquals(a, b, true));
}
@Test
public void testNodeEquality() {
MapData a = MakeTestData.makeSimpleThreeEntry();
MapData b = MakeTestData.makeSimpleThreeEntry();
assertTrue(Util.deepEquals(a.getNodeById(2L), b.getNodeById(2L), true));
assertFalse(Util.deepEquals(a.getNodeById(2L), b.getNodeById(3L), true));
}
}
| package uk.me.mjt.ch;
import java.util.HashMap;
import org.junit.Test;
import static org.junit.Assert.*;
public class UtilTest {
public UtilTest() {
}
@Test
public void testDeepEquals_HashMap_HashMap() {
System.out.println("deepEquals");
MapData a = MakeTestData.makeSimpleThreeEntry();
MapData b = MakeTestData.makeSimpleThreeEntry();
assertTrue(Util.deepEquals(a, b, false));
Node n = a.getNodeById(2L);
n.edgesFrom.remove(0);
assertFalse(Util.deepEquals(a, b, false));
}
}
|
Fix --sample-size error messages lacking newlines | import sys
import psshutil
import random
class ServerPool(list):
def __init__(self, options):
self.options = options
try:
hosts = psshutil.read_host_files(options.host_files, default_user=options.user)
except IOError:
_, e, _ = sys.exc_info()
sys.stderr.write('Could not open hosts file: %s\n' % e.strerror)
sys.exit(1)
if options.host_strings:
for s in options.host_strings:
hosts.extend(psshutil.parse_host_string(s, default_user=options.user))
sample_size = options.sample_size
if sample_size:
if sample_size <= 0:
sys.stderr.write('Sample size cannot be negative\n')
sys.exit(1)
elif sample_size > len(hosts):
sys.stderr.write('Sample size larger than population\n')
sys.exit(1)
hosts = random.sample(hosts, sample_size)
super(ServerPool, self).__init__(hosts)
| import sys
import psshutil
import random
class ServerPool(list):
def __init__(self, options):
self.options = options
try:
hosts = psshutil.read_host_files(options.host_files, default_user=options.user)
except IOError:
_, e, _ = sys.exc_info()
sys.stderr.write('Could not open hosts file: %s\n' % e.strerror)
sys.exit(1)
if options.host_strings:
for s in options.host_strings:
hosts.extend(psshutil.parse_host_string(s, default_user=options.user))
sample_size = options.sample_size
if sample_size:
if sample_size <= 0:
sys.stderr.write('Sample size cannot be negative')
sys.exit(1)
elif sample_size > len(hosts):
sys.stderr.write('Sample size larger than population')
sys.exit(1)
hosts = random.sample(hosts, sample_size)
super(ServerPool, self).__init__(hosts)
|
Use just newline for file terminator. | import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
writer = csv.writer(file, lineterminator='\n')
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
| import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
writer = csv.writer(file)
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
|
Revert year range end back to 2015 (2016 is not over) | #!/usr/bin/env python
import csv
import sys
import figs
def load_counts(filename):
counts = {}
with open(filename) as stream:
stream.readline()
reader = csv.reader(stream)
for row in reader:
year, count = map(int, row)
counts[year] = count
return counts
# read in the data
new_counts = load_counts(sys.argv[1])
old_counts = load_counts(sys.argv[2])
year_range = range(2004, 2015)
new_counts = [new_counts[year] for year in year_range]
old_counts = [-old_counts[year] for year in year_range]
fig = figs.FlowOverTime(year_range, new_counts, old_counts)
fig.save(sys.argv[-1])
| #!/usr/bin/env python
import csv
import sys
import figs
def load_counts(filename):
counts = {}
with open(filename) as stream:
stream.readline()
reader = csv.reader(stream)
for row in reader:
year, count = map(int, row)
counts[year] = count
return counts
# read in the data
new_counts = load_counts(sys.argv[1])
old_counts = load_counts(sys.argv[2])
year_range = range(2004, 2016)
new_counts = [new_counts[year] for year in year_range]
old_counts = [-old_counts[year] for year in year_range]
fig = figs.FlowOverTime(year_range, new_counts, old_counts)
fig.save(sys.argv[-1])
|
Index on ISIN for StockData | define([], function() {
function createStockDataTable() {
alasql('CREATE TABLE IF NOT EXISTS StockData ( \
namn STRING, \
kortnamn STRING,\
isin STRING,\
marknad STRING,\
bransch STRING,\
handlas STRING); \
\
CREATE INDEX isinIndex ON StockData(isin); \
');
}
function loadDataFromFileToTable() {
alasql('TRUNCATE TABLE StockData');
alasql("SELECT * FROM JSON('stockdata.json')",[],function(jsonResult){
alasql('INSERT INTO StockData SELECT namn, kortnamn, isin, marknad, bransch, handlas FROM ?', [jsonResult]);
});
};
function getVärdepapperNamn(isin) {
return alasql('SELECT namn FROM StockData WHERE isin ="' + isin + '"');
}
return {
createStockDataTable: createStockDataTable,
loadDataFromFileToTable: loadDataFromFileToTable,
getVärdepapperNamn: getVärdepapperNamn
};
}); | define([], function() {
function createStockDataTable() {
alasql('CREATE TABLE IF NOT EXISTS StockData ( \
namn STRING, \
kortnamn STRING,\
isin STRING,\
marknad STRING,\
bransch STRING,\
handlas STRING); \
');
}
function loadDataFromFileToTable() {
alasql('TRUNCATE TABLE StockData');
alasql("SELECT * FROM JSON('stockdata.json')",[],function(jsonResult){
alasql('INSERT INTO StockData SELECT namn, kortnamn, isin, marknad, bransch, handlas FROM ?', [jsonResult]);
});
};
function getVärdepapperNamn(isin) {
return alasql('SELECT namn FROM StockData WHERE isin ="' + isin + '"');
}
return {
createStockDataTable: createStockDataTable,
loadDataFromFileToTable: loadDataFromFileToTable,
getVärdepapperNamn: getVärdepapperNamn
};
}); |
Use jQuery objects for appending inputs | define('media-input', ['jquery', 'z'], function($, z) {
function createInput($section) {
$section.append($('<input>', {type: 'text', placeholder: $section.attr('data-placeholder')}));
}
z.page.on('loaded', function() {
$('.fallback').each(function() {
createInput($(this));
});
})
z.page.on('input', '.screenshots input[type=text], .videos input[type=text]', function(e) {
var $input = $(e.target);
var $allInputs = $input.parent().children('input[type=text]');
var $emptyInputs = $allInputs.filter(function() {
return !$(this).val();
});
if ($input.val() && $emptyInputs.length === 0) {
createInput($input.parent());
} else {
// So that at any point in time, there will be exactly
// ONE empty input field for user to enter more URLs.
$emptyInputs.slice(1).remove();
}
});
});
| define('media-input', ['jquery', 'z'], function($, z) {
function createInput($section) {
$section.append('<input type="text" placeholder="' + $section.attr('data-placeholder') + '">');
}
z.page.on('loaded', function() {
$('.fallback').each(function() {
createInput($(this));
});
})
z.page.on('input', '.screenshots input[type=text], .videos input[type=text]', function(e) {
var $input = $(e.target);
var $allInputs = $input.parent().children('input[type=text]');
var $emptyInputs = $allInputs.filter(function() {
return !$(this).val();
});
if ($input.val() && $emptyInputs.length === 0) {
createInput($input.parent());
} else {
// So that at any point in time, there will be exactly
// ONE empty input field for user to enter more URLs.
$emptyInputs.slice(1).remove();
}
});
});
|
Prepare for release of 8.3dev-602. | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.22 2007/07/31 06:05:43 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public final static int buildNumber = 602;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
| /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.21 2006/12/01 12:06:21 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public final static int buildNumber = 601;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
|
Fix unit test Kanbanize module loading | <?php
$env = getenv('APPLICATION_ENV') ? : "local";
return array(
'modules' => array(
'DoctrineModule',
'DoctrineORMModule',
'ProophEventStoreModule',
'Application',
'Accounting',
'TaskManagement',
'ZendOAuth2',
'User',
),
'module_listener_options' => array(
'module_paths' => array(
__DIR__.'/../../src/module',
__DIR__.'/../../src/vendor',
),
'config_glob_paths' => array(
__DIR__.'/../../src/config/autoload/{,*.}{'.$env.',global}.php',
),
)
); | <?php
$env = getenv('APPLICATION_ENV') ? : "local";
return array(
'modules' => array(
'DoctrineModule',
'DoctrineORMModule',
'ProophEventStoreModule',
'Application',
'Accounting',
'TaskManagement',
'ZendOAuth2',
'User',
'Kanbanize'
),
'module_listener_options' => array(
'module_paths' => array(
__DIR__.'/../../src/module',
__DIR__.'/../../src/vendor',
),
'config_glob_paths' => array(
__DIR__.'/../../src/config/autoload/{,*.}{'.$env.',global}.php',
),
)
); |
Use Node resolving mechanism to locate Prism CSS | var Prism = require('prismjs');
var cheerio = require('cheerio');
var path = require('path');
var cssFile = require.resolve('prismjs/themes/prism.css');
var cssDirectory = path.dirname(cssFile);
module.exports = {
book: {
assets: cssDirectory,
css: [path.basename(cssFile)]
},
hooks: {
page: function (page) {
page.sections.forEach(function (section) {
var $ = cheerio.load(section.content);
$('code').each(function() {
var text = $(this).text();
var highlighted = Prism.highlight(text, Prism.languages.javascript);
$(this).html(highlighted);
});
section.content = $.html();
});
return page;
}
}
};
| var Prism = require('prismjs');
var cheerio = require('cheerio');
module.exports = {
book: {
assets: './node_modules/prismjs/themes',
css: [
'prism.css'
]
},
hooks: {
page: function (page) {
page.sections.forEach(function (section) {
var $ = cheerio.load(section.content);
$('code').each(function() {
var text = $(this).text();
var highlighted = Prism.highlight(text, Prism.languages.javascript);
$(this).html(highlighted);
});
section.content = $.html();
});
return page;
}
}
};
|
Fix a small bug related to onLoadHooks | /* boilerUtils
* This object holds functions that assist Boilerplate
*/
var boilerUtils = {}
boilerUtils.renderAction = function renderAction (action) {
return {
'string': altboiler.getTemplate,
'function': action
}[typeof action](action)
},
boilerUtils.getBoilerTemplateData = function getTemplateData (includes, content, onLoadHooks) {
return {
script: Assets.getText('assets/loader.js'),
styles: Assets.getText('assets/styles.css'),
content: content,
head: '"' + encodeURIComponent(includes['head'].join('\n')) + '"',
body: '"' + encodeURIComponent(includes['body'].join('\n')) + '"',
jsIncludes: EJSON.stringify(includes['js']),
onLoadHooks: '[' + boilerUtils.parseOnLoadHooks(onLoadHooks).join(',') + ']',
meteorRuntimeConfig: EJSON.stringify(__meteor_runtime_config__ || {})
}
},
/* boilerUtils.parseOnLoadHooks(hooksArr)
* `hooksArr` - An array of hooks to parse
* Maps through the array;
* simply executing and returning `toString`
*/
boilerUtils.parseOnLoadHooks = function parseOnLoadHooks (hooksArr) {
return _.invoke(hooksArr, 'toString')
}
altboilerScope = altboilerScope || {}
altboilerScope._boilerUtils = boilerUtils | /* boilerUtils
* This object holds functions that assist Boilerplate
*/
var boilerUtils = {}
boilerUtils.renderAction = function renderAction (action) {
return {
'string': altboiler.getTemplate,
'function': action
}[typeof action](action)
},
boilerUtils.getBoilerTemplateData = function getTemplateData (includes, content, options) {
return {
script: Assets.getText('assets/loader.js'),
styles: Assets.getText('assets/styles.css'),
content: content,
head: '"' + encodeURIComponent(includes['head'].join('\n')) + '"',
body: '"' + encodeURIComponent(includes['body'].join('\n')) + '"',
jsIncludes: EJSON.stringify(includes['js']),
onLoadHooks: '[' + boilerUtils.parseOnLoadHooks(options.onLoad).join(',') + ']',
meteorRuntimeConfig: EJSON.stringify(__meteor_runtime_config__ || {})
}
},
/* boilerUtils.parseOnLoadHooks(hooksArr)
* `hooksArr` - An array of hooks to parse
* Maps through the array;
* simply executing and returning `toString`
*/
boilerUtils.parseOnLoadHooks = function parseOnLoadHooks (hooksArr) {
return _.invoke(hooksArr, 'toString')
}
altboilerScope = altboilerScope || {}
altboilerScope._boilerUtils = boilerUtils |
Change Preact from React :( | 'use strict';
const path = require('path');
const webpack = require('webpack');
const validator = require('webpack-validator');
module.exports = validator({
entry: path.join(__dirname, 'src', 'js', 'index.js'),
output: {
path: path.join(__dirname, 'build', 'js'),
filename: 'main.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
}
})
],
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules|src\/server/,
include: /src/
}]
}
// ,
// resolve: {
// alias: {
// 'react': 'preact-compat',
// 'react-dom': 'preact-compat'
// }
// }
});
| 'use strict';
const path = require('path');
const webpack = require('webpack');
const validator = require('webpack-validator');
module.exports = validator({
entry: path.join(__dirname, 'src', 'js', 'index.js'),
output: {
path: path.join(__dirname, 'build', 'js'),
filename: 'main.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
}
})
],
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules|src\/server/,
include: /src/
}]
},
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat'
}
}
});
|
Remove use Vimeo and add Vimeo\Vimeo. | <?php
/**
* Copyright 2013 Vimeo
*
* 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.
*/
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once('vendor/autoload.php');
$config = json_decode(file_get_contents('./config.json'), true);
$lib = new Vimeo\Vimeo($config['client_id'], $config['client_secret']);
$user = $lib->request('/users/dashron');
print_r($user);
| <?php
/**
* Copyright 2013 Vimeo
*
* 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.
*/
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once('vendor/autoload.php');
use Vimeo;
$config = json_decode(file_get_contents('./config.json'), true);
$lib = new Vimeo($config['client_id'], $config['client_secret']);
$user = $lib->request('/users/dashron');
print_r($user);
|
Move schema salad minimum version back to earlier version. | #!/usr/bin/env python
import os
import sys
import shutil
import setuptools.command.egg_info as egg_info_cmd
from setuptools import setup, find_packages
SETUP_DIR = os.path.dirname(__file__)
README = os.path.join(SETUP_DIR, 'README.rst')
try:
import gittaggers
tagger = gittaggers.EggInfoFromGit
except ImportError:
tagger = egg_info_cmd.egg_info
setup(name='cwltest',
version='1.0',
description='Common workflow language testing framework',
long_description=open(README).read(),
author='Common workflow language working group',
author_email='common-workflow-language@googlegroups.com',
url="https://github.com/common-workflow-language/cwltest",
download_url="https://github.com/common-workflow-language/cwltest",
license='Apache 2.0',
packages=["cwltest"],
install_requires=[
'schema-salad >= 1.14',
'typing >= 3.5.2' ],
tests_require=[],
entry_points={
'console_scripts': [ "cwltest=cwltest:main" ]
},
zip_safe=True,
cmdclass={'egg_info': tagger},
)
| #!/usr/bin/env python
import os
import sys
import shutil
import setuptools.command.egg_info as egg_info_cmd
from setuptools import setup, find_packages
SETUP_DIR = os.path.dirname(__file__)
README = os.path.join(SETUP_DIR, 'README.rst')
try:
import gittaggers
tagger = gittaggers.EggInfoFromGit
except ImportError:
tagger = egg_info_cmd.egg_info
setup(name='cwltest',
version='1.0',
description='Common workflow language testing framework',
long_description=open(README).read(),
author='Common workflow language working group',
author_email='common-workflow-language@googlegroups.com',
url="https://github.com/common-workflow-language/cwltest",
download_url="https://github.com/common-workflow-language/cwltest",
license='Apache 2.0',
packages=["cwltest"],
install_requires=[
'schema-salad >= 1.17',
'typing >= 3.5.2' ],
tests_require=[],
entry_points={
'console_scripts': [ "cwltest=cwltest:main" ]
},
zip_safe=True,
cmdclass={'egg_info': tagger},
)
|
Automate Transfers: Change default metadata added | #!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
dc_id, _, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
| #!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
_, dc_id, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
|
Comment out the file exist check | <?php
// If the later function cannot handle autoloading, uncomment the default one as well
// set_include_path(get_include_path().PATH_SEPARATOR.dirname(__DIR__));
// spl_autoload_extensions('.php');
//
// // spl_autoload needs to be passed because of PHPUnit
// spl_autoload_register('spl_autoload');
// This is used to handle Linux which is case sensitive
spl_autoload_register(function ($className) {
$className = str_replace('\\', '/', $className);
$file = dirname(__DIR__) . DIRECTORY_SEPARATOR . $className . '.php';
// leave the file_exists commented in production, for debugging add the file_exists check
//if (file_exists($file)) {
require_once $file;
//} else {
// (new \CodeJetter\core\ErrorHandler())->logError("Class file '{$file}' does not exist");
//}
});
| <?php
// If the later function cannot handle autoloading, uncomment the default one as well
// set_include_path(get_include_path().PATH_SEPARATOR.dirname(__DIR__));
// spl_autoload_extensions('.php');
//
// // spl_autoload needs to be passed because of PHPUnit
// spl_autoload_register('spl_autoload');
// This is used to handle Linux which is case sensitive
spl_autoload_register(function ($className) {
$className = str_replace('\\', '/', $className);
$file = dirname(__DIR__) . DIRECTORY_SEPARATOR . $className . '.php';
if (file_exists($file)) {
require_once $file;
} else {
(new \CodeJetter\core\ErrorHandler())->logError("Class file '{$file}' does not exist");
}
});
|
Add a PriceRule test if match is attempted when stock is not in the exchange. | from datetime import datetime
from unittest import TestCase
from rule import PriceRule
from stock import Stock
class TestPriceRule(TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 11)
cls.exchange = {"GOOG": goog}
def test_a_PriceRule_matches_when_it_meets_the_condition(self):
"""Tests if true is returned when an exchange matches a rule.
"""
rule = PriceRule("GOOG", lambda stock: stock.price > 10)
self.assertTrue(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_condition_is_not_met(self):
"""Tests if false is returned when an exchange does not match a rule.
"""
rule = PriceRule("GOOG", lambda stock: stock.price < 10)
self.assertFalse(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_stock_is_not_in_the_exchange(self):
"""Tests if false is returned if a match is attempted when the stock is not in the exchange.
"""
rule = PriceRule("MSFT", lambda stock: stock.price > 10)
self.assertFalse(rule.matches(self.exchange))
| from datetime import datetime
from unittest import TestCase
from rule import PriceRule
from stock import Stock
class TestPriceRule(TestCase):
@classmethod
def setUpClass(cls):
goog = Stock("GOOG")
goog.update(datetime(2014, 2, 10), 11)
cls.exchange = {"GOOG": goog}
def test_a_PriceRule_matches_when_it_meets_the_condition(self):
"""Tests if true is returned when an exchange matches a rule.
"""
rule = PriceRule("GOOG", lambda stock: stock.price > 10)
self.assertTrue(rule.matches(self.exchange))
def test_a_PriceRule_is_False_if_the_condition_is_not_met(self):
"""Tests if false is returned when an exchange does not match a rule.
"""
rule = PriceRule("GOOG", lambda stock: stock.price < 10)
self.assertFalse(rule.matches(self.exchange))
|
Remove redirect again, it's somehow causing the JS issue and it won't work for other media types | from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r'^upload/', 'filebrowser.views.upload', name="fb_upload"),
url(r'^rename/$', 'filebrowser.views.rename', name="fb_rename"),
url(r'^delete/$', 'filebrowser.views.delete', name="fb_delete"),
url(r'^versions/$', 'filebrowser.views.versions', name="fb_versions"),
url(r'^check_file/$', 'filebrowser.views._check_file', name="fb_check"),
url(r'^upload_file/$', 'filebrowser.views._upload_file', name="fb_do_upload"),
)
| from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1', 'permanent': True}, name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r'^upload/', 'filebrowser.views.upload', name="fb_upload"),
url(r'^rename/$', 'filebrowser.views.rename', name="fb_rename"),
url(r'^delete/$', 'filebrowser.views.delete', name="fb_delete"),
url(r'^versions/$', 'filebrowser.views.versions', name="fb_versions"),
url(r'^check_file/$', 'filebrowser.views._check_file', name="fb_check"),
url(r'^upload_file/$', 'filebrowser.views._upload_file', name="fb_do_upload"),
)
|
Fix link opened in background tab | function documentClick(event) {
var target = event.target;
// Open non-javascript links clicked in background tabs.
var targetClickedIsAnchor = target.nodeName === 'A';
if (targetClickedIsAnchor && target.href && target.href !== 'javascript:void(0)') {
openBackgroundTab(target.href);
event.preventDefault();
return;
}
// Avoid collapsing comment when there is a selection.
if (window.getSelection().toString() !== '') {
return;
}
// Toggle comment collapse when comment is clicked.
var targetParents = getElementParents(target, '.comment');
if (target.classList.contains('comment') || targetParents.length ) {
var comment = getElementParents(target, '.athing')[0];
var commentToggle = comment.querySelector('.togg');
commentToggle.click();
}
}
document.addEventListener('click', documentClick);
| function documentClick(event) {
var target = event.target;
// Open non-javascript links clicked in background tabs.
var targetClickedIsAnchor = target.nodeName === 'A';
var anchorUrl = target.getAttribute('href');
if (targetClickedIsAnchor && anchorUrl !== 'javascript:void(0)') {
openBackgroundTab(anchorUrl);
event.preventDefault();
return;
}
// Avoid collapsing comment when there is a selection.
if (window.getSelection().toString() !== '') {
return;
}
// Toggle comment collapse when comment is clicked.
var targetParents = getElementParents(target, '.comment');
if (target.classList.contains('comment') || targetParents.length ) {
var comment = getElementParents(target, '.athing')[0];
var commentToggle = comment.querySelector('.togg');
commentToggle.click();
}
}
document.addEventListener('click', documentClick);
|
Delete FirebaseApp on server shutdown | package com.google.slurp.servlets;
import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
/**
* Servlet context listener that is looked for whenever the backend server
* receives a startup or shutdown request.
*/
@WebListener
public class ServerListener implements ServletContextListener {
public FirebaseApp app;
/**
* {@inheritDoc}
*
* Initialize the Firebase Admin app for the server.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("Server initialized and starting up...");
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.build();
app = FirebaseApp.initializeApp(options);
} catch (IOException error) {
System.err.println("Error obtaining the Application Default Credentials:");
error.printStackTrace();
}
}
/**
* {@inheritDoc}
*
* Delete the Firebase Admin app.
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("Server destroyed and shutting down...");
app.delete();
}
}
| package com.google.slurp.servlets;
import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
/**
* Servlet context listener that is looked for whenever the backend server
* receives a startup or shutdown request.
*/
@WebListener
public class ServerListener implements ServletContextListener {
/**
* {@inheritDoc}
*
* Initialize the Firebase Admin app for the server.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("Server initialized and starting up...");
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.build();
FirebaseApp.initializeApp(options);
} catch (IOException error) {
System.err.println("Error obtaining the Application Default Credentials:");
error.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("Server destroyed and shutting down...");
}
}
|
Support multiple documents in single YAML file | /*
* Copyright (c) 2016-2017 by OpenText Corporation. All Rights Reserved.
*/
package com.opentext.ia.sdk.configurer;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
public class YamlConfiguration {
private final Map<String, String> map = new HashMap<>();
public YamlConfiguration(File yaml) throws IOException {
try (InputStream input = new FileInputStream(yaml)) {
expand(input);
}
}
public YamlConfiguration(InputStream yaml) throws IOException {
expand(yaml);
}
public YamlConfiguration(String yaml) throws IOException {
try (InputStream input = new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))) {
expand(input);
}
}
@SuppressWarnings("unchecked")
private void expand(InputStream input) {
Map<String, Object> source = new HashMap<>();
for (Object data : new Yaml().loadAll(input)) {
source.putAll((Map<String, Object>)data);
}
expand(source);
}
@SuppressWarnings("PMD.UnusedFormalParameter")
private void expand(Map<String, Object> source) {
// TODO: Expand the YAML in [source] into [map]
}
public Map<String, String> toMap() {
return map;
}
}
| /*
* Copyright (c) 2016-2017 by OpenText Corporation. All Rights Reserved.
*/
package com.opentext.ia.sdk.configurer;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
public class YamlConfiguration {
private final Map<String, String> map = new HashMap<>();
public YamlConfiguration(File yaml) throws IOException {
try (InputStream input = new FileInputStream(yaml)) {
expand(input);
}
}
public YamlConfiguration(InputStream yaml) throws IOException {
expand(yaml);
}
public YamlConfiguration(String yaml) throws IOException {
try (InputStream input = new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))) {
expand(input);
}
}
@SuppressWarnings("unchecked")
private void expand(InputStream input) {
expand((Map<String, Object>)new Yaml().load(input));
}
@SuppressWarnings("PMD.UnusedFormalParameter")
private void expand(Map<String, Object> source) {
// TODO: Expand the YAML in [source] into [map]
}
public Map<String, String> toMap() {
return map;
}
}
|
Add handler to main app | #!/usr/bin/env python
import os
import tornado
from curldrop import StreamHandler, config
from contextlib import closing
import sqlite3
schema = '''drop table if exists files;
create table files (
id integer primary key autoincrement,
file_id text not null,
timestamp integer not null,
ip text not null,
originalname text not null
);'''
if not os.path.isfile(config['DATABASE']):
with closing(sqlite3.connect(config['DATABASE'])) as db:
db.cursor().executescript(schema)
db.commit()
if not os.path.isdir(config['UPLOADDIR']):
os.makedirs(config['UPLOADDIR'])
application = tornado.web.Application([
(r"/list_files", FileListHandler),
(r"/(.*)", StreamHandler),
])
server = tornado.httpserver.HTTPServer(application,
max_buffer_size=config["SERVERBUFF"])
server.listen(config["PORT"])
tornado.ioloop.IOLoop.instance().start()
| #!/usr/bin/env python
import os
import tornado
from curldrop import StreamHandler, config
from contextlib import closing
import sqlite3
schema = '''drop table if exists files;
create table files (
id integer primary key autoincrement,
file_id text not null,
timestamp integer not null,
ip text not null,
originalname text not null
);'''
if not os.path.isfile(config['DATABASE']):
with closing(sqlite3.connect(config['DATABASE'])) as db:
db.cursor().executescript(schema)
db.commit()
if not os.path.isdir(config['UPLOADDIR']):
os.makedirs(config['UPLOADDIR'])
application = tornado.web.Application([
(r"/(.*)", StreamHandler),
])
server = tornado.httpserver.HTTPServer(application,
max_buffer_size=config["SERVERBUFF"])
server.listen(config["PORT"])
tornado.ioloop.IOLoop.instance().start()
|
Fix VTFMS protocol unit tests | package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class VtfmsProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
VtfmsProtocolDecoder decoder = new VtfmsProtocolDecoder(new VtfmsProtocol());
verifyPosition(decoder, text(
"(865733028143493,00I76,00,000,,,,,A,133755,210617,10.57354,077.24912,SW,000,00598,00000,K,0017368,1,12.7,,,0.000,,,0,0,0,0,1,1,0,,)074"));
verifyPosition(decoder, text(
"(863071010087648,0HK44,00,000,14,2,9,,A,114946,180313,11.0244,076.9768,282,000,00000,00000,K,0000128,1,12.8,,200,2.501,,4.001,0,0,0,0,0,0,0,,)105"));
}
}
| package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class VtfmsProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
VtfmsProtocolDecoder decoder = new VtfmsProtocolDecoder(new VtfmsProtocol());
verifyNull(decoder, text(
"(865733028143493,00I76,00,000,,,,,A,133755,210617,10.57354,077.24912,SW,000,00598,00000,K,0017368,1,12.7,,,0.000,,,0,0,0,0,1,1,0,,)074"));
verifyPosition(decoder, text(
"(863071010087648,0HK44,00,000,14,2,9,,A,114946,180313,11.0244,076.9768,282,000,00000,00000,K,0000128,1,12.8,,200,2.501,,4.001,0,0,0,0,0,0,0,,)105"));
}
}
|
Bump version to 1.0.0 for first release | Package.describe({
name: 'klaussner:svelte',
version: '1.0.0',
summary: 'Use the magical disappearing UI framework in Meteor',
git: 'https://github.com/klaussner/meteor-svelte.git'
});
Package.registerBuildPlugin({
name: 'svelte-compiler',
use: ['caching-compiler@1.1.9', 'babel-compiler@6.13.0', 'ecmascript@0.6.1'],
sources: [
'plugin.js'
],
npmDependencies: {
htmlparser2: '3.9.2',
'source-map': '0.5.6',
'svelte-es5-meteor': '0.1.3'
}
});
Package.onUse(function (api) {
api.use('isobuild:compiler-plugin@1.0.0');
api.imply('modules@0.7.7');
api.imply('ecmascript-runtime@0.3.15');
api.imply('babel-runtime@1.0.1');
api.imply('promise@0.8.8');
});
| Package.describe({
name: 'klaussner:svelte',
version: '0.0.1',
summary: 'Use the magical disappearing UI framework in Meteor',
git: 'https://github.com/klaussner/meteor-svelte.git'
});
Package.registerBuildPlugin({
name: 'svelte-compiler',
use: ['caching-compiler@1.1.9', 'babel-compiler@6.13.0', 'ecmascript@0.6.1'],
sources: [
'plugin.js'
],
npmDependencies: {
htmlparser2: '3.9.2',
'source-map': '0.5.6',
'svelte-es5-meteor': '0.1.3'
}
});
Package.onUse(function (api) {
api.use('isobuild:compiler-plugin@1.0.0');
api.imply('modules@0.7.7');
api.imply('ecmascript-runtime@0.3.15');
api.imply('babel-runtime@1.0.1');
api.imply('promise@0.8.8');
});
|
Kill "Ja existeix una factura amb el mateix.." too | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")])
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Ja existeix una factura amb el mateix origen")])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
total = len(imp_del_ids)
n = 0
for imp_del_id in imp_del_ids:
try:
imp_obj.unlink([imp_del_id])
n +=1
print "%d/%d" % (n,total)
except Exception, e:
print e
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")])
#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")])
imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")])
total = len(imp_del_ids)
n = 0
for imp_del_id in imp_del_ids:
try:
imp_obj.unlink([imp_del_id])
n +=1
print "%d/%d" % (n,total)
except Exception, e:
print e
|
[REF] Fix notice with $dir_handle not being defined, improve code formatting
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@64294 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
/**
* @param $installer
* @return void|bool
*/
function upgrade_20170127_remove_templates_c_tiki($installer)
{
$dir_handle = false;
$dirname = 'templates_c';
if (is_dir($dirname)) {
$dir_handle = opendir($dirname);
}
if (! $dir_handle) {
return false;
}
while ($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (! is_dir($dirname . "/" . $file)) {
unlink($dirname . "/" . $file);
} else {
delete_directory($dirname . '/' . $file);
}
}
}
closedir($dir_handle);
rmdir($dirname);
}
| <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
/**
* @param $installer
*/
function upgrade_20170127_remove_templates_c_tiki($installer)
{
$dirname = 'templates_c';
if (is_dir($dirname)) {
$dir_handle = opendir($dirname);
}
if (!$dir_handle) {
return false;
}
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
}
|
Add error handling to chekcing package.json | #! /usr/bin/env node
const args = require('./args') // TODO
const path = require('path')
const { sendQuery, readFile, checkPath, REPL } = require('./src/api')
const { pullHeaders, colorResponse } = require('./src/util')
args
.option('header', 'HTTP request header')
.option('baseUrl', 'Base URL for sending HTTP requests')
const flags = args.parse(process.argv)
if (!flags.help && !flags.version) {
let config
let schema
try {
config = require(path.join(process.cwd(), 'package.json'))
} catch (e) {}
try {
schema = require(path.join(process.cwd(), (config && config.schema) || 'schema'))
} catch (e) {
switch (e.code) {
case 'MODULE_NOT_FOUND':
console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
break
default: console.log(e)
}
process.exit()
}
const options = Object.assign({}, config, pullHeaders(flags), { baseURL: flags.baseUrl })
if (args.sub && args.sub.length) {
checkPath(path.join(__dirname, args.sub[0]))
.then(readFile)
.catch(() => args.sub[0])
.then(sendQuery(schema, options))
.then(colorResponse)
.then(console.log)
.catch(console.log)
.then(() => process.exit())
} else {
// REPL
REPL(schema, options)
}
}
| #! /usr/bin/env node
const args = require('./args') // TODO
const path = require('path')
const { graphql: config } = require(path.join(process.cwd(), 'package.json'))
const { sendQuery, readFile, checkPath, REPL } = require('./src/api')
const { pullHeaders, colorResponse } = require('./src/util')
args
.option('header', 'HTTP request header')
.option('baseUrl', 'Base URL for sending HTTP requests')
const flags = args.parse(process.argv)
if (!flags.help && !flags.version) {
let schema
try {
schema = require(path.join(process.cwd(), (config && config.schema) || 'schema.js'))
} catch (e) {
console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
process.exit()
}
const options = Object.assign({}, config, pullHeaders(flags), { baseURL: flags.baseUrl })
if (args.sub && args.sub.length) {
checkPath(path.join(__dirname, args.sub[0]))
.then(readFile)
.catch(() => args.sub[0])
.then(sendQuery(schema, options))
.then(colorResponse)
.then(console.log)
.catch(console.log)
.then(() => process.exit())
} else {
// REPL
REPL(schema, options)
}
}
|
Replace `while True` with `while 1` for more web scale sauce.
In Python 2.x, True is not a keyword, so it can be reassigned. Compiler replaces `while 1` loop with a single jump, so it is faster by 10%.
http://www.reddit.com/r/Python/comments/ppote/how_would_you_explain_a_performance_gap_between/ | from gevent.server import StreamServer
import os
def mangodb(socket, address):
socket.sendall('HELLO\r\n')
client = socket.makefile()
output = open('/dev/null', 'w')
while 1:
line = client.readline()
if not line:
break
cmd_bits = line.split(' ', 1)
cmd = cmd_bits[0]
if cmd == 'BYE':
break
if len(cmd_bits) > 1:
output.write(cmd_bits[1])
if os.environ.get('MANGODB_DURABLE', False):
output.flush()
os.fsync(output.fileno())
client.write('OK' + os.urandom(1024) + '\r\n')
client.flush()
if __name__ == '__main__':
server = StreamServer(('0.0.0.0', 27017), mangodb)
print ('Starting MangoDB on port 27017')
server.serve_forever()
| from gevent.server import StreamServer
import os
def mangodb(socket, address):
socket.sendall('HELLO\r\n')
client = socket.makefile()
output = open('/dev/null', 'w')
while True:
line = client.readline()
if not line:
break
cmd_bits = line.split(' ', 1)
cmd = cmd_bits[0]
if cmd == 'BYE':
break
if len(cmd_bits) > 1:
output.write(cmd_bits[1])
if os.environ.get('MANGODB_DURABLE', False):
output.flush()
os.fsync(output.fileno())
client.write('OK' + os.urandom(1024) + '\r\n')
client.flush()
if __name__ == '__main__':
server = StreamServer(('0.0.0.0', 27017), mangodb)
print ('Starting MangoDB on port 27017')
server.serve_forever()
|
Fix pathHead to ensure console works under that path | #!/usr/bin/env node
var Console = require("./console")
, arg, options = {
workDir: process.cwd()
, consolePath: "/roil/"
, port : 3000
}
, args = process.argv.slice(2)
, connect = require("connect")
, server = connect.createServer()
, c = new Console()
while (arg = args.shift()) {
switch (arg) {
case "-d":
case "--work-dir":
options.workDir = args.shift()
break;
case "-p":
case "--port":
options.port = parseInt(args.shift(), 10)
break;
case "-c":
case "--console-path":
options.consolePath = args.shift()
break;
case "--debug":
options.debug = true
break;
defaut:
throw new Error("Unknown argument: " + arg)
}
}
c.attach(server, options)
server.listen(options.port)
if (options.debug) {
var context = require("repl").start().context
context.c = c
context.s = server
c._socketListener.on("connection", function(client) {
client.on("message", function(msg) {
console.log(msg)
})
})
process.on("uncaughtException", function(e) {
console.log(e.stack || e.message)
})
}
| #!/usr/bin/env node
var Console = require("./console")
, arg, options = {
workDir: process.cwd()
, consolePath: "/roil"
, port : 3000
}
, args = process.argv.slice(2)
, connect = require("connect")
, server = connect.createServer()
, c = new Console()
while (arg = args.shift()) {
switch (arg) {
case "-d":
case "--work-dir":
options.workDir = args.shift()
break;
case "-p":
case "--port":
options.port = parseInt(args.shift(), 10)
break;
case "-c":
case "--console-path":
options.consolePath = args.shift()
break;
case "--debug":
options.debug = true
break;
defaut:
throw new Error("Unknown argument: " + arg)
}
}
c.attach(server, options)
server.listen(options.port)
if (options.debug) {
var context = require("repl").start().context
context.c = c
context.s = server
c._socketListener.on("connection", function(client) {
client.on("message", function(msg) {
console.log(msg)
})
})
process.on("uncaughtException", function(e) {
console.log(e.stack || e.message)
})
}
|
Add basic page request exception handling | #!/usr/bin/python3.4
from flask import Flask, render_template, url_for, Markup, abort
from flask.ext.libsass import *
import pkg_resources
import markdown
app=Flask(__name__)
Sass(
{'app': 'scss/app.scss'},
app,
url_path='/static/css',
include_paths=[pkg_resources.resource_filename('views', 'scss')],
output_style='compressed'
)
@app.route('/<page>')
def get_page(page):
try:
md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8')
html=Markup(markdown.markdown(md.read(), output_format='html5'))
md.close()
if page=='index':
return render_template('page.html', content=html)
return render_template('page.html', content=html, title=page)
except OSError:
abort(404)
@app.route('/')
def index():
return get_page('index')
if __name__=='__main__':
app.run()
| #!/usr/bin/python3.4
from flask import Flask, render_template, url_for, Markup
from flask.ext.libsass import *
import pkg_resources
import markdown
app=Flask(__name__)
Sass(
{'app': 'scss/app.scss'},
app,
url_path='/static/css',
include_paths=[pkg_resources.resource_filename('views', 'scss')],
output_style='compressed'
)
@app.route('/<page>')
def get_page(page):
md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8')
html=Markup(markdown.markdown(md.read(), output_format='html5'))
md.close()
if page=='index':
return render_template('page.html', content=html)
return render_template('page.html', content=html, title=page)
@app.route('/')
def index():
return get_page('index')
if __name__=='__main__':
app.run()
|
Change tryserver.chromium.perf to watch chrome-try/try-perf
so that perf bisect tryjobs are isolated to their own repo to avoid
cross contamination.
BUG=416009
Review URL: https://codereview.chromium.org/588353002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292078 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-perf'
last_good_url = base_app_url + '/lkgr'
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try'
last_good_url = base_app_url + '/lkgr'
|
Change function names to camelCase | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = { 'command': command, 'parameters': parameters }
if timeout is not None:
json['timeout'] = timeout
when(response).json().thenReturn({ 'command': command, 'timeout': timeout, 'parameters': parameters })
return response
def setResponse(self, response):
when(self.server._requests).get('').thenReturn(response)
def setUp(self):
self.server = Server('')
self.server._requests = mock()
def tearDown(self):
pass
def testGet(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get()
self.assertIsInstance(response, Copy)
self.assertEqual(response.parameters, {'src': 'source', 'dst': 'destination', })
self.assertIs(response.timeout, 10)
def testGetCommandNotFound(self):
self.setResponse(self.createCommandResponse('Not found command'))
self.assertRaises(CommandNotFoundException, self.server.get) | from nose.tools import *
from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class MyTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = { 'command': command, 'parameters': parameters }
if timeout is not None:
json['timeout'] = timeout
when(response).json().thenReturn({ 'command': command, 'timeout': timeout, 'parameters': parameters })
return response
def setResponse(self, response):
when(self.server._requests).get('').thenReturn(response)
def setUp(self):
self.server = Server('')
self.server._requests = mock()
def tearDown(self):
pass
def test_get(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get()
self.assertIsInstance(response, Copy)
self.assertEqual(response.parameters, {'src': 'source', 'dst': 'destination', })
self.assertIs(response.timeout, 10)
def test_get_command_not_found(self):
self.setResponse(self.createCommandResponse('Not found command'))
self.assertRaises(CommandNotFoundException, self.server.get) |
Add sourceMap to babel-emotion-plugin config | const { injectBabelPlugin, getLoader, getBabelLoader, loaderNameMatches } = require('react-app-rewired')
module.exports = function override(config, env) {
// Inject all babel plugins before rewiring typescript
// Inject babel-plugin-emotion
config = injectBabelPlugin(
[
'emotion',
{
autoLabel: true,
hoist: env === 'production',
labelFormat: '[filename]--[local]',
sourceMap: env !== 'production'
}
],
config
)
// Rewire typescript with our rewired babel config
const babelLoader = getBabelLoader(config.module.rules)
const tsLoader = getLoader(config.module.rules, rule => /ts|tsx/.test(rule.test))
tsLoader.use.unshift({
loader: babelLoader.loader,
options: babelLoader.options
})
return config
}
| const { injectBabelPlugin, getLoader, getBabelLoader, loaderNameMatches } = require('react-app-rewired')
module.exports = function override(config, env) {
// Inject all babel plugins before rewiring typescript
// Inject babel-plugin-emotion
config = injectBabelPlugin(
[
'emotion',
{
autoLabel: true,
hoist: env === 'production',
labelFormat: '[filename]--[local]'
}
],
config
)
// Rewire typescript with our rewired babel config
const babelLoader = getBabelLoader(config.module.rules)
const tsLoader = getLoader(config.module.rules, rule => /ts|tsx/.test(rule.test))
tsLoader.use.unshift({
loader: babelLoader.loader,
options: babelLoader.options
})
return config
}
|
Remove redundant source from PMO
This removes the redundant source that was left over from the DoneJS 2
guide. Fixes #1156 | import { Component } from 'can';
import './list.less';
import view from './list.stache';
import Restaurant from '~/models/restaurant';
const RestaurantList = Component.extend({
tag: 'pmo-restaurant-list',
view,
ViewModel: {
// EXTERNAL STATEFUL PROPERTIES
// These properties are passed from another component. Example:
// value: {type: "number"}
// INTERNAL STATEFUL PROPERTIES
// These properties are owned by this component.
restaurants: {
default() {
return Restaurant.getList({});
}
},
// DERIVED PROPERTIES
// These properties combine other property values. Example:
// get valueAndMessage(){ return this.value + this.message; }
// METHODS
// Functions that can be called by the view. Example:
// incrementValue() { this.value++; }
// SIDE EFFECTS
// The following is a good place to perform changes to the DOM
// or do things that don't fit in to one of the areas above.
connectedCallback(element){
}
}
});
export default RestaurantList;
export const ViewModel = RestaurantList.ViewModel;
| import { Component } from 'can';
import './list.less';
import view from './list.stache';
import Restaurant from '~/models/restaurant';
const RestaurantList = Component.extend({
tag: 'pmo-restaurant-list',
view,
ViewModel: {
// EXTERNAL STATEFUL PROPERTIES
// These properties are passed from another component. Example:
// value: {type: "number"}
// INTERNAL STATEFUL PROPERTIES
// These properties are owned by this component.
restaurants: {
default() {
return Restaurant.getList({});
}
},
// DERIVED PROPERTIES
// These properties combine other property values. Example:
// get valueAndMessage(){ return this.value + this.message; }
// METHODS
// Functions that can be called by the view. Example:
// incrementValue() { this.value++; }
// SIDE EFFECTS
// The following is a good place to perform changes to the DOM
// or do things that don't fit in to one of the areas above.
connectedCallback(element){
}
}
});
export default RestaurantList;
export const ViewModel = RestaurantList.ViewModel;
import Component from 'can-component';
import DefineMap from 'can-define/map/';
import './list.less';
import view from './list.stache';
import Restaurant from '~/models/restaurant';
export const ViewModel = DefineMap.extend({
restaurants: {
value() {
return Restaurant.getList({});
}
}
});
export default Component.extend({
tag: 'pmo-restaurant-list',
ViewModel,
view
});
|
Implement Object schema toJSON function. | var schema = require('../schema')
var ObjectSchema = module.exports = function(object) {
this.reference = {}
for (var property in object) this.reference[property] = schema(object[property])
return schema.call(this)
}
ObjectSchema.prototype = {
validate : function(instance) {
if (instance == null) return false
instance = Object(instance)
for (var property in this.reference) {
if (property in instance) {
if (!this.reference[property](instance[property])) return false
} else {
if (!this.reference[property]()) return false
}
}
return true
},
toJSON : function() {
var schema = { type : 'object', required : true }
if (Object.keys(this.reference).length > 0) {
schema.properties = {}
for (var property in this.reference) {
schema.properties[property] = this.reference[property].toJSON()
}
}
return schema
}
}
schema.fromJS.def(function(object) {
if (object instanceof Object) return new ObjectSchema(object)
})
| var schema = require('../schema')
var ObjectSchema = module.exports = function(object) {
this.reference = {}
for (var property in object) this.reference[property] = schema(object[property])
return schema.call(this)
}
ObjectSchema.prototype = {
validate : function(instance) {
if (instance == null) return false
instance = Object(instance)
for (var property in this.reference) {
if (property in instance) {
if (!this.reference[property](instance[property])) return false
} else {
if (!this.reference[property]()) return false
}
}
return true
}
}
schema.fromJS.def(function(object) {
if (object instanceof Object) return new ObjectSchema(object)
})
|
Add the support for the new module constants to the LiveEntryManager
git-svn-id: 9770886a22906f523ce26b0ad22db0fc46e41232@71 5f8205a5-902a-0410-8b63-8f478ce83d95 | from comment_utils.managers import CommentedObjectManager
from django.db import models
class LiveEntryManager(CommentedObjectManager):
"""
Custom manager for the Entry model, providing shortcuts for
filtering by entry status.
"""
def featured(self):
"""
Returns a ``QuerySet`` of featured Entries.
"""
return self.filter(featured__exact=True)
def get_query_set(self):
"""
Overrides the default ``QuerySet`` to only include Entries
with a status of 'live'.
"""
return super(LiveEntryManager, self).get_query_set().filter(status__exact=self.model.LIVE_STATUS)
def latest_featured(self):
"""
Returns the latest featured Entry if there is one, or ``None``
if there isn't.
"""
try:
return self.featured()[0]
except IndexError:
return None
| from comment_utils.managers import CommentedObjectManager
from django.db import models
class LiveEntryManager(CommentedObjectManager):
"""
Custom manager for the Entry model, providing shortcuts for
filtering by entry status.
"""
def featured(self):
"""
Returns a ``QuerySet`` of featured Entries.
"""
return self.filter(featured__exact=True)
def get_query_set(self):
"""
Overrides the default ``QuerySet`` to only include Entries
with a status of 'live'.
"""
return super(LiveEntryManager, self).get_query_set().filter(status__exact=1)
def latest_featured(self):
"""
Returns the latest featured Entry if there is one, or ``None``
if there isn't.
"""
try:
return self.featured()[0]
except IndexError:
return None
|
Fix 5.4 error in cell test | <?php
namespace Michaeljennings\Carpenter\Tests\Components;
use Michaeljennings\Carpenter\Components\Cell as CellComponent;
use Michaeljennings\Carpenter\Tests\TestCase;
class CellTest extends TestCase
{
public function testCellImplementsContract()
{
$cell = $this->makeCell();
$this->assertInstanceOf('Michaeljennings\Carpenter\Contracts\Cell', $cell);
}
public function testValueCanBeRetrieved()
{
$cell = $this->makeCell();
$this->assertEquals('Test', $cell->value);
$this->assertEquals('Test', $cell->getValue());
$this->assertEquals('Test', $cell->value());
$this->assertEquals('Test', $cell);
}
public function testColumnPresenterIsRunOnCellValue()
{
$table = $this->makeTableWithData();
$table->column('foo')->setPresenter(function($value) {
return 'Value is: ' . $value;
});
$cell = new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);
$this->assertEquals('Value is: Test', $cell->value);
}
protected function makeCell()
{
$table = $this->makeTableWithData();
return new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);
}
} | <?php
namespace Michaeljennings\Carpenter\Tests\Components;
use Michaeljennings\Carpenter\Components\Cell as CellComponent;
use Michaeljennings\Carpenter\Contracts\Cell as CellContract;
use Michaeljennings\Carpenter\Tests\TestCase;
class CellTest extends TestCase
{
public function testCellImplementsContract()
{
$cell = $this->makeCell();
$this->assertInstanceOf(CellContract::Class, $cell);
}
public function testValueCanBeRetrieved()
{
$cell = $this->makeCell();
$this->assertEquals('Test', $cell->value);
$this->assertEquals('Test', $cell->getValue());
$this->assertEquals('Test', $cell->value());
$this->assertEquals('Test', $cell);
}
public function testColumnPresenterIsRunOnCellValue()
{
$table = $this->makeTableWithData();
$table->column('foo')->setPresenter(function($value) {
return 'Value is: ' . $value;
});
$cell = new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);
$this->assertEquals('Value is: Test', $cell->value);
}
protected function makeCell()
{
$table = $this->makeTableWithData();
return new CellComponent($table->column('foo'), 'Test', $this->getData()[0]);
}
} |
Add IP address of requested client | package main
import (
"log"
"os"
"github.com/joho/godotenv"
"github.com/labstack/echo"
"github.com/labstack/echo/engine/standard"
"github.com/labstack/echo/middleware"
)
func init() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORS())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*", "http://192.168.43.108:8100/"},
}))
e.POST("/qoutes/", CreateQoute)
e.GET("/qoutes/", GetAllQoutes)
e.GET("/qoutes/by/:status", GetQoutesByStatus)
e.GET("/qoutes/:id", GetQoute)
e.PUT("/qoutes/:id", UpdateQoute)
e.PUT("/qoutes/:id/:status", UpdateStatus)
e.DELETE("/qoutes/:id", DeleteQoute)
log.Print("Server listing on port", os.Getenv("PORT"))
e.Run(standard.New(os.Getenv("PORT")))
}
| package main
import (
"log"
"os"
"github.com/joho/godotenv"
"github.com/labstack/echo"
"github.com/labstack/echo/engine/standard"
"github.com/labstack/echo/middleware"
)
func init() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORS())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:8100/"},
}))
e.POST("/qoutes/", CreateQoute)
e.GET("/qoutes/", GetAllQoutes)
e.GET("/qoutes/by/:status", GetQoutesByStatus)
e.GET("/qoutes/:id", GetQoute)
e.PUT("/qoutes/:id", UpdateQoute)
e.PUT("/qoutes/:id/:status", UpdateStatus)
e.DELETE("/qoutes/:id", DeleteQoute)
log.Print("Server listing on port", os.Getenv("PORT"))
e.Run(standard.New(os.Getenv("PORT")))
}
|
Fix code launching onReady() handlers |
// SwellRT bootstrap script
// A fake SwellRT object to register on ready handlers
// before the GWT module is loaded
window.swellrt = {
onReady: function(handler) {
if (!handler || typeof handler !== "function")
return;
if (window.swellrt.runtime) {
handler.apply(window, window.swellrt.runtime.get());
} else {
if (!window._lh)
window._lh = [];
window._lh.push(handler);
}
}
}
var scripts = document.getElementsByTagName('script');
var thisScript = scripts[scripts.length -1];
if (thisScript) {
var p = document.createElement('a');
p.href = thisScript.src;
// Polyfill for ES6 proxy/reflect
if (!window.Proxy || !window.Reflect) {
try {
var reflectSrc = p.protocol + "//" +p.host + "/reflect.js";
document.write("<script src='"+reflectSrc+"'></script>");
} catch (e) {
console.log("No proxies supported: "+e);
}
}
var scriptSrc = p.protocol + "//" +p.host + "/swellrt_beta/swellrt_beta.nocache.js";
document.write("<script src='"+scriptSrc+"'></script>");
} else {
console.log("Unable to inject swellrt script!");
}
|
// SwellRT bootstrap script
// A fake SwellRT object to register on ready handlers
// before the GWT module is loaded
window.swellrt = {
onReady: function(handler) {
if (!handler || typeof handler !== "function")
return;
if (!window._lh)
window._lh = [];
window._lh.push(handler);
}
}
var scripts = document.getElementsByTagName('script');
var thisScript = scripts[scripts.length -1];
if (thisScript) {
var p = document.createElement('a');
p.href = thisScript.src;
// Polyfill for ES6 proxy/reflect
if (!window.Proxy || !window.Reflect) {
var reflectSrc = p.protocol + "//" +p.host + "/reflect.js";
document.write("<script src='"+reflectSrc+"'></script>");
}
var scriptSrc = p.protocol + "//" +p.host + "/swellrt_beta/swellrt_beta.nocache.js";
document.write("<script src='"+scriptSrc+"'></script>");
}
|
Load store into the tested components too | import jq from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import createHistory from 'history/lib/createBrowserHistory';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../../src/js/reducers';
// Global prerequisites to make it work in the command line
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
const $ = jq(window);
// Set up chai-jquery
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const store = createStore(reducers, state);
props.store = store;
const componentInstance = ReactTestUtils.renderIntoDocument(
<Provider store={store}>
<ComponentClass {...props} />
</Provider>
);
// Produces HTML
return $(ReactDOM.findDOMNode(componentInstance));
}
function mockHistory(component) {
component.childContextTypes = { history: React.PropTypes.object };
component.prototype.getChildContext = () => ({ history: createHistory() });
}
// Helper for simulating events
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
ReactTestUtils.Simulate[eventName](this[0]);
};
export { renderComponent, mockHistory, expect };
| import jq from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import createHistory from 'history/lib/createBrowserHistory';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../../src/js/reducers';
// Global prerequisites to make it work in the command line
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
const $ = jq(window);
// Set up chai-jquery
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = ReactTestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
// Produces HTML
return $(ReactDOM.findDOMNode(componentInstance));
}
function mockHistory(component) {
component.childContextTypes = { history: React.PropTypes.object };
component.prototype.getChildContext = () => ({ history: createHistory() });
}
// Helper for simulating events
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
ReactTestUtils.Simulate[eventName](this[0]);
};
export { renderComponent, mockHistory, expect };
|
Add a comment about where the basic example was taken
[skip CI] | # Basic example for testing purposes, taken from
# https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/
import sys
from browser import BrowserDialog
from PyQt4 import QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView
class MyBrowser(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
QWebView.__init__(self)
self.ui = BrowserDialog()
self.ui.setupUi(self)
self.ui.lineEdit.returnPressed.connect(self.loadURL)
def loadURL(self):
url = self.ui.lineEdit.text()
self.ui.qwebview.load(QUrl(url))
self.show()
# self.ui.lineEdit.setText("")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyBrowser()
myapp.ui.qwebview.load(QUrl('http://localhost:8800/taxtweb'))
myapp.show()
sys.exit(app.exec_())
| import sys
from browser import BrowserDialog
from PyQt4 import QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView
class MyBrowser(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
QWebView.__init__(self)
self.ui = BrowserDialog()
self.ui.setupUi(self)
self.ui.lineEdit.returnPressed.connect(self.loadURL)
def loadURL(self):
url = self.ui.lineEdit.text()
self.ui.qwebview.load(QUrl(url))
self.show()
# self.ui.lineEdit.setText("")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyBrowser()
myapp.ui.qwebview.load(QUrl('http://localhost:8800/taxtweb'))
myapp.show()
sys.exit(app.exec_())
|
Remove the day suffix from day heading
Closes #78 | <?php $formattedDate = $context->getDateTime()->format('l, F j'); ?>
<h1 class="day-heading" data-datetime="<?php echo $context->getDateTime()->format('c') ?>">
<?php echo $formattedDate ?>
<a class="permalink" href="<?php echo $context->getURL(); ?>" title="permalink"><span class="wdn-icon-link"></span></a>
<a title="ics format for events on <?php echo $formattedDate ?>" href="<?php echo $context->getURL() ?>.ics"><span class="wdn-icon-calendar"></span></a>
</h1>
<p class="day-nav">
<a class="url prev" href="<?php echo $context->getPreviousDay()->getURL(); ?>">Previous Day</a>
<a class="url next" href="<?php echo $context->getNextDay()->getURL(); ?>">Next Day</a>
</p>
<?php echo $savvy->render($context, 'EventListing.tpl.php'); ?>
| <?php $formattedDate = $context->getDateTime()->format('l, F jS'); ?>
<h1 class="day-heading">
<?php echo $formattedDate ?>
<a class="permalink" href="<?php echo $context->getURL(); ?>" title="permalink"><span class="wdn-icon-link"></span></a>
<a title="ics format for events on <?php echo $formattedDate ?>" href="<?php echo $context->getURL() ?>.ics"><span class="wdn-icon-calendar"></span></a>
</h1>
<p class="day-nav">
<a class="url prev" href="<?php echo $context->getPreviousDay()->getURL(); ?>">Previous Day</a>
<a class="url next" href="<?php echo $context->getNextDay()->getURL(); ?>">Next Day</a>
</p>
<?php echo $savvy->render($context, 'EventListing.tpl.php'); ?>
|
Change wrapper code to use [] notation for attribute access | from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
setattr(self.task, flow.name, NestedWorkflow(flow))
nested = getattr(self.task, flow.name)
for port in flow.input:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
self.input[port.name] = type
self.input[port.name] >> nested.input[port.name]
for port in flow.output:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
self.output[port.name] = type
nested.output[port.name] >> self.output[port.name]
| from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
setattr(self.task, flow.name, NestedWorkflow(flow))
nested = getattr(self.task, flow.name)
for port in flow.input:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
setattr(self.input, port.name, type)
getattr(self.input, port.name) >> getattr(nested.input, port.name)
for port in flow.output:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
setattr(self.output, port.name, type)
getattr(nested.output, port.name) >> getattr(self.output, port.name)
|
Replace ' in href attribute | <?php
namespace Vivo\View\Helper;
use Vivo\UI\Component;
use Zend\View\Helper\AbstractHelper;
/**
* View helper for gettting action url
*/
class ActionLink extends AbstractHelper
{
public function __invoke($action, $body, $params = array(), $reuseMatchedParams = false)
{
$model = $this->view->plugin('view_model')->getCurrent();
$component = $model->getVariable('component');
$act = $component['path'] . Component::COMPONENT_SEPARATOR . $action;
$urlHelper = $this->getView()->plugin('url');
$url = $urlHelper(null, array('act' => $act, 'args' => $params), $reuseMatchedParams);
$link = "<a href=\"$url\">$body</a>";
return $link;
}
}
| <?php
namespace Vivo\View\Helper;
use Vivo\UI\Component;
use Zend\View\Helper\AbstractHelper;
/**
* View helper for gettting action url
*/
class ActionLink extends AbstractHelper
{
public function __invoke($action, $body, $params = array(), $reuseMatchedParams = false)
{
$model = $this->view->plugin('view_model')->getCurrent();
$component = $model->getVariable('component');
$act = $component['path'] . Component::COMPONENT_SEPARATOR . $action;
$urlHelper = $this->getView()->plugin('url');
$url = $urlHelper(null,
array('act' => $act, 'args' => $params), $reuseMatchedParams);
$link = "<a href='$url'>$body</a>";
return $link;
}
}
|
Add temporary default admin user | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
DBSession.add(User(email='test@example.com', password='test', admin=True)) | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
|
Revert New Project button style | import React, { PropTypes } from 'react';
import { Button, List } from 'semantic-ui-react';
import { Link } from 'react-router';
function getProjectPath(id) {
return `/project/${id}`;
}
const Projects = ({ projects }) => {
return (
<div>
<h2>Projects</h2>
<List divided relaxed>
{
projects.length ?
projects.map(project => {
return (
<List.Item key={project.id}>
<Link to={getProjectPath(project.id)}>{project.name}</Link>
</List.Item>
)
}) :
<div></div>
}
</List>
<Button as={Link} to="/new-project" color="teal">New Project</Button>
</div>
)
};
Projects.propTypes = {
projects: PropTypes.array.isRequired
};
export default Projects; | import React, { PropTypes } from 'react';
import { Button, List, Menu } from 'semantic-ui-react';
import { Link } from 'react-router';
function getProjectPath(id) {
return `/project/${id}`;
}
const Projects = ({ projects }) => {
return (
<div>
<Menu secondary size="mini">
<Menu.Item>
<h2>Projects</h2>
</Menu.Item>
<Menu.Item>
<Button as={Link} to="/new-project" color="teal">New Project</Button>
</Menu.Item>
</Menu>
<List divided relaxed>
{
projects.length ?
projects.map(project => {
return (
<List.Item key={project.id}>
<Link to={getProjectPath(project.id)}>{project.name}</Link>
</List.Item>
)
}) :
<div></div>
}
</List>
</div>
)
};
Projects.propTypes = {
projects: PropTypes.array.isRequired
};
export default Projects; |
Add comment for xml-js lib | courses = {
0:{
'dept':'CS',
'num':383,
'sections':{
'A':{
'M':[],
'T':[],
'W':[],
'R':[],
'F':[]
}
}
}
}
/*
Start with classes with the least amount of sections, that should help keep the possible schedules down
Maybe add courses and update to see possible combos with that
Define required courses then list optional ones to include but also show schedules where that course would cause a conflict
*/
//https://www.npmjs.com/package/xml-js
| courses = {
0:{
'dept':'CS',
'num':383,
'sections':{
'A':{
'M':[],
'T':[],
'W':[],
'R':[],
'F':[]
}
}
}
}
/*
Start with classes with the least amount of sections, that should help keep the possible schedules down
Maybe add courses and update to see possible combos with that
Define required courses then list optional ones to include but also show schedules where that course would cause a conflict
*/
|
Remove old button to submit the apppassword login
Signed-off-by: John Molakvoæ (skjnldsv) <0835dbafb601d1e4088d26d0286d7121ba48453b@protonmail.com> | <?php
/**
* @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
*
* @license GNU AGPL version 3 or any later version
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
script('core', 'login/redirect');
style('core', 'login/authpicker');
/** @var array $_ */
/** @var \OCP\IURLGenerator $urlGenerator */
$urlGenerator = $_['urlGenerator'];
?>
<div class="picker-window">
<p><?php p($l->t('Redirecting …')) ?></p>
</div>
| <?php
/**
* @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
*
* @license GNU AGPL version 3 or any later version
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
script('core', 'login/redirect');
style('core', 'login/authpicker');
/** @var array $_ */
/** @var \OCP\IURLGenerator $urlGenerator */
$urlGenerator = $_['urlGenerator'];
?>
<div class="picker-window">
<p><?php p($l->t('Redirecting …')) ?></p>
</div>
<form method="POST" action="<?php p($urlGenerator->linkToRouteAbsolute('core.ClientFlowLogin.generateAppPassword')) ?>">
<input type="hidden" name="clientIdentifier" value="<?php p($_['clientIdentifier']) ?>" />
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
<input type="hidden" name="stateToken" value="<?php p($_['stateToken']) ?>" />
<input type="hidden" name="oauthState" value="<?php p($_['oauthState']) ?>" />
<input id="submit-redirect-form" type="submit" class="hidden "/>
</form>
|
Add conversion function to go Regexp | package p5r
import (
goregexp "regexp"
)
// Compatability functions for the "regexp" package
// MatchString return true if the string matches the regex
// Returns false if an error/timeout occurs
func (re *Regexp) MatchString(s string) bool {
m, err := re.run(true, -1, getRunes(s))
if err != nil {
return false
}
return m != nil
}
// ReplaceAllString returns a modified string if the replacement worked
// Returns the original string if an error occured
func (re *Regexp) ReplaceAllString(input, replacement string) string {
output, err := re.Replace(input, replacement, -1, -1)
if err != nil {
// Return the original string if something went wrong
return input
}
// Return the string with replacements
return output
}
// Compile a string to a Regexp
func MustCompile(input string) *Regexp {
return MustCompile2(input, 0)
}
// Compile a string to a Regexp, returns an error if something went wrong
func Compile(input string) (*Regexp, error) {
return Compile2(input, 0)
}
// Convert a p5r.Regex to a regexp.Regexp
func (re *Regexp) Regexp() (*goregexp.Regexp, error) {
return goregexp.Compile(re.pattern)
}
| package p5r
// Compatability functions for the "regexp" package
// MatchString return true if the string matches the regex
// Returns false if an error/timeout occurs
func (re *Regexp) MatchString(s string) bool {
m, err := re.run(true, -1, getRunes(s))
if err != nil {
return false
}
return m != nil
}
// ReplaceAllString returns a modified string if the replacement worked
// Returns the original string if an error occured
func (re *Regexp) ReplaceAllString(input, replacement string) string {
output, err := re.Replace(input, replacement, -1, -1)
if err != nil {
// Return the original string if something went wrong
return input
}
// Return the string with replacements
return output
}
func MustCompile(input string) *Regexp {
return MustCompile2(input, 0)
}
func Compile(input string) (*Regexp, error) {
return Compile2(input, 0)
}
|
Fix odd casing of reddit2kindle | #!/usr/bin/env python
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='reddit2kindle',
entry_points={
'console_scripts': [
'r2k = r2klib.cli:from_cli'
]
},
packages=find_packages(),
install_requires=[
'markdown2',
'praw',
'docopt',
'jinja2'
],
version='0.6.0',
author='Antriksh Yadav',
author_email='antrikshy@gmail.com',
url='http://www.antrikshy.com/projects/reddit2kindle.htm',
description=(
'Compiles top posts from a specified subreddit for a specified time'
'period into a well-formatted Kindle book.'
),
long_description=(
'See http://www.github.com/Antrikshy/reddit2kindle for instructions.'
'Requires KindleGen from Amazon to convert HTML result to .mobi for'
'Kindle.'
),
classifiers=[
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'Natural Language :: English',
'License :: OSI Approved :: MIT License'
],
)
| #!/usr/bin/env python
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='reddit2Kindle',
entry_points={
'console_scripts': [
'r2k = r2klib.cli:from_cli'
]
},
packages=find_packages(),
install_requires=[
'markdown2',
'praw',
'docopt',
'jinja2'
],
version='0.6.0',
author='Antriksh Yadav',
author_email='antrikshy@gmail.com',
url='http://www.antrikshy.com/projects/reddit2Kindle.htm',
description=(
'Compiles top posts from a specified subreddit for a specified time'
'period into a well-formatted Kindle book.'
),
long_description=(
'See http://www.github.com/Antrikshy/reddit2Kindle for instructions.'
'Requires KindleGen from Amazon to convert HTML result to .mobi for'
'Kindle.'
),
classifiers=[
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'Natural Language :: English',
'License :: OSI Approved :: MIT License'
],
)
|
Fix Azure to use it's ip-detect script rather than AWS' | import pkg_resources
import yaml
entry = {
'must': {
'resolvers': '["168.63.129.16"]',
'ip_detect_contents': yaml.dump(pkg_resources.resource_string('gen', 'ip-detect/azure.sh').decode()),
'master_discovery': 'static',
'exhibitor_storage_backend': 'azure',
'master_cloud_config': '{{ master_cloud_config }}',
'slave_cloud_config': '{{ slave_cloud_config }}',
'slave_public_cloud_config': '{{ slave_public_cloud_config }}',
'oauth_enabled': "[[[variables('oauthEnabled')]]]",
'oauth_available': 'true'
}
}
| import pkg_resources
import yaml
entry = {
'must': {
'resolvers': '["168.63.129.16"]',
'ip_detect_contents': yaml.dump(pkg_resources.resource_string('gen', 'ip-detect/aws.sh').decode()),
'master_discovery': 'static',
'exhibitor_storage_backend': 'azure',
'master_cloud_config': '{{ master_cloud_config }}',
'slave_cloud_config': '{{ slave_cloud_config }}',
'slave_public_cloud_config': '{{ slave_public_cloud_config }}',
'oauth_enabled': "[[[variables('oauthEnabled')]]]",
'oauth_available': 'true'
}
}
|
Allow to specify initial items on DictionaryObject constructor | class AttributeObject:
def __init__(self, *excluded_keys):
self._excluded_keys = excluded_keys
def __getattr__(self, item):
return self._getattr(item)
def __setattr__(self, key, value):
if key == "_excluded_keys" or key in self._excluded_keys:
super().__setattr__(key, value)
else:
self._setattr(key, value)
def _getattr(self, item):
pass
def _setattr(self, key, value):
pass
class DictionaryObject(AttributeObject):
def __init__(self, initial_items={}):
super().__init__("_dictionary")
self._dictionary = dict(initial_items)
def _getattr(self, item):
return self._dictionary.get(item)
def _setattr(self, key, value):
self._dictionary[key] = value
def _copy(self):
return DictionaryObject(self._dictionary)
| class AttributeObject:
def __init__(self, *excluded_keys):
self._excluded_keys = excluded_keys
def __getattr__(self, item):
return self._getattr(item)
def __setattr__(self, key, value):
if key == "_excluded_keys" or key in self._excluded_keys:
super().__setattr__(key, value)
else:
self._setattr(key, value)
def _getattr(self, item):
pass
def _setattr(self, key, value):
pass
class DictionaryObject(AttributeObject):
def __init__(self):
super().__init__("_dictionary")
self._dictionary = {}
def _getattr(self, item):
return self._dictionary.get(item)
def _setattr(self, key, value):
self._dictionary[key] = value
def _copy(self):
new = DictionaryObject()
new._dictionary = self._dictionary.copy()
return new
|
Make sure the Shindig library is set on the include path, for the hack to work
git-svn-id: e77a8db410fc7e53f700994083f7980387c3a882@686 528793b8-127e-4309-9901-b74759c7208d | <?php
/**
* SURFconext EngineBlock
*
* LICENSE
*
* Copyright 2011 SURFnet bv, The Netherlands
*
* 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.
*
* @category SURFconext EngineBlock
* @package
* @copyright Copyright © 2010-2011 SURFnet SURFnet bv, The Netherlands (http://www.surfnet.nl)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
*/
define('ENGINEBLOCK_FOLDER_SHINDIG', ENGINEBLOCK_FOLDER_LIBRARY . 'shindig/php/');
set_include_path(ENGINEBLOCK_FOLDER_SHINDIG . PATH_SEPARATOR . get_include_path());
/**
* HACK, load up the Shindig OAuth library as it's the same as the OpenSocial Clients one.
*/
require_once 'external/OAuth/OAuth.php'; | <?php
/**
* SURFconext EngineBlock
*
* LICENSE
*
* Copyright 2011 SURFnet bv, The Netherlands
*
* 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.
*
* @category SURFconext EngineBlock
* @package
* @copyright Copyright © 2010-2011 SURFnet SURFnet bv, The Netherlands (http://www.surfnet.nl)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
*/
/**
* HACK, load up the Shindig OAuth library as it's the same as the OpenSocial Clients one.
*/
require_once 'external/OAuth.php'; |
:white_check_mark: Update the CanBuildBaseString test trait. | <?php
use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Signature\CanBuildBaseString;
use Risan\OAuth1\Signature\BaseStringBuilderInterface;
class CanBuildBaseStringTest extends TestCase
{
private $canBuildBaseStringStub;
function setUp()
{
$this->canBuildBaseStringStub = $this->getMockForTrait(CanBuildBaseString::class);
}
/** @test */
function can_build_base_string_trait_can_get_base_string_builder_interface_instance()
{
$this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseStringStub->getBaseStringBuilder());
}
/** @test */
function can_build_base_string_trait_can_build_base_string()
{
$baseString = $this->canBuildBaseStringStub->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST');
$this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $canBuildBaseStringStub);
}
}
| <?php
use PHPUnit\Framework\TestCase;
use Risan\OAuth1\Signature\CanBuildBaseString;
use Risan\OAuth1\Signature\BaseStringBuilderInterface;
class CanBuildBaseStringTest extends TestCase
{
private $canBuildBaseString;
function setUp()
{
$this->canBuildBaseString = $this->getMockForTrait(CanBuildBaseString::class);
}
/** @test */
function can_build_base_string_trait_can_get_base_string_builder_interface_instance()
{
$this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseString->getBaseStringBuilder());
}
/** @test */
function can_build_base_string_trait_can_build_base_string()
{
$baseString = $this->canBuildBaseString->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST');
$this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $baseString);
}
}
|
Remove Driver after touch test | /*
Copyright 2012 Selenium committers
Copyright 2012 Software Freedom Conservancy
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.openqa.selenium.interactions.touch;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.AfterClass;
import org.openqa.selenium.interactions.touch.TouchDoubleTapTest;
import org.openqa.selenium.interactions.touch.TouchFlickTest;
import org.openqa.selenium.interactions.touch.TouchLongPressTest;
import org.openqa.selenium.interactions.touch.TouchScrollTest;
import org.openqa.selenium.interactions.touch.TouchSingleTapTest;
import org.openqa.selenium.testing.JUnit4TestBase;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TouchDoubleTapTest.class,
TouchFlickTest.class,
TouchLongPressTest.class,
TouchScrollTest.class,
TouchSingleTapTest.class
})
public class TouchTests {
@AfterClass
public static void cleanUpDriver() {
JUnit4TestBase.removeDriver();
}
}
| /*
Copyright 2012 Selenium committers
Copyright 2012 Software Freedom Conservancy
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.openqa.selenium.interactions.touch;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.openqa.selenium.interactions.touch.TouchDoubleTapTest;
import org.openqa.selenium.interactions.touch.TouchFlickTest;
import org.openqa.selenium.interactions.touch.TouchLongPressTest;
import org.openqa.selenium.interactions.touch.TouchScrollTest;
import org.openqa.selenium.interactions.touch.TouchSingleTapTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TouchDoubleTapTest.class,
TouchFlickTest.class,
TouchLongPressTest.class,
TouchScrollTest.class,
TouchSingleTapTest.class
})
public class TouchTests {
}
|
Make help accessible for logged-in non-admin users
Signed-off-by: Hemanth Kumar Veeranki <hemanthveeranki@gmail.com>
Reviewed-by: Johannes Keyser <187051b70230423a457adbc3e507f9e4fff08d4b@posteo.de> | #
# This file is part of Plinth.
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
URLs for the Help module
"""
from django.conf.urls import url
from plinth.utils import non_admin_view
from . import help as views
urlpatterns = [
# having two urls for one page is a hack to help the current url/menu
# system highlight the correct menu item. Every submenu-item with the same
# url prefix as the main-menu is highlighted automatically.
url(r'^help/$', non_admin_view(views.index), name='index'),
url(r'^help/index/$', non_admin_view(views.index), name='index_explicit'),
url(r'^help/about/$', non_admin_view(views.about), name='about'),
url(r'^help/manual/$', non_admin_view(views.manual), name='manual'),
url(r'^help/status-log/$', non_admin_view(views.status_log), name='status-log'),
]
| #
# This file is part of Plinth.
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
URLs for the Help module
"""
from django.conf.urls import url
from . import help as views
urlpatterns = [
# having two urls for one page is a hack to help the current url/menu
# system highlight the correct menu item. Every submenu-item with the same
# url prefix as the main-menu is highlighted automatically.
url(r'^help/$', views.index, name='index'),
url(r'^help/index/$', views.index, name='index_explicit'),
url(r'^help/about/$', views.about, name='about'),
url(r'^help/manual/$', views.manual, name='manual'),
url(r'^help/status-log/$', views.status_log, name='status-log'),
]
|
Update minimum version of psycopg2 required
For the `super_user` context manager, we are doing something like:
```
db_conn = psycopg2.connect('user=tester dbname=testing', user='postgres')
```
This was not supported by psycopg2 < 2.7:
```
Traceback (most recent call last):
File \"/var/cnx/venvs/publishing/bin/dbmigrator\", line 11, in <module>
sys.exit(main())
File \"/var/cnx/venvs/publishing/local/lib/python2.7/site-packages/dbmigrator/cli.py\", line 104, in main
return args['cmmd'](**args)
File \"/var/cnx/venvs/publishing/local/lib/python2.7/site-packages/dbmigrator/utils.py\", line 145, in wrapper
return func(cursor, *args, **kwargs)
File \"/var/cnx/venvs/publishing/local/lib/python2.7/site-packages/dbmigrator/commands/migrate.py\", line 32, in cli_command
run_deferred)
File \"/var/cnx/venvs/publishing/local/lib/python2.7/site-packages/dbmigrator/utils.py\", line 227, in compare_schema
callback(*args, **kwargs)
File \"/var/cnx/venvs/publishing/local/lib/python2.7/site-packages/dbmigrator/utils.py\", line 257, in run_migration
migration.up(cursor)
File \"../../var/cnx/venvs/publishing/src/cnx-db/cnxdb/migrations/20170912134157_shred-colxml-uuids.py\", line 19, in up
with super_user() as super_cursor:
File \"/usr/lib/python2.7/contextlib.py\", line 17, in __enter__
return self.gen.next()
File \"/var/cnx/venvs/publishing/local/lib/python2.7/site-packages/dbmigrator/utils.py\", line 57, in super_user
user=super_user) as db_conn:
File \"/var/cnx/venvs/publishing/local/lib/python2.7/site-packages/psycopg2/__init__.py\", line 155, in connect
% items[0][0])
TypeError: 'user' is an invalid keyword argument when the dsn is specified
``` | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
import sys
from setuptools import setup, find_packages
install_requires = (
'psycopg2>=2.7',
)
tests_require = [
]
if sys.version_info.major < 3:
tests_require.append('mock')
LONG_DESC = '\n\n~~~~\n\n'.join([open('README.rst').read(),
open('CHANGELOG.rst').read()])
setup(
name='db-migrator',
version='1.0.0',
author='Connexions',
author_email='info@cnx.org',
url='https://github.com/karenc/db-migrator',
license='AGPL, see also LICENSE.txt',
description='Python package to migrate postgresql database',
long_description=LONG_DESC,
packages=find_packages(),
install_requires=install_requires,
tests_require=tests_require,
test_suite='dbmigrator.tests',
include_package_data=True,
entry_points={
'console_scripts': [
'dbmigrator = dbmigrator.cli:main',
],
},
)
| # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
import sys
from setuptools import setup, find_packages
install_requires = (
'psycopg2>=2.5',
)
tests_require = [
]
if sys.version_info.major < 3:
tests_require.append('mock')
LONG_DESC = '\n\n~~~~\n\n'.join([open('README.rst').read(),
open('CHANGELOG.rst').read()])
setup(
name='db-migrator',
version='1.0.0',
author='Connexions',
author_email='info@cnx.org',
url='https://github.com/karenc/db-migrator',
license='AGPL, see also LICENSE.txt',
description='Python package to migrate postgresql database',
long_description=LONG_DESC,
packages=find_packages(),
install_requires=install_requires,
tests_require=tests_require,
test_suite='dbmigrator.tests',
include_package_data=True,
entry_points={
'console_scripts': [
'dbmigrator = dbmigrator.cli:main',
],
},
)
|
Fix unexpected swoole sever crash on high concurrency operation
`SplQueue` is operated using `enqueue()` and `dequeue()` not with `push()` and `pop()` which is for `Stack`.
`SplQueue` is a `FIFO`, but use of `push/pop` turns it into `Stack` which is `LIFO`, this has caused numerous disconnections that resulted into a swoole server crash.
By fixing this, disconnection from database server does not cause server crash anymore.
Ref.
[SplQueue dequeue](http://php.net/manual/en/splqueue.dequeue.php)
[SplQueue enqueue](http://php.net/manual/en/splqueue.enqueue.php) | <?php
$count = 0;
$pool = new SplQueue();
$server = new Swoole\Http\Server('127.0.0.1', 9501, SWOOLE_BASE);
$server->on('Request', function($request, $response) use(&$count, $pool) {
if (count($pool) == 0) {
$redis = new Swoole\Coroutine\Redis();
$res = $redis->connect('127.0.0.1', 6379);
if ($res == false) {
$response->end("redis connect fail!");
return;
}
$pool->enqueue($redis);
}
$redis = $pool->dequeue();
$count ++;
$ret = $redis->set('key', 'value');
$response->end("swoole response is ok, count = $count, result=" . var_export($ret, true));
$pool->enqueue($redis);
});
$server->start();
| <?php
$count = 0;
$pool = new SplQueue();
$server = new Swoole\Http\Server('127.0.0.1', 9501, SWOOLE_BASE);
$server->on('Request', function($request, $response) use(&$count, $pool) {
if (count($pool) == 0) {
$redis = new Swoole\Coroutine\Redis();
$res = $redis->connect('127.0.0.1', 6379);
if ($res == false) {
$response->end("redis connect fail!");
return;
}
$pool->push($redis);
}
$redis = $pool->pop();
$count ++;
$ret = $redis->set('key', 'value');
$response->end("swoole response is ok, count = $count, result=" . var_export($ret, true));
$pool->push($redis);
});
$server->start();
|
Put latest additions in package. | from setuptools import setup, find_packages
setup(
version='0.44',
name="pydvkbiology",
packages=find_packages(),
description='Python scripts used in my biology/bioinformatics research',
author='DV Klopfenstein',
author_email='music_pupil@yahoo.com',
scripts=['./pydvkbiology/NCBI/cols.py'],
license='BSD',
url='http://github.com/dvklopfenstein/biocode',
download_url='http://github.com/dvklopfenstein/biocode/tarball/0.1',
keywords=['NCBI', 'biology', 'bioinformatics'],
classifiers = [
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Topic :: Scientific/Engineering :: Bio-Informatics'],
#install_requires=['sys', 're', 'os', 'collections']
# Potential other requires:
# Entrez
# math
# matplotlib
# numpy
# requests
# shutil
)
| from setuptools import setup, find_packages
setup(
version='0.43',
name="pydvkbiology",
packages=find_packages(),
description='Python scripts used in my biology/bioinformatics research',
author='DV Klopfenstein',
author_email='music_pupil@yahoo.com',
scripts=['./pydvkbiology/NCBI/cols.py'],
license='BSD',
url='http://github.com/dvklopfenstein/biocode',
download_url='http://github.com/dvklopfenstein/biocode/tarball/0.1',
keywords=['NCBI', 'biology', 'bioinformatics'],
classifiers = [
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Topic :: Scientific/Engineering :: Bio-Informatics'],
#install_requires=['sys', 're', 'os', 'collections']
# Potential other requires:
# Entrez
# math
# matplotlib
# numpy
# requests
# shutil
)
|
Move text to template, prepare for translation | <form id="password_policy" class="section">
<h2><?php p($l->t('Password Policy')); ?></h2>
<p><?php p($l->t('The following password restrictions are currently in place:')); ?></p>
<p><?php p($l->t('All passwords are required to be at least %s characters in length and;', [ $_['minlength']])); ?></p>
<ul style="list-style: circle; margin-left: 20px;">
<?php if(isset($_['mixedcase']) && $_['mixedcase'] == "true"){
?><li><?php
p($l->t('Must contain UPPER and lower case characters.'));
?></li><?php
}?>
<?php if(isset($_['numbers']) && $_['numbers'] == "true"){
?><li><?php
p($l->t('Must contain numbers.'));
?></li><?php
}?>
<?php if(isset($_['specialchars']) && $_['specialchars'] == "true"){
?><li><?php
p($l->t('Must contain special characters: %s', [ $_['specialcharslist'] ]));
?></li><?php
}?>
</ul>
</form>
| <form id="password_policy" class="section">
<h2><?php p($l->t('Password Policy')); ?></h2>
<p>The following password restrictions are currently in place:</p>
<p>All passwords are required to be at least <?php p($_['minlength']); ?> characters in length and;</p>
<ul style="list-style: circle; margin-left: 20px;">
<?php if(isset($_['mixedcase'])){
?><li><?php
p($_['mixedcase']);
?></li><?php
}?>
<?php if(isset($_['numbers'])){
?><li><?php
p($_['numbers']);
?></li><?php
}?>
<?php if(isset($_['specialcharslist'])){
?><li><?php
p($_['specialcharslist']);
?></li><?php
}?>
</ul>
</form> |
Use the correct Requests OAuth lib version (previously we used a patched lib). | import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
required = ['requests>=0.11.2',
'requests-oauth2>=0.2.0']
setup(
name='basecampx',
version='0.1.7',
author='Rimvydas Naktinis',
author_email='naktinis@gmail.com',
description=('Wrapper for Basecamp Next API.'),
license="MIT",
keywords="basecamp bcx api",
url='https://github.com/nous-consulting/basecamp-next',
packages=['basecampx'],
install_requires=required,
long_description=read('README.rst'),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7'
],
)
| import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
required = ['requests>=0.11.2',
'requests-oauth2>=0.2.1']
setup(
name='basecampx',
version='0.1.7',
author='Rimvydas Naktinis',
author_email='naktinis@gmail.com',
description=('Wrapper for Basecamp Next API.'),
license="MIT",
keywords="basecamp bcx api",
url='https://github.com/nous-consulting/basecamp-next',
packages=['basecampx'],
install_requires=required,
long_description=read('README.rst'),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7'
],
)
|
Test that users can not access frontend by default | from django.test import TestCase
from django.contrib.auth.models import User, Group
from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group, FRONTEND_USER_GROUP
class TestFrontendPermissions(TestCase):
def test_user_can_not_access_frontend_by_default(self):
a_user = User.objects.create_user('U. Ser', 'user@example.com', 'password')
self.assertFalse(user_in_osmaxx_group(a_user))
def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self):
an_admin = User.objects.create_superuser('A. D. Min', 'admin@example.com', 'password')
self.assertTrue(user_in_osmaxx_group(an_admin))
def test_user_can_access_frontend_when_in_osmaxx_group(self):
a_user = User.objects.create_user('U. Ser', 'user@example.com', 'password')
a_user.groups.add(Group.objects.get(name=FRONTEND_USER_GROUP))
self.assertTrue(user_in_osmaxx_group(a_user))
| from django.test import TestCase
from django.contrib.auth.models import User, Group
from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group, FRONTEND_USER_GROUP
class TestFrontendPermissions(TestCase):
def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self):
an_admin = User.objects.create_superuser('A. D. Min', 'admin@example.com', 'password')
self.assertTrue(user_in_osmaxx_group(an_admin))
def test_user_can_access_frontend_when_in_osmaxx_group(self):
a_user = User.objects.create_user('U. Ser', 'user@example.com', 'password')
a_user.groups.add(Group.objects.get(name=FRONTEND_USER_GROUP))
self.assertTrue(user_in_osmaxx_group(a_user))
|
Add some potentially helpful startup console output | #!/usr/bin/env node
process.title = 'timeline_serve';
var _ = require('underscore')._;
var express = require('express');
var socket = require('socket.io');
var fs = require('fs');
var app = express();
app.configure(function () {
app.use(express.static(__dirname + '/../public'));
});
var server = app.listen(8888);
function readData () {
var fileNames = fs.readdirSync('./');
return _.reduce(fileNames, function (memo, filename) {
var stat = fs.statSync(filename);
if (stat.isFile()) {
memo[filename] = fs.readFileSync(filename, 'utf8');
}
return memo;
}, {});
}
var io = socket.listen(server);
io.configure(function () {
io.set("log level", 1);
});
io.sockets.on('connection', function (socket) {
socket.emit('data', readData());
});
var watch = require('node-watch');
watch(__dirname + '/../public', function () {
io.sockets.emit('reload');
});
watch('./', function () {
io.sockets.emit('data', readData());
});
console.log('Timeline server started.');
console.log('Reading timeline files from ' + fs.realpathSync('./'));
console.log('Point your browser to http://localhost:8888/');
| #!/usr/bin/env node
process.title = 'timeline_serve';
var _ = require('underscore')._;
var express = require('express');
var socket = require('socket.io');
var fs = require('fs');
var app = express();
app.configure(function () {
app.use(express.static(__dirname + '/../public'));
});
var server = app.listen(8888);
function readData () {
var fileNames = fs.readdirSync('./');
return _.reduce(fileNames, function (memo, filename) {
var stat = fs.statSync(filename);
if (stat.isFile()) {
memo[filename] = fs.readFileSync(filename, 'utf8');
}
return memo;
}, {});
}
var io = socket.listen(server);
io.configure(function () {
io.set("log level", 1);
});
io.sockets.on('connection', function (socket) {
socket.emit('data', readData());
});
var watch = require('node-watch');
watch(__dirname + '/../public', function () {
io.sockets.emit('reload');
});
watch('./', function () {
io.sockets.emit('data', readData());
});
|
Update local copy of notification when marking as read | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Core\Notifications\Commands;
use Flarum\Core\Notifications\Notification;
use Flarum\Core\Exceptions\PermissionDeniedException;
use Flarum\Core\Support\DispatchesEvents;
class ReadNotificationHandler
{
/**
* @param ReadNotification $command
* @return Notification
* @throws \Flarum\Core\Exceptions\PermissionDeniedException
*/
public function handle(ReadNotification $command)
{
$actor = $command->actor;
if ($actor->isGuest()) {
throw new PermissionDeniedException;
}
$notification = Notification::where('user_id', $actor->id)->findOrFail($command->notificationId);
Notification::where([
'user_id' => $actor->id,
'type' => $notification->type,
'subject_id' => $notification->subject_id
])
->update(['is_read' => true]);
$notification->is_read = true;
return $notification;
}
}
| <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Core\Notifications\Commands;
use Flarum\Core\Notifications\Notification;
use Flarum\Core\Exceptions\PermissionDeniedException;
use Flarum\Core\Support\DispatchesEvents;
class ReadNotificationHandler
{
/**
* @param ReadNotification $command
* @return Notification
* @throws \Flarum\Core\Exceptions\PermissionDeniedException
*/
public function handle(ReadNotification $command)
{
$actor = $command->actor;
if ($actor->isGuest()) {
throw new PermissionDeniedException;
}
$notification = Notification::where('user_id', $actor->id)->findOrFail($command->notificationId);
Notification::where([
'user_id' => $actor->id,
'type' => $notification->type,
'subject_id' => $notification->subject_id
])
->update(['is_read' => true]);
return $notification;
}
}
|
Cut fbcode_builder dep for thrift on krb5
Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and no longer has any build-time dependency on `krb5`. Clean this up.
Reviewed By: stevegury, vitaut
Differential Revision: D14814205
fbshipit-source-id: dca469d22098e34573674194facaaac6c4c6aa32 | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
| #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.github_project_workdir('krb5/krb5', 'src'),
builder.autoconf_install('krb5/krb5'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
Hide CC icon from the footer | <?php
class HitchwikiHooks {
/**
* Handler for BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function onBeforePageDisplay( &$out, &$skin ) {
// Ensure Hitchwiki skin runs only against Vector skin
// FIXME: See bug 62897
if ( $skin->getSkinName() !== 'vector' ) {
return true;
}
// Add our modules
$modules = array(
'skins.vector.hitchwiki'
);
$out->addModules( $modules );
return true;
}
/**
* Disable powered by footer icons
* Handled at hook BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function modifyFooterIcons( &$out, &$skin ) {
global $wgFooterIcons;
unset($wgFooterIcons["poweredby"]);
unset($wgFooterIcons["copyright"]);
return true;
}
}
| <?php
class HitchwikiHooks {
/**
* Handler for BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function onBeforePageDisplay( &$out, &$skin ) {
// Ensure Hitchwiki skin runs only against Vector skin
// FIXME: See bug 62897
if ( $skin->getSkinName() !== 'vector' ) {
return true;
}
// Add our modules
$modules = array(
'skins.vector.hitchwiki'
);
$out->addModules( $modules );
return true;
}
/**
* Disable powered by footer icons
* Handled at hook BeforePageDisplay
* @param OutputPage $out
* @param Skin $skin
* @return bool
*/
static function modifyFooterIcons( &$out, &$skin ) {
global $wgFooterIcons;
unset($wgFooterIcons["poweredby"]);
return true;
}
}
|
Add a detection of a function definition. | #!/usr/bin/env python
from sys import argv
from operator import add, sub, mul, div
functions = { \
'+': (2, add), \
'-': (2, sub), \
'*': (2, mul), \
'/': (2, div) \
}
def get_code():
return argv[1]
def get_tokens(code):
return code.split(' ')
def parse_function(tokens):
return 'test', (23, None), tokens[-1:]
def evaluate(tokens):
name = tokens[0]
tokens = tokens[1:]
if name == 'fn':
name, function, tokens = parse_function(tokens)
functions[name] = function
return 0, tokens
if name not in functions:
return int(name), tokens
function = functions[name]
arguments = []
for _ in xrange(function[0]):
value, tokens = evaluate(tokens)
arguments.append(value)
value = function[1](*arguments)
return value, tokens
if __name__ == '__main__':
code = get_code()
tokens = get_tokens(code)
value, _ = evaluate(tokens)
print(value)
print(functions)
| #!/usr/bin/env python
from sys import argv
from operator import add, sub, mul, div
functions = { \
'+': (2, add), \
'-': (2, sub), \
'*': (2, mul), \
'/': (2, div) \
}
def get_code():
return argv[1]
def get_tokens(code):
return code.split(' ')
def evaluate(tokens):
name = tokens[0]
tokens = tokens[1:]
if name not in functions:
return int(name), tokens
function = functions[name]
arguments = []
for _ in xrange(function[0]):
value, tokens = evaluate(tokens)
arguments.append(value)
value = function[1](*arguments)
return value, tokens
if __name__ == '__main__':
code = get_code()
tokens = get_tokens(code)
value, _ = evaluate(tokens)
print(value)
|
Fix test failure on php 5.3 | <?php
namespace Emonkak\Random\Tests\Engine;
use Emonkak\Random\Engine\RandomDevice;
/**
* @requires extension mcrypt
*/
class RandomDeviceTest extends \PHPUnit_Framework_TestCase
{
public function testMax()
{
$engine = new RandomDevice();
return $this->assertSame(0x7fffffff, $engine->max());
}
public function testMin()
{
$engine = new RandomDevice();
return $this->assertSame(0, $engine->min());
}
public function testNext()
{
$engine = new RandomDevice();
for ($i = 0; $i < 1000; $i++) {
$n = $engine->next();
$this->assertGreaterThanOrEqual($engine->min(), $n);
$this->assertLessThanOrEqual($engine->max(), $n);
}
}
}
| <?php
namespace Emonkak\Random\Tests\Engine;
use Emonkak\Random\Engine\RandomDevice;
/**
* @requires extension mcrypt
*/
class RandomDeviceTest extends \PHPUnit_Framework_TestCase
{
public function testMax()
{
return $this->assertSame(0x7fffffff, (new RandomDevice())->max());
}
public function testMin()
{
return $this->assertSame(0, (new RandomDevice())->min());
}
public function testNext()
{
$engine = new RandomDevice();
for ($i = 0; $i < 1000; $i++) {
$n = $engine->next();
$this->assertGreaterThanOrEqual($engine->min(), $n);
$this->assertLessThanOrEqual($engine->max(), $n);
}
}
}
|
Comment about recursion limit in categories. | # Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl>
#
# This file is part of django-webshop.
#
# django-webshop 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 2, or (at your option)
# any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
Django-webshop, by default, contains base classes for two kinds of categories:
* Simple categories, which define a base class for products that belong to
exactly one category.
* Advanced categories, that belong to zero or more categories.
Furthermore, generic abstract base models are defined for 'normal' categories
and for nested categories, allowing for the hierarchical categorization of
products.
TODO: We want a setting allowing us to limit the nestedness of categories.
For 'navigational' reasons, a number of 3 should be a reasonable default.
""" | # Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl>
#
# This file is part of django-webshop.
#
# django-webshop 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 2, or (at your option)
# any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
Django-webshop, by default, contains base classes for two kinds of categories:
* Simple categories, which define a base class for products that belong to
exactly one category.
* Advanced categories, that belong to zero or more categories.
Furthermore, generic abstract base models are defined for 'normal' categories
and for nested categories, allowing for the hierarchical categorization of
products.
""" |
Add test checking board can't get overfilled. | from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((4,0)) == 1
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((3,0)) == 1
assert board.addPiece(1, 1) == True
assert board.boardMatrix.item((4,1)) == 1
assert board.addPiece(4, 1) == True
assert board.boardMatrix.item((4,4)) == 1
"""
Tests that the board can be filled up completely
but no more.
"""
def test_addPieceMaxColumn():
board = Board(5,5)
# Fill board
for x in range(board.columns):
for y in range(board.rows):
assert board.addPiece(x, 1) == True
# Attempt to overfill
for x in range(board.columns):
assert board.addPiece(x, 2) == False
# Make sure initially filled values weren't overriden
for x in range(board.columns):
for y in range(board.rows):
assert board.boardMatrix.item((x,y)) == 1
| from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((4,0)) == 1
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((3,0)) == 1
assert board.addPiece(1, 1) == True
assert board.boardMatrix.item((4,1)) == 1
assert board.addPiece(4, 1) == True
assert board.boardMatrix.item((4,4)) == 1
|
Fix `@package` annotation in ClearCache command | <?php
namespace wcf\system\cache\command;
use wcf\data\option\OptionEditor;
use wcf\data\package\update\server\PackageUpdateServer;
use wcf\system\cache\CacheHandler;
use wcf\system\cache\event\CacheCleared;
use wcf\system\event\EventHandler;
use wcf\system\language\LanguageFactory;
use wcf\system\style\StyleHandler;
use wcf\system\user\storage\UserStorageHandler;
/**
* Performs a full cache clear.
*
* @author Tim Duesterhus
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Cache\Command
* @since 6.0
*/
final class ClearCache
{
private EventHandler $eventHandler;
public function __construct()
{
$this->eventHandler = EventHandler::getInstance();
}
public function __invoke()
{
OptionEditor::resetCache();
UserStorageHandler::getInstance()->clear();
StyleHandler::resetStylesheets();
LanguageFactory::getInstance()->deleteLanguageCache();
CacheHandler::getInstance()->flushAll();
PackageUpdateServer::resetAll();
$this->eventHandler->fire(
new CacheCleared()
);
}
}
| <?php
namespace wcf\system\cache\command;
use wcf\data\option\OptionEditor;
use wcf\data\package\update\server\PackageUpdateServer;
use wcf\system\cache\CacheHandler;
use wcf\system\cache\event\CacheCleared;
use wcf\system\event\EventHandler;
use wcf\system\language\LanguageFactory;
use wcf\system\style\StyleHandler;
use wcf\system\user\storage\UserStorageHandler;
/**
* Performs a full cache clear.
*
* @author Tim Duesterhus
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Cache\Event
* @since 6.0
*/
final class ClearCache
{
private EventHandler $eventHandler;
public function __construct()
{
$this->eventHandler = EventHandler::getInstance();
}
public function __invoke()
{
OptionEditor::resetCache();
UserStorageHandler::getInstance()->clear();
StyleHandler::resetStylesheets();
LanguageFactory::getInstance()->deleteLanguageCache();
CacheHandler::getInstance()->flushAll();
PackageUpdateServer::resetAll();
$this->eventHandler->fire(
new CacheCleared()
);
}
}
|
Fix errors with Blade parsing
For some reason, if `@endif` is directly next to a bare string it doesn't parse correctly. This is one way to fix it, another would be to wrap them in Blade "echo" tags: `{{ 'active' }}@endif` | <li class="@if($item->getItemClass()){{ $item->getItemClass() }}@endif @if($active)active @endif @if($item->hasItems())treeview @endif clearfix">
<a href="{{ $item->getUrl() }}" class="@if(count($appends) > 0) hasAppend @endif" @if($item->getNewTab())target="_blank"@endif>
<i class="{{ $item->getIcon() }}"></i>
<span>{{ $item->getName() }}</span>
@foreach($badges as $badge)
{!! $badge !!}
@endforeach
@if($item->hasItems())<i class="{{ $item->getToggleIcon() }} pull-right"></i>@endif
</a>
@foreach($appends as $append)
{!! $append !!}
@endforeach
@if(count($items) > 0)
<ul class="treeview-menu">
@foreach($items as $item)
{!! $item !!}
@endforeach
</ul>
@endif
</li>
| <li class="@if($item->getItemClass()){{ $item->getItemClass() }}@endif @if($active)active@endif @if($item->hasItems())treeview@endif clearfix">
<a href="{{ $item->getUrl() }}" class="@if(count($appends) > 0) hasAppend @endif" @if($item->getNewTab())target="_blank"@endif>
<i class="{{ $item->getIcon() }}"></i>
<span>{{ $item->getName() }}</span>
@foreach($badges as $badge)
{!! $badge !!}
@endforeach
@if($item->hasItems())<i class="{{ $item->getToggleIcon() }} pull-right"></i>@endif
</a>
@foreach($appends as $append)
{!! $append !!}
@endforeach
@if(count($items) > 0)
<ul class="treeview-menu">
@foreach($items as $item)
{!! $item !!}
@endforeach
</ul>
@endif
</li>
|
Remove unused parameter from object. | var LoadingBar = function(game, parent) {
Phaser.Group.call(this, game, parent);
// Images loaded by MyGame.Init
this.background = game.add.sprite(game.world.centerX, game.world.centerY, 'loadingBarBg');
this.background.anchor.setTo(0.5, 0.5);
this.add(this.background);
// Left to right loading bar
this.bar = game.add.sprite(game.world.centerX - 175, game.world.centerY - 16, 'loadingBar');
// Center to outsides loading bar.
//this.bar = game.add.sprite(game.world.centerX, game.world.centerY, 'loadingBar');
//this.bar.anchor.setTo(0.5, 0.5);
this.add(this.bar);
};
LoadingBar.prototype = Object.create(Phaser.Group.prototype);
LoadingBar.prototype.constructor = LoadingBar;
| var LoadingBar = function(game, parent, color) {
Phaser.Group.call(this, game, parent);
// Images loaded by MyGame.Init
this.background = game.add.sprite(game.world.centerX, game.world.centerY, 'loadingBarBg');
this.background.anchor.setTo(0.5, 0.5);
this.add(this.background);
// Left to right loading bar
this.bar = game.add.sprite(game.world.centerX - 175, game.world.centerY - 16, 'loadingBar');
// Center to outsides loading bar.
//this.bar = game.add.sprite(game.world.centerX, game.world.centerY, 'loadingBar');
//this.bar.anchor.setTo(0.5, 0.5);
this.add(this.bar);
};
LoadingBar.prototype = Object.create(Phaser.Group.prototype);
LoadingBar.prototype.constructor = LoadingBar;
|
Update helper to use \ as prefix for global functions.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
use Illuminate\Http\RedirectResponse;
if (! \function_exists('redirect_with_errors')) {
/**
* Redirect with input and errors.
*
* @param string $to
* @param \Illuminate\Contracts\Support\MessageBag|array $errors
*
* @return \Illuminate\Http\RedirectResponse
*/
function redirect_with_errors(string $to, $errors): RedirectResponse
{
return \redirect($to)->withInput()->withErrors($errors);
}
}
if (! \function_exists('redirect_with_message')) {
/**
* Queue notification and redirect.
*
* @param string $to
* @param string|null $message
* @param string $type
*
* @return mixed
*/
function redirect_with_message(
string $to,
?string $message = null,
string $type = 'success'
): RedirectResponse {
if (! \is_null($message)) {
\app('orchestra.messages')->add($type, $message);
}
return \redirect($to);
}
}
| <?php
use Illuminate\Http\RedirectResponse;
if (! function_exists('redirect_with_errors')) {
/**
* Redirect with input and errors.
*
* @param string $to
* @param \Illuminate\Contracts\Support\MessageBag|array $errors
*
* @return \Illuminate\Http\RedirectResponse
*/
function redirect_with_errors(string $to, $errors): RedirectResponse
{
return redirect($to)->withInput()->withErrors($errors);
}
}
if (! function_exists('redirect_with_message')) {
/**
* Queue notification and redirect.
*
* @param string $to
* @param string|null $message
* @param string $type
*
* @return mixed
*/
function redirect_with_message(
string $to,
?string $message = null,
string $type = 'success'
): RedirectResponse {
! is_null($message) && app('orchestra.messages')->add($type, $message);
return redirect($to);
}
}
|
Add a couple of things to console support provider. | <?php namespace Illuminate\Foundation\Providers;
use Illuminate\Support\ServiceProvider;
class ConsoleSupportServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* The provider class names.
*
* @var array
*/
protected $providers = array(
'Illuminate\Auth\GeneratorServiceProvider',
'Illuminate\Database\MigrationServiceProvider',
'Illuminate\Database\SeedServiceProvider',
'Illuminate\Foundation\Providers\ComposerServiceProvider',
'Illuminate\Foundation\Providers\PublisherServiceProvider',
'Illuminate\Queue\FailConsoleServiceProvider',
'Illuminate\Routing\GeneratorServiceProvider',
'Illuminate\Session\CommandsServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
);
/**
* An array of the service provider instances.
*
* @var array
*/
protected $instances = array();
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->instances = array();
foreach ($this->providers as $provider)
{
$this->instances[] = $this->app->register($provider);
}
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
$provides = array();
foreach ($this->providers as $provider)
{
$instance = $this->app->resolveProviderClass($provider);
$provides = array_merge($provides, $instance->provides());
}
return $provides;
}
}
| <?php namespace Illuminate\Foundation\Providers;
use Illuminate\Support\ServiceProvider;
class ConsoleSupportServiceProvider extends ServiceProvider {
/**
* The provider class names.
*
* @var array
*/
protected $providers = array(
'Illuminate\Auth\GeneratorServiceProvider',
'Illuminate\Foundation\Providers\ComposerServiceProvider',
'Illuminate\Foundation\Providers\PublisherServiceProvider',
'Illuminate\Queue\FailConsoleServiceProvider',
'Illuminate\Routing\GeneratorServiceProvider',
'Illuminate\Session\CommandsServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
);
/**
* An array of the service provider instances.
*
* @var array
*/
protected $instances = array();
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->instances = array();
foreach ($this->providers as $provider)
{
$this->instances[] = $this->app->register($provider);
}
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
$provides = array();
foreach ($this->providers as $provider)
{
$instance = $this->app->resolveProviderClass($provider);
$provides = array_merge($provides, $instance->provides());
}
return $provides;
}
}
|
:new: Support ternary in dead code removal plugin | // @flow
import * as t from '@babel/types'
// Empty out bodies of falsy parts of if/else statements
// to avoid requiring modules that aren't needed aka
// if (process.env.NODE_ENV === 'production') module.exports = require('./prod-version') else module.exports = require('./dev-version')
// OR
// module.exports = process.env.NODE_ENV === 'production' ? require('./prod-version') : require('./dev-version')
function processBooleanConditional(path) {
const { node } = path
const { test, consequent, alternate } = node
if (test && test.type === 'BooleanLiteral') {
if (test.value) {
if (alternate) {
if (t.isBlockStatement(alternate)) {
node.alternate = null
} else {
node.alternate = t.numericLiteral(0)
}
}
} else {
consequent.body = []
}
}
}
export default {
visitor: {
IfStatement: {
exit: processBooleanConditional,
},
ConditionalExpression: {
exit: processBooleanConditional,
},
},
}
| // @flow
// Empty out bodies of falsy parts of if/else statements
// to avoid requiring modules that aren't needed aka
// if (process.env.NODE_ENV === 'production') module.exports = require('./prod-version') else module.exports = require('./dev-version')
// OR
// module.exports = process.env.NODE_ENV === 'production' ? require('./prod-version') : require('./dev-version')
export default {
visitor: {
IfStatement: {
exit(path) {
const { node } = path
const { test, consequent } = node
if (test && test.type === 'BooleanLiteral') {
if (test.value) {
if (node.alternate) {
node.alternate = null
}
} else {
consequent.body = []
}
}
},
},
},
}
|
Fix - added two missing parameters to the constructor | package com.twu.biblioteca;
import com.twu.biblioteca.views.BibliotecaAppView;
import com.twu.biblioteca.views.BooksView;
import com.twu.biblioteca.views.MenuView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class BibliotecaAppTest {
@Mock
private BibliotecaAppView mockBibliotecaAppView;
@Mock
private BooksView mockBooksView;
@Mock
private MenuView mockMenuView;
@Mock
private Books mockBooks;
@Mock
private Menu mockMenu;
@Test
public void shouldInvokeMethodsOnBibliotecaAppViewBooksViewAndMenuView() throws Exception {
BibliotecaApp bibliotecaApp = new BibliotecaApp(mockBibliotecaAppView, mockBooksView, mockMenuView, mockBooks, mockMenu);
bibliotecaApp.start();
Mockito.verify(mockBibliotecaAppView).display("***Welcome to Biblioteca***");
Mockito.verify(mockMenuView).display();
}
} | package com.twu.biblioteca;
import com.twu.biblioteca.views.BibliotecaAppView;
import com.twu.biblioteca.views.BooksView;
import com.twu.biblioteca.views.MenuView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class BibliotecaAppTest {
@Mock
private BibliotecaAppView mockBibliotecaAppView;
@Mock
private BooksView mockBooksView;
@Mock
private MenuView mockMenuView;
@Test
public void shouldInvokeMethodsOnBibliotecaAppViewBooksViewAndMenuView() throws Exception {
BibliotecaApp bibliotecaApp = new BibliotecaApp(mockBibliotecaAppView, mockBooksView, mockMenuView);
bibliotecaApp.start();
Mockito.verify(mockBibliotecaAppView).display("***Welcome to Biblioteca***");
Mockito.verify(mockMenuView).display();
}
} |
Prepare for use as module | from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
fillcolor(FARBE)
shape(SHAPE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESSE*30)
left(90)
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
end_fill()
pu()
if brennt:
zeichneFlamme()
def zeichneFlamme():
left(90)
fd(GROESSE*430)
pd()
color("yellow")
dot(GROESSE*60)
color("black")
back(GROESSE*30)
pu()
home()
if __name__=="__main__":
zeichneKerze(True)
hideturtle()
| from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
fillcolor(FARBE)
shape(SHAPE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESSE*30)
left(90)
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
end_fill()
pu()
if brennt:
zeichneFlamme()
def zeichneFlamme():
left(90)
fd(GROESSE*430)
pd()
color("yellow")
dot(GROESSE*60)
color("black")
back(GROESSE*30)
pu()
home()
##zeichneKerze(brennt=False) # testweise erstmal nur nicht brennende Kerze
zeichneKerze(True)
hideturtle()
|
Fix broadcast sound on Baykok spawn | package totemic_commons.pokefenn.ceremony;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import totemic_commons.pokefenn.api.ceremony.Ceremony;
import totemic_commons.pokefenn.api.music.MusicInstrument;
import totemic_commons.pokefenn.entity.boss.EntityBaykok;
public class CeremonyBaykok extends Ceremony
{
public CeremonyBaykok(String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments)
{
super(name, musicNeeded, maxStartupTime, instruments);
}
@Override
public void effect(World world, BlockPos pos, int time)
{
if(world.isRemote || time != getEffectTime() - 1)
return;
world.playBroadcastSound(1023, pos, 0); //Wither spawn sound
BlockPos spos = pos.offset(EnumFacing.getHorizontal(world.rand.nextInt(4)));
EntityBaykok baykok = new EntityBaykok(world);
baykok.setPosition(spos.getX() + 0.5, spos.getY(), spos.getZ() + 0.5);
baykok.onInitialSpawn(world.getDifficultyForLocation(spos), null);
world.spawnEntityInWorld(baykok);
}
@Override
public int getEffectTime()
{
return 4 * 20;
}
}
| package totemic_commons.pokefenn.ceremony;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import totemic_commons.pokefenn.api.ceremony.Ceremony;
import totemic_commons.pokefenn.api.music.MusicInstrument;
import totemic_commons.pokefenn.entity.boss.EntityBaykok;
public class CeremonyBaykok extends Ceremony
{
public CeremonyBaykok(String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments)
{
super(name, musicNeeded, maxStartupTime, instruments);
}
@Override
public void effect(World world, BlockPos pos, int time)
{
if(world.isRemote || time != getEffectTime() - 1)
return;
world.playBroadcastSound(1013, pos, 0); //Wither spawn sound
BlockPos spos = pos.offset(EnumFacing.getHorizontal(world.rand.nextInt(4)));
EntityBaykok baykok = new EntityBaykok(world);
baykok.setPosition(spos.getX() + 0.5, spos.getY(), spos.getZ() + 0.5);
baykok.onInitialSpawn(world.getDifficultyForLocation(spos), null);
world.spawnEntityInWorld(baykok);
}
@Override
public int getEffectTime()
{
return 4 * 20;
}
}
|
Adjust for multiple bot instances | import asyncio
from urllib.request import urlopen
from jshbot import configurations
from jshbot.exceptions import BotException
from jshbot.utilities import future
__version__ = '0.1.1'
EXCEPTION = 'Carbonitex Data Pusher'
uses_configuration = True
def get_commands():
return []
async def bot_on_ready_boot(bot):
"""Periodically sends a POST request to Carbonitex."""
carbonitex_key = configurations.get(bot, __name__, key='key')
use_loop = configurations.get(bot, __name__, key='enabled')
while use_loop:
print("In Carbonitex loop")
await asyncio.sleep(60*60*2) # 2 hour delay
servercount = sum(len(it.servers) for it in bot.all_instances)
try:
await future(
urlopen, 'https://www.carbonitex.net/discord/data/botdata.php',
data={'key': carbonitex_key, 'servercount': servercount})
except Exception as e:
raise BotException(
EXCEPTION, "Failed to update Carbonitex data:", e)
| import asyncio
from urllib.request import urlopen
from jshbot import configurations
from jshbot.exceptions import BotException
from jshbot.utilities import future
__version__ = '0.1.0'
EXCEPTION = 'Carbonitex Data Pusher'
uses_configuration = True
def get_commands():
return []
async def bot_on_ready_boot(bot):
"""Periodically sends a POST request to Carbonitex."""
carbonitex_key = configurations.get(bot, __name__, key='key')
use_loop = configurations.get(bot, __name__, key='enabled')
while use_loop:
print("In Carbonitex loop")
await asyncio.sleep(60*60*2) # 2 hour delay
try:
await future(
urlopen, 'https://www.carbonitex.net/discord/data/botdata.php',
data={'key': carbonitex_key, 'servercount': len(bot.servers)})
except Exception as e:
raise BotException(
EXCEPTION, "Failed to update Carbonitex data:", e)
|
Change test data to work properly | <?php
class Kwc_Trl_Table_Table_Trl_TrlModel extends Kwf_Model_FnF
{
protected function _init()
{
$this->_siblingModels[] = new Kwf_Model_Field(array('fieldName'=>'data'));
parent::_init();
}
public function __construct($config = array())
{
$config['columns'] = array('id', 'component_id', 'data', 'master_id', 'visible');
$config['namespace'] = 'table_trl_model';
$config['primaryKey'] = 'id';
$config['data'] = array(
array('id'=>2, 'visible'=>1, 'component_id'=>'root-en_table', 'master_id'=>1 , 'data'=>'[]'),
array('id'=>1, 'visible'=>1, 'component_id'=>'root-en_table', 'data'=>'{"css_style":null,"column1":"Abc","column3":"234","column4":"","column5":"","column6":"","column7":"","column8":"","column9":"","column10":"","column11":"","column12":"","column13":"","column14":"","column15":"","column16":"","column17":"","column18":"","column19":"","column20":"","column21":"","column22":"","column23":"","column24":"","column25":"","column26":""}', 'master_id'=>2),
);
parent::__construct($config);
}
}
| <?php
class Kwc_Trl_Table_Table_Trl_TrlModel extends Kwf_Model_FnF
{
protected function _init()
{
$this->_siblingModels[] = new Kwf_Model_Field(array('fieldName'=>'data'));
parent::_init();
}
public function __construct($config = array())
{
$config['columns'] = array('id', 'component_id', 'data', 'master_id');
$config['namespace'] = 'table_trl_model';
$config['primaryKey'] = 'id';
$config['data'] = array(
array('id'=>1, 'component_id'=>'root-en_table', 'data'=>'{"css_style":null,"column1":"Abc","column3":"234","column4":"","column5":"","column6":"","column7":"","column8":"","column9":"","column10":"","column11":"","column12":"","column13":"","column14":"","column15":"","column16":"","column17":"","column18":"","column19":"","column20":"","column21":"","column22":"","column23":"","column24":"","column25":"","column26":""}', 'master_id'=>2),
);
parent::__construct($config);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.