text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Support symfony2 instances running in subfolders
<?php namespace Rednose\FrameworkBundle\Cache; /** * Public cache instance */ class PublicCacheInstance extends CacheInstance implements CacheInstanceInterface { /** * @var string */ protected $cacheName; /** * @var string */ protected $publicPath; /** * Constructor * * @param string $cacheName * @param string $publicPath * @param string $rootPath */ public function __construct($cacheName, $publicPath, $rootPath) { $this->cacheName = $cacheName; $this->publicPath = $publicPath; $publicPath = substr($publicPath, strpos($publicPath, '/cache')); parent::__construct($rootPath.$publicPath, $cacheName); } /** * {@inheritdoc} */ public function getPublicUrl() { return $this->publicPath . '/' . $this->cacheName; } /** * {@inheritdoc} */ public function isPublic() { return false; } }
<?php namespace Rednose\FrameworkBundle\Cache; /** * Public cache instance */ class PublicCacheInstance extends CacheInstance implements CacheInstanceInterface { /** * @var string */ protected $cacheName; /** * @var string */ protected $publicPath; /** * Constructor * * @param string $cacheName * @param string $publicPath * @param string $rootPath */ public function __construct($cacheName, $publicPath, $rootPath) { $this->cacheName = $cacheName; $this->publicPath = $publicPath; parent::__construct($rootPath.$publicPath, $cacheName); } /** * {@inheritdoc} */ public function getPublicUrl() { return $this->publicPath.'/'.$this->cacheName; } /** * {@inheritdoc} */ public function isPublic() { return false; } }
Remove unneeded block in define.
import json import random import pprint class Noah(object): def __init__(self, dictionary_file): self.dictionary = json.load(dictionary_file) def list(self): return '\n'.join([entry['word'] for entry in self.dictionary]) def define(self, word): return self.output(filter(lambda x: x['word'] == word, self.dictionary)) def random(self): return self.output(random.choice(self.dictionary)) def output(self, data): return json.dumps(data, indent=4) def main(): with open('../dictionaries/english.json') as dictionary: n = Noah(dictionary) print n.list() print n.define('run') print n.random() if __name__ == '__main__': main()
import json import random import pprint class Noah(object): def __init__(self, dictionary_file): self.dictionary = json.load(dictionary_file) def list(self): return '\n'.join([entry['word'] for entry in self.dictionary]) def define(self, word): return self.output(filter(lambda x: x['word'] == word, self.dictionary)) if not entry is None: return self.output(entry) def random(self): return self.output(random.choice(self.dictionary)) def output(self, data): return json.dumps(data, indent=4) def main(): with open('../dictionaries/english.json') as dictionary: n = Noah(dictionary) print n.list() print n.define('run') print n.random() if __name__ == '__main__': main()
Fix a bug where the widgets of an open page would reload when hovered
import React from 'react'; import PropTypes from 'prop-types'; import { VegaChart, getVegaTheme } from 'widget-editor'; // /widget_data.json?widget_id= class WidgetBlock extends React.Component { constructor(props) { super(props); this.widgetConfig = null; this.state = { loading: true, widget: null }; } componentWillMount() { const { item } = this.props; this.getChart(item.content.widgetId); } shouldComponentUpdate(nextProps, nextState) { // This fixes a bug where the widgets would reload when hovering them return this.state !== nextState || this.props.item.content.widgetId !== nextProps.item.content.widgetId; } getChart(widgetId) { fetch(`${window.location.origin}/widget_data.json?widget_id=${widgetId}`).then((res) => { return res.json(); }).then((widget) => { this.setState({ loading: false, widget }); }); } render() { if (this.state.loading) { return null; } return ( <VegaChart data={this.state.widget.visualization} theme={getVegaTheme()} reloadOnResize /> ); } } WidgetBlock.propTypes = { item: PropTypes.object.isRequired }; export default WidgetBlock;
import React from 'react'; import PropTypes from 'prop-types'; import { VegaChart, getVegaTheme } from 'widget-editor'; // /widget_data.json?widget_id= class WidgetBlock extends React.Component { constructor(props) { super(props); this.widgetConfig = null; this.state = { loading: true, widget: null }; } componentWillMount() { const { item } = this.props; this.getChart(item.content.widgetId); } getChart(widgetId) { fetch(`${window.location.origin}/widget_data.json?widget_id=${widgetId}`).then((res) => { return res.json(); }).then((widget) => { this.setState({ loading: false, widget }); }); } render() { if (this.state.loading) { return null; } return ( <VegaChart data={this.state.widget.visualization} theme={getVegaTheme()} reloadOnResize /> ); } } WidgetBlock.propTypes = { item: PropTypes.object.isRequired }; export default WidgetBlock;
Update contact details to the company
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='blanc-contentfiles', version='0.2.1', description='Blanc Content Files', long_description=open('README.rst').read(), url='https://github.com/blancltd/blanc-contentfiles', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='blanc-contentfiles', version='0.2.1', description='Blanc Content Files', long_description=open('README.rst').read(), url='https://github.com/blancltd/blanc-contentfiles', maintainer='Alex Tomkins', maintainer_email='alex@blanc.ltd.uk', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
Revert "Scaling crash testing twitFeed" This reverts commit 3216af3058e496f249781cf97e94359e01d7fa82.
Meteor.methods({ fetchInstaApi: function(){ /*var instaDebounce = _.debounce(Meteor.bindEnvironment(function(){ var ig = Meteor.npmRequire('instagram-node').instagram(); ig.use({ access_token: Meteor.settings.instagram.access_token }); ig.user_self_media_recent(Meteor.bindEnvironment(function(err, medias, pagination, remaining, limit) { if(!err){ medias.forEach(function(entry){ if(entry.tags.indexOf("webonaut") > -1 || entry.tags.indexOf("Webonaut") > -1){ Meteor.call('addInsta', entry) ; } }) } }, 60 * 1000)); })); instaDebounce();*/ } });
Meteor.methods({ fetchInstaApi: function(){ var instaDebounce = _.debounce(Meteor.bindEnvironment(function(){ var ig = Meteor.npmRequire('instagram-node').instagram(); ig.use({ access_token: Meteor.settings.instagram.access_token }); ig.user_self_media_recent(Meteor.bindEnvironment(function(err, medias, pagination, remaining, limit) { if(!err){ medias.forEach(function(entry){ if(entry.tags.indexOf("webonaut") > -1 || entry.tags.indexOf("Webonaut") > -1){ Meteor.call('addInsta', entry) ; } }) } }, 60 * 1000)); })); instaDebounce(); } });
Make font rendering mono (disable anti-aliasing to keep pixel looknfeel
package tv.rocketbeans.supermafiosi.graphics; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; import de.bitbrain.braingdx.assets.SharedAssetManager; public class BitmapFontBaker { public static BitmapFont bake(String fontPath, int fontSize) { FreeTypeFontGenerator generator = SharedAssetManager.getInstance().get(fontPath, FreeTypeFontGenerator.class); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = fontSize; parameter.mono = true; parameter.color = Color.WHITE.cpy(); BitmapFont font = generator.generateFont(parameter); return font; } }
package tv.rocketbeans.supermafiosi.graphics; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; import de.bitbrain.braingdx.assets.SharedAssetManager; public class BitmapFontBaker { public static BitmapFont bake(String fontPath, int fontSize) { FreeTypeFontGenerator generator = SharedAssetManager.getInstance().get(fontPath, FreeTypeFontGenerator.class); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = fontSize; parameter.mono = false; parameter.color = Color.WHITE.cpy(); BitmapFont font = generator.generateFont(parameter); return font; } }
Check the test repo is created correctly
package pro.cucumber; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public abstract class RevisionProviderContract { private Path rootPath; @Before public void createScm() throws IOException { rootPath = Files.createTempDirectory("GitWC"); Path subfolder = rootPath.resolve("subfolder"); Files.createDirectory(subfolder); Files.createFile(subfolder.resolve("file")); Exec.cmd("git init", rootPath); Exec.cmd("git add -A", rootPath); Exec.cmd("git commit -am \"files\"", rootPath); List<String> status = Exec.cmd("git status --porcelain", rootPath); assertEquals(new ArrayList<String>(), status); } @Test public void findsRev() { String sha1Pattern = "^[a-f0-9]{40}$"; RevisionProvider revisionProvider = makeRevisionProvider(rootPath); String rev = revisionProvider.getRev(); assertTrue("Expected a sha1, got: " + rev, Pattern.matches(sha1Pattern, rev)); } protected abstract RevisionProvider makeRevisionProvider(Path rootPath); }
package pro.cucumber; import org.junit.Before; import org.junit.Test; import pro.cucumber.gitcli.GitCliRevisionProvider; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; public abstract class RevisionProviderContract { private Path rootPath; @Before public void createScm() throws IOException { rootPath = Files.createTempDirectory("GitWC"); Path subfolder = rootPath.resolve("subfolder"); Files.createDirectory(subfolder); Files.createFile(subfolder.resolve("file")); Exec.cmd("git init", rootPath); Exec.cmd("git add -A", rootPath); Exec.cmd("git commit -am \"files\"", rootPath); } @Test public void findsRev() { String sha1Pattern = "^[a-f0-9]{40}$"; RevisionProvider revisionProvider = makeRevisionProvider(rootPath); String rev = revisionProvider.getRev(); assertTrue("Expected a sha1, got: "+rev, Pattern.matches(sha1Pattern, rev)); } protected abstract RevisionProvider makeRevisionProvider(Path rootPath); }
Fix copyright on new file
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.util; import com.google.common.collect.ImmutableSet; import java8.util.stream.Collector; import java8.util.stream.Collectors; /** * Custom collector for compatibility between {@link Collector} compat class and Guava {@link * ImmutableSet}. */ public abstract class ImmutableSetCollector { /** Do not instantiate. */ private ImmutableSetCollector() {} private static final Collector<Object, ?, ImmutableSet<Object>> TO_IMMUTABLE_SET = Collectors.of( ImmutableSet::builder, ImmutableSet.Builder::add, (a, b) -> { throw new UnsupportedOperationException(); }, ImmutableSet.Builder::build); /** Returns a {@link Collector} that accumulates the input elements into a new ImmutableSet. */ public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() { return (Collector) TO_IMMUTABLE_SET; } }
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.util; import com.google.common.collect.ImmutableSet; import java8.util.stream.Collector; import java8.util.stream.Collectors; /** * Custom collector for compatibility between {@link Collector} compat class and Guava {@link * ImmutableSet}. */ public abstract class ImmutableSetCollector { /** Do not instantiate. */ private ImmutableSetCollector() {} private static final Collector<Object, ?, ImmutableSet<Object>> TO_IMMUTABLE_SET = Collectors.of( ImmutableSet::builder, ImmutableSet.Builder::add, (a, b) -> { throw new UnsupportedOperationException(); }, ImmutableSet.Builder::build); /** Returns a {@link Collector} that accumulates the input elements into a new ImmutableSet. */ public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() { return (Collector) TO_IMMUTABLE_SET; } }
[Genomics]: Make it easier to run the RealignerTargetCreator on a single file. RealignerTargetCreator is not scatter-gatherable, so we thus have to merge the SAM files before obtaining the targets. See: http://gatkforums.broadinstitute.org/gatk/discussion/1975/how-can-i-use-parallelism-to-make-gatk-tools-run-faster for more information,
package com.github.sparkcaller.preprocessing; import com.github.sparkcaller.BaseGATKProgram; import com.github.sparkcaller.Utils; import org.apache.spark.api.java.function.Function; import scala.Tuple2; import java.io.File; import java.util.ArrayList; /* * Minimize the amount of mismatching bases across all reads. * * See: * https://www.broadinstitute.org/gatk/gatkdocs/org_broadinstitute_gatk_tools_walkers_indels_RealignerTargetCreator.php * * For more information. * */ public class IndelTargetCreator extends BaseGATKProgram { public IndelTargetCreator(String pathToReference, String extraArgsString, String coresPerNode) { super("RealignerTargetCreator", extraArgsString); setReference(pathToReference); addArgument("-nt", coresPerNode); // The target creator is better optimized for multiple data threads. } public File createTargets(File file) throws Exception { setInputFile(file.getPath()); final String outputIntervalsFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-target.intervals"; File outputIntervalsFile = new File(outputIntervalsFilename); setOutputFile(outputIntervalsFile.getPath()); executeProgram(); return outputIntervalsFile; } }
package com.github.sparkcaller.preprocessing; import com.github.sparkcaller.BaseGATKProgram; import com.github.sparkcaller.Utils; import org.apache.spark.api.java.function.Function; import scala.Tuple2; import java.io.File; import java.util.ArrayList; /* * Minimize the amount of mismatching bases across all reads. * * See: * https://www.broadinstitute.org/gatk/gatkdocs/org_broadinstitute_gatk_tools_walkers_indels_RealignerTargetCreator.php * * For more information. * */ public class IndelTargetCreator extends BaseGATKProgram implements Function<File, Tuple2<File, File>> { public IndelTargetCreator(String pathToReference, String extraArgsString, String coresPerNode) { super("RealignerTargetCreator", extraArgsString); setReference(pathToReference); addArgument("-nt", coresPerNode); // The target creator is better optimized for multiple data threads. } public Tuple2<File, File> call(File file) throws Exception { setInputFile(file.getPath()); final String outputIntervalsFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-target.intervals"; File outputIntervalsFile = new File(outputIntervalsFilename); setOutputFile(outputIntervalsFile.getPath()); executeProgram(); return new Tuple2<File, File>(file, outputIntervalsFile); } }
Update the version to 3.0.0
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (3, 0, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (2, 9, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
Set is_public on create note
<?php namespace AppBundle\Controller; use AppBundle\Entity\Note; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Symfony\Component\HttpFoundation\Response; class NoteController extends Controller { /** * @Route("/note") */ public function indexAction() { $notes = $this->getDoctrine() ->getRepository('AppBundle:Note') ->findAll(); return $this->render( 'note/index.html.twig', array('notes' => $notes) ); } /** * @Route("/note/create") */ public function createAction() { $note = new Note(); $note->setContent('My very first note'); $note->setIsPublic(true); $em = $this->getDoctrine()->getManager(); $em->persist($note); $em->flush(); return new Response('Created note id '.$note->getId()); } }
<?php namespace AppBundle\Controller; use AppBundle\Entity\Note; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; class NoteController extends Controller { /** * @Route("/note") */ public function indexAction() { $notes = $this->getDoctrine() ->getRepository('AppBundle:Note') ->findAll(); return $this->render( 'note/index.html.twig', array('notes' => $notes) ); } /** * @Route("/note/{id}") * @ParamConverter("note", class="AppBundle:Note") */ public function showAction(Note $note) { } /** * @Route("/note/create") */ public function createAction() { $note = new Note(); $note->setContent('My very first note'); $em = $this->getDoctrine()->getManager(); $em->persist($note); $em->flush(); return new Response('Created note id '.$note->getId()); } }
Use plupload.dev.js instead of full, as it contains fixes for PUT option.
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-plupload', included: function (app) { this._super.included(app); if (process.env.EMBER_ENV === 'development') { app.import('bower_components/plupload/js/moxie.js'); app.import('bower_components/plupload/js/plupload.dev.js'); } else { app.import('bower_components/plupload/js/plupload.dev.js'); } app.import('bower_components/plupload/js/Moxie.swf', { destDir: 'assets' }); app.import('bower_components/plupload/js/Moxie.xap', { destDir: 'assets' }); app.import('bower_components/dinosheets/dist/dinosheets.amd.js', { exports: { 'dinosheets': ['default'] } }); app.import('vendor/styles/ember-plupload.css'); } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-plupload', included: function (app) { this._super.included(app); if (process.env.EMBER_ENV === 'development') { app.import('bower_components/plupload/js/moxie.js'); app.import('bower_components/plupload/js/plupload.dev.js'); } else { app.import('bower_components/plupload/js/plupload.full.min.js'); } app.import('bower_components/plupload/js/Moxie.swf', { destDir: 'assets' }); app.import('bower_components/plupload/js/Moxie.xap', { destDir: 'assets' }); app.import('bower_components/dinosheets/dist/dinosheets.amd.js', { exports: { 'dinosheets': ['default'] } }); app.import('vendor/styles/ember-plupload.css'); } };
Add a new category: Estabelecimentos comerciais
<?php /* * This file is part of Bens Penhorados, an undergraduate capstone project. * * (c) Fábio Santos <ffsantos92@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Seeder; class ItemCategoriesTableSeeder extends Seeder { public function run() { DB::table('item_categories')->delete(); $categories = [ ['name' => 'Veículos', 'slug' => 'veiculos', 'code' => '01'], ['name' => 'Imóveis', 'slug' => 'imoveis', 'code' => '02'], ['name' => 'Participações sociais', 'slug' => 'participacoes-sociais', 'code' => '05'], ['name' => 'Estabelecimentos comerciais', 'estabelecimentos-comerciais', 'code' => '08'], ['name' => 'Outros', 'slug' => 'outros', 'code' => '09'], ]; DB::table('item_categories')->insert($categories); } }
<?php /* * This file is part of Bens Penhorados, an undergraduate capstone project. * * (c) Fábio Santos <ffsantos92@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Seeder; class ItemCategoriesTableSeeder extends Seeder { public function run() { DB::table('item_categories')->delete(); $categories = [ ['name' => 'Veículos', 'slug' => 'veiculos', 'code' => '01'], ['name' => 'Imóveis', 'slug' => 'imoveis', 'code' => '02'], ['name' => 'Participações sociais', 'slug' => 'part-sociais', 'code' => '05'], ['name' => 'Outros', 'slug' => 'outros', 'code' => '09'], ]; DB::table('item_categories')->insert($categories); } }
Fix the build to test Hudson git-svn-id: ec6ef1d57ec0831ce4cbff3b75527511e63bfbe3@736937 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jsecurity.util; /** * Interface implemented by components that can be named, such as via configuration, and wish to have that name * set once it has been configured. * * @author Les Hazlewood * @since 0.9 */ public interface Nameable { /** * Sets the (preferably application unique) name for this component. * @param name the preferably application unique name for this component. */ void setName(String name); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jsecurity.util; BREAK BUILD /** * Interface implemented by components that can be named, such as via configuration, and wish to have that name * set once it has been configured. * * @author Les Hazlewood * @since 0.9 */ public interface Nameable { /** * Sets the (preferably application unique) name for this component. * @param name the preferably application unique name for this component. */ void setName(String name); }
Add TODO comment for get_data_index
import numpy as np import pandas def main(): data = pandas.read_csv('sarcasm_v2.csv').as_matrix() # print(data.shape) data[:, 0] = np.array([find_category(x) for x in data[:, 0]]) data[:, 1] = np.array([sarcasm(x) for x in data[:, 1]]) # print(data[0,1]) # should be 1 for sarcasm def find_category(category): return { 'GEN': 0, # general 'HYP': 1, # hyperbole 'RQ': 2 # rhetorical question }[category] def sarcasm(sarcasm_value): return { 'sarc': 1, # true for sarcasm 'notsarc': 0 # false for sarcasm }[sarcasm_value] def get_data_index(ID): '''find the index of the data point. Corresponds to 1234 in GEN_sarc_1234 under ID in data. ''' # TODO: given a string as shown in the comment, extract the number in it, possibly with regex. if __name__ == '__main__': main()
import numpy as np import pandas def main(): data = pandas.read_csv('sarcasm_v2.csv').as_matrix() # print(data.shape) data[:, 0] = np.array([find_category(x) for x in data[:, 0]]) data[:, 1] = np.array([sarcasm(x) for x in data[:, 1]]) # print(data[0,1]) # should be 1 for sarcasm def find_category(category): return { 'GEN': 0, # general 'HYP': 1, # hyperbole 'RQ': 2 # rhetorical question }[category] def sarcasm(sarcasm_value): return { 'sarc': 1, # true for sarcasm 'notsarc': 0 # false for sarcasm }[sarcasm_value] def get_data_index(ID): '''find the index of the data point. Corresponds to 1234 in GEN_sarc_1234 under ID in data. ''' # TODO if __name__ == '__main__': main()
Make sure long has l suffix to handle overflows
/* * Copyright 2011 Matthew Avery, mavery@advancedpwr.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.advancedpwr.record.methods; import com.advancedpwr.record.AccessPath; public class LongBuilder extends AbstractPrimitiveBuilder implements MethodWriterFactory { public String resultBuilder() { return "new Long( " + result() + "l )"; } /* (non-Javadoc) * @see com.advancedpwr.record.methods.Factory#accept(java.lang.Class) */ public boolean accept( Class inClass ) { return long.class.isAssignableFrom( inClass ) || Long.class.isAssignableFrom( inClass ); } /* (non-Javadoc) * @see com.advancedpwr.record.methods.Factory#createMethodBuilder(com.advancedpwr.record.AccessPath) */ public BuildMethodWriter createMethodBuilder( AccessPath inPath ) { return this; } }
/* * Copyright 2011 Matthew Avery, mavery@advancedpwr.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.advancedpwr.record.methods; import com.advancedpwr.record.AccessPath; public class LongBuilder extends AbstractPrimitiveBuilder implements MethodWriterFactory { public String resultBuilder() { return "new Long( " + result() + " )"; } /* (non-Javadoc) * @see com.advancedpwr.record.methods.Factory#accept(java.lang.Class) */ public boolean accept( Class inClass ) { return long.class.isAssignableFrom( inClass ) || Long.class.isAssignableFrom( inClass ); } /* (non-Javadoc) * @see com.advancedpwr.record.methods.Factory#createMethodBuilder(com.advancedpwr.record.AccessPath) */ public BuildMethodWriter createMethodBuilder( AccessPath inPath ) { return this; } }
Remove JSHint ignore rules from lib folder
// This file is part of bandiera-client-node. // // bandiera-client-node is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // bandiera-client-node is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with bandiera-client-node. If not, see <http://www.gnu.org/licenses/>. /* global afterEach, beforeEach, describe, it */ 'use strict'; var bandiera = module.exports = { Client: BandieraClient, createClient: createClient }; function createClient (baseUri) { return new bandiera.Client(baseUri); } function BandieraClient (baseUri) { this.baseUri = baseUri; }
// This file is part of bandiera-client-node. // // bandiera-client-node is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // bandiera-client-node is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with bandiera-client-node. If not, see <http://www.gnu.org/licenses/>. /* global afterEach, beforeEach, describe, it */ /* jshint maxlen: false, maxstatements: false */ 'use strict'; var bandiera = module.exports = { Client: BandieraClient, createClient: createClient }; function createClient (baseUri) { return new bandiera.Client(baseUri); } function BandieraClient (baseUri) { this.baseUri = baseUri; }
Make mutation hoc accept mutations without arguments
/* HoC that provides a simple mutation that expects a single JSON object in return Example usage: export default withMutation({ name: 'getEmbedlyData', args: {url: 'String'}, })(EmbedlyURL); */ import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; export default function withMutation({name, args}) { let mutation; if (args) { const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url mutation = ` mutation ${name}(${args1}) { ${name}(${args2}) } ` } else { mutation = ` mutation ${name} { ${name} } ` } return graphql(gql`${mutation}`, { props: ({ownProps, mutate}) => ({ [name]: (vars) => { return mutate({ variables: vars, }); } }), }); }
/* HoC that provides a simple mutation that expects a single JSON object in return Example usage: export default withMutation({ name: 'getEmbedlyData', args: {url: 'String'}, })(EmbedlyURL); */ import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; export default function withMutation({name, args}) { const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url return graphql(gql` mutation ${name}(${args1}) { ${name}(${args2}) } `, { props: ({ownProps, mutate}) => ({ [name]: (vars) => { return mutate({ variables: vars, }); } }), }); }
Move exported function to end of file
import _ from 'underscore'; const DATE_FILENAME_MATCHER = /^(?:.+\/)*(\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]))-(.*)(\.[^.]+)$/; const FILENAME_MATCHER = /^(.*)(\.[^.]+)$/; const validated = (field, single) => { switch (single) { case 'required': return !!field; case 'date': return DATE_FILENAME_MATCHER.test(field); case 'filename': return FILENAME_MATCHER.test(field); default: return false; } }; /** * Returns error messages if the given values does not pass the provided validations. * @param {Object} values * @param {Object} validations * @param {Object} messages * @return {Array} errorMessages */ export const validator = (values, validations, messages) => { let errorMessages = []; _.each(validations, (validationStr, field, list) => { const validationArr = validationStr.split('|'); _.each(validationArr, single => { if (!validated(values[field], single)) { errorMessages.push(messages[`${field}.${single}`]); } }); }); return errorMessages; };
import _ from 'underscore'; const DATE_FILENAME_MATCHER = /^(?:.+\/)*(\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]))-(.*)(\.[^.]+)$/; const FILENAME_MATCHER = /^(.*)(\.[^.]+)$/; /** * Returns error messages if the given values does not pass the provided validations. * @param {Object} values * @param {Object} validations * @param {Object} messages * @return {Array} errorMessages */ export const validator = (values, validations, messages) => { let errorMessages = []; _.each(validations, (validationStr, field, list) => { const validationArr = validationStr.split('|'); _.each(validationArr, single => { if (!validated(values[field], single)) { errorMessages.push(messages[`${field}.${single}`]); } }); }); return errorMessages; }; const validated = (field, single) => { switch (single) { case 'required': return !!field; case 'date': return DATE_FILENAME_MATCHER.test(field); case 'filename': return FILENAME_MATCHER.test(field); default: return false; } };
FIX: Use mysite instead of project() for finding the database backup taken
<?php if (PHP_SAPI != 'cli') { header("HTTP/1.0 404 Not Found"); exit; } $_SERVER['SCRIPT_FILENAME'] = __FILE__; chdir(dirname(dirname(dirname(__FILE__))).'/framework'); require_once 'core/Core.php'; $outfile = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : $outfile = Director::baseFolder().'/mysite/scripts/backup-'.date('Y-m-d-H-i-s').'.sql.gz'; global $databaseConfig; switch ($databaseConfig['type']) { case 'MySQLDatabase': $u = $databaseConfig['username']; $p = $databaseConfig['password']; $h = $databaseConfig['server']; $d = $databaseConfig['database']; $cmd = "mysqldump --user=".escapeshellarg($u)." --password=".escapeshellarg($p)." --ignore-table=$d.details --host=".escapeshellarg($h)." ".escapeshellarg($d)." | gzip > ".escapeshellarg($outfile); exec($cmd); break; case 'SQLiteDatabase': case 'SQLite3Database': $d = $databaseConfig['database']; $path = realpath(dirname(__FILE__).'/../../assets/.sqlitedb/'.$d); $cmd = "sqlite3 ".escapeshellarg($path)." .dump | gzip > ".escapeshellarg($outfile); exec($cmd); break; default: break; }
<?php if (PHP_SAPI != 'cli') { header("HTTP/1.0 404 Not Found"); exit; } $_SERVER['SCRIPT_FILENAME'] = __FILE__; chdir(dirname(dirname(dirname(__FILE__))).'/framework'); require_once 'core/Core.php'; $outfile = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : $outfile = Director::baseFolder().'/'.project().'/scripts/backup-'.date('Y-m-d-H-i-s').'.sql.gz'; global $databaseConfig; switch ($databaseConfig['type']) { case 'MySQLDatabase': $u = $databaseConfig['username']; $p = $databaseConfig['password']; $h = $databaseConfig['server']; $d = $databaseConfig['database']; $cmd = "mysqldump --user=".escapeshellarg($u)." --password=".escapeshellarg($p)." --ignore-table=$d.details --host=".escapeshellarg($h)." ".escapeshellarg($d)." | gzip > ".escapeshellarg($outfile); exec($cmd); break; case 'SQLiteDatabase': case 'SQLite3Database': $d = $databaseConfig['database']; $path = realpath(dirname(__FILE__).'/../../assets/.sqlitedb/'.$d); $cmd = "sqlite3 ".escapeshellarg($path)." .dump | gzip > ".escapeshellarg($outfile); exec($cmd); break; default: break; }
Add more tests for the SystemTime class
package beaform.utilities; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Date; import org.junit.After; import org.junit.Test; public class SystemTimeTest { @After public void destroy() { SystemTime.reset(); } @Test public void testWithEpoch() { SystemTime.setTimeSource(() -> 0); long systemTimeInMillis = SystemTime.getAsLong(); assertEquals("The expected time should be 0", 0, systemTimeInMillis); } @Test public void testWithEpochAsDate() { SystemTime.setTimeSource(() -> 0); Date systemTime = SystemTime.getAsDate(); assertEquals("The expected time should be 0", 0, systemTime.getTime()); } @Test public void testDefaultTimeSource() { SystemTime.reset(); final long start = System.currentTimeMillis(); final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertTrue("The tested value is not between the given arguments", isBetween(start, end, tested)); } private boolean isBetween(long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { lower = boundary1; upper = boundary2; } else { lower = boundary2; upper = boundary1; } return (lower <= tested) && (tested <= upper); } }
package beaform.utilities; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Test; public class SystemTimeTest { @After public void destroy() { SystemTime.reset(); } @Test public void testDefaultTimeSource() { SystemTime.reset(); final long start = System.currentTimeMillis(); final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertTrue("The tested value is not between the given arguments", isBetween(start, end, tested)); } private boolean isBetween(long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { lower = boundary1; upper = boundary2; } else { lower = boundary2; upper = boundary1; } return (lower <= tested) && (tested <= upper); } }
Add test for denying get requests
"""accounts app unittests for views """ from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. """ response = self.client.get('/') self.assertTemplateUsed(response, 'accounts/welcome.html') class SendLoginEmailTest(TestCase): """Tests for the view which sends the login email. """ def setUp(self): self.url = reverse('send_login_email') self.test_email = 'newvisitor@example.com' def test_uses_emailsent_template(self): """The send_login_email url responds with login_email_sent template. """ response = self.client.post(self.url, data={'email': self.test_email}) self.assertTemplateUsed(response, 'accounts/login_email_sent.html') def test_get_request_yields_405(self): """Accessing the view via get request is not allowed. """ response = self.client.get(self.url) self.assertEqual(response.status_code, 405)
"""accounts app unittests for views """ from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. """ response = self.client.get('/') self.assertTemplateUsed(response, 'accounts/welcome.html') class SendLoginEmailTest(TestCase): """Tests for the view which sends the login email. """ def setUp(self): self.url = reverse('send_login_email') self.test_email = 'newvisitor@example.com' def test_uses_emailsent_template(self): """The send_login_email url responds with login_email_sent template. """ response = self.client.post(self.url, data={'email': self.test_email}) self.assertTemplateUsed(response, 'accounts/login_email_sent.html')
Set MAX_MEMORY_LIMIT_IN_BYTES to number returned by cgroups where there is no limit
#!/usr/bin/python env_vars = {} def read_file(path): try: with open(path, 'r') as f: return f.read().strip() except IOError: return None def get_memory_limit(): limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes') if limit: env_vars['MEMORY_LIMIT_IN_BYTES'] = limit def get_number_of_cores(): core_count = 0 line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus') if line is None: return for group in line.split(','): core_ids = list(map(int, group.split('-'))) if len(core_ids) == 2: core_count += core_ids[1] - core_ids[0] + 1 else: core_count += 1 env_vars['NUMBER_OF_CORES'] = str(core_count) get_memory_limit() get_number_of_cores() print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807") for item in env_vars.items(): print("=".join(item))
#!/usr/bin/python env_vars = {} def read_file(path): try: with open(path, 'r') as f: return f.read().strip() except IOError: return None def get_memory_limit(): limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes') if limit: env_vars['MEMORY_LIMIT_IN_BYTES'] = limit def get_number_of_cores(): core_count = 0 line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus') if line is None: return for group in line.split(','): core_ids = list(map(int, group.split('-'))) if len(core_ids) == 2: core_count += core_ids[1] - core_ids[0] + 1 else: core_count += 1 env_vars['NUMBER_OF_CORES'] = str(core_count) get_memory_limit() get_number_of_cores() for item in env_vars.items(): print("=".join(item))
prjxray: Add INOUT to direction enum. INOUT is found on the PS7 interface on the Zynq. Signed-off-by: Tim 'mithro' Ansell <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@mith.ro>
""" Description of a site type """ from collections import namedtuple import enum class SitePinDirection(enum.Enum): IN = "IN" OUT = "OUT" INOUT = "INOUT" SiteTypePin = namedtuple('SiteTypePin', 'name direction') class SiteType(object): def __init__(self, site_type): self.type = site_type['type'] self.site_pins = {} for site_pin, site_pin_info in site_type['site_pins'].items(): self.site_pins[site_pin] = SiteTypePin( name=site_pin, direction=SitePinDirection(site_pin_info['direction']), ) def get_site_pins(self): return self.site_pins.keys() def get_site_pin(self, site_pin): return self.site_pins[site_pin]
""" Description of a site type """ from collections import namedtuple import enum class SitePinDirection(enum.Enum): IN = "IN" OUT = "OUT" SiteTypePin = namedtuple('SiteTypePin', 'name direction') class SiteType(object): def __init__(self, site_type): self.type = site_type['type'] self.site_pins = {} for site_pin, site_pin_info in site_type['site_pins'].items(): self.site_pins[site_pin] = SiteTypePin( name=site_pin, direction=SitePinDirection(site_pin_info['direction']), ) def get_site_pins(self): return self.site_pins.keys() def get_site_pin(self, site_pin): return self.site_pins[site_pin]
Add possible fallback for different Database encodes
<?php namespace Wdi\Providers; use Carbon\Carbon; use Illuminate\Support\ServiceProvider; use Schema; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Schema::defaultStringLength(191); } /** * Register any application services. * * @return void */ public function register() { $this->setLocales(); } private function setLocales() { config("app.localed_extended"); setlocale(LC_TIME, config("app.localed_extended")); setlocale(LC_MONETARY, config("app.localed_extended")); Carbon::setLocale(config("app.localed_extended")); } }
<?php namespace Wdi\Providers; use Carbon\Carbon; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { } /** * Register any application services. * * @return void */ public function register() { $this->setLocales(); } private function setLocales() { config("app.localed_extended"); setlocale(LC_TIME, config("app.localed_extended")); setlocale(LC_MONETARY, config("app.localed_extended")); Carbon::setLocale(config("app.localed_extended")); } }
Remove src/ from package.json in development
const path = require('path'); const babelOptions = { presets: ['es2015', 'stage-0'], plugins: ['transform-decorators-legacy', 'transform-runtime'] }; exports.module = function runModule(modulePath) { /* eslint-disable lines-around-comment, global-require */ const packageJson = require(path.resolve('package.json')); require('register-module')({ name: packageJson.name, path: path.resolve('src'), main: packageJson.main ? packageJson.main.replace('src/', '') : 'index.js' }); require('babel-register')(babelOptions); require(modulePath); /* eslint-enable lines-around-comment, global-require */ }; exports.stdin = function runStdin() { /* eslint-disable lines-around-comment, no-var */ var code = ''; /* eslint-enable lines-around-comment, no-var */ process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { const data = process.stdin.read(); if (data) { code += data; } else { /* eslint-disable lines-around-comment, global-require, no-underscore-dangle */ const compiled = require('babel-core').transform(code, babelOptions); require('babel-register')(babelOptions); module._compile(compiled.code, 'stdin'); /* eslint-enable lines-around-comment, global-require, no-underscore-dangle */ } }); };
const path = require('path'); const babelOptions = { presets: ['es2015', 'stage-0'], plugins: ['transform-decorators-legacy', 'transform-runtime'] }; exports.module = function runModule(modulePath) { /* eslint-disable lines-around-comment, global-require */ const packageJson = require(path.resolve('package.json')); require('register-module')({ name: packageJson.name, path: path.resolve('src'), main: packageJson.main || 'index.js' }); require('babel-register')(babelOptions); require(modulePath); /* eslint-enable lines-around-comment, global-require */ }; exports.stdin = function runStdin() { /* eslint-disable lines-around-comment, no-var */ var code = ''; /* eslint-enable lines-around-comment, no-var */ process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { const data = process.stdin.read(); if (data) { code += data; } else { /* eslint-disable lines-around-comment, global-require, no-underscore-dangle */ const compiled = require('babel-core').transform(code, babelOptions); require('babel-register')(babelOptions); module._compile(compiled.code, 'stdin'); /* eslint-enable lines-around-comment, global-require, no-underscore-dangle */ } }); };
Fix the spelling of the class name
<?php require_once(__DIR__ . '/../test_helpers.php'); class Mock_Resource extends Recurly_Resource { protected function getNodeName() { return 'mock'; } protected function getWriteableAttributes() { return array('date', 'bool', 'number', 'array', 'nil', 'string'); } protected function getRequiredAttributes() { return array('required'); } } class Recurly_ResourceTest extends Recurly_TestCase { public function testXml() { $resource = new Mock_Resource(); $resource->date = new DateTime("@1384202874"); $resource->bool = true; $resource->number = 34; $resource->array = array( 'int' => 1, 'string' => 'foo', ); $resource->nil = null; $resource->string = "Foo & Bar"; $this->assertEquals( "<?xml version=\"1.0\"?>\n<mock><date>2013-11-11T20:47:54+00:00</date><bool>true</bool><number>34</number><array><int>1</int><string>foo</string></array><nil nil=\"nil\"></nil><string>Foo &amp; Bar</string></mock>\n", $resource->xml() ); } }
<?php require_once(__DIR__ . '/../test_helpers.php'); class Recource_Mock_Resource extends Recurly_Resource { protected function getNodeName() { return 'mock'; } protected function getWriteableAttributes() { return array('date', 'bool', 'number', 'array', 'nil', 'string'); } protected function getRequiredAttributes() { return array('required'); } } class Recurly_ResourceTest extends Recurly_TestCase { public function testXml() { $resource = new Recource_Mock_Resource(); $resource->date = new DateTime("@1384202874"); $resource->bool = true; $resource->number = 34; $resource->array = array( 'int' => 1, 'string' => 'foo', ); $resource->nil = null; $resource->string = "Foo & Bar"; $this->assertEquals( "<?xml version=\"1.0\"?>\n<mock><date>2013-11-11T20:47:54+00:00</date><bool>true</bool><number>34</number><array><int>1</int><string>foo</string></array><nil nil=\"nil\"></nil><string>Foo &amp; Bar</string></mock>\n", $resource->xml() ); } }
Rename the TEXTAREA_FIELD to TEXTAREA in the VM snapshot form
import { componentTypes, validatorTypes } from '@@ddf'; const createSchema = (hideName, showMemory, descriptionRequired) => { const nameField = { component: componentTypes.TEXT_FIELD, id: 'name', name: 'name', label: __('Name'), isRequired: true, validate: [{ type: validatorTypes.REQUIRED, message: __('Required'), }], }; const memoryField = { component: componentTypes.SWITCH, id: 'snap_memory', name: 'snap_memory', label: __('Snapshot VM memory'), onText: __('Yes'), offText: __('No'), }; const fields = [ ...(hideName ? [] : [nameField]), { component: componentTypes.TEXTAREA, id: 'description', name: 'description', label: __('Description'), isRequired: descriptionRequired, validate: descriptionRequired ? [{ type: validatorTypes.REQUIRED, message: __('Required'), }] : [], }, ...(showMemory ? [memoryField] : []), ]; return { fields }; }; export default createSchema;
import { componentTypes, validatorTypes } from '@@ddf'; const createSchema = (hideName, showMemory, descriptionRequired) => { const nameField = { component: componentTypes.TEXT_FIELD, id: 'name', name: 'name', label: __('Name'), isRequired: true, validate: [{ type: validatorTypes.REQUIRED, message: __('Required'), }], }; const memoryField = { component: componentTypes.SWITCH, id: 'snap_memory', name: 'snap_memory', label: __('Snapshot VM memory'), onText: __('Yes'), offText: __('No'), }; const fields = [ ...(hideName ? [] : [nameField]), { component: componentTypes.TEXTAREA_FIELD, id: 'description', name: 'description', label: __('Description'), isRequired: descriptionRequired, validate: descriptionRequired ? [{ type: validatorTypes.REQUIRED, message: __('Required'), }] : [], }, ...(showMemory ? [memoryField] : []), ]; return { fields }; }; export default createSchema;
Make sort option fields static
package edu.iastate.cs.design.spec.stackexchange.request; public class QuestionAnswersRequestData implements IStackExchangeRequestData { public static final String ACTIVITY_SORT = "activity"; public static final String CREATION_DATE_SORT = "creation"; public static final String VOTES_SORT = "votes"; private String sort; // The api actually accepts a list of ids, but we will just use one. private int id; public QuestionAnswersRequestData(String sort, int id) { this.sort = sort; this.id = id; } public String getSort() { return sort; } public int getId() { return id; } public String requestUrl() { StringBuilder requestBuilder = new StringBuilder(); requestBuilder.append("https://api.stackexchange.com/2.2/questions/"); requestBuilder.append(id); requestBuilder.append("/answers?order=desc&sort="); requestBuilder.append(sort); requestBuilder.append("&site=stackoverflow"); requestBuilder.append("&key=KW1Do4aYqEdlMNsHpPEHdg(("); return requestBuilder.toString(); } }
package edu.iastate.cs.design.spec.stackexchange.request; public class QuestionAnswersRequestData implements IStackExchangeRequestData { public final String ACTIVITY_SORT = "activity"; public final String CREATION_DATE_SORT = "creation"; public final String VOTES_SORT = "votes"; private String sort; // The api actually accepts a list of ids, but we will just use one. private int id; public QuestionAnswersRequestData(String sort, int id) { this.sort = sort; this.id = id; } public String getSort() { return sort; } public int getId() { return id; } public String requestUrl() { StringBuilder requestBuilder = new StringBuilder(); requestBuilder.append("https://api.stackexchange.com/2.2/questions/"); requestBuilder.append(id); requestBuilder.append("/answers?order=desc&sort="); requestBuilder.append(sort); requestBuilder.append("&site=stackoverflow"); requestBuilder.append("&key=KW1Do4aYqEdlMNsHpPEHdg(("); return requestBuilder.toString(); } }
Add click events for buttons.
/** * Copyright (C) 2015 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.rx.sample.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import com.fernandocejas.android10.rx.sample.R; import com.fernandocejas.android10.rx.sample.data.DataManager; import rx.Subscription; import rx.subscriptions.Subscriptions; public class SampleActivityObservableTransfor extends Activity { @InjectView(R.id.btn_flatMap) Button btn_flatMap; @InjectView(R.id.btn_concatMap) Button btn_concatMap; private DataManager dataManager; private Subscription subscription; public static Intent getCallingIntent(Context context) { return new Intent(context, SampleActivityObservableTransfor.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample_observervable_transform); ButterKnife.inject(this); initialize(); } @Override protected void onDestroy() { this.subscription.unsubscribe(); super.onDestroy(); } private void initialize() { this.subscription = Subscriptions.empty(); } @OnClick(R.id.btn_flatMap) void onFlatMapClick() { } @OnClick(R.id.btn_concatMap) void onConcatMapClick() { } }
/** * Copyright (C) 2015 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.rx.sample.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import butterknife.ButterKnife; import com.fernandocejas.android10.rx.sample.R; import rx.Subscription; import rx.subscriptions.Subscriptions; public class SampleActivityObservableTransfor extends Activity { private Subscription subscription; public static Intent getCallingIntent(Context context) { return new Intent(context, SampleActivityObservableTransfor.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample_observervable_transform); ButterKnife.inject(this); initialize(); } @Override protected void onDestroy() { this.subscription.unsubscribe(); super.onDestroy(); } private void initialize() { this.subscription = Subscriptions.empty(); } }
Support multipart uploads from browser
package gofakes3 import ( "net/http" "strings" ) var ( corsHeaders = []string{ "Accept", "Accept-Encoding", "Authorization", "Content-Disposition", "Content-Length", "Content-Type", "X-Amz-Date", "X-Amz-User-Agent", "X-CSRF-Token", "x-amz-acl", "x-amz-content-sha256", "x-amz-meta-filename", "x-amz-meta-from", "x-amz-meta-private", "x-amz-meta-to", "x-amz-security-token", } corsHeadersString = strings.Join(corsHeaders, ", ") ) type withCORS struct { r http.Handler log Logger } func (s *withCORS) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD") w.Header().Set("Access-Control-Allow-Headers", corsHeadersString) w.Header().Set("Access-Control-Expose-Headers", "ETag") if r.Method == "OPTIONS" { return } s.r.ServeHTTP(w, r) }
package gofakes3 import ( "net/http" "strings" ) var ( corsHeaders = []string{ "Accept", "Accept-Encoding", "Authorization", "Content-Disposition", "Content-Length", "Content-Type", "X-Amz-Date", "X-Amz-User-Agent", "X-CSRF-Token", "x-amz-acl", "x-amz-meta-filename", "x-amz-meta-from", "x-amz-meta-private", "x-amz-meta-to", } corsHeadersString = strings.Join(corsHeaders, ", ") ) type withCORS struct { r http.Handler log Logger } func (s *withCORS) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD") w.Header().Set("Access-Control-Allow-Headers", corsHeadersString) if r.Method == "OPTIONS" { return } s.r.ServeHTTP(w, r) }
Move test code to package moeparser_test
package moeparser_test import ( "fmt" "moeparser" "testing" ) func TestBbCodeParse(t *testing.T) { testString := `Something [b][i][img=http://sauyon.com/blah.png][/i][/i] [b]hi[/b=what] This seems to work very well :D [url][/url] [size=12px]something [url]http://sauyon.com/wrappedinurl[/url] [url=http://sauyon.com] [img=//sauyon.com]What[/img] [url][/url]` out, err := BbCodeParse(testString) if err != nil { fmt.Printf("Parsing failed! Error:", err) } fmt.Println("Parse succeeeded. Output is:") fmt.Println(out) testString1 := "[url=http://google.com/][img]http://www.google.com/intl/en_ALL/images/logo.gif[/img][/url]" out1, err := BbCodeParse(testString1) if err != nil { fmt.Printf("Parsing failed! Error:", err) } fmt.Println("Parse succeeeded. Output is:") fmt.Println(out1) }
package moeparser import ( "fmt" "testing" ) func TestBbCodeParse(t *testing.T) { testString := `Something [b][i][img=http://sauyon.com/blah.png][/i][/i] [b]hi[/b=what] This seems to work very well :D [url][/url] [size=12px]something [url]http://sauyon.com/wrappedinurl[/url] [url=http://sauyon.com] [img=//sauyon.com]What[/img] [url][/url]` out, err := BbCodeParse(testString) if err != nil { fmt.Printf("Parsing failed! Error:", err) } fmt.Println("Parse succeeeded. Output is:") fmt.Println(out) testString1 := "[url=http://google.com/][img]http://www.google.com/intl/en_ALL/images/logo.gif[/img][/url]" out1, err := BbCodeParse(testString1) if err != nil { fmt.Printf("Parsing failed! Error:", err) } fmt.Println("Parse succeeeded. Output is:") fmt.Println(out1) }
Fix typo in error message
package tasks import ( "errors" "reflect" ) var ( // ErrTaskMustBeFunc ... ErrTaskMustBeFunc = errors.New("Task must be a func type") // ErrTaskReturnsNoValue ... ErrTaskReturnsNoValue = errors.New("Task must return at least a single value") // ErrLastReturnValueMustBeError .. ErrLastReturnValueMustBeError = errors.New("Last return value of a task must be error") ) // ValidateTask validates task function using reflection and makes sure // it has a proper signature. Functions used as tasks must return at least a // single value and the last return type must be error func ValidateTask(task interface{}) error { v := reflect.ValueOf(task) t := v.Type() // Task must be a function if t.Kind() != reflect.Func { return ErrTaskMustBeFunc } // Task must return at least a single value if t.NumOut() < 1 { return ErrTaskReturnsNoValue } // Last return value must be error lastReturnType := t.Out(t.NumOut() - 1) errorInterface := reflect.TypeOf((*error)(nil)).Elem() if !lastReturnType.Implements(errorInterface) { return ErrLastReturnValueMustBeError } return nil }
package tasks import ( "errors" "reflect" ) var ( // ErrTaskMustBeFunc ... ErrTaskMustBeFunc = errors.New("Task must be a func type") // ErrTaskReturnsNoValue ... ErrTaskReturnsNoValue = errors.New("Taks must return at least a single value") // ErrLastReturnValueMustBeError .. ErrLastReturnValueMustBeError = errors.New("Last return value of a task must be error") ) // ValidateTask validates task function using reflection and makes sure // it has a proper signature. Functions used as tasks must return at least a // single value and the last return type must be error func ValidateTask(task interface{}) error { v := reflect.ValueOf(task) t := v.Type() // Task must be a function if t.Kind() != reflect.Func { return ErrTaskMustBeFunc } // Task must return at least a single value if t.NumOut() < 1 { return ErrTaskReturnsNoValue } // Last return value must be error lastReturnType := t.Out(t.NumOut() - 1) errorInterface := reflect.TypeOf((*error)(nil)).Elem() if !lastReturnType.Implements(errorInterface) { return ErrLastReturnValueMustBeError } return nil }
Test closing github issue automatically? Fixes #5
(function() { 'use strict'; let path = require('path'); let express = require('express'); let http = require('http'); let _ = require('lodash'); let bodyParser = require('body-parser'); let sseExpress = require('sse-express'); let app = express(); let globalId = 1; let connections = []; app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use((req, res, next) => { // setup cors res.setHeader('Access-Control-Allow-Origin', '*'); next(); }); app.post('/sendMessage', (req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); connections.forEach(function(connection) { connection.sse('message', { text: req.body.message, userId: req.body.userId }); }); res.end(); }); app.get('/updates', sseExpress, function(req, res) { connections.push(res); // send id to user res.sse('connected', { id: globalId }); globalId++; req.on("close", function() { _.remove(connections, res); console.log('clients: ' + connections.length); }); console.log(`Hello, ${globalId}!`); }); app.listen(99, function () { console.log('Example app listening on port 99!'); }); })();
(function() { 'use strict'; let path = require('path'); let express = require('express'); let http = require('http'); let _ = require('lodash'); let bodyParser = require('body-parser'); let sseExpress = require('sse-express'); let app = express(); let globalId = 1; let connections = []; app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use((req, res, next) => { // cors res.setHeader('Access-Control-Allow-Origin', '*'); next(); }); app.post('/sendMessage', (req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); connections.forEach(function(connection) { connection.sse('message', { text: req.body.message, userId: req.body.userId }); }); res.end(); }); app.get('/updates', sseExpress, function(req, res) { connections.push(res); // send id to user res.sse('connected', { id: globalId }); globalId++; req.on("close", function() { _.remove(connections, res); console.log('clients: ' + connections.length); }); console.log(`Hello, ${globalId}!`); }); app.listen(99, function () { console.log('Example app listening on port 99!'); }); })();
Add featured tag to featured challenges
<tr> <td> <a class="" title="" href="{{ route('quizzes.quiz', $challenge->id) }}"> <figure> <img src="{{ !empty($pages[$challenge->content_page]->logo) ? $pages[$challenge->content_page]->logo : $pages[$challenge->content_page]->coverimage }}" class="img-responsive"> </figure> </a> </td> <td> <a class="" title="" href="{{ route('quizzes.quiz', $challenge->id) }}"> <div> <h2> <span class="theme-primary">{{ $pages[$challenge->content_page]->heading }}</span> </h2> <p>{{ $challenge->points_max }} Points @if($challenge->type == ChallengeType::FEATURED) <span class="btn btn-danger btn-xs"> FEATURED </span> @endif </p> </div> </a> </td> <td class="text-center" width="72"> @if( $challenge->remaining_attempts == 0 ) <i class="fa fa-check-circle" aria-hidden="true"></i> @else &nbsp; @endif </td> </tr>
<tr> <td> <a class="" title="" href="{{ route('quizzes.quiz', $challenge->id) }}"> <figure> <img src="{{ !empty($pages[$challenge->content_page]->logo) ? $pages[$challenge->content_page]->logo : $pages[$challenge->content_page]->coverimage }}" class="img-responsive"> </figure> </a> </td> <td> <a class="" title="" href="{{ route('quizzes.quiz', $challenge->id) }}"> <div> <h2> <span class="theme-primary">{{ $pages[$challenge->content_page]->heading }}</span> </h2> <p>{{ $challenge->points_max }} Points</p> </div> </a> </td> <td class="text-center" width="72"> @if( $challenge->remaining_attempts == 0 ) <i class="fa fa-check-circle" aria-hidden="true"></i> @else &nbsp; @endif </td> </tr>
Undo version increment. 1.0.2 was never released/tagged.
<?php /** * Pines' information. * * @package Pines * @license http://www.gnu.org/licenses/agpl-3.0.html * @author Hunter Perrin <hunter@sciactive.com> * @copyright SciActive.com * @link http://sciactive.com/ */ /* @var $pines pines */ defined('P_RUN') or die('Direct access prohibited'); return array( 'name' => 'Pines', 'author' => 'SciActive', 'version' => '1.0.2', 'license' => 'http://www.gnu.org/licenses/agpl-3.0.html', 'website' => 'http://www.sciactive.com', 'short_description' => 'Pines framework core system', 'description' => 'The core system of the Pines PHP application framework.', 'depend' => array( 'php' => '>=5.2.10' ), 'abilities' => array( array('all', 'All Abilities', 'Let user do anything, regardless of whether they have the ability.') ), ); ?>
<?php /** * Pines' information. * * @package Pines * @license http://www.gnu.org/licenses/agpl-3.0.html * @author Hunter Perrin <hunter@sciactive.com> * @copyright SciActive.com * @link http://sciactive.com/ */ /* @var $pines pines */ defined('P_RUN') or die('Direct access prohibited'); return array( 'name' => 'Pines', 'author' => 'SciActive', 'version' => '1.0.3', 'license' => 'http://www.gnu.org/licenses/agpl-3.0.html', 'website' => 'http://www.sciactive.com', 'short_description' => 'Pines framework core system', 'description' => 'The core system of the Pines PHP application framework.', 'depend' => array( 'php' => '>=5.2.10' ), 'abilities' => array( array('all', 'All Abilities', 'Let user do anything, regardless of whether they have the ability.') ), ); ?>
Apply arguments, check message for string
if(Meteor.isServer) { winston = Npm.require('winston'); } Space.Logger = Space.Object.extend(Space, 'Logger', { _logger: null, _state: 'stopped', Constructor() { if(Meteor.isServer) { this._logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)() ] }); } if(Meteor.isClient) { this._logger = console; } }, start() { if(this._state === 'stopped') { this._state = 'running'; } }, stop() { if(this._state === 'running') { this._state = 'stopped'; } }, info(message, meta) { check(message, String) if(this.shouldLog()) this._logger.info.apply(this, arguments); }, warn(message, meta) { check(message, String) if(this.shouldLog()) this._logger.warn.apply(this, arguments); }, error(message, meta) { check(message, String) if(this.shouldLog()) this._logger.error.apply(this, arguments); }, shouldLog() { if(this._state === 'running') return true; } }); // System log Space.log = new Space.Logger(); if(Space.configuration.sysLog.enabled) { Space.log.start(); }
if (Meteor.isServer) { winston = Npm.require('winston'); } Space.Logger = Space.Object.extend(Space, 'Logger', { _logger: null, _state: 'stopped', Constructor() { if (Meteor.isServer) { this._logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)() ] }); } if (Meteor.isClient) { this._logger = console; } }, start() { if (this._state === 'stopped') { this._state = 'running'; } }, stop() { if (this._state === 'running') { this._state = 'stopped'; } }, info(message, meta) { if (this.shouldLog()) this._logger.info(message, meta); }, warn(message, meta) { if (this.shouldLog()) this._logger.warn(message, meta); }, error(message, meta) { if (this.shouldLog()) this._logger.error(message, meta); }, shouldLog() { if (this._state === 'running') return true; } }); // System log Space.log = new Space.Logger(); if (Space.configuration.sysLog.enabled) { Space.log.start(); }
Disable eslint console warnings in test files
// Cascading config (merges with parent config) // http://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy module.exports = { "env": { "mocha": true }, "extends": [ "plugin:mocha/recommended" ], "parserOptions": { "ecmaVersion": 8, }, "plugins": [ "chai-expect", "mocha" ], "rules": { "mocha/no-hooks-for-single-case": ["off"], "mocha/no-top-level-hooks" : ["off"], "mocha/no-setup-in-describe" : ["off"], "no-console" : ["off"] } };
// Cascading config (merges with parent config) // http://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy module.exports = { "env": { "mocha": true }, "extends": [ "plugin:mocha/recommended" ], "parserOptions": { "ecmaVersion": 8, }, "plugins": [ "chai-expect", "mocha" ], "rules": { "mocha/no-hooks-for-single-case": ["off"], "mocha/no-top-level-hooks" : ["off"], "mocha/no-setup-in-describe" : ["off"] } };
Add player object to game
package game; import model.Grid; /** * Created by kuro on 10/03/16. */ public class Game { private Grid grid; private Player player0; private boolean gameLooping; private long now, last; public Game() { //Setup game environement here grid = new Grid(); gameLooping = true; player0 = new Player(); } /** * Launch the main loop of the game */ public void loop() { while(gameLooping) { now = System.nanoTime(); System.out.println(now - last); update(); last = now; } } private void update() { } public Grid getGrid() { return grid; } }
package game; import model.Grid; /** * Created by kuro on 10/03/16. */ public class Game { private Grid grid; private boolean gameLooping; private long now, last; public Game() { //Setup game environement here grid = new Grid(); gameLooping = true; } /** * Launch the main loop of the game */ public void loop() { while(gameLooping) { now = System.nanoTime(); System.out.println(now - last); update(); last = now; } } private void update() { } public Grid getGrid() { return grid; } }
Fix innacurate test for whether or not a route was an IndexRoute The issue was caused by the fact that we can't use reference equality to compare an object to its minified self. Since we obviously want to minify in production it is not viable to test `route === IndexRoute`. The new approach is not very sophisticated, but if it causes issues down the road we can address them.
import { isArray, isUndefined } from 'lodash/lang'; import { flattenDeep } from 'lodash/array'; /** * This is not a very sophisticated checking method. Assuming we already know * this is either a Route or an IndexRoute under what cases would this break? */ const isIndexRoute = route => isUndefined(route.props.path); /** * NOTE: We could likely use createRoutes to our advantage here. It may simplify * the code we currently use to recurse over the virtual dom tree: * * import { createRoutes } from 'react-router'; * console.log(createRoutes(routes)); => * [ { path: '/', * component: [Function: Layout], * childRoutes: [ [Object], [Object] ] } ] * * Ex: * const routes = ( * <Route component={App} path='/'> * <Route component={About} path='/about' /> * </Route> * ); * * getAllPaths(routes); => ['/', '/about] */ export const getNestedPaths = (route, prefix = '') => { if (!route) return []; if (isArray(route)) return route.map(x => getNestedPaths(x, prefix)); // Index routes don't represent a distinct path, so we don't count them if (isIndexRoute(route)) return []; const path = prefix + route.props.path; const nextPrefix = path === '/' ? path : path + '/'; return ([path].concat(getNestedPaths(route.props.children, nextPrefix))); }; export const getAllPaths = routes => { return flattenDeep(getNestedPaths(routes)); }; export default getAllPaths;
import { IndexRoute } from 'react-router'; import { isArray } from 'lodash/lang'; import { flattenDeep } from 'lodash/array'; /** * NOTE: We could likely use createRoutes to our advantage here. It may simplify * the code we currently use to recurse over the virtual dom tree: * * import { createRoutes } from 'react-router'; * console.log(createRoutes(routes)); => * [ { path: '/', * component: [Function: Layout], * childRoutes: [ [Object], [Object] ] } ] * * Ex: * const routes = ( * <Route component={App} path='/'> * <Route component={About} path='/about' /> * </Route> * ); * * getAllPaths(routes); => ['/', '/about] */ export const getNestedPaths = (route, prefix = '') => { if (!route) return []; if (isArray(route)) return route.map(x => getNestedPaths(x, prefix)); // Index routes don't represent a distinct path, so we don't count them if (route.type === IndexRoute) return []; const path = prefix + route.props.path; const nextPrefix = path === '/' ? path : path + '/'; return ([path].concat(getNestedPaths(route.props.children, nextPrefix))); }; export const getAllPaths = routes => { return flattenDeep(getNestedPaths(routes)); }; export default getAllPaths;
Allow importing from pymp module directly
import logging import multiprocessing from pymp.dispatcher import State, Dispatcher, Proxy DEBUG = False # for now def get_logger(level=None): logger = multiprocessing.get_logger() format = '[%(asctime)s][%(levelname)s/%(processName)s] %(message)s' formatter = logging.Formatter(format) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if level: logger.setLevel(level) return logger if DEBUG: logger = get_logger(logging.DEBUG) else: logger = get_logger() def trace_function(f): if DEBUG: def run(*args, **kwargs): logger.debug("%s called" % repr(f)) value = f(*args, **kwargs) logger.debug("%s returned" % repr(f)) return value return run else: return f
import logging import multiprocessing DEBUG = False # for now def get_logger(level=None): logger = multiprocessing.get_logger() format = '[%(asctime)s][%(levelname)s/%(processName)s] %(message)s' formatter = logging.Formatter(format) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if level: logger.setLevel(level) return logger if DEBUG: logger = get_logger(logging.DEBUG) else: logger = get_logger() def trace_function(f): if DEBUG: def run(*args, **kwargs): logger.debug("%s called" % repr(f)) value = f(*args, **kwargs) logger.debug("%s returned" % repr(f)) return value return run else: return f
Convert to use the base class and update for new plugin path.
import re import snmpy class log_processor(snmpy.plugin): def __init__(self, conf, script=False): snmpy.plugin.__init__(self, conf, script) def key(self, idx): return 'string', self.data[idx - 1]['label'] def val(self, idx): return 'integer', self.data[idx - 1]['value'] def worker(self): self.data = [{'value':0, 'label': self.conf['objects'][item]['label'], 'regex': re.compile(self.conf['objects'][item]['regex'])} for item in sorted(self.conf['objects'])] self.tail() @snmpy.task def tail(self): for line in snmpy.tail(self.conf['logfile']): for item in xrange(len(self.data)): find = self.data[item]['regex'].search(line) if find: self.data[item]['value'] += 1 break
import re, snmpy_plugins class log_processor: def __init__(self, conf): self.data = [{'value':0, 'label': conf['objects'][item]['label'], 'regex': re.compile(conf['objects'][item]['regex'])} for item in sorted(conf['objects'])] self.proc(conf['logfile']) def len(self): return len(self.data) def key(self, idx): return 'string', self.data[idx - 1]['label'] def val(self, idx): return 'integer', self.data[idx - 1]['value'] @snmpy_plugins.task def proc(self, file): for line in snmpy_plugins.tail(file): for item in xrange(len(self.data)): find = self.data[item]['regex'].search(line) if find: self.data[item]['value'] += 1 break
Reduce the size of the jamendo album cover images requested since we don't use them for anything larger than 160x160 at the moment
<?php function resolve_external_url($url) { if (substr($url, 0, 10) == "jamendo://") { return process_jamendo_url($url); } return $url; } function process_jamendo_url($url) { if (substr($url, 10, 13) == "track/stream/") { $id = substr($url, 23); return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2"; } if (substr($url, 10, 15) == "album/download/") { $id = substr($url, 25); return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3"; } if (substr($url, 10, 10) == "album/art/") { $id = substr($url, 20); return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=200"; } // We don't know what this is return $url; } ?>
<?php function resolve_external_url($url) { if (substr($url, 0, 10) == "jamendo://") { return process_jamendo_url($url); } return $url; } function process_jamendo_url($url) { if (substr($url, 10, 13) == "track/stream/") { $id = substr($url, 23); return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2"; } if (substr($url, 10, 15) == "album/download/") { $id = substr($url, 25); return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3"; } if (substr($url, 10, 10) == "album/art/") { $id = substr($url, 20); return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=400"; } // We don't know what this is return $url; } ?>
Add mainTitle.raw to default work search field
module.exports = { queryDefaults: { size: 100 }, defaultAggregates: { facets: { global: {}, aggs: {} } }, defaultPublicationFields: [ 'agents^10', 'author^50', 'country', 'desc', 'ean', 'format', 'inst', 'isbn', 'ismn', 'language', 'mainTitle^50', 'mt', 'partNumber', 'partTitle', 'publishedBy', 'recordId', 'series^20', 'title^20' ], defaultWorkFields: [ 'agents^0', 'author^50', 'bio', 'compType', 'country', 'desc', 'genre', 'inst', 'language', 'litform', 'mainTitle^50', 'mainTitle.raw^100', 'mt', 'partNumber', 'partTitle', 'subtitle', 'series^10', 'subject^50', 'summary', 'title^20' ] }
module.exports = { queryDefaults: { size: 100 }, defaultAggregates: { facets: { global: {}, aggs: {} } }, defaultPublicationFields: [ 'agents^10', 'author^50', 'country', 'desc', 'ean', 'format', 'inst', 'isbn', 'ismn', 'language', 'mainTitle^50', 'mt', 'partNumber', 'partTitle', 'publishedBy', 'recordId', 'series^20', 'title^20' ], defaultWorkFields: [ 'agents^0', 'author^50', 'bio', 'compType', 'country', 'desc', 'genre', 'inst', 'language', 'litform', 'mainTitle^50', 'mt', 'partNumber', 'partTitle', 'subtitle', 'series^10', 'subject^50', 'summary', 'title^20' ] }
Add charset specification to ajax request. Firefox automatically adds it, chrome doesn't, the current backend chokes on it not being present.
var Cart = function(baseUrl) { var self = this this.baseUrl = baseUrl this.userID = ''; this.online = [] ko.track(this) } Cart.prototype = Object.create(Array.prototype) Cart.prototype.doesntContain = function(doc) { var found = false for (var i=0; i<this.length; ++i) { found = (this[i].id === doc.id ? true : found) } return !found } Cart.prototype.add = function(doc) { if (this.doesntContain(doc)) { this.push(doc) } } Cart.prototype.drop = function(doc) { var index = this.indexOf(doc) if (index < 0) { return } this.splice(index, 1) } Cart.prototype.save = function() { var self = this if (this.userID === '') { alert('Please enter a user name first.') return } var docIDs = [] for (var i=0; i<self.length; i++) { docIDs.push(self[i].id) } $.ajax({ url: this.baseUrl + '/data/carts/' + this.userID, type: 'POST', contentType: 'application/json; charset=UTF-8', data: JSON.stringify(docIDs), success: function() { for (var i=0; i<self.length; i++) { self.online.push(self[i]) } self.splice(0, self.length) } }) }
var Cart = function(baseUrl) { var self = this this.baseUrl = baseUrl this.userID = ''; this.online = [] ko.track(this) } Cart.prototype = Object.create(Array.prototype) Cart.prototype.doesntContain = function(doc) { var found = false for (var i=0; i<this.length; ++i) { found = (this[i].id === doc.id ? true : found) } return !found } Cart.prototype.add = function(doc) { if (this.doesntContain(doc)) { this.push(doc) } } Cart.prototype.drop = function(doc) { var index = this.indexOf(doc) if (index < 0) { return } this.splice(index, 1) } Cart.prototype.save = function() { var self = this if (this.userID === '') { alert('Please enter a user name first.') return } var docIDs = [] for (var i=0; i<self.length; i++) { docIDs.push(self[i].id) } $.ajax({ url: this.baseUrl + '/data/carts/' + this.userID, type: 'POST', contentType: 'application/json', data: JSON.stringify(docIDs), success: function() { for (var i=0; i<self.length; i++) { self.online.push(self[i]) } self.splice(0, self.length) } }) }
Fix window and global object
;(function(context) { var modules = {}; var _modules = {}; var stack = {}; // define(id, function(require, module, exports)) function define(id, callback) { if (typeof id !== 'string' || id === '') throw Error('invalid module id ' + id); if (_modules[id]) throw Error('dupicated module id ' + id); if (typeof callback !== 'function') throw Error('invalid module function'); _modules[id] = callback; } // require(id) function require(id) { if (!_modules[id]) throw Error('module ' + id + ' is not defined'); if (stack[id]) throw Error(outputCircular()); if (modules[id]) return modules[id].exports; var m = modules[id] = { id: id, require: require, exports: {} }; stack[id] = true; _modules[id](require, m, m.exports); stack[id] = false; return m.exports; } function outputCircular() { return 'circular: ' + Object.keys(stack).join(', '); } context.define = define; context.require = require; })(typeof window !== 'undefined'? window : global);
(function(window) { var modules = {}; var _modules = {}; var stack = {}; // define(id, function(require, module, exports)) function define(id, callback) { if (typeof id !== 'string' || id === '') throw Error('invalid module id ' + id); if (_modules[id]) throw Error('dupicated module id ' + id); if (typeof callback !== 'function') throw Error('invalid module function'); _modules[id] = callback; } // require(id) function require(id) { if (!_modules[id]) throw Error('module ' + id + ' is not defined'); if (stack[id]) throw Error(outputCircular()); if (modules[id]) return modules[id].exports; var m = modules[id] = { id: id, require: require, exports: {} }; stack[id] = true; _modules[id](require, m, m.exports); stack[id] = false; return m.exports; } function outputCircular() { s = 'circular:'; for (var i in stack) { if (stack[i]) s += ' ' + i; } return s; } window.define = define; window.require = require; })(global || window);
Remove unused options param from cmd util
import { spawn } from 'child_process' const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] // Simple util for calling a child process export function cmd (string) { const [ cmd, ...args ] = string.split(' ') return new Promise((resolve, reject) => { const child = spawn(cmd, args) let data = '' child.stdout.on('data', buffer => { data += buffer.toString() }) child.stdout.on('end', () => resolve(data)) child.on('error', reject) }) } export function niceDate (string) { const date = new Date(string) const day = date.getDate() const month = MONTH_NAMES[date.getMonth()] const year = date.getFullYear() return `${day} ${month} ${year}` } export function removeIndentation (string) { return string.replace(/\n +/g, '\n') } export function isLink (string) { return /^http/.test(string) }
import { spawn } from 'child_process' const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] // Simple util for calling a child process export function cmd (string, options = {}) { const [ cmd, ...args ] = string.split(' ') return new Promise((resolve, reject) => { const child = spawn(cmd, args, options) let data = '' child.stdout.on('data', buffer => { data += buffer.toString() }) child.stdout.on('end', () => resolve(data)) child.on('error', reject) }) } export function niceDate (string) { const date = new Date(string) const day = date.getDate() const month = MONTH_NAMES[date.getMonth()] const year = date.getFullYear() return `${day} ${month} ${year}` } export function removeIndentation (string) { return string.replace(/\n +/g, '\n') } export function isLink (string) { return /^http/.test(string) }
Implement set_remote_url in pygit2 implementation
from __future__ import absolute_import import pygit2 from .base_git import NoSuchRemote from .plain_git import PlainGit class Pygit2Git(PlainGit): @staticmethod def _find_remote(repo, remote_name): for remote in repo.remotes: if remote.name == remote_name: return remote else: raise NoSuchRemote() @staticmethod def is_on_branch(path): repo = pygit2.Repository(path) return not (repo.head_is_detached or repo.head_is_unborn) @staticmethod def get_remote_url(path, remote_name): repo = pygit2.Repository(path) remote = Pygit2Git._find_remote(repo, remote_name) return remote.url @staticmethod def add_remote(path, remote_name, remote_url): repo = pygit2.Repository(path) repo.create_remote(remote_name, remote_url) @staticmethod def set_remote_url(path, remote_name, remote_url): repo = pygit2.Repository(path) remote = Pygit2Git._find_remote(repo, remote_name) remote.url = remote_url remote.save()
from __future__ import absolute_import import pygit2 from .base_git import NoSuchRemote from .plain_git import PlainGit class Pygit2Git(PlainGit): @staticmethod def is_on_branch(path): repo = pygit2.Repository(path) return not (repo.head_is_detached or repo.head_is_unborn) @staticmethod def get_remote_url(path, remote_name): repo = pygit2.Repository(path) for remote in repo.remotes: if remote.name == remote_name: break else: raise NoSuchRemote() return remote.url @staticmethod def add_remote(path, remote_name, remote_url): repo = pygit2.Repository(path) repo.create_remote(remote_name, remote_url)
Create albums for each folder instead of tags
import os import re import datetime from trovebox import Trovebox def main(): try: client = Trovebox() client.configure(api_version=2) except IOError, e: print print '!! Could not initialize Trovebox connection.' print '!! Check that ~/.config/trovebox/default exists and contains proper information.' print raise e starttime = datetime.datetime.now() for root, folders, files in os.walk(os.getcwd()): folder_name = album = None for filename in files: if not re.match(r'^.+\.jpg$', filename, flags=re.IGNORECASE): continue if not folder_name: folder_name = root.split('/')[-1] album = client.album.create(folder_name) print 'Entering folder %s' % root print 'Uploading %s...' % filename path = '%s/%s' % (root, filename) client.photo.upload(path, albums=[album.id]) print datetime.datetime.now() - starttime if __name__ == "__main__": main()
import os import re import datetime from trovebox import Trovebox def main(): try: client = Trovebox() client.configure(api_version=2) except IOError, e: print print '!! Could not initialize Trovebox connection.' print '!! Check that ~/.config/trovebox/default exists and contains proper information.' print raise e starttime = datetime.datetime.now() for root, folders, files in os.walk(os.getcwd()): folder_name = None for filename in files: if not re.match(r'^.+\.jpg$', filename, flags=re.IGNORECASE): continue if not folder_name: folder_name = root.split('/')[-1] print 'Entering folder %s' % root print 'Uploading %s...' % filename path = '%s/%s' % (root, filename) client.photo.upload(path, tags=['API test', folder_name]) print datetime.datetime.now() - starttime if __name__ == "__main__": main()
Add test for Cramer with different spatial sizes
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"][0]) self.tester3 = Cramer_Distance(dataset2["cube"][0], small_data) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance)
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance'])
Fix that crazy error that would cause enless looping...
#i = 0 #numbers = [] #while i < 6: # print "At the top i is %d" % i # numbers.append(i) # # i += 1 # print "Numbers now: ", numbers # print "At the bottom i is %d" % i # # #print "The numbers: " # #for num in numbers: # print num #Study Drills print "What's the limit of the list?" a = int(raw_input("> ")) def list_numbers(a): """This function might add numbers to a list?""" i = 0 numbers = [] while i < a: print "At the top i is %d" % i numbers.append(i) i += 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num return list_numbers(a)
#i = 0 #numbers = [] #while i < 6: # print "At the top i is %d" % i # numbers.append(i) # # i += 1 # print "Numbers now: ", numbers # print "At the bottom i is %d" % i # # #print "The numbers: " # #for num in numbers: # print num #Study Drills print "What's the limit of the list?" a = raw_input("> ") def list_numbers(a): """This function might add numbers to a list?""" i = 0 numbers = [] while i < a: print "At the top i is %d" % i numbers.append(i) i += 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num return list_numbers(a)
Add extra line for class in test admin Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
from web_test import WebTest from scoring_engine.models.team import Team from scoring_engine.models.user import User class TestAdmin(WebTest): def setup(self): super(TestAdmin, self).setup() team1 = Team(name="Team 1", color="White") self.db.save(team1) user1 = User(username='testuser', password='testpass', team=team1) self.db.save(user1) def auth_and_get_path(self, path): self.client.login('testuser', 'testpass') return self.client.get(path) def test_auth_required_admin(self): self.verify_auth_required('/admin') def test_auth_required_admin_status(self): self.verify_auth_required('/admin/status') stats_resp = self.auth_and_get_path('/admin/status') assert stats_resp.status_code == 200 def test_auth_required_admin_manage(self): self.verify_auth_required('/admin/manage') stats_resp = self.auth_and_get_path('/admin/manage') assert stats_resp.status_code == 200 def test_auth_required_admin_stats(self): self.verify_auth_required('/admin/stats') stats_resp = self.auth_and_get_path('/admin/stats') assert stats_resp.status_code == 200
from web_test import WebTest from scoring_engine.models.team import Team from scoring_engine.models.user import User class TestAdmin(WebTest): def setup(self): super(TestAdmin, self).setup() team1 = Team(name="Team 1", color="White") self.db.save(team1) user1 = User(username='testuser', password='testpass', team=team1) self.db.save(user1) def auth_and_get_path(self, path): self.client.login('testuser', 'testpass') return self.client.get(path) def test_auth_required_admin(self): self.verify_auth_required('/admin') def test_auth_required_admin_status(self): self.verify_auth_required('/admin/status') stats_resp = self.auth_and_get_path('/admin/status') assert stats_resp.status_code == 200 def test_auth_required_admin_manage(self): self.verify_auth_required('/admin/manage') stats_resp = self.auth_and_get_path('/admin/manage') assert stats_resp.status_code == 200 def test_auth_required_admin_stats(self): self.verify_auth_required('/admin/stats') stats_resp = self.auth_and_get_path('/admin/stats') assert stats_resp.status_code == 200
Revert "logs pyzabbix com variavel de ambiente" This reverts commit df796462b07f7470d86f4d0622a414c956a45ced.
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import sys from dbaas_zabbix.dbaas_api import DatabaseAsAServiceApi from dbaas_zabbix.provider_factory import ProviderFactory from pyzabbix import ZabbixAPI stream = logging.StreamHandler(sys.stdout) stream.setLevel(logging.DEBUG) log = logging.getLogger('pyzabbix') log.addHandler(stream) log.setLevel(logging.DEBUG) def factory_for(**kwargs): databaseinfra = kwargs['databaseinfra'] credentials = kwargs['credentials'] del kwargs['databaseinfra'] del kwargs['credentials'] zabbix_api = ZabbixAPI if kwargs.get('zabbix_api'): zabbix_api = kwargs.get('zabbix_api') del kwargs['zabbix_api'] dbaas_api = DatabaseAsAServiceApi(databaseinfra, credentials) return ProviderFactory.factory(dbaas_api, zabbix_api=zabbix_api, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import os import sys from dbaas_zabbix.dbaas_api import DatabaseAsAServiceApi from dbaas_zabbix.provider_factory import ProviderFactory from pyzabbix import ZabbixAPI LOG = logging.getLogger(__name__) def set_integration_logger(): stream = logging.StreamHandler(sys.stdout) stream.setLevel(logging.DEBUG) log = logging.getLogger('pyzabbix') log.addHandler(stream) log.setLevel(logging.DEBUG) def factory_for(**kwargs): databaseinfra = kwargs['databaseinfra'] credentials = kwargs['credentials'] del kwargs['databaseinfra'] del kwargs['credentials'] zabbix_api = ZabbixAPI if kwargs.get('zabbix_api'): zabbix_api = kwargs.get('zabbix_api') del kwargs['zabbix_api'] dbaas_api = DatabaseAsAServiceApi(databaseinfra, credentials) return ProviderFactory.factory(dbaas_api, zabbix_api=zabbix_api, **kwargs) ZABBIX_INTEGRATION_LOG = os.getenv('ZABBIX_INTEGRATION_LOG') == "1" LOG.info('ZABBIX_INTEGRATION_LOG = ' + str(ZABBIX_INTEGRATION_LOG)) if ZABBIX_INTEGRATION_LOG: LOG.info("Activating log stream for pyzabbix") set_integration_logger()
Use block quotes for Markov-chain plugin
"""Displays a randomly generated witticism from Brian Chu himself.""" import json import random __match__ = r"!brian" with open('plugins/brian_corpus/cache.json', 'r') as infile: cache = json.load(infile) with open('plugins/brian_corpus/phrases.json', 'r') as infile: phrases = json.load(infile) def generate_phrase(phrases, cache): seed_phrase = [] while len(seed_phrase) < 3: seed_phrase = random.choice(phrases).split() w1, w2 = seed_phrase[:2] chosen = [w1, w2] while "{}|{}".format(w1, w2) in cache: choice = random.choice(cache["{}|{}".format(w1, w2)]) w1, w2 = w2, choice chosen.append(choice) return ' '.join(chosen) def on_message(bot, channel, user, message): return '> {}'.format(generate_phrase(phrases, cache))
"""Displays a randomly generated witticism from Brian Chu himself.""" import json import random __match__ = r"!brian" with open('plugins/brian_corpus/cache.json', 'r') as infile: cache = json.load(infile) with open('plugins/brian_corpus/phrases.json', 'r') as infile: phrases = json.load(infile) def generate_phrase(phrases, cache): seed_phrase = [] while len(seed_phrase) < 3: seed_phrase = random.choice(phrases).split() w1, w2 = seed_phrase[:2] chosen = [w1, w2] while "{}|{}".format(w1, w2) in cache: choice = random.choice(cache["{}|{}".format(w1, w2)]) w1, w2 = w2, choice chosen.append(choice) return ' '.join(chosen) def on_message(bot, channel, user, message): return generate_phrase(phrases, cache)
Make sure we give an example for two servers.
# put this into ~/.alphahub/config.py and make sure it's # not readable by anyone else (it contains passwords!) # the host we run on and want to receive packets on; note # that "localhost" is probably the wrong thing here, you # want your actual host name here so the sockets bind the # right way and receive packets from the outside HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), "some.other.game.tld": (543, "monkeyspam"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
# put this into ~/.alphahub/config.py and make sure it's # not readable by anyone else (it contains passwords!) # the host we run on and want to receive packets on; note # that "localhost" is probably the wrong thing here, you # want your actual host name here so the sockets bind the # right way and receive packets from the outside HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
Move webroot definition into correct scope
/* @method gitPull Takes a flightplan instance and transport @param remote {Object} Flightplan transport instance @param webRoot {string} path to run git pull on the remote server e.g. /var/www/project */ var gitPull = function (remote, webRoot) { // git pull remote.with('cd ' + webRoot, function() { remote.exec('git pull'); }); }; /* @method addToPlan Takes a flightplan instance and adds a task called gitDeploy @param plan {Object} Flightplan instance @param plan.runtime.options.webRoot {String} Remote path to run git pull */ var addToPlan = function (plan) { // Task to git deploy via ssh remote plan.remote('gitDeploy', function(remote) { var webRoot = plan.runtime.options.webRoot; gitPull(remote, webRoot); }); }; module.exports = { addToPlan: addToPlan, gitPull: gitPull };
/* @method gitPull Takes a flightplan instance and transport @param remote {Object} Flightplan transport instance @param webRoot {string} path to run git pull on the remote server e.g. /var/www/project */ var gitPull = function (remote, webRoot) { // git pull remote.with('cd ' + webRoot, function() { remote.exec('git pull'); }); }; /* @method addToPlan Takes a flightplan instance and adds a task called gitDeploy @param plan {Object} Flightplan instance @param plan.runtime.options.webRoot {String} Remote path to run git pull */ var addToPlan = function (plan) { // Plan to git deploy via ssh remote var webRoot = plan.runtime.options.webRoot; plan.remote('gitDeploy', function(remote) { gitPull(remote, webRoot); }); }; module.exports = { addToPlan: addToPlan, gitPull: gitPull };
Change filter example to use KeyMap
package main import ( "bufio" "encoding/json" "fmt" "io" "os" "github.com/mgutz/logxi/v1" ) func sendExternal(obj map[string]interface{}) { // normally you would send this to an external service like InfluxDB // or some logging framework. Let's filter out some data. fmt.Printf("Time: %s Level: %s Message: %s\n", obj[log.KeyMap.Time], obj[log.KeyMap.Level], obj[log.KeyMap.Message], ) } func main() { r := bufio.NewReader(os.Stdin) dec := json.NewDecoder(r) for { var obj map[string]interface{} if err := dec.Decode(&obj); err == io.EOF { break } else if err != nil { log.InternalLog.Fatal("Could not decode", "err", err) } sendExternal(obj) } }
package main import ( "bufio" "encoding/json" "fmt" "io" "os" "github.com/mgutz/logxi/v1" ) func sendExternal(obj map[string]interface{}) { // normally you would send this to an external service like InfluxDB // or some logging framework. Let's filter out some data. fmt.Printf("Time: %s Level: %s Message: %s\n", obj[log.TimeKey], obj[log.LevelKey], obj[log.MessageKey], ) } func main() { r := bufio.NewReader(os.Stdin) dec := json.NewDecoder(r) for { var obj map[string]interface{} if err := dec.Decode(&obj); err == io.EOF { break } else if err != nil { log.InternalLog.Fatal("Could not decode", "err", err) } sendExternal(obj) } }
Destroy idle timer instance after test has finished
(function($) { /* ======== A Handy Little QUnit Reference ======== http://docs.jquery.com/QUnit Test methods: expect(numAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) raises(block, [expected], [message]) */ module("jQuery#idle-timer"); asyncTest( "default behavior", function() { expect( 1 ); $( document ).on( "idle.idleTimer", function(){ ok( true, "idleTime fires at document by default" ); start(); $.idleTimer( "destroy" ); }); $.idleTimer( 100 ); }); }(jQuery));
(function($) { /* ======== A Handy Little QUnit Reference ======== http://docs.jquery.com/QUnit Test methods: expect(numAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) raises(block, [expected], [message]) */ module("jQuery#idle-timer"); asyncTest( "default behavior", function() { expect( 1 ); $( document ).on( "idle.idleTimer", function(){ ok( true, "idleTime fires at document by default" ); start(); }); $.idleTimer( 100 ); }); }(jQuery));
Make this a post because it deletes data
var express = require('express'); var DataStore = require('./regard-data-store.js'); var router = express.Router(); var dataStore = new DataStore('regard', 'website'); router.get('/userevents/:id', function (req, res, next) { var id = req.params.id; dataStore.getEventsForUser(id).then(function (events) { res.json({ userevents: [{ _id: id, events: JSON.parse(events) }] }); }); }); router.post('/userevents/:id/delete-data', function (req, res, next) { var id = req.params.id; dataStore.deleteData(id).then(function () { res.send(200); }, next); }); module.exports = router;
var express = require('express'); var DataStore = require('./regard-data-store.js'); var router = express.Router(); var dataStore = new DataStore('regard', 'website'); router.get('/userevents/:id', function (req, res, next) { var id = req.params.id; dataStore.getEventsForUser(id).then(function (events) { res.json({ userevents: [{ _id: id, events: JSON.parse(events) }] }); }); }); router.get('/userevents/:id/delete-data', function (req, res, next) { var id = req.params.id; dataStore.deleteData(id).then(function () { res.send(200); }, next); }); module.exports = router;
Fix test_show test to support tuned systems
import os.path import sys from perf.tests import get_output from perf.tests import unittest class SystemTests(unittest.TestCase): def test_show(self): args = [sys.executable, '-m', 'perf', 'system', 'show'] proc = get_output(args) regex = ('(Run "%s -m perf system tune" to tune the system configuration to run benchmarks' '|OK! System ready for benchmarking' '|WARNING: no operation available for your platform)' % os.path.basename(sys.executable)) self.assertRegex(proc.stdout, regex, msg=proc) # The return code is either 0 if the system is tuned or 2 if the # system isn't self.assertIn(proc.returncode, (0, 2), msg=proc) if __name__ == "__main__": unittest.main()
import os.path import sys from perf.tests import get_output from perf.tests import unittest class SystemTests(unittest.TestCase): def test_show(self): args = [sys.executable, '-m', 'perf', 'system', 'show'] proc = get_output(args) regex = ('(Run "%s -m perf system tune" to tune the system configuration to run benchmarks' '|OK! System ready for benchmarking' '|WARNING: no operation available for your platform)' % os.path.basename(sys.executable)) self.assertRegex(proc.stdout, regex, msg=proc) self.assertEqual(proc.returncode, 2, msg=proc) if __name__ == "__main__": unittest.main()
Set Critical CSS before minimization
/** * Automatic Deploy * * @description: Deploy Task for an automated Build Process */ import gulp from 'gulp' import runSequence from 'run-sequence' const buildTask = (cb) => { // Overwrite the Changed Check global.checkChanged = true runSequence( [ 'version:bump', ], [ 'copy:launch', 'copy:fonts', 'rebuild:js', 'rebuild:images', 'copy:contentimages'<% if (projectUsage === 'Integrate in Wordpress' ) { %>, 'copy:wpconfig', 'copy:wpplugins'<% } %> ], [ 'compiler:css', 'compiler:html' ]<% if (projectcritical === true) { %>, [ 'optimize:criticalCss' ]<% } %>, [ 'minify:js', 'minify:contentimages', 'minify:inlineimages', 'minify:css' ], cb) } gulp.task('build', buildTask) module.exports = buildTask
/** * Automatic Deploy * * @description: Deploy Task for an automated Build Process */ import gulp from 'gulp' import runSequence from 'run-sequence' const buildTask = (cb) => { // Overwrite the Changed Check global.checkChanged = true runSequence( [ 'version:bump', ], [ 'copy:launch', 'copy:fonts', 'rebuild:js', 'rebuild:images', 'copy:contentimages'<% if (projectUsage === 'Integrate in Wordpress' ) { %>, 'copy:wpconfig', 'copy:wpplugins'<% } %> ], [ 'compiler:css', 'compiler:html' ], [ 'minify:js', 'minify:contentimages', 'minify:inlineimages', 'minify:css' ]<% if (projectcritical === true) { %>, [ 'optimize:criticalCss' ]<% } %>, cb) } gulp.task('build', buildTask) module.exports = buildTask
FIX : Version was not compatible with node Reason : webpack was using window
var webpack = require('webpack'), path = require('path'), CleanWebpackPlugin = require('clean-webpack-plugin'); var libraryName = 'webstompobs', dist = '/dist'; module.exports = { target: 'node', entry: __dirname + '/src/index.ts', context: path.resolve("./src"), output: { path: path.join(__dirname, dist), filename: libraryName + '.bundle.js', library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx' ] }, plugins: [ new CleanWebpackPlugin(['dist']) ], module: { rules: [ { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] } };
var webpack = require('webpack'), path = require('path'), CleanWebpackPlugin = require('clean-webpack-plugin'); var libraryName = 'webstompobs', dist = '/dist'; module.exports = { entry: __dirname + '/src/index.ts', context: path.resolve("./src"), output: { path: path.join(__dirname, dist), filename: libraryName + '.bundle.js', library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx' ] }, plugins: [ new CleanWebpackPlugin(['dist']) ], module: { rules: [ { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] } };
Add list listing view option
<?php /** * Listing component * * Helpers to format different kinds of content as columns in a list view. */ abstract class sqListing { // Formats basic text public static function text($text) { return $text; } // Formats a value as yes / no public static function bool($value) { if ($value) { return 'Yes'; } return 'No'; } // Formats date string public static function date($value) { return view::date(sq::config('list/date-format'), $value); } // Creates image from URL public static function image($value) { return '<img src="'.$value.'"/>'; } // Truncates text in listing public static function blurb($value) { return view::truncate($value, 50); } // Returns value formatted as currency public static function currency($price) { return '&#36;'.$price; } // Returns value as a link public static function link($url) { return '<a href="'.$url.'">'.$url.'</a>'; } // Displays model as a list of items public static function list($model) { if ($model->count()) { $model->layout->subList = true; return $model; } } } ?>
<?php /** * Listing component * * Helpers to format different kinds of content as columns in a list view. */ abstract class sqListing { // Formats basic text public static function text($text) { return $text; } // Formats a value as yes / no public static function bool($value) { if ($value) { return 'Yes'; } return 'No'; } // Formats date string public static function date($value) { return view::date(sq::config('list/date-format'), $value); } // Creates image from URL public static function image($value) { return '<img src="'.$value.'"/>'; } // Truncates text in listing public static function blurb($value) { return view::truncate($value, 50); } // Returns value formatted as currency public static function currency($price) { return '&#36;'.$price; } // Returns value as a link public static function link($url) { return '<a href="'.$url.'">'.$url.'</a>'; } } ?>
Remove unused imports of .h files from implementaion for darwin
// +build darwin package daemon import ( "syscall" "unsafe" ) import "C" // darwin's MAXPATHLEN const maxpathlen = 1024 func lockFile(fd uintptr) error { err := syscall.Flock(int(fd), syscall.LOCK_EX|syscall.LOCK_NB) if err == syscall.EWOULDBLOCK { err = ErrWouldBlock } return err } func unlockFile(fd uintptr) error { err := syscall.Flock(int(fd), syscall.LOCK_UN) if err == syscall.EWOULDBLOCK { err = ErrWouldBlock } return err } func getFdName(fd uintptr) (name string, err error) { buf := make([]C.char, maxpathlen+1) _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fd, syscall.F_GETPATH, uintptr(unsafe.Pointer(&buf[0]))) if errno == 0 { return C.GoString(&buf[0]), nil } return "", errno }
// +build darwin package daemon /* #define __DARWIN_UNIX03 0 #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include <dirent.h> #include <fcntl.h> #include <sys/param.h> */ import "C" import ( "syscall" "unsafe" ) func lockFile(fd uintptr) error { err := syscall.Flock(int(fd), syscall.LOCK_EX|syscall.LOCK_NB) if err == syscall.EWOULDBLOCK { err = ErrWouldBlock } return err } func unlockFile(fd uintptr) error { err := syscall.Flock(int(fd), syscall.LOCK_UN) if err == syscall.EWOULDBLOCK { err = ErrWouldBlock } return err } func getFdName(fd uintptr) (name string, err error) { buf := make([]C.char, int(C.MAXPATHLEN)+1) _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fd, syscall.F_GETPATH, uintptr(unsafe.Pointer(&buf[0]))) if errno == 0 { return C.GoString(&buf[0]), nil } return "", errno }
Use `getOwnPropertyNames` instead of `keys` to retrieve list of keys
import Ember from 'ember'; const [major, minor] = Ember.VERSION.split('.'); const isGlimmer = major > 2 || (major == 2 && minor >= 10); // >= 2.10 let hasBlockSymbol; if (major == 3 && minor >= 1) { // do nothing since the symbol is not exported } else if (isGlimmer) { hasBlockSymbol = Ember.__loader.require('ember-glimmer/component')[ 'HAS_BLOCK' ]; } else { hasBlockSymbol = Ember.__loader.require('ember-htmlbars/component')[ 'HAS_BLOCK' ]; } // NOTE: I really don't know how to test this export default function hasBlock(emberComponent) { // Since Glimmer moved to TypeScript, we can't get the symbol. // This is a terrible but working way to get the value. if (!hasBlockSymbol) { const regex = /HAS_BLOCK/; hasBlockSymbol = Object.getOwnPropertyNames(emberComponent).find(key => regex.test(key) ); } return Ember.get(emberComponent, hasBlockSymbol); }
import Ember from 'ember'; const [major, minor] = Ember.VERSION.split('.'); const isGlimmer = major > 2 || (major == 2 && minor >= 10); // >= 2.10 let hasBlockSymbol; if (major == 3 && minor >= 1) { // do nothing since the symbol is not exported } else if (isGlimmer) { hasBlockSymbol = Ember.__loader.require('ember-glimmer/component')[ 'HAS_BLOCK' ]; } else { hasBlockSymbol = Ember.__loader.require('ember-htmlbars/component')[ 'HAS_BLOCK' ]; } // NOTE: I really don't know how to test this export default function hasBlock(emberComponent) { // Since Glimmer moved to TypeScript, we can't get the symbol. // This is a terrible but working way to get the value. if (!hasBlockSymbol) { const regex = /HAS_BLOCK/; hasBlockSymbol = Object.keys(emberComponent).find(key => regex.test(key)); } return Ember.get(emberComponent, hasBlockSymbol); }
tools: Fix externs definitions for Q Set the method Q.resolve and Q.reject to take an optional variadic parameter of any type.
var Q = {}; /** * @constructor */ function QDeferred () {}; /** * @param {...*} args */ QDeferred.prototype.reject = function (args) {}; /** * @param {...*} args */ QDeferred.prototype.resolve = function (args) {}; /** * @type {string} */ QDeferred.prototype.state; /** * @type {string} */ QDeferred.prototype.reason; /** * @returns {QDeferred} */ Q.defer = function () {}; /** * @constructor */ function QPromise () {}; QPromise.prototype.then = function (args) {}; QPromise.prototype.catch = function (args) {}; /** * @returns {QPromise} */ Q.promise = function() {}; /** * @returns {QPromise} * @param {Array<QPromise>} promises */ Q.allSettled = function (promises) {}; /** * @returns {QPromise} * @param {Array<QPromise>} promises */ Q.all = function (promises) {}; /** * @returns {QPromise} * @param {function(...?):?} fn * @param {...*} args */ Q.nfcall = function (fn, args) {};
var Q = {}; /** * @constructor */ function QDeferred () {}; QDeferred.prototype.reject = function (args) {}; QDeferred.prototype.resolve = function (args) {}; /** * @type {string} */ QDeferred.prototype.state; /** * @type {string} */ QDeferred.prototype.reason; /** * @returns {QDeferred} */ Q.defer = function () {}; /** * @constructor */ function QPromise () {}; QPromise.prototype.then = function (args) {}; QPromise.prototype.catch = function (args) {}; /** * @returns {QPromise} */ Q.promise = function() {}; /** * @returns {QPromise} * @param {Array<QPromise>} promises */ Q.allSettled = function (promises) {}; /** * @returns {QPromise} * @param {Array<QPromise>} promises */ Q.all = function (promises) {}; /** * @returns {QPromise} * @param {function(...?):?} fn * @param {...*} args */ Q.nfcall = function (fn, args) {};
Restructure session handling in sqlalchemy.
import os import sqlite3 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import ConvertRequest, Base class Database(object): db_connection_string = None engine = None session_maker = None def __init__(self, path, echo): if not os.path.exists(os.path.dirname(path)): raise Exception("Path doesn't exists.") Database.db_connection_string = "sqlite:///" + path Database.engine = create_engine(Database.db_connection_string, echo=echo) Database.session_maker = sessionmaker(bind=Database.engine) Base.metadata.create_all(Database.engine) self.session = None def add(self, cr: ConvertRequest): try: self.session.add(cr) self.session.commit() return True except: return False def retrieve(self, id): req = self.session.query(ConvertRequest).filter_by(id=id).first() return req def update(self): # TODO: Update status and result of conversion jobs. self.session.commit() pass def renew(self): self.session = Database.session_maker() def finalize(self): self.session.commit() self.session.close()
import os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import ConvertRequest, Base class Database(object): db_connection_string = None engine = None Session = None def __init__(self, path, echo): if not os.path.exists(os.path.dirname(path)): raise Exception("Path doesn't exists.") Database.db_connection_string = "sqlite:///" + path Database.engine = create_engine(Database.db_connection_string, echo=echo) Database.Session = sessionmaker(bind=Database.engine) Base.metadata.create_all(Database.engine) def add(self, cr: ConvertRequest): try: session = Database.Session() session.add(cr) session.commit() return True except: return False def retrieve(self, id): session = Database.Session() return session.query(ConvertRequest).filter_by(id=id).first() def update(self): # TODO: Update status and result of conversion jobs. pass
Leverage isort's check mode to make our logic simpler This avoids having to check for in_lines or compare against the out_lines by just asking for a check and using the results
from isort import SortImports import mothermayi.colors import mothermayi.errors import mothermayi.files def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename, check=True) return results.incorrectly_sorted def get_status(had_changes): return mothermayi.colors.red('unsorted') if had_changes else mothermayi.colors.green('sorted') def pre_commit(config, staged): python_files = list(mothermayi.files.python_source(staged)) if not python_files: return changes = [do_sort(filename) for filename in python_files] messages = [get_status(had_change) for had_change in changes] lines = [" {0:<30} ... {1:<10}".format(filename, message) for filename, message in zip(python_files, messages)] result = "\n".join(lines) if any(changes): raise mothermayi.errors.FailHook(result) return result
from isort import SortImports import mothermayi.colors import mothermayi.errors import mothermayi.files def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return getattr(results, 'in_lines', None) and results.in_lines != results.out_lines def get_status(had_changes): return mothermayi.colors.red('unsorted') if had_changes else mothermayi.colors.green('sorted') def pre_commit(config, staged): python_files = list(mothermayi.files.python_source(staged)) if not python_files: return changes = [do_sort(filename) for filename in python_files] messages = [get_status(had_change) for had_change in changes] lines = [" {0:<30} ... {1:<10}".format(filename, message) for filename, message in zip(python_files, messages)] result = "\n".join(lines) if any(changes): raise mothermayi.errors.FailHook(result) return result
Trim value before checking if string is empty
/* * Copyright 2015 Martijn van der Woud - The Crimson Cricket Internet Services * * 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.crimsoncricket.asserts; import java.util.Collection; public class Assert { public static void assertStateNotNull(Object anObject, String message) { if (anObject == null) throw new IllegalStateException(message); } public static void assertArgumentNotNull(Object anArgument, String message) { if (anArgument == null) throw new IllegalArgumentException(message); } public static void assertStringArgumentNotEmpty(String anArgument, String message) { if (anArgument.trim().isEmpty()) throw new IllegalArgumentException(message); } public static void assertArgumentCollectionNotContainsNull(Collection<?> anArgument, String message) { if (anArgument.stream().anyMatch(element -> element == null)) throw new IllegalArgumentException(message); } }
/* * Copyright 2015 Martijn van der Woud - The Crimson Cricket Internet Services * * 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.crimsoncricket.asserts; import java.util.Collection; public class Assert { public static void assertStateNotNull(Object anObject, String message) { if (anObject == null) throw new IllegalStateException(message); } public static void assertArgumentNotNull(Object anArgument, String message) { if (anArgument == null) throw new IllegalArgumentException(message); } public static void assertStringArgumentNotEmpty(String anArgument, String message) { if (anArgument.isEmpty()) throw new IllegalArgumentException(message); } public static void assertArgumentCollectionNotContainsNull(Collection<?> anArgument, String message) { if (anArgument.stream().anyMatch(element -> element == null)) throw new IllegalArgumentException(message); } }
Rename "open" method to "show"
var React = require('react/addons'); var Notification = React.createClass({ /** * @function hide * @description Focus on the element. */ show: function () { this.setState({ active: true }); }, /** * @function hide * @description Focus on the element. */ hide: function () { this.setState({ active: false }); }, propTypes: { message: React.PropTypes.string.isRequired, action: React.PropTypes.string, onClick: React.PropTypes.func }, getInitialState: function () { return { active: false }; }, getDefaultProps: function () { return { action: 'Dismiss', onClick: function () { this.hide(); } }; }, render: function () { return ( <div className="notificiation-bar"> <div className="notification-bar-wrapper" onClick={this.props.onClick}> <span className="notification-bar-message">{this.props.message}</span> <span className="notification-bar-action">{this.props.action}</span> </div> </div> ); } }); module.exports = Notification;
var React = require('react/addons'); var Notification = React.createClass({ /** * @function hide * @description Focus on the element. */ open: function () { this.setState({ active: true }); }, /** * @function hide * @description Focus on the element. */ hide: function () { this.setState({ active: false }); }, propTypes: { message: React.PropTypes.string.isRequired, action: React.PropTypes.string, onClick: React.PropTypes.func }, getInitialState: function () { return { active: false }; }, getDefaultProps: function () { return { action: 'Dismiss', onClick: function () { this.hide(); } }; }, render: function () { return ( <div className="notificiation-bar"> <div className="notification-bar-wrapper" onClick={this.props.onClick}> <span className="notification-bar-message">{this.props.message}</span> <span className="notification-bar-action">{this.props.action}</span> </div> </div> ); } }); module.exports = Notification;
Revert "Fix JSON encoding of `PacketLocation`" This reverts commit 9e91912c6c1764c88890ec47df9372e6ac41612c.
import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ])
import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) def encode(self, obj): # If a builtin type provides a `serialize` method, use that instead of # the default serialisation, eg. namedtuple if getattr(obj, 'serialize', None): obj = obj.serialize() return super(OpenPGPJsonEncoder, self).encode(obj) @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ])
Move admin flag as separate method
from flask import g from flask.views import View class BaseController(View): """Base Controller The base controller of this module, it shows how to make 'class based controller' with 'Flask Pluggable view'. You can make controller inherited from BaseController not from Flask.View class ExampleController(BaseController): # your methods """ methods = [] decorators = [] def show_admin_nav(self): """Show admin navigation flag This is just a boolean flag to help admin menu in top navigation bar should show or not. TODO: Make better implementation that show/hide admin menu """ return True def is_form_valid(self, form): """Validate form It wraps the flask-wtf `validate_on_submit`, it needs flask-wtf form object to be passed in. """ return form.validate_on_submit() def get_site_data(self): """Placeholder of site data It gets site data from `site_setting` decorator. """ return g.school def dispatch_request(self): pass
from flask import g from flask.views import View class BaseController(View): """Base Controller The base controller of this module, it shows how to make 'class based controller' with 'Flask Pluggable view'. You can make controller inherited from BaseController not from Flask.View class ExampleController(BaseController): # your methods """ methods = [] decorators = [] def is_form_valid(self, form): """Validate form It wraps the flask-wtf `validate_on_submit`, it needs flask-wtf form object to be passed in. """ return form.validate_on_submit() def get_site_data(self): """Placeholder of site data It gets site data from `site_setting` decorator. """ return g.school def dispatch_request(self): pass
Add some more trigger messages
#!/usr/bin/env node 'use strict'; var Slack = require('slack-client'); var token = process.argv[2]; var trigger = /(q+u+o+i+|k+o+i+|k+o+a+|c+o+m+e+n+t+)\s*[?!]*$/; if (!token) { console.error([ 'Usage: feurbot <token>', null, 'To generate a token, create a bot at http://my.slack.com/services/new/bot' ].join('\n')); process.exit(1); } var slack = new Slack(token); slack.on('message', function (message) { if (message.type !== 'message') { return; } if (!trigger.test(message.text) && Math.random() < 0.99) { return; } var channel = slack.getChannelGroupOrDMByID(message.channel); var before = 'FEEEEEUUUUUUUR !'; var after = Math.random() < .5 ? '(bim !)' : '(boum !)'; var msg = channel.send(before); setTimeout(function() { msg.updateMessage(before + ' ' + after); }, 700); }); slack.on('error', function (err) { if (err === 'invalid_auth') { console.error('Invalid token, go grab a valid one!') process.exit(1); } console.error(err); }); slack.login();
#!/usr/bin/env node 'use strict'; var Slack = require('slack-client'); var token = process.argv[2]; if (!token) { console.error([ 'Usage: feurbot <token>', null, 'To generate a token, create a bot at http://my.slack.com/services/new/bot' ].join('\n')); process.exit(1); } var slack = new Slack(token); slack.on('message', function (message) { if (message.type !== 'message') { return; } if (!/quoi\s*[?!]*$/.test(message.text) && Math.random() < 0.99) { return; } var channel = slack.getChannelGroupOrDMByID(message.channel); var before = 'FEEEEEUUUUUUUR !'; var after = Math.random() < .5 ? '(bim !)' : '(boum !)'; var msg = channel.send(before); setTimeout(function() { msg.updateMessage(before + ' ' + after); }, 700); }); slack.on('error', function (err) { if (err === 'invalid_auth') { console.error('Invalid token, go grab a valid one!') process.exit(1); } console.error(err); }); slack.login();
Increase waitforTimeout to 60 seconds
exports.config = { specs: [ './test/**/*.js' ], exclude: [ ], sync: true, logLevel: 'silent', coloredLogs: true, bail: 0, screenshotPath: 'screenshots', baseUrl: 'http://localhost:3000', framework: 'mocha', mochaOpts: { ui: 'bdd', }, reporters: [ 'spec' ], waitforTimeout: 60000, connectionRetryTimeout: 90000, connectionRetryCount: 3, services: [ 'browserstack' ], maxInstances: 1, capabilities: [ { browserName: 'chrome', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'safari', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'firefox', project: 'telepathy-web', 'browserstack.local': true, }, ], browserstackLocal: true, user: process.env.BROWSERSTACK_USER, key: process.env.BROWSERSTACK_PASS, };
exports.config = { specs: [ './test/**/*.js' ], exclude: [ ], sync: true, logLevel: 'silent', coloredLogs: true, bail: 0, screenshotPath: 'screenshots', baseUrl: 'http://localhost:3000', framework: 'mocha', mochaOpts: { ui: 'bdd', }, reporters: [ 'spec' ], waitforTimeout: 30000, connectionRetryTimeout: 90000, connectionRetryCount: 3, services: [ 'browserstack' ], maxInstances: 1, capabilities: [ { browserName: 'chrome', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'safari', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'firefox', project: 'telepathy-web', 'browserstack.local': true, }, ], browserstackLocal: true, user: process.env.BROWSERSTACK_USER, key: process.env.BROWSERSTACK_PASS, };
Fix NotOnJavaFXThread exception for remote import
package org.jabref.gui.remote; import java.util.Arrays; import java.util.List; import javafx.application.Platform; import org.jabref.JabRefGUI; import org.jabref.cli.ArgumentProcessor; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.remote.server.MessageHandler; public class JabRefMessageHandler implements MessageHandler { @Override public void handleCommandLineArguments(String[] message) { ArgumentProcessor argumentProcessor = new ArgumentProcessor(message, ArgumentProcessor.Mode.REMOTE_START); if (!(argumentProcessor.hasParserResults())) { throw new IllegalStateException("Could not start JabRef with arguments " + Arrays.toString(message)); } List<ParserResult> loaded = argumentProcessor.getParserResults(); for (int i = 0; i < loaded.size(); i++) { ParserResult pr = loaded.get(i); boolean focusPanel = i == 0; Platform.runLater(() -> // Need to run this on the JavaFX thread JabRefGUI.getMainFrame().addParserResult(pr, focusPanel) ); } } }
package org.jabref.gui.remote; import java.util.Arrays; import java.util.List; import org.jabref.JabRefGUI; import org.jabref.cli.ArgumentProcessor; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.remote.server.MessageHandler; public class JabRefMessageHandler implements MessageHandler { @Override public void handleCommandLineArguments(String[] message) { ArgumentProcessor argumentProcessor = new ArgumentProcessor(message, ArgumentProcessor.Mode.REMOTE_START); if (!(argumentProcessor.hasParserResults())) { throw new IllegalStateException("Could not start JabRef with arguments " + Arrays.toString(message)); } List<ParserResult> loaded = argumentProcessor.getParserResults(); for (int i = 0; i < loaded.size(); i++) { ParserResult pr = loaded.get(i); JabRefGUI.getMainFrame().addParserResult(pr, i == 0); } } }
Add test for ignore existing property for object literal completion
// environment=browser // environment=jquery // plugin=requirejs {"override": {"jquery": "=$"}} requirejs(["foo", "bar!abc", "useexports", "simplifiedcommon", "subdir/zap"], function(foo, bar, useexports, simplified, zap) { foo.aString; //: string bar.aNumber; //: number bar.baz.bazProp; //: Date bar.baz.bazFooProp; //: string useexports.hello; //: bool simplified.hello; //: string simplified.func; //: fn() -> bool zap; //: string foo; //origin: foo.js bar; //origin: bar.js bar.baz; //origin: baz.js }); requirejs(["jquery"], function($) { $.fx.off; //: bool }); requirejs(["require"], function(require) { require("jquery").fx.off; //: bool require("requireme").someprop; //: string }); requirejs.config({ p //+ packages, paths, ... }); requirejs.config({ //+ baseUrl, config, context, map, nodeIdCompat, packages, paths, shim, ... }); requirejs.config({ baseUrl: '', //+ config, context, map, nodeIdCompat, packages, paths, shim, ... });
// environment=browser // environment=jquery // plugin=requirejs {"override": {"jquery": "=$"}} requirejs(["foo", "bar!abc", "useexports", "simplifiedcommon", "subdir/zap"], function(foo, bar, useexports, simplified, zap) { foo.aString; //: string bar.aNumber; //: number bar.baz.bazProp; //: Date bar.baz.bazFooProp; //: string useexports.hello; //: bool simplified.hello; //: string simplified.func; //: fn() -> bool zap; //: string foo; //origin: foo.js bar; //origin: bar.js bar.baz; //origin: baz.js }); requirejs(["jquery"], function($) { $.fx.off; //: bool }); requirejs(["require"], function(require) { require("jquery").fx.off; //: bool require("requireme").someprop; //: string }); requirejs.config({ p //+ packages, paths, ... }); requirejs.config({ //+ baseUrl, config, context, map, nodeIdCompat, packages, paths, shim, ... });
Update to take name from state and not props
import React, { Component } from 'react' import HouseholdService from '../services/HouseholdService' class Household extends Component { constructor(props) { super(props) this.state = { name: '' } } componentWillReceiveProps(nextProps) { const { id } = nextProps.match.params HouseholdService.fetchHousehold(id) .then(household => this.setState({ name: household.name })) } componentDidMount() { const { id } = this.props.match.params HouseholdService.fetchHousehold(id) .then(household => this.setState({ name: household.name })) } render() { const { name } = this.state return ( <div> <h3>{name}</h3> </div> ) } } export default Household
import React, { Component } from 'react' import HouseholdService from '../services/HouseholdService' class Household extends Component { constructor(props) { super(props) this.state = { name: '' } } componentWillReceiveProps(nextProps) { const { id } = nextProps.match.params HouseholdService.fetchHousehold(id) .then(household => this.setState({ name: household.name })) } componentDidMount() { const { id } = this.props.match.params HouseholdService.fetchHousehold(id) .then(household => this.setState({ name: household.name })) } render() { const { name } = this.props return ( <div> <h3>{name}</h3> </div> ) } } export default Household
Add cascade deletion for Appointments->[Contact|Business] relationships
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAppointmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('appointments', function(Blueprint $table) { $table->increments('id'); $table->integer('contact_id')->unsigned(); $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade'); $table->integer('business_id')->unsigned(); $table->foreign('business_id')->references('id')->on('businesses')->onDelete('cascade'); $table->string('hash', 32)->unique(); $table->enum('status', ['R','C', 'A', 'S']); // Reserved, Confirmed, Annulated, Served $table->timestamp('start_at')->index(); $table->integer('duration')->nullable(); $table->json('services')->nullable(); $table->string('comments')->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('appointments'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAppointmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('appointments', function(Blueprint $table) { $table->increments('id'); $table->integer('contact_id')->unsigned(); $table->foreign('contact_id')->references('id')->on('contacts'); $table->integer('business_id')->unsigned(); $table->foreign('business_id')->references('id')->on('businesses'); $table->string('hash', 32)->unique(); $table->enum('status', ['R','C', 'A', 'S']); // Reserved, Confirmed, Annulated, Served $table->timestamp('start_at')->index(); $table->integer('duration')->nullable(); $table->json('services')->nullable(); $table->string('comments')->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('appointments'); } }
Test if request is the issue
const request = require('request'); const jsdom = require('jsdom'); const utils = require('../misc/utils'); const globals = require('../globals'); const database = require('../database/database'); const shuffle = require('knuth-shuffle').knuthShuffle const validate = linkOrUri => { const link = utils.linkOrUriToLink(linkOrUri); return new Promise((resolve, reject) => { link.size = 1000; resolve(link) // request( // { uri: link.href, timeout: globals.maxValidationRequestTime }, // (error, response, body) => { // if ( // !error && // response.statusCode === 200 && // utils.isImageResponse(response) && // response.headers['content-length'] < globals.maxLinkSize && // utils.isNotInvalidImgur(response) // ) { // link.size = response.headers['content-length']; // resolve(link); // } else { // database.insertInvalidLinkId(link.linkId) // .then(() => reject(link)); // } // } // ); }) } module.exports = validate;
const request = require('request'); const jsdom = require('jsdom'); const utils = require('../misc/utils'); const globals = require('../globals'); const database = require('../database/database'); const shuffle = require('knuth-shuffle').knuthShuffle const validate = linkOrUri => { const link = utils.linkOrUriToLink(linkOrUri); return new Promise((resolve, reject) => { request( { uri: link.href, timeout: globals.maxValidationRequestTime }, (error, response, body) => { if ( !error && response.statusCode === 200 && utils.isImageResponse(response) && response.headers['content-length'] < globals.maxLinkSize && utils.isNotInvalidImgur(response) ) { link.size = response.headers['content-length']; resolve(link); } else { database.insertInvalidLinkId(link.linkId) .then(() => reject(link)); } } ); }) } module.exports = validate;
Add a real prime number test
<?php namespace Calendar\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Scarlett\Controller\Controller; use Calendar\Model\LeapYear; class LeapYearController extends Controller { public function indexAction(Request $request, $year) { $leapyear = new LeapYear(); if ($leapyear->isLeapYear($year)) { $message = 'Yep, this is a leap year!'; }else{ $message = 'Nope, this is not a leap year!'; } return $this->render('leapYear', array('message' => $message)); } public function primeAction(Request $request, $number) { $message = "It's prime!"; for($i=$number-1;$i>=2;$i--) { if($number%$i == 0) { $message =" It's not prime!"; break; } } return $this->render('primeNumber', array('message' => $message)); } }
<?php namespace Calendar\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Scarlett\Controller\Controller; use Calendar\Model\LeapYear; class LeapYearController extends Controller { public function indexAction(Request $request, $year) { $leapyear = new LeapYear(); if ($leapyear->isLeapYear($year)) { $message = 'Yep, this is a leap year!'; }else{ $message = 'Nope, this is not a leap year!'; } return $this->render('leapYear', array('message' => $message)); } public function primeAction(Request $request, $number) { if($number%$number == 0 && $number%1 == 0){ $message = 'Prime number'; }else{ $message = 'Not prime'; } return $this->render('primeNumber', array('message' => $message)); } }
Fix lost grid reload callback after ajax grid reload.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require bootstrap-sprockets //= require 'moment' //= require bootstrap-datetimepicker //= require_tree . $('.container').on('click', 'tr.add-meal button.close', function() { $(this).closest('tr.add-meal').prev('tr.hidden').andSelf().toggleClass('hidden'); }); $('.container').on('click', '.js-filter-form :reset', function(e) { e.preventDefault(); this.form.reset(); $(this.form).find(':submit').click(); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require bootstrap-sprockets //= require 'moment' //= require bootstrap-datetimepicker //= require_tree . $('.container').on('click', 'tr.add-meal button.close', function() { $(this).closest('tr.add-meal').prev('tr.hidden').andSelf().toggleClass('hidden'); }); $('.js-filter-form :reset').click(function(e){ e.preventDefault(); this.form.reset(); $(this.form).find(':submit').click(); });
Make the 2 mandatory parameters mandatory. Make the help message a bit clearer and provides an example.
#!/usr/bin/env python3 # https://faq.i3wm.org/question/3699/how-can-i-open-an-application-when-i-open-a-certain-workspace-for-the-first-time/ from argparse import ArgumentParser import i3ipc i3 = i3ipc.Connection() parser = ArgumentParser(description="""Open the given application each time the given workspace is created. For instance, running 'app-on-ws-init.py 6 i3-sensible-terminal' should open your terminal as soon as you create the workspace 6. """) parser.add_argument('workspace', metavar='WS_NAME', help='The name of the workspace') parser.add_argument('command', metavar='CMD', help='The command to run on the newly initted workspace') args = parser.parse_args() def on_workspace(i3, e): if e.current.props.name == args.workspace and not len(e.current.leaves()): i3.command('exec {}'.format(args.command)) i3.on('workspace::focus', on_workspace) i3.main()
#!/usr/bin/env python3 # https://faq.i3wm.org/question/3699/how-can-i-open-an-application-when-i-open-a-certain-workspace-for-the-first-time/ from argparse import ArgumentParser import i3ipc i3 = i3ipc.Connection() parser = ArgumentParser(description='Open an application on a given workspace when it is initialized') parser.add_argument('--workspace', metavar='NAME', help='The name of the workspace') parser.add_argument('--command', metavar='CMD', help='The command to run on the newly initted workspace') args = parser.parse_args() def on_workspace(i3, e): if e.current.props.name == args.workspace and not len(e.current.leaves()): i3.command('exec {}'.format(args.command)) i3.on('workspace::focus', on_workspace) i3.main()
Fix pycroft backend displaying wrong finance balance
# -*- coding: utf-8 -*- from __future__ import annotations from decimal import Decimal from typing import List, Optional from sipa.model.pycroft.unserialize import unserializer @unserializer class UserData: id: int user_id: str login: str name: str status: UserStatus room: str mail: str cache: bool traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: Decimal finance_history: List[FinanceHistoryEntry] # TODO implement `cls.Meta.custom_constructors`, use `parse_date` for this last_finance_update: str # TODO introduce properties once they can be excluded @unserializer class UserStatus: member: bool traffic_exceeded: bool network_access: bool account_balanced: bool violation: bool @unserializer class Interface: id: int mac: str ips: List[str] @unserializer class TrafficHistoryEntry: timestamp: str ingress: Optional[int] egress: Optional[int] @unserializer class FinanceHistoryEntry: valid_on: str amount: int description: str
# -*- coding: utf-8 -*- from __future__ import annotations from typing import List, Optional from sipa.model.pycroft.unserialize import unserializer @unserializer class UserData: id: int user_id: str login: str name: str status: UserStatus room: str mail: str cache: bool traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: int finance_history: List[FinanceHistoryEntry] # TODO implement `cls.Meta.custom_constructors`, use `parse_date` for this last_finance_update: str # TODO introduce properties once they can be excluded @unserializer class UserStatus: member: bool traffic_exceeded: bool network_access: bool account_balanced: bool violation: bool @unserializer class Interface: id: int mac: str ips: List[str] @unserializer class TrafficHistoryEntry: timestamp: str ingress: Optional[int] egress: Optional[int] @unserializer class FinanceHistoryEntry: valid_on: str amount: int description: str
Use bot messages instead of telegram in handler
package bot import "github.com/graffic/wanon/telegram" // RouteNothing do nothing in handling const RouteNothing = 0 const ( // RouteAccept handle the message RouteAccept = 1 << iota // RouteStop stop handling more messages after this one RouteStop ) // Message from the telegram router type Message struct { *telegram.Message *telegram.AnswerBack } // Handler pairs a check and a handle function type Handler interface { Check(messages *Message) int Handle(messages *Message) } // Router stores handlers for messages type Router struct { handles []Handler } // AddHandler adds a handler to the router func (router *Router) AddHandler(handler Handler) { router.handles = append(router.handles, handler) } // RouteMessages checks which handler is the destination of a message func (router *Router) RouteMessages(messages chan *telegram.Message, context *Context) { for { message := <-messages answer := telegram.AnswerBack{API: context.API, Message: message} routerMessage := Message{message, &answer} for _, handler := range router.handles { result := handler.Check(&routerMessage) if (result & RouteAccept) > 0 { handler.Handle(&routerMessage) } if (result & RouteStop) > 0 { break } } } }
package bot import ( "github.com/graffic/wanon/telegram" ) // RouteNothing do nothing in handling const RouteNothing = 0 const ( // RouteAccept handle the message RouteAccept = 1 << iota // RouteStop stop handling more messages after this one RouteStop ) // Handler pairs a check and a handle function type Handler interface { Check(*telegram.Message, *Context) int Handle(*telegram.Message, *Context) } // Router stores handlers for messages type Router struct { handles []Handler } // AddHandler adds a handler to the router func (router *Router) AddHandler(handler Handler) { router.handles = append(router.handles, handler) } // RouteMessages checks which handler is the destination of a message func (router *Router) RouteMessages(messages chan *telegram.Message, context *Context) { for { message := <-messages for _, handler := range router.handles { result := handler.Check(message, context) if (result & RouteAccept) > 0 { handler.Handle(message, context) } if (result & RouteStop) > 0 { break } } } }
Fix no out element case
class BindInOut { constructor(bindIn, bindOut) { this.in = bindIn; this.out = bindOut; this.eventWrapper = {}; this.eventType = /(INPUT|TEXTAREA)/.test(bindIn.tagName) ? 'keyup' : 'change'; } addEvents() { this.eventWrapper.updateOut = this.updateOut.bind(this); this.in.addEventListener(this.eventType, this.eventWrapper.updateOut); return this; } updateOut() { this.out.textContent = this.in.value; return this; } removeEvents() { this.in.removeEventListener(this.eventType, this.eventWrapper.updateOut); return this; } static initAll() { const ins = document.querySelectorAll('*[data-bind-in]'); return [].map.call(ins, anIn => BindInOut.init(anIn)); } static init(anIn, anOut) { const out = anOut || document.querySelector(`*[data-bind-out="${anIn.dataset.bindIn}"]`); if (!out) return; const bindInOut = new BindInOut(anIn, out); return bindInOut.addEvents().updateOut(); } } export default BindInOut;
class BindInOut { constructor(bindIn, bindOut) { this.in = bindIn; this.out = bindOut; this.eventWrapper = {}; this.eventType = /(INPUT|TEXTAREA)/.test(bindIn.tagName) ? 'keyup' : 'change'; } addEvents() { this.eventWrapper.updateOut = this.updateOut.bind(this); this.in.addEventListener(this.eventType, this.eventWrapper.updateOut); return this; } updateOut() { this.out.textContent = this.in.value; return this; } removeEvents() { this.in.removeEventListener(this.eventType, this.eventWrapper.updateOut); return this; } static initAll() { const ins = document.querySelectorAll('*[data-bind-in]'); return [].map.call(ins, anIn => BindInOut.init(anIn)); } static init(anIn, anOut) { const out = anOut || document.querySelector(`*[data-bind-out="${anIn.dataset.bindIn}"]`); const bindInOut = new BindInOut(anIn, out); return bindInOut.addEvents().updateOut(); } } export default BindInOut;
emoji: Clarify what these "key"s are. These are keys, yes -- in particular, they're IDs of these realm emoji. The latter is more informative.
/* @flow */ import { createSelector } from 'reselect'; import { getRawRealmEmoji } from '../directSelectors'; import { getAuth } from '../account/accountSelectors'; import { getFullUrl } from '../utils/url'; export const getAllRealmEmojiById = createSelector(getAuth, getRawRealmEmoji, (auth, emojis) => Object.keys(emojis).reduce((result, id) => { result[id] = { ...emojis[id], source_url: getFullUrl(emojis[id].source_url, auth.realm) }; return result; }, {}), ); export const getActiveRealmEmojiById = createSelector(getAllRealmEmojiById, emojis => Object.keys(emojis) .filter(id => !emojis[id].deactivated) .reduce((result, id) => { result[id] = emojis[id]; return result; }, {}), );
/* @flow */ import { createSelector } from 'reselect'; import { getRawRealmEmoji } from '../directSelectors'; import { getAuth } from '../account/accountSelectors'; import { getFullUrl } from '../utils/url'; export const getAllRealmEmojiById = createSelector(getAuth, getRawRealmEmoji, (auth, emojis) => Object.keys(emojis).reduce((result, key) => { result[key] = { ...emojis[key], source_url: getFullUrl(emojis[key].source_url, auth.realm) }; return result; }, {}), ); export const getActiveRealmEmojiById = createSelector(getAllRealmEmojiById, emojis => Object.keys(emojis) .filter(emoji => !emojis[emoji].deactivated) .reduce((result, key) => { result[key] = emojis[key]; return result; }, {}), );
Set poll_on_creation to False for run_job
from civis import APIClient from civis.futures import CivisFuture def run_job(job_id, api_key=None): """Run a job. Parameters ---------- job_id : str or int The ID of the job. api_key : str, optional Your Civis API key. If not given, the :envvar:`CIVIS_API_KEY` environment variable will be used. Returns ------- results : :class:`~civis.futures.CivisFuture` A `CivisFuture` object. """ client = APIClient(api_key=api_key, resources='all') run = client.jobs.post_runs(job_id) return CivisFuture(client.jobs.get_runs, (job_id, run['id']), api_key=api_key, poll_on_creation=False)
from civis import APIClient from civis.futures import CivisFuture def run_job(job_id, api_key=None): """Run a job. Parameters ---------- job_id : str or int The ID of the job. api_key : str, optional Your Civis API key. If not given, the :envvar:`CIVIS_API_KEY` environment variable will be used. Returns ------- results : :class:`~civis.futures.CivisFuture` A `CivisFuture` object. """ client = APIClient(api_key=api_key, resources='all') run = client.jobs.post_runs(job_id) return CivisFuture(client.jobs.get_runs, (job_id, run['id']), api_key=api_key)
Fix bug in for-each loop and correct comments
// Get messages from the newest to oldest channel.getMessages(20 /* by pages of 20 messages */ ) .then(messagesPage => { messagesPage.items.forEach(message => { // do stuff for each message }); // note, that by default pages are in "backwards" order, // so you should ask for previous page, not the next one if (messagesPage.hasPrevPage) { return messagesPage.prevPage(); // here we can ask for following page } }); // Get messages from the message with id 3 to newest channel.getMessages(20, 3, 'forward') .then(messagesPage => { /* handle page the same way as above */ }); // Handle multiple pages // Unfortunately, js has no asynchronous iterators yet, so there should be // some boilerplate here. One of the way to go through all messages would be // like this: function processPage(page) { page.items.forEach(message => { /* do something for message */ }); if (page.hasNextPage) { page.nextPage().then(processPage); } else { // all messages read! } } channel.getMessage(10, null, 'forward').then(processPage);
// Get messages from the newest to oldest channel.getMessages(20 /* by pages of 20 messages */ ) .then(messagesPage => { messagesPage.items.forEach(message => { // do stuff for each message } // note, that by default pages are in "backwards" order, // so you should ask for previous page, not the next one if (messagesPage.hasPrevPage) { return messagesPage.prevPage(); // here we can ask for following page } }); // Get messages from the message with id 3 to newest channel.getMessages(20, 3, 'forward') .then(messagesPage => { handle page the same way as above }); // Handle multiple pages // Unfortunately, js has no asynchronous iterators yet, so there should be // some boilerplate here. One of the way to go through all messages would be // like this: function processPage(page) { page.items.forEach(message => { do something for message }); if (page.hasNextPage) { page.nextPage().then(processPage); } else { // all messages read! } } channel.getMessage(10, null, 'forward').then(processPage);
[DASH-2397] Fix display only valid domains in hosting URLs
import React from 'react'; import { withRouter } from 'react-router'; import _ from 'lodash'; import { LinkWithIcon } from '../../common'; const HostingListItemLinks = ({ items, isDefault, params }) => { const styles = { item: { padding: '4px 0' } }; let isCnameFounded = false; const getLinkUrl = (domain) => { const isValidCname = /\.[a-zA-Z]+$/.test(domain); if (domain === 'default' && isDefault) { return `https://${params.instanceName}.syncano.site`; } if (!isCnameFounded && isValidCname) { isCnameFounded = true; return domain; } return `https://${domain}--${params.instanceName}.syncano.site`; }; return ( <div> {_.map(items, (item, index) => ( <div style={styles.item} key={`domain-${item}-${index}`} > <LinkWithIcon url={getLinkUrl(item)} /> </div> ))} </div> ); }; export default withRouter(HostingListItemLinks);
import React from 'react'; import { withRouter } from 'react-router'; import _ from 'lodash'; import { LinkWithIcon } from '../../common'; const HostingListItemLinks = ({ items, isDefault, params }) => { const styles = { item: { padding: '4px 0' } }; let isCnameFounded = false; const getLinkUrl = (domain) => { if (domain === 'default' && isDefault) { return `https://${params.instanceName}.syncano.site`; } if (!isCnameFounded) { isCnameFounded = true; return domain; } return `https://${domain}--${params.instanceName}.syncano.site`; }; return ( <div> {_.map(items, (item, index) => ( <div style={styles.item} key={`domain-${item}-${index}`} > <LinkWithIcon url={getLinkUrl(item)} /> </div> ))} </div> ); }; export default withRouter(HostingListItemLinks);
Set noqa to silence flake8.
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved import sys from django.core.management.base import BaseCommand from awx.main.task_engine import TaskSerializer class Command(BaseCommand): """Return a exit status of 0 if MongoDB should be active, and an exit status of 1 otherwise. This script is intended to be used by bash and init scripts to conditionally start MongoDB, so its focus is on being bash-friendly. """ def handle(self, **kwargs): # Get the license data. license_reader = TaskSerializer() license_data = license_reader.from_file() # Does the license contain the system tracking feature? # If and only if it does, MongoDB should run. system_tracking = license_data['features']['system_tracking'] # Okay, do we need MongoDB to be turned on? # This is a silly variable assignment right now, but I expect the # rules here will grow more complicated over time. # FIXME: Most likely this should be False if HA is active # (not just enabled by license, but actually in use). uses_mongo = system_tracking # noqa # If we do not need Mongo, return a non-zero exit status. print('MongoDB NOT required') sys.exit(1) # We do need Mongo, return zero. print('MongoDB required') sys.exit(0)
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved import sys from django.core.management.base import BaseCommand from awx.main.task_engine import TaskSerializer class Command(BaseCommand): """Return a exit status of 0 if MongoDB should be active, and an exit status of 1 otherwise. This script is intended to be used by bash and init scripts to conditionally start MongoDB, so its focus is on being bash-friendly. """ def handle(self, **kwargs): # Get the license data. license_reader = TaskSerializer() license_data = license_reader.from_file() # Does the license contain the system tracking feature? # If and only if it does, MongoDB should run. system_tracking = license_data['features']['system_tracking'] # Okay, do we need MongoDB to be turned on? # This is a silly variable assignment right now, but I expect the # rules here will grow more complicated over time. # FIXME: Most likely this should be False if HA is active # (not just enabled by license, but actually in use). uses_mongo = system_tracking # If we do not need Mongo, return a non-zero exit status. print('MongoDB NOT required') sys.exit(1) # We do need Mongo, return zero. print('MongoDB required') sys.exit(0)
Send RideRegistration id through with api response
import requests from django.conf import settings from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from server.api.serializers.chapters import ChapterSerializer from .riders import RiderSerializer from server.core.models.rides import Ride, RideRiders class RideSerializer(serializers.ModelSerializer): chapter = ChapterSerializer() riders = RiderSerializer(source='registered_riders', many=True, read_only=True) class Meta: model = Ride fields = ('id', 'name', 'slug', 'description_html', 'start_location', 'end_location', 'start_date', 'end_date', 'chapter', 'rider_capacity', 'riders', 'spaces_left', 'price', 'full_cost', 'currency', 'is_over', 'fundraising_total', 'fundraising_target') class RideRiderSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = RideRiders fields = ('id', 'ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') validators = [ UniqueTogetherValidator( queryset=RideRiders.objects.all(), fields=('user', 'ride'), message='You have already registered for this ride.' ) ]
import requests from django.conf import settings from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from server.api.serializers.chapters import ChapterSerializer from .riders import RiderSerializer from server.core.models.rides import Ride, RideRiders class RideSerializer(serializers.ModelSerializer): chapter = ChapterSerializer() riders = RiderSerializer(source='registered_riders', many=True, read_only=True) class Meta: model = Ride fields = ('id', 'name', 'slug', 'description_html', 'start_location', 'end_location', 'start_date', 'end_date', 'chapter', 'rider_capacity', 'riders', 'spaces_left', 'price', 'full_cost', 'currency', 'is_over', 'fundraising_total', 'fundraising_target') class RideRiderSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = RideRiders fields = ('ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') validators = [ UniqueTogetherValidator( queryset=RideRiders.objects.all(), fields=('user', 'ride'), message='You have already registered for this ride.' ) ]
Fix crash on invalid URL
package mil.nga.giat.mage.sdk.http.resource; import android.content.Context; import com.squareup.okhttp.ResponseBody; import mil.nga.giat.mage.sdk.http.HttpClientManager; import retrofit.Call; import retrofit.Callback; import retrofit.Retrofit; import retrofit.http.GET; /*** * RESTful communication for the API * * @author newmanw */ public class ApiResource { public interface ApiService { @GET("/api") Call<ResponseBody> getApi(); } private static final String LOG_NAME = ApiResource.class.getName(); private Context context; public ApiResource(Context context) { this.context = context; } public void getApi(String url, Callback<ResponseBody> callback) { try { Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .client(HttpClientManager.getInstance(context).httpClient()) .build(); ApiService service = retrofit.create(ApiService.class); service.getApi().enqueue(callback); } catch (IllegalArgumentException e) { callback.onFailure(e); } } }
package mil.nga.giat.mage.sdk.http.resource; import android.content.Context; import com.squareup.okhttp.ResponseBody; import mil.nga.giat.mage.sdk.http.HttpClientManager; import retrofit.Call; import retrofit.Callback; import retrofit.Retrofit; import retrofit.http.GET; /*** * RESTful communication for the API * * @author newmanw */ public class ApiResource { public interface ApiService { @GET("/api") Call<ResponseBody> getApi(); } private static final String LOG_NAME = ApiResource.class.getName(); private Context context; public ApiResource(Context context) { this.context = context; } public void getApi(String url, Callback<ResponseBody> callback) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .client(HttpClientManager.getInstance(context).httpClient()) .build(); ApiService service = retrofit.create(ApiService.class); service.getApi().enqueue(callback); } }
Update alert to allow for setting an id.
'use strict'; if (!waitlist) { var waitlist = {}; } waitlist.base = (function(){ function getMetaData (name) { return $('meta[name="'+name+'"]').attr('content'); } function displayMessage(message, type, html=false, id=false) { var alertHTML = $($.parseHTML(`<div class="alert alert-dismissible alert-${type}" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="text-xs-center"></p> </div>`)); var textContainer = $('.text-xs-center', alertHTML); if (id !== false) { alertHTML.attr("id", id); } if (html === true) { textContainer.html(message); } else { textContainer.text(message); } var alertArea = $('#alert-area-base'); alertArea.append(alertHTML); } return { getMetaData: getMetaData, displayMessage: displayMessage }; })();
'use strict'; if (!waitlist) { var waitlist = {}; } waitlist.base = (function(){ function getMetaData (name) { return $('meta[name="'+name+'"]').attr('content'); } function displayMessage(message, type, html=false) { var alertHTML = $($.parseHTML(`<div class="alert alert-dismissible alert-${type}" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="text-xs-center"></p> </div>`)); var textContainer = $('.text-xs-center', alertHTML); if (html === true) { textContainer.html(message); } else { textContainer.text(message); } var alertArea = $('#alert-area-base'); alertArea.append(alertHTML); } return { getMetaData: getMetaData, displayMessage: displayMessage }; })();
Use an object for the queue of unsent events
module.exports = class ReporterProxy { constructor () { this.reporter = null this.timingsQueue = [] this.eventType = 'find-and-replace-v1' } setReporter (reporter) { this.reporter = reporter let timingsEvent while ((timingsEvent = this.timingsQueue.shift())) { this.reporter.addTiming(this.eventType, timingsEvent.duration, timingsEvent.metadata) } } unsetReporter () { delete this.reporter } sendSearchEvent (duration, numResults) { const metadata = { ec: 'time-to-search', ev: numResults } this._addTiming(duration, metadata) } _addTiming (duration, metadata) { if (this.reporter) { this.reporter.addTiming(this.eventType, duration, metadata) } else { this.timingsQueue.push({duration, metadata}) } } }
module.exports = class ReporterProxy { constructor () { this.reporter = null this.timingsQueue = [] this.eventType = 'find-and-replace-v1' } setReporter (reporter) { this.reporter = reporter let timingsEvent while ((timingsEvent = this.timingsQueue.shift())) { this.reporter.addTiming(this.eventType, timingsEvent[0], timingsEvent[1]) } } unsetReporter () { delete this.reporter } sendSearchEvent (duration, numResults) { const metadata = { ec: 'time-to-search', ev: numResults } this._addTiming(duration, metadata) } _addTiming (duration, metadata) { if (this.reporter) { this.reporter.addTiming(this.eventType, duration, metadata) } else { this.timingsQueue.push([duration, metadata]) } } }
Fix script name Bump to 0.1.2
from distutils.core import setup with open('README.rst') as readme: long_description = readme.read() VERSION = '0.1.2' setup( install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'], name='gmusicsync', version=VERSION, py_modules=['gmusicsync'], url='https://github.com/sashgorokhov/gmusicsync', download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION, keywords=['gmusic', 'google music', 'music'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Multimedia :: Sound/Audio', ], long_description=long_description, license='MIT License', author='sashgorokhov', author_email='sashgorokhov@gmail.com', description='Google Music playlist syncing to offline destination', scripts=[ 'gmusicsync.py' ] )
from distutils.core import setup with open('README.rst') as readme: long_description = readme.read() VERSION = '0.1.1' setup( install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'], name='gmusicsync', version=VERSION, py_modules=['gmusicsync'], url='https://github.com/sashgorokhov/gmusicsync', download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION, keywords=['gmusic', 'google music', 'music'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Multimedia :: Sound/Audio', ], long_description=long_description, license='MIT License', author='sashgorokhov', author_email='sashgorokhov@gmail.com', description='Google Music playlist syncing to offline destination', scripts=[ 'gmusicsync' ] )
Add indents in saved config
const fs = require("fs"); function evalTemplate(template, scope) { with(scope) { try { return eval(`\`${template.replace(/`/g, '\\`')}\``); } catch (error) { console.log("Error encountered while evaluating a template:"); console.log(`Message: ${error.message}`); console.log(`Stack trace: \n${error.stack}`); } } } function hexToRGB(hex) { let bigint = parseInt(hex, 16); return new RGB((bigint >> 16) & 255, (bigint >> 8) & 255, bigint & 255); } function loadJSON(path) { return JSON.parse(fs.readFileSync(path)); } function saveJSON(path, object) { return fs.writeFileSync(path, JSON.stringify(object, null, 4)); } module.exports = { evalTemplate, hexToRGB, loadJSON, saveJSON }
const fs = require("fs"); function evalTemplate(template, scope) { with(scope) { try { return eval(`\`${template.replace(/`/g, '\\`')}\``); } catch (error) { console.log("Error encountered while evaluating a template:"); console.log(`Message: ${error.message}`); console.log(`Stack trace: \n${error.stack}`); } } } function hexToRGB(hex) { let bigint = parseInt(hex, 16); return new RGB((bigint >> 16) & 255, (bigint >> 8) & 255, bigint & 255); } function loadJSON(path) { return JSON.parse(fs.readFileSync(path)); } function saveJSON(path, object) { return fs.writeFileSync(path, JSON.stringify(object)); } module.exports = { evalTemplate, hexToRGB, loadJSON, saveJSON }
Load config via requires, web route added.
/** * sivart-ci v0.1.0 * * A simple interactive CI Dashboard built on MEAN stack. * * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com) * Date: 27 November, 2015 * * Sivart App Main Script. */ /* * Load Configurations and Utilities. */ var fs = require('fs'), stringTemplate = require('string-template'), configuration = require('./configuration.json'); /* * Load Modules. */ var express = require('express'), mongoose = require('mongoose'), morgan = require('morgan'); /* * Init App Modules */ var changelistModel = require('./model/changelist'), indexRoutes = require('./routes/index'), changelistRoutes = require('./routes/changelist'), sivartApp; /* * Intialize App Server. */ sivartApp = express(); mongoose.connect(stringTemplate('{protocol}://{dbUserName}:{dbPassword}@{dbURL}', configuration.modulus)); sivartApp.use(express.static(__dirname + configuration.sivart.publicDir)); sivartApp.use(morgan(configuration.morgan.logType)); sivartApp.use('/', indexRoutes); sivartApp.use('/api', changelistRoutes); module.exports = sivartApp;
/** * sivart-ci v0.1.0 * * A simple interactive CI Dashboard built on MEAN stack. * * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com) * Date: 27 November, 2015 * * Sivart App Main Script. */ /* * Load Configurations and Utilities. */ var fs = require('fs'), stringTemplate = require('string-template'), configuration = JSON.parse(fs.readFileSync('configuration.json')); /* * Load Modules. */ var express = require('express'), mongoose = require('mongoose'), morgan = require('morgan'); /* * Init App Modules */ var changelistModel = require('./model/changelist'), changelistRoutes = require('./routes/changelist'), sivartApp; /* * Intialize App Server. */ sivartApp = express(); mongoose.connect(stringTemplate('{protocol}://{dbUserName}:{dbPassword}@{dbURL}', configuration.modulus)); sivartApp.use(express.static(__dirname + configuration.sivart.publicDir)); sivartApp.use(morgan(configuration.morgan.logType)); sivartApp.use('/api', changelistRoutes); module.exports = sivartApp;
Bump package version forward to next development version Change-Id: Ia04ceb0e83d4927e75a863252571ed76f83b2ef1
#!/usr/bin/env python import os from setuptools import setup # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = 'voltha', version = '2.0.0-dev', author = 'Open Networking Foundation, et al', author_email = 'info@opennetworking.org', description = ('Virtual Optical Line Terminal (OLT) Hardware Abstraction'), license = 'Apache License 2.0', keywords = 'volt gpon cord', url = 'https://gerrit.opencord.org/#/q/project:voltha', packages=['voltha', 'tests'], long_description=read('README.md'), classifiers=[ 'Development Status :: 3 - Alpha', 'Topic :: System :: Networking', 'Programming Language :: Python', 'License :: OSI Approved :: Apache License 2.0', ], )
#!/usr/bin/env python import os from setuptools import setup # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = 'voltha', version = '1.3.0', author = 'Open Networking Foundation, et al', author_email = 'info@opennetworking.org', description = ('Virtual Optical Line Terminal (OLT) Hardware Abstraction'), license = 'Apache License 2.0', keywords = 'volt gpon cord', url = 'https://gerrit.opencord.org/#/q/project:voltha', packages=['voltha', 'tests'], long_description=read('README.md'), classifiers=[ 'Development Status :: 3 - Alpha', 'Topic :: System :: Networking', 'Programming Language :: Python', 'License :: OSI Approved :: Apache License 2.0', ], )
Change the structure of the string
<?php /** * Copyright 2015-2018 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'top-headers' => [ 'headline' => 'Live Streams', 'description' => 'Data is fetched from twitch.tv every five minutes based on the directory listing. Feel free to start streaming and get yourself listed! For more information on how to get setup, please check out :here.', 'here' => 'the wiki page on live streaming', ], 'headers' => [ 'regular' => 'Currently Streaming', ], ];
<?php /** * Copyright 2015-2018 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'top-headers' => [ 'headline' => 'Live Streams', 'description' => 'Data is fetched from twitch.tv every five minutes based on the directory listing. Feel free to start streaming and get yourself listed! For more information on how to get setup, please check out the wiki page on live streaming.', ], 'headers' => [ 'regular' => 'Currently Streaming', ], ];
Set default lease to a higher value.
/******************************************************************************* * * 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. * * Copyright 2014 Fraunhofer FOKUS *******************************************************************************/ module.exports = { CERTIFICATE_LOCATION : "~/.ocdb/", REQUIRED_MIMETYPE : "application/json", FILE_ENDPOINTS : "./endpoints", LOCATION_RESOURCES : "./resources/", SERVER_PORT : 443, BASEURL_PATH : "/", API_VERSION : "v1", SESSION_LEASE : 43200000, ERROR_OK : "ok", ERROR_WRONG_MIMETYPE : "wrong_mimetype", ERROR_METHOD_NOT_ALLOWED : "method_not_allowed", ERROR_NOT_FOUND : "resource_not_found", ERROR_CONFLICT : "resource_conflict", ERROR_REQUEST_INVALID : "request_invalid", ERROR_REQUEST_UNAUTHORIZED : "request_unauthorized", ERROR_INTERNAL : "internal_server_error" }
/******************************************************************************* * * 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. * * Copyright 2014 Fraunhofer FOKUS *******************************************************************************/ module.exports = { CERTIFICATE_LOCATION : "~/.ocdb/", REQUIRED_MIMETYPE : "application/json", FILE_ENDPOINTS : "./endpoints", LOCATION_RESOURCES : "./resources/", SERVER_PORT : 443, BASEURL_PATH : "/", API_VERSION : "v1", SESSION_LEASE : 900000, ERROR_OK : "ok", ERROR_WRONG_MIMETYPE : "wrong_mimetype", ERROR_METHOD_NOT_ALLOWED : "method_not_allowed", ERROR_NOT_FOUND : "resource_not_found", ERROR_CONFLICT : "resource_conflict", ERROR_REQUEST_INVALID : "request_invalid", ERROR_REQUEST_UNAUTHORIZED : "request_unauthorized", ERROR_INTERNAL : "internal_server_error" }