text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
SGenJavaValidatorTest: Use Linker instead of LazyLinker
|
/**
* Copyright (c) 2012 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.generator.genmodel.test.util;
import org.eclipse.xtext.documentation.IEObjectDocumentationProvider;
import org.eclipse.xtext.linking.ILinker;
import org.eclipse.xtext.linking.impl.Linker;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.yakindu.sct.generator.genmodel.SGenRuntimeModule;
import org.yakindu.sct.generator.genmodel.ui.help.SGenUserHelpDocumentationProvider;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class SGenTestRuntimeModule extends SGenRuntimeModule {
@Override
public Class<? extends IScopeProvider> bindIScopeProvider() {
return SGenTestScopeProvider.class;
}
public Class<? extends IEObjectDocumentationProvider> bindIEObjectDocumentationProvider() {
return SGenUserHelpDocumentationProvider.class;
}
@Override
public Class<? extends ILinker> bindILinker() {
return Linker.class;
}
}
|
/**
* Copyright (c) 2012 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.generator.genmodel.test.util;
import org.eclipse.xtext.documentation.IEObjectDocumentationProvider;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.yakindu.sct.generator.genmodel.SGenRuntimeModule;
import org.yakindu.sct.generator.genmodel.ui.help.SGenUserHelpDocumentationProvider;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class SGenTestRuntimeModule extends SGenRuntimeModule {
@Override
public Class<? extends IScopeProvider> bindIScopeProvider() {
return SGenTestScopeProvider.class;
}
public Class<? extends IEObjectDocumentationProvider> bindIEObjectDocumentationProvider() {
return SGenUserHelpDocumentationProvider.class;
}
}
|
Update sniffer tests with new argument passing
|
from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
sniffer_params = {
'snifferendpoint': self.endpoint,
'sourceip': '147.102.239.229',
'host': 'dionyziz.com',
'interface': 'wlan0',
'port': '8080',
'calibration_wait': 0.0
}
self.sniffer = Sniffer(sniffer_params)
@patch('breach.sniffer.requests')
def test_sniffer_start(self, requests):
self.sniffer.start()
self.assertTrue(requests.post.called)
@patch('breach.sniffer.requests')
def test_sniffer_read(self, requests):
self.sniffer.read()
self.assertTrue(requests.get.called)
@patch('breach.sniffer.requests')
def test_sniffer_delete(self, requests):
self.sniffer.delete()
self.assertTrue(requests.post.called)
|
from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080')
@patch('breach.sniffer.requests')
def test_sniffer_start(self, requests):
self.sniffer.start()
self.assertTrue(requests.post.called)
@patch('breach.sniffer.requests')
def test_sniffer_read(self, requests):
self.sniffer.read()
self.assertTrue(requests.get.called)
@patch('breach.sniffer.requests')
def test_sniffer_delete(self, requests):
self.sniffer.delete()
self.assertTrue(requests.post.called)
|
Refactor code using es6 syntax
|
import passport from 'passport';
import passportLocal from 'passport-local';
import user from '../models';
const LocalStrategy = passportLocal.Strategy;
passport.serializeUser((sessionUser, done) => {
done(null, sessionUser.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, sessionUser) => done(err, sessionUser));
});
passport.use(new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
user.User.findOne({
where: {
username
}
}).then((users, err) => {
if (!users) {
return done(null, false, { message: 'Incorrect username' });
}
if (users.password !== req.body.password) {
return done(null, false, { message: ' Incorrect password.' });
}
return done(null, users);
}).catch(err => done(err));
}
));
module.exports = passport;
|
import passport from 'passport';
import passportLocal from 'passport-local';
import user from '../models';
const LocalStrategy = passportLocal.Strategy;
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
user.User.findOne({
where: {
username
}
}).then((users, err) => {
if (!users) {
return done(null, false, { message: 'Incorrect username' });
}
if (users.password !== req.body.password) {
return done(null, false, { message: ' Incorrect password.' });
}
return done(null, users);
}).catch(err => done(err));
}
));
module.exports = passport;
|
Implement ability to submit the reply form
|
import React from 'react';
import { Modal, Form, Button, Header } from 'semantic-ui-react';
const ReplyFormModal = ({ onChange, onSubmit, listingId, userId }) =>
<Modal trigger={<Button>Contact Them!</Button>}>
<Modal.Header>Contact Form</Modal.Header>
<Modal.Content>
<Modal.Description>
<Header>Send Them A Message!</Header>
<Form onSubmit={e => onSubmit(e, listingId, userId)}>
<Form.Input
name="title"
label="Subject"
placeholder="Subject"
onChange={e => onChange(e)}
/>
<Form.TextArea
name="body"
label="Message"
placeholder="Tell them who you are and why you are contacting them..."
onChange={e => onChange(e)}
/>
<Form.Button>Send Message</Form.Button>
</Form>
</Modal.Description>
</Modal.Content>
</Modal>;
ReplyFormModal.propTypes = {
listingId: React.PropTypes.number.isRequired,
userId: React.PropTypes.number.isRequired,
onChange: React.PropTypes.func.isRequired,
onSubmit: React.PropTypes.func.isRequired,
};
export default ReplyFormModal;
|
import React from 'react';
import { Modal, Form, Button, Header } from 'semantic-ui-react';
const ReplyFormModal = () => {
return (
<Modal trigger={<Button>Contact Them!</Button>}>
<Modal.Header>Contact Form</Modal.Header>
<Modal.Content>
<Modal.Description>
<Header>Send Them A Message!</Header>
<Form>
<Form.Input
name="title"
label="Subject"
placeholder="Subject"
/>
<Form.TextArea
name="body"
label="Message"
placeholder="Tell them who you are and why you are contacting them..."
/>
<Form.Button>Send Message</Form.Button>
</Form>
</Modal.Description>
</Modal.Content>
</Modal>
);
};
export default ReplyFormModal;
|
Fix issue where interfaces pass in _out
|
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
get_printout(out, opts)(data)
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return None
return outputters[out]
|
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
if opts is None:
opts = {}
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
outputters['pprint'](data)
outputters[out](data)
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return None
return outputters[out]
|
Disable less tests on php 7.4+
|
<?php
namespace Minify\Test;
use Minify_HTML_Helper;
/**
* @requires php < 7.3
* @see https://github.com/mrclay/minify/pull/685
*/
class LessSourceTest extends TestCase
{
public function setUp()
{
$this->realDocRoot = $_SERVER['DOCUMENT_ROOT'];
$_SERVER['DOCUMENT_ROOT'] = self::$document_root;
}
/**
* @link https://github.com/mrclay/minify/issues/500
*/
public function testLessTimestamp()
{
$baseDir = self::$test_files;
$mainLess = "$baseDir/main.less";
$includedLess = "$baseDir/included.less";
// touch timestamp with 1s difference
touch($mainLess);
sleep(1);
touch($includedLess);
$mtime1 = filemtime($mainLess);
$mtime2 = filemtime($includedLess);
$max = max($mtime1, $mtime2);
$options = array(
'groupsConfigFile' => "$baseDir/htmlHelper_groupsConfig.php",
);
$res = Minify_HTML_Helper::getUri('less', $options);
$this->assertEquals("/min/g=less&{$max}", $res);
}
}
|
<?php
namespace Minify\Test;
use Minify_HTML_Helper;
/**
* @requires php < 7.3
*/
class LessSourceTest extends TestCase
{
public function setUp()
{
$this->realDocRoot = $_SERVER['DOCUMENT_ROOT'];
$_SERVER['DOCUMENT_ROOT'] = self::$document_root;
}
/**
* @link https://github.com/mrclay/minify/issues/500
*/
public function testLessTimestamp()
{
$baseDir = self::$test_files;
$mainLess = "$baseDir/main.less";
$includedLess = "$baseDir/included.less";
// touch timestamp with 1s difference
touch($mainLess);
sleep(1);
touch($includedLess);
$mtime1 = filemtime($mainLess);
$mtime2 = filemtime($includedLess);
$max = max($mtime1, $mtime2);
$options = array(
'groupsConfigFile' => "$baseDir/htmlHelper_groupsConfig.php",
);
$res = Minify_HTML_Helper::getUri('less', $options);
$this->assertEquals("/min/g=less&{$max}", $res);
}
}
|
Add real diff reporter to list of defaults
|
package reporters
import (
"os/exec"
"github.com/approvals/go-approval-tests/utils"
)
// NewFrontLoadedReporter creates the default front loaded reporter.
func NewFrontLoadedReporter() Reporter {
return NewFirstWorkingReporter(
NewContinuousIntegrationReporter(),
)
}
// NewDiffReporter creates the default diff reporter.
func NewDiffReporter() Reporter {
return NewFirstWorkingReporter(
NewBeyondCompareReporter(),
NewIntelliJReporter(),
NewFileMergeReporter(),
NewVSCodeReporter(),
NewGoLandReporter(),
NewRealDiffReporter(),
NewPrintSupportedDiffProgramsReporter(),
NewQuietReporter(),
)
}
func launchProgram(programName, approved string, args ...string) bool {
if !utils.DoesFileExist(programName) {
return false
}
utils.EnsureExists(approved)
cmd := exec.Command(programName, args...)
cmd.Start()
return true
}
|
package reporters
import (
"os/exec"
"github.com/approvals/go-approval-tests/utils"
)
// NewFrontLoadedReporter creates the default front loaded reporter.
func NewFrontLoadedReporter() Reporter {
return NewFirstWorkingReporter(
NewContinuousIntegrationReporter(),
)
}
// NewDiffReporter creates the default diff reporter.
func NewDiffReporter() Reporter {
return NewFirstWorkingReporter(
NewBeyondCompareReporter(),
NewIntelliJReporter(),
NewFileMergeReporter(),
NewVSCodeReporter(),
NewGoLandReporter(),
NewPrintSupportedDiffProgramsReporter(),
NewQuietReporter(),
)
}
func launchProgram(programName, approved string, args ...string) bool {
if !utils.DoesFileExist(programName) {
return false
}
utils.EnsureExists(approved)
cmd := exec.Command(programName, args...)
cmd.Start()
return true
}
|
Delete isn't a post method
This should fix the issue described in this stack overflow question https://stackoverflow.com/questions/49714538/unable-to-delete-an-object-parse-server
|
/*
* Copyright 2015 Chidiebere Okwudire.
*
* 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.
*
* Original implementation adapted from Thiago Locatelli's Parse4J project
* (see https://github.com/thiagolocatelli/parse4j)
*/
package com.parse4cn1.command;
import com.codename1.io.ConnectionRequest;
import com.parse4cn1.ParseException;
/**
* This class defines a command for deleting resources from the Parse server.
*/
public class ParseDeleteCommand extends ParseCommand {
private final String endPoint;
private String objectId;
public ParseDeleteCommand(String endPoint, String objectId) {
this.endPoint = endPoint;
this.objectId = objectId;
}
public ParseDeleteCommand(String endPoint) {
this.endPoint = endPoint;
}
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
setupDefaultHeaders();
request.setPost(false);
request.setHttpMethod("DELETE");
request.setUrl(getUrl(endPoint, objectId));
}
}
|
/*
* Copyright 2015 Chidiebere Okwudire.
*
* 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.
*
* Original implementation adapted from Thiago Locatelli's Parse4J project
* (see https://github.com/thiagolocatelli/parse4j)
*/
package com.parse4cn1.command;
import com.codename1.io.ConnectionRequest;
import com.parse4cn1.ParseException;
/**
* This class defines a command for deleting resources from the Parse server.
*/
public class ParseDeleteCommand extends ParseCommand {
private final String endPoint;
private String objectId;
public ParseDeleteCommand(String endPoint, String objectId) {
this.endPoint = endPoint;
this.objectId = objectId;
}
public ParseDeleteCommand(String endPoint) {
this.endPoint = endPoint;
}
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
setupDefaultHeaders();
request.setPost(true);
request.setHttpMethod("DELETE");
request.setUrl(getUrl(endPoint, objectId));
}
}
|
Fix a bug with application stdout print
|
from .baselauncher import BaseLauncher
class BaseTestCases(BaseLauncher):
def handle_problem_set(self, name, problems):
for i, prob in enumerate(problems):
answer_got = self.get_answer(prob, name, i, len(problems))
if not answer_got:
return False
if not prob.validate(answer_got):
try:
answer_expected = prob.Answer().for_problem(prob)
except NotImplementedError:
print("\nFAILED. STDIN:\n{}\nGOT:\n{}"
.format(prob.to_stdin(), answer_got.to_stdout()))
else:
print("\nFAILED. STDIN:\n{}\nEXPECTED:\n{}\nGOT:\n{}"
.format(prob.to_stdin(), answer_expected.to_stdout(), answer_got.to_stdout()))
return False
print("")
return True
|
from .baselauncher import BaseLauncher
class BaseTestCases(BaseLauncher):
def handle_problem_set(self, name, problems):
for i, prob in enumerate(problems):
answer_got = self.get_answer(prob, name, i, len(problems))
if not answer_got:
return False
if not prob.validate(answer_got):
try:
answer_expected = prob.Answer().for_problem(prob)
except NotImplementedError:
print("\nFAILED. STDIN:\n{}\nGOT:\n{}"
.format(prob.to_stdin(), stdout))
else:
print("\nFAILED. STDIN:\n{}\nEXPECTED:\n{}\nGOT:\n{}"
.format(prob.to_stdin(), answer_expected.to_stdout(), stdout))
return False
print("")
return True
|
Fix leftover reference to v4.0.0-alpha.6
Running `./build/change-version.js v4.0.0-alpha.6 v4.0.0` fixed this,
so the version change script works fine. I'm presuming instead this
change was just omitted from 35f80bb12e4e, and then wouldn't have
been caught by subsequent runs of `change-version`, since it only
ever replaces the exact old version string specified.
|
import $ from 'jquery'
import Alert from './alert'
import Button from './button'
import Carousel from './carousel'
import Collapse from './collapse'
import Dropdown from './dropdown'
import Modal from './modal'
import Popover from './popover'
import Scrollspy from './scrollspy'
import Tab from './tab'
import Tooltip from './tooltip'
import Util from './util'
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(($) => {
if (typeof $ === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.')
}
const version = $.fn.jquery.split(' ')[0].split('.')
const minMajor = 1
const ltMajor = 2
const minMinor = 9
const minPatch = 1
const maxMajor = 4
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')
}
})($)
export {
Util,
Alert,
Button,
Carousel,
Collapse,
Dropdown,
Modal,
Popover,
Scrollspy,
Tab,
Tooltip
}
|
import $ from 'jquery'
import Alert from './alert'
import Button from './button'
import Carousel from './carousel'
import Collapse from './collapse'
import Dropdown from './dropdown'
import Modal from './modal'
import Popover from './popover'
import Scrollspy from './scrollspy'
import Tab from './tab'
import Tooltip from './tooltip'
import Util from './util'
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(($) => {
if (typeof $ === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.')
}
const version = $.fn.jquery.split(' ')[0].split('.')
const minMajor = 1
const ltMajor = 2
const minMinor = 9
const minPatch = 1
const maxMajor = 4
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')
}
})($)
export {
Util,
Alert,
Button,
Carousel,
Collapse,
Dropdown,
Modal,
Popover,
Scrollspy,
Tab,
Tooltip
}
|
Improve `arc lint --output summary`
Summary:
This currently output like this:
file_a:
file_b:
file_c:
Warning on line 29: blah blah
This isn't especially useful and can't be piped to other tools. Instead, emit output like:
file_c:29:Warning: blah blah
This is greppable / pipeable.
Test Plan: Ran `arc lint --output summary`.
Reviewers: btrahan
Reviewed By: btrahan
CC: aran
Differential Revision: https://secure.phabricator.com/D7788
|
<?php
/**
* Shows lint messages to the user.
*
* @group lint
*/
final class ArcanistLintSummaryRenderer extends ArcanistLintRenderer {
public function renderLintResult(ArcanistLintResult $result) {
$messages = $result->getMessages();
$path = $result->getPath();
$text = array();
foreach ($messages as $message) {
$name = $message->getName();
$severity = ArcanistLintSeverity::getStringForSeverity(
$message->getSeverity());
$line = $message->getLine();
$text[] = "{$path}:{$line}:{$severity}: {$name}\n";
}
return implode("", $text);
}
public function renderOkayResult() {
return
phutil_console_format("<bg:green>** OKAY **</bg> No lint warnings.\n");
}
}
|
<?php
/**
* Shows lint messages to the user.
*
* @group lint
*/
final class ArcanistLintSummaryRenderer extends ArcanistLintRenderer {
public function renderLintResult(ArcanistLintResult $result) {
$messages = $result->getMessages();
$path = $result->getPath();
$text = array();
$text[] = $path.":";
foreach ($messages as $message) {
$name = $message->getName();
$severity = ArcanistLintSeverity::getStringForSeverity(
$message->getSeverity());
$line = $message->getLine();
$text[] = " {$severity} on line {$line}: {$name}";
}
$text[] = null;
return implode("\n", $text);
}
public function renderOkayResult() {
return
phutil_console_format("<bg:green>** OKAY **</bg> No lint warnings.\n");
}
}
|
Update js interface to allow more params
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var LastPhotoTaken = {
getLastPhoto: function(max, startTime, endTime, scanStartTime, onSuccess, onFailure){
cordova.exec(onSuccess, onFailure, "LastPhotoTaken", "getLastPhoto", [max, startTime, endTime, scanStartTime]);
}
};
module.exports = LastPhotoTaken;
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var LastPhotoTaken = {
getLastPhoto: function(max, startTime, endTime, onSuccess, onFailure){
cordova.exec(onSuccess, onFailure, "LastPhotoTaken", "getLastPhoto", [max, startTime, endTime]);
}
};
module.exports = LastPhotoTaken;
|
Put Tejas email in contact form
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'tejas.sathe@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
Add a "FIXME" comment for the disabled test so it shows up as a note in Eclipse (this idea was suggested awhile ago by brozow).
|
package org.opennms.netmgt.vulnscand;
import junit.framework.TestCase;
import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueImpl;
import org.opennms.netmgt.config.VulnscandConfigFactory;
public class SchedulerTest extends TestCase {
protected void setUp() throws Exception {
System.setProperty("opennms.home", "src/test/test-configurations/vulnscand");
VulnscandConfigFactory.init();
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
// FIXME
public void FIXMEtestCreate() throws Exception {
FifoQueue q = new FifoQueueImpl();
Scheduler scheduler = new Scheduler(q);
Vulnscand vulnscand = null;
vulnscand.initialize();
}
}
|
package org.opennms.netmgt.vulnscand;
import junit.framework.TestCase;
import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueImpl;
import org.opennms.netmgt.config.VulnscandConfigFactory;
public class SchedulerTest extends TestCase {
protected void setUp() throws Exception {
System.setProperty("opennms.home", "src/test/test-configurations/vulnscand");
VulnscandConfigFactory.init();
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void FIXMEtestCreate() throws Exception {
FifoQueue q = new FifoQueueImpl();
Scheduler scheduler = new Scheduler(q);
Vulnscand vulnscand = null;
vulnscand.initialize();
}
}
|
Remove starred expression for 3.4 compatibility
|
import enum
import functools
import operator
import struct
class Packet(enum.IntEnum):
connect = 0
disconnect = 1
data = 2
ack = 3
end = 4
def build_data_packet(window, blockseed, block):
payload = struct.pack('!II', window, blockseed) + block
return build_packet(Packet.data, payload)
def build_shift_packet(window_num):
payload = struct.pack('!I', window_num)
return build_packet(Packet.ack, payload)
def build_packet(type_, payload):
crc = functools.reduce(operator.xor, payload, type_)
packet = struct.pack('!B%dsB' % len(payload), type_, payload, crc)
return packet
def clean_packet(packet):
type_, payload, pack_crc = struct.unpack('!B%dsB' % (len(packet)-2), packet)
crc = functools.reduce(operator.xor, payload, type_)
if crc != pack_crc:
raise ValueError('Invalid packet check sum.')
if type_ == Packet.ack:
payload = struct.unpack('!I', payload)
elif type_ == Packet.data:
payload = struct.unpack('!II%ds' % (len(payload) - 8), payload)
return type_, payload
|
import enum
import functools
import operator
import struct
class Packet(enum.IntEnum):
connect = 0
disconnect = 1
data = 2
ack = 3
end = 4
def build_data_packet(window, blockseed, block):
payload = struct.pack('!II', window, blockseed) + block
return build_packet(Packet.data, payload)
def build_shift_packet(window_num):
payload = struct.pack('!I', window_num)
return build_packet(Packet.ack, payload)
def build_packet(type_, payload):
crc = functools.reduce(operator.xor, payload, type_)
packet = struct.pack('!B%dsB' % len(payload), type_, payload, crc)
return packet
def clean_packet(packet):
type_, payload, pack_crc = struct.unpack('!B%dsB' % (len(packet)-2), packet)
crc = functools.reduce(operator.xor, payload, type_)
if crc != pack_crc:
raise ValueError('Invalid packet check sum.')
if type_ == Packet.ack:
payload = struct.unpack('!I', payload)
elif type_ == Packet.data:
payload = *struct.unpack('!II', payload[:8]), payload[8:]
return type_, payload
|
Change admin sort for slots
|
"""Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
column_default_sort='start',
column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
|
"""Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
|
Fix check for empty min/max years.
|
from django import template
from django.db.models import Min, Max
from gnotty.models import IRCMessage
from gnotty.conf import settings
register = template.Library()
@register.inclusion_tag("gnotty/includes/nav.html", takes_context=True)
def gnotty_nav(context):
min_max = IRCMessage.objects.aggregate(Min("message_time"),
Max("message_time"))
if min_max.values()[0]:
years = range(min_max["message_time__max"].year,
min_max["message_time__min"].year - 1, -1)
else:
years = []
context["IRC_CHANNEL"] = settings.IRC_CHANNEL
context["years"] = years
return context
|
from django import template
from django.db.models import Min, Max
from gnotty.models import IRCMessage
from gnotty.conf import settings
register = template.Library()
@register.inclusion_tag("gnotty/includes/nav.html", takes_context=True)
def gnotty_nav(context):
min_max = IRCMessage.objects.aggregate(Min("message_time"),
Max("message_time"))
if min_max:
years = range(min_max["message_time__max"].year,
min_max["message_time__min"].year - 1, -1)
else:
years = []
context["IRC_CHANNEL"] = settings.IRC_CHANNEL
context["years"] = years
return context
|
Use .name to lookup tag name under fruitloops
|
/*global viewTemplateOverrides, createErrorMessage */
Handlebars.registerViewHelper('view', {
factory: function(args, options) {
var View = args.length >= 1 ? args[0] : Thorax.View;
return Thorax.Util.getViewInstance(View, options.options);
},
// ensure generated placeholder tag in template
// will match tag of view instance
modifyHTMLAttributes: function(htmlAttributes, instance) {
// Handle fruitloops tag name lookup via the .name case.
htmlAttributes.tagName = (instance.el.tagName || instance.el.name || '').toLowerCase();
},
callback: function(view) {
var instance = arguments[arguments.length-1],
options = instance._helperOptions.options,
placeholderId = instance.cid;
// view will be the argument passed to the helper, if it was
// a string, a new instance was created on the fly, ok to pass
// hash arguments, otherwise need to throw as templates should
// not introduce side effects to existing view instances
if (!_.isString(view) && options.hash && _.keys(options.hash).length > 0) {
throw new Error(createErrorMessage('view-helper-hash-args'));
}
if (options.fn) {
viewTemplateOverrides[placeholderId] = options.fn;
}
}
});
|
/*global viewTemplateOverrides, createErrorMessage */
Handlebars.registerViewHelper('view', {
factory: function(args, options) {
var View = args.length >= 1 ? args[0] : Thorax.View;
return Thorax.Util.getViewInstance(View, options.options);
},
// ensure generated placeholder tag in template
// will match tag of view instance
modifyHTMLAttributes: function(htmlAttributes, instance) {
htmlAttributes.tagName = instance.el.tagName.toLowerCase();
},
callback: function(view) {
var instance = arguments[arguments.length-1],
options = instance._helperOptions.options,
placeholderId = instance.cid;
// view will be the argument passed to the helper, if it was
// a string, a new instance was created on the fly, ok to pass
// hash arguments, otherwise need to throw as templates should
// not introduce side effects to existing view instances
if (!_.isString(view) && options.hash && _.keys(options.hash).length > 0) {
throw new Error(createErrorMessage('view-helper-hash-args'));
}
if (options.fn) {
viewTemplateOverrides[placeholderId] = options.fn;
}
}
});
|
Add plugin state to logging
|
/* eslint-disable no-console */
import { CONFIG } from '../constants';
import { Socket } from 'phoenix';
import { startPlugin } from '..';
import listenAuth from './listenAuth';
import handleNotifications from './handleNotifications';
import handleWork from './handleWork';
import renderIcon from './renderIcon';
export const startChromePlugin = (auth, chrome, enhancer, socketConstructor = Socket) => {
const reloader = () => window.location.reload(true);
const plugin = startPlugin({ auth, enhancer, reloader, socketConstructor });
const store = plugin.getStore();
const getStore = () => store;
listenAuth(store, chrome);
handleNotifications(store, chrome);
renderIcon(store, chrome);
handleWork(store, chrome);
if (CONFIG.env === 'dev') {
// redux dev tools don't work with the plugin, so we have a dumb
// replacement.
store.subscribe(() => {
const { worker, socket, plugin: pluginState } = store.getState();
console.log('Worker:', worker.toJS(),
'Socket:', socket.toJS(),
'Plugin:', pluginState.toJS());
});
}
return { getStore };
};
|
/* eslint-disable no-console */
import { CONFIG } from '../constants';
import { Socket } from 'phoenix';
import { startPlugin } from '..';
import listenAuth from './listenAuth';
import handleNotifications from './handleNotifications';
import handleWork from './handleWork';
import renderIcon from './renderIcon';
export const startChromePlugin = (auth, chrome, enhancer, socketConstructor = Socket) => {
const reloader = () => window.location.reload(true);
const plugin = startPlugin({ auth, enhancer, reloader, socketConstructor });
const store = plugin.getStore();
const getStore = () => store;
listenAuth(store, chrome);
handleNotifications(store, chrome);
renderIcon(store, chrome);
handleWork(store, chrome);
if (CONFIG.env === 'dev') {
// redux dev tools don't work with the plugin, so we have a dumb
// replacement.
store.subscribe(() => {
const { worker, socket } = store.getState();
console.log('Worker:', worker.toJS(), 'Socket:', socket.toJS());
});
}
return { getStore };
};
|
Update ember-addon file to be compatible with latest master
|
'use strict';
var path = require('path');
var commands = require('./lib/commands');
var postBuild = require('./lib/tasks/post-build');
module.exports = {
name: 'ember-cli-cordova',
treePaths: {
app: 'app',
styles: 'app/styles',
templates: 'app/templates',
addon: 'addon',
'addon-styles': 'addon/styles',
'addon-templates': 'addon/templates',
vendor: 'vendor',
'test-support': 'test-support',
'public': 'public'
},
blueprintsPath: function() {
return path.join(__dirname, 'blueprints');
},
includedCommands: function() {
return commands;
},
cdvConfig: function() {
var config = this.project.config('development');
if (config.cordova) {
return config.cordova
}
return {};
},
postBuild: function() {
return postBuild(this.project, this.cdvConfig())();
}
};
|
'use strict';
var path = require('path');
var commands = require('./lib/commands');
var postBuild = require('./lib/tasks/post-build');
module.exports = {
name: 'ember-cli-cordova',
init: function() {
this.setConfig();
},
blueprintsPath: function() {
return path.join(__dirname, 'blueprints');
},
includedCommands: function() {
return commands;
},
setConfig: function(){
var env = this.project.config('development');
if(!this.config) {
this.config = {};
}
if (env.cordova) {
this.config = env.cordova;
}
},
postBuild: function() {
return postBuild(this.project, this.config)();
}
};
|
Stop rollup bundling for example
|
import { terser } from 'rollup-plugin-terser'
import pkg from './package.json'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
const umd = { format: 'umd', name: 'A11yDialog', exports: 'default' }
const es = { format: 'es' }
const minify = {
plugins: [terser()],
banner: () => `/*! a11y-dialog ${pkg.version} — © Kitty Giraudel */`,
}
export default {
input: 'a11y-dialog.js',
output: [
// Main files
{ file: 'dist/a11y-dialog.js', ...umd },
{ file: 'dist/a11y-dialog.esm.js', ...es },
// Minified versions
{ file: 'dist/a11y-dialog.min.js', ...umd, ...minify },
{ file: 'dist/a11y-dialog.esm.min.js', ...es, ...minify },
],
plugins: [nodeResolve(), commonjs({ include: 'node_modules/**' })],
}
|
import { terser } from 'rollup-plugin-terser'
import pkg from './package.json'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
const umd = { format: 'umd', name: 'A11yDialog', exports: 'default' }
const es = { format: 'es' }
const minify = {
plugins: [terser()],
banner: () => `/*! a11y-dialog ${pkg.version} — © Kitty Giraudel */`,
}
export default {
input: 'a11y-dialog.js',
output: [
// Main files
{ file: 'dist/a11y-dialog.js', ...umd },
{ file: 'dist/a11y-dialog.esm.js', ...es },
// Minified versions
{ file: 'dist/a11y-dialog.min.js', ...umd, ...minify },
{ file: 'dist/a11y-dialog.esm.min.js', ...es, ...minify },
// Copy of the main file for example and tests
{ file: 'example/a11y-dialog.js', ...umd },
],
plugins: [nodeResolve(), commonjs({ include: 'node_modules/**' })],
}
|
Rename internal properties of SmoothHelper to avoid collisions with
classes that use the mixin.
|
Dashboard.SmoothHelper = Ember.Mixin.create({
_smoothHelperInterval: 10,
_smoothHelperProperties: function() {
return {};
}.property(),
setSmooth: function(property, value, duration) {
var p = this.get('_smoothHelperProperties');
var d = typeof duration !== 'undefined' ? duration : 1000;
if (p[property] && p[property].intervalCall) {
clearInterval(p[property].intervalCall);
}
p[property] = {
initialValue: this.get(property),
targetValue: value,
currentX: 0,
step: Math.PI / (d / this.get('_smoothHelperInterval') * 2)
};
var that = this;
p[property].intervalCall = setInterval(function() {
if (p[property].currentX >= Math.PI / 2)
clearInterval(p[property].intervalCall);
else {
that.set(property, p[property].initialValue + (p[property].targetValue - p[property].initialValue) * Math.sin(p[property].currentX));
p[property].currentX = p[property].currentX + p[property].step;
}
}, this.get('_smoothHelperInterval'));
}
});
|
Dashboard.SmoothHelper = Ember.Mixin.create({
interval: 10,
properties: function() {
return {};
}.property(),
setSmooth: function(property, value, duration) {
var p = this.get('properties');
var d = typeof duration !== 'undefined' ? duration : 1000;
if (p[property] && p[property].intervalCall) {
clearInterval(p[property].intervalCall);
}
p[property] = {
initialValue: this.get(property),
targetValue: value,
currentX: 0,
step: Math.PI / (d / this.get('interval') * 2)
};
var that = this;
p[property].intervalCall = setInterval(function() {
if (p[property].currentX >= Math.PI / 2)
clearInterval(p[property].intervalCall);
else {
that.set(property, p[property].initialValue + (p[property].targetValue - p[property].initialValue) * Math.sin(p[property].currentX));
p[property].currentX = p[property].currentX + p[property].step;
}
}, this.get('interval'));
}
});
|
Accordion: Update test helper to use QUnit.push instead of deepEqual to get useful stacktrace
|
function accordion_state( accordion ) {
var expected = $.makeArray( arguments ).slice( 1 );
var actual = accordion.find( ".ui-accordion-content" ).map(function() {
return $( this ).css( "display" ) === "none" ? 0 : 1;
}).get();
QUnit.push( QUnit.equiv(actual, expected), actual, expected );
}
function accordion_equalHeights( accordion, min, max ) {
var sizes = [];
accordion.find( ".ui-accordion-content" ).each(function() {
sizes.push( $( this ).outerHeight() );
});
ok( sizes[ 0 ] >= min && sizes[ 0 ] <= max,
"must be within " + min + " and " + max + ", was " + sizes[ 0 ] );
deepEqual( sizes[ 0 ], sizes[ 1 ] );
deepEqual( sizes[ 0 ], sizes[ 2 ] );
}
function accordion_setupTeardown() {
var animate = $.ui.accordion.prototype.options.animate;
return {
setup: function() {
$.ui.accordion.prototype.options.animate = false;
},
teardown: function() {
$.ui.accordion.prototype.options.animate = animate;
}
};
}
|
function accordion_state( accordion ) {
var expected = $.makeArray( arguments ).slice( 1 );
var actual = accordion.find( ".ui-accordion-content" ).map(function() {
return $( this ).css( "display" ) === "none" ? 0 : 1;
}).get();
deepEqual( actual, expected );
}
function accordion_equalHeights( accordion, min, max ) {
var sizes = [];
accordion.find( ".ui-accordion-content" ).each(function() {
sizes.push( $( this ).outerHeight() );
});
ok( sizes[ 0 ] >= min && sizes[ 0 ] <= max,
"must be within " + min + " and " + max + ", was " + sizes[ 0 ] );
deepEqual( sizes[ 0 ], sizes[ 1 ] );
deepEqual( sizes[ 0 ], sizes[ 2 ] );
}
function accordion_setupTeardown() {
var animate = $.ui.accordion.prototype.options.animate;
return {
setup: function() {
$.ui.accordion.prototype.options.animate = false;
},
teardown: function() {
$.ui.accordion.prototype.options.animate = animate;
}
};
}
|
Fix incomplete update to botocross 1.1.1
|
#!/usr/bin/env python
from distutils.core import setup
from setuptools import find_packages
import stackformation
import sys
if sys.version_info <= (2, 5):
error = "ERROR: stackformation requires Python Version 2.6 or above...exiting."
print >> sys.stderr, error
sys.exit(1)
setup(name="stackformation",
version=stackformation.__version__,
author="Steffen Opel",
packages=find_packages(),
license="Apache 2",
platforms="Posix; MacOS X; Windows",
install_requires=[
"boto >= 2.6.0",
"botocross >= 1.1.1",
],
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet",
],
)
|
#!/usr/bin/env python
from distutils.core import setup
from setuptools import find_packages
import stackformation
import sys
if sys.version_info <= (2, 5):
error = "ERROR: stackformation requires Python Version 2.6 or above...exiting."
print >> sys.stderr, error
sys.exit(1)
setup(name="stackformation",
version=stackformation.__version__,
author="Steffen Opel",
packages=find_packages(),
license="Apache 2",
platforms="Posix; MacOS X; Windows",
install_requires=[
"boto >= 2.6.0",
"botocross >= 1.1.0",
],
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet",
],
)
|
Add handle method in order to delegate to fire method for Laravel 5.5
|
<?php
namespace Torann\Currency\Console;
use Illuminate\Console\Command;
class Cleanup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'currency:cleanup';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Cleanup currency cache';
/**
* Currency instance
*
* @var \Torann\Currency\Currency
*/
protected $currency;
/**
* Create a new command instance.
*/
public function __construct()
{
$this->currency = app('currency');
parent::__construct();
}
/**
* Execute the console command for Laravel 5.4 and below
*
* @return void
*/
public function fire()
{
$this->handle();
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
// Clear cache
$this->currency->clearCache();
$this->comment('Currency cache cleaned.');
// Force the system to rebuild cache
$this->currency->getCurrencies();
$this->comment('Currency cache rebuilt.');
}
}
|
<?php
namespace Torann\Currency\Console;
use Illuminate\Console\Command;
class Cleanup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'currency:cleanup';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Cleanup currency cache';
/**
* Currency instance
*
* @var \Torann\Currency\Currency
*/
protected $currency;
/**
* Create a new command instance.
*/
public function __construct()
{
$this->currency = app('currency');
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
// Clear cache
$this->currency->clearCache();
$this->comment('Currency cache cleaned.');
// Force the system to rebuild cache
$this->currency->getCurrencies();
$this->comment('Currency cache rebuilt.');
}
}
|
Fix error when part of profile data is unset
|
<?php
namespace BNETDocs\Models\User;
use \CarlBennett\MVC\Libraries\Model;
class View extends Model {
public $biography;
public $contributions;
public $discord;
public $documents;
public $facebook;
public $facebook_uri;
public $github;
public $github_uri;
public $instagram;
public $instagram_uri;
public $news_posts;
public $packets;
public $profiledata;
public $phone;
public $phone_uri;
public $reddit;
public $reddit_uri;
public $servers;
public $skype;
public $skype_uri;
public $steam_id;
public $steam_uri;
public $sum_documents;
public $sum_news_posts;
public $sum_packets;
public $sum_servers;
public $twitter;
public $twitter_uri;
public $user;
public $user_est;
public $user_id;
public $user_profile;
public $website;
public $website_uri;
}
|
<?php
namespace BNETDocs\Models\User;
use \CarlBennett\MVC\Libraries\Model;
class View extends Model {
public $biography;
public $contributions;
public $discord;
public $documents;
public $facebook;
public $facebook_uri;
public $github;
public $github_uri;
public $instagram;
public $instagram_uri;
public $news_posts;
public $packets;
public $profiledata;
public $reddit;
public $reddit_uri;
public $servers;
public $skype;
public $skype_uri;
public $steam_id;
public $steam_uri;
public $sum_documents;
public $sum_news_posts;
public $sum_packets;
public $sum_servers;
public $twitter;
public $twitter_uri;
public $user;
public $user_est;
public $user_id;
public $user_profile;
public $website;
public $website_uri;
}
|
Remove whitespace from en dash
https://stackoverflow.com/questions/5078239
|
<!-- Sticky Header -->
<div id="header-placeholder" role="presentation">
<header role="banner">
<div class="container">
<div class="header-left">
<a href="http://www.artic.edu/">
<img src="images/logo.svg" alt="Art Institute of Chicago">
</a>
<span class="exhibit">
<span class="title">Gauguin</span>
</span>
</div>
<div class="header-right">
<span class="dates">
<span class="start">{{ $page->dates['start'] }}</span
><span class="dash">–</span
><span class="end">{{ $page->dates['end'] }}</span>
</span>
<span class="buttons" role="menu">
<a class="btn btn-small btn-member" href="https://sales.artic.edu/memberships" role="menuitem">Become a Member</a>
<a class="btn btn-small btn-ticket" href="https://sales.artic.edu/admissiondate" role="menuitem"><span class="verb">Buy </span>Tickets</a>
</span>
</div>
</div>
@if ($page->subHeader)
<div class="sub-header">
{{ $page->subHeader }}
</div>
@endif
</header>
{{-- Wrapping header into the placeholder prooved to provide smoother transitions --}}
</div>
|
<!-- Sticky Header -->
<div id="header-placeholder" role="presentation">
<header role="banner">
<div class="container">
<div class="header-left">
<a href="http://www.artic.edu/">
<img src="images/logo.svg" alt="Art Institute of Chicago">
</a>
<span class="exhibit">
<span class="title">Gauguin</span>
</span>
</div>
<div class="header-right">
<span class="dates">
<span class="start">{{ $page->dates['start'] }}</span>
<span class="dash">–</span>
<span class="end">{{ $page->dates['end'] }}</span>
</span>
<span class="buttons" role="menu">
<a class="btn btn-small btn-member" href="https://sales.artic.edu/memberships" role="menuitem">Become a Member</a>
<a class="btn btn-small btn-ticket" href="https://sales.artic.edu/admissiondate" role="menuitem"><span class="verb">Buy </span>Tickets</a>
</span>
</div>
</div>
@if ($page->subHeader)
<div class="sub-header">
{{ $page->subHeader }}
</div>
@endif
</header>
{{-- Wrapping header into the placeholder prooved to provide smoother transitions --}}
</div>
|
Fix Client Send Empty message
|
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import model.Message;
import view.MessageBoard;
public class MessageBoardController implements ActionListener{
private Controller controller;
public MessageBoardController(Controller controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
MessageBoard messageBoard =(MessageBoard)((JButton)e.getSource()).getParent();
//System.out.println("Send this message: "+messageBoard.getMessage()+" to: "+messageBoard.getUser().getUserName());
String mess = messageBoard.getMessage();
if(!mess.equals("")){
System.out.println("in controller "+mess);
Message messageToServet = new Message(messageBoard.getUser().getUserName(),mess);
Message messageToDoc = new Message(controller.getModel().getAuthUser().getUserName(),mess);
messageToDoc.printMessage(messageBoard.getUser().getDoc());
controller.getServerHandler().sendMessage(messageToServet);
}
}
}
|
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import model.Message;
import view.MessageBoard;
public class MessageBoardController implements ActionListener{
private Controller controller;
public MessageBoardController(Controller controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
MessageBoard messageBoard =(MessageBoard)((JButton)e.getSource()).getParent();
//System.out.println("Send this message: "+messageBoard.getMessage()+" to: "+messageBoard.getUser().getUserName());
String mess = messageBoard.getMessage();
System.out.println("in controller "+mess);
Message messageToServet = new Message(messageBoard.getUser().getUserName(),mess);
Message messageToDoc = new Message(controller.getModel().getAuthUser().getUserName(),mess);
messageToDoc.printMessage(messageBoard.getUser().getDoc());
controller.getServerHandler().sendMessage(messageToServet);
}
}
|
Fix iteration was over whole element instead of only over subelements.
|
#!/usr/bin/env python
"""
================================================================================
:mod:`header` -- XML handler for header
================================================================================
.. module:: header
:synopsis: XML handler for header
.. inheritance-diagram:: header
"""
# Standard library modules.
import xml.etree.ElementTree as etree
# Third party modules.
# Local modules.
from pyhmsa.spec.header import Header
from pyhmsa.fileformat.xmlhandler.xmlhandler import _XMLHandler
# Globals and constants variables.
class HeaderXMLHandler(_XMLHandler):
def can_parse(self, element):
return element.tag == 'Header'
def parse(self, element):
obj = self._parse_parameter(element, Header)
for subelement in element:
name = subelement.tag
if name in obj:
continue # already parsed
obj[name] = subelement.text
return obj
def can_convert(self, obj):
return isinstance(obj, Header)
def convert(self, obj):
element = self._convert_parameter(obj, 'Header')
for name, value in obj._extras.items():
subelement = etree.Element(name)
subelement.text = str(value)
element.append(subelement)
return element
|
#!/usr/bin/env python
"""
================================================================================
:mod:`header` -- XML handler for header
================================================================================
.. module:: header
:synopsis: XML handler for header
.. inheritance-diagram:: header
"""
# Standard library modules.
import xml.etree.ElementTree as etree
# Third party modules.
# Local modules.
from pyhmsa.spec.header import Header
from pyhmsa.fileformat.xmlhandler.xmlhandler import _XMLHandler
# Globals and constants variables.
class HeaderXMLHandler(_XMLHandler):
def can_parse(self, element):
return element.tag == 'Header'
def parse(self, element):
obj = self._parse_parameter(element, Header)
for subelement in element.iter():
name = subelement.tag
if name in obj:
continue # already parsed
obj[name] = subelement.text
return obj
def can_convert(self, obj):
return isinstance(obj, Header)
def convert(self, obj):
element = self._convert_parameter(obj, 'Header')
for name, value in obj._extras.items():
subelement = etree.Element(name)
subelement.text = str(value)
element.append(subelement)
return element
|
Remove forgotten if in customer.py
|
from .Base import Base
class Customer(Base):
@property
def id(self):
return self.getProperty('id')
@property
def name(self):
return self.getProperty('name')
@property
def email(self):
return self.getProperty('email')
@property
def locale(self):
return self.getProperty('locale')
@property
def metadata(self):
return self.getProperty('metadata')
@property
def mode(self):
return self.getProperty('mode')
@property
def resource(self):
return self.getProperty('resource')
@property
def createdAt(self):
return self.getProperty('createdAt')
|
from .Base import Base
class Customer(Base):
@property
def id(self):
return self.getProperty('id')
@property
def name(self):
return self.getProperty('name')
@property
def email(self):
return self.getProperty('email')
@property
def locale(self):
return self.getProperty('locale')
@property
def metadata(self):
if 'metadata' not in self:
return None
return self.getProperty('metadata')
@property
def mode(self):
return self.getProperty('mode')
@property
def resource(self):
return self.getProperty('resource')
@property
def createdAt(self):
return self.getProperty('createdAt')
|
Rename the related name for User one-to-one relationship
|
from django.db import models
from django.utils.translation import ugettext as _
from Django.contrib.auth.models import User
FEMALE = 'F'
MALE = 'M'
class Teacher(models.Model):
"""
Halaqat teachers information
"""
GENDER_CHOICES = (
(MALE, _('Male')),
(FEMALE, _('Female')),
)
gender = models.CharField(max_length=1, verbose_name=_('Gender'),
choices=GENDER_CHOICES)
civil_id = models.CharField(max_length=12, verbose_name=_('Civil ID'))
phone_number = models.CharField(max_length=15,
verbose_name=_('Phone Number'))
job_title = models.CharField(max_length=15, verbose_name=_('Title'))
enabled = models.BooleanField(default=True)
user = models.OneToOneField(to=User, related_name='teacher_profile')
def enable(self):
"""
Enable teacher profile
:return:
"""
self.enabled = True
self.save()
def disable(self):
"""
Disable teacher profile
:return:
"""
self.enabled = False
self.save()
|
from django.db import models
from django.utils.translation import ugettext as _
from Django.contrib.auth.models import User
FEMALE = 'F'
MALE = 'M'
class Teacher(models.Model):
"""
Halaqat teachers information
"""
GENDER_CHOICES = (
(MALE, _('Male')),
(FEMALE, _('Female')),
)
gender = models.CharField(max_length=1, verbose_name=_('Gender'),
choices=GENDER_CHOICES)
civil_id = models.CharField(max_length=12, verbose_name=_('Civil ID'))
phone_number = models.CharField(max_length=15,
verbose_name=_('Phone Number'))
job_title = models.CharField(max_length=15, verbose_name=_('Title'))
enabled = models.BooleanField(default=True)
user = models.OneToOneField(to=User, related_name='teachers')
def enable(self):
"""
Enable teacher profile
:return:
"""
self.enabled = True
self.save()
def disable(self):
"""
Disable teacher profile
:return:
"""
self.enabled = False
self.save()
|
Remove loading user meta data.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php
namespace Orchestra\Foundation\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The bootstrap classes for the application.
*
* @return void
*/
protected $bootstrappers = [
\Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,
\Orchestra\Config\Bootstrap\LoadConfiguration::class,
\Illuminate\Foundation\Bootstrap\HandleExceptions::class,
\Illuminate\Foundation\Bootstrap\RegisterFacades::class,
\Illuminate\Foundation\Bootstrap\RegisterProviders::class,
\Illuminate\Foundation\Bootstrap\BootProviders::class,
\Orchestra\Foundation\Bootstrap\LoadFoundation::class,
\Orchestra\Foundation\Bootstrap\UserAccessPolicy::class,
\Orchestra\Extension\Bootstrap\LoadExtension::class,
\Orchestra\Foundation\Bootstrap\NotifyIfSafeMode::class,
\Orchestra\View\Bootstrap\LoadCurrentTheme::class,
\Orchestra\Foundation\Bootstrap\LoadExpresso::class,
];
}
|
<?php
namespace Orchestra\Foundation\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The bootstrap classes for the application.
*
* @return void
*/
protected $bootstrappers = [
\Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,
\Orchestra\Config\Bootstrap\LoadConfiguration::class,
\Illuminate\Foundation\Bootstrap\HandleExceptions::class,
\Illuminate\Foundation\Bootstrap\RegisterFacades::class,
\Illuminate\Foundation\Bootstrap\RegisterProviders::class,
\Illuminate\Foundation\Bootstrap\BootProviders::class,
\Orchestra\Foundation\Bootstrap\LoadFoundation::class,
\Orchestra\Foundation\Bootstrap\UserAccessPolicy::class,
\Orchestra\Extension\Bootstrap\LoadExtension::class,
\Orchestra\Foundation\Bootstrap\LoadUserMetaData::class,
\Orchestra\Foundation\Bootstrap\NotifyIfSafeMode::class,
\Orchestra\View\Bootstrap\LoadCurrentTheme::class,
\Orchestra\Foundation\Bootstrap\LoadExpresso::class,
];
}
|
Change var to const in webpack file
|
const path = require('path');
const webpack = require('webpack');
const APP_DIR = path.resolve(__dirname, 'client');
const SERVER_DIR = path.resolve(__dirname, 'server');
module.exports = {
devtool: 'eval',
entry: [
'webpack-hot-middleware/client', 'webpack/hot/dev-server',
APP_DIR + '/index.jsx'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.jsx?/,
loaders: ['react-hot', 'babel'],
include: APP_DIR
}]
}
};
|
var path = require('path');
var webpack = require('webpack');
var APP_DIR = path.resolve(__dirname, 'client');
var SERVER_DIR = path.resolve(__dirname, 'server');
console.log('=============', path.join(__dirname, 'dist'))
module.exports = {
devtool: 'eval',
entry: [
'webpack-hot-middleware/client', 'webpack/hot/dev-server',
APP_DIR + '/index.jsx'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.jsx?/,
loaders: ['react-hot', 'babel'],
include: APP_DIR
}]
}
};
|
Use the right way to limit queries
|
from django import template
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs,
'all_sites': True,
}
@register.assignment_tag
def get_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
@register.inclusion_tag('events/agenda_tag.html')
def show_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs
}
@register.assignment_tag
def get_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
|
from django import template
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return {
'occurrences': qs,
'all_sites': True,
}
@register.assignment_tag
def get_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return qs
@register.inclusion_tag('events/agenda_tag.html')
def show_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return {
'occurrences': qs
}
@register.assignment_tag
def get_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return qs
|
Switch to obj long for nullable field
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request;
import co.phoenixlab.discord.api.entities.PresenceGame;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UpdateStatusRequest {
private PresenceGame game;
private Long idleSince;
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request;
import co.phoenixlab.discord.api.entities.PresenceGame;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UpdateStatusRequest {
private PresenceGame game;
private long idleSince;
}
|
Update comparator to select based on smallest by CPU, then Memory
|
define(function (require) {
"use strict";
var Backbone = require('backbone'),
_ = require('underscore'),
Size = require('models/Size'),
globals = require('globals');
return Backbone.Collection.extend({
model: Size,
url: globals.API_V2_ROOT + "/sizes",
parse: function (response) {
this.meta = {
count: response.count,
next: response.next,
previous: response.previous
};
return response.results;
},
comparator: function (sizeA, sizeB) {
var cpu_a = parseInt(sizeA.get('cpu'));
var cpu_b = parseInt(sizeB.get('cpu'));
var mem_a = parseInt(sizeA.get('mem'));
var mem_b = parseInt(sizeB.get('mem'));
if (cpu_a === cpu_b) return mem_a < mem_b ? -1 : 1;
return cpu_a < cpu_b ? -1 : 1;
}
});
});
|
define(function (require) {
"use strict";
var Backbone = require('backbone'),
_ = require('underscore'),
Size = require('models/Size'),
globals = require('globals');
return Backbone.Collection.extend({
model: Size,
url: globals.API_V2_ROOT + "/sizes",
parse: function (response) {
this.meta = {
count: response.count,
next: response.next,
previous: response.previous
};
return response.results;
},
comparator: function (sizeA, sizeB) {
var aliasA = parseInt(sizeA.get('alias'));
var aliasB = parseInt(sizeB.get('alias'));
if (aliasA === aliasB) return 0;
return aliasA < aliasB ? -1 : 1;
}
});
});
|
Use custom error message if email is invalid
|
const Sequelize = require('sequelize')
const bcrypt = require('bcrypt')
module.exports = {
model: {
name: Sequelize.STRING,
email: {
type: Sequelize.STRING,
allowNull: false,
unique: {
msg: 'username taken'
},
validate: {
isEmail: {
msg: 'username is not a valid email address'
}
}
},
password: Sequelize.STRING,
photo: Sequelize.STRING,
verifiedEmail: Sequelize.BOOLEAN,
emailToken: Sequelize.STRING,
emailTokenExpires: Sequelize.DATE,
permission: {
type: Sequelize.STRING,
defaultValue: 'admin'
}
},
options: {
freezeTableName: true,
setterMethods: {
password: function(value) {
const salt = bcrypt.genSaltSync()
const hash = bcrypt.hashSync(value, salt)
this.setDataValue('password', hash)
}
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password)
}
}
},
relations: [
['belongsToMany', 'hub', {
through: 'userHub'
}]
]
}
|
const Sequelize = require('sequelize')
const bcrypt = require('bcrypt')
module.exports = {
model: {
name: Sequelize.STRING,
email: {
type: Sequelize.STRING,
allowNull: false,
unique: {
msg: 'username taken'
},
validate: {
isEmail: true
}
},
password: Sequelize.STRING,
photo: Sequelize.STRING,
verifiedEmail: Sequelize.BOOLEAN,
emailToken: Sequelize.STRING,
emailTokenExpires: Sequelize.DATE,
permission: {
type: Sequelize.STRING,
defaultValue: 'admin'
}
},
options: {
freezeTableName: true,
setterMethods: {
password: function(value) {
const salt = bcrypt.genSaltSync()
const hash = bcrypt.hashSync(value, salt)
this.setDataValue('password', hash)
}
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password)
}
}
},
relations: [
['belongsToMany', 'hub', {
through: 'userHub'
}]
]
}
|
Fix typo when displaying individual category details
|
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Cache;
class CategoriesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$output = Cache::rememberForever('categories', function () {
return ['data' => ['categories' => Category::categoryAsc()->get()]];
});
return response()->json($output);
}
/**
* Get the category JSON by a given category_id
* route: api/categories/<category_id>
* @param int $category_id
* @return json {"success": true or false, "data": {"category": category}};
*/
public function show($categoryId)
{
$category = Category::find($categoryId);
if ($category === null) {
return response()->json(['success' => false]);
}
return response()->json(["success" => true, "data" => ["category" => $category]]);
}
}
|
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Cache;
class CategoriesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$output = Cache::rememberForever('categories', function () {
return ['data' => ['categories' => Category::categoryAsc()->get()]];
});
return response()->json($output);
}
/**
* Get the category JSON by a given category_id
* route: api/categories/<category_id>
* @param int $category_id
* @return json {"success": true or false, "data": {"category": category}};
*/
public function show($categoryd)
{
$category = Category::find($categoryId);
if ($category === null) {
return response()->json(['success' => false]);
}
return response()->json(["success" => true, "data" => ["category" => $category]]);
}
}
|
Fix wrong input component order
|
import React from 'react';
import LoadingContainer from '../containers/LoadingContainer';
import PathResultsContainer from '../containers/PathResultsContainer';
import ErrorMessageContainer from '../containers/ErrorMessageContainer';
import SearchButtonContainer from '../containers/SearchButtonContainer';
import ToArticleInputContainer from '../containers/ToArticleInputContainer';
import FromArticleInputContainer from '../containers/FromArticleInputContainer';
import logo from '../images/logo.png';
import {P, Logo, InputFlexContainer, MainContent} from './Home.styles';
export default () => (
<div>
<Logo src={logo} alt="Six Degrees of Wikipedia Logo" />
<MainContent>
<P>Find the shortest paths from</P>
<InputFlexContainer>
<FromArticleInputContainer />
<P style={{margin: '20px 24px'}}>to</P>
<ToArticleInputContainer />
</InputFlexContainer>
<SearchButtonContainer />
<LoadingContainer />
<PathResultsContainer />
<ErrorMessageContainer />
</MainContent>
</div>
);
|
import React from 'react';
import LoadingContainer from '../containers/LoadingContainer';
import PathResultsContainer from '../containers/PathResultsContainer';
import ErrorMessageContainer from '../containers/ErrorMessageContainer';
import SearchButtonContainer from '../containers/SearchButtonContainer';
import ToArticleInputContainer from '../containers/ToArticleInputContainer';
import FromArticleInputContainer from '../containers/FromArticleInputContainer';
import logo from '../images/logo.png';
import {P, Logo, InputFlexContainer, MainContent} from './Home.styles';
export default () => (
<div>
<Logo src={logo} alt="Six Degrees of Wikipedia Logo" />
<MainContent>
<P>Find the shortest paths from</P>
<InputFlexContainer>
<ToArticleInputContainer />
<P style={{margin: '20px 24px'}}>to</P>
<FromArticleInputContainer />
</InputFlexContainer>
<SearchButtonContainer />
<LoadingContainer />
<PathResultsContainer />
<ErrorMessageContainer />
</MainContent>
</div>
);
|
Fix exception to use the filename instead of a blank string.
The exception was not reporting the problem file due to using the wrong
variable.
|
<?php
namespace Sprockets\Filter;
use Sprockets\File;
class Scss extends Base
{
private $parser;
public function __construct()
{
$previous_error_reporting = error_reporting();
error_reporting(E_ERROR);
$this->parser = new \SassParser(array('syntax' => \SassFile::SCSS));
error_reporting($previous_error_reporting);
}
public function __invoke($content, $file, $dir, $vars)
{
$content = preg_replace_callback('/@import\s+["\']([a-z0-9\/]+)["\']/i', function ($match) use ($dir)
{
if ($match[1] == '/')
$filename = $match;
else
$filename = $dir . '/' . $match[1];
if ($this->pipeline->locator->hasFile($filename, 'css'))
$file = new File($filename . '.css');
else if ($this->pipeline->locator->hasFile($index_file = $filename . '/index', 'css'))
$file = new File($index_file . '.css');
else
throw new \Sprockets\Exception\FileNotFound($filename, 'css');
return '@import "' . str_replace('//', '/', $file->getFilepath()) . '"';
}, $content);
$content = $this->parser->toCss($content, false);
return $content;
}
}
|
<?php
namespace Sprockets\Filter;
use Sprockets\File;
class Scss extends Base
{
private $parser;
public function __construct()
{
$previous_error_reporting = error_reporting();
error_reporting(E_ERROR);
$this->parser = new \SassParser(array('syntax' => \SassFile::SCSS));
error_reporting($previous_error_reporting);
}
public function __invoke($content, $file, $dir, $vars)
{
$content = preg_replace_callback('/@import\s+["\']([a-z0-9\/]+)["\']/i', function ($match) use ($dir)
{
if ($match[1] == '/')
$filename = $match;
else
$filename = $dir . '/' . $match[1];
if ($this->pipeline->locator->hasFile($filename, 'css'))
$file = new File($filename . '.css');
else if ($this->pipeline->locator->hasFile($index_file = $filename . '/index', 'css'))
$file = new File($index_file . '.css');
else
throw new \Sprockets\Exception\FileNotFound($file, 'css');
return '@import "' . str_replace('//', '/', $file->getFilepath()) . '"';
}, $content);
$content = $this->parser->toCss($content, false);
return $content;
}
}
|
Make study id types compatible
|
package com.movisens.xs.api.models;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
@Generated("org.jsonschema2pojo")
public class Study {
@Expose
private Integer id;
@Expose
private String name;
/**
*
* @return The id
*/
public Integer getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
}
|
package com.movisens.xs.api.models;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
@Generated("org.jsonschema2pojo")
public class Study {
@Expose
private long id;
@Expose
private String name;
/**
*
* @return The id
*/
public long getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(long id) {
this.id = id;
}
/**
*
* @return The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
}
|
Change single quotes to double
|
#!/usr/bin/env python
import setuptools
from distutils.core import setup
execfile("sodapy/version.py")
with open("requirements.txt") as requirements:
required = requirements.read().splitlines()
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
kwargs = {
"name": "sodapy",
"version": str(__version__),
"packages": ["sodapy"],
"description": "Python bindings for the Socrata Open Data API",
"long_description": long_description,
"author": "Cristina Munoz",
"maintainer": "Cristina Munoz",
"author_email": "hi@xmunoz.com",
"maintainer_email": "hi@xmunoz.com",
"license": "Apache",
"install_requires": required,
"url": "https://github.com/xmunoz/sodapy",
"download_url": "https://github.com/xmunoz/sodapy/archive/master.tar.gz",
"keywords": "soda socrata opendata api",
"classifiers": [
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
]
}
setup(**kwargs)
|
#!/usr/bin/env python
import setuptools
from distutils.core import setup
execfile('sodapy/version.py')
with open('requirements.txt') as requirements:
required = requirements.read().splitlines()
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
kwargs = {
"name": "sodapy",
"version": str(__version__),
"packages": ["sodapy"],
"description": "Python bindings for the Socrata Open Data API",
"long_description": long_description,
"author": "Cristina Munoz",
"maintainer": "Cristina Munoz",
"author_email": "hi@xmunoz.com",
"maintainer_email": "hi@xmunoz.com",
"license": "Apache",
"install_requires": required,
"url": "https://github.com/xmunoz/sodapy",
"download_url": "https://github.com/xmunoz/sodapy/archive/master.tar.gz",
"keywords": "soda socrata opendata api",
"classifiers": [
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
]
}
setup(**kwargs)
|
Remove removeOperation from grouped operation
This function is never used and actually should never be used. The operation may not be modified after it is used, so removing an operation from the list makes no sense.
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
## An operation that groups several other operations together.
#
# The intent of this operation is to hide an underlying chain of operations
# from the user if they correspond to only one interaction with the user, such
# as an operation applied to multiple scene nodes or a re-arrangement of
# multiple items in the scene.
class GroupedOperation(Operation.Operation):
## Creates a new grouped operation.
#
# The grouped operation is empty after its initialisation.
def __init__(self):
super().__init__()
self._children = []
## Adds an operation to this group.
#
# The operation will be undone together with the rest of the operations in
# this group.
# Note that when the order matters, the operations are undone in reverse
# order as the order in which they are added.
def addOperation(self, op):
self._children.append(op)
## Undo all operations in this group.
#
# The operations are undone in reverse order as the order in which they
# were added.
def undo(self):
for op in reversed(self._children):
op.undo()
## Redoes all operations in this group.
def redo(self):
for op in self._children:
op.redo()
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
## An operation that groups several other operations together.
#
# The intent of this operation is to hide an underlying chain of operations
# from the user if they correspond to only one interaction with the user, such
# as an operation applied to multiple scene nodes or a re-arrangement of
# multiple items in the scene.
class GroupedOperation(Operation.Operation):
## Creates a new grouped operation.
#
# The grouped operation is empty after its initialisation.
def __init__(self):
super().__init__()
self._children = []
## Adds an operation to this group.
#
# The operation will be undone together with the rest of the operations in
# this group.
# Note that when the order matters, the operations are undone in reverse
# order as the order in which they are added.
def addOperation(self, op):
self._children.append(op)
## Removes an operation from this group.
def removeOperation(self, index):
del self._children[index]
## Undo all operations in this group.
#
# The operations are undone in reverse order as the order in which they
# were added.
def undo(self):
for op in reversed(self._children):
op.undo()
## Redoes all operations in this group.
def redo(self):
for op in self._children:
op.redo()
|
Format arrivalDate when creating reservation in db
|
var db = require('./db.js');
var moment = require('moment');
var _ = require('lodash');
var get = function() {
return db.get('reservations').value();
};
var make = function(id, arrivalDate, nights, guests) {
if (guests > 5 || !arrivalDate || !nights || !guests) {
return false;
}
let reservationDetails = {
"id": id,
"arrivalDate": moment(arrivalDate).format('MMMM Do YYYY'),
"nights": nights,
"guests": guests,
"status": 'Confirmed',
"bookedOn": moment().format('MMMM Do YYYY'),
"price": nights*_.random(200,249)
};
db.get('reservations')
.push(reservationDetails)
.value();
return reservationDetails;
};
module.exports = {
get: get,
make: make
};
|
var db = require('./db.js');
var moment = require('moment');
var _ = require('lodash');
var get = function() {
return db.get('reservations').value();
};
var make = function(id, arrivalDate, nights, guests) {
if (guests > 5 || !arrivalDate || !nights || !guests) {
return false;
}
let reservationDetails = {
"id": id,
"arrivalDate": arrivalDate,
"nights": nights,
"guests": guests,
"status": 'Confirmed',
"bookedOn": moment().format('MMMM Do YYYY'),
"price": nights*_.random(200,249)
};
db.get('reservations')
.push(reservationDetails)
.value();
return reservationDetails;
};
module.exports = {
get: get,
make: make
};
|
Use mapDispatchToProps and bindActionCreators to streamline the dispatch process.
|
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Heading from '../components/heading'
import Counter from '../components/counter'
import * as Actions from '../actions'
class App extends Component {
render() {
const { increment, decrement, counter, children } = this.props
return (
<div>
<Heading>Counter</Heading>
<Counter
counter = {counter}
onIncrement = { () =>
increment() }
onDecrement = { () =>
decrement() } />
{children}
</div>
);
}
}
function mapStateToProps (state) {
return {
counter: state.counter
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators(Actions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Heading from '../components/heading'
import Counter from '../components/counter'
import { increment, decrement } from '../actions'
class App extends Component {
render() {
const { dispatch, counter, children } = this.props
return (
<div>
<Heading>Counter</Heading>
<Counter
counter = {counter}
onIncrement = { () =>
dispatch(increment()) }
onDecrement = { () =>
dispatch(decrement()) }
/>
{children}
</div>
);
}
}
function mapStateToProps (state) {
return {
counter: state.counter
}
}
export default connect(mapStateToProps)(App);
|
Use only the python module index, but not the one from the (broken) pyqt4 extension
|
# -*- coding: utf-8 -*-
import sys, os
import pyudev
needs_sphinx = '1.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinxcontrib.pyqt4', 'sphinxcontrib.issuetracker']
master_doc = 'index'
exclude_patterns = ['_build/*']
source_suffix = '.rst'
project = u'pyudev'
copyright = u'2010, Sebastian Wiesner'
version = '.'.join(pyudev.__version__.split('.')[:2])
release = pyudev.__version__
html_theme = 'default'
html_static_path = []
html_domain_indices = ['py-modindex']
intersphinx_mapping = {'python': ('http://docs.python.org/', None)}
issuetracker = 'github'
issuetracker_user = u'lunaryorn'
def setup(app):
from sphinx.ext.autodoc import cut_lines
app.connect('autodoc-process-docstring', cut_lines(2, what=['module']))
|
# -*- coding: utf-8 -*-
import sys, os
import pyudev
needs_sphinx = '1.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinxcontrib.pyqt4', 'sphinxcontrib.issuetracker']
master_doc = 'index'
exclude_patterns = ['_build/*']
source_suffix = '.rst'
project = u'pyudev'
copyright = u'2010, Sebastian Wiesner'
version = '.'.join(pyudev.__version__.split('.')[:2])
release = pyudev.__version__
html_theme = 'default'
html_static_path = []
intersphinx_mapping = {'python': ('http://docs.python.org/', None)}
issuetracker = 'github'
issuetracker_user = u'lunaryorn'
def setup(app):
from sphinx.ext.autodoc import cut_lines
app.connect('autodoc-process-docstring', cut_lines(2, what=['module']))
|
Allow select type to link to item in column
|
import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var SelectColumn = React.createClass({
displayName: 'SelectColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
linkTo: React.PropTypes.string,
},
getValue () {
const value = this.props.data.fields[this.props.col.path];
const option = this.props.col.field.ops.filter(i => i.value === value)[0];
return option ? option.label : null;
},
render () {
const value = this.getValue();
const empty = !value && this.props.linkTo ? true : false;
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type} to={this.props.linkTo} empty={empty}>
{value}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = SelectColumn;
|
import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var SelectColumn = React.createClass({
displayName: 'SelectColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
const option = this.props.col.field.ops.filter(i => i.value === value)[0];
return option ? option.label : null;
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = SelectColumn;
|
Fix build path for browser benchmark entry
|
"use strict";
const target = require( "@pegjs/bundler/target" );
module.exports = [
/* https://unpkg.com/pegjs@latest/dist/peg.js */
target( {
entry: require.resolve( "pegjs" ),
library: "peg",
output: "packages/pegjs/dist/peg.js",
} ),
/* https://unpkg.com/pegjs@latest/dist/peg.min.js */
target( {
entry: require.resolve( "pegjs" ),
library: "peg",
output: "packages/pegjs/dist/peg.min.js",
} ),
/* https://unpkg.com/pegjs@dev/dist/*-bundle.min.js */
target( {
entry: {
"benchmark": require.resolve( "@pegjs/benchmark-suite/browser.stub.js" ),
"test": require.resolve( "@pegjs/spec-suite/browser.stub.js" ),
},
library: [ "peg", "[name]" ],
output: "packages/pegjs/dist/[name]-bundle.min.js",
} ),
];
|
"use strict";
const target = require( "@pegjs/bundler/target" );
module.exports = [
/* https://unpkg.com/pegjs@latest/dist/peg.js */
target( {
entry: require.resolve( "pegjs" ),
library: "peg",
output: "packages/pegjs/dist/peg.js",
} ),
/* https://unpkg.com/pegjs@latest/dist/peg.min.js */
target( {
entry: require.resolve( "pegjs" ),
library: "peg",
output: "packages/pegjs/dist/peg.min.js",
} ),
/* https://unpkg.com/pegjs@dev/dist/*-bundle.min.js */
target( {
entry: {
"benchmark": require.resolve( "@pegjs/benchmark-suite/browser.js" ),
"test": require.resolve( "@pegjs/spec-suite/browser.stub.js" ),
},
library: [ "peg", "[name]" ],
output: "packages/pegjs/dist/[name]-bundle.min.js",
} ),
];
|
Fix stopping on a breakpoint for PyCharm 2017.3
|
# -*- coding: utf-8 -*-
import threading
def pytest_exception_interact(node, call, report):
"""
Drop into PyCharm debugger, if available, on uncaught exceptions.
"""
try:
import pydevd
from pydevd import pydevd_tracing
except ImportError:
pass
else:
exctype, value, traceback = call.excinfo._excinfo
frames = []
while traceback:
frames.append(traceback.tb_frame)
traceback = traceback.tb_next
thread = threading.current_thread()
frames_by_id = dict([(id(frame), frame) for frame in frames])
frame = frames[-1]
exception = (exctype, value, traceback)
thread.additional_info.pydev_message = 'test fail'
try:
debugger = pydevd.debugger
except AttributeError:
debugger = pydevd.get_global_debugger()
pydevd_tracing.SetTrace(None) # no tracing from here
debugger.handle_post_mortem_stop(thread, frame, frames_by_id, exception)
return report
|
# -*- coding: utf-8 -*-
import threading
def pytest_exception_interact(node, call, report):
"""
Drop into PyCharm debugger, if available, on uncaught exceptions.
"""
try:
import pydevd
from pydevd import pydevd_tracing
except ImportError:
pass
else:
exctype, value, traceback = call.excinfo._excinfo
frames = []
while traceback:
frames.append(traceback.tb_frame)
traceback = traceback.tb_next
thread = threading.current_thread()
frames_by_id = dict([(id(frame), frame) for frame in frames])
frame = frames[-1]
exception = (exctype, value, traceback)
thread.additional_info.pydev_message = 'test fail'
debugger = pydevd.debugger
pydevd_tracing.SetTrace(None) # no tracing from here
debugger.handle_post_mortem_stop(thread, frame, frames_by_id, exception)
return report
|
Add missing comma in classifiers.
|
from setuptools import setup
setup(
name='jobcli',
version='0.1.a1',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email='stephan.goergen@gmail.com',
description='Job Search from the Command Line',
license='MIT',
zip_safe=False,
include_package_data=False,
keywords='board job search command line career developer engineer',
classifiers=[
'License :: OSI Approved :: MIT License'
,'Development Status :: 3 - Alpha'
,'Environment :: Console'
,'Operating System :: OS Independent'
,'Natural Language :: English'
,'Intended Audience :: Developers'
,'Intended Audience :: Information Technology'
,'Intended Audience :: System Administrators'
,'Intended Audience :: Science/Research'
,'Topic :: Office/Business'
,'Programming Language :: Python :: 2'
,'Programming Language :: Python :: 2.7'
,'Programming Language :: Python :: 3'
,'Programming Language :: Python :: 3.3'
,'Programming Language :: Python :: 3.4'
,'Programming Language :: Python :: 3.5'
]
)
|
from setuptools import setup
setup(
name='jobcli',
version='0.1.a1',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email='stephan.goergen@gmail.com',
description='Job Search from the Command Line',
license='MIT',
zip_safe=False,
include_package_data=False,
keywords='board job search command line career developer engineer',
classifiers=[
'License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Operating System :: OS Independent'
'Natural Language :: English',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'Intended Audience :: Science/Research',
'Topic :: Office/Business',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
Remove callback when the job is done
|
package io.github.izzyleung.zhihudailypurify.task;
import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication;
import io.github.izzyleung.zhihudailypurify.bean.DailyNews;
import java.util.List;
public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> {
protected boolean isRefreshSuccess = true;
protected boolean isContentSame = false;
protected String date;
private OnTaskFinishedCallback mCallback;
public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) {
this.date = date;
this.mCallback = callback;
}
@Override
protected void onPreExecute() {
mCallback.beforeTaskStart();
}
@Override
protected void onPostExecute(List<DailyNews> resultNewsList) {
mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame);
mCallback = null;
}
protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) {
return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date));
}
public interface OnTaskFinishedCallback {
public void beforeTaskStart();
public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame);
}
}
|
package io.github.izzyleung.zhihudailypurify.task;
import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication;
import io.github.izzyleung.zhihudailypurify.bean.DailyNews;
import java.util.List;
public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> {
protected boolean isRefreshSuccess = true;
protected boolean isContentSame = false;
protected String date;
private OnTaskFinishedCallback mCallback;
public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) {
this.date = date;
this.mCallback = callback;
}
@Override
protected void onPreExecute() {
mCallback.beforeTaskStart();
}
@Override
protected void onPostExecute(List<DailyNews> resultNewsList) {
mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame);
}
protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) {
return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date));
}
public interface OnTaskFinishedCallback {
public void beforeTaskStart();
public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame);
}
}
|
Simplify comments list behavior so API requests are consistent with other types of records.
|
import Ember from 'ember';
const {
Route,
inject: { service }
} = Ember;
export default Route.extend({
currentUser: service(),
model(params) {
let projectId = this.modelFor('project').id;
let { number } = params;
return this.store.queryRecord('task', { projectId, number });
},
setupController(controller, task) {
let user = this.get('currentUser.user');
let newComment = this.store.createRecord('comment', { user });
controller.setProperties({ newComment, task });
},
actions: {
save(task) {
return task.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
},
saveComment(comment) {
let task = this.get('controller.task');
comment.set('task', task);
comment.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
}
}
});
|
import Ember from 'ember';
const {
Route,
inject: { service }
} = Ember;
export default Route.extend({
currentUser: service(),
model(params) {
let projectId = this.modelFor('project').id;
let { number } = params;
return this.store.queryRecord('task', { projectId, number });
},
setupController(controller, task) {
let user = this.get('currentUser.user');
let newComment = this.store.createRecord('comment', { user });
return controller.setProperties({ newComment, task });
},
actions: {
save(task) {
return task.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
},
saveComment(comment) {
let task = this.get('controller.task');
comment.set('task', task);
comment.save().catch((error) => {
let payloadContainsValidationErrors = error.errors.some((error) => error.status === 422);
if (!payloadContainsValidationErrors) {
this.controllerFor('project.tasks.task').set('error', error);
}
});
}
}
});
|
Remove .only() call for tests. Sorry
|
'use strict';
var validation = require('../lib/index')
, app = require('./app')
, should = require('should')
, request = require('supertest');
describe('set default values', function() {
describe('when the values are missing', function() {
// Expect default values to be set
it('should return the request with default values', function(done) {
request(app)
.post('/defaults')
.send({firstname: "Jane", lastname: "Doe"})
.expect(200)
.end(function (err, res) {
var response = JSON.parse(res.text);
response.username.should.equal("jane-doe");
done();
});
});
});
})
|
'use strict';
var validation = require('../lib/index')
, app = require('./app')
, should = require('should')
, request = require('supertest');
describe.only('set default values', function() {
describe('when the values are missing', function() {
// Expect default values to be set
it('should return the request with default values', function(done) {
request(app)
.post('/defaults')
.send({firstname: "Jane", lastname: "Doe"})
.expect(200)
.end(function (err, res) {
var response = JSON.parse(res.text);
response.username.should.equal("jane-doe");
done();
});
});
});
})
|
Extend default idle timeout to account for the long and somewhat rare ListActiveBreakpoint calls.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=126710902
|
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Defines the keys for the well known labels used by the cloud debugger.
*
* DO NOT EDIT - This file is auto-generated
*/
package com.google.devtools.clouddebugger.v2;
public final class Labels {
public static final class Debuggee {
public static final String DOMAIN = "domain";
public static final String PROJECT_ID = "projectid";
public static final String MODULE = "module";
public static final String MINOR_VERSION = "minorversion";
public static final String VERSION = "version";
private Debuggee() {}
}
public static final class Breakpoint {
public static final String REQUEST_LOG_ID = "requestlogid";
private Breakpoint() {}
}
private Labels() {}
}
|
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Defines the keys for the well known labels used by the cloud debugger.
*
* DO NOT EDIT - This file is auto-generated
*/
package com.google.devtools.clouddebugger.v2;
public final class Labels {
public static final class Breakpoint {
public static final String REQUEST_LOG_ID = "requestlogid";
private Breakpoint() {}
}
public static final class Debuggee {
public static final String DOMAIN = "domain";
public static final String PROJECT_ID = "projectid";
public static final String MODULE = "module";
public static final String MINOR_VERSION = "minorversion";
public static final String VERSION = "version";
private Debuggee() {}
}
private Labels() {}
}
|
Add reset color to default mention templates.
|
package com.nguyenquyhy.discordbridge.models;
import ninja.leaping.configurate.objectmapping.Setting;
import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable;
/**
* Created by Hy on 12/11/2016.
*/
@ConfigSerializable
public class ChannelMinecraftMentionConfig implements IConfigInheritable<ChannelMinecraftMentionConfig> {
public ChannelMinecraftMentionConfig() {
}
/**
* This is called only when the config file is first created.
*/
void initializeDefault() {
userTemplate = "&6@&e%a&r";
roleTemplate = "&6@&a%r&r";
everyoneTemplate = "&6@&3%a&r";
}
@Setting
public String userTemplate;
@Setting
public String roleTemplate;
@Setting
public String everyoneTemplate;
@Override
public void inherit(ChannelMinecraftMentionConfig parent) {
if (userTemplate == null) userTemplate = parent.userTemplate;
if (roleTemplate == null) roleTemplate = parent.roleTemplate;
if (everyoneTemplate == null) everyoneTemplate = parent.everyoneTemplate;
}
}
|
package com.nguyenquyhy.discordbridge.models;
import ninja.leaping.configurate.objectmapping.Setting;
import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable;
/**
* Created by Hy on 12/11/2016.
*/
@ConfigSerializable
public class ChannelMinecraftMentionConfig implements IConfigInheritable<ChannelMinecraftMentionConfig> {
public ChannelMinecraftMentionConfig() {
}
/**
* This is called only when the config file is first created.
*/
void initializeDefault() {
userTemplate = "&6@&e%a";
roleTemplate = "&6@&a%r";
everyoneTemplate = "&6@&3%a";
}
@Setting
public String userTemplate;
@Setting
public String roleTemplate;
@Setting
public String everyoneTemplate;
@Override
public void inherit(ChannelMinecraftMentionConfig parent) {
if (userTemplate == null) userTemplate = parent.userTemplate;
if (roleTemplate == null) roleTemplate = parent.roleTemplate;
if (everyoneTemplate == null) everyoneTemplate = parent.everyoneTemplate;
}
}
|
Fix Memcachestat. Using wrong classname
|
<?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_Memcache::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?>
|
<?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_MemcacheStore::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?>
|
Fix syntax and merge differences
|
#!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')(process.argv.slice(2));
var printHelp = function() {
console.log('oust');
console.log(pkg.description);
console.log('');
console.log('Usage:');
console.log(' $ oust <filename> <selector>');
};
if(argv.h || argv.help) {
printHelp();
return;
}
if(argv.v || argv.version) {
console.log(pkg.version);
return;
}
var file = argv._[0];
var selector = argv._[1];
fs.readFile(file, function(err, data) {
if(err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
var res = oust(data, selector);
console.log(res.join("\n"));
});
|
#!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')((process.argv.slice(2)))
var printHelp = function() {
console.log('oust');
console.log(pkg.description);
console.log('');
console.log('Usage:');
console.log(' $ oust <filename> <selector>');
};
if(argv.h || argv.help) {
printHelp();
return;
}
if(argv.v || argv.version) {
console.log(pkg.version);
return;
}
var file = argv._[0];
var selector = argv._[1];
fs.readFile(file, function(err, data) {
if(err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
var res = oust(data, type);
console.log(res.join("\n"));
});
|
Refactor config class in dataservice module
|
'use strict';
var EventEmitter = require('events').EventEmitter
class Config {
constructor() {
this.requiredKeys = ['url','type']
this.messages = {
missingConfig: 'DataService missing config object',
missingKey: 'DataService config missing required key: '
}
}
error(msg) {
throw new Error(msg)
}
checkKeyValidity(config, key) {
if (!config.hasOwnProperty(key))
this.error(this.messages.missingKey + key)
}
validate(config) {
if (!config) this.error(this.messages.missingConfig)
this.requiredKeys.forEach((key) => this.checkKeyValidity(config, key))
return config
}
}
class DataService extends EventEmitter {
constructor(config) {
this.config = new Config().validate(config)
this.data = null
}
getData() {
return this.data
}
load(cb) {
return cb(null, {})
}
}
module.exports = function(config) {
return new DataService(config)
}
|
'use strict';
var EventEmitter = require('events').EventEmitter
class Config {
constructor() {
this.requiredKeys = ['url','type']
this.messages = {
missingConfig: 'DataService missing config object',
missingKey: 'DataService config missing required key: '
}
}
error(msg) {
throw new Error(msg)
}
checkKeyValidity(config, key) {
if (!config.hasOwnProperty(key)) this.error(this.messages.missingKey + key)
}
validate(config) {
if (!config) this.error(this.messages.missingConfig)
this.requiredKeys.forEach(key => this.checkKeyValidity(config, key))
return config
}
}
class DataService extends EventEmitter {
constructor(config) {
this.config = new Config().validate(config)
this.data = null
}
getData() {
return this.data
}
load(cb) {
return cb(null, {})
}
}
module.exports = function(config) {
return new DataService(config)
}
|
Update to new Cervus API
|
import { Game } from 'cervus/core';
import { Plane, Box } from 'cervus/shapes';
import { basic } from 'cervus/materials';
const game = new Game({
width: window.innerWidth,
height: window.innerHeight,
clear_color: "#eeeeee",
far: 1000
});
document.querySelector("#ui").addEventListener(
'click', () => game.canvas.requestPointerLock()
);
game.camera.position = [0, 1.5, 0];
game.camera.keyboard_controlled = true;
game.camera.mouse_controlled = true;
game.camera.move_speed = 10;
game.add(new Plane({
material: basic,
color: "#000000",
scale: [1000, 1, 1000]
}));
for (let i = 0; i < 20; i++) {
const sign = Math.cos(i * Math.PI);
const x = 75 + 100 * Math.sin(i * Math.PI / 6);
game.add(new Box({
material: basic,
color: "#000000",
position: [sign * x, 20, 20 * i],
scale: [90, 40, 15]
}));
}
|
import { Game } from 'cervus/modules/core';
import { Plane, Box } from 'cervus/modules/shapes';
import { basic } from 'cervus/modules/materials';
const game = new Game({
width: window.innerWidth,
height: window.innerHeight,
clear_color: "#eeeeee",
far: 1000
});
document.querySelector("#ui").addEventListener(
'click', () => game.canvas.requestPointerLock()
);
game.camera.position = [0, 1.5, 0];
game.camera.keyboard_controlled = true;
game.camera.mouse_controlled = true;
game.camera.move_speed = 10;
game.add(new Plane({
material: basic,
color: "#000000",
scale: [1000, 1, 1000]
}));
for (let i = 0; i < 20; i++) {
const sign = Math.cos(i * Math.PI);
const x = 75 + 100 * Math.sin(i * Math.PI / 6);
game.add(new Box({
material: basic,
color: "#000000",
position: [sign * x, 20, 20 * i],
scale: [90, 40, 15]
}));
}
|
Clarify implications of introducing new migrations
|
const { last } = require('lodash');
const db = require('../database');
const settings = require('../settings');
const { runMigrations } = require('./run_migrations');
// IMPORTANT: Add new migrations that need to traverse entire database, e.g.
// messages store, below. Whenever we need this, we need to force attachment
// migration on startup:
const migrations = [
// {
// version: 0,
// migrate(transaction, next) {
// next();
// },
// },
];
exports.run = async ({ Backbone, database } = {}) => {
const { canRun } = await exports.getStatus({ database });
if (!canRun) {
throw new Error('Cannot run migrations on database without attachment data');
}
await runMigrations({ Backbone, database });
};
exports.getStatus = async ({ database } = {}) => {
const connection = await db.open(database.id, database.version);
const isAttachmentMigrationComplete =
await settings.isAttachmentMigrationComplete(connection);
const hasMigrations = migrations.length > 0;
const canRun = isAttachmentMigrationComplete && hasMigrations;
return {
isAttachmentMigrationComplete,
hasMigrations,
canRun,
};
};
exports.getLatestVersion = () => {
const lastMigration = last(migrations);
if (!lastMigration) {
return null;
}
return lastMigration.version;
};
|
const { last } = require('lodash');
const db = require('../database');
const settings = require('../settings');
const { runMigrations } = require('./run_migrations');
// NOTE: Add new migrations that need to traverse entire database, e.g. messages
// store, here. These will only run after attachment migration has completed in
// the background:
const migrations = [
// {
// version: 0,
// migrate(transaction, next) {
// next();
// },
// },
];
exports.run = async ({ Backbone, database } = {}) => {
const { canRun } = await exports.getStatus({ database });
if (!canRun) {
throw new Error('Cannot run migrations on database without attachment data');
}
await runMigrations({ Backbone, database });
};
exports.getStatus = async ({ database } = {}) => {
const connection = await db.open(database.id, database.version);
const isAttachmentMigrationComplete =
await settings.isAttachmentMigrationComplete(connection);
const hasMigrations = migrations.length > 0;
const canRun = isAttachmentMigrationComplete && hasMigrations;
return {
isAttachmentMigrationComplete,
hasMigrations,
canRun,
};
};
exports.getLatestVersion = () => {
const lastMigration = last(migrations);
if (!lastMigration) {
return null;
}
return lastMigration.version;
};
|
Switch to automated git clone and pull
|
#!/usr/bin/env python
import os
dependencies = (
('resources/vim/bundle/neobundle.vim',
'https://github.com/Shougo/neobundle.vim'),
('resources/zsh/zsh-syntax-highlighting',
'git://github.com/zsh-users/zsh-syntax-highlighting.git'),
('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'),
('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'),
('bins/iscp', 'https://github.com/EvanHahn/iscp.git'),
('bins/journ', 'https://github.com/EvanHahn/journ.git'),
('bins/rename', 'https://github.com/EvanHahn/rename.git'),
)
my_path = os.path.dirname(os.path.realpath(__file__))
root_path = os.path.join(my_path, '..')
for (path, url) in dependencies:
os.chdir(root_path)
exists = os.path.isdir(path)
if exists:
os.chdir(path)
os.system('git checkout master')
os.system('git pull origin master')
else:
os.system('git clone {0} {1}'.format(url, path))
|
#!/usr/bin/env python
import os
dependencies = (
('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'),
('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'),
('bins/iscp', 'https://github.com/EvanHahn/iscp.git'),
('bins/journ', 'https://github.com/EvanHahn/journ.git'),
('bins/rename', 'https://github.com/EvanHahn/rename.git'),
)
my_path = os.path.dirname(os.path.realpath(__file__))
root_path = os.path.join(my_path, '..')
os.chdir(root_path)
for (path, url) in dependencies:
exists = os.path.isdir(path)
subtree_command = 'pull' if exists else 'add'
os.system('git subtree {0} --prefix {1} {2} master --squash'.format(
subtree_command, path, url))
|
Support for Redux DevTools Extension
|
import {
applyMiddleware,
combineReducers,
compose,
createStore as createReduxStore
} from 'redux'
const makeRootReducer = (reducers, asyncReducers) => {
// Redux + combineReducers always expect at least one reducer, if reducers
// and asyncReducers are empty, we define an useless reducer function
// returning the state
if (!reducers && !asyncReducers) { return (state) => state }
return combineReducers({
...reducers,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.reducers, store.asyncReducers))
}
export const createStore = (initialState = {}, reducers = {}, middlewares = {}, enhancers = {}) => {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createReduxStore(
makeRootReducer(reducers),
initialState,
composeEnhancers(
applyMiddleware(...middlewares),
...enhancers
)
)
store.reducers = reducers
store.asyncReducers = {}
return store
}
|
import {
applyMiddleware,
combineReducers,
compose,
createStore as createReduxStore
} from 'redux'
const makeRootReducer = (reducers, asyncReducers) => {
// Redux + combineReducers always expect at least one reducer, if reducers
// and asyncReducers are empty, we define an useless reducer function
// returning the state
if (!reducers && !asyncReducers) { return (state) => state }
return combineReducers({
...reducers,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.reducers, store.asyncReducers))
}
export const createStore = (initialState = {}, reducers = {}, middlewares = {}, enhancers = {}) => {
const store = createReduxStore(
makeRootReducer(reducers),
initialState,
compose(
applyMiddleware(...middlewares),
...enhancers
)
)
store.reducers = reducers
store.asyncReducers = {}
return store
}
|
Update galaxy params w/ new model choices
|
'''
Use parameters from Diskfit in the Galaxy class
'''
from galaxies import Galaxy
from astropy.table import Table
from cube_analysis.rotation_curves import update_galaxy_params
from paths import fourteenB_HI_data_path, fourteenB_HI_data_wGBT_path
# The models from the peak velocity aren't as biased, based on comparing
# the VLA and VLA+GBT velocity curves. Using these as the defaults
folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output"
param_name = \
fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name))
param_table = Table.read(param_name)
gal = Galaxy("M33")
update_galaxy_params(gal, param_table)
# Load in the model from the feathered data as well.
folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output"
param_name = \
fourteenB_HI_data_wGBT_path("{}/rad.out.params.csv".format(folder_name))
param_table = Table.read(param_name)
gal_feath = Galaxy("M33")
update_galaxy_params(gal_feath, param_table)
|
'''
Use parameters from Diskfit in the Galaxy class
'''
from astropy import units as u
from galaxies import Galaxy
from astropy.table import Table
from paths import fourteenB_HI_data_path
def update_galaxy_params(gal, param_table):
'''
Use the fit values from fit rather than the hard-coded values in galaxies.
'''
from astropy.coordinates import Angle, SkyCoord
gal.inclination = Angle(param_table["inc"] * u.deg)[0]
gal.position_angle = Angle(param_table["PA"] * u.deg)[0]
gal.vsys = (param_table["Vsys"] * u.km / u.s)[0]
# The positions in the table are in pixels, so convert to the sky using
# the spatial WCS info.
ra_cent, dec_cent = param_table["RAcent"], param_table["Deccent"]
gal.center_position = SkyCoord(ra_cent, dec_cent, unit=(u.deg, u.deg),
frame='fk5')
folder_name = "diskfit_noasymm_noradial_nowarp_output"
param_name = \
fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name))
param_table = Table.read(param_name)
gal = Galaxy("M33")
update_galaxy_params(gal, param_table)
|
Add db name for unit tests
|
<?php
/**
* Application configuration shared by all test types
*/
return [
'language' => 'en-US',
'controllerMap' => [
'fixture' => [
'class' => 'yii\faker\FixtureController',
'fixtureDataPath' => '@tests/codeception/fixtures',
'templatePath' => '@tests/codeception/templates',
'namespace' => 'tests\codeception\fixtures',
],
],
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=intern_system_tests',
],
'mailer' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
];
|
<?php
/**
* Application configuration shared by all test types
*/
return [
'language' => 'en-US',
'controllerMap' => [
'fixture' => [
'class' => 'yii\faker\FixtureController',
'fixtureDataPath' => '@tests/codeception/fixtures',
'templatePath' => '@tests/codeception/templates',
'namespace' => 'tests\codeception\fixtures',
],
],
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_basic_tests',
],
'mailer' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
];
|
Add reference from article to catalog.
|
/*jslint eqeq: true, indent: 2, node: true, plusplus: true, regexp: true, unparam: true, vars: true, nomen: true */
'use strict';
var Schema = require('mongoose').Schema;
/**
* The article schema.
*/
var PostSchema = new Schema({
type: {type: Number, 'default': 0},
authorId: String,
catalogId: {type: String, ref: 'catalog'},
tags: [String],
title: Number,
content: String,
date: {type: Date, 'default': Date.now}
});
var statics = PostSchema.statics;
statics.listLatestPosts = function (param, cb) {
var q = this.find();
if (param) {
if (param.start) {
q.skip(param.start);
}
if (param.limit) {
q.limit(param.limit);
}
}
q.sort({date: 'desc'});
if (cb) {
return q.exec(cb);
} else {
return q;
}
};
module.exports = PostSchema;
|
/*jslint eqeq: true, indent: 2, node: true, plusplus: true, regexp: true, unparam: true, vars: true, nomen: true */
'use strict';
var Schema = require('mongoose').Schema;
/**
* The article schema.
*/
var PostSchema = new Schema({
type: { type: Number, 'default': 0},
authorId: String,
catalogId: String,
tags: [String],
title: Number,
content: String,
date: { type: Date, 'default': Date.now}
});
var statics = PostSchema.statics;
statics.listLatestPosts = function (param, cb) {
var q = this.find();
if (param) {
if (param.start) {
q.skip(param.start);
}
if (param.limit) {
q.limit(param.limit);
}
}
q.sort({date: 'desc'});
if (cb) {
return q.exec(cb);
} else {
return q;
}
};
module.exports = PostSchema;
|
Fix spec issue with Transfer::Server ProtocolDetails
|
patches = [
{
"op": "move",
"from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType",
"path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType",
"value": "String",
},
{
"op": "move",
"from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType",
"path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType",
"value": "String",
},
{
"op": "move",
"from": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/ItemType",
"path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType",
},
{
"op": "replace",
"path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType",
"value": "String",
},
]
|
patches = [
{
"op": "move",
"from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType",
"path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType",
"value": "String",
},
{
"op": "move",
"from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType",
"path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType",
"value": "String",
},
]
|
[reference] Add a reference name in the list.
|
var loadManyReferenceList = require('./builder').loadMany;
var dispatcher = require('../dispatcher');
/**
* Focus reference action.
* @param {array} referenceNames - An array which contains the name of all the references to load.
* @returns {Promise} - The promise of loading all the references.
*/
function builtInReferenceAction(referenceNames){
return function(){
if(!referenceNames){
return undefined;
}
return Promise.all(loadManyReferenceList(referenceNames))
.then(function successReferenceLoading(data){
//Rebuilt a constructed information from the map.
var reconstructedData = {};
referenceNames.map((name, index)=>{
reconstructedData[name] = data[index];
});
//
dispatcher.handleViewAction({data: reconstructedData, type: 'update', subject: 'reference'});
}, function errorReferenceLoading(err){
dispatcher.handleViewAction({data: err, type: 'error'});
});
};
}
module.exports = builtInReferenceAction;
|
var loadManyReferenceList = require('./builder').loadMany;
var dispatcher = require('../dispatcher');
/**
* Focus reference action.
* @param {array} referenceNames - An array which contains the name of all the references to load.
* @returns {Promise} - The promise of loading all the references.
*/
function builtInReferenceAction(referenceNames){
return function(){
if(!this.referenceNames){
return undefined;
}
return Promise.all(loadManyReferenceList(referenceNames))
.then(function successReferenceLoading(data){
//Rebuilt a constructed information from the map.
var reconstructedData = {};
referenceNames.map((name, index)=>{
reconstructedData[name] = data[index];
});
//
dispatcher.handleViewAction({data: reconstructedData, type: 'update', subject: 'reference'});
}, function errorReferenceLoading(err){
dispatcher.handleViewAction({data: err, type: 'error'});
});
};
}
module.exports = builtInReferenceAction;
|
Add slugify to the jinja2's globals scope
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from helpers.text import slugify
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
ads = UploadSet('ads', IMAGES)
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
app.jinja_env.globals.update(slugify=slugify)
bootstrap.init_app(app)
db.init_app(app)
login_manager.init_app(app)
configure_uploads(app, ads)
from .aflafrettir import aflafrettir as afla_blueprint
from .auth import auth as auth_blueprint
from .admin import admin as admin_blueprint
app.register_blueprint(afla_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(admin_blueprint, url_prefix='/admin')
return app
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
ads = UploadSet('ads', IMAGES)
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
bootstrap.init_app(app)
db.init_app(app)
login_manager.init_app(app)
configure_uploads(app, ads)
from .aflafrettir import aflafrettir as afla_blueprint
from .auth import auth as auth_blueprint
from .admin import admin as admin_blueprint
app.register_blueprint(afla_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(admin_blueprint, url_prefix='/admin')
return app
|
Replace deprecated "getName()" method from Twig extensions.
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Twig\Extension;
use Darvin\Utils\NewObject\NewObjectCounterInterface;
/**
* New object Twig extension
*/
class NewObjectExtension extends \Twig_Extension
{
/**
* @var \Darvin\Utils\NewObject\NewObjectCounterInterface
*/
private $newObjectCounter;
/**
* @param \Darvin\Utils\NewObject\NewObjectCounterInterface $newObjectCounter New object counter
*/
public function __construct(NewObjectCounterInterface $newObjectCounter)
{
$this->newObjectCounter = $newObjectCounter;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction('utils_count_new_objects', [$this->newObjectCounter, 'count']),
new \Twig_SimpleFunction('utils_new_objects_countable', [$this->newObjectCounter, 'isCountable']),
];
}
}
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Twig\Extension;
use Darvin\Utils\NewObject\NewObjectCounterInterface;
/**
* New object Twig extension
*/
class NewObjectExtension extends \Twig_Extension
{
/**
* @var \Darvin\Utils\NewObject\NewObjectCounterInterface
*/
private $newObjectCounter;
/**
* @param \Darvin\Utils\NewObject\NewObjectCounterInterface $newObjectCounter New object counter
*/
public function __construct(NewObjectCounterInterface $newObjectCounter)
{
$this->newObjectCounter = $newObjectCounter;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction('utils_count_new_objects', [$this->newObjectCounter, 'count']),
new \Twig_SimpleFunction('utils_new_objects_countable', [$this->newObjectCounter, 'isCountable']),
];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'darvin_utils_new_object_extension';
}
}
|
Fix UTF-8 encoding for json exports
|
from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
with open(options['target'], 'w', encoding='utf-8') as outfile:
json.dump(places, outfile, ensure_ascii=False)
|
from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
with open(options['target'], 'w') as outfile:
json.dump(places, outfile)
|
XWIKI-10405: Implement a new Platform Mail Sender API
* Add missing @Unstable annotation
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.mail;
import javax.mail.internet.MimeMessage;
import org.xwiki.stability.Unstable;
/**
* Allows listening to Mail sending results.
*
* @version $Id$
* @since 6.1M2
*/
@Unstable
public interface MailResultListener
{
/**
* Called when the mail is sent successfully.
*
* @param message the message sent
*/
void onSuccess(MimeMessage message);
/**
* Called when the mail has failed to be sent.
*
* @param message the message that was tried to be sent
* @param t the exception explaining why the message couldn't be sent
*/
void onError(MimeMessage message, Throwable t);
}
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.mail;
import javax.mail.internet.MimeMessage;
/**
* Allows listening to Mail sending results.
*
* @version $Id$
* @since 6.1M2
*/
public interface MailResultListener
{
/**
* Called when the mail is sent successfully.
*
* @param message the message sent
*/
void onSuccess(MimeMessage message);
/**
* Called when the mail has failed to be sent.
*
* @param message the message that was tried to be sent
* @param t the exception explaining why the message couldn't be sent
*/
void onError(MimeMessage message, Throwable t);
}
|
Add getKeys and count to Patricia Tree
|
package com.cc4102.stringDict;
import java.util.ArrayList;
/**
* @author Lucas Puebla Silva
*
*/
public class PatriciaTree implements StringDictionary {
private PatriciaNode root;
public PatriciaTree() {
this.root = new PatriciaNode("", true, null, new ArrayList<>());
}
public int getLength() {
return 0;
}
public int getSize() {
return 0;
}
public Object getRoot() {
return root;
}
public ArrayList<Integer> search(String key) {
return root.search(key);
}
public void insert(String word, int pos) {
root.insert(word, pos);
}
public String[] getKeys() {
return new String[0];
}
public int count(String key) {
return root.search(key).size();
}
}
|
package com.cc4102.stringDict;
import java.util.ArrayList;
/**
* @author Lucas Puebla Silva
*
*/
public class PatriciaTree implements StringDictionary {
private PatriciaNode root;
public PatriciaTree() {
this.root = new PatriciaNode("", true, null, new ArrayList<>());
}
@Override
public int getLength() {
return 0;
}
@Override
public int getSize() {
return 0;
}
@Override
public Object getRoot() {
return root;
}
@Override
public ArrayList<Integer> search(String key) {
return root.search(key);
}
@Override
public void insert(String word, int pos) {
root.insert(word, pos);
}
}
|
Change version number for release
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.1',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.0',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Add a language string for logging the actions
Signed-off-by: Suki <52329a27ea5670aeec0efeeb0773bf1b4f1affa1@missallsunday.com>
|
<?php
/**
*
* @package moderateAdmin mod
* @version 1.0
* @author Jessica Gonzlez <suki@missallsunday.com>
* @copyright Copyright (c) 2013, Jessica Gonzlez
* @license http://www.mozilla.org/MPL/ MPL 2.0
*/
global $txt;
$txt['mA_main'] = 'moderate admin';
// Permissions
$txt['cannot_moderateAdmin'] = 'I\'m sorry, you are not allowed to moderate Admin\'s messages.';
$txt['permissionname_moderateAdmin'] = 'Moderate Admin\'s messages';
// Settings
$txt['mA_adminOptions'] = 'Who are going to be protected by the moderate permission?';
$txt['mA_adminOptions_sub'] = 'If you select the "single admin" option make sure to specify a valid ID in the setting below, if no setting is provided, the mod will use ID 1';
$txt['mA_singleAdmin'] = 'A single admin';
$txt['mA_primaryAdmin'] = 'All users who have an admin account as primary group.';
$txt['mA_allAdmins'] = 'All admins, including users who have an admin group as secondary.';
$txt['mA_uniqueAdmin'] = 'Set the user ID for the single admin who will be protected by the moderate permission.';
$txt['mA_uniqueAdmin_sub'] = 'Must be a valid user ID, if its not set the mod will use the ID 1.';
// Error strings
$txt['mA_error_log'] = 'User %1$s has tried to %2$s the following message: %3$s';
|
<?php
/**
*
* @package moderateAdmin mod
* @version 1.0
* @author Jessica Gonzlez <suki@missallsunday.com>
* @copyright Copyright (c) 2013, Jessica Gonzlez
* @license http://www.mozilla.org/MPL/ MPL 2.0
*/
global $txt;
$txt['mA_main'] = 'moderate admin';
// Permissions
$txt['cannot_moderateAdmin'] = 'I\'m sorry, you are not allowed to moderate Admin\'s messages.';
$txt['permissionname_moderateAdmin'] = 'Moderate Admin\'s messages';
// Settings
$txt['mA_adminOptions'] = 'Who are going to be protected by the moderate permission?';
$txt['mA_adminOptions_sub'] = 'If you select the "single admin" option make sure to specify a valid ID in the setting below, if no setting is provided, the mod will use ID 1';
$txt['mA_singleAdmin'] = 'A single admin';
$txt['mA_primaryAdmin'] = 'All users who have an admin account as primary group.';
$txt['mA_allAdmins'] = 'All admins, including users who have an admin group as secondary.';
$txt['mA_uniqueAdmin'] = 'Set the user ID for the single admin who will be protected by the moderate permission.';
$txt['mA_uniqueAdmin_sub'] = 'Must be a valid user ID, if its not set the mod will use the ID 1.';
|
Update service provider to use bindShared.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Widget;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class WidgetServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.widget', function ($app) {
return new WidgetManager($app);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Widget', 'Orchestra\Support\Facades\Widget');
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../');
$this->package('orchestra/widget', 'orchestra/widget', $path);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.widget');
}
}
|
<?php namespace Orchestra\Widget;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class WidgetServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.widget'] = $this->app->share(function ($app) {
return new WidgetManager($app);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Widget', 'Orchestra\Support\Facades\Widget');
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../');
$this->package('orchestra/widget', 'orchestra/widget', $path);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.widget');
}
}
|
Fix @package annotation from Jam to Atlas
|
<?php namespace CL\Atlas\Test;
use Openbuildings\EnvironmentBackup as EB;
use CL\Atlas\DB;
/**
* @package Atlas
* @author Ivan Kerin
*/
abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase {
public $env;
public function setUp()
{
parent::setUp();
$this->env = new EB\Environment(array(
'static' => new EB\Environment_Group_Static,
));
DB::configuration('default', array(
'class' => 'DB_Test',
'dsn' => 'mysql:dbname=test-db;host=127.0.0.1',
'username' => 'root',
));
$this->env->backup_and_set(array(
'CL\Atlas\DB::$instances' => array(),
));
}
public function tearDown()
{
$this->env->restore();
parent::tearDown();
}
}
|
<?php namespace CL\Atlas\Test;
use Openbuildings\EnvironmentBackup as EB;
use CL\Atlas\DB;
/**
* @package Jam
* @author Ivan Kerin
*/
abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase {
public $env;
public function setUp()
{
parent::setUp();
$this->env = new EB\Environment(array(
'static' => new EB\Environment_Group_Static,
));
DB::configuration('default', array(
'class' => 'DB_Test',
'dsn' => 'mysql:dbname=test-db;host=127.0.0.1',
'username' => 'root',
));
$this->env->backup_and_set(array(
'CL\Atlas\DB::$instances' => array(),
));
}
public function tearDown()
{
$this->env->restore();
parent::tearDown();
}
}
|
Rename variable torpedos to torpedoCount
|
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {
private int torpedoCount = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedoCount = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.01) {
// successful firing
this.torpedoCount -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedoCount <= 0;
}
public int getTorpedoCount() {
return this.torpedoCount;
}
}
|
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {
private int torpedos = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedos = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.01) {
// successful firing
this.torpedos -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedos <= 0;
}
public int getNumberOfTorpedos() {
return this.torpedos;
}
}
|
Add ``get_domain`` test fixture factory.
Helpful to test the ``Domain``.
|
from us_ignite.apps.models import (Application, ApplicationMembership,
Domain, Page)
from us_ignite.profiles.tests.fixtures import get_user
def get_application(**kwargs):
data = {
'name': 'Gigabit app',
}
if not 'owner' in kwargs:
data['owner'] = get_user('us-ignite')
data.update(kwargs)
return Application.objects.create(**data)
def get_membership(application, user):
membership, is_new = (ApplicationMembership.objects
.get_or_create(application=application, user=user))
return membership
def get_page(**kwargs):
data = {
'name': 'Application list',
}
data.update(kwargs)
return Page.objects.create(**data)
def get_domain(**kwargs):
data = {
'name': 'Healthcare',
'slug': 'healthcare',
}
data.update(kwargs)
return Domain.objects.create(**data)
|
from us_ignite.apps.models import Application, ApplicationMembership, Page
from us_ignite.profiles.tests.fixtures import get_user
def get_application(**kwargs):
defaults = {
'name': 'Gigabit app',
}
if not 'owner' in kwargs:
defaults['owner'] = get_user('us-ignite')
defaults.update(kwargs)
return Application.objects.create(**defaults)
def get_membership(application, user):
membership, is_new = (ApplicationMembership.objects
.get_or_create(application=application, user=user))
return membership
def get_page(**kwargs):
defaults = {
'name': 'Application list',
}
defaults.update(kwargs)
return Page.objects.create(**defaults)
|
Fix moment.js not found in production
|
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require lodash
//= require handlebars.runtime
// To use placeholders in inputs in browsers that do not support it
// natively yet.
//= require jquery/jquery.placeholder
// Notifications (flash messages).
//= require jquery/jquery.noty
// To crop logos.
//= require jquery/jquery.Jcrop
// Used internally in the chat.
//= require jquery/jquery.autosize
// For modals.
//= require bootstrap/bootstrap-modal
//= require bootstrap/bootstrap-modalmanager
// Used in crop, modals and possibly other places. Grep for `ajaxForm`
// and `ajaxSubmit`.
//= require jquery/jquery.form
// Use to search for models (e.g. users) dynamically.
//= require select2
// Use for XMPP in the chat.
//= require strophe
//= require i18n/translations
// Moment.js for dates
//= require moment
//= require moment/pt-br
// Datetime picker for bootstrap
//= require bootstrap-datetimepicker
// TODO: remove this dependecy, this is only used in attachments now and
// can be easily replaced by standard jquery methods.
//= require jquery/jquery.livequery
// 'base' HAS to be the first one included
//= require ./app/application/base
//= require_tree ./templates
//= require_tree ./app/application/
//= require_tree ./app/_all/
|
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require lodash
//= require handlebars.runtime
// To use placeholders in inputs in browsers that do not support it
// natively yet.
//= require jquery/jquery.placeholder
// Notifications (flash messages).
//= require jquery/jquery.noty
// To crop logos.
//= require jquery/jquery.Jcrop
// Used internally in the chat.
//= require jquery/jquery.autosize
// For modals.
//= require bootstrap/bootstrap-modal
//= require bootstrap/bootstrap-modalmanager
// Used in crop, modals and possibly other places. Grep for `ajaxForm`
// and `ajaxSubmit`.
//= require jquery/jquery.form
// Use to search for models (e.g. users) dynamically.
//= require select2
// Use for XMPP in the chat.
//= require strophe
//= require i18n/translations
// Datetime picker for bootstrap
//= require bootstrap-datetimepicker
// Moment.js for dates
//= require moment
//= require moment/pt-br
// TODO: remove this dependecy, this is only used in attachments now and
// can be easily replaced by standard jquery methods.
//= require jquery/jquery.livequery
// 'base' HAS to be the first one included
//= require ./app/application/base
//= require_tree ./templates
//= require_tree ./app/application/
//= require_tree ./app/_all/
|
Add import and export buttons
|
//Source:
//https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM
//http://bgrins.github.io/devtools-snippets/#console-save
//A simple way to save objects as .json files from the console
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data');
return;
}
if(!filename) filename = 'console.json';
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
};
})(console);
|
//Source:
//https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM
//http://bgrins.github.io/devtools-snippets/#console-save
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data');
return;
}
if(!filename) filename = 'console.json';
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
};
})(console);
|
Add capture method to charge
|
<?php
class Stripe_Charge extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::_scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function refund($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/refund';
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom($response, $apiKey);
return $this;
}
public function capture($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/capture';
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom($response, $apiKey);
return $this;
}
}
|
<?php
class Stripe_Charge extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::_scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
public function refund($params=null)
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/refund';
list($response, $apiKey) = $requestor->request('post', $url, $params);
$this->refreshFrom($response, $apiKey);
return $this;
}
}
|
Rename variable for more consitency
|
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const nock = require('nock');
chai.use(chaiAsPromised);
chai.should();
const expect = chai.expect;
const pnut = require('../lib/pnut');
describe('The pnut API wrapper', function () {
before(function() {
let base = 'https://api.pnut.io';
nock(base)
.get('/v0')
.reply(200, {})
nock(base)
.get('/v0/posts/streams/global')
.reply(200, {posts: 1})
});
after(function() {
nock.cleanAll();
});
it('should get the global timeline', function() {;
return pnut.global().should.become({'posts': 1})
});
});
|
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const nock = require('nock');
chai.use(chaiAsPromised);
chai.should();
const expect = chai.expect;
const pnut = require('../lib/pnut');
describe('The pnut API wrapper', function () {
before(function() {
let root = 'https://api.pnut.io'
nock(root)
.get('/v0')
.reply(200, {})
nock(root)
.get('/v0/posts/streams/global')
.reply(200, {posts: 1})
});
after(function() {
nock.cleanAll();
});
it('should get the global timeline', function() {;
return pnut.global().should.become({'posts': 1})
});
});
|
Set REALTIME_UI default to true.
|
<?php
use PHPCensor\Configuration;
use PHPCensor\DatabaseManager;
use PHPCensor\Helper\Lang;
use PHPCensor\StoreRegistry;
const ROOT_DIR = __DIR__ . '/';
const SRC_DIR = ROOT_DIR . 'src/';
const PUBLIC_DIR = ROOT_DIR . 'public/';
const APP_DIR = ROOT_DIR . 'app/';
const RUNTIME_DIR = ROOT_DIR . 'runtime/';
require_once(ROOT_DIR . 'vendor/autoload.php');
$configurationPath = APP_DIR . 'config.yml';
$configuration = new Configuration($configurationPath);
$databaseManager = new DatabaseManager($configuration);
$storeRegistry = new StoreRegistry($databaseManager);
\define('APP_URL', $configuration->get('php-censor.url', '') . '/');
\define('REALTIME_UI', true);
Lang::init($configuration, $storeRegistry);
|
<?php
use PHPCensor\Configuration;
use PHPCensor\DatabaseManager;
use PHPCensor\Helper\Lang;
use PHPCensor\StoreRegistry;
const ROOT_DIR = __DIR__ . '/';
const SRC_DIR = ROOT_DIR . 'src/';
const PUBLIC_DIR = ROOT_DIR . 'public/';
const APP_DIR = ROOT_DIR . 'app/';
const RUNTIME_DIR = ROOT_DIR . 'runtime/';
require_once(ROOT_DIR . 'vendor/autoload.php');
$configurationPath = APP_DIR . 'config.yml';
$configuration = new Configuration($configurationPath);
$databaseManager = new DatabaseManager($configuration);
$storeRegistry = new StoreRegistry($databaseManager);
\define('APP_URL', $configuration->get('php-censor.url', '') . '/');
\define('REALTIME_UI', false);
Lang::init($configuration, $storeRegistry);
|
Change sequelize to use new logger
|
// Sequelize Initialization
var log = require('npmlog');
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var lodash = require('lodash');
var config = require('../config');
var db = {};
var sequelize = new Sequelize(
config.db[config.mode].name,
config.db[config.mode].user,
config.db[config.mode].password,
{
logging: function(message) {
log.info('[\u2713]', message);
}
}
);
fs.readdirSync(__dirname).filter(function(file) {
return ((file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) == '.js'))
}).forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].options.hasOwnProperty('associate')) {
db[modelName].options.associate(db);
}
});
module.exports = lodash.extend({
sequelize: sequelize,
Sequelize: Sequelize
}, db);
|
// Sequelize Initialization
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var lodash = require('lodash');
var config = require('../config');
var sequelize = new Sequelize(config.db[config.mode].name, config.db[config.mode].user, config.db[config.mode].password);
var db = {};
fs.readdirSync(__dirname).filter(function(file) {
return ((file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) == '.js'))
}).forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].options.hasOwnProperty('associate')) {
db[modelName].options.associate(db);
}
});
module.exports = lodash.extend({
sequelize: sequelize,
Sequelize: Sequelize
}, db);
|
Remove db password from source control
|
<?php
include("/secure/data_db_settings.php");
# Read GET variables
$stime = $_POST['stime'];
$etime = $_POST['etime'];
$moves = $_POST['moves'];
$conn = mysql_connect('localhost:3036', $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
unset($dbuser, $dbpass);
mysql_select_db('c0smic_maze-game');
$sql= "INSERT INTO data (stime, etime, moves)
VALUES
('$stime','$etime','$moves')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
echo $str;
?>
|
<?php
# Database variables
$dbhost = 'localhost:3036';
$dbuser = 'c0smic_tyro';
$dbpass = '2$M*k^4!?oDm';
# Read GET variables
$stime = $_POST['stime'];
$etime = $_POST['etime'];
$moves = $_POST['moves'];
# Create output string
$str = "$stime, $etime, \"$moves\"";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('c0smic_maze-game');
$sql= "INSERT INTO data (stime, etime, moves)
VALUES
('$stime','$etime','$moves')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
echo $str;
?>
|
Hide the sidebar by default.
|
import {Experiment, ExperimentStep} from './experiment.model';
angular.module('materialscommons').component('mcExperiment', {
templateUrl: 'app/project/experiments/experiment/mc-experiment.html',
controller: MCExperimentComponentController
});
/*@ngInject*/
function MCExperimentComponentController($scope, moveStep) {
let ctrl = this;
ctrl.currentStep = null;
ctrl.currentNode = null;
ctrl.showSidebar = false;
// Create the initial hard coded experiment
ctrl.experiment = new Experiment('test experiment');
let s = new ExperimentStep('', '');
s.id = "simple0";
ctrl.experiment.steps.push(s);
ctrl.currentStep = s;
ctrl.moveLeft = () => moveStep.left(ctrl.currentNode, ctrl.currentStep, ctrl.experiment);
ctrl.moveRight = () => moveStep.right(ctrl.currentNode, ctrl.currentStep);
ctrl.moveUp = () => moveStep.up(ctrl.currentNode, ctrl.currentStep);
ctrl.moveDown = () => moveStep.down(ctrl.currentNode, ctrl.currentStep, ctrl.experiment);
ctrl.expandAll = () => $scope.$broadcast('angular-ui-tree:expand-all');
ctrl.collapseAll = () => $scope.$broadcast('angular-ui-tree:collapse-all');
ctrl.showStepMaximized = () => ctrl.currentStep && ctrl.currentStep.displayState.maximize;
}
|
import {Experiment, ExperimentStep} from './experiment.model';
angular.module('materialscommons').component('mcExperiment', {
templateUrl: 'app/project/experiments/experiment/mc-experiment.html',
controller: MCExperimentComponentController
});
/*@ngInject*/
function MCExperimentComponentController($scope, moveStep) {
let ctrl = this;
ctrl.currentStep = null;
ctrl.currentNode = null;
ctrl.showSidebar = true;
// Create the initial hard coded experiment
ctrl.experiment = new Experiment('test experiment');
let s = new ExperimentStep('', '');
s.id = "simple0";
ctrl.experiment.steps.push(s);
ctrl.currentStep = s;
ctrl.moveLeft = () => moveStep.left(ctrl.currentNode, ctrl.currentStep, ctrl.experiment);
ctrl.moveRight = () => moveStep.right(ctrl.currentNode, ctrl.currentStep);
ctrl.moveUp = () => moveStep.up(ctrl.currentNode, ctrl.currentStep);
ctrl.moveDown = () => moveStep.down(ctrl.currentNode, ctrl.currentStep, ctrl.experiment);
ctrl.expandAll = () => $scope.$broadcast('angular-ui-tree:expand-all');
ctrl.collapseAll = () => $scope.$broadcast('angular-ui-tree:collapse-all');
ctrl.showStepMaximized = () => ctrl.currentStep && ctrl.currentStep.displayState.maximize;
}
|
Add interval for checking flow meter
|
var twilio = require('twilio'),
express = require('express'),
orderPizza = require('orderpizza'),
kegapi = require('kegapi'),
sendText = require('sendText');
var app = express();
var textResponse = function(request, response) {
console.log('got here');
if (twilio.validateExpressRequest(request, '08b1eaf92fd66749470c93088253c7b4', { url: 'http://samshreds.com:7890/text' })) {
response.header('Content-Type', 'text/xml');
var body = request.param('Body').trim();
var from = request.param('From');
console.log(body);
response.send('<Response><Sms>LOL.</Sms></Response>');
} else {
response.statusCode = 403;
response.render('forbidden');
}
};
app.get('/text', textResponse);
app.listen('7890', function() {
console.log('Visit http://localhost:7890/ in your browser to see your TwiML document!');
});
setInterval(function() {
kegapi.getDrinks(function(volume) {
if(volume > 0) {
sendText('+16107616189', 'I noticed you have been drinking from the keg a lot! Do you want some pizza?.', function() {});
orderPizza();
}
});
}, 60000);
|
var twilio = require('twilio'),
express = require('express'),
orderPizza = require('orderpizza'),
sendText = require('sendText');
var app = express();
var textResponse = function(request, response) {
console.log('got here');
if (twilio.validateExpressRequest(request, '08b1eaf92fd66749470c93088253c7b4', { url: 'http://samshreds.com:7890/text' })) {
response.header('Content-Type', 'text/xml');
var body = request.param('Body').trim();
var from = request.param('From');
console.log(body);
response.send('<Response><Sms>LOL.</Sms></Response>');
} else {
response.statusCode = 403;
response.render('forbidden');
}
};
app.get('/text', textResponse);
app.listen('7890', function() {
console.log('Visit http://localhost:7890/ in your browser to see your TwiML document!');
});
|
Fix expected case on mysql5 foreignKey extraction
|
<?php
/**
* DBSteward unit test for mysql5 foreign key extraction
*
* @package DBSteward
* @license http://www.opensource.org/licenses/bsd-license.php Simplified BSD License
*/
require_once __DIR__ . '/Mysql5ExtractionTest.php';
/**
* @group mysql5
*/
class Mysql5ExtractCompoundForeignKeyTest extends Mysql5ExtractionTest {
public function testCompoundFKeyExtraction() {
$sql = <<<SQL
CREATE TABLE t1 (c1 int, c2 int);
CREATE TABLE t2 (c1 int, c2 int);
CREATE INDEX t2_fkey_idx ON t2 (c1, c2);
ALTER TABLE t1 ADD FOREIGN KEY (c1, c2) REFERENCES t2 (c1, c2);
SQL;
$expected = <<<XML
<foreignKey columns="c1, c2" foreignSchema="Mysql5ExtractionTest" foreignTable="t2" foreignColumns="c1, c2" constraintName="t1_ibfk_1"/>
XML;
$schema = $this->extract($sql);
$this->assertEquals(simplexml_load_string($expected), $schema->table[0]->foreignKey);
}
}
|
<?php
/**
* DBSteward unit test for mysql5 foreign key extraction
*
* @package DBSteward
* @license http://www.opensource.org/licenses/bsd-license.php Simplified BSD License
*/
require_once __DIR__ . '/Mysql5ExtractionTest.php';
/**
* @group mysql5
*/
class Mysql5ExtractCompoundForeignKeyTest extends Mysql5ExtractionTest {
public function testCompoundFKeyExtraction() {
$sql = <<<SQL
CREATE TABLE t1 (c1 int, c2 int);
CREATE TABLE t2 (c1 int, c2 int);
CREATE INDEX t2_fkey_idx ON t2 (c1, c2);
ALTER TABLE t1 ADD FOREIGN KEY (c1, c2) REFERENCES t2 (c1, c2);
SQL;
$expected = <<<XML
<foreignKey columns="c1, c2" foreignSchema="mysql5extractiontest" foreignTable="t2" foreignColumns="c1, c2" constraintName="t1_ibfk_1"/>
XML;
$schema = $this->extract($sql);
$this->assertEquals(simplexml_load_string($expected), $schema->table[0]->foreignKey);
}
}
|
Print the error in the regression test.
|
"""
A regression test for computing three kinds of spectrogram.
Just to ensure we didn't break anything.
"""
import numpy as np
import os
from tfr.files import load_wav
from tfr.spectrogram_features import spectrogram_features
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
def test_spectrograms():
for spectrogram_type in ['stft', 'reassigned', 'chromagram']:
yield assert_spectrogram_is_ok, spectrogram_type
def assert_spectrogram_is_ok(spectrogram_type):
x, fs = load_wav(os.path.join(DATA_DIR, 'she_brings_to_me.wav'))
X = spectrogram_features(x, fs, block_size=4096, hop_size=2048,
spectrogram_type=spectrogram_type, to_log=True)
npz_file = os.path.join(DATA_DIR, 'she_brings_to_me_%s.npz' % spectrogram_type)
X_expected = np.load(npz_file)['arr_0']
print('spectrogram [%s]: max abs error' % spectrogram_type, abs(X - X_expected).max())
assert np.allclose(X, X_expected)
|
"""
A regression test for computing three kinds of spectrogram.
Just to ensure we didn't break anything.
"""
import numpy as np
import os
from tfr.files import load_wav
from tfr.spectrogram_features import spectrogram_features
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
def test_spectrograms():
for spectrogram_type in ['stft', 'reassigned', 'chromagram']:
yield assert_spectrogram_is_ok, spectrogram_type
def assert_spectrogram_is_ok(spectrogram_type):
x, fs = load_wav(os.path.join(DATA_DIR, 'she_brings_to_me.wav'))
X = spectrogram_features(x, fs, block_size=4096, hop_size=2048,
spectrogram_type=spectrogram_type, to_log=True)
npz_file = os.path.join(DATA_DIR, 'she_brings_to_me_%s.npz' % spectrogram_type)
X_expected = np.load(npz_file)['arr_0']
assert np.allclose(X, X_expected)
|
Fix array structure in @var annotation
|
<?php
declare(strict_types=1);
namespace Codeception\Subscriber;
use Codeception\Event\TestEvent;
use Codeception\Events;
use Codeception\ResultAggregator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FailFast implements EventSubscriberInterface
{
use Shared\StaticEventsTrait;
/**
* @var array<string, array<string|int>>
*/
protected static array $events = [
Events::TEST_FAIL => ['stopOnFail', 128],
Events::TEST_ERROR => ['stopOnFail', 128],
];
private int $failureCount = 0;
public function __construct(private int $stopFailureCount, private ResultAggregator $resultAggregator)
{
}
public function stopOnFail(TestEvent $e): void
{
$this->failureCount++;
if ($this->failureCount >= $this->stopFailureCount) {
$this->resultAggregator->stop();
}
}
}
|
<?php
declare(strict_types=1);
namespace Codeception\Subscriber;
use Codeception\Event\TestEvent;
use Codeception\Events;
use Codeception\ResultAggregator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FailFast implements EventSubscriberInterface
{
use Shared\StaticEventsTrait;
/**
* @var array<string, array<string, int>>
*/
protected static array $events = [
Events::TEST_FAIL => ['stopOnFail', 128],
Events::TEST_ERROR => ['stopOnFail', 128],
];
private int $failureCount = 0;
public function __construct(private int $stopFailureCount, private ResultAggregator $resultAggregator)
{
}
public function stopOnFail(TestEvent $e): void
{
$this->failureCount++;
if ($this->failureCount >= $this->stopFailureCount) {
$this->resultAggregator->stop();
}
}
}
|
Add blank line to fix linting error
|
"""A module to prove a way of locating and loading test resource files.
This is akin to the `iati.resources` module, but deals with test data.
"""
import iati.resources
def load_as_dataset(file_path):
"""Load a specified test data file as a Dataset.
Args:
file_path (str): The path of the file, relative to the root test data folder. Folders should be separated by a forward-slash (`/`).
Returns:
dataset: A Dataset containing the contents of the file at the specified location.
Raises:
iati.exceptions.ValidationError: If the provided XML does not conform to the IATI standard.
"""
return iati.resources.load_as_dataset(iati.resources.get_test_data_path(file_path))
def load_as_string(file_path):
"""Load a specified test data file as a string.
Args:
file_path (str): The path of the file, relative to the root test data folder. Folders should be separated by a forward-slash (`/`).
Returns:
str (python3) / unicode (python2): The contents of the file at the specified location.
"""
return iati.resources.load_as_string(iati.resources.get_test_data_path(file_path))
|
"""A module to prove a way of locating and loading test resource files.
This is akin to the `iati.resources` module, but deals with test data.
"""
import iati.resources
def load_as_dataset(file_path):
"""Load a specified test data file as a Dataset.
Args:
file_path (str): The path of the file, relative to the root test data folder. Folders should be separated by a forward-slash (`/`).
Returns:
dataset: A Dataset containing the contents of the file at the specified location.
Raises:
iati.exceptions.ValidationError: If the provided XML does not conform to the IATI standard.
"""
return iati.resources.load_as_dataset(iati.resources.get_test_data_path(file_path))
def load_as_string(file_path):
"""Load a specified test data file as a string.
Args:
file_path (str): The path of the file, relative to the root test data folder. Folders should be separated by a forward-slash (`/`).
Returns:
str (python3) / unicode (python2): The contents of the file at the specified location.
"""
return iati.resources.load_as_string(iati.resources.get_test_data_path(file_path))
|
Add option to print only last step of iteration.
|
#!/usr/bin/env python3
from argparse import ArgumentParser
from itertools import groupby
def iterate(n):
result = 0
digits = [int(i) for i in str(n)]
for k, g in groupby(digits):
result = result * 100 + len(tuple(g)) * 10 + k
return result
def compute(n, i=20):
yield n
x = n
for i in range(0, i):
x = iterate(x)
yield x
def last_item(iter):
item = None
for item in iter:
pass
return item
if __name__ == "__main__":
parser = ArgumentParser(description='Generate sequence of Look-and-Say numbers.')
parser.add_argument('seed', type=int, nargs='?', default=1,
help='sequence seed')
parser.add_argument('-i', '--iterations', dest='iterations', type=int, default=20,
help='number of iterations')
parser.add_argument('-last', '--only-last', action='store_true',
help='print only last step of the iteration')
args = parser.parse_args()
computer = compute(args.seed, args.iterations)
if not args.only_last:
for step in computer:
print(step)
else:
print(last_item(computer))
|
#!/usr/bin/env python3
from argparse import ArgumentParser
from itertools import groupby
def iterate(n):
result = 0
digits = [int(i) for i in str(n)]
for k, g in groupby(digits):
result = result * 100 + len(tuple(g)) * 10 + k
return result
def compute(n, i=20):
yield n
x = n
for i in range(0, i):
x = iterate(x)
yield x
if __name__ == "__main__":
parser = ArgumentParser(description='Generate sequence of Look-and-Say numbers.')
parser.add_argument('seed', type=int, nargs='?', default=1,
help='sequence seed')
parser.add_argument('-i', '--iterations', dest='iterations', type=int, default=20,
help='number of iterations')
args = parser.parse_args()
for step in compute(args.seed, args.iterations):
print(step)
|
Plugins: Read logger config from Preferences
required due to 9b30d85d1b60fef4f4d7c35868dd406f0c5d94f3
|
import logging
import sublime
PACKAGE_NAME = __package__.split(".", 1)[0]
logging.basicConfig(
level=logging.ERROR,
format="%(name)s [%(levelname)s]: %(message)s"
)
logger = logging.getLogger(PACKAGE_NAME)
def load_logger():
"""
Subscribe to Preferences changes in to get log level from user settings.
Must be called in plugin_loaded().
"""
settings = sublime.load_settings("Preferences.sublime-settings")
settings.clear_on_change(__name__)
settings.add_on_change(__name__, on_preferences_changed)
on_preferences_changed()
def unload_logger():
"""
Unsubscribe to Preferences changes.
Must be called in plugin_unloaded().
"""
settings = sublime.load_settings("Preferences.sublime-settings")
settings.clear_on_change(__name__)
def on_preferences_changed():
"""
Update log level according to user settings
"""
settings = sublime.load_settings("Preferences.sublime-settings")
try:
logger.setLevel(settings.get("mde.logging.level", "ERROR"))
except (TypeError, ValueError):
logger.setLevel(logging.ERROR)
|
import logging
import sublime
PACKAGE_NAME = __package__.split(".", 1)[0]
logging.basicConfig(
level=logging.ERROR,
format="%(name)s [%(levelname)s]: %(message)s"
)
logger = logging.getLogger(PACKAGE_NAME)
def load_logger():
"""
Subscribe to Markdown changes in to get log level from user settings.
Must be called in plugin_loaded().
"""
settings = sublime.load_settings("Markdown.sublime-settings")
settings.clear_on_change(__name__)
settings.add_on_change(__name__, on_preferences_changed)
on_preferences_changed()
def unload_logger():
"""
Unsubscribe to Markdown changes.
Must be called in plugin_unloaded().
"""
settings = sublime.load_settings("Markdown.sublime-settings")
settings.clear_on_change(__name__)
def on_preferences_changed():
"""
Update log level according to user settings
"""
settings = sublime.load_settings("Markdown.sublime-settings")
try:
logger.setLevel(settings.get("mde.logging.level", "ERROR"))
except (TypeError, ValueError):
logger.setLevel(logging.ERROR)
|
Expatistan: Move to group "base" and enable "More at ..."
|
(function(env){
env.ddg_spice_expatistan = function(api_result) {
"use strict";
if(!api_result || api_result.status !== 'OK') {
return Spice.failed('expatistan');
}
Spice.add({
id: "expatistan",
name: "Expatistan",
data: api_result,
meta: {
sourceUrl: api_result.source_url,
sourceName: 'Expatistan'
},
templates: {
group: 'base',
options: {
content: Spice.expatistan.content,
moreAt: true
}
}
});
}
}(this));
|
(function(env){
env.ddg_spice_expatistan = function(api_result) {
"use strict";
if(!api_result || api_result.status !== 'OK') {
return Spice.failed('expatistan');
}
Spice.add({
id: "expatistan",
name: "Expatistan",
data: api_result,
meta: {
sourceUrl: api_result.source_url,
sourceName: 'Expatistan'
},
templates: {
group: 'info',
options: {
content: Spice.expatistan.content
}
}
});
}
}(this));
|
Add retry_after to meta of too many requests exception
|
<?php
namespace Notimatica\ApiExceptions;
use Exception;
class TooManyRequestsApiException extends ApiException
{
/**
* @var int|null
*/
protected $retryAfter = null;
/**
* @param int|null $retryAfter
* @param array $headers
* @param string $message
* @param Exception $previous
*/
public function __construct($retryAfter = null, $headers = [], $message = '', Exception $previous = null)
{
$this->retryAfter = $retryAfter;
if (empty($message)) {
$message = 'Rate limit exceed.';
}
if ($retryAfter) {
$headers['Retry-After'] = $retryAfter;
}
parent::__construct(429, 'too_many_requests', $message, $previous, $headers);
}
/**
* Add extra info to the output.
*
* @return mixed
*/
public function getMeta()
{
if ($this->retryAfter) {
return [
'retry_after' => $this->retryAfter
];
}
}
}
|
<?php
namespace Notimatica\ApiExceptions;
use Exception;
class TooManyRequestsApiException extends ApiException
{
/**
* @param int|null $retryAfter
* @param array $headers
* @param string $message
* @param Exception $previous
*/
public function __construct($retryAfter = null, $headers = [], $message = '', Exception $previous = null)
{
if (empty($message)) {
$message = 'Rate limit exceed.';
}
if ($retryAfter) {
$headers['Retry-After'] = $retryAfter;
}
parent::__construct(429, 'too_many_requests', $message, $previous, $headers);
}
}
|
Set log level to WARNING when testing
|
import logging
import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTask():
def setup(self):
wf = sl.WorkflowTask()
self.t = sl.new_task('testtask', TestTask, wf)
def teardown(self):
self.t = None
os.remove(TESTFILE_PATH)
def test_run(self):
# Run a task with a luigi worker
w = luigi.worker.Worker()
w.add(self.t)
w.run()
w.stop()
assert os.path.isfile(TESTFILE_PATH)
|
import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTask():
def setup(self):
wf = sl.WorkflowTask()
self.t = sl.new_task('testtask', TestTask, wf)
def teardown(self):
self.t = None
os.remove(TESTFILE_PATH)
def test_run(self):
# Run a task with a luigi worker
w = luigi.worker.Worker()
w.add(self.t)
w.run()
w.stop()
assert os.path.isfile(TESTFILE_PATH)
|
Allow specifying entry to run
When making an entries object, it's not predictable which entry will be first. This patch allows specifying the entry by name.
|
import cluster from "cluster";
export default class StartServerPlugin {
constructor(entry) {
this.entry = entry;
this.afterEmit = this.afterEmit.bind(this);
this.apply = this.apply.bind(this);
this.startServer = this.startServer.bind(this);
this.worker = null;
}
afterEmit(compilation, callback) {
if (this.worker && this.worker.isConnected()) {
return callback();
}
this.startServer(compilation, callback);
}
apply(compiler) {
compiler.plugin("after-emit", this.afterEmit);
}
startServer(compilation, callback) {
let entry;
const entries = Object.keys(compilation.assets);
if (this.entry) {
entry = this.entry;
if (!compilation.assets[entry]) {
console.error("Entry " + entry + " not found. Try one of: " + entries.join(" "));
} else {
entry = entries[0];
if (entries.length > 1) {
console.log("More than one entry built, selected " + entry + ". All entries: " + entries.join(" "));
}
}
const { existsAt } = compilation.assets[entry];
cluster.setupMaster({ exec: existsAt });
cluster.on("online", (worker) => {
this.worker = worker;
callback();
});
cluster.fork();
}
}
|
import cluster from "cluster";
export default class StartServerPlugin {
constructor() {
this.afterEmit = this.afterEmit.bind(this);
this.apply = this.apply.bind(this);
this.startServer = this.startServer.bind(this);
this.worker = null;
}
afterEmit(compilation, callback) {
if (this.worker && this.worker.isConnected()) {
return callback();
}
this.startServer(compilation, callback);
}
apply(compiler) {
compiler.plugin("after-emit", this.afterEmit);
}
startServer(compilation, callback) {
const entry = Object.keys(compilation.assets).shift();
const { existsAt } = compilation.assets[entry];
cluster.setupMaster({ exec: existsAt });
cluster.on("online", (worker) => {
this.worker = worker;
callback();
});
cluster.fork();
}
}
|
Update to depend on separate powershift-cli package.
|
import sys
import os
from setuptools import setup
long_description = open('README.rst').read()
classifiers = [
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
]
setup_kwargs = dict(
name='powershift-cluster',
version='1.0.4',
description='PowerShift command plugin for creating OpenShift clusters.',
long_description=long_description,
url='https://github.com/getwarped/powershift-cluster',
author='Graham Dumpleton',
author_email='Graham.Dumpleton@gmail.com',
license='BSD',
classifiers=classifiers,
keywords='openshift kubernetes',
packages=['powershift', 'powershift.cluster'],
package_dir={'powershift': 'src/powershift'},
install_requires=['powershift>=1.3.8', 'powershift-cli'],
entry_points = {'powershift_cli_plugins': ['cluster = powershift.cluster']},
)
setup(**setup_kwargs)
|
import sys
import os
from setuptools import setup
long_description = open('README.rst').read()
classifiers = [
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
]
setup_kwargs = dict(
name='powershift-cluster',
version='1.0.4',
description='PowerShift command plugin for creating OpenShift clusters.',
long_description=long_description,
url='https://github.com/getwarped/powershift-cli-cluster',
author='Graham Dumpleton',
author_email='Graham.Dumpleton@gmail.com',
license='BSD',
classifiers=classifiers,
keywords='openshift kubernetes',
packages=['powershift', 'powershift.cluster'],
package_dir={'powershift': 'src/powershift'},
install_requires=['powershift>=1.3.7'],
entry_points = {'powershift_cli_plugins': ['cluster = powershift.cluster']},
)
setup(**setup_kwargs)
|
Add README content to long description
|
import codecs
import setuptools
setuptools.setup(
name='bashlint',
version='0.0.1',
description='Bash linting tool',
long_description=codecs.open('README.rst', 'r', 'utf-8').read(),
keywords='bash',
author='Stanislav Kudriashev',
author_email='stas.kudriashev@gmail.com',
url='https://github.com/skudriashev/bashlint',
license='MIT',
py_modules=['bashlint'],
zip_safe=False,
entry_points={
'console_scripts': [
'bashlint = bashlint:main',
],
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
import setuptools
setuptools.setup(
name='bashlint',
version='0.0.1',
description="Bash linting tool",
long_description="Simple Bash linting tool written in Python.",
keywords='bash',
author='Stanislav Kudriashev',
author_email='stas.kudriashev@gmail.com',
url='https://github.com/skudriashev/bashlint',
license='MIT',
py_modules=['bashlint'],
zip_safe=False,
entry_points={
'console_scripts': [
'bashlint = bashlint:main',
],
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Make fields in example app non required
|
from django.db import models
import i18n
from i18n.models import TranslatableModel
class Document(TranslatableModel):
untranslated_charfield = models.CharField(max_length=50, blank=True)
charfield = i18n.LocalizedCharField(max_length=50)
textfield = i18n.LocalizedTextField(max_length=500, blank=True)
filefield = i18n.LocalizedFileField(null=True, upload_to='files', blank=True)
imagefield = i18n.LocalizedImageField(null=True, upload_to='images', blank=True)
booleanfield = i18n.LocalizedBooleanField()
datefield = i18n.LocalizedDateField(blank=True, null=True)
fkfield = i18n.LocalizedForeignKey('self', null=True, blank=True,
related_name='+')
urlfied = i18n.LocalizedURLField(null=True, blank=True)
decimalfield = i18n.LocalizedDecimalField(max_digits=4, decimal_places=2, null=True,
blank=True)
integerfield = i18n.LocalizedIntegerField(null=True, blank=True)
def __str__(self):
return '%d, %s' % (self.pk, self.charfield)
class Meta:
app_label = 'example'
|
import i18n
from i18n.models import TranslatableModel
class Document(TranslatableModel):
charfield = i18n.LocalizedCharField(max_length=50)
textfield = i18n.LocalizedTextField(max_length=512)
filefield = i18n.LocalizedFileField(null=True, upload_to='files')
imagefield = i18n.LocalizedImageField(null=True, upload_to='images')
booleanfield = i18n.LocalizedBooleanField()
datefield = i18n.LocalizedDateField()
fkfield = i18n.LocalizedForeignKey('self', null=True, blank=True,
related_name='+')
urlfied = i18n.LocalizedURLField()
decimalfield = i18n.LocalizedDecimalField(max_digits=4, decimal_places=2)
integerfield = i18n.LocalizedIntegerField()
def __str__(self):
return '%d, %s' % (self.pk, self.charfield)
class Meta:
app_label = 'example'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.