text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add scrolling to go to the more interesting parts of desk_intelwiki.skp
Bug: skia:11804
Change-Id: I96ce34311b5e5420ee343a0dbc68ef20f399be4f
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/390336
Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
Reviewed-by: Robert Phillips <95e8ac5504948c7bf91b22c16a8dbb7ae7c66bfd@google.com> | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
class SkiaBuildbotDesktopPage(page_module.Page):
def __init__(self, url, page_set):
super(SkiaBuildbotDesktopPage, self).__init__(
url=url,
name=url,
page_set=page_set,
shared_page_state_class=shared_page_state.SharedDesktopPageState)
self.archive_data_file = 'data/skia_intelwiki_desktop.json'
def RunNavigateSteps(self, action_runner):
action_runner.Navigate(self.url)
action_runner.Wait(20)
def RunPageInteractions(self, action_runner):
with action_runner.CreateGestureInteraction('ScrollAction'):
action_runner.ScrollPage()
class SkiaIntelwikiDesktopPageSet(story.StorySet):
""" Pages designed to represent the median, not highly optimized web """
def __init__(self):
super(SkiaIntelwikiDesktopPageSet, self).__init__(
archive_data_file='data/skia_intelwiki_desktop.json')
urls_list = [
# go/skia-skps-3-19
'https://en.wikipedia.org/wiki/Intel_Graphics_Technology',
]
for url in urls_list:
self.AddStory(SkiaBuildbotDesktopPage(url, self))
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
class SkiaBuildbotDesktopPage(page_module.Page):
def __init__(self, url, page_set):
super(SkiaBuildbotDesktopPage, self).__init__(
url=url,
name=url,
page_set=page_set,
shared_page_state_class=shared_page_state.SharedDesktopPageState)
self.archive_data_file = 'data/skia_intelwiki_desktop.json'
def RunNavigateSteps(self, action_runner):
action_runner.Navigate(self.url)
action_runner.Wait(120)
class SkiaIntelwikiDesktopPageSet(story.StorySet):
""" Pages designed to represent the median, not highly optimized web """
def __init__(self):
super(SkiaIntelwikiDesktopPageSet, self).__init__(
archive_data_file='data/skia_intelwiki_desktop.json')
urls_list = [
# go/skia-skps-3-19
'https://en.wikipedia.org/wiki/Intel_Graphics_Technology',
]
for url in urls_list:
self.AddStory(SkiaBuildbotDesktopPage(url, self))
|
Fix bug that prevents Locale from launching scripts. | /*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.ase.locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.ase.Constants;
import com.google.ase.IntentBuilders;
public class LocaleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String scriptName = intent.getStringExtra(Constants.EXTRA_SCRIPT_NAME);
Log.v("LocaleReceiver", "Locale initiated launch of " + scriptName);
context.startActivity(IntentBuilders.buildStartInTerminalIntent(scriptName));
}
}
| /*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.ase.locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.ase.Constants;
import com.google.ase.IntentBuilders;
public class LocaleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String scriptName = intent.getStringExtra(Constants.EXTRA_SCRIPT_NAME);
Log.v("LocaleReceiver", "Locale initiated launch of " + scriptName);
context.startService(IntentBuilders.buildStartInTerminalIntent(scriptName));
}
}
|
Updated: Make sure nick has prefix if you're going to cut it off (TagAPI) | package org.royaldev.royalcommands.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import org.royaldev.royalcommands.PConfManager;
import org.royaldev.royalcommands.RoyalCommands;
public class TagAPIListener implements Listener {
RoyalCommands plugin;
public TagAPIListener(RoyalCommands instance) {
plugin = instance;
}
@EventHandler
public void onTag(PlayerReceiveNameTagEvent e) {
if (e.getNamedPlayer() == null) return;
PConfManager pcm = new PConfManager(e.getNamedPlayer());
String dispname = pcm.getString("dispname");
if (dispname == null) return;
if (dispname.equalsIgnoreCase(e.getNamedPlayer().getName())) {
e.setTag(dispname);
return;
}
if (!plugin.nickPrefix.equals("") && dispname.startsWith(plugin.nickPrefix))
dispname = dispname.substring(plugin.nickPrefix.length());
e.setTag(dispname);
}
}
| package org.royaldev.royalcommands.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import org.royaldev.royalcommands.PConfManager;
import org.royaldev.royalcommands.RoyalCommands;
public class TagAPIListener implements Listener {
RoyalCommands plugin;
public TagAPIListener(RoyalCommands instance) {
plugin = instance;
}
@EventHandler
public void onTag(PlayerReceiveNameTagEvent e) {
if (e.getNamedPlayer() == null) return;
PConfManager pcm = new PConfManager(e.getNamedPlayer());
String dispname = pcm.getString("dispname");
if (dispname == null) return;
if (dispname.equalsIgnoreCase(e.getNamedPlayer().getName())) {
e.setTag(dispname);
return;
}
if (!plugin.nickPrefix.equals(""))
dispname = dispname.substring(plugin.nickPrefix.length());
e.setTag(dispname);
}
}
|
fix(check): Include more action names in various checks. | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Actions that, if allowed, would allow an attacker
// to try a candidtate password against an account.
var PASSWORD_CHECKING_ACTION = {
accountLogin: true,
accountDestroy: true,
passwordChange: true,
}
// Actions that, if allowed, would allow an attacker
// to check whether an account exists for a particular user.
// Basically any unauthenticated endpoint that takes
// an email address as input.
var ACCOUNT_STATUS_ACTION = {
accountCreate: true,
accountLogin: true,
accountDestroy: true,
accountLock: true,
accountUnlockResendCode: true,
passwordChange: true,
passwordForgotSendCode: true,
accountStatusCheck: true
}
// Actions that send an email, and hence might make
// us look like spammers if abused.
var EMAIL_SENDING_ACTION = {
accountCreate: true,
accountUnlockResendCode: true,
recoveryEmailResendCode: true,
passwordForgotSendCode: true,
passwordForgotResendCode: true
}
module.exports = {
isPasswordCheckingAction: function isPasswordCheckingAction(action) {
return PASSWORD_CHECKING_ACTION[action]
},
isAccountStatusAction: function isAccountStatusAction(action) {
return ACCOUNT_STATUS_ACTION[action]
},
isEmailSendingAction: function isEmailSendingAction(action) {
return EMAIL_SENDING_ACTION[action]
}
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var PASSWORD_CHECKING_ACTION = {
accountLogin: true,
accountDestroy: true,
passwordChange: true,
}
var ACCOUNT_STATUS_ACTION = {
accountStatusCheck: true
}
var EMAIL_SENDING_ACTION = {
accountCreate: true,
recoveryEmailResendCode: true,
passwordForgotSendCode: true,
passwordForgotResendCode: true
}
module.exports = {
isPasswordCheckingAction: function isPasswordCheckingAction(action) {
return PASSWORD_CHECKING_ACTION[action]
},
isAccountStatusAction: function isAccountStatusAction(action) {
return ACCOUNT_STATUS_ACTION[action]
},
isEmailSendingAction: function isEmailSendingAction(action) {
return EMAIL_SENDING_ACTION[action]
}
}
|
Make minimum cffi versions consistent | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.0', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
| #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.3', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
|
Make dev server accessible on lan | var webpack = require('webpack');
var config = require('./webpack.config.js');
config.entry = [
'webpack-dev-server/client?http://localhost:8888',
'webpack/hot/only-dev-server'
].concat(config.entry);
config.plugins = [
new webpack.NoErrorsPlugin()
];
config.module.loaders = [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?optional[]=es7.classProperties'],
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'resolve-url', 'sass'],
exclude: /node_modules/
}
].concat(config.module.loaders);
config.devServer = {
contentBase: "./public",
noInfo: true, // --no-info option
historyApiFallback: true,
hot: true,
host: '0.0.0.0',
inline: true,
port: 8888,
watchOptions: {
poll: true
}
}
module.exports = config;
| var webpack = require('webpack');
var config = require('./webpack.config.js');
config.entry = [
'webpack-dev-server/client?http://localhost:8888',
'webpack/hot/only-dev-server'
].concat(config.entry);
config.plugins = [
new webpack.NoErrorsPlugin()
];
config.module.loaders = [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?optional[]=es7.classProperties'],
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'resolve-url', 'sass'],
exclude: /node_modules/
}
].concat(config.module.loaders);
config.devServer = {
contentBase: "./public",
noInfo: true, // --no-info option
historyApiFallback: true,
hot: true,
inline: true,
port: 8888,
watchOptions: {
poll: true
}
}
module.exports = config;
|
Add extra space for convention. | var rest = require('restler');
module.exports = {
'gif': function(input, cb) {
var self = this;
var query = encodeURIComponent(input.parsed);
var options = { rejectUnauthorized: false };
var baseUrl = 'https://ticketap.com/rightgif';
var url = baseUrl + '?text='+query;
rest.get(url, options).on('complete', function(data) {
var img;
if (data.gifs && data.gifs.length > 0) {
img = self.chooseRandom(data.gifs).url;
} else {
img = data.url;
}
cb(null, 'word! ' + img);
});
},
'chooseRandom': function(gifs) {
return gifs[Math.floor(Math.random() * gifs.length)];
}
};
| var rest = require('restler');
module.exports = {
'gif': function(input, cb) {
var self = this;
var query = encodeURIComponent(input.parsed);
var options = { rejectUnauthorized: false };
var baseUrl = 'https://ticketap.com/rightgif';
var url = baseUrl + '?text='+query;
rest.get(url, options).on('complete', function(data) {
var img;
if(data.gifs && data.gifs.length > 0) {
img = self.chooseRandom(data.gifs).url;
} else {
img = data.url;
}
cb(null, 'word! ' + img);
});
},
'chooseRandom': function(gifs) {
return gifs[Math.floor(Math.random() * gifs.length)];
}
};
|
Add the 'hljs' class to the pre tag | 'use strict';
var cheerio = require('cheerio');
var he = require('he');
var hl = require('highlight.js');
var highlightAuto = hl.highlightAuto;
var highlight = hl.highlight;
module.exports = function(input) {
this.cacheable();
var $ = cheerio.load(input);
$('code').replaceWith(function(i, e) {
var $e = $(e);
var text = $e.text();
if(text.split('\n').length < 2) {
return $('<code>' + he.encode(text) + '</code>');
}
var text = $e.text();
var klass = $e.attr('class') || '';
var lang = klass.split('lang-').filter(id);
lang = lang && lang[0];
if(lang) {
return highlight(lang, text).value;
}
return highlightAuto(text).value;
});
$('pre').addClass('hljs');
return $.html();
};
function id(a) {return a;}
| 'use strict';
var cheerio = require('cheerio');
var he = require('he');
var hl = require('highlight.js');
var highlightAuto = hl.highlightAuto;
var highlight = hl.highlight;
module.exports = function(input) {
this.cacheable();
var $ = cheerio.load(input);
$('code').replaceWith(function(i, e) {
var $e = $(e);
var text = $e.text();
if(text.split('\n').length < 2) {
return $('<code>' + he.encode(text) + '</code>');
}
var text = $e.text();
var klass = $e.attr('class') || '';
var lang = klass.split('lang-').filter(id);
lang = lang && lang[0];
if(lang) {
return highlight(lang, text).value;
}
return highlightAuto(text).value;
});
return $.html();
};
function id(a) {return a;}
|
Modify harvestibility for butter blocks. | package net.darkmorford.btweagles.block;
import net.darkmorford.btweagles.BetterThanWeagles;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockButter extends Block
{
public BlockButter()
{
super(Material.ROCK);
this.slipperiness = 0.98F;
setRegistryName(BetterThanWeagles.MODID, "butter");
setUnlocalizedName("butter");
setCreativeTab(BetterThanWeagles.tabBTWeagles);
setSoundType(SoundType.SLIME);
setHarvestLevel("shovel", 2);
setHardness(2.0F);
}
@SideOnly(Side.CLIENT)
public void initModel()
{
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
}
}
| package net.darkmorford.btweagles.block;
import net.darkmorford.btweagles.BetterThanWeagles;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockButter extends Block
{
public BlockButter()
{
super(Material.CLAY);
this.slipperiness = 0.98F;
setRegistryName(BetterThanWeagles.MODID, "butter");
setUnlocalizedName("butter");
setCreativeTab(BetterThanWeagles.tabBTWeagles);
setSoundType(SoundType.SLIME);
}
@SideOnly(Side.CLIENT)
public void initModel()
{
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
}
}
|
Make So loading inside generated TMM delegates less confusing
Summary:
## Rationale
Inlining the maybeLoadSoLibrary private static method makes following the So load chain from TurboModuleManagerDelegate through ReactPackageTurboModuleManagerDelegate to each app's TurboModuleManagerDelegate much easier to understand.
Changelog: [Internal]
Reviewed By: sshic
Differential Revision: D30082675
fbshipit-source-id: ff467d6ac8c792317dd9bdcd91844d3b480cbb60 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.uiapp;
import androidx.annotation.VisibleForTesting;
import com.facebook.jni.HybridData;
import com.facebook.react.ReactPackage;
import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.soloader.SoLoader;
import java.util.List;
/** This class is responsible for creating all the TurboModules for the RNTester app. */
public class RNTesterTurboModuleManagerDelegate extends ReactPackageTurboModuleManagerDelegate {
private static volatile boolean sIsSoLibraryLoaded;
protected native HybridData initHybrid();
@VisibleForTesting
native boolean canCreateTurboModule(String moduleName);
private RNTesterTurboModuleManagerDelegate(
ReactApplicationContext context, List<ReactPackage> packages) {
super(context, packages);
}
public static class Builder extends ReactPackageTurboModuleManagerDelegate.Builder {
protected RNTesterTurboModuleManagerDelegate build(
ReactApplicationContext context, List<ReactPackage> packages) {
return new RNTesterTurboModuleManagerDelegate(context, packages);
}
}
@Override
protected synchronized void maybeLoadOtherSoLibraries() {
// Prevents issues with initializer interruptions.
if (!sIsSoLibraryLoaded) {
SoLoader.loadLibrary("rntester_appmodules");
sIsSoLibraryLoaded = true;
}
}
}
| /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.uiapp;
import androidx.annotation.VisibleForTesting;
import com.facebook.jni.HybridData;
import com.facebook.react.ReactPackage;
import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.soloader.SoLoader;
import java.util.List;
/** This class is responsible for creating all the TurboModules for the RNTester app. */
public class RNTesterTurboModuleManagerDelegate extends ReactPackageTurboModuleManagerDelegate {
private static volatile boolean sIsSoLibraryLoaded;
protected native HybridData initHybrid();
@VisibleForTesting
native boolean canCreateTurboModule(String moduleName);
private RNTesterTurboModuleManagerDelegate(
ReactApplicationContext context, List<ReactPackage> packages) {
super(context, packages);
}
public static class Builder extends ReactPackageTurboModuleManagerDelegate.Builder {
protected RNTesterTurboModuleManagerDelegate build(
ReactApplicationContext context, List<ReactPackage> packages) {
return new RNTesterTurboModuleManagerDelegate(context, packages);
}
}
@Override
protected void maybeLoadOtherSoLibraries() {
maybeLoadSoLibraries();
}
// Prevents issues with initializer interruptions.
private static synchronized void maybeLoadSoLibraries() {
if (!sIsSoLibraryLoaded) {
SoLoader.loadLibrary("rntester_appmodules");
sIsSoLibraryLoaded = true;
}
}
}
|
Add handy main() method for hashing a given value | /*
* Copyright Myrrix Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.myrrix.client.translating;
import org.apache.mahout.cf.taste.impl.model.AbstractIDMigrator;
/**
* Used when translation is needed only one-way, never back. The mappings do not need to be remembered.
*/
public final class OneWayMigrator extends AbstractIDMigrator {
@Override
public String toStringID(long longID) {
throw new UnsupportedOperationException();
}
/**
* Prints the hashed long value of the given string argument.
*
* @param args first argument is string to hash
*/
public static void main(String[] args) {
System.out.println(new OneWayMigrator().toLongID(args[0]));
}
}
| /*
* Copyright Myrrix Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.myrrix.client.translating;
import org.apache.mahout.cf.taste.impl.model.AbstractIDMigrator;
/**
* Used when translation is needed only one-way, never back. The mappings do not need to be remembered.
*/
public final class OneWayMigrator extends AbstractIDMigrator {
@Override
public String toStringID(long longID) {
throw new UnsupportedOperationException();
}
}
|
Change votes route to / | Router.configure({
layoutTemplate: 'layout'
});
Router.route('/', {name: 'votesList'});
Router.route('/iframe', {name: 'iFrame'});
Router.route('/submitvote', {name: 'submitVote'});
Router.route('/signup', {name: 'signup'});
Router.route('/scores', {name: 'scoreCard'});
Router.route('/login', {name: 'loginpage'});
var requireLogin = function() { if (! Meteor.user()) {
if (Meteor.loggingIn()) { this.render(this.loadingTemplate);
} this.render('accessDenied');
} else {
this.next(); }
}
Router.onBeforeAction(requireLogin, {only: 'submitVote'});
Router.route('/votes/:_id', {
name: 'voteInfoPage',
data: function() { return VotesCollection.findOne(this.params._id); }
});
Router.route('/votes/comments/:_id', {
name: 'commentList',
data: function() { return VotesCollection.findOne(this.params._id); }
});
| Router.configure({
layoutTemplate: 'layout'
});
Router.route('/votes', {name: 'votesList'});
Router.route('/iframe', {name: 'iFrame'});
Router.route('/submitvote', {name: 'submitVote'});
Router.route('/signup', {name: 'signup'});
Router.route('/scores', {name: 'scoreCard'});
Router.route('/login', {name: 'loginpage'});
var requireLogin = function() { if (! Meteor.user()) {
if (Meteor.loggingIn()) { this.render(this.loadingTemplate);
} this.render('accessDenied');
} else {
this.next(); }
}
Router.onBeforeAction(requireLogin, {only: 'submitVote'});
Router.route('/votes/:_id', {
name: 'voteInfoPage',
data: function() { return VotesCollection.findOne(this.params._id); }
});
Router.route('/votes/comments/:_id', {
name: 'commentList',
data: function() { return VotesCollection.findOne(this.params._id); }
});
|
Add build step into Conan recipe. | from conans import ConanFile, CMake
class ArgsConan(ConanFile):
name = "cfgfile"
version = "0.2.8.2"
url = "https://github.com/igormironchik/cfgfile.git"
license = "MIT"
description = "Header-only library for reading/saving configuration files with schema defined in sources."
exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp"
def build(self):
cmake = CMake(self)
cmake.configure(source_folder="generator")
cmake.build()
def package(self):
self.copy("COPYING", src=".", dst=".")
self.copy("*", src="cfgfile", dst="cfgfile")
self.copy("*", src="generator", dst="generator")
self.copy("*.hpp", src="3rdparty/Args/Args", dst="3rdparty/Args/Args")
def package_info(self):
self.cpp_info.includedirs = ["."]
| from conans import ConanFile
class ArgsConan(ConanFile):
name = "cfgfile"
version = "0.2.8.2"
url = "https://github.com/igormironchik/cfgfile.git"
license = "MIT"
description = "Header-only library for reading/saving configuration files with schema defined in sources."
exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp"
def package(self):
self.copy("COPYING", src=".", dst=".")
self.copy("*", src="cfgfile", dst="cfgfile")
self.copy("*", src="generator", dst="generator")
self.copy("*.hpp", src="3rdparty/Args/Args", dst="3rdparty/Args/Args")
def package_info(self):
self.cpp_info.includedirs = ["."]
|
Add documentation for stooge types | package creational
import (
"fmt"
"io"
"os"
)
var outputWriter io.Writer = os.Stdout // modified during testing
// StoogeType is used as a enum for stooge types.
type StoogeType int
const (
Larry StoogeType = iota // Larry stooge
Moe // Moe stooge
Curly // Cutly stooge
)
// Stooge provides an interface for interacting with stooges.
type Stooge interface {
SlapStick()
}
type larry struct {
}
func (s *larry) SlapStick() {
fmt.Fprint(outputWriter, "Larry: Poke eyes\n")
}
type moe struct {
}
func (s *moe) SlapStick() {
fmt.Fprint(outputWriter, "Moe: Slap head\n")
}
type curly struct {
}
func (s *curly) SlapStick() {
fmt.Fprint(outputWriter, "Curly: Suffer abuse\n")
}
// NewStooge creates new stooges given the stooge type.
// Nil is returned if the stooge type is not recognised.
func NewStooge(stooge StoogeType) Stooge {
if stooge == Larry {
return &larry{}
} else if stooge == Moe {
return &moe{}
} else if stooge == Curly {
return &curly{}
}
return nil
}
| package creational
import (
"fmt"
"io"
"os"
)
var outputWriter io.Writer = os.Stdout // modified during testing
// StoogeType is used as a enum for stooge types.
type StoogeType int
const (
Larry StoogeType = iota
Moe
Curly
)
// Stooge provides an interface for interacting with stooges.
type Stooge interface {
SlapStick()
}
type larry struct {
}
func (s *larry) SlapStick() {
fmt.Fprint(outputWriter, "Larry: Poke eyes\n")
}
type moe struct {
}
func (s *moe) SlapStick() {
fmt.Fprint(outputWriter, "Moe: Slap head\n")
}
type curly struct {
}
func (s *curly) SlapStick() {
fmt.Fprint(outputWriter, "Curly: Suffer abuse\n")
}
// NewStooge creates new stooges given the stooge type.
// Nil is returned if the stooge type is not recognised.
func NewStooge(stooge StoogeType) Stooge {
if stooge == Larry {
return &larry{}
} else if stooge == Moe {
return &moe{}
} else if stooge == Curly {
return &curly{}
}
return nil
}
|
Improve batching of ids for querying | import {pluck} from 'lodash/collection'
import Promise from 'bluebird'
const BATCH_CHAR_LIMIT = 1990
/**
* Gets the content already existent on the destination space that needs
* updating, based on the response retrieved from the source space
*/
export default function getDestinationContentForUpdate (managementClient, spaceId, sourceResponse) {
const entryIds = pluck(sourceResponse.entries, 'sys.id')
const assetIds = pluck(sourceResponse.assets, 'sys.id')
return managementClient.getSpace(spaceId)
.then(space => {
return Promise.props({
contentTypes: space.getContentTypes(),
entries: batchedIdQuery(space, 'getEntries', entryIds),
assets: batchedIdQuery(space, 'getAssets', assetIds),
locales: space.getLocales()
})
})
}
function batchedIdQuery (space, method, ids) {
return Promise.reduce(getIdBatches(ids), (fullResponse, batch) => {
return space[method]({'sys.id[in]': batch})
.then(response => {
fullResponse = fullResponse.concat(response)
return fullResponse
})
}, [])
}
function getIdBatches (ids) {
const batches = []
let currentBatch = []
while (ids.length > 0) {
let id = ids.splice(0, 1)
currentBatch.push(id)
if (currentBatch.length > BATCH_CHAR_LIMIT || ids.length === 0) {
batches.push(currentBatch.join(','))
currentBatch = []
}
}
return batches
}
| import {pluck} from 'lodash/collection'
import Promise from 'bluebird'
const BATCH_CHAR_LIMIT = 1990
/**
* Gets the content already existent on the destination space that needs
* updating, based on the response retrieved from the source space
*/
export default function getDestinationContentForUpdate (managementClient, spaceId, sourceResponse) {
const entryIds = pluck(sourceResponse.entries, 'sys.id')
const assetIds = pluck(sourceResponse.assets, 'sys.id')
return managementClient.getSpace(spaceId)
.then(space => {
return Promise.props({
contentTypes: space.getContentTypes(),
entries: batchedIdQuery(space, 'getEntries', entryIds),
assets: batchedIdQuery(space, 'getAssets', assetIds),
locales: space.getLocales()
})
})
}
function batchedIdQuery (space, method, ids) {
return Promise.reduce(getIdBatches(ids), (fullResponse, batch) => {
return space[method]({'sys.id[in]': batch})
.then(response => {
fullResponse = fullResponse.concat(response)
return fullResponse
})
}, [])
}
function getIdBatches (ids) {
let currentBatch = ''
const batches = []
while (ids.length > 0) {
let id = ids.splice(0, 1)
currentBatch += id + ','
if (currentBatch.length > BATCH_CHAR_LIMIT || ids.length === 0) {
batches.push(currentBatch)
currentBatch = ''
}
}
return batches
}
|
Update tests to reflect title change | from flask import url_for
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from tests.helpers import slow
@pytest.mark.usefixtures('live_server')
@slow
def test_home_page_accessible(selenium):
go_to_home_page(selenium)
WebDriverWait(selenium, 5).until(expected_conditions.title_is(
'Flask + Dashboard = Flash'
))
assert selenium.find_element(By.CLASS_NAME, 'headline').text == 'PROJECT GNOME'
@pytest.mark.usefixtures('live_server')
@slow
def test_home_page_contains_tracker_dashboard(selenium):
go_to_home_page(selenium)
WebDriverWait(selenium, 5).until(
expected_conditions.presence_of_element_located(
(By.CLASS_NAME, 'tracker-pane')
)
)
def go_to_home_page(selenium):
selenium.get(url_for('home', _external=True))
| from flask import url_for
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from tests.helpers import slow
@pytest.mark.usefixtures('live_server')
@slow
def test_home_page_accessible(selenium):
go_to_home_page(selenium)
WebDriverWait(selenium, 5).until(expected_conditions.title_is(
'Flash - Flask Dashboard'
))
assert selenium.find_element(By.CLASS_NAME, 'headline').text == 'PROJECT GNOME'
@pytest.mark.usefixtures('live_server')
@slow
def test_home_page_contains_tracker_dashboard(selenium):
go_to_home_page(selenium)
WebDriverWait(selenium, 5).until(
expected_conditions.presence_of_element_located(
(By.CLASS_NAME, 'tracker-pane')
)
)
def go_to_home_page(selenium):
selenium.get(url_for('home', _external=True))
|
Increment static resources for Firebase. | import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
"firebase-url": "https://thebluealliance-dev.firebaseio.com/{}.json?print=silent&auth={}"
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
"firebase-url": "https://thebluealliance.firebaseio.com/{}.json?print=silent&auth={}"
}
CONFIG['landing_handler'] = COMPETITIONSEASON
CONFIG["static_resource_version"] = 4
| import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
"firebase-url": "https://thebluealliance-dev.firebaseio.com/{}.json?print=silent&auth={}"
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
"firebase-url": "https://thebluealliance.firebaseio.com/{}.json?print=silent&auth={}"
}
CONFIG['landing_handler'] = COMPETITIONSEASON
CONFIG["static_resource_version"] = 3
|
Make development version badge less prominent | /**
* Background tasks
*/
class PathmarksBackground {
static standardIcon() {
chrome.browserAction.setIcon({path: '../images/icon38.png'});
}
static devBadge() {
if (chrome.runtime.getManifest().short_name === 'PathDev') {
chrome.browserAction.setBadgeText({text: "µ"});
chrome.browserAction.setBadgeBackgroundColor({color: 'rgb(80,80,80)'});
}
}
}
/**
* Upgrade tasks
*/
class PathmarksUpgrade {
static upgradeToSyncStorage() {
chrome.storage.local.get('pathmarks', (store) => {
if (store['pathmarks']) {
console.log("Local storage entries found. Convert to sync storage...");
chrome.storage.sync.set(store, () => {
console.log('Copy pathmarks to sync storage.');
chrome.storage.local.clear(() => {
console.log("Remove local storage entries");
console.log('Conversion to sync storage completed.');
});
});
}
});
}
}
chrome.runtime.onInstalled.addListener(() => PathmarksUpgrade.upgradeToSyncStorage());
chrome.runtime.onInstalled.addListener(() => PathmarksBackground.devBadge());
chrome.runtime.onConnect.addListener((port) => {
port.onDisconnect.addListener(() => PathmarksBackground.standardIcon());
});
| /**
* Background tasks
*/
class PathmarksBackground {
static standardIcon() {
chrome.browserAction.setIcon({path: '../images/icon38.png'});
}
static devBadge() {
if (chrome.runtime.getManifest().short_name === 'PathDev') {
chrome.browserAction.setBadgeText({text: "µ"});
chrome.browserAction.setBadgeBackgroundColor({color: '#753015'});
}
}
}
/**
* Upgrade tasks
*/
class PathmarksUpgrade {
static upgradeToSyncStorage() {
chrome.storage.local.get('pathmarks', (store) => {
if (store['pathmarks']) {
console.log("Local storage entries found. Convert to sync storage...");
chrome.storage.sync.set(store, () => {
console.log('Copy pathmarks to sync storage.');
chrome.storage.local.clear(() => {
console.log("Remove local storage entries");
console.log('Conversion to sync storage completed.');
});
});
}
});
}
}
chrome.runtime.onInstalled.addListener(() => PathmarksUpgrade.upgradeToSyncStorage());
chrome.runtime.onInstalled.addListener(() => PathmarksBackground.devBadge());
chrome.runtime.onConnect.addListener((port) => {
port.onDisconnect.addListener(() => PathmarksBackground.standardIcon());
});
|
Fix `migrate:reset` args as it doesn't accept --step | <?php
declare(strict_types=1);
namespace Rinvex\Attributes\Console\Commands;
use Illuminate\Console\Command;
class RollbackCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:rollback:attributes {--force : Force the operation to run when in production.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rollback Rinvex Attributes Tables.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
if (file_exists($path = 'database/migrations/rinvex/laravel-attributes')) {
$this->call('migrate:reset', [
'--path' => $path,
'--force' => $this->option('force'),
]);
} else {
$this->warn('No migrations found! Consider publish them first: <fg=green>php artisan rinvex:publish:attributes</>');
}
$this->line('');
}
}
| <?php
declare(strict_types=1);
namespace Rinvex\Attributes\Console\Commands;
use Illuminate\Console\Command;
class RollbackCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:rollback:attributes {--force : Force the operation to run when in production.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rollback Rinvex Attributes Tables.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
if (file_exists($path = 'database/migrations/rinvex/laravel-attributes')) {
$this->call('migrate:reset', [
'--step' => true,
'--path' => $path,
'--force' => $this->option('force'),
]);
} else {
$this->warn('No migrations found! Consider publish them first: <fg=green>php artisan rinvex:publish:attributes</>');
}
$this->line('');
}
}
|
Change widget attribute to string
In Django 1.8, widget attribute data-date-picker=True will be rendered
as 'data-date-picker'. This patch will just look for the presence of the
attribute, ignoring the actual value.
Change-Id: I0beabddfe13c060ef2222a09636738428135040a
Closes-Bug: #1467935 | horizon.metering = {
init_create_usage_report_form: function() {
horizon.datepickers.add('input[data-date-picker]');
horizon.metering.add_change_event_to_period_dropdown();
horizon.metering.show_or_hide_date_fields();
},
init_stats_page: function() {
if (typeof horizon.d3_line_chart !== 'undefined') {
horizon.d3_line_chart.init("div[data-chart-type='line_chart']",
{'auto_resize': true});
}
horizon.metering.add_change_event_to_period_dropdown();
horizon.metering.show_or_hide_date_fields();
},
show_or_hide_date_fields: function() {
$("#date_from .controls input, #date_to .controls input").val('');
if ($("#id_period").find("option:selected").val() === "other"){
$("#id_date_from, #id_date_to").parent().parent().show();
return true;
} else {
$("#id_date_from, #id_date_to").parent().parent().hide();
return false;
}
},
add_change_event_to_period_dropdown: function() {
$("#id_period").change(function(evt) {
if (horizon.metering.show_or_hide_date_fields()) {
evt.stopPropagation();
}
});
}
};
| horizon.metering = {
init_create_usage_report_form: function() {
horizon.datepickers.add('input[data-date-picker="True"]');
horizon.metering.add_change_event_to_period_dropdown();
horizon.metering.show_or_hide_date_fields();
},
init_stats_page: function() {
if (typeof horizon.d3_line_chart !== 'undefined') {
horizon.d3_line_chart.init("div[data-chart-type='line_chart']",
{'auto_resize': true});
}
horizon.metering.add_change_event_to_period_dropdown();
horizon.metering.show_or_hide_date_fields();
},
show_or_hide_date_fields: function() {
$("#date_from .controls input, #date_to .controls input").val('');
if ($("#id_period").find("option:selected").val() === "other"){
$("#id_date_from, #id_date_to").parent().parent().show();
return true;
} else {
$("#id_date_from, #id_date_to").parent().parent().hide();
return false;
}
},
add_change_event_to_period_dropdown: function() {
$("#id_period").change(function(evt) {
if (horizon.metering.show_or_hide_date_fields()) {
evt.stopPropagation();
}
});
}
};
|
Fix neverending creation of migrations on heroku | from celery import states
from django.db import models
ALL_STATES = sorted(states.ALL_STATES)
STATES_CHOICES = zip(ALL_STATES, ALL_STATES)
class TaskStatus(models.Model):
"""
Task status.
With this the status of celery tasks can be monitored, more reliably than
depending on the broker or celery itself.
"""
status = models.CharField(max_length=20, default=states.PENDING, choices=STATES_CHOICES, db_index=True)
task_id = models.CharField(max_length=50, unique=True, blank=True, null=True, db_index=True)
signature = models.CharField(max_length=255, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expires_at = models.DateTimeField(null=True)
def __unicode__(self):
return unicode('%s | %s | %s ' % (
self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
self.status,
self.signature
))
class Meta:
app_label = 'taskmonitor'
verbose_name_plural = 'Task statuses'
| from celery import states
from django.db import models
STATES_CHOICES = zip(states.ALL_STATES, states.ALL_STATES)
class TaskStatus(models.Model):
"""
Task status.
With this the status of celery tasks can be monitored, more reliably than
depending on the broker or celery itself.
"""
status = models.CharField(max_length=20, default=states.PENDING, choices=STATES_CHOICES, db_index=True)
task_id = models.CharField(max_length=50, unique=True, blank=True, null=True, db_index=True)
signature = models.CharField(max_length=255, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expires_at = models.DateTimeField(null=True)
def __unicode__(self):
return unicode('%s | %s | %s ' % (
self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
self.status,
self.signature
))
class Meta:
app_label = 'taskmonitor'
verbose_name_plural = 'Task statuses'
|
Change msgpack-python requirement to msgpack
This package has been renamed to `msgpack` starting with their `0.5.0` version. The old package seems likely to be deprecated soon, but this change will keep the dependency being updated as intended.
https://pypi.python.org/pypi/msgpack
https://pypi.python.org/pypi/msgpack-python | import sys
from setuptools import setup
_requires = [
'msgpack',
]
if sys.version_info < (2, 7, 0, ) :
_requires.append('ordereddict', )
setup(
name='serf-python',
version='0.2.2',
description='serf client for python',
long_description="""
For more details, please see https://github.com/spikeekips/serf-python .
""",
author='Spike^ekipS',
author_email='spikeekips@gmail.com',
url='https://github.com/spikeekips/serf-python',
license='License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
install_requires=tuple(_requires, ),
packages=('serf', ),
package_dir={'': 'src', },
)
| import sys
from setuptools import setup
_requires = [
'msgpack-python',
]
if sys.version_info < (2, 7, 0, ) :
_requires.append('ordereddict', )
setup(
name='serf-python',
version='0.2.2',
description='serf client for python',
long_description="""
For more details, please see https://github.com/spikeekips/serf-python .
""",
author='Spike^ekipS',
author_email='spikeekips@gmail.com',
url='https://github.com/spikeekips/serf-python',
license='License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
install_requires=tuple(_requires, ),
packages=('serf', ),
package_dir={'': 'src', },
)
|
Use separate component for TexMath, so model changes lead to a rerender. | import { NodeComponent } from 'substance'
import katex from 'katex'
export default class InlineFormulaComponent extends NodeComponent {
render($$) {
const node = this.props.node
// TODO: Find out why node.find('tex-math') returns null here
const texMath = node.findChild('tex-math')
const el = $$('span').addClass('sc-inline-formula')
el.append(
$$(TexMathComponent, {
node: texMath
})
)
if (this.props.isolatedNodeState) {
el.addClass('sm-'+this.props.isolatedNodeState)
}
return el
}
}
class TexMathComponent extends NodeComponent {
render($$) {
const node = this.props.node
const texMath = node.textContent
const el = $$('span').addClass('sc-math')
try {
el.append(
$$('span').html(katex.renderToString(texMath))
)
let blockerEl = $$('div').addClass('se-blocker')
el.append(blockerEl)
} catch (error) {
el.addClass('sm-error')
.text(error.message)
}
return el
}
}
| import { NodeComponent } from 'substance'
import katex from 'katex'
export default class InlineFormulaComponent extends NodeComponent {
render($$) {
const node = this.props.node
// TODO: Find out why node.find('tex-math') returns null here
const texMath = node.findChild('tex-math').textContent
// TODO: Use KaTeX
const el = $$('span').addClass('sc-math')
if (this.props.isolatedNodeState) {
el.addClass('sm-'+this.props.isolatedNodeState)
}
try {
el.append(
$$('span').html(katex.renderToString(texMath))
)
let blockerEl = $$('div').addClass('se-blocker')
el.append(blockerEl)
} catch (error) {
el.addClass('sm-error')
.text(error.message)
}
return el
}
}
|
Update broken link to DS.attr docs
Closes #5816 | import { isNone as none } from '@ember/utils';
import Transform from './transform';
/**
The `DS.StringTransform` class is used to serialize and deserialize
string attributes on Ember Data record objects. This transform is
used when `string` is passed as the type parameter to the
[DS.attr](./DS/methods/attr?anchor=attr) function.
Usage
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
isAdmin: DS.attr('boolean'),
name: DS.attr('string'),
email: DS.attr('string')
});
```
@class StringTransform
@extends DS.Transform
@namespace DS
*/
export default Transform.extend({
deserialize(serialized) {
return none(serialized) ? null : String(serialized);
},
serialize(deserialized) {
return none(deserialized) ? null : String(deserialized);
},
});
| import { isNone as none } from '@ember/utils';
import Transform from './transform';
/**
The `DS.StringTransform` class is used to serialize and deserialize
string attributes on Ember Data record objects. This transform is
used when `string` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
isAdmin: DS.attr('boolean'),
name: DS.attr('string'),
email: DS.attr('string')
});
```
@class StringTransform
@extends DS.Transform
@namespace DS
*/
export default Transform.extend({
deserialize(serialized) {
return none(serialized) ? null : String(serialized);
},
serialize(deserialized) {
return none(deserialized) ? null : String(deserialized);
},
});
|
Allow double quotes to avoid escaping single quotes | import path from 'path';
import {CLIEngine, linter} from 'eslint';
import PackageJson from '../lib/package_json';
const project = PackageJson.load();
const baseConfig = linter.defaults();
const options = {
baseConfig: Object.assign(baseConfig, {
parser: 'babel-eslint',
env: Object.assign(baseConfig.env, {
es6: true,
browser: true,
node: true,
jasmine: project.dependsOn(/jasmine/)
}),
ecmaFeatures: Object.assign(baseConfig.ecmaFeatures, {
modules: true
}),
rules: Object.assign(baseConfig.rules, {
strict: 0,
quotes: [2, 'single', 'avoid-escape'],
'no-process-exit': 0
})
}),
ignorePath: path.resolve('.gitignore')
};
const cli = new CLIEngine(options);
const formatter = cli.getFormatter();
const report = cli.executeOnFiles(['.']);
if (report.errorCount > 0) {
process.stderr.write(formatter(report.results));
process.exit(1);
}
| import path from 'path';
import {CLIEngine, linter} from 'eslint';
import PackageJson from '../lib/package_json';
const project = PackageJson.load();
const baseConfig = linter.defaults();
const options = {
baseConfig: Object.assign(baseConfig, {
parser: 'babel-eslint',
env: Object.assign(baseConfig.env, {
es6: true,
browser: true,
node: true,
jasmine: project.dependsOn(/jasmine/)
}),
ecmaFeatures: Object.assign(baseConfig.ecmaFeatures, {
modules: true
}),
rules: Object.assign(baseConfig.rules, {
strict: 0,
quotes: [2, 'single'],
'no-process-exit': 0
})
}),
ignorePath: path.resolve('.gitignore')
};
const cli = new CLIEngine(options);
const formatter = cli.getFormatter();
const report = cli.executeOnFiles(['.']);
if (report.errorCount > 0) {
process.stderr.write(formatter(report.results));
process.exit(1);
}
|
Fix async test - return the promise | /*
* Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* 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.
*/
/* eslint-env mocha */
'use strict';
const thymeleaf = require('../lib/thymeleaf');
const {areSerializedDocumentsEqual} = require('../lib/utilities/Dom');
const {assert} = require('chai');
const fs = require('fs');
const path = require('path');
/**
* Tests for the Thymeleaf processing functions.
*/
describe('Thymeleaf', function() {
it('Process a template without any processors', function() {
let templatePath = path.join(__dirname, 'template.html');
return thymeleaf.processFile(templatePath, {
title: 'Hello!'
})
.then(template => {
let templateFromFile = fs.readFileSync(templatePath).toString();
assert.isTrue(areSerializedDocumentsEqual(template, templateFromFile));
});
});
});
| /*
* Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* 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.
*/
/* eslint-env mocha */
'use strict';
const thymeleaf = require('../lib/thymeleaf');
const {areSerializedDocumentsEqual} = require('../lib/utilities/Dom');
const {assert} = require('chai');
const fs = require('fs');
const path = require('path');
/**
* Tests for the Thymeleaf processing functions.
*/
describe('Thymeleaf', function() {
it('Process a template without any processors', function(done) {
let templatePath = path.join(__dirname, 'template.html');
thymeleaf.processFile(templatePath, {
title: 'Hello!'
})
.then(template => {
let templateFromFile = fs.readFileSync(templatePath).toString();
assert.isTrue(areSerializedDocumentsEqual(template, templateFromFile));
done();
})
.catch(error => {
assert.fail();
done();
});
});
});
|
Correct types on the error toaster
Bug:
This copy was hardcoded to just 'comment' but the action applies to both
comments and posts. When something went wrong on a post upvote we'd show
"failed to upvote the comment", which makes no sense.
Fix:
Use the `type` (which is either 'post' or 'comment') in the copy. | import { models, errors } from '@r/api-client';
import * as platformActions from '@r/platform/actions';
import { apiOptionsFromState } from 'lib/apiOptionsFromState';
import { LOGGEDOUT_REDIRECT } from 'app/constants';
const { ResponseError } = errors;
export const PENDING = 'VOTE__PENDING';
export const SUCCESS = 'VOTE__SUCCESS';
export const FAILURE = 'VOTE__FAILURE';
export const pending = (id, model) => ({ type: PENDING, id, model });
export const success = (id, model) => ({ type: SUCCESS, id, model });
export const failure = (direction, type) => {
const voteWord = direction === 1 ? 'upvote' : 'downvote';
return {
type: FAILURE,
message: `Failed to ${voteWord} the ${type}.`,
};
};
export const vote = (id, direction) => async (dispatch, getState) => {
const state = getState();
if (!state.session.isValid) {
dispatch(platformActions.setPage(LOGGEDOUT_REDIRECT));
return;
}
const type = models.ModelTypes.thingType(id);
const thing = state[`${type}s`][id];
const stub = thing._vote(apiOptionsFromState(state), direction);
dispatch(pending(id, stub));
try {
const model = await stub.promise();
dispatch(success(id, model));
} catch (e) {
dispatch(failure(direction, type));
if (!(e instanceof ResponseError)) {
throw e;
}
}
};
| import { models, errors } from '@r/api-client';
import * as platformActions from '@r/platform/actions';
import { apiOptionsFromState } from 'lib/apiOptionsFromState';
import { LOGGEDOUT_REDIRECT } from 'app/constants';
const { ResponseError } = errors;
export const PENDING = 'VOTE__PENDING';
export const SUCCESS = 'VOTE__SUCCESS';
export const FAILURE = 'VOTE__FAILURE';
export const pending = (id, model) => ({ type: PENDING, id, model });
export const success = (id, model) => ({ type: SUCCESS, id, model });
export const failure = direction => {
const voteWord = direction === 1 ? 'upvote' : 'downvote';
return {
type: FAILURE,
message: `Failed to ${voteWord} the comment.`,
};
};
export const vote = (id, direction) => async (dispatch, getState) => {
const state = getState();
if (!state.session.isValid) {
dispatch(platformActions.setPage(LOGGEDOUT_REDIRECT));
return;
}
const type = models.ModelTypes.thingType(id);
const thing = state[`${type}s`][id];
const stub = thing._vote(apiOptionsFromState(state), direction);
dispatch(pending(id, stub));
try {
const model = await stub.promise();
dispatch(success(id, model));
} catch (e) {
dispatch(failure(direction));
if (!(e instanceof ResponseError)) {
throw e;
}
}
};
|
Add start dates to Semester Types | package at.ac.tuwien.inso.entity;
public enum SemesterType {
WinterSemester("WS", 10, 1),
SummerSemester("SS", 3, 1);
/**
* Name of the semester: WS or SS
*/
private final String name;
/**
* Month the semester starts
*/
private final int startMonth;
/**
* Day in month the semester starts
*/
private final int startDay;
SemesterType(String name, int startMonth, int startDay) {
this.name = name;
this.startMonth = startMonth;
this.startDay = startDay;
}
public int getStartMonth() {
return startMonth;
}
public int getStartDay() {
return startDay;
}
@Override
public String toString() {
return name;
}
/**
* Reverse of toString
*/
public static SemesterType fromString(String name) {
for (SemesterType type : SemesterType.values()) {
if (type.toString().equals(name)) {
return type;
}
}
throw new IllegalArgumentException("Type '" + name + "' is not a valid SemesterType");
}
}
| package at.ac.tuwien.inso.entity;
public enum SemesterType {
WinterSemester("WS"),
SummerSemester("SS");
private final String name;
SemesterType(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
/**
* Reverse of toString
*/
public static SemesterType fromString(String name) {
for (SemesterType type : SemesterType.values()) {
if (type.toString().equals(name)) {
return type;
}
}
throw new IllegalArgumentException("Type '" + name + "' is not a valid SemesterType");
}
}
|
Enhance readability of time out command test | package name.webdizz.fault.tolerance.inventory.client.command;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static name.webdizz.fault.tolerance.inventory.client.InventoryApiTestConstants.DEFAULT_PRODUCT;
import static name.webdizz.fault.tolerance.inventory.client.InventoryApiTestConstants.DEFAULT_STORE;
import static name.webdizz.fault.tolerance.inventory.client.InventoryApiTestConstants.INVENTORY_SERVICE_URL;
import org.junit.Test;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
public class TimeOutInventoryRequestCommandTest {
private static final int TIMEOUT_IN_MILLIS = 10;
private InventoryRequester inventoryRequester = new InventoryRequester(INVENTORY_SERVICE_URL);
private final boolean timedOut = true;
@Test
public void shouldNotCompleteInventoryRequestDueToTimeout() {
TimeOutInventoryRequestCommand timeOutInventoryRequestCommand;
timeOutInventoryRequestCommand = new TimeOutInventoryRequestCommand(inventoryRequester, DEFAULT_STORE, DEFAULT_PRODUCT, TIMEOUT_IN_MILLIS);
boolean request = timeOutInventoryRequestCommand.isResponseTimedOut();
assertThat(request, is(timedOut));
}
} | package name.webdizz.fault.tolerance.inventory.client.command;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static name.webdizz.fault.tolerance.inventory.client.InventoryApiTestConstants.DEFAULT_PRODUCT;
import static name.webdizz.fault.tolerance.inventory.client.InventoryApiTestConstants.DEFAULT_STORE;
import static name.webdizz.fault.tolerance.inventory.client.InventoryApiTestConstants.INVENTORY_SERVICE_URL;
import org.junit.Test;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
import name.webdizz.fault.tolerance.inventory.domain.Inventory;
public class TimeOutInventoryRequestCommandTest {
private static final int TIMEOUT_IN_MILLIS = 10;
private InventoryRequester inventoryRequester = new InventoryRequester(INVENTORY_SERVICE_URL);
@Test
public void shouldNotCompleteInventoryRequestDueToTimeout() {
TimeOutInventoryRequestCommand timeOutInventoryRequestCommand;
timeOutInventoryRequestCommand = new TimeOutInventoryRequestCommand(inventoryRequester, DEFAULT_STORE, DEFAULT_PRODUCT, TIMEOUT_IN_MILLIS);
Inventory inventory = timeOutInventoryRequestCommand.execute();
assertThat(timeOutInventoryRequestCommand.isResponseTimedOut(), is(true));
}
} |
Update testing request sheet in debug mode | import logging
import os
from .test_settings import *
try:
import debug_panel
except ImportError:
# no debug panel, no use trying to add it to our middleware
pass
else:
# if debug_panel exists, add it to our INSTALLED_APPS
INSTALLED_APPS += ('debug_panel', 'debug_toolbar', 'pympler')
MIDDLEWARE_CLASSES += ('debug_panel.middleware.DebugPanelMiddleware',)
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': lambda x: True,
}
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]
# GOOGLE DRIVE SETTINGS
GOOGLE_STORAGE_REQUEST_SHEET = "16X6zcFK8FS5t5tFaGpnxbWnWTXP88h4ccpSpPbyLeA8"
| import logging
import os
from .test_settings import *
try:
import debug_panel
except ImportError:
# no debug panel, no use trying to add it to our middleware
pass
else:
# if debug_panel exists, add it to our INSTALLED_APPS
INSTALLED_APPS += ('debug_panel', 'debug_toolbar', 'pympler')
MIDDLEWARE_CLASSES += ('debug_panel.middleware.DebugPanelMiddleware',)
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': lambda x: True,
}
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]
|
Add proper Python version classifiers. | # -*- coding: utf-8 -*-
VERSION = '0.2'
from setuptools import setup
setup(
name='nutshell',
packages=["nutshell"],
version=VERSION,
description='A minimal python library to access Nutshell CRM:s JSON-RPC API.',
author=u'Emil Stenström',
author_email='em@kth.se',
url='https://github.com/EmilStenstrom/python-nutshell',
download_url='https://github.com/EmilStenstrom/python-nutshell/tarball/' + VERSION,
install_requires=["requests>=2.9.1", "six>=1.10.0"],
tests_require=["mock>=1.0.1", "nose>=1.3.7"],
test_suite="nose.collector",
keywords=['nutshell', 'nutshell-crm', 'json-rpc'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Operating System :: OS Independent",
])
| # -*- coding: utf-8 -*-
VERSION = '0.2'
from setuptools import setup
setup(
name='nutshell',
packages=["nutshell"],
version=VERSION,
description='A minimal python library to access Nutshell CRM:s JSON-RPC API.',
author=u'Emil Stenström',
author_email='em@kth.se',
url='https://github.com/EmilStenstrom/python-nutshell',
download_url='https://github.com/EmilStenstrom/python-nutshell/tarball/' + VERSION,
install_requires=["requests>=2.9.1", "six>=1.10.0"],
tests_require=["mock>=1.0.1", "nose>=1.3.7"],
test_suite="nose.collector",
keywords=['nutshell', 'nutshell-crm', 'json-rpc'],
classifiers=[],
)
|
Make sure that the Imgur ID can be correctly extracted from the URL
This was made to address the case where the URL might end with '/' | import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url
if '?' in url:
url = url[:url.rfind('?')]
if url.endswith("/"):
url = url[:-1]
return url
def limit_file_name(file_name, length=65):
if len(file_name) <= length:
return file_name
else:
extension = file_name[file_name.rfind("."):]
file_name = file_name[:length - len(extension)] + extension
LOGGER.debug("Will have to limit the file name %s as it exceeds %i" % (file_name, length))
return file_name
| import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url
if '?' in url:
url = url[:url.rfind('?')]
return url
def limit_file_name(file_name, length=65):
if len(file_name) <= length:
return file_name
else:
extension = file_name[file_name.rfind("."):]
file_name = file_name[:length - len(extension)] + extension
LOGGER.debug("Will have to limit the file name %s as it exceeds %i" % (file_name, length))
return file_name
|
[Telemetry] Disable flaky MSR power monitor unit test.
BUG=chromium:712486
Review-Url: https://codereview.chromium.org/2827723002 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
import unittest
from telemetry import decorators
from telemetry.internal.platform.power_monitor import msr_power_monitor
from telemetry.internal.platform import win_platform_backend
class MsrPowerMonitorTest(unittest.TestCase):
@decorators.Disabled('all') # http://crbug.com/712486
#@decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337
def testMsrRuns(self):
platform_backend = win_platform_backend.WinPlatformBackend()
power_monitor = msr_power_monitor.MsrPowerMonitorWin(platform_backend)
if not power_monitor.CanMonitorPower():
logging.warning('Test not supported on this platform.')
return
power_monitor.StartMonitoringPower(None)
time.sleep(0.01)
statistics = power_monitor.StopMonitoringPower()
self.assertEqual(statistics['identifier'], 'msr')
self.assertIn('energy_consumption_mwh', statistics)
self.assertGreater(statistics['energy_consumption_mwh'], 0)
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
import unittest
from telemetry import decorators
from telemetry.internal.platform.power_monitor import msr_power_monitor
from telemetry.internal.platform import win_platform_backend
class MsrPowerMonitorTest(unittest.TestCase):
@decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337
def testMsrRuns(self):
platform_backend = win_platform_backend.WinPlatformBackend()
power_monitor = msr_power_monitor.MsrPowerMonitorWin(platform_backend)
if not power_monitor.CanMonitorPower():
logging.warning('Test not supported on this platform.')
return
power_monitor.StartMonitoringPower(None)
time.sleep(0.01)
statistics = power_monitor.StopMonitoringPower()
self.assertEqual(statistics['identifier'], 'msr')
self.assertIn('energy_consumption_mwh', statistics)
self.assertGreater(statistics['energy_consumption_mwh'], 0)
|
Use fixed queries for population script | <?php
include_once '../../config/config-local.php';
include_once '../../models/database.php';
include_once '../../models/db.php';
include_once 'countries_array.php';
$countries = getCountries();
$array = array();
$count = 0;
$keys = array_keys( $countries );
foreach ( $keys as $key ) {
$value = $countries[ $key ];
$res = db_insert( 'countries', array( 'id' => NULL, 'country' => $value, 'shortname' => $key ) );
if ( $res === false ) {
die( "sql query died with the following error\n\"" . mysql_error() );
}
++$count;
}
echo "You imported $count raws in the table 'countries'.";
?>
| <?php
include_once '../../config/config-local.php';
include_once '../../models/database.php';
include_once 'countries_array.php';
$array = array();
$count = 0;
$keys = array_keys( $countries );
foreach ( $keys as $key ) {
$value = $countries[ $key ];
$array[] = "INSERT INTO
`countries` (`id`, `country`, `shortname`)
VALUES
(NULL, '$value', '$key');";
}
foreach( $array as $sql ) {
$res = mysql_query( $sql );
if ( $res === false ) {
die( "sql query died with the following error\n\"" . mysql_error() );
}
++$count;
}
echo "You imported $count raws in the table 'countries'.";
?>
|
Allow real <= and >= in LateX | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For
# a full list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
#
# To see the default sample conf.py, run sphinx-quickstart in an empty
# directory. Most of the original comments and options were removed.
import sphinx_rtd_theme # noQA F401
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
project = 'QPDF'
copyright = '2005-2021, Jay Berkenbilt'
author = 'Jay Berkenbilt'
# make_dist and the CI build lexically find the release version from this file.
release = '10.5.0'
version = release
extensions = [
'sphinx_rtd_theme',
'qpdf',
]
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
"body_max_width": None,
}
html_logo = '../logo/qpdf.svg'
html_static_path = ['_static']
html_css_files = [
'css/wraptable.css',
]
latex_elements = {
'preamble': r'''
\sphinxDUC{2264}{$\leq$}
\sphinxDUC{2265}{$\geq$}
''',
}
highlight_language = 'none'
| # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For
# a full list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
#
# To see the default sample conf.py, run sphinx-quickstart in an empty
# directory. Most of the original comments and options were removed.
import sphinx_rtd_theme # noQA F401
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
project = 'QPDF'
copyright = '2005-2021, Jay Berkenbilt'
author = 'Jay Berkenbilt'
# make_dist and the CI build lexically find the release version from this file.
release = '10.5.0'
version = release
extensions = [
'sphinx_rtd_theme',
'qpdf',
]
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
"body_max_width": None,
}
html_logo = '../logo/qpdf.svg'
html_static_path = ['_static']
html_css_files = [
'css/wraptable.css',
]
highlight_language = 'none'
|
Disable Encoding not specified inspection in console. | package com.jetbrains.python.console;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.inspections.*;
import com.jetbrains.python.validation.DocStringAnnotator;
import org.jetbrains.annotations.NotNull;
/**
* User : catherine
*
* filter out some python inspections and annotations if we're in console
*/
public class ConsoleVisitorFilter implements PythonVisitorFilter {
@Override
public boolean isSupported(@NotNull final Class visitorClass, @NotNull final PsiFile file) {
//if we're in console
if (PydevConsoleRunner.isInPydevConsole(file)) {
//inspections
if (visitorClass == PyUnusedLocalInspection.class || visitorClass == PyUnboundLocalVariableInspection.class ||
visitorClass == PyStatementEffectInspection.class || visitorClass == PySingleQuotedDocstringInspection.class ||
visitorClass == PyDocstringInspection.class || visitorClass == PyMandatoryEncodingInspection.class) {
return false;
}
//annotators
if (visitorClass == DocStringAnnotator.class) {
return false;
}
}
return true;
}
}
| package com.jetbrains.python.console;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.inspections.*;
import com.jetbrains.python.validation.DocStringAnnotator;
import org.jetbrains.annotations.NotNull;
/**
* User : catherine
*
* filter out some python inspections and annotations if we're in console
*/
public class ConsoleVisitorFilter implements PythonVisitorFilter {
@Override
public boolean isSupported(@NotNull final Class visitorClass, @NotNull final PsiFile file) {
//if we're in console
if (PydevConsoleRunner.isInPydevConsole(file)) {
//inspections
if (visitorClass == PyUnusedLocalInspection.class || visitorClass == PyUnboundLocalVariableInspection.class ||
visitorClass == PyStatementEffectInspection.class || visitorClass == PySingleQuotedDocstringInspection.class ||
visitorClass == PyDocstringInspection.class) {
return false;
}
//annotators
if (visitorClass == DocStringAnnotator.class) {
return false;
}
}
return true;
}
}
|
Change legacy to use Symfony session and set username to session | <?php
function StartSession($name) {
global $user_id;
$user_id = 1;
$session = $GLOBALS['container']->get('session');
$session->set('user_id', $user_id);
$session->set('username', 'admin');
}
function get_body($path) {
global $basePath;
return '<img src="' . $basePath . 'images/legacy.jpg"/><br>'
. 'Image by order_242 <a href="https://www.flickr.com/photos/juanelo242a/15393888991" target="_blank">www.flickr.com/photos/juanelo242a/15393888991</a>';
}
function get_heading($path) {
return '';
}
function get_menu($path) {
global $baseUrl;
$router = $GLOBALS['container']->get('router');
return '<ul>
<li><a href="' . $baseUrl . 'home.html">Home</a></li>
<li><a href="' . $baseUrl . 'user.html">User</a></li>
<li><a href="' . $baseUrl . 'dirs.html">Dir structure</a></li>
<li><a href="' . $router->generate('_demo') . '">Demo Home</a></li>
</ul>';
}
function isAdmin() {
global $user_id;
return Info::getUsername($user_id) == 'admin';
}
function noAccess() {
die('<p style="color: #f00">Access denied</p>');
}
| <?php
function StartSession($name) {
global $user_id;
$user_id = 1;
session_name($name);
session_start();
}
function get_body($path) {
global $basePath;
return '<img src="' . $basePath . 'images/legacy.jpg"/><br>'
. 'Image by order_242 <a href="https://www.flickr.com/photos/juanelo242a/15393888991" target="_blank">www.flickr.com/photos/juanelo242a/15393888991</a>';
}
function get_heading($path) {
return '';
}
function get_menu($path) {
global $baseUrl;
$router = $GLOBALS['container']->get('router');
return '<ul>
<li><a href="' . $baseUrl . 'home.html">Home</a></li>
<li><a href="' . $baseUrl . 'user.html">User</a></li>
<li><a href="' . $baseUrl . 'dirs.html">Dir structure</a></li>
<li><a href="' . $router->generate('_demo') . '">Demo Home</a></li>
</ul>';
}
function isAdmin() {
global $user_id;
return Info::getUsername($user_id) == 'admin';
}
function noAccess() {
die('<p style="color: #f00">Access denied</p>');
}
|
Print actual port number in server init log | 'use strict';
/**
* Imports.
*/
const express = require('express');
const http = require('http');
/**
* Initialize Express.
*/
const app = express();
// Setup locals variable in config/index.js.
app.locals = require('./config');
// Configure express app based on local configuration.
app.set('env', app.locals.express.env);
/**
* Routing.
*/
// Root:
app.get('/', (req, res) => {
res.send('Hi, I\'m Blink!');
});
// Api root:
app.use('/api', require('./api'));
// API Version 1
app.use('/api/v1', require('./api/v1'));
/**
* Create server.
*/
const server = http.createServer(app);
server.listen(app.locals.express.port, () => {
const address = server.address();
app.locals.logger.info(`Blink is listening on port:${address.port} env:${app.locals.express.env}`);
});
module.exports = app;
| 'use strict';
/**
* Imports.
*/
const express = require('express');
/**
* Initialize Express.
*/
const app = express();
// Setup locals variable in config/index.js.
app.locals = require('./config');
// Configure express app based on local configuration.
app.set('env', app.locals.express.env);
/**
* Routing.
*/
// Root:
app.get('/', (req, res) => {
res.send('Hi, I\'m Blink!');
});
// Api root:
app.use('/api', require('./api'));
// API Version 1
app.use('/api/v1', require('./api/v1'));
/**
* Listen.
*/
app.listen(app.locals.express.port, () => {
app.locals.logger.info(`Blink is listening on port:${app.locals.express.port} env:${app.get('env')}`);
});
module.exports = app;
|
Bring google syncs back online | module.exports = {
port: 8001,
//cdns: ['bootstrap', 'cdnjs', 'google', 'jsdelivr', 'jquery'],
cdns: ['bootstrap-cdn', 'jsdelivr', 'cdnjs', 'google'],
//cdns: ['bootstrap-cdn', 'jsdelivr', 'cdnjs'],
//cdns: ['bootstrap','google'],
db: 'db',
cdnCollections: [
{name: 'bootstrap-cdn', aliases: ['bootstrap']},
{name: 'jsdelivr', aliases: ['jsdelivr']},
{name: 'cdnjs', aliases: ['cdnjs']},
{name: 'google', aliases: ['google']}
],
etagsCollection: 'etagsCollection',
syncUrl: 'http://localhost:8000/data/',
//syncUrl: 'http://jsdelivrapi-sync.aws.af.cm/data/',
tasks: {
sync: {minute: 5}
},
maxcdn: {
alias: 'replace this',
key: 'replace this',
secret: 'replace this',
zoneId: 0 // replace with some zone id
},
github: '' // replace with github token
};
| module.exports = {
port: 8001,
//cdns: ['bootstrap', 'cdnjs', 'google', 'jsdelivr', 'jquery'],
//cdns: ['bootstrap-cdn', 'jsdelivr', 'cdnjs', 'google'],
cdns: ['bootstrap-cdn', 'jsdelivr', 'cdnjs'],
//cdns: ['bootstrap','google'],
db: 'db',
cdnCollections: [
{name: 'bootstrap-cdn', aliases: ['bootstrap']},
{name: 'jsdelivr', aliases: ['jsdelivr']},
{name: 'cdnjs', aliases: ['cdnjs']},
//{name: 'google', aliases: ['google']}
],
etagsCollection: 'etagsCollection',
syncUrl: 'http://localhost:8000/data/',
//syncUrl: 'http://jsdelivrapi-sync.aws.af.cm/data/',
tasks: {
sync: {minute: 5}
},
maxcdn: {
alias: 'replace this',
key: 'replace this',
secret: 'replace this',
zoneId: 0 // replace with some zone id
},
github: '' // replace with github token
};
|
Update pypi description and release new version | """
==============
PiPocketGeiger
==============
Radiation Watch Pocket Geiger Type 5 library for Raspberry Pi.
Usage
=====
::
from PiPocketGeiger import RadiationWatch
import time
with RadiationWatch(24, 23) as radiationWatch:
while 1:
print(radiationWatch.status())
time.sleep(5)
See GitHub repository for complete documentation.
"""
import re
import ast
from setuptools import setup
setup(
name='PiPocketGeiger',
version='0.1a',
url='https://github.com/MonsieurV/PiPocketGeiger',
license='MIT',
author='Yoan Tournade',
author_email='yoan@ytotech.com',
description='A library for monitoring radiation with the Radiation Watch '
'Pocket Geiger.',
long_description=__doc__,
packages=['PiPocketGeiger'],
include_package_data=True,
zip_safe=True,
platforms='any',
install_requires=[
'RPi.GPIO>=0.5.0a',
]
)
| """
PiPocketGeiger
-----
Radiation Watch Pocket Geiger Type 5 library for Raspberry Pi.
Links
`````
* `code and documentation <https://github.com/MonsieurV/PiPocketGeiger>`_
"""
import re
import ast
from setuptools import setup
setup(
name='PiPocketGeiger',
version=0.1,
url='https://github.com/MonsieurV/PiPocketGeiger',
license='MIT',
author='Yoan Tournade',
author_email='yoan@ytotech.com',
description='A library for monitoring radiation with the Radiation Watch '
'Pocket Geiger.',
long_description=__doc__,
packages=['PiPocketGeiger'],
include_package_data=True,
zip_safe=True,
platforms='any',
install_requires=[
'RPi.GPIO>=0.5.0a',
]
)
|
Check for amount of li's |
"use strict";
describe('Footer component', () => {
let element = undefined;
let $rootScope = undefined;
let $compile = undefined;
let mod = angular.module('tests.footer', []).service('Authentication', function () {
this.check = false;
this.attempt = credentials => {
if (credentials.username == 'test' && credentials.password == 'test') {
this.check = true;
}
};
this.status = () => this.check;
});
beforeEach(angular.mock.module(mod.name));
beforeEach(inject((_$rootScope_, _$compile_) => {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
describe('Footer while not logged in', () => {
it('should only display one li', () => {
let tpl = angular.element('<monad-footer></monad-footer>');
element = $compile(tpl)($rootScope);
$rootScope.$digest();
expect(element.find('li').length).toBe(1);
});
});
});
|
"use strict";
describe('Footer component', () => {
let element = undefined;
let $rootScope = undefined;
let $compile = undefined;
let mod = angular.module('tests.footer', []).service('Authentication', function () {
this.check = false;
this.attempt = credentials => {
if (credentials.username == 'test' && credentials.password == 'test') {
this.check = true;
}
};
this.status = () => this.check;
});
beforeEach(angular.mock.module(mod.name));
beforeEach(inject((_$rootScope_, _$compile_) => {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
describe('Footer while not logged in', () => {
it('should not display a logout button', () => {
let tpl = angular.element('<monad-footer></monad-footer>');
element = $compile(tpl)($rootScope);
$rootScope.$digest();
expect(element.find('#logout').length).toBe(0);
});
});
});
|
Use a relative path to fetch the data.json file | import { h, render, Component } from 'preact';
import lunr from 'lunr';
import SearchForm from 'js/components/search-form';
import SearchResults from 'js/components/search-results';
export default class CheatSheet extends Component {
state = {
data: [],
results: []
}
search = (term) => {
let results = this.state.index.search(term).map(
(result) => this.state.data[result.ref]
);
this.setState({ ...this.state, results });
}
loadData() {
fetch('./data.json').then((response) => {
return response.text();
})
.then((rawData) => {
const data = JSON.parse(rawData);
const index = lunr(function() {
this.field('name', { boost: 10 });
this.field('tags', { boost: 15 });
this.field('description');
this.ref('id');
});
data.forEach((item, id) => index.add({ ...item, id }));
this.setState({ data, index });
this.search('color');
});
}
componentDidMount() {
this.loadData();
}
render({ }, { results }) {
return (
<div>
<SearchForm search={this.search} />
<SearchResults results={results} />
</div>
);
}
}
| import { h, render, Component } from 'preact';
import lunr from 'lunr';
import SearchForm from 'js/components/search-form';
import SearchResults from 'js/components/search-results';
export default class CheatSheet extends Component {
state = {
data: [],
results: []
}
search = (term) => {
let results = this.state.index.search(term).map(
(result) => this.state.data[result.ref]
);
this.setState({ ...this.state, results });
}
loadData() {
fetch('/data.json').then((response) => {
return response.text();
})
.then((rawData) => {
const data = JSON.parse(rawData);
const index = lunr(function() {
this.field('name', { boost: 10 });
this.field('tags', { boost: 15 });
this.field('description');
this.ref('id');
});
data.forEach((item, id) => index.add({ ...item, id }));
this.setState({ data, index });
this.search('color');
});
}
componentDidMount() {
this.loadData();
}
render({ }, { results }) {
return (
<div>
<SearchForm search={this.search} />
<SearchResults results={results} />
</div>
);
}
}
|
INFORCRM-15838: Change chart type to column to match 3.6 | import declare from 'dojo/_base/declare';
import lang from 'dojo/_base/lang';
import View from 'argos/View';
import _ChartMixin from './_ChartMixin';
/**
* @class crm.Views.Charts.GenericBar
*
* @extends argos.View
* @mixins crm.Views.Charts._ChartMixin
*
* @requires argos.View
*
*/
const __class = declare('crm.Views.Charts.GenericBar', [View, _ChartMixin], {
id: 'chart_generic_bar',
titleText: '',
expose: false,
chart: null,
formatter: function formatter(val) {
return val;
},
attributeMap: {
chartContent: {
node: 'contentNode',
type: 'innerHTML',
},
},
createChart: function createChart(rawData) {
this.inherited(arguments);
this.showSearchExpression();
const data = rawData.map((item) => {
return {
name: item.$descriptor,
value: item.value,
};
});
const chart = $(this.contentNode).chart({
type: 'column',
dataset: [{
data,
}],
showLegend: false,
xAxis: {
rotate: '-65',
},
});
this.chart = chart.data('chart');
},
});
lang.setObject('Mobile.SalesLogix.Views.Charts.GenericBar', __class);
export default __class;
| import declare from 'dojo/_base/declare';
import lang from 'dojo/_base/lang';
import View from 'argos/View';
import _ChartMixin from './_ChartMixin';
/**
* @class crm.Views.Charts.GenericBar
*
* @extends argos.View
* @mixins crm.Views.Charts._ChartMixin
*
* @requires argos.View
*
*/
const __class = declare('crm.Views.Charts.GenericBar', [View, _ChartMixin], {
id: 'chart_generic_bar',
titleText: '',
expose: false,
chart: null,
formatter: function formatter(val) {
return val;
},
attributeMap: {
chartContent: {
node: 'contentNode',
type: 'innerHTML',
},
},
createChart: function createChart(rawData) {
this.inherited(arguments);
this.showSearchExpression();
const data = rawData.map((item) => {
return {
name: item.$descriptor,
value: item.value,
};
});
const chart = $(this.contentNode).chart({
type: 'bar',
dataset: [{
data,
}],
showLegend: false,
});
this.chart = chart.data('chart');
},
});
lang.setObject('Mobile.SalesLogix.Views.Charts.GenericBar', __class);
export default __class;
|
Set more turns for testing. | package com.ibm.sk;
public class WorldConstans {
public static final int X_BOUNDRY = 15;
public static final int Y_BOUNDRY = 10;
/**
* number of TURNS to evaluate game.
*/
public static final int TURNS = 500;
/**
* the amount of ants in one anthill at the beginning of the world.
*/
public static final int INITIAL_ANT_COUNT = 5;
/**
* frequency of food adding.
*/
public static final int FOOD_REFILL_FREQUENCY = 5;
/**
* number of ants in the hill at the beginning of the game.
*/
public static final int ANTS_START_POPULATION = 5;
public static final double POPULATION_WAR_FACTOR = 2.0 / 5.0;
/**
* File where to serialize the world per step.
*/
public static final String FILE_NAME = "traciking.ser";
} | package com.ibm.sk;
public class WorldConstans {
public static final int X_BOUNDRY = 15;
public static final int Y_BOUNDRY = 10;
/**
* number of TURNS to evaluate game.
*/
public static final int TURNS = 50;
/**
* the amount of ants in one anthill at the beginning of the world.
*/
public static final int INITIAL_ANT_COUNT = 5;
/**
* frequency of food adding.
*/
public static final int FOOD_REFILL_FREQUENCY = 5;
/**
* number of ants in the hill at the beginning of the game.
*/
public static final int ANTS_START_POPULATION = 5;
public static final double POPULATION_WAR_FACTOR = 2.0 / 5.0;
/**
* File where to serialize the world per step.
*/
public static final String FILE_NAME = "traciking.ser";
} |
Remove redundant exception handling in exportCollection | const { search, exportSearch } = require('../services')
const { transformApiResponseToSearchCollection } = require('../transformers')
function getCollection (searchEntity, entityDetails, ...itemTransformers) {
return async function (req, res, next) {
try {
res.locals.results = await search({
searchEntity,
requestBody: req.body,
token: req.session.token,
page: req.query.page,
isAggregation: false,
}).then(transformApiResponseToSearchCollection({ query: req.query }, entityDetails, ...itemTransformers))
next()
} catch (error) {
next(error)
}
}
}
function exportCollection (searchEntity) {
return async function (req, res, next) {
return exportSearch({
searchEntity,
requestBody: req.body,
token: req.session.token,
}).then(apiReq => {
return apiReq.pipe(res)
}).catch(error => {
return next(error)
})
}
}
module.exports = {
exportCollection,
getCollection,
}
| const { search, exportSearch } = require('../services')
const { transformApiResponseToSearchCollection } = require('../transformers')
function getCollection (searchEntity, entityDetails, ...itemTransformers) {
return async function (req, res, next) {
try {
res.locals.results = await search({
searchEntity,
requestBody: req.body,
token: req.session.token,
page: req.query.page,
isAggregation: false,
}).then(transformApiResponseToSearchCollection({ query: req.query }, entityDetails, ...itemTransformers))
next()
} catch (error) {
next(error)
}
}
}
function exportCollection (searchEntity) {
return async function (req, res, next) {
try {
exportSearch({
searchEntity,
requestBody: req.body,
token: req.session.token,
}).then(apiReq => {
return apiReq.pipe(res)
}).catch(error => {
return next(error)
})
} catch (error) {
next(error)
}
}
}
module.exports = {
exportCollection,
getCollection,
}
|
Set correct service type for light bulb service | package service
import(
"github.com/brutella/hap/model/characteristic"
)
type LightBulb struct {
*Service
On *characteristic.On
Name *characteristic.Name
Brightness *characteristic.Brightness
Saturation *characteristic.Saturation
Hue *characteristic.Hue
}
func NewLightBulb(name string, on bool) *LightBulb {
on_char := characteristic.NewOn(on)
name_char := characteristic.NewName(name)
brightness := characteristic.NewBrightness(100) // 100%
saturation := characteristic.NewSaturation(0.0)
hue := characteristic.NewHue(0.0)
service := NewService()
service.Type = TypeLightBulb
service.AddCharacteristic(on_char.Characteristic)
service.AddCharacteristic(name_char.Characteristic)
service.AddCharacteristic(brightness.Characteristic)
service.AddCharacteristic(saturation.Characteristic)
service.AddCharacteristic(hue.Characteristic)
return &LightBulb{service, on_char, name_char, brightness, saturation, hue}
} | package service
import(
"github.com/brutella/hap/model/characteristic"
)
type LightBulb struct {
*Service
On *characteristic.On
Name *characteristic.Name
Brightness *characteristic.Brightness
Saturation *characteristic.Saturation
Hue *characteristic.Hue
}
func NewLightBulb(name string, on bool) *LightBulb {
on_char := characteristic.NewOn(on)
name_char := characteristic.NewName(name)
brightness := characteristic.NewBrightness(100) // 100%
saturation := characteristic.NewSaturation(0.0)
hue := characteristic.NewHue(0.0)
service := NewService()
service.Type = TypeSwitch
service.AddCharacteristic(on_char.Characteristic)
service.AddCharacteristic(name_char.Characteristic)
service.AddCharacteristic(brightness.Characteristic)
service.AddCharacteristic(saturation.Characteristic)
service.AddCharacteristic(hue.Characteristic)
return &LightBulb{service, on_char, name_char, brightness, saturation, hue}
} |
Clean up exception handler. Add new ignores. | <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\Access\UnauthorizedException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
HttpException::class,
ModelNotFoundException::class,
UnauthorizedException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Throwable $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
| <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
HttpException::class,
ModelNotFoundException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Throwable $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
return parent::render($request, $e);
}
}
|
Add some test card numbers. | import React, { Component } from 'react';
import { faintBlack, cyan500 } from 'material-ui/styles/colors';
import MenuItem from 'material-ui/MenuItem';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton/IconButton';
import ActionHelpOutline from 'material-ui/svg-icons/action/help-outline';
const TEST_CARD_NUMBERS = [
'01-2167-30-92545',
'26-2167-19-35623',
'29-2167-26-31433'
];
class TestCardNumber extends Component {
constructor() {
super();
this.state = {
cardNumber: ''
};
}
renredCardNumbers() {
return TEST_CARD_NUMBERS.map((number, index) => <MenuItem key={index} value={number} primaryText={number} />);
}
render() {
return (
<IconMenu
className='buka-cardnumber__help'
onChange={this.props.onChange}
iconButtonElement={<IconButton><ActionHelpOutline color={faintBlack} hoverColor={cyan500} /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}>
{this.renredCardNumbers()}
</IconMenu>
);
}
}
TestCardNumber.propTypes = {
onChange: React.PropTypes.func
};
export default TestCardNumber; | import React, { Component } from 'react';
import { faintBlack, cyan500 } from 'material-ui/styles/colors';
import MenuItem from 'material-ui/MenuItem';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton/IconButton';
import ActionHelpOutline from 'material-ui/svg-icons/action/help-outline';
const TEST_CARD_NUMBERS = [
'01-2167-30-92545'
];
class TestCardNumber extends Component {
constructor() {
super();
this.state = {
cardNumber: ''
};
}
renredCardNumbers() {
return TEST_CARD_NUMBERS.map((number, index) => <MenuItem key={index} value={number} primaryText={number} />);
}
render() {
return (
<IconMenu
className='buka-cardnumber__help'
onChange={this.props.onChange}
iconButtonElement={<IconButton><ActionHelpOutline color={faintBlack} hoverColor={cyan500} /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}>
{this.renredCardNumbers()}
</IconMenu>
);
}
}
TestCardNumber.propTypes = {
onChange: React.PropTypes.func
};
export default TestCardNumber; |
Use a const and a ternary, rather than mutate | const { merge } = require('webpack-merge')
const baseConfig = require('./base')
const devServer = require('../dev_server')
const { runningWebpackDevServer } = require('../env')
const { outputPath: contentBase, publicPath } = require('../config')
let devConfig = {
mode: 'development',
devtool: 'cheap-module-source-map'
}
if (runningWebpackDevServer) {
const liveReload = devServer.live_reload !== undefined ? devServer.live_reload : !devServer.hmr
const devServerConfig = {
devMiddleware: {
publicPath
},
compress: devServer.compress,
allowedHosts: devServer.allowed_hosts,
host: devServer.host,
port: devServer.port,
https: devServer.https,
hot: devServer.hmr,
liveReload,
historyApiFallback: { disableDotRule: true },
headers: devServer.headers,
static: {
publicPath: contentBase
}
}
if (devServer.static) {
devServerConfig.static = { ...devServerConfig.static, ...devServer.static }
}
if (devServer.client) {
devServerConfig.client = devServer.client
}
devConfig = merge(devConfig, {
stats: {
colors: true,
entrypoints: false,
errorDetails: true,
modules: false,
moduleTrace: false
},
devServer: devServerConfig
})
}
module.exports = merge(baseConfig, devConfig)
| const { merge } = require('webpack-merge')
const baseConfig = require('./base')
const devServer = require('../dev_server')
const { runningWebpackDevServer } = require('../env')
const { outputPath: contentBase, publicPath } = require('../config')
let devConfig = {
mode: 'development',
devtool: 'cheap-module-source-map'
}
if (runningWebpackDevServer) {
let liveReload = !devServer.hmr
if (devServer.live_reload !== undefined) {
liveReload = devServer.live_reload
}
const devServerConfig = {
devMiddleware: {
publicPath
},
compress: devServer.compress,
allowedHosts: devServer.allowed_hosts,
host: devServer.host,
port: devServer.port,
https: devServer.https,
hot: devServer.hmr,
liveReload,
historyApiFallback: { disableDotRule: true },
headers: devServer.headers,
static: {
publicPath: contentBase
}
}
if (devServer.static) {
devServerConfig.static = { ...devServerConfig.static, ...devServer.static }
}
if (devServer.client) {
devServerConfig.client = devServer.client
}
devConfig = merge(devConfig, {
stats: {
colors: true,
entrypoints: false,
errorDetails: true,
modules: false,
moduleTrace: false
},
devServer: devServerConfig
})
}
module.exports = merge(baseConfig, devConfig)
|
Increase number of SoundCloud episodes pulled in
This is related to the fact that unpublished episodes still pull through. | import os
import inspect
# Flask
DEBUG = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = 'www.vpr.net'
AWS_DIRECTORY = 'sandbox/app/'
SOUNDCLOUD_API = {
"client_id": "",
"client_secret": "",
"username": "",
"password": ""}
SOUNDCLOUD_NUM_TRACKS = 10
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Frozen Flask
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
FREEZER_DESTINATION = 'build'
FREEZER_BASE_URL = 'http://%s/%s' % (AWS_BUCKET, AWS_DIRECTORY)
FREEZER_STATIC_IGNORE = ['Gruntfile*', 'node_modules', 'package.json',
'dev', '.sass-cache']
WEBFACTION_PATH = AWS_DIRECTORY
ABSOLUTE_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/'
| import os
import inspect
# Flask
DEBUG = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = 'www.vpr.net'
AWS_DIRECTORY = 'sandbox/app/'
SOUNDCLOUD_API = {
"client_id": "",
"client_secret": "",
"username": "",
"password": ""}
SOUNDCLOUD_NUM_TRACKS = 5
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Frozen Flask
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
FREEZER_DESTINATION = 'build'
FREEZER_BASE_URL = 'http://%s/%s' % (AWS_BUCKET, AWS_DIRECTORY)
FREEZER_STATIC_IGNORE = ['Gruntfile*', 'node_modules', 'package.json',
'dev', '.sass-cache']
WEBFACTION_PATH = AWS_DIRECTORY
ABSOLUTE_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/'
|
Update webpack static, remove webpack clean so dist builds work again. | const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
index: ['./src/index.css', './src/index.js']
},
node: false,
output: {
path: path.join(__dirname, 'dist'),
chunkFilename: 'chunks/[id].js'
},
devServer: {
static: path.join(__dirname, 'dist'),
compress: true,
port: 3001,
},
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
title: 'ArcGIS API for JavaScript',
template: './public/index.html',
filename: './index.html',
chunksSortMode: 'none',
inlineSource: '.(css)$'
}),
new MiniCssExtractPlugin({
filename: "[name].[chunkhash].css",
chunkFilename: "[id].css"
})
]
};
| const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
index: ['./src/index.css', './src/index.js']
},
node: false,
output: {
path: path.join(__dirname, 'dist'),
chunkFilename: 'chunks/[id].js',
clean: true
},
devServer: {
static: './dist',
compress: true,
port: 3001,
},
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
title: 'ArcGIS API for JavaScript',
template: './public/index.html',
filename: './index.html',
chunksSortMode: 'none',
inlineSource: '.(css)$'
}),
new MiniCssExtractPlugin({
filename: "[name].[chunkhash].css",
chunkFilename: "[id].css"
})
]
};
|
Return statusCode 0 if request was aborted | var BufferList = require('bl');
var onFinished = require('on-finished');
module.exports = function bufferResponse(res, cb) {
var write = res.write;
var end = res.end;
var buf = new BufferList();
res.write = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
write.bind(res)(data, enc);
};
res.end = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
end.bind(res)(data, enc);
};
onFinished(res, function(err) {
res.write = write;
res.end = end;
var len = parseInt(res.get('Content-Length'));
if (!isNaN(len)) {
buf = buf.slice(0, len);
}
if (!err && res.req.connection.destroyed) {
res.statusCode = 0;
buf = null;
}
cb(err, buf);
});
};
function bufferAdd(buf, data, enc) {
if (typeof data == "string") buf.append(new Buffer(data, enc));
else if (data) buf.append(data);
}
| var BufferList = require('bl');
var onFinished = require('on-finished');
module.exports = function bufferResponse(res, cb) {
var write = res.write;
var end = res.end;
var buf = new BufferList();
res.write = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
write.bind(res)(data, enc);
};
res.end = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
end.bind(res)(data, enc);
};
onFinished(res, function(err) {
res.write = write;
res.end = end;
var len = parseInt(res.get('Content-Length'));
if (!isNaN(len)) buf = buf.slice(0, len);
cb(err, buf);
});
};
function bufferAdd(buf, data, enc) {
if (typeof data == "string") buf.append(new Buffer(data, enc));
else if (data) buf.append(data);
}
|
Fix typo in initial state | import React from 'react';
import PropTypes from 'prop-types';
import GatewayRegistry from './GatewayRegistry';
import {deprecated} from 'react-prop-types';
export default class GatewayDest extends React.Component {
static contextTypes = {
gatewayRegistry: PropTypes.instanceOf(GatewayRegistry).isRequired
};
static propTypes = {
name: PropTypes.string.isRequired,
tagName: deprecated(PropTypes.string, 'Use "component" instead.'),
component: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
])
};
constructor(props, context) {
super(props, context);
this.gatewayRegistry = context.gatewayRegistry;
}
state = {
children: null
};
componentWillMount() {
this.gatewayRegistry.addContainer(this.props.name, this);
}
componentWillUnmount() {
this.gatewayRegistry.removeContainer(this.props.name, this);
}
render() {
const { component, tagName, ...attrs } = this.props;
delete attrs.name;
return React.createElement(component || tagName || 'div', attrs, this.state.children);
}
}
| import React from 'react';
import PropTypes from 'prop-types';
import GatewayRegistry from './GatewayRegistry';
import {deprecated} from 'react-prop-types';
export default class GatewayDest extends React.Component {
static contextTypes = {
gatewayRegistry: PropTypes.instanceOf(GatewayRegistry).isRequired
};
static propTypes = {
name: PropTypes.string.isRequired,
tagName: deprecated(PropTypes.string, 'Use "component" instead.'),
component: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
])
};
constructor(props, context) {
super(props, context);
this.gatewayRegistry = context.gatewayRegistry;
}
state = {
child: null
};
componentWillMount() {
this.gatewayRegistry.addContainer(this.props.name, this);
}
componentWillUnmount() {
this.gatewayRegistry.removeContainer(this.props.name, this);
}
render() {
const { component, tagName, ...attrs } = this.props;
delete attrs.name;
return React.createElement(component || tagName || 'div', attrs, this.state.children);
}
}
|
Add support for prototype mocking | var assert = require('chai').assert;
var deepEqual = require('deep-equal');
var makeMockFunction = require('./makeMockFunction');
module.exports = function makeMock(object, type) {
var args = [];
var mockObj = function mockObj() {};
var prop;
for (prop in object) {
console.log('Prop: ', prop);
var mocked = getMockForProp(prop, object);
mockObj[prop] = mocked;
}
for (prop in object.prototype) {
mockObj.prototype[prop] = makeMockFunction(args, prop);
}
mockObj.prototype.reset = reset;
mockObj.prototype.getArgs = getArgs;
mockObj.reset = reset;
mockObj.getArgs = getArgs;
function reset() {
for (prop in args) {
if (args.hasOwnProperty(prop)) {
args[prop] = [];
}
}
}
function getArgs() {
return args;
}
function getMockForProp(prop, object) {
// Mock the function
if (typeof object[prop] === 'function') {
return makeMockFunction(args, prop);
}
// Recursively iterate through object mocking all properties
else if (typeof object[prop] === 'object') {
var mockInterface = {};
for (var propName in object[prop]) {
mockInterface[propName] = getMockForProp(propName, object[prop]);
}
return mockInterface;
}
// Return the property if not a function or object
return object[prop];
}
return mockObj;
};
| var assert = require('chai').assert;
var deepEqual = require('deep-equal');
var makeMockFunction = require('./makeMockFunction');
module.exports = function makeMock(object, type) {
var args = [];
var mockObj = function mockObj() {};
var prop;
for (prop in object) {
var mocked = getMockForProp(prop, object);
mockObj[prop] = mocked;
}
mockObj.prototype.reset = reset;
mockObj.prototype.getArgs = getArgs;
mockObj.reset = reset;
mockObj.getArgs = getArgs;
function reset() {
for (prop in args) {
if (args.hasOwnProperty(prop)) {
args[prop] = [];
}
}
}
function getArgs() {
return args;
}
function getMockForProp(prop, object) {
// Mock the function
if (typeof object[prop] === 'function') {
return makeMockFunction(args, prop);
}
// Recursively iterate through object mocking all properties
else if (typeof object[prop] === 'object') {
var mockInterface = {};
for (var propName in object[prop]) {
mockInterface[propName] = getMockForProp(propName, object[prop]);
}
return mockInterface;
}
// Return the property if not a function or object
return object[prop];
}
return mockObj;
};
|
Send headers with local queries | const axios = require('axios')
const path = require('path')
let GraphQL
try {
// do to GraphQL schema issue [see](https://github.com/graphql/graphiql/issues/58)
GraphQL = require(path.join(process.cwd(), './node_modules/graphql'))
} catch (e) {
// fallback if graphql is not installed locally
GraphQL = require('graphql')
}
const { graphql } = GraphQL
const { correctURL, encode, DEFAULT_CONFIG } = require('./util')
function Gest (schema, config = {}) {
const { baseURL, headers, timeout } = Object.assign(DEFAULT_CONFIG, config)
return function (query) {
if (baseURL) {
const instance = axios.create({
timeout,
headers
})
const corrected = correctURL(baseURL)
if (config.verbose) console.log(`${query} -> ${corrected}`)
return instance.post(corrected, encode(query))
.then(res => res.data)
}
if (config.verbose) console.log(query)
return graphql(schema, query, null, { headers })
}
}
module.exports = exports.default = Gest
| const axios = require('axios')
const path = require('path')
let GraphQL
try {
// do to GraphQL schema issue [see](https://github.com/graphql/graphiql/issues/58)
GraphQL = require(path.join(process.cwd(), './node_modules/graphql'))
} catch (e) {
// fallback if graphql is not installed locally
GraphQL = require('graphql')
}
const { graphql } = GraphQL
const { correctURL, encode, DEFAULT_CONFIG } = require('./util')
function Gest (schema, config = {}) {
const { baseURL, headers, timeout } = Object.assign(DEFAULT_CONFIG, config)
return function (query) {
if (baseURL) {
const instance = axios.create({
timeout,
headers
})
const corrected = correctURL(baseURL)
if (config.verbose) console.log(`${query} -> ${corrected}`)
return instance.post(corrected, encode(query))
.then(res => res.data)
}
if (config.verbose) console.log(query)
return graphql(schema, query)
}
}
module.exports = exports.default = Gest
|
Adjust test_polint to be less stdout-spammy | from django.core.management import call_command
from fjord.base.tests import TestCase
class TestGenerateData(TestCase):
def test_generate_data(self):
"""Make sure ./manage.py generatedata runs."""
call_command('generatedata')
call_command('generatedata', bigsample=True)
class TestPOLint(TestCase):
def test_polint(self):
"""Make sure ./manage.py polint runs."""
# Note: This doesn't make sure it works--just that it doesn't kick
# up obvious errors when it runs like if Dennis has changed in
# some way that prevents it from working correctly.
try:
call_command('polint', '--version')
except SystemExit:
# WOAH! WTF ARE YOU DOING? The lint command calls
# sys.exit() because it needs to return correct exit codes
# so we catch that here and ignore it. Otherwise testing
# it will kill the test suite.
pass
| from django.core.management import call_command
from fjord.base.tests import TestCase
class TestGenerateData(TestCase):
def test_generate_data(self):
"""Make sure ./manage.py generatedata runs."""
call_command('generatedata')
call_command('generatedata', bigsample=True)
class TestPOLint(TestCase):
def test_polint(self):
"""Make sure ./manage.py polint runs."""
# Note: This doesn't make sure it works--just that it doesn't kick
# up obvious errors when it runs like if Dennis has changed in
# some way that prevents it from working correctly.
try:
call_command('polint')
except SystemExit:
# WOAH! WTF ARE YOU DOING? The lint command calls
# sys.exit() because it needs to return correct exit codes
# so we catch that here and ignore it. Otherwise testing
# it will kill the test suite.
pass
|
Remove the commented out block | """Example Rejected Consumer"""
from rejected import consumer
import random
from tornado import gen
from tornado import httpclient
__version__ = '1.0.0'
class ExampleConsumer(consumer.SmartConsumer):
def process(self):
self.logger.info('Message: %r', self.body)
action = random.randint(0, 100)
if action == 0:
raise consumer.ConsumerException('zomg')
elif action < 5:
raise consumer.MessageException('reject')
elif action < 10:
raise consumer.ProcessingException('publish')
class AsyncExampleConsumer(consumer.Consumer):
@gen.coroutine
def process(self):
self.logger.info('Message: %r', self.body)
http_client = httpclient.AsyncHTTPClient()
results = yield [http_client.fetch('http://www.google.com'),
http_client.fetch('http://www.bing.com')]
self.logger.info('Length: %r', [len(r.body) for r in results])
| """Example Rejected Consumer"""
from rejected import consumer
import random
from tornado import gen
from tornado import httpclient
__version__ = '1.0.0'
class ExampleConsumer(consumer.SmartConsumer):
def process(self):
self.logger.info('Message: %r', self.body)
"""
action = random.randint(0, 100)
if action == 0:
raise consumer.ConsumerException('zomg')
elif action < 5:
raise consumer.MessageException('reject')
elif action < 10:
raise consumer.ProcessingException('publish')
"""
class AsyncExampleConsumer(consumer.Consumer):
@gen.coroutine
def process(self):
self.logger.info('Message: %r', self.body)
http_client = httpclient.AsyncHTTPClient()
results = yield [http_client.fetch('http://www.google.com'),
http_client.fetch('http://www.bing.com')]
self.logger.info('Length: %r', [len(r.body) for r in results])
|
Configure json.dumps() to use an item separator of "," instead of the default ", " to prevent single whitespace at the end of lines.
Without this option, all prettyfied JSON has one space at the end of each line, which is not so pretty:
{
"key": "value",_
"key": "value",_
"key": "value"
}
This could of course be configured, but with the current simplicity of the package it would probably be overkill. | import sublime
import sublime_plugin
import json
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the selection
if region.empty() and s.get("use_entire_file_if_no_selection"):
selection = sublime.Region(0, self.view.size())
else:
selection = region
try:
obj = json.loads(self.view.substr(selection))
self.view.replace(edit, selection, json.dumps(obj, indent=s.get("indent_size", 4), ensure_ascii=False, sort_keys=s.get("sort_keys", True), separators=(',', ': ')))
except Exception, e:
sublime.status_message(str(e))
| import sublime
import sublime_plugin
import json
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the selection
if region.empty() and s.get("use_entire_file_if_no_selection"):
selection = sublime.Region(0, self.view.size())
else:
selection = region
try:
obj = json.loads(self.view.substr(selection))
self.view.replace(edit, selection, json.dumps(obj, indent=s.get("indent_size", 4), ensure_ascii=False, sort_keys=s.get("sort_keys", True)))
except Exception, e:
sublime.status_message(str(e))
|
Remove deprecated version requirement settings
Linter plugins can no longer set version requirements.
https://github.com/SublimeLinter/SublimeLinter/issues/1087 | #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]'
| #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.6.0'
check_version = True
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]'
|
Add ContentItemRelation to SharedContent model
Displays objects in the admin delete screen. | from django.db import models
from django.utils.translation import ugettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
from fluent_contents.models import ContentItem, PlaceholderField, ContentItemRelation
class SharedContent(TranslatableModel):
"""
The parent hosting object for shared content
"""
translations = TranslatedFields(
title = models.CharField(_("Title"), max_length=200)
)
slug = models.SlugField(_("Template code"), unique=True, help_text=_("This unique name can be used refer to this content in in templates."))
contents = PlaceholderField("shared_content", verbose_name=_("Contents"))
# NOTE: settings such as "template_name", and which plugins are allowed can be added later.
# Adding the reverse relation for ContentItem objects
# causes the admin to list these objects when moving the shared content
contentitem_set = ContentItemRelation()
class Meta:
verbose_name = _("Shared content")
verbose_name_plural = _("Shared content")
def __unicode__(self):
return self.title
class SharedContentItem(ContentItem):
"""
The contentitem to include in a page.
"""
shared_content = models.ForeignKey(SharedContent, verbose_name=_('Shared content'), related_name='shared_content_items')
class Meta:
verbose_name = _('Shared content')
verbose_name_plural = _('Shared content')
def __unicode__(self):
return unicode(self.shared_content)
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
from fluent_contents.models import ContentItem, PlaceholderField
class SharedContent(TranslatableModel):
"""
The parent hosting object for shared content
"""
translations = TranslatedFields(
title = models.CharField(_("Title"), max_length=200)
)
slug = models.SlugField(_("Template code"), unique=True, help_text=_("This unique name can be used refer to this content in in templates."))
contents = PlaceholderField("shared_content", verbose_name=_("Contents"))
# NOTE: settings such as "template_name", and which plugins are allowed can be added later.
class Meta:
verbose_name = _("Shared content")
verbose_name_plural = _("Shared content")
def __unicode__(self):
return self.title
class SharedContentItem(ContentItem):
"""
The contentitem to include in a page.
"""
shared_content = models.ForeignKey(SharedContent, verbose_name=_('Shared content'), related_name='shared_content_items')
class Meta:
verbose_name = _('Shared content')
verbose_name_plural = _('Shared content')
def __unicode__(self):
return unicode(self.shared_content)
|
Fix import error when CUDA is not available | import chainerx
try:
import cupy
_cupy_available = True
except Exception:
_cupy_available = False
_chainerx_allocator = None
def cupy_share_allocator(owner=chainerx._global_context):
# Replace CuPy's allocator with ChainerX's if ChainerX is available with
# the CUDA backend. This is needed in order to share the GPU memory
# without having both modules using separate memory pools.
# TODO(imanishi): Make sure this allocator works when the global
# default context is changed by the user. It currently will not
# since the allocator is only configured here once.
try:
owner.get_backend('cuda')
except chainerx.BackendError:
raise RuntimeError(
'Cannot share allocator with CuPy without the CUDA backend.')
if not _cupy_available:
raise RuntimeError(
'Cannot share allocator with CuPy since CuPy is not available.')
param = chainerx._pybind_cuda.get_backend_ptr()
malloc_func, free_func = (
chainerx._pybind_cuda.get_backend_malloc_free_ptrs())
global _chainerx_allocator
_chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(
param, malloc_func, free_func, owner)
cupy.cuda.set_allocator(_chainerx_allocator.malloc)
| import chainerx
from chainerx import _pybind_cuda
try:
import cupy
_cupy_available = True
except Exception:
_cupy_available = False
_chainerx_allocator = None
def cupy_share_allocator(owner=chainerx._global_context):
# Replace CuPy's allocator with ChainerX's if ChainerX is available with
# the CUDA backend. This is needed in order to share the GPU memory
# without having both modules using separate memory pools.
# TODO(imanishi): Make sure this allocator works when the global
# default context is changed by the user. It currently will not
# since the allocator is only configured here once.
try:
owner.get_backend('cuda')
except chainerx.BackendError:
raise RuntimeError(
'Cannot share allocator with CuPy without the CUDA backend.')
if not _cupy_available:
raise RuntimeError(
'Cannot share allocator with CuPy since CuPy is not available.')
param = _pybind_cuda.get_backend_ptr()
malloc_func, free_func = _pybind_cuda.get_backend_malloc_free_ptrs()
global _chainerx_allocator
_chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(
param, malloc_func, free_func, owner)
cupy.cuda.set_allocator(_chainerx_allocator.malloc)
|
Revert "Bundle the position service with the lib for now so users dont have to depend on ng2-bootstrap"
This reverts commit 807a45bfcc7140124271e7e0e47e6fb4a22093b0. | module.exports = {
entry: './angular2-bootstrap-confirm.ts',
output: {
filename: './angular2-bootstrap-confirm.js',
libraryTarget: 'umd',
library: 'ng2BootstrapConfirm'
},
externals: {
'angular2/core': {
root: ['ng', 'core'],
commonjs: 'angular2/core',
commonjs2: 'angular2/core',
amd: 'angular2/core'
},
'ng2-bootstrap/components/position': 'ng2-bootstrap/components/position'
},
devtool: 'source-map',
module: {
preLoaders: [{
test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/
}],
loaders: [{
test: /\.ts$/, loader: 'ts', exclude: /node_modules/,
query: {
compilerOptions: {
declaration: true
}
}
}]
},
resolve: {
extensions: ['', '.ts', '.js']
}
}; | module.exports = {
entry: './angular2-bootstrap-confirm.ts',
output: {
filename: './angular2-bootstrap-confirm.js',
libraryTarget: 'umd',
library: 'ng2BootstrapConfirm'
},
externals: {
'angular2/core': {
root: ['ng', 'core'],
commonjs: 'angular2/core',
commonjs2: 'angular2/core',
amd: 'angular2/core'
}
},
devtool: 'source-map',
module: {
preLoaders: [{
test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/
}],
loaders: [{
test: /\.ts$/, loader: 'ts', exclude: /node_modules/,
query: {
compilerOptions: {
declaration: true
}
}
}]
},
resolve: {
extensions: ['', '.ts', '.js']
}
}; |
Fix arrays being converted to objects
typeof new Array() is 'object', so the check if the thing was an array never hit | function forIn(object, callback) {
for (const key in object) {
if (!object.hasOwnProperty(key)) {
continue;
}
callback(key);
}
}
function normalize(metaInformation) {
const normalized = {};
forIn(metaInformation, function cb(key) {
if (Array.isArray(metaInformation[key])) {
// Normalize nested arrays
normalized[key] = [];
for (let i = 0; i < metaInformation[key].length; i++) {
normalized[key][i] = normalize(metaInformation[key][i]);
}
} else if (typeof metaInformation[key] === 'object') {
// Normalize nested objects
if (key === 'flowType') {
// Replace 'flowType' with 'type'
normalized.type = normalize(metaInformation[key]);
return;
}
normalized[key] = normalize(metaInformation[key]);
return;
}
normalized[key] = metaInformation[key];
});
return normalized;
}
module.exports = normalize;
| function forIn(object, callback) {
for (const key in object) {
if (!object.hasOwnProperty(key)) {
continue;
}
callback(key);
}
}
function normalize(metaInformation) {
const normalized = {};
forIn(metaInformation, function cb(key) {
if (typeof metaInformation[key] === 'object') {
// Normalize nested objects
if (key === 'flowType') {
// Replace 'flowType' with 'type'
normalized.type = normalize(metaInformation[key]);
return;
}
normalized[key] = normalize(metaInformation[key]);
return;
} else if (Array.isArray(metaInformation[key])) {
// Normalize nested arrays
for (let i = 0; i < metaInformation[key].length; i++) {
normalized[key][i] = normalize(metaInformation[key][i]);
}
}
normalized[key] = metaInformation[key];
});
return normalized;
}
module.exports = normalize;
|
Check if checkbox value has updated. |
from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.checkbox import CheckBox
from asciimatics.widgets import CheckBox as ACheckBox
class TestCheckBox(TestCase):
def test_checkbox(self):
"""
Test the checkbox
:return: void
"""
changed_checkbox = []
def change_handler(checkbox):
changed_checkbox.append(checkbox)
checkbox = CheckBox(self.rand_str(), on_change=change_handler)
self.assert_is_instance(checkbox, ACheckBox)
for value in [True, False, True]:
previous_count = len(changed_checkbox)
checkbox.value = value
self.assert_equal(value, checkbox.value)
self.assert_equal(previous_count + 1, len(changed_checkbox))
self.assert_equal(checkbox, changed_checkbox[-1])
|
from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.checkbox import CheckBox
from asciimatics.widgets import CheckBox as ACheckBox
class TestCheckBox(TestCase):
def test_checkbox(self):
"""
Test the checkbox
:return: void
"""
changed_checkbox = []
def change_handler(checkbox):
changed_checkbox.append(checkbox)
checkbox = CheckBox(self.rand_str(), on_change=change_handler)
self.assert_is_instance(checkbox, ACheckBox)
for value in [True, False, True]:
previous_count = len(changed_checkbox)
checkbox.value = value
self.assert_equal(previous_count + 1, len(changed_checkbox))
self.assert_equal(checkbox, changed_checkbox[-1])
|
Handle FObejcts in foam.swift.stringify during generation. | /**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.LIB({
name: 'foam.swift',
methods: [
function stringify(v) {
var type = foam.typeOf(v);
if ( type == foam.Number || type == foam.Boolean ) {
return `${v}`;
} else if ( type == foam.String ) {
return `"${v
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
}"`;
} else if ( type == foam.Array ) {
return `[${v.map(foam.swift.stringify).join(',')}]`;
} else if ( type == foam.Function ) {
// Unable to convert functions.
return 'nil';
} else if ( type == foam.core.FObject ) {
// TODO: Should be able to serialize an FObject to swift.
return 'nil';
} else {
console.log('Encountered unexpected type while converitng value to string:', v);
debugger;
}
},
],
});
| /**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.LIB({
name: 'foam.swift',
methods: [
function stringify(v) {
var type = foam.typeOf(v);
if ( type == foam.Number || type == foam.Boolean ) {
return `${v}`;
} else if ( type == foam.String ) {
return `"${v
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
}"`;
} else if ( type == foam.Array ) {
return `[${v.map(foam.swift.stringify).join(',')}]`;
} else if ( type == foam.Function ) {
// Unable to convert functions.
return 'nil';
} else {
console.log('Encountered unexpected type while converitng value to string:', v);
debugger;
}
},
],
});
|
Add penalty for not making food | function collectWood(){
wood = wood + woodAdd;
update();
}
function collectStone(){
if(wood >= 5){
wood = wood - 5;
stone = stone + stoneAdd;
}
update();
}
function collectFood(){
if(stone >= 5){
food = food + foodAdd;
stone = stone - 5;
}
update();
}
function makePop(){
if(food >= 5){
if(wood >= 5){
if(stone >= 5){
population = population + 1;
stone = stone - 5;
wood = wood -5;
food = food - 5;
}
}
}
update();
}
var foodLossInterval = 0;
function update(){
$("#popText").text("Population: " + population);
$("#foodText").text("Food: " + food);
$("#stoneText").text("Stone: " + stone);
$("#woodText").text("Wood: " + wood);
foodLossInterval++;
if(foodLossInterval == 50){
foodLossInterval = 0;
if(population > food){
population = population - 1;
} else{
food = food - population;
}
}
} | function collectWood(){
wood = wood + woodAdd;
update();
}
function collectStone(){
if(wood >= 5){
wood = wood - 5;
stone = stone + stoneAdd;
}
update();
}
function collectFood(){
if(stone >= 5){
food = food + foodAdd;
stone = stone - 5;
}
update();
}
function makePop(){
if(food >= 5){
if(wood >= 5){
if(stone >= 5){
population = population + 1;
stone = stone - 5;
wood = wood -5;
food = food - 5;
}
}
}
update();
}
function update(){
$("#popText").text("Population: " + population);
$("#foodText").text("Food: " + food);
$("#stoneText").text("Stone: " + stone);
$("#woodText").text("Wood: " + wood);
} |
Make article_aggregated_views user_id column non-nullable | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticleAggregatedViewsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('article_aggregated_views', function (Blueprint $table) {
$table->integer('article_id')->unsigned();
$table->string('user_id');
$table->string('browser_id');
$table->date('date');
$table->integer('pageviews')->default(0);
$table->integer('timespent')->default(0);
$table->primary(['article_id', 'user_id', 'browser_id', 'date'], 'primary_index');
$table->foreign('article_id')->references('id')->on('articles');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('article_aggregated_views');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticleAggregatedViewsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('article_aggregated_views', function (Blueprint $table) {
$table->integer('article_id')->unsigned();
$table->string('user_id')->nullable();
$table->string('browser_id');
$table->date('date');
$table->integer('pageviews')->default(0);
$table->integer('timespent')->default(0);
$table->primary(['article_id', 'user_id', 'browser_id', 'date'], 'primary_index');
$table->foreign('article_id')->references('id')->on('articles');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('article_aggregated_views');
}
}
|
Add __all__ variable to enforce ordering in docs | # -*- coding: utf-8 -*-
#
# Artifacts - Artifactory Search Client
#
# Copyright 2015 Smarter Travel
#
# Available under the MIT license. See LICENSE for details.
#
"""
artifacts.exceptions
~~~~~~~~~~~~~~~~~~~~
Exceptions raised by the Artifacts library.
"""
from __future__ import print_function, division
__all__ = [
'ArtifactsError',
'ArtifactoryApiError',
'NoReleaseArtifactsError',
'NoArtifactVersionsError'
]
class ArtifactsError(RuntimeError):
"""Base for exceptions raised by the Artifacts library"""
class ArtifactoryApiError(ArtifactsError):
"""Base for errors interacting with the Artifactory REST API"""
def __init__(self, *args, **kwargs):
#: HTTP status code returned by the Artifactory REST API
self.code = kwargs.pop('code', None)
#: URL used for making a request to the Artifactory REST API
self.url = kwargs.pop('url', None)
super(ArtifactoryApiError, self).__init__(*args, **kwargs)
class NoReleaseArtifactsError(ArtifactoryApiError):
"""There were no release artifacts for the project in the given repository"""
class NoArtifactVersionsError(ArtifactoryApiError):
"""There were no versions for the project in the given repository"""
| # -*- coding: utf-8 -*-
#
# Artifacts - Artifactory Search Client
#
# Copyright 2015 Smarter Travel
#
# Available under the MIT license. See LICENSE for details.
#
"""
artifacts.exceptions
~~~~~~~~~~~~~~~~~~~~
Exceptions raised by the Artifacts library.
"""
from __future__ import print_function, division
class ArtifactsError(RuntimeError):
"""Base for all exceptions raised by the Artifacts library"""
class ArtifactoryApiError(ArtifactsError):
"""Root for errors interacting with the Artifactory REST API"""
def __init__(self, *args, **kwargs):
#: HTTP status code returned by the Artifactory REST API
self.code = kwargs.pop('code', None)
#: URL used for making a request to the Artifactory REST API
self.url = kwargs.pop('url', None)
super(ArtifactoryApiError, self).__init__(*args, **kwargs)
class NoReleaseArtifactsError(ArtifactoryApiError):
"""There were no release artifacts for the project in the given repository"""
class NoArtifactVersionsError(ArtifactoryApiError):
"""There were no versions for the project in the given repository"""
|
Fix misnamed SwatHtmltag
This was probably never caught because we seldom (if ever) use SwatDisplableContainer's own display() method
svn commit r10293 | <?php
require_once 'Swat/SwatContainer.php';
/**
* Base class for containers that display an XHTML element
*
* @package Swat
* @copyright 2006 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatDisplayableContainer extends SwatContainer
{
// {{{ public function display()
/**
* Displays this container
*/
public function display()
{
if (!$this->visible)
return;
$div = new SwatHtmlTag('div');
$div->id = $this->id;
$div->class = $this->getCSSClassString();
$div->open();
$this->displayChildren();
$div->close();
}
// }}}
// {{{ protected function getCSSClassNames()
/**
* Gets the array of CSS classes that are applied to this displayable
* container
*
* @return array the array of CSS classes that are applied to this
* displayable container.
*/
protected function getCSSClassNames()
{
$classes = array('swat-displayable-container');
$classes = array_merge($classes, $this->classes);
return $classes;
}
// }}}
}
?>
| <?php
require_once 'Swat/SwatContainer.php';
/**
* Base class for containers that display an XHTML element
*
* @package Swat
* @copyright 2006 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatDisplayableContainer extends SwatContainer
{
// {{{ public function display()
/**
* Displays this container
*/
public function display()
{
if (!$this->visible)
return;
$div_tag = new SwatHtmlTag('div');
$div_tag->id = $this->id;
$div_tag->class = $this->getCSSClassString();
$div->open();
$this->displayChildren();
$div->close();
}
// }}}
// {{{ protected function getCSSClassNames()
/**
* Gets the array of CSS classes that are applied to this displayable
* container
*
* @return array the array of CSS classes that are applied to this
* displayable container.
*/
protected function getCSSClassNames()
{
$classes = array('swat-displayable-container');
$classes = array_merge($classes, $this->classes);
return $classes;
}
// }}}
}
?>
|
Fix smelting and crafting with subtypes | package me.zford.jobs.bukkit.actions;
import me.zford.jobs.container.ActionInfo;
import me.zford.jobs.container.ActionType;
import me.zford.jobs.container.BaseActionInfo;
import org.bukkit.inventory.ItemStack;
public class ItemActionInfo extends BaseActionInfo implements ActionInfo {
private ItemStack items;
public ItemActionInfo(ItemStack items, ActionType type) {
super(type);
this.items = items;
}
@Override
public String getName() {
return items.getType().toString();
}
@Override
public String getNameWithSub() {
return getName()+":"+items.getData().getData();
}
}
| package me.zford.jobs.bukkit.actions;
import me.zford.jobs.container.ActionInfo;
import me.zford.jobs.container.ActionType;
import me.zford.jobs.container.BaseActionInfo;
import org.bukkit.inventory.ItemStack;
public class ItemActionInfo extends BaseActionInfo implements ActionInfo {
private ItemStack items;
public ItemActionInfo(ItemStack items, ActionType type) {
super(type);
this.items = items;
}
@Override
public String getName() {
return items.getType().toString();
}
@Override
public String getNameWithSub() {
return getName()+":"+items.getData();
}
}
|
Increase character length for food | from django.db import models
class Menu(models.Model):
day = models.CharField(max_length=10, blank=False, null=False)
food = models.CharField(max_length=120, blank=False, null=False)
meal = models.CharField(max_length=10, blank=False, null=False)
option = models.IntegerField(null=False)
week = models.IntegerField(null=False)
class Meta:
ordering = ('-week',)
db_table = 'menu_table'
def __unicode__(self):
return u'%s %s %s' % (self.day, self.week, self.meal)
class Rating(models.Model):
date = models.DateTimeField(auto_now_add=True)
user_id = models.CharField(max_length=20)
menu = models.ForeignKey(Menu, related_name='rating')
rate = models.IntegerField(blank=False, null=False)
comment = models.TextField(default='no comment', )
class Meta:
ordering = ('-date',)
db_table = 'rating'
def __unicode__(self):
return u'%s' % (self.date)
| from django.db import models
class Menu(models.Model):
day = models.CharField(max_length=10, blank=False, null=False)
food = models.CharField(max_length=60, blank=False, null=False)
meal = models.CharField(max_length=10, blank=False, null=False)
option = models.IntegerField(null=False)
week = models.IntegerField(null=False)
class Meta:
ordering = ('-week',)
db_table = 'menu_table'
def __unicode__(self):
return u'%s %s' % (self.day, self.week)
class Rating(models.Model):
date = models.DateTimeField(auto_now_add=True)
user_id = models.CharField(max_length=20)
menu = models.ForeignKey(Menu, related_name='rating')
rate = models.IntegerField(blank=False, null=False)
comment = models.TextField(default='no comment', )
class Meta:
ordering = ('-date',)
db_table = 'rating'
def __unicode__(self):
return u'%s' % (self.date)
|
Rename variables, var -> const/let | const MESSAGE_RANGE = 1000
class Shouty {
constructor() {
this.locationsByShouter = new Map()
this.messagesByShouter = new Map()
}
setLocation(person, coordinate) {
this.locationsByShouter.set(person, coordinate)
}
shout(person, message) {
this.messagesByShouter.set(person, message)
}
getMessagesHeardBy(listener) {
const messagesHeard = new Map()
for (const [shouter, message] of this.messagesByShouter) {
const shouterLocation = this.locationsByShouter.get(shouter)
const listenerLocation = this.locationsByShouter.get(listener)
if (shouterLocation.distanceFrom(listenerLocation) < MESSAGE_RANGE) {
messagesHeard.set(shouter, message)
}
}
return messagesHeard
}
}
module.exports = Shouty
| const MESSAGE_RANGE = 1000
class Shouty {
constructor() {
this.locations = new Map()
this.messages = new Map()
}
setLocation(person, coordinate) {
this.locations.set(person, coordinate)
}
shout(person, message) {
this.messages.set(person, message)
}
getMessagesHeardBy(listener) {
var msgHeard = new Map()
for(let [shouter, msg] of this.messages) {
var shouterPos = this.locations.get(shouter)
var listenerPos = this.locations.get(listener)
if(shouterPos.distanceFrom(listenerPos) < MESSAGE_RANGE) {
msgHeard.set(shouter, msg)
}
}
return msgHeard
}
}
module.exports = Shouty
|
Handle stealable element with utils | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""A module for extended info page models (visible in LHN on hover over
object members)"""
from selenium.common import exceptions
from lib import base
from lib.constants import locator
from lib.utils import selenium_utils
class ExtendedInfo(base.Component):
"""Model representing an extended info box that allows the object to be
mapped"""
locator_cls = locator.ExtendedInfo
def __init__(self, driver):
super(ExtendedInfo, self).__init__(driver)
self.is_mapped = None
self.button_map = None
self.title = base.Label(driver, self.locator_cls.TITLE)
self._set_is_mapped()
def map_to_object(self):
selenium_utils.click_on_staleable_element(
self._driver,
self.locator_cls.BUTTON_MAP_TO)
self.is_mapped = True
def _set_is_mapped(self):
"""Checks if the object is already mapped"""
try:
self._driver.find_element(*self.locator_cls.ALREADY_MAPPED)
self.is_mapped = True
except exceptions.NoSuchElementException:
self.is_mapped = False
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""A module for extended info page models (visible in LHN on hover over
object members)"""
from selenium.common import exceptions
from lib import base
from lib.constants import locator
class ExtendedInfo(base.Component):
"""Model representing an extended info box that allows the object to be
mapped"""
_locator = locator.ExtendedInfo
def __init__(self, driver):
super(ExtendedInfo, self).__init__(driver)
self.button_map = None
def _reload_contents(self):
self.button_map = base.Button(
self._driver, self._locator.BUTTON_MAP_TO)
def map_to_object(self):
try:
self.button_map = base.Button(
self._driver, self._locator.BUTTON_MAP_TO)
self.button_map.click()
except exceptions.StaleElementReferenceException:
self._reload_contents()
return self.map_to_object()
def is_already_mapped(self):
"""Checks if the object is already mapped"""
try:
self._driver.find_element(*self._locator.ALREADY_MAPPED)
return True
except exceptions.NoSuchElementException:
return False
|
Remove "Programming Language :: Foxpro" classifier. | # coding=utf-8
from __future__ import absolute_import, division, print_function
import sys
from setuptools import setup
VERSION='0.1.0'
setup(
name='vfp2py',
version=VERSION,
description='Convert foxpro code to python',
author='Michael Wisslead',
author_email='michael.wisslead@gmail.com',
url='https://github.com/mwisslead',
packages=['vfp2py'],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
install_requires=[
'antlr4-python2-runtime==4.8; python_version < \'3\'',
'antlr4-python3-runtime==4.8; python_version >= \'3\'',
'dbf',
'autopep8',
'isort<5',
'python-dateutil',
'pyodbc'
],
test_suite='nose.collector',
tests_require=['nose', 'Faker'],
entry_points = {
'console_scripts': ['vfp2py=vfp2py.__main__:main'],
}
)
| # coding=utf-8
from __future__ import absolute_import, division, print_function
import sys
from setuptools import setup
VERSION='0.1.0'
setup(
name='vfp2py',
version=VERSION,
description='Convert foxpro code to python',
author='Michael Wisslead',
author_email='michael.wisslead@gmail.com',
url='https://github.com/mwisslead',
packages=['vfp2py'],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Foxpro",
"Topic :: Software Development :: Libraries :: Python Modules",
],
install_requires=[
'antlr4-python2-runtime==4.8; python_version < \'3\'',
'antlr4-python3-runtime==4.8; python_version >= \'3\'',
'dbf',
'autopep8',
'isort<5',
'python-dateutil',
'pyodbc'
],
test_suite='nose.collector',
tests_require=['nose', 'Faker'],
entry_points = {
'console_scripts': ['vfp2py=vfp2py.__main__:main'],
}
)
|
Use httputil DumpRequest instead of just %v formatting
This makes logplexd output a lot more useful in most cases.
DumpRequest is set up to render the request body, also.
Signed-off-by: Daniel Farina <3d0f3b9ddcacec30c4008c5e030e6c13a478cb4f@fdr.io> | package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
"os"
"os/signal"
)
type LogplexPrint struct{}
func (*LogplexPrint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
dump, err := httputil.DumpRequest(r, true)
if err != nil {
log.Printf("Could not dump request: %#v", err)
}
log.Printf("%s", dump)
// Respond saying everything is OK.
w.WriteHeader(http.StatusNoContent)
}
func main() {
s := httptest.NewTLSServer(&LogplexPrint{})
fmt.Println(s.URL)
// Signal handling:
sigch := make(chan os.Signal)
signal.Notify(sigch, os.Interrupt, os.Kill)
for sig := range sigch {
log.Printf("got signal %v", sig)
if sig == os.Kill {
os.Exit(2)
} else if sig == os.Interrupt {
os.Exit(0)
}
}
}
| package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"os/signal"
)
type LogplexPrint struct{}
func (*LogplexPrint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %#v", *r)
w.WriteHeader(http.StatusNoContent)
}
func main() {
s := httptest.NewTLSServer(&LogplexPrint{})
fmt.Println(s.URL)
// Signal handling:
sigch := make(chan os.Signal)
signal.Notify(sigch, os.Interrupt, os.Kill)
for sig := range sigch {
log.Printf("got signal %v", sig)
if sig == os.Kill {
os.Exit(2)
} else if sig == os.Interrupt {
os.Exit(0)
}
}
}
|
Add some basic error handling and remove tuples.
No need for tuples when the lists are going to be
so small. The speed difference between the two
will be minimal. | #!/usr/bin/env python3
from config import WOLFRAM_KEY
import sys
import wolframalpha
POD_TITLE = 'Average nutrition facts'
QUERY = input()
def get_macros(pod_text):
items = pod_text.split("|")
for t in items:
chunks = t.split()
if 'protein' in chunks:
protein = chunks[-2::]
elif 'total' in chunks:
if 'carbohydrates' in chunks:
carbs = chunks[-2::]
elif 'fat' in chunks:
fat = chunks[-2::]
return protein, carbs, fat
client = wolframalpha.Client(WOLFRAM_KEY)
res = client.query(QUERY)
try:
macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text)
except IndexError:
print(QUERY + '\'s macros not found on Wolfram.')
sys.exit(1)
print('-' * len(QUERY))
print("Protein: " + macros[0][0] + macros[0][1])
print("Fat: " + macros[2][0] + macros[2][1])
print("Carbs: " + macros[1][0] + macros[1][1])
| #!/usr/bin/env python3
from config import WOLFRAM_KEY
import wolframalpha
POD_TITLE = 'Average nutrition facts'
QUERY = input()
def get_macros(pod_text):
items = pod_text.split("|")
for t in items:
chunks = t.split()
if 'protein' in chunks:
protein = tuple(chunks[-2::])
elif 'total' in chunks:
if 'carbohydrates' in chunks:
carbs = tuple(chunks[-2::])
elif 'fat' in chunks:
fat = tuple(chunks[-2::])
return protein, carbs, fat
client = wolframalpha.Client(WOLFRAM_KEY)
res = client.query(QUERY)
macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text)
print('-' * len(QUERY))
print("Protein: " + macros[0][0] + macros[0][1])
print("Fat: " + macros[2][0] + macros[2][1])
print("Carbs: " + macros[1][0] + macros[1][1])
|
Update inline documentation for `NodeList` -> `Array` change. | import settings from './settings';
/*
The findAll test helper uses `querySelectorAll` to search inside the test
DOM (based on app configuration for the rootElement).
Alternalively, a second argument may be passed which is an element as the
DOM context to search within.
@method findAll
@param {String} CSS selector to find elements in the test DOM
@param {HTMLElement} contextEl to query within, query from its contained DOM
@return {Array} An array of zero or more HTMLElement objects
@public
*/
export function findAll(selector, contextEl) {
let result;
if (contextEl instanceof HTMLElement) {
result = contextEl.querySelectorAll(selector);
} else {
result = document.querySelectorAll(`${settings.rootElement} ${selector}`);
}
return toArray(result);
}
function toArray(nodelist) {
let array = new Array(nodelist.length);
for (let i = 0; i < nodelist.length; i++) {
array[i] = nodelist[i];
}
return array;
}
| import settings from './settings';
/*
The findAll test helper uses `querySelectorAll` to search inside the test
DOM (based on app configuration for the rootElement).
Alternalively, a second argument may be passed which is an element as the
DOM context to search within.
@method findAll
@param {String} CSS selector to find elements in the test DOM
@param {HTMLElement} contextEl to query within, query from its contained DOM
@return {NodeList} A (non-live) list of zero or more HTMLElement objects
@public
*/
export function findAll(selector, contextEl) {
let result;
if (contextEl instanceof HTMLElement) {
result = contextEl.querySelectorAll(selector);
} else {
result = document.querySelectorAll(`${settings.rootElement} ${selector}`);
}
return toArray(result);
}
function toArray(nodelist) {
let array = new Array(nodelist.length);
for (let i = 0; i < nodelist.length; i++) {
array[i] = nodelist[i];
}
return array;
}
|
[R] Add empty line after imports | #!/usr/bin/env python3
"""
Follow the white house rabbit
This fetches tweets from an user and prints
the full json output from the api.
"""
import os
import sys
import json
from twython import Twython
from twython import TwythonError
CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY')
CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY')
ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
def query(screen_name='realDonaldTrump'):
# Requires Authentication as of Twitter API v1.1
twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \
ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
try:
user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200)
except TwythonError as e:
print(e)
print(json.dumps(user_timeline))
if __name__ == '__main__':
try:
query(sys.argv[1])
except IndexError as e:
print("Missing Twitter user name as first parameter")
| #!/usr/bin/env python3
"""
Follow the white house rabbit
This fetches tweets from an user and prints
the full json output from the api.
"""
import os
import sys
import json
from twython import Twython
from twython import TwythonError
CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY')
CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY')
ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
def query(screen_name='realDonaldTrump'):
# Requires Authentication as of Twitter API v1.1
twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \
ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
try:
user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200)
except TwythonError as e:
print(e)
print(json.dumps(user_timeline))
if __name__ == '__main__':
try:
query(sys.argv[1])
except IndexError as e:
print("Missing Twitter user name as first parameter")
|
BB-1049: Address form om frontend does not work | define([
'backbone',
'routing',
'oroaddress/js/region/model',
'underscore'
], function(Backbone, routing, RegionModel, _) {
'use strict';
/**
* @export oroaddress/js/region/collection
* @class oroaddress.region.Collection
* @extends Backbone.Collection
*/
return Backbone.Collection.extend({
defaultOptions: {
route: 'oro_api_country_get_regions'
},
url: null,
model: RegionModel,
/**
* Constructor
*/
initialize: function(models, options) {
this.options = _.extend({}, this.defaultOptions, options);
this.url = routing.generate(this.options.route);
},
/**
* Regenerate route for selected country
*
* @param id {string}
*/
setCountryId: function(id) {
this.url = routing.generate(this.options.route, {country: id});
}
});
});
| define([
'backbone',
'routing',
'oroaddress/js/region/model'
], function(Backbone, routing, RegionModel) {
'use strict';
/**
* @export oroaddress/js/region/collection
* @class oroaddress.region.Collection
* @extends Backbone.Collection
*/
return Backbone.Collection.extend({
defaultOptions: {
route: 'oro_api_country_get_regions'
},
url: null,
model: RegionModel,
/**
* Constructor
*/
initialize: function(models, options) {
this.options = _.extend({}, this.defaultOptions, options);
this.url = routing.generate(this.options.route);
},
/**
* Regenerate route for selected country
*
* @param id {string}
*/
setCountryId: function(id) {
this.url = routing.generate(this.options.route, {country: id});
}
});
});
|
Use specially registered domain instead of real domain test.com | <?php
$config = null;
$client = null;
/* @var $client KalturaClient */
require_once __DIR__ . '/lib/init.php';
$partner = new KalturaPartner();
$partner->name = 'sanity-test';
$partner->website = 'sanity.example.com';
$partner->adminName = 'sanity-test';
$partner->adminEmail = uniqid('sanity.') . '@example.com';
$partner->description = 'sanity-test';
$cmsPassword = uniqid('pW@4');
$registeredPartner = $client->partner->register($partner, $cmsPassword);
/* @var $registeredPartner KalturaPartner */
if(!$registeredPartner || !$registeredPartner->id)
{
echo "No partner created\n";
exit(-1);
}
$config['session']['partnerId'] = $registeredPartner->id;
$config['session']['secret'] = $registeredPartner->secret;
$config['session']['adminSecret'] = $registeredPartner->adminSecret;
write_ini_file($config);
$partnerSession = $client->user->loginByLoginId($registeredPartner->adminEmail, $cmsPassword, $registeredPartner->id, 86400, 'disableentitlement');
$client->setKs($partnerSession);
$user = $client->user->getByLoginId($registeredPartner->adminEmail);
/* @var $user KalturaUser */
if(!$user || !$user->id)
{
echo "Unable to login\n";
exit(-1);
}
exit(0); | <?php
$config = null;
$client = null;
/* @var $client KalturaClient */
require_once __DIR__ . '/lib/init.php';
$partner = new KalturaPartner();
$partner->name = 'sanity-test';
$partner->website = 'sanity.test.com';
$partner->adminName = 'sanity-test';
$partner->adminEmail = uniqid('sanity.') . '@test.com';
$partner->description = 'sanity-test';
$cmsPassword = uniqid('pW@4');
$registeredPartner = $client->partner->register($partner, $cmsPassword);
/* @var $registeredPartner KalturaPartner */
if(!$registeredPartner || !$registeredPartner->id)
{
echo "No partner created\n";
exit(-1);
}
$config['session']['partnerId'] = $registeredPartner->id;
$config['session']['secret'] = $registeredPartner->secret;
$config['session']['adminSecret'] = $registeredPartner->adminSecret;
write_ini_file($config);
$partnerSession = $client->user->loginByLoginId($registeredPartner->adminEmail, $cmsPassword, $registeredPartner->id, 86400, 'disableentitlement');
$client->setKs($partnerSession);
$user = $client->user->getByLoginId($registeredPartner->adminEmail);
/* @var $user KalturaUser */
if(!$user || !$user->id)
{
echo "Unable to login\n";
exit(-1);
}
exit(0); |
Add Onimaru to the character list | export const characters = Object.assign({},
require('./characters/geiger.jsx'),
require('./characters/grave.jsx'),
require('./characters/gwen.jsx'),
require('./characters/jaina.jsx'),
require('./characters/midori.jsx'),
require('./characters/rook.jsx'),
require('./characters/setsuki.jsx'),
require('./characters/troq.jsx'),
require('./characters/valerie.jsx'),
require('./characters/argagarg.jsx'),
require('./characters/degrey.jsx'),
require('./characters/lum.jsx'),
require('./characters/menelker.jsx'),
require('./characters/quince.jsx'),
require('./characters/persephone.jsx'),
require('./characters/onimaru.jsx'),
);
export default characters
| export const characters = Object.assign({},
require('./characters/geiger.jsx'),
require('./characters/grave.jsx'),
require('./characters/gwen.jsx'),
require('./characters/jaina.jsx'),
require('./characters/midori.jsx'),
require('./characters/rook.jsx'),
require('./characters/setsuki.jsx'),
require('./characters/troq.jsx'),
require('./characters/valerie.jsx'),
require('./characters/argagarg.jsx'),
require('./characters/degrey.jsx'),
require('./characters/lum.jsx'),
require('./characters/menelker.jsx'),
require('./characters/quince.jsx'),
require('./characters/persephone.jsx'),
);
export default characters
|
Make sure there is a default for LOG Group | import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_PUBLIC_KEY = os.getenv('EQ_RRM_PUBLIC_KEY')
EQ_SR_PRIVATE_KEY = os.getenv('EQ_SR_PRIVATE_KEY')
EQ_GIT_REF = os.getenv('EQ_GIT_REF', None)
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER', 'UNKNOWN') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
| import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_PUBLIC_KEY = os.getenv('EQ_RRM_PUBLIC_KEY')
EQ_SR_PRIVATE_KEY = os.getenv('EQ_SR_PRIVATE_KEY')
EQ_GIT_REF = os.getenv('EQ_GIT_REF', None)
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
|
Correct linearization/delinearization of this linking function. | <?php
namespace mcordingley\Regression\Linking;
/**
* Power
*
* Linking implementation that transforms data that follows a geometric curve.
*/
class Power implements LinkingInterface
{
protected $exponent;
/**
* __construct
*
* @param float|null $exponent The exponent that best describes the progression that the data follows. Defaults to 2.
*/
public function __construct($exponent = 2)
{
$this->exponent = $exponent;
}
public function delinearize($value)
{
return pow($value, $this->exponent);
}
public function linearize($value)
{
return pow($value, 1 / $this->exponent);
}
} | <?php
namespace mcordingley\Regression\Linking;
/**
* Power
*
* Linking implementation that transforms data that follows a geometric curve.
*/
class Power implements LinkingInterface
{
protected $exponent;
/**
* __construct
*
* @param float|null $exponent The exponent that best describes the progression that the data follows. Defaults to 2.
*/
public function __construct($exponent = 2)
{
$this->exponent = $exponent;
}
public function delinearize($value)
{
return pow($value, 1 / $this->exponent);
}
public function linearize($value)
{
return pow($value, $this->exponent);
}
} |
Fix proptypes error related to validation | import {PropTypes} from 'react'
function lazy(fn) {
let cachedFn
return (...args) => (cachedFn || (cachedFn = fn()))(...args)
}
const field = PropTypes.shape({
name: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
placeholder: PropTypes.string,
type: PropTypes.string,
to: lazy(() => PropTypes.arrayOf(field)),
of: lazy(() => PropTypes.arrayOf(field))
})
const type = PropTypes.shape({
fields: PropTypes.arrayOf(field),
alias: PropTypes.string,
isPrimitive: PropTypes.bool
})
const validation = {
fields: PropTypes.objectOf(lazy(() => PropTypes.shape(validation))),
messages: PropTypes.arrayOf(PropTypes.shape({
type: PropTypes.oneOf(['error', 'warning']),
id: PropTypes.string,
message: PropTypes.string
}))
}
const schema = PropTypes.objectOf(type)
export default {
type,
schema,
field,
validation
}
| import {PropTypes} from 'react'
function lazy(fn) {
let cachedFn
return (...args) => (cachedFn || (cachedFn = fn()))(...args)
}
const field = PropTypes.shape({
name: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
placeholder: PropTypes.string,
type: PropTypes.string,
to: lazy(() => PropTypes.arrayOf(field)),
of: lazy(() => PropTypes.arrayOf(field))
})
const type = PropTypes.shape({
fields: PropTypes.arrayOf(field),
alias: PropTypes.string,
isPrimitive: PropTypes.bool
})
const validation = {
fields: PropTypes.objectOf(lazy(() => validation)),
messages: PropTypes.arrayOf(PropTypes.shape({
type: PropTypes.oneOf(['error', 'warning']),
id: PropTypes.string,
message: PropTypes.string
}))
}
const schema = PropTypes.objectOf(type)
export default {
type,
schema,
field,
validation
}
|
[FIX] Fix 'installable' syntax in manifest file | # © 2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Pdf watermark",
"version": "12.0.1.0.0",
"author": "Therp BV, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Technical Settings",
"summary": "Add watermarks to your QWEB PDF reports",
"website": "https://github.com/oca/reporting-engine",
"depends": [
'web',
],
"data": [
"demo/report.xml",
"views/ir_actions_report_xml.xml",
"views/layout_templates.xml",
],
"demo": [
"demo/report.xml"
],
"installable": True,
'external_dependencies': {
'python': [
'PyPDF2',
],
},
}
| # © 2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Pdf watermark",
"version": "12.0.1.0.0",
"author": "Therp BV, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Technical Settings",
"summary": "Add watermarks to your QWEB PDF reports",
"website": "https://github.com/oca/reporting-engine",
"depends": [
'web',
],
"data": [
"demo/report.xml",
"views/ir_actions_report_xml.xml",
"views/layout_templates.xml",
],
"demo": [
"demo/report.xml"
],
"intallable": True,
'external_dependencies': {
'python': [
'PyPDF2',
],
},
}
|
Handle sign in failure from traccar | import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
me = graphene.Field(lambda: UserType)
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
if r.status_code == 404:
raise GraphQLError('Authentication required')
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
| import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
me = graphene.Field(lambda: UserType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
|
Add OrderCreator to global scope | /**
* This file is part of Shuup.
*
* Copyright (c) 2012-2018, Shuup Inc. All rights reserved.
*
* This source code is licensed under the OSL-3.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
//-- jQuery
var jquery = require("jquery");
window.$ = window.jQuery = jquery;
const _ = require('lodash');
window._ = _;
window.Dropzone = require('dropzone');
Dropzone.autoDiscover = false;
window.OrderCreator = require('../../modules/orders/static_src/create/index.js');
window.Shepherd = require('tether-shepherd');
const m = require('mithril');
window.m = m;
import select2 from 'select2';
select2($);
require('bootstrap');
require('chart.js');
require('imagelightbox');
require('get-size');
require('desandro-matches-selector');
require('ev-emitter');
require('fizzy-ui-utils');
require('jquery.easing');
require('jquery.scrollbar');
require('moment');
require('outlayer');
require('popper.js');
require('summernote/dist/summernote-bs4.js');
require('tether');
require('@chenfengyuan/datepicker');
| /**
* This file is part of Shuup.
*
* Copyright (c) 2012-2018, Shuup Inc. All rights reserved.
*
* This source code is licensed under the OSL-3.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
//-- jQuery
var jquery = require("jquery");
window.$ = window.jQuery = jquery;
const _ = require('lodash');
window._ = _;
window.Dropzone = require('dropzone');
Dropzone.autoDiscover = false;
import select2 from 'select2';
select2($);
require('bootstrap');
require('chart.js');
require('imagelightbox');
require('get-size');
require('desandro-matches-selector');
require('ev-emitter');
require('fizzy-ui-utils');
require('jquery.easing');
require('jquery.scrollbar');
require('moment');
require('outlayer');
require('popper.js');
require('summernote/dist/summernote-bs4.js');
require('tether');
require('@chenfengyuan/datepicker');
window.Shepherd = require('tether-shepherd');
const m = require('mithril');
window.m = m;
|
Fix subscribe link in sidebar widget. | <?php
require_once 'mnw.php';
function mnw_subscribe_widget_register() {
register_sidebar_widget (__('mnw Subscribe'), 'mnw_subscribe_widget');
}
add_action('init', 'mnw_subscribe_widget_register');
function mnw_subscribe_widget($args) {
extract($args);
global $wpdb;
$count = $wpdb->get_var('SELECT COUNT(*) FROM ' . MNW_SUBSCRIBER_TABLE);
echo $before_widget;
?>
<div style="height: 45px; padding-left: 45px; background: transparent url(<?php echo get_template_directory_uri(); ?>/omb.png) no-repeat scroll left center;
text-align: right; font-size:170%;">
<?php printf(__ngettext('%d OMB subscriber', '%d OMB subscribers', $count, 'mnw'), $count); ?><br />
<a href="<?php echo get_option('mnw_themepage_url'); ?>"><?php _e('Subscribe!', 'mnw'); ?></a>
</div>
<?php
echo $after_widget;
}
?>
| <?php
require_once 'mnw.php';
function mnw_subscribe_widget_register() {
register_sidebar_widget (__('mnw Subscribe'), 'mnw_subscribe_widget');
}
add_action('init', 'mnw_subscribe_widget_register');
function mnw_subscribe_widget($args) {
extract($args);
global $wpdb;
$count = $wpdb->get_var('SELECT COUNT(*) FROM ' . MNW_SUBSCRIBER_TABLE);
echo $before_widget;
?>
<div style="height: 45px; padding-left: 45px; background: transparent url(<?php echo get_template_directory_uri(); ?>/omb.png) no-repeat scroll left center;
text-align: right; font-size:170%;">
<?php printf(__ngettext('%d OMB subscriber', '%d OMB subscribers', $count, 'mnw'), $count); ?><br />
<a href="<?php get_option('mnw_themepage_url'); ?>"><?php _e('Subscribe!', 'mnw'); ?></a>
</div>
<?php
echo $after_widget;
}
?>
|
Put back the authentication to pass Travis CI tests | // Load environment variables
if (process.env.NODE_ENV === 'development') {
require('dotenv').config({ path: './env/development.env' });
}
var express = require('express');
var passport = require('passport');
var util = require('./lib/utility.js');
var app = express();
// Initial Configuration, Static Assets, & View Engine Configuration
require('./config/initialize.js')(app, express);
// Authentication Middleware: Express Sessions, Passport Strategy
require('./config/auth.js')(app, express, passport);
// Pre-Authentication Routes & OAuth Requests
require('./routes/auth-routes.js')(app, passport);
//Authentication check currently commented out, uncomment line to re-activate
app.use(util.ensureAuthenticated);
// View Routes
require('./routes/view-routes.js')(app);
// API Routes
require('./routes/api-routes.js')(app);
// Wildcard route
app.get('/*', function(req, res) {
res.redirect('/');
})
app.listen(Number(process.env.PORT), process.env.HOST, function() {
console.log('NODE_ENV: ' + process.env.NODE_ENV);
console.log(process.env.APP_NAME + ' is listening at ' + process.env.HOST + ' on port ' + process.env.PORT + '.')
}); | // Load environment variables
if (process.env.NODE_ENV === 'development') {
require('dotenv').config({ path: './env/development.env' });
}
var express = require('express');
var passport = require('passport');
var util = require('./lib/utility.js');
var app = express();
// Initial Configuration, Static Assets, & View Engine Configuration
require('./config/initialize.js')(app, express);
// Authentication Middleware: Express Sessions, Passport Strategy
require('./config/auth.js')(app, express, passport);
// Pre-Authentication Routes & OAuth Requests
require('./routes/auth-routes.js')(app, passport);
//Authentication check currently commented out, uncomment line to re-activate
// app.use(util.ensureAuthenticated);
// View Routes
require('./routes/view-routes.js')(app);
// API Routes
require('./routes/api-routes.js')(app);
// Wildcard route
app.get('/*', function(req, res) {
res.redirect('/');
})
app.listen(Number(process.env.PORT), process.env.HOST, function() {
console.log('NODE_ENV: ' + process.env.NODE_ENV);
console.log(process.env.APP_NAME + ' is listening at ' + process.env.HOST + ' on port ' + process.env.PORT + '.')
}); |
Fix case: tostring to toString | define(function() {
'use strict';
return function(item) {
return item.getBytes().then(function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (dv.getUint32(0, false) !== bytes.length) {
return Promise.reject('length does not match data');
}
var previousData = new Uint8Array(256 * 2);
var dataObject = [];
var pos = 4;
while (pos < bytes.length) {
var endPos = pos + dv.getUint16(pos);
if (endPos === pos) break;
pos += 2;
while (pos < endPos) {
var patchLength = bytes[pos] * 2, patchOffset = bytes[pos + 1] * 2;
pos += 2;
var patch = bytes.subarray(pos, pos + patchLength);
pos += patchLength;
dataObject.push({
offset: patchOffset,
patch: [].map.call(patch, function(v) {
return ('0' + v.toString(16)).slice(-2);
}).join(' '),
});
}
}
item.setDataObject(dataObject);
});
};
});
| define(function() {
'use strict';
return function(item) {
return item.getBytes().then(function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (dv.getUint32(0, false) !== bytes.length) {
return Promise.reject('length does not match data');
}
var previousData = new Uint8Array(256 * 2);
var dataObject = [];
var pos = 4;
while (pos < bytes.length) {
var endPos = pos + dv.getUint16(pos);
if (endPos === pos) break;
pos += 2;
while (pos < endPos) {
var patchLength = bytes[pos] * 2, patchOffset = bytes[pos + 1] * 2;
pos += 2;
var patch = bytes.subarray(pos, pos + patchLength);
pos += patchLength;
dataObject.push({
offset: patchOffset,
patch: [].map.call(patch, function(v) {
return ('0' + v.tostring(16)).slice(-2);
}).join(' '),
});
}
}
item.setDataObject(dataObject);
});
};
});
|
Check jQuery dependency, minor syntax adjustments | if (typeof jQuery === 'undefined') {
throw new Error('The jQuery equal height extension requires jQuery!');
}
jQuery.fn.equalHeight = function() {
var $ = jQuery;
var that = this;
var setHeights = function() {
var elems = {};
var cont = $(that);
// Reset the elements heights
cont.each(function() {
$(this).height('');
});
// Create a mapping of elements and the max height for all elements at that top offset
cont.each(function() {
var t = $(this).offset().top;
if (typeof elems[t] == "undefined") elems[t] = {maxHeight: 0, e: []};
elems[t].e.push($(this));
elems[t].maxHeight = Math.max($(this).outerHeight(), elems[t].maxHeight);
});
// Apply the max height to all elements in each offset class
for (var t in elems) {
var mh = elems[t].maxHeight;
for (var i in elems[t].e) {
var e = elems[t].e[i];
var padding = e.outerHeight() - e.height();
e.height(mh - padding);
}
}
}
setHeights();
setTimeout(setHeights, 100); // Set heights after page elements have rendered, is there a more elegant way to do this?
$(window).resize(setHeights);
};
| jQuery.fn.equalHeight = function() {
var $ = jQuery;
var that = this;
var setHeights = function() {
var elems = {};
var cont = $(that);
// Reset the elements heights
cont.each(function() {
$(this).height('');
});
// Create a mapping of elements and the max height for all elements at that top offset
cont.each(function() {
var t = $(this).offset().top;
if (typeof elems[t] == "undefined") elems[t] = {maxHeight: 0, e: []};
elems[t].e.push($(this));
elems[t].maxHeight = Math.max($(this).outerHeight(), elems[t].maxHeight);
});
// Apply the max height to all elements in each offset class
for (t in elems) {
var mh = elems[t].maxHeight;
for (i in elems[t].e) {
var e = elems[t].e[i];
var padding = e.outerHeight() - e.height();
e.height(mh - padding);
}
}
}
setHeights();
setTimeout(setHeights, 100); // Set heights after page elements have rendered, is there a more elegant way to do this?
$(window).resize(setHeights);
}
|
Delete message more verbose: title included | $(function() {
$('a.deleteShow').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
var title = $(this).closest('tr').find('td:eq(1)').text();
var userConfig = {
captionOk: 'Yes',
captionCancel: 'No',
title: 'Confirmation',
onOk: function() {
location.href = url;
}
};
var cd = new ConfirmationDialog('Really delete "' + title +'"?', userConfig);
cd.show();
});
$('a.searchShow').click(function(e) {
e.preventDefault();
var provider = $('#searchProvider').val();
var url = $(this).attr('href') + provider;
location.href = url;
});
});
| $(function() {
$('a.deleteShow').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
var userConfig = {
captionOk: 'Yes',
captionCancel: 'No',
title: 'Confirmation',
onOk: function() {
location.href = url;
}
};
var cd = new ConfirmationDialog('Really delete this show?', userConfig);
cd.show();
});
$('a.searchShow').click(function(e) {
e.preventDefault();
var provider = $('#searchProvider').val();
var url = $(this).attr('href') + provider;
location.href = url;
});
});
|
Add function to TaxonPresenter to resolve view template path from request
Still uses the selected tab for the template name, but now looks for the
template in a directory names after the base path.
e.g. - '/taxons/:taxonSlug' will render templates from 'app/views/taxons' | var taxonHelpers = require('../helpers/taxon-helpers.js');
var filterHelpers = require('../helpers/filter-helpers.js');
function TaxonPresenter (taxonSlug, request) {
this.taxonSlug = taxonSlug; // the slug of the taxon in the Content Store
this.selectedTab = request.query.tab;
if (this.selectedTab == undefined) { this.selectedTab = 'guidance' }; //default view
this.pageTitle = taxonHelpers.fetchCurrentTaxonTitle(this.taxonSlug);
// Fetch appropriate taxonomy data
this.childTaxons = taxonHelpers.fetchChildTaxons(this.taxonSlug);
this.parentTaxon = taxonHelpers.fetchParentTaxon(this.taxonSlug);
this.allContent = taxonHelpers.fetchTaggedItems(this.taxonSlug);
this.determineContentList = function () {
switch (this.selectedTab) {
case 'all':
return this.allContent; break;
default:
return filterHelpers.sectionFilter(this.allContent, this.selectedTab);
}
};
this.contentListToRender = this.determineContentList();
this.curatedContent = this.contentListToRender.slice(0,6);
this.latestContent = this.contentListToRender.slice(0,3);
this.resolveViewTemplateName = function () {
return request.path.replace(this.taxonSlug, '').replace(/^\//, '') + this.selectedTab;
};
this.viewTemplateName = this.resolveViewTemplateName();
}
module.exports = TaxonPresenter;
| var taxonHelpers = require('../helpers/taxon-helpers.js');
var filterHelpers = require('../helpers/filter-helpers.js');
function TaxonPresenter (taxonSlug, request) {
this.taxonSlug = taxonSlug; // the slug of the taxon in the Content Store
this.selectedTab = request.query.tab;
if (this.selectedTab == undefined) { this.selectedTab = 'guidance' }; //default view
this.pageTitle = taxonHelpers.fetchCurrentTaxonTitle(this.taxonSlug);
// Fetch appropriate taxonomy data
this.childTaxons = taxonHelpers.fetchChildTaxons(this.taxonSlug);
this.parentTaxon = taxonHelpers.fetchParentTaxon(this.taxonSlug);
this.allContent = taxonHelpers.fetchTaggedItems(this.taxonSlug);
this.determineContentList = function () {
switch (this.selectedTab) {
case 'all':
return this.allContent; break;
default:
return filterHelpers.sectionFilter(this.allContent, this.selectedTab);
}
};
this.contentListToRender = this.determineContentList();
this.curatedContent = this.contentListToRender.slice(0,6);
this.latestContent = this.contentListToRender.slice(0,3);
}
module.exports = TaxonPresenter;
|
Fix initialization of the Set trough comma separated values | package af.props;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Getter;
import lombok.Setter;
/**
* Java collections.
* <p>
* The {@code set} field has the setter to support initialization from a string of comma separated values.
*
* @author Alessandro Falappa
*/
@ConfigurationProperties(prefix = "collections")
public class CollectionsProperties {
/**
* A set of doubles.
*/
@Getter
@Setter
private Set<Double> set = new HashSet<>();
/**
* A list of strings.
*/
@Getter
private List<String> list = new ArrayList<>();
/**
* A map of strings indexed by integers.
*/
@Getter
private Map<Integer, String> map = new HashMap<>();
}
| package af.props;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Getter;
/**
* Java collections.
* <p>
* As per documentation only field getters are needed.
*
* @author Alessandro Falappa
*/
@ConfigurationProperties(prefix = "collections")
@Getter
public class CollectionsProperties {
/**
* A set of doubles.
*/
private Set<Double> set = new HashSet<>();
/**
* A list of strings.
*/
private List<String> list = new ArrayList<>();
/**
* A map of strings indexed by integers.
*/
private Map<Integer, String> map = new HashMap<>();
}
|
Use proper PSR4 in example | <?php
use laserred\lrcpt;
class ExampleCPT extends lrcpt{
public $name;
public $labels = array('name' => 'Blaa');
public $args = array();
public $metaboxes = array();
/**
* Call the parent constuctor to do all the work.
*/
public function __construct(){
$this->metaboxes[] = array(
'id' => 'blaa',
'title' => 'blaa',
'pages' => 'blaa',
'fields' => array(
array(
'id' => 'sometext',
'name' => 'Some text',
'type' => 'text',
'cols' => 3
),
)
);
PARENT::__construct();
}
}
| <?php
class ExampleCPT extends LRCPT{
public $name;
public $labels = array('name' => 'Blaa');
public $args = array();
public $metaboxes = array();
/**
* Call the parent constuctor to do all the work.
*/
public function __construct(){
$this->metaboxes[] = array(
'id' => 'blaa',
'title' => 'blaa',
'pages' => 'blaa',
'fields' => array(
array(
'id' => 'sometext',
'name' => 'Some text',
'type' => 'text',
'cols' => 3
),
)
);
PARENT::__construct();
}
}
|
Make the printing of sqlite version in verbose mode work with regrtest -w. | import test.support
# Skip test if _sqlite3 module not installed
test.support.import_module('_sqlite3')
import sqlite3
from sqlite3.test import (dbapi, types, userfunctions,
factory, transactions, hooks, regression,
dump)
def test_main():
if test.support.verbose:
print("test_sqlite: testing with version",
"{!r}, sqlite_version {!r}".format(sqlite3.version,
sqlite3.sqlite_version))
test.support.run_unittest(dbapi.suite(), types.suite(),
userfunctions.suite(),
factory.suite(), transactions.suite(),
hooks.suite(), regression.suite(),
dump.suite())
if __name__ == "__main__":
test_main()
| from test.support import run_unittest, import_module, verbose
# Skip test if _sqlite3 module not installed
import_module('_sqlite3')
import sqlite3
from sqlite3.test import (dbapi, types, userfunctions,
factory, transactions, hooks, regression,
dump)
def test_main():
if verbose:
print("test_sqlite: testing with version",
"{!r}, sqlite_version {!r}".format(sqlite3.version,
sqlite3.sqlite_version))
run_unittest(dbapi.suite(), types.suite(), userfunctions.suite(),
factory.suite(), transactions.suite(),
hooks.suite(), regression.suite(), dump.suite())
if __name__ == "__main__":
test_main()
|
[wapitit] Add one signature for wapiti 2.2.1 | """
Wapiti does not provide ranking for the vulnerabilities it has found.
This file tries to define a ranking for every vulnerability Wapiti might
find.
"""
from libptp.constants import HIGH, MEDIUM, LOW, INFO
SIGNATURES = {
# High ranked vulnerabilities
'SQL Injection': HIGH,
'Blind SQL Injection': HIGH,
'Command execution': HIGH,
# Medium ranked vulnerabilities
'Htaccess Bypass': MEDIUM,
'Cross Site Scripting': MEDIUM,
'CRLF Injection': MEDIUM,
'CRLF': MEDIUM,
# Low ranked vulnerabilities
'File Handling': LOW, # a.k.a Path or Directory listing
'Resource consumption': LOW, # TODO: Is this higher than LOW?
# Informational ranked vulnerabilities
'Backup file': INFO,
'Potentially dangerous file': INFO, # TODO: Is this higher than INFO?
'Internal Server Error': INFO,
}
| """
Wapiti does not provide ranking for the vulnerabilities it has found.
This file tries to define a ranking for every vulnerability Wapiti might
find.
"""
from libptp.constants import HIGH, MEDIUM, LOW, INFO
SIGNATURES = {
# High ranked vulnerabilities
'SQL Injection': HIGH,
'Blind SQL Injection': HIGH,
'Command execution': HIGH,
# Medium ranked vulnerabilities
'Htaccess Bypass': MEDIUM,
'Cross Site Scripting': MEDIUM,
'CRLF Injection': MEDIUM,
# Low ranked vulnerabilities
'File Handling': LOW, # a.k.a Path or Directory listing
'Resource consumption': LOW, # TODO: Is this higher than LOW?
# Informational ranked vulnerabilities
'Backup file': INFO,
'Potentially dangerous file': INFO, # TODO: Is this higher than INFO?
'Internal Server Error': INFO,
}
|
Fix ohe type in ce | """ Contains base tf losses """
import tensorflow as tf
def softmax_cross_entropy(labels, logits, *args, **kwargs):
""" Multi-class CE which takes plain or one-hot labels
Parameters
----------
labels : tf.Tensor
logits : tf.Tensor
args
other positional parameters from `tf.losses.softmax_cross_entropy`
kwargs
other named parameters from `tf.losses.softmax_cross_entropy`
Returns
-------
tf.Tensor
"""
labels_shape = tf.shape(labels)
logits_shape = tf.shape(logits)
c = tf.cast(tf.equal(labels_shape, logits_shape), tf.int32)
e = tf.equal(tf.reduce_sum(c, axis=-1), logits_shape.shape[-1])
labels = tf.cond(e, lambda: tf.cast(labels, dtype=logits.dtype),
lambda: tf.one_hot(tf.cast(labels, tf.int32), logits_shape[-1], dtype=logits.dtype))
return tf.losses.softmax_cross_entropy(labels, logits, *args, **kwargs)
| """ Contains base tf losses """
import tensorflow as tf
def softmax_cross_entropy(labels, logits, *args, **kwargs):
""" Multi-class CE which takes plain or one-hot labels
Parameters
----------
labels : tf.Tensor
logits : tf.Tensor
args
other positional parameters from `tf.losses.softmax_cross_entropy`
kwargs
other named parameters from `tf.losses.softmax_cross_entropy`
Returns
-------
tf.Tensor
"""
labels_shape = tf.shape(labels)
logits_shape = tf.shape(logits)
c = tf.cast(tf.equal(labels_shape, logits_shape), tf.int32)
e = tf.equal(tf.reduce_sum(c, axis=-1), logits_shape.shape[-1])
labels = tf.cond(e, lambda: tf.cast(labels, dtype=logits.dtype),
lambda: tf.one_hot(labels, logits_shape[-1], dtype=logits.dtype))
return tf.losses.softmax_cross_entropy(labels, logits, *args, **kwargs)
|
Add CSRF filter to '/profile' Route. | <?php
/**
* Routes - all standard routes are defined here.
*
* @author David Carr - dave@daveismyname.com
* @version 3.0
*/
use Core\Router;
use Helpers\Hooks;
/** Define static routes. */
// Default Routing
Router::any('', 'App\Controllers\Welcome@index');
Router::any('subpage', 'App\Controllers\Welcome@subPage');
Router::any('admin/(:any)(/(:any)(/(:any)(/(:all))))', array(
'filters' => 'test',
'uses' => 'App\Controllers\Demo@test'
));
// The default Auth Routes.
Router::any('login', array('filters' => 'guest|csrf', 'uses' => 'App\Controllers\Users@login'));
Router::get('logout', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@logout'));
// The User's Dashboard.
Router::get('dashboard', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@dashboard'));
// The User's Profile.
Router::any('profile', array('filters' => 'auth|csrf', 'uses' => 'App\Controllers\Users@profile'));
// The Framework's Language Changer.
Router::any('language/(:any)', 'App\Controllers\Language@change');
/** End default Routes */
/** Module Routes. */
$hooks = Hooks::get();
$hooks->run('routes');
/** End Module Routes. */
| <?php
/**
* Routes - all standard routes are defined here.
*
* @author David Carr - dave@daveismyname.com
* @version 3.0
*/
use Core\Router;
use Helpers\Hooks;
/** Define static routes. */
// Default Routing
Router::any('', 'App\Controllers\Welcome@index');
Router::any('subpage', 'App\Controllers\Welcome@subPage');
Router::any('admin/(:any)(/(:any)(/(:any)(/(:all))))', array(
'filters' => 'test',
'uses' => 'App\Controllers\Demo@test'
));
// The default Auth Routes.
Router::any('login', array('filters' => 'guest|csrf', 'uses' => 'App\Controllers\Users@login'));
Router::get('logout', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@logout'));
// The User's Dashboard.
Router::get('dashboard', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@dashboard'));
// The User's Profile.
Router::any('profile', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@profile'));
// The Framework's Language Changer.
Router::any('language/(:any)', 'App\Controllers\Language@change');
/** End default Routes */
/** Module Routes. */
$hooks = Hooks::get();
$hooks->run('routes');
/** End Module Routes. */
|
Fix an edge case when a file is dropped outside <body> | import union from 'lodash/array/union';
import without from 'lodash/array/without';
export default class EnterLeaveCounter {
constructor() {
this.entered = [];
}
enter(enteringNode) {
this.entered = union(
this.entered.filter(node =>
document.documentElement.contains(node) &&
(!node.contains || node.contains(enteringNode))
),
[enteringNode]
);
return this.entered.length === 1;
}
leave(leavingNode) {
this.entered = without(
this.entered.filter(node =>
document.documentElement.contains(node)
),
leavingNode
);
return this.entered.length === 0;
}
reset() {
this.entered = [];
}
}
| import union from 'lodash/array/union';
import without from 'lodash/array/without';
export default class EnterLeaveCounter {
constructor() {
this.entered = [];
}
enter(enteringNode) {
this.entered = union(
this.entered.filter(node =>
document.body.contains(node) &&
(!node.contains || node.contains(enteringNode))
),
[enteringNode]
);
return this.entered.length === 1;
}
leave(leavingNode) {
this.entered = without(
this.entered.filter(node =>
document.body.contains(node)
),
leavingNode
);
return this.entered.length === 0;
}
reset() {
this.entered = [];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.