text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add one more lstm layer
from keras.models import Sequential from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Embedding from keras.layers.recurrent import LSTM def get_model(X_vocab_len, X_max_len, y_vocab_len, y_max_len, hidden_size, num_layers): model = Sequential() # encoder model.add(Embedding(X_vocab_len, 64, input_length=X_max_len, mask_zero=True)) model.add(LSTM(hidden_size)) model.add(LSTM(hidden_size)) model.add(RepeatVector(y_max_len)) # decoder for _ in range(num_layers): model.add(LSTM(hidden_size, return_sequences=True)) model.add(TimeDistributed(Dense(y_vocab_len))) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
from keras.models import Sequential from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Embedding from keras.layers.recurrent import LSTM def get_model(X_vocab_len, X_max_len, y_vocab_len, y_max_len, hidden_size, num_layers): model = Sequential() # encoder model.add(Embedding(X_vocab_len, 64, input_length=X_max_len, mask_zero=True)) model.add(LSTM(hidden_size)) model.add(RepeatVector(y_max_len)) # decoder for _ in range(num_layers): model.add(LSTM(hidden_size, return_sequences=True)) model.add(TimeDistributed(Dense(y_vocab_len))) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
Add @Incubating and @since annotations To MultipleBuildActionsException. Signed-off-by: Lucas Smaira <ebde68659be3ad482cc698f6db784bb2a410fa24@google.com>
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.tooling.exceptions; import org.gradle.api.Incubating; /** * Thrown when the {@link org.gradle.tooling.PhasedBuildActionExecuter.Builder} has been configured * with more than one {@link org.gradle.tooling.BuildAction} per phase. * * @since 4.7 */ @Incubating public class MultipleBuildActionsException extends RuntimeException { public MultipleBuildActionsException(String message) { super(message); } }
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.tooling.exceptions; /** * Thrown when the {@link org.gradle.tooling.PhasedBuildActionExecuter.Builder} has been configured * with more than one {@link org.gradle.tooling.BuildAction} per phase. */ public class MultipleBuildActionsException extends RuntimeException { public MultipleBuildActionsException(String message) { super(message); } }
Increase client timeout to be larger than server timeout (for projections) so that we can see server response
// Copyright © 2016-2017 Esko Luontola // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 import axios from "axios"; const OBSERVED_POSITION_HEADER = 'x-observed-position'; let observedPosition = null; function rememberObservedPosition(response) { const value = response.headers[OBSERVED_POSITION_HEADER]; if (value) { observedPosition = value; } } async function handleResponse(responsePromise) { const response = await responsePromise; rememberObservedPosition(response); return response; } export function buildConfig() { const headers = {}; if (observedPosition) { headers[OBSERVED_POSITION_HEADER] = observedPosition; } return { headers }; } const http = axios.create({ timeout: 60000, headers: { 'Accept': 'application/json', }, }); export default { get: (url) => handleResponse(http.get(url, buildConfig())), post: (url, data) => handleResponse(http.post(url, data, buildConfig())) }
// Copyright © 2016-2017 Esko Luontola // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 import axios from "axios"; const OBSERVED_POSITION_HEADER = 'x-observed-position'; let observedPosition = null; function rememberObservedPosition(response) { const value = response.headers[OBSERVED_POSITION_HEADER]; if (value) { observedPosition = value; } } async function handleResponse(responsePromise) { const response = await responsePromise; rememberObservedPosition(response); return response; } export function buildConfig() { const headers = {}; if (observedPosition) { headers[OBSERVED_POSITION_HEADER] = observedPosition; } return { headers }; } const http = axios.create({ timeout: 15000, headers: { 'Accept': 'application/json', }, }); export default { get: (url) => handleResponse(http.get(url, buildConfig())), post: (url, data) => handleResponse(http.post(url, data, buildConfig())) }
Use a span as the element
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import cx from 'classnames'; import theme from './theme.css'; class Bullet extends PureComponent { static propTypes = { className: PropTypes.string, color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']), size: PropTypes.oneOf(['small', 'medium']), }; static defaultProps = { color: 'neutral', size: 'medium', }; render() { const { className, color, size, ...others } = this.props; const classNames = cx(theme['bullet'], theme[color], theme[size], className); return <Box data-teamleader-ui="bullet" className={classNames} element="span" {...others} />; } } export default Bullet;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import cx from 'classnames'; import theme from './theme.css'; class Bullet extends PureComponent { static propTypes = { className: PropTypes.string, color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']), size: PropTypes.oneOf(['small', 'medium']), }; static defaultProps = { color: 'neutral', size: 'medium', }; render() { const { className, color, size, ...others } = this.props; const classNames = cx(theme['bullet'], theme[color], theme[size], className); return <Box data-teamleader-ui="bullet" className={classNames} {...others} />; } } export default Bullet;
Fix typo in Union initialization exception
import six from ..utils.is_base_type import is_base_type from .options import Options class UnionMeta(type): def __new__(cls, name, bases, attrs): # Also ensure initialization is only performed for subclasses of # Union if not is_base_type(bases, UnionMeta): return type.__new__(cls, name, bases, attrs) options = Options( attrs.pop('Meta', None), name=name, description=attrs.get('__doc__'), types=(), ) assert ( isinstance(options.types, (list, tuple)) and len(options.types) > 0 ), 'Must provide types for Union {}.'.format(options.name) return type.__new__(cls, name, bases, dict(attrs, _meta=options)) def __str__(cls): # noqa: N805 return cls._meta.name class Union(six.with_metaclass(UnionMeta)): ''' Union Type Definition When a field can return one of a heterogeneous set of types, a Union type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved. ''' resolve_type = None def __init__(self, *args, **kwargs): raise Exception("A Union cannot be intitialized")
import six from ..utils.is_base_type import is_base_type from .options import Options class UnionMeta(type): def __new__(cls, name, bases, attrs): # Also ensure initialization is only performed for subclasses of # Union if not is_base_type(bases, UnionMeta): return type.__new__(cls, name, bases, attrs) options = Options( attrs.pop('Meta', None), name=name, description=attrs.get('__doc__'), types=(), ) assert ( isinstance(options.types, (list, tuple)) and len(options.types) > 0 ), 'Must provide types for Union {}.'.format(options.name) return type.__new__(cls, name, bases, dict(attrs, _meta=options)) def __str__(cls): # noqa: N805 return cls._meta.name class Union(six.with_metaclass(UnionMeta)): ''' Union Type Definition When a field can return one of a heterogeneous set of types, a Union type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved. ''' resolve_type = None def __init__(self, *args, **kwargs): raise Exception("An Union cannot be intitialized")
Prepare for 0.1.1 small improvement release
from distutils.core import setup import os.path here = os.path.abspath(os.path.dirname(__file__)) try: with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() except: long_description = "" setup(name='diary', packages=['diary'], scripts=['diary/bin/diary'], version='0.1.1', description='Async Logging', long_description=long_description, author='Sam Rosen', author_email='samrosen90@gmail.com', url='https://github.com/GreenVars/diary', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='logging async asynchronous parallel threading', )
from distutils.core import setup import os.path here = os.path.abspath(os.path.dirname(__file__)) try: with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() except: long_description = "" setup(name='diary', packages=['diary'], scripts=['diary/bin/diary'], version='0.1.0', description='Async Logging', long_description=long_description, author='Sam Rosen', author_email='samrosen90@gmail.com', url='https://github.com/GreenVars/diary', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='logging async asynchronous parallel threading', )
Fix License Header (Thanks Christophe). git-svn-id: 02b679d096242155780e1604e997947d154ee04a@572356 13f79535-47bb-0310-9956-ffa450edef68
/* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.ocm.exception; /** * The <code>InvalidQuerySyntaxException</code> is an * <code>ObjectContentManagerException</code> thrown if the query of the * {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObjectIterator(String, String)} * is invalid. This exception actually wraps a standard JCR * <code>javax.jcr.InvalidQueryException</code> to make it an unchecked * exception. The cause of this exception will always be the original * <code>InvalidQueryException</code> and the message will always be the * original exception's message. */ public class InvalidQueryException extends ObjectContentManagerException { /** * Create an exception wrapping the given checked JCR exception * * @param cause The wrapped JCR <code>InvalidQueryException</code> */ public InvalidQueryException(javax.jcr.query.InvalidQueryException cause) { super(cause.getMessage(), cause); } }
/* * $Url: $ * $Id: $ * * Copyright 1997-2005 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package org.apache.jackrabbit.ocm.exception; /** * The <code>InvalidQuerySyntaxException</code> is an * <code>ObjectContentManagerException</code> thrown if the query of the * {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObjectIterator(String, String)} * is invalid. This exception actually wraps a standard JCR * <code>javax.jcr.InvalidQueryException</code> to make it an unchecked * exception. The cause of this exception will always be the original * <code>InvalidQueryException</code> and the message will always be the * original exception's message. */ public class InvalidQueryException extends ObjectContentManagerException { /** * Create an exception wrapping the given checked JCR exception * * @param cause The wrapped JCR <code>InvalidQueryException</code> */ public InvalidQueryException(javax.jcr.query.InvalidQueryException cause) { super(cause.getMessage(), cause); } }
Replace storybook-state usage from buttonGroup story with useState
import React, { useState } from 'react'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; import { IconAddMediumOutline } from '@teamleader/ui-icons'; import Button from '../button'; import ButtonGroup from './ButtonGroup'; export default { component: ButtonGroup, title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Button group'), }; export const Normal = (args) => ( <ButtonGroup {...args}> <Button label="Button 1" /> <Button label="Button 2" /> <Button icon={<IconAddMediumOutline />} /> </ButtonGroup> ); export const withActive = () => { const [value, setValue] = useState('option2'); const handleChange = (value) => { setValue(value); }; return ( <ButtonGroup segmented value={value} onChange={handleChange} level="secondary"> <Button label="Option 1" value="option1" /> <Button label="Option 2" value="option2" /> <Button label="Option 3" value="option3" /> </ButtonGroup> ); }; withActive.story = { name: 'With active', };
import React from 'react'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; import { Store, State } from '@sambego/storybook-state'; import { IconAddMediumOutline } from '@teamleader/ui-icons'; import Button from '../button'; import ButtonGroup from './ButtonGroup'; const store = new Store({ value: 'option2', }); const handleChangeValue = (value, event) => { store.set({ value }); }; export default { component: ButtonGroup, title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Button group'), }; export const Normal = (args) => ( <ButtonGroup {...args}> <Button label="Button 1" /> <Button label="Button 2" /> <Button icon={<IconAddMediumOutline />} /> </ButtonGroup> ); export const withActive = () => ( <State store={store}> <ButtonGroup segmented value="option2" onChange={handleChangeValue} level="secondary"> <Button label="Option 1" value="option1" /> <Button label="Option 2" value="option2" /> <Button label="Option 3" value="option3" /> </ButtonGroup> </State> ); withActive.story = { name: 'With active', };
Use the best model from the leader board in the prediction web app.
from flask import Flask, redirect, render_template, request from gevent.wsgi import WSGIServer from predict import InstrumentClassifier from leaderboard import LeaderBoard app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 1 * 2**20 model_dir = 'data/working/single-notes-2000/models' model_id = LeaderBoard(model_dir).best_model() model = InstrumentClassifier(model_dir + '/' + model_id) print('Using model:', model_id) @app.route('/') def hello(): return render_template('home.html') @app.route('/api/classify/instrument', methods=['POST']) def classify(): if 'audio_file' not in request.files: return redirect('/') # File-like object than can be directy passed to soundfile.read() # without saving to disk. audio_file = request.files['audio_file'] if audio_file.filename == '': return redirect('/') class_probabilities = model.predict_probabilities(audio_file) class_probabilities = class_probabilities.round(5) label = model.class_label_from_probabilities( class_probabilities) return render_template('home.html', audio_file=audio_file.filename, predicted_label=label, class_probabilities=class_probabilities) if __name__ == '__main__': # app.run(debug=True) app.debug = True # needed since Flask dev mode interacts badly with TensorFlow http_server = WSGIServer(('', 5000), app) http_server.serve_forever()
from flask import Flask, redirect, render_template, request from gevent.wsgi import WSGIServer from predict import InstrumentClassifier app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 1 * 2**20 model = InstrumentClassifier(model_dir='data/working/single-notes-2000/model') @app.route('/') def hello(): return render_template('home.html') @app.route('/api/classify/instrument', methods=['POST']) def classify(): if 'audio_file' not in request.files: return redirect('/') # File-like object than can be directy passed to soundfile.read() # without saving to disk. audio_file = request.files['audio_file'] if audio_file.filename == '': return redirect('/') class_probabilities = model.predict_probabilities(audio_file) class_probabilities = class_probabilities.round(5) label = model.class_label_from_probabilities( class_probabilities) return render_template('home.html', audio_file=audio_file.filename, predicted_label=label, class_probabilities=class_probabilities) if __name__ == '__main__': # app.run(debug=True) app.debug = True # needed since Flask dev mode interacts badly with TensorFlow http_server = WSGIServer(('', 5000), app) http_server.serve_forever()
Add berkeley_build to package data.
import os from setuptools import find_packages from setuptools import setup f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() setup( name='peewee', version=__import__('peewee').__version__, description='a little orm', long_description=readme, author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/peewee/', package_data = { 'playhouse': ['berkeley_build.sh']}, packages=['playhouse'], py_modules=['peewee', 'pwiz'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], test_suite='tests', scripts = ['pwiz.py'], )
import os from setuptools import find_packages from setuptools import setup f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() setup( name='peewee', version=__import__('peewee').__version__, description='a little orm', long_description=readme, author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/peewee/', packages=['playhouse'], py_modules=['peewee', 'pwiz'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], test_suite='tests', scripts = ['pwiz.py'], )
Allow clock to be set to current time.
// Prevayler(TM) - The Open-Source Prevalence Layer. // Copyright (C) 2001 Klaus Wuestefeld. // This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. package org.prevayler.util.clock; import java.util.Date; /** A deterministic Clock that always returns the same time until it is forced to advance. A new BrokenClock's time() starts off at new Date(Long.MIN_VALUE); */ public class BrokenClock implements Clock, java.io.Serializable { protected long _millis = Long.MIN_VALUE; private Date _time = new Date(_millis); public Date time() { return _time; } synchronized void advanceTo(Date newTime) { long newMillis = newTime.getTime(); if (newMillis < _millis) throw new RuntimeException("A Clock can only be set to the future. Current time: " + _time + " new time: " + newTime); _millis = newMillis; _time = newTime; } }
// Prevayler(TM) - The Open-Source Prevalence Layer. // Copyright (C) 2001 Klaus Wuestefeld. // This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. package org.prevayler.util.clock; import java.util.Date; /** A deterministic Clock that always returns the same time until it is forced to advance. A new BrokenClock's time() starts off at new Date(Long.MIN_VALUE); */ public class BrokenClock implements Clock, java.io.Serializable { protected long _millis = Long.MIN_VALUE; private Date _time = new Date(_millis); public Date time() { return _time; } synchronized void advanceTo(Date newTime) { long newMillis = newTime.getTime(); if (newMillis <= _millis) throw new RuntimeException("A Clock can only be set to the future. Current time: " + _time + " new time: " + newTime); _millis = newMillis; _time = newTime; } }
Exit with non-zero status code on error
package main import ( "bytes" "fmt" "io/ioutil" "net/http" "os" ) func main() { var content []byte var err error if len(os.Args) == 1 { content, err = ioutil.ReadAll(os.Stdin) } else { content, err = ioutil.ReadFile(os.Args[1]) } if err != nil { if os.IsNotExist(err) { fmt.Println("Gopl: the file does not exist.") } else { fmt.Println("Gopl: Huehoe it's embarrassing but an error occurs -> ", err) } os.Exit(1) } url := "http://play.golang.org/share" req, err := http.NewRequest("POST", url, bytes.NewBuffer(content)) if err != nil { fmt.Println(err) os.Exit(1) } req.Header.Set("Content-Type", "raw") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println(err) os.Exit(1) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println("http://play.golang.org/p/" + string(body)) }
package main import ( "bytes" "fmt" "io/ioutil" "net/http" "os" ) func main() { var content []byte var err error if len(os.Args) == 1 { content, err = ioutil.ReadAll(os.Stdin) } else { content, err = ioutil.ReadFile(os.Args[1]) } if err != nil { if os.IsNotExist(err) { fmt.Println("Gopl: the file does not exist.") } else { fmt.Println("Gopl: Huehoe it's embarrassing but an error occurs -> ", err) } return } url := "http://play.golang.org/share" req, err := http.NewRequest("POST", url, bytes.NewBuffer(content)) if err != nil { fmt.Println(err) return } req.Header.Set("Content-Type", "raw") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println("http://play.golang.org/p/" + string(body)) }
Rewrite lambda to work with 7.3
<?php namespace QuickCheck; use PHPUnit\Framework\TestCase; use QuickCheck\Generator as Gen; use QuickCheck\PHPUnit\PropertyConstraint; class PHPUnitIntegrationTest extends TestCase { /** * Test example from PHPUnit integration documentation */ public function testStringsAreLessThanTenChars() { $property = Property::forAll( [Gen::strings()], function ($s) { return 10 > strlen($s); } ); $this->assertFalse( PropertyConstraint::check(50)->evaluate( $property, 'Expected property to fail', true ) ); } }
<?php namespace QuickCheck; use PHPUnit\Framework\TestCase; use QuickCheck\Generator as Gen; use QuickCheck\PHPUnit\PropertyConstraint; class PHPUnitIntegrationTest extends TestCase { /** * Test example from PHPUnit integration documentation */ public function testStringsAreLessThanTenChars() { $property = Property::forAll( [Gen::strings()], fn ($s): bool => 10 > strlen($s) ); $this->assertFalse( PropertyConstraint::check(50)->evaluate( $property, 'Expected property to fail', true ) ); } }
Add doc str and change logger config
# This script downloads weekly dengue statistics from data.gov.bn import os import sys import logging DIRECTORY = '../../data/raw/disease_BN' OUTFILE = "Trend of Notifiable Diseases (2008 - 2012).xlsx" URL = "https://www.data.gov.bn/Lists/dataset/Attachments/460/Trend%20of%20Notifiable%20Diseases%20(2008%20-%202012).xlsx" logger = logging.getLogger(__name__) def download(): """ Download disease data from data.gov.bn """ logging.info('Downloading raw data of Notifiable Diseases between 2008 and 2012') if sys.version_info < (3, 0): try: os.makedirs(DIRECTORY) except OSError as e: pass import urllib as downloader from urllib2 import URLError, HTTPError else: os.makedirs(DIRECTORY, exist_ok=True) import urllib.request as downloader from urllib.error import URLError, HTTPError output_path = os.path.join(DIRECTORY, OUTFILE) try: downloader.urlretrieve(URL, output_path) logger.info('Downloaded successfully to %s', os.path.abspath(output_path)) except (HTTPError, URLError) as e: logger.error('Failed to download: %s', e.reason) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) download()
# This script downloads weekly dengue statistics from data.gov.bn import os import sys import logging DIRECTORY = '../../Data/raw/disease_BN' OUTFILE = "Trend of Notifiable Diseases (2008 - 2012).xlsx" URL = "https://www.data.gov.bn/Lists/dataset/Attachments/460/Trend%20of%20Notifiable%20Diseases%20(2008%20-%202012).xlsx" logger = logging.getLogger(__name__) def download(): if sys.version_info < (3, 0): try: os.makedirs(DIRECTORY) except OSError as e: pass import urllib as downloader from urllib2 import URLError, HTTPError else: os.makedirs(DIRECTORY, exist_ok=True) import urllib.request as downloader from urllib.error import URLError, HTTPError output_path = os.path.join(DIRECTORY, OUTFILE) try: downloader.urlretrieve(URL, output_path) logger.info('Downloaded successfully to %s', os.path.abspath(output_path)) except (HTTPError, URLError) as e: logger.error('Failed to download: %s', e.reason) if __name__ == "__main__": DIRECTORY = '../../../Data/raw/disease_BN' logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) download()
Fix displaying multiple images command
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser from IPython.display import Image from IPython.display import display if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): display(Image(GoogleMap(*location).image))
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser import IPython if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): IPython.core.display.Image(GoogleMap(*location).image)
Refactor factorial web sample to use compileProgramFile
var cobs = require('../..'), http = require('http'), fs = require('fs'); function compileFile(filename) { return cobs.compileProgramFile(filename); }; var program = compileFile('./factorial.cob'); http.createServer(function(req, res) { var runtime = { display: function() { if (arguments && arguments.length) for (var k = 0; k < arguments.length; k++) if (arguments[k]) res.write(arguments[k].toString()); res.write('\r\n'); } } program.run(runtime); res.end(); }).listen(8000); console.log('Server started, listening at port 8000');
var cobs = require('../..'), http = require('http'), fs = require('fs'); function compileFile(filename) { var text = fs.readFileSync(filename).toString(); var parser = new cobs.Parser(text); var program = parser.parseProgram(); program.text = program.command.compile(program); return program; }; var program = compileFile('./factorial.cob'); http.createServer(function(req, res) { var runtime = { display: function() { if (arguments && arguments.length) for (var k = 0; k < arguments.length; k++) if (arguments[k]) res.write(arguments[k].toString()); res.write('\r\n'); } } cobs.run(program.text, runtime, program); res.end(); }).listen(8000); console.log('Server started, listening at port 8000');
Improve SiteService with valid url list
angular.module('seoApp').factory('SiteService', ['$http', function($http) { var service = {}, urlUtils = require('urlUtils'), site = {}, init; init = function() { $http.get('seo-data.json').success(function(json) { var address = json.address, pages = json.pages || [], urls = []; for (var i in pages) { var page = pages[i]; if (page.status !== 'success') { continue; } urls.push(page.url); page.name = urlUtils.relative(address, page.url); page.id = urlUtils.slug(page.name); } // Assign service data site = {address: address, urls: urls, pages: pages}; }); }; service.getSite = function() { return site; }; service.getPages = function() { return site.pages || []; }; service.getPageById = function(id) { var pages = service.getPages(); for (var i in pages) { if (pages[i].id === id) { return pages[i]; } } }; init(); return service; }]);
angular.module('seoApp').factory('SiteService', ['$http', function($http) { var service = {}, urlUtils = require('urlUtils'), data = {}, init; init = function() { $http.get('seo-data.json').success(function(json) { data = json; for (var i in data.pages) { data.pages[i].name = urlUtils.relative(data.address, data.pages[i].url); data.pages[i].id = urlUtils.slug(data.pages[i].name); } }); }; service.getSite = function() { return data; }; service.getPages = function() { return data.pages || []; }; service.getPageById = function(id) { var pages = service.getPages(); for (var i in pages) { if (pages[i].id === id) { return pages[i]; } } }; init(); return service; }]);
Remove line for debugging which lists object type from elements of listbox
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) print objs[pref_mappings[option]] objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
Read package long description from readme
import os from setuptools import setup, find_packages def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name='gears-coffeescript', version='0.1.dev', url='https://github.com/gears/gears', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='CoffeeScript compiler for Gears', long_description=read('README.rst'), packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
from setuptools import setup, find_packages setup( name='gears-coffeescript', version='0.1.dev', url='https://github.com/gears/gears', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='CoffeeScript compiler for Gears', packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Test of standalone myrial mode
"""Basic test of the command-line interface to Myrial.""" import subprocess import unittest class CliTest(unittest.TestCase): def test_cli(self): out = subprocess.check_output(['python', 'scripts/myrial', 'examples/reachable.myl']) self.assertIn('DO', out) self.assertIn('WHILE', out) def test_cli_standalone(self): out = subprocess.check_output(['python', 'scripts/myrial', '-f', 'examples/standalone.myl']) self.assertIn('Dan Suciu,engineering', out) def test_cli_reserved_column_name(self): proc = subprocess.Popen( ['python', 'scripts/myrial', 'examples/bad_column_name.myl'], stdout=subprocess.PIPE) out = proc.communicate()[0] self.assertIn('The token "SafeDiv" on line 2 is reserved', out)
"""Basic test of the command-line interface to Myrial.""" import subprocess import unittest class CliTest(unittest.TestCase): def test_cli(self): out = subprocess.check_output(['python', 'scripts/myrial', 'examples/reachable.myl']) self.assertIn('DO', out) self.assertIn('WHILE', out) def test_cli_reserved_column_name(self): proc = subprocess.Popen( ['python', 'scripts/myrial', 'examples/bad_column_name.myl'], stdout=subprocess.PIPE) out = proc.communicate()[0] self.assertIn('The token "SafeDiv" on line 2 is reserved', out)
Fix invalid path in command line.
'use strict'; const program = require('commander'); const packageInfo = require('./package.json'); const confc = require('./'); var files; program .version(packageInfo.version) .usage(`[options] [filename ...]`) .description(`Clone your default configurations to current working directory.`) .arguments(`[fileNames...]`) .action((fileNames) => { if (typeof fileNames !== 'undefined') { files = fileNames; } }) .option(`-p, --path [path]`, `Path to default configuration files.`, (p) => p.replace(/"|'/g, '')) .option(`-v, --verbose`, `Display more information.`) .parse(process.argv); if (typeof program.path === 'string') { confc.config.path = program.path; } if (program.verbose) { confc.config.verbose = true; } if (Array.isArray(files) && (files.length > 0)) { confc.copy(files).catch((errors) => { confc.utils.displayErrors(errors); }); } else { confc.copyAll().catch((errors) => { confc.utils.displayErrors(errors); }); }
'use strict'; const program = require('commander'); const packageInfo = require('./package.json'); const confc = require('./'); var files; program .version(packageInfo.version) .arguments(`[fileNames...]`) .action((fileNames) => { if (typeof fileNames !== 'undefined') { files = fileNames; } }) .option(`-p, --path [path]`, `Path to default configuration files.`) .option(`-v, --verbose`, `Display more information.`) .parse(process.argv); if (typeof program.path === 'string') { confc.config.path = program.path; } if (program.verbose) { confc.config.verbose = true; } if (Array.isArray(files) && (files.length > 0)) { confc.copy(files).catch((errors) => { confc.utils.displayErrors(errors); }); } else { confc.copyAll().catch((errors) => { confc.utils.displayErrors(errors); }); }
Create the Account List > List Accounts - Create URL
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from marketing.views import HomePage from accounts.views import AccountList urlpatterns = patterns('', # Marketing pages url(r'^$', HomePage.as_view(), name="home"), # Subscriber related URLs url(r'^signup/$', 'crmapp.subscribers.views.subscriber_new', name='sub_new' ), # Admin URL (r'^admin/', include(admin.site.urls)), # Login/Logout URLs (r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'} ), (r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login/'} ), # Account related URLs url(r'^account/list/$', AccountList.as_view(), name='account_list' ), # Contact related URLS # Communication related URLs )
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from marketing.views import HomePage urlpatterns = patterns('', # Marketing pages url(r'^$', HomePage.as_view(), name="home"), # Subscriber related URLs url(r'^signup/$', 'crmapp.subscribers.views.subscriber_new', name='sub_new' ), # Admin URL (r'^admin/', include(admin.site.urls)), # Login/Logout URLs (r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'} ), (r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login/'} ), # Account related URLs # Contact related URLS # Communication related URLs )
Update test to reflect config file change
'use strict'; /* config ->read from file, holds values and supplies as needed */ require('chai').should() var config = require('../lib/config')() describe('Config', () => { describe('#getLayers', () => { it('should return layers config array', () => { //Given //When var layers = config.getLayers() //Then layers.should.be.an('array') layers[0].name.should.be.a('string') }) }) describe('#getMap', () => { it('should return map config object', () => { //Given //When var map = config.getMap() //Then map.should.be.an('object') map.tileLayers.should.be.an('object') }) }) })
'use strict'; /* config ->read from file, holds values and supplies as needed */ require('chai').should() var config = require('../lib/config')() describe('Config', () => { describe('#getLayers', () => { it('should return layers config array', () => { //Given //When var layers = config.getLayers() //Then layers.should.be.an('array') layers[0].name.should.be.a('string') }) }) describe('#getMap', () => { it('should return map config object', () => { //Given //When var map = config.getMap() //Then map.should.be.an('object') map.tileLayers.should.be.an('array') }) }) })
Fix displaying of Factlink Bubble Signed-off-by: tomdev <96835dd8bfa718bd6447ccc87af89ae1675daeca@codigy.nl>
(function () { function createIframe() { var body = document.getElementsByTagName("body")[0]; var iframe = document.createElement("iframe"); var div = document.createElement("div"); iframe.style.display = "none"; iframe.id = "factlink-iframe"; div.id = "fl"; body.appendChild(div); div.insertBefore(iframe, div.firstChild); return iframe; } var iframe = createIframe(); var iDocument = iframe.contentWindow.document; var iHead = iDocument.getElementsByTagName("head")[0]; var head = document.getElementsByTagName("head")[0]; var flScript = document.createElement("script"); flScript.src = FactlinkConfig.lib + (FactlinkConfig.srcPath || "/dist/factlink.core.min.js"); var configScript = document.createElement("script"); configScript.type = "text/javascript"; configScript.innerHTML = "window.FactlinkConfig = " + JSON.stringify(FactlinkConfig) + ";"; iHead.insertBefore(configScript, iHead.firstChild); iHead.insertBefore(flScript, iHead.firstChild); }());
(function () { function createIframe() { var body = document.getElementsByTagName("body")[0]; var iframe = document.createElement("iframe"); var div = document.createElement("div"); iframe.style.display = "none"; iframe.id = "factlink-iframe"; div.id = "fl"; div.style.display = "none"; body.insertBefore(div, body.firstChild); div.insertBefore(iframe, div.firstChild); return iframe; } var iframe = createIframe(); var iDocument = iframe.contentWindow.document; var iHead = iDocument.getElementsByTagName("head")[0]; var head = document.getElementsByTagName("head")[0]; var flScript = document.createElement("script"); flScript.src = FactlinkConfig.lib + (FactlinkConfig.srcPath || "/dist/factlink.core.min.js"); var configScript = document.createElement("script"); configScript.type = "text/javascript"; configScript.innerHTML = "window.FactlinkConfig = " + JSON.stringify(FactlinkConfig) + ";"; iHead.insertBefore(configScript, iHead.firstChild); iHead.insertBefore(flScript, iHead.firstChild); }());
Fix php error message “Notice: Use of undefined constant”.
<?php /////////////////////////////////////////////////////// // ---------------------------------------------------------- // SNIPPET // ---------------------------------------------------------- // Google analytics.js // ---------------------------------------------------------- // Enable and set analytics ID/API KEY in config.php // ---------------------------------------------------------- ///////////////////////////////////////////////////////////// // ---------------------------------------------------------- // Google Universal Analytics // ---------------------------------------------------------- if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): // Respect user's privacy (https://blog.j15h.nu/web-analytics-privacy/) if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1'): ?> <script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::substr($site->url(), 7); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script> <script src="https://www.google-analytics.com/analytics.js" async defer></script> <?php endif; ?> <?php else: ?> <!-- NO TRACKING SET! --> <?php endif; ?>
<?php /////////////////////////////////////////////////////// // ---------------------------------------------------------- // SNIPPET // ---------------------------------------------------------- // Google analytics.js // ---------------------------------------------------------- // Enable and set analytics ID/API KEY in config.php // ---------------------------------------------------------- ///////////////////////////////////////////////////////////// // ---------------------------------------------------------- // Google Universal Analytics // ---------------------------------------------------------- if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): // Respect user's privacy (https://blog.j15h.nu/web-analytics-privacy/) if (navigator.doNotTrack != "yes" && navigator.doNotTrack != "1" && navigator.msDoNotTrack != "1"): ?> <script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::substr($site->url(), 7); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script> <script src="https://www.google-analytics.com/analytics.js" async defer></script> <?php endif; ?> <?php else: ?> <!-- NO TRACKING SET! --> <?php endif; ?>
Add with_statement import for python2.5. See http://www.python.org/dev/peps/pep-0343/ which describes the with statement. Review URL: http://codereview.chromium.org/5690003
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ # Python 2.5 needs this for the with statement. from __future__ import with_statement import os import TestGyp test = TestGyp.TestGyp(formats=['make']) test.run_gyp('shared_dependency.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') with open('relocate/src/Makefile') as makefile: make_contents = makefile.read() # If we remove the code to generate lib1, Make should still be able # to build lib2 since lib1.so already exists. make_contents = make_contents.replace('include lib1.target.mk', '') with open('relocate/src/Makefile', 'w') as makefile: makefile.write(make_contents) test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') test.pass_test()
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ import os import TestGyp test = TestGyp.TestGyp(formats=['make']) test.run_gyp('shared_dependency.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') with open('relocate/src/Makefile') as makefile: make_contents = makefile.read() # If we remove the code to generate lib1, Make should still be able # to build lib2 since lib1.so already exists. make_contents = make_contents.replace('include lib1.target.mk', '') with open('relocate/src/Makefile', 'w') as makefile: makefile.write(make_contents) test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') test.pass_test()
Add exp and task ids to API
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author',) def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Experiment exclude = ('author',) def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
Remove quota testing from notestest since API change == quotas broken
# import json # import os # import sys # # sys.path.append('..') # from skytap.Quotas import Quotas # noqa # # quotas = Quotas() # # # def test_quota_count(): # assert len(quotas) > 0 # # # def test_quota_id(): # for quota in quotas: # assert len(quota.id) > 0 # # # def test_quota_usage(): # for quota in quotas: # assert quota.usage > 0 # # # def test_quota_units(): # for quota in quotas: # assert len(quota.units) > 0 # # # def test_quota_limit(): # for quota in quotas: # if quota.limit is not None: # assert quota.usage <= quota.limit # assert quota.pct == quota.usage / quota.limit # # # def test_quota_time(): # for quota in quotas: # if quota.units == 'hours': # assert quota.time.seconds > 0 # # # def test_quota_str_conversion(): # for quota in quotas: # assert len(str(quota)) > 0
import json import os import sys sys.path.append('..') from skytap.Quotas import Quotas # noqa quotas = Quotas() def test_quota_count(): assert len(quotas) > 0 def test_quota_id(): for quota in quotas: assert len(quota.id) > 0 def test_quota_usage(): for quota in quotas: assert quota.usage > 0 def test_quota_units(): for quota in quotas: assert len(quota.units) > 0 def test_quota_limit(): for quota in quotas: if quota.limit is not None: assert quota.usage <= quota.limit assert quota.pct == quota.usage / quota.limit def test_quota_time(): for quota in quotas: if quota.units == 'hours': assert quota.time.seconds > 0 def test_quota_str_conversion(): for quota in quotas: assert len(str(quota)) > 0
Call diff_fonts with correct params
"""Functional tests Test will produce the following tuple of all path permutations paths = ['path/to/font_a', 'path/to/font_b'] [ (path/to/font_a, path/to/font_b), (path/to/font_b, path/to/font_a), ] and run them through our main diff_fonts functions. This test is slow and should be run on challenging fonts. """ from diffenator.diff import diff_fonts from diffenator.font import InputFont from itertools import permutations import collections from glob import glob import os import unittest class TestFunctionality(unittest.TestCase): def setUp(self): _path = os.path.dirname(__file__) font_paths = glob(os.path.join(_path, 'data', '*.ttf')) self.font_path_combos = permutations(font_paths, r=2) def test_diff(self): for font_a_path, font_b_path in self.font_path_combos: font_a = InputFont(font_a_path) font_b = InputFont(font_b_path) diff = diff_fonts(font_a, font_b) self.assertNotEqual(diff, collections.defaultdict(dict)) if __name__ == '__main__': unittest.main()
"""Functional tests Test will produce the following tuple of all path permutations paths = ['path/to/font_a', 'path/to/font_b'] [ (path/to/font_a, path/to/font_b), (path/to/font_b, path/to/font_a), ] and run them through our main diff_fonts functions. This test is slow and should be run on challenging fonts. """ from diffenator.diff import diff_fonts from itertools import permutations import collections from glob import glob import os import unittest class TestFunctionality(unittest.TestCase): def setUp(self): _path = os.path.dirname(__file__) font_paths = glob(os.path.join(_path, 'data', '*.ttf')) self.font_path_combos = permutations(font_paths, r=2) def test_diff(self): for font_a_path, font_b_path in self.font_path_combos: diff = diff_fonts(font_a_path, font_b_path) self.assertNotEqual(diff, collections.defaultdict(dict)) if __name__ == '__main__': unittest.main()
Create log dir if not available
var winston = require("winston"); var fs = require("fs"); var logDir = "logs/"; if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir); } var logger = new winston.Logger({ transports: [ new winston.transports.File({ level: "error", filename: "./" + logDir + "error.log", handleExceptions: true, json: true, maxsize: 50000000, maxFiles: 5, colorize: false }), new winston.transports.Console({ level: "debug", handleExceptions: true, json: false, colorize: true }) ], exitOnError: false }); var fallback = function(err, req, res, next) { logger.error(err); res.status(500).json({ message: "Oh ooh... Something went terribly wrong." }); }; module.exports = logger; module.exports.fallback = fallback;
var winston = require("winston"); var logger = new winston.Logger({ transports: [ new winston.transports.File({ level: "error", filename: "./" + logDir + "error.log", handleExceptions: true, json: true, maxsize: 50000000, maxFiles: 5, colorize: false }), new winston.transports.Console({ level: "debug", handleExceptions: true, json: false, colorize: true }) ], exitOnError: false }); var fallback = function(err, req, res, next) { logger.error(err); res.status(500).json({ message: "Oh ooh... Something went terribly wrong." }); }; module.exports = logger; module.exports.fallback = fallback;
Remove redundant modifier on native method Change-Id: I74188ecf0b2e811aff3992693aa96a866e1267ea
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.reviewers.client; import com.google.gwt.core.client.JavaScriptObject; public class ChangeReviewersInput extends JavaScriptObject { public static ChangeReviewersInput create() { return (ChangeReviewersInput) createObject(); } protected ChangeReviewersInput() { } final void setAction(Action a) { setActionRaw(a.name()); } final native void setActionRaw(String a) /*-{ if(a)this.action=a; }-*/; final native void setFilter(String f) /*-{ if(f)this.filter=f; }-*/; final native void setReviewer(String r) /*-{ if(r)this.reviewer=r; }-*/; }
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.reviewers.client; import com.google.gwt.core.client.JavaScriptObject; public class ChangeReviewersInput extends JavaScriptObject { public static ChangeReviewersInput create() { return (ChangeReviewersInput) createObject(); } protected ChangeReviewersInput() { } final void setAction(Action a) { setActionRaw(a.name()); } private final native void setActionRaw(String a) /*-{ if(a)this.action=a; }-*/; final native void setFilter(String f) /*-{ if(f)this.filter=f; }-*/; final native void setReviewer(String r) /*-{ if(r)this.reviewer=r; }-*/; }
Add command to send messages via GCM
import json import requests from Suchary.local_settings import GCM_API_KEY from api.models import Device URL = 'https://android.googleapis.com/gcm/send' HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'} def get_reg_ids(): reg_ids = [device.registration_id for device in Device.objects.filter(active=True)] return reg_ids def send(data, collapse_key=None): reg_ids = get_reg_ids() payload = {'registration_ids': reg_ids, 'data': data} if collapse_key is not None: payload.update({'collapse_key': collapse_key}) r = requests.post(URL, data=json.dumps(payload), headers=HEADER) def edit_joke(key): data = { 'type': 'edit', 'key': key } send(data) def new_jokes(): data = { 'type': 'new' } send(data, 'new') def delete_joke(key): data = { 'type': 'delete', 'key': key } send(data) def send_message(title, body): data = { 'type': 'message', 'title': title, 'text': body } send(data)
import json import requests from Suchary.local_settings import GCM_API_KEY from api.models import Device URL = 'https://android.googleapis.com/gcm/send' HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'} def get_reg_ids(): reg_ids = [device.registration_id for device in Device.objects.filter(active=True)] return reg_ids def send(data, collapse_key=None): reg_ids = get_reg_ids() payload = {'registration_ids': reg_ids, 'data': data} if collapse_key is not None: payload.update({'collapse_key': collapse_key}) r = requests.post(URL, data=json.dumps(payload), headers=HEADER) def edit_joke(key): data = { 'type': 'edit', 'key': key } send(data) def new_jokes(): data = { 'type': 'new' } send(data, 'new') def delete_joke(key): data = { 'type': 'delete', 'key': key } send(data)
Add consolescripts entry to produce 'dotsecrets' cli script
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.rst')).read() requires = [ 'pyyaml', ] setup(name='dotsecrets', version='0.0', description='Manage dot files with secrets in Git', long_description=README + '\n\n' + CHANGES, license='BSD', classifiers=[ "License :: OSI Approved :: BSD License", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Software Development :: Version Control", "Topic :: System :: Systems Administration", "Topic :: Utilities" ], author='Olaf Conradi', author_email='olaf@conradi.org', url='https://github.com/oohlaf/dotsecrets', keywords='dotfiles git secret manage private', packages=find_packages(), entry_points = { 'console_scripts': ['dotsecrets=dotsecrets.dotsecrets:main'], }, install_requires=requires, tests_require=requires, test_suite="dotsecrets.tests", )
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.rst')).read() requires = [ 'pyyaml', ] setup(name='dotsecrets', version='0.0', description='Manage dot files with secrets in Git', long_description=README + '\n\n' + CHANGES, license='BSD', classifiers=[ "License :: OSI Approved :: BSD License", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Software Development :: Version Control", "Topic :: System :: Systems Administration", "Topic :: Utilities" ], author='Olaf Conradi', author_email='olaf@conradi.org', url='https://github.com/oohlaf/dotsecrets', keywords='dotfiles git secret manage private', packages=find_packages(), install_requires=requires, tests_require=requires, test_suite="dotsecrets.tests", )
Fix 'Day' button is not working correctly issue
import React, { PropTypes } from 'react' import ReactDOM from 'react-dom' import classnames from 'classnames' import classes from './RadioButton.scss' export default class RadioButton extends React.Component { static propTypes = { onChange: PropTypes.func.isRequired, label: PropTypes.string.isRequired, groupName: PropTypes.string.isRequired, checked: PropTypes.bool } componentDidMount () { let inputNode = ReactDOM.findDOMNode(this.refs.radiobutton_input) if (this.props.checked) { inputNode.click() } let radioButtonNode = ReactDOM.findDOMNode(this.refs.radiobutton) componentHandler.upgradeElement(radioButtonNode) } handleChange = (e) => { this.props.onChange(e.target.id) } render () { let input = ( <input type='radio' id={this.props.label} className='mdl-radio__button' name={this.props.groupName} onClick={this.handleChange} ref='radiobutton_input' /> ) return ( <label className={classnames(classes.label, 'mdl-radio', 'mdl-js-radio', 'mdl-js-ripple-effect')} htmlFor={this.props.label} key={this.props.label} ref='radiobutton'> {input} <span className='mdl-radio__label'>{this.props.label}</span> </label> ) } }
import React, { PropTypes } from 'react' import ReactDOM from 'react-dom' import classnames from 'classnames' import classes from './RadioButton.scss' export default class RadioButton extends React.Component { static propTypes = { onChange: PropTypes.func.isRequired, label: PropTypes.string.isRequired, groupName: PropTypes.string.isRequired, checked: PropTypes.bool } componentDidMount () { let inputNode = ReactDOM.findDOMNode(this.refs.radiobutton_input) if (this.props.checked) { inputNode.click() } let radioButtonNode = ReactDOM.findDOMNode(this.refs.radiobutton) componentHandler.upgradeElement(radioButtonNode) } handleChange = (e) => { this.props.onChange(e.target.id) } render () { let input = ( <input type='radio' id={this.props.label} className='mdl-radio__button' name={this.props.groupName} onChange={this.handleChange} ref='radiobutton_input' /> ) return ( <label className={classnames(classes.label, 'mdl-radio', 'mdl-js-radio', 'mdl-js-ripple-effect')} htmlFor={this.props.label} key={this.props.label} ref='radiobutton'> {input} <span className='mdl-radio__label'>{this.props.label}</span> </label> ) } }
Make sure pipes are called in order
package nl.fifth.postulate.circuit; import org.junit.Test; import org.mockito.InOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.inOrder; public class PipeAssemblyTest { @Test public void shouldCallPipes() { Pipe mockPipe = mock(Pipe.class); PipeAssembly pipeAssembly = Assembly.with(mockPipe).build(); pipeAssembly.process(); verify(mockPipe).process(); } @Test public void shouldCallMultiplePipesInARow() { Pipe firstMockPipe = mock(Pipe.class); Pipe secondMockPipe = mock(Pipe.class); PipeAssembly pipeAssembly = Assembly .with(firstMockPipe) .andThen(secondMockPipe) .build(); InOrder inOrder = inOrder(firstMockPipe, secondMockPipe); pipeAssembly.process(); inOrder.verify(firstMockPipe).process(); inOrder.verify(secondMockPipe).process(); } }
package nl.fifth.postulate.circuit; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class PipeAssemblyTest { @Test public void shouldCallPipes() { Pipe mockPipe = mock(Pipe.class); PipeAssembly pipeAssembly = Assembly.with(mockPipe).build(); pipeAssembly.process(); verify(mockPipe).process(); } @Test public void shouldCallMultiplePipesInARow() { Pipe firstMockPipe = mock(Pipe.class); Pipe secondMockPipe = mock(Pipe.class); PipeAssembly pipeAssembly = Assembly .with(firstMockPipe) .andThen(secondMockPipe) .build(); pipeAssembly.process(); verify(firstMockPipe).process(); verify(secondMockPipe).process(); } }
Change exception wanted by IntMath test
package ciir.jfoley.chai; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class IntMathTest { @Test public void testNearestPowerOfTwo() throws Exception { assertEquals(1, IntMath.nearestPowerOfTwo(0)); assertEquals(2, IntMath.nearestPowerOfTwo(1)); assertEquals(4, IntMath.nearestPowerOfTwo(2)); assertEquals(8, IntMath.nearestPowerOfTwo(7)); assertEquals(16, IntMath.nearestPowerOfTwo(8)); assertEquals(16, IntMath.nearestPowerOfTwo(9)); assertEquals(32, IntMath.nearestPowerOfTwo(16)); } @Test public void testFromLong() { try { assertEquals(0, IntMath.fromLong(1L << 45)); fail("This is super un-possible."); } catch (ArithmeticException nfe) { } // assertEquals(1<<31, IntMath.fromLong(1L << 31)); // This one wraps negative! assertTrue(1L << 31 > 0); assertTrue(1 << 31 < 0); for (int i = 0; i < 31; i++) { assertEquals(1<<i, IntMath.fromLong(1L << i)); } } }
package ciir.jfoley.chai; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class IntMathTest { @Test public void testNearestPowerOfTwo() throws Exception { assertEquals(1, IntMath.nearestPowerOfTwo(0)); assertEquals(2, IntMath.nearestPowerOfTwo(1)); assertEquals(4, IntMath.nearestPowerOfTwo(2)); assertEquals(8, IntMath.nearestPowerOfTwo(7)); assertEquals(16, IntMath.nearestPowerOfTwo(8)); assertEquals(16, IntMath.nearestPowerOfTwo(9)); assertEquals(32, IntMath.nearestPowerOfTwo(16)); } @Test public void testFromLong() { try { assertEquals(0, IntMath.fromLong(1L << 45)); fail("This is super un-possible."); } catch (NumberFormatException nfe) { } // assertEquals(1<<31, IntMath.fromLong(1L << 31)); // This one wraps negative! assertTrue(1L << 31 > 0); assertTrue(1 << 31 < 0); for (int i = 0; i < 31; i++) { assertEquals(1<<i, IntMath.fromLong(1L << i)); } } }
Set the right CKAN organization
"""settings.py - settings and configuration used over all modules : Copyright (c) 2018 Heinrich Widmann (DKRZ) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import time def init(): # check the version from : global B2FINDVersion B2FINDVersion = '2.4.0' global TimeStart TimeStart = time.time() global ckanorg ckanorg = 'eudat-b2find'
"""settings.py - settings and configuration used over all modules : Copyright (c) 2018 Heinrich Widmann (DKRZ) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import time def init(): # check the version from : global B2FINDVersion B2FINDVersion = '2.4.0' global TimeStart TimeStart = time.time() global ckanorg ckanorg = 'rda'
Test remote service with USB data source (and no device plugged in). This might not be an exhaustive test - the remote service actually dies, and I'm not sure that's the right thing.
package com.openxc.remote; import com.openxc.remote.RemoteVehicleService; import com.openxc.remote.sources.ManualVehicleDataSource; import android.content.Intent; import android.test.ServiceTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; public class RemoteVehicleServiceTest extends ServiceTestCase<RemoteVehicleService> { Intent startIntent; public RemoteVehicleServiceTest() { super(RemoteVehicleService.class); } @Override protected void setUp() throws Exception { super.setUp(); startIntent = new Intent(); startIntent.setClass(getContext(), RemoteVehicleServiceInterface.class); } @SmallTest public void testPreconditions() { } @SmallTest public void testStartable() { startService(startIntent); } @MediumTest public void testUsingUsbSource() { assertNotNull(bindService(startIntent)); } @MediumTest public void testUsingManualSource() { startIntent.putExtra(RemoteVehicleService.DATA_SOURCE_NAME_EXTRA, ManualVehicleDataSource.class.getName()); assertNotNull(bindService(startIntent)); } }
package com.openxc.remote; import com.openxc.remote.RemoteVehicleService; import com.openxc.remote.sources.ManualVehicleDataSource; import android.content.Intent; import android.test.ServiceTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; public class RemoteVehicleServiceTest extends ServiceTestCase<RemoteVehicleService> { Intent startIntent; public RemoteVehicleServiceTest() { super(RemoteVehicleService.class); } @Override protected void setUp() throws Exception { super.setUp(); startIntent = new Intent(); startIntent.putExtra(RemoteVehicleService.DATA_SOURCE_NAME_EXTRA, ManualVehicleDataSource.class.getName()); startIntent.setClass(getContext(), RemoteVehicleServiceInterface.class); } @SmallTest public void testPreconditions() { } @SmallTest public void testStartable() { startService(startIntent); } @MediumTest public void testBindable() { assertNotNull(bindService(startIntent)); } @MediumTest public void testUsingManualSource() { startIntent.putExtra("data_source", ManualVehicleDataSource.class.getName()); assertNotNull(bindService(startIntent)); } }
Update the test with the expected files
/* * @license * Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved. * This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt * The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt * The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt */ 'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-polymer-init-ibm-element:app', function() { before(function() { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({ name: 'ibm-element', description: 'IBM element description' }) .toPromise(); }); it('creates files', function() { assert.file([ 'demo/index.html', 'test/ibm-element.html', 'test/index.html', '.gitignore', 'ibm-element.html', 'bower.json', 'index.html', 'LICENSE', 'README.md' ]); }); });
/* * @license * Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved. * This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt * The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt * The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt */ 'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-polymer-init-ibm-element:app', function() { before(function() { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({someAnswer: true}) .toPromise(); }); it('creates files', function() { assert.file([ 'dummyfile.txt' ]); }); });
Update notes on how to publish
""" Setup script for python packaging """ from setuptools import setup setup( name="nbwavedrom", packages=["nbwavedrom"], version="0.3.0", description="Wavedrom timing diagrams for Jupyter Notebook", author="witchard", author_email="witchard@hotmail.co.uk", url="https://github.com/witchard/nbwavedrom", download_url="https://github.com/witchard/nbwavedrom/tarball/0.3.0", keywords=["wavedrom", "jupyter", "notebook"], classifiers=[ "Development Status :: 4 - Beta", "Framework :: Jupyter", "Framework :: Jupyter :: JupyterLab", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", ], ) # Release with: # Modify release URL above to new version # git tag <version> # git push --tags # python setup.py sdist # twine upload dist/nbwavedrom-<version>.tar.gz
""" Setup script for python packaging """ from setuptools import setup setup( name="nbwavedrom", packages=["nbwavedrom"], version="0.3.0", description="Wavedrom timing diagrams for Jupyter Notebook", author="witchard", author_email="witchard@hotmail.co.uk", url="https://github.com/witchard/nbwavedrom", download_url="https://github.com/witchard/nbwavedrom/tarball/0.3.0", keywords=["wavedrom", "jupyter", "notebook"], classifiers=[ "Development Status :: 4 - Beta", "Framework :: Jupyter", "Framework :: Jupyter :: JupyterLab", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", ], ) # DONT FORGET TO CHANGE DOWNLOAD_URL WHEN DOING A RELEASE! # Thanks to this guide: http://peterdowns.com/posts/first-time-with-pypi.html # Release with: # git tag <version> # git push --tags # python setup.py sdist upload -r pypi
Remove comment containing `@FunctionalInterface` as per review comments.
/* * Copyright 2014 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.world.sun; /** * An interface for celestial systems (with only one sun) */ public interface CelestialSystem { /** * @return angle of the sun in radians */ float getSunPosAngle(); /** * Toggles the halting of sun's position and angle * * @param timeInDays */ void toggleSunHalting(float timeInDays); /** * @return Whether the sun is currently halted or not */ boolean isSunHalted(); }
/* * Copyright 2014 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.world.sun; /** * An interface for celestial systems (with only one sun) */ //@FunctionalInterface public interface CelestialSystem { /** * @return angle of the sun in radians */ float getSunPosAngle(); /** * Toggles the halting of sun's position and angle * * @param timeInDays */ void toggleSunHalting(float timeInDays); /** * @return Whether the sun is currently halted or not */ boolean isSunHalted(); }
Make Ctrl-P work for EL functions (IDEADEV-23634)
/* * Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.jsp.impl; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiType; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.meta.PsiWritableMetaData; import com.intellij.psi.xml.XmlTag; import org.jetbrains.annotations.Nullable; import java.util.List; /** * @author peter */ public interface FunctionDescriptor extends PsiWritableMetaData, PsiMetaData { String getFunctionClass(); void setFunctionClass(String functionClass); String getFunctionSignature(); void setFunctionSignature(String functionSignature); XmlTag getTag(); int getParameterCount(); String getFunctionName(); List<String> getFunctionParameters(); String getFunctionReturnType(); @Nullable PsiType getResultType(); @Nullable PsiMethod getReferencedMethod(); }
/* * Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.jsp.impl; import com.intellij.psi.PsiType; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.meta.PsiWritableMetaData; import com.intellij.psi.xml.XmlTag; import org.jetbrains.annotations.Nullable; import java.util.List; /** * @author peter */ public interface FunctionDescriptor extends PsiWritableMetaData, PsiMetaData { String getFunctionClass(); void setFunctionClass(String functionClass); String getFunctionSignature(); void setFunctionSignature(String functionSignature); XmlTag getTag(); int getParameterCount(); String getFunctionName(); List<String> getFunctionParameters(); String getFunctionReturnType(); @Nullable PsiType getResultType(); }
Adjust loading bar latency threshold
var app = angular.module('meanmap', ['ngRoute','ngStorage','ngMessages','angularMoment','angular-loading-bar','ngFileUpload','leaflet-directive','ui.bootstrap','appRoutes','ngSanitize','toastr','geocoder','ngLodash']) .factory('authInterceptor', function($q, $location, $window){ return { request: function(config){ config.headers = config.headers || {}; if($window.sessionStorage["token"]){ config.headers.token = $window.sessionStorage["token"]; } return config; }, responseError: function(response){ if(response.status == 401){ $location.path('/auth/login'); } return $q.reject(response); } }; }) .config(['cfpLoadingBarProvider','$httpProvider', function(cfpLoadingBarProvider, $httpProvider){ $httpProvider.interceptors.push('authInterceptor'); cfpLoadingBarProvider.includeSpinner = false; cfpLoadingBarProvider.includeBar = true; }]) .run(['$rootScope', '$location', function($rootScope, $location) { $rootScope.$on( "$routeChangeStart", function(event, next, current) { if($rootScope.currentUser === undefined && next.requireAuth) { $location.path( "/" ); } }); }]);
var app = angular.module('meanmap', ['ngRoute','ngStorage','ngMessages','angularMoment','angular-loading-bar','ngFileUpload','leaflet-directive','ui.bootstrap','appRoutes','ngSanitize','toastr','geocoder','ngLodash']) .factory('authInterceptor', function($q, $location, $window){ return { request: function(config){ config.headers = config.headers || {}; if($window.sessionStorage["token"]){ config.headers.token = $window.sessionStorage["token"]; } return config; }, responseError: function(response){ if(response.status == 401){ $location.path('/auth/login'); } return $q.reject(response); } }; }) .config(['cfpLoadingBarProvider','$httpProvider', function(cfpLoadingBarProvider, $httpProvider){ $httpProvider.interceptors.push('authInterceptor'); cfpLoadingBarProvider.includeSpinner = false; cfpLoadingBarProvider.includeBar = true; cfpLoadingBarProvider.latencyThreshold = 5; }]) .run(['$rootScope', '$location', function($rootScope, $location) { $rootScope.$on( "$routeChangeStart", function(event, next, current) { if($rootScope.currentUser === undefined && next.requireAuth) { $location.path( "/" ); } }); }]);
Update helper method call to unregister bundle
package flyway.asdi; import java.sql.Connection; import java.util.List; import org.flywaydb.core.api.migration.jdbc.JdbcMigration; import fi.nls.oskari.db.BundleHelper; import fi.nls.oskari.util.FlywayHelper; public class V1_19_0__remove_asdi_guided_tour implements JdbcMigration { private static final String BUNDLE_NAME = "asdi-guided-tour"; @Override public void migrate(Connection connection) throws Exception { final List<Long> views = FlywayHelper.getUserAndDefaultViewIds(connection); for (Long viewId : views) { if (FlywayHelper.viewContainsBundle(connection, BUNDLE_NAME, viewId)) { FlywayHelper.removeBundleFromView(connection, BUNDLE_NAME, viewId); } } BundleHelper.unregisterBundle(BUNDLE_NAME, connection); } }
package flyway.asdi; import java.sql.Connection; import java.util.List; import org.flywaydb.core.api.migration.jdbc.JdbcMigration; import fi.nls.oskari.db.BundleHelper; import fi.nls.oskari.domain.map.view.Bundle; import fi.nls.oskari.util.FlywayHelper; public class V1_19_0__remove_asdi_guided_tour implements JdbcMigration { private static final String BUNDLE_NAME = "asdi-guided-tour"; @Override public void migrate(Connection connection) throws Exception { Bundle bundle = new Bundle(); bundle.setName(BUNDLE_NAME); final List<Long> views = FlywayHelper.getUserAndDefaultViewIds(connection); for (Long viewId : views) { if (FlywayHelper.viewContainsBundle(connection, BUNDLE_NAME, viewId)) { FlywayHelper.removeBundleFromView(connection, BUNDLE_NAME, viewId); } } BundleHelper.removeBundle(bundle, connection); } }
Throw error if 0 roads are found
const getJSON = require('get-json'); const unique = require('array-unique'); /** URL of the Overpass API being used */ const overpass = 'http://overpass-api.de/api/interpreter?data='; /** * Get all road names within a specified distance from a location. * @param {number} lat - Latitude of centre location. * @param {number} long - Longitude of centre location. * @param {number} distance - Radius distance in metres. * @param {function} callback - callback(err, data) * @returns {array} - Array of road names, use callback. */ function fromCentre(lat, long, distance, callback) { const query = `[out:json]; way["highway"](around:${distance},${lat},${long}); out;`; getJSON(`${overpass}${query}`, (err, result) => { if (err) callback(err, null); if (result.elements.length === 0) callback(new Error('Found 0 Roads'), null); let roads = []; result.elements.forEach(element => roads.push(element.tags.name)); roads = unique(roads); callback(null, roads); }); } fromCentre(51.424037, -0.148666, 100, (err, data) => { if (err) console.log(err); else console.log(data); });
const getJSON = require('get-json'); const unique = require('array-unique'); /** URL of the Overpass API being used */ const overpass = 'http://overpass-api.de/api/interpreter?data='; /** * Get all road names within a specified distance from a location. * @param {number} lat - Latitude of centre location. * @param {number} long - Longitude of centre location. * @param {number} distance - Radius distance in metres. * @param {function} callback - callback(err, data) * @returns {array} - Array of road names, use callback. */ function fromCentre(lat, long, distance, callback) { const query = `[out:json]; way["highway"](around:${distance},${lat},${long}); out;`; getJSON(`${overpass}${query}`, (err, result) => { if (err) callback(err, null); let roads = []; result.elements.forEach(element => roads.push(element.tags.name)); roads = unique(roads); callback(null, roads); }); } fromCentre(51.424037, -0.148666, 100, (err, data) => { if (err) console.log(err); console.log(data); });
Change ResourceLeakDetector to PARANOID for displayleaks
package us.myles.ViaVersion.commands.defaultsubs; import io.netty.util.ResourceLeakDetector; import us.myles.ViaVersion.api.command.ViaCommandSender; import us.myles.ViaVersion.api.command.ViaSubCommand; public class DisplayLeaksSubCmd extends ViaSubCommand { @Override public String name() { return "displayleaks"; } @Override public String description() { return "Try to hunt memory leaks!"; } @Override public boolean execute(ViaCommandSender sender, String[] args) { if (ResourceLeakDetector.getLevel() != ResourceLeakDetector.Level.PARANOID) ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); else ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED); sendMessage(sender, "&6Leak detector is now %s", (ResourceLeakDetector.getLevel() == ResourceLeakDetector.Level.PARANOID ? "&aenabled" : "&cdisabled")); return true; } }
package us.myles.ViaVersion.commands.defaultsubs; import io.netty.util.ResourceLeakDetector; import us.myles.ViaVersion.api.command.ViaCommandSender; import us.myles.ViaVersion.api.command.ViaSubCommand; public class DisplayLeaksSubCmd extends ViaSubCommand { @Override public String name() { return "displayleaks"; } @Override public String description() { return "Try to hunt memory leaks!"; } @Override public boolean execute(ViaCommandSender sender, String[] args) { if (ResourceLeakDetector.getLevel() != ResourceLeakDetector.Level.ADVANCED) ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED); else ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED); sendMessage(sender, "&6Leak detector is now %s", (ResourceLeakDetector.getLevel() == ResourceLeakDetector.Level.ADVANCED ? "&aenabled" : "&cdisabled")); return true; } }
Make the extrn object use the convention for rebased addresses
from cle.absobj import AbsObj class AngrExternObject(AbsObj): def __init__(self, alloc_size=0x1000): super(AngrExternObject, self).__init__('##angr_externs##') self._next_addr = 0 self._lookup_table = {} self._alloc_size = alloc_size self.memory = 'please never look at this' def get_max_addr(self): return self._alloc_size + self.rebase_addr def get_min_addr(self): return self.rebase_addr def get_pseudo_addr(self, ident): if ident not in self._lookup_table: self._lookup_table[ident] = self._next_addr self._next_addr += 16 return self._lookup_table[ident] + self.rebase_addr
from cle.absobj import AbsObj class AngrExternObject(AbsObj): def __init__(self, alloc_size=0x1000): super(AngrExternObject, self).__init__('##angr_externs##') self._next_addr = 0 self._lookup_table = {} self._alloc_size = alloc_size self.memory = 'please never look at this' def get_max_addr(self): return self._alloc_size def get_min_addr(self): return 0 def get_pseudo_addr(self, ident): if ident not in self._lookup_table: self._lookup_table[ident] = self._next_addr self._next_addr += 16 return self._lookup_table[ident] + self.rebase_addr
Change column name of user in speaker entity Accordingly to other tables and to the database diagram
<?php namespace Project\AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Speaker * * @ORM\Table() * @ORM\Entity(repositoryClass="Project\AppBundle\Entity\SpeakerRepository") */ class Speaker { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\OneToOne(targetEntity="Project\AppBundle\Entity\User", cascade={"persist"}) */ private $user; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set user * * @param \Project\AppBundle\Entity\User $user * @return Speaker */ public function setUser(\Project\AppBundle\Entity\User $user = null) { $this->user = $user; return $this; } /** * Get user * * @return \Project\AppBundle\Entity\User */ public function getUser() { return $this->user; } }
<?php namespace Project\AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Speaker * * @ORM\Table() * @ORM\Entity(repositoryClass="Project\AppBundle\Entity\SpeakerRepository") */ class Speaker { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\OneToOne(targetEntity="Project\AppBundle\Entity\User", cascade={"persist"}) * @ORM\JoinColumn(name="id", referencedColumnName="id") */ private $user; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set user * * @param \Project\AppBundle\Entity\User $user * @return Speaker */ public function setUser(\Project\AppBundle\Entity\User $user = null) { $this->user = $user; return $this; } /** * Get user * * @return \Project\AppBundle\Entity\User */ public function getUser() { return $this->user; } }
[BUGFIX] Fix the jit-grunt mapping for the replace task
module.exports = function(grunt) { "use strict"; // Display the execution time of grunt tasks require("time-grunt")(grunt); // Load all grunt-tasks in 'Build/Grunt-Options'. var gruntOptionsObj = require("load-grunt-configs")(grunt, { "config" : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. require('jit-grunt')(grunt, { replace: 'grunt-text-replace' }); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask("default", ["compass:dev", "jshint"]); /** * Travis CI task * Test all specified grunt tasks. */ grunt.registerTask("travis", ["init", "replace:init", "jshint", "deploy", "undeploy"]); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks("Build/Grunt-Tasks"); };
module.exports = function(grunt) { "use strict"; // Display the execution time of grunt tasks require("time-grunt")(grunt); // Load all grunt-tasks in 'Build/Grunt-Options'. var gruntOptionsObj = require("load-grunt-configs")(grunt, { "config" : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. require('jit-grunt')(grunt); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask("default", ["compass:dev", "jshint"]); /** * Travis CI task * Test all specified grunt tasks. */ grunt.registerTask("travis", ["init", "replace:init", "jshint", "deploy", "undeploy"]); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks("Build/Grunt-Tasks"); };
Use .get instead of getattr, dummy.
import twitter import urllib2 NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT" def retrieve_and_post(conf): post = False pull_url = NOAA_URL.replace('*station_id*', conf['station']) request = urllib2.Request(pull_url, None) response = urllib2.urlopen(request) metar = response.read().split('\n')[1] # NOAA includes a "real" timestamp as the first line of the response if conf.get('hashtag', False): metar = '%s #%s' % (metar, conf['hashtag']) api = twitter.Api(username=conf['twitter_user'], password=conf['twitter_password']) # get the last posted message and make sure it's different before attempting to post. Twitter isn't supposed to allow dupes through but I'm seeing it happen anyway past_statuses = api.GetUserTimeline(conf['twitter_user']) if past_statuses[-0].text != metar: post = True if post: api.PostUpdate(metar) if __name__ == '__main__': retrieve_and_post({'station': '<station_id>', 'twitter_user': '<twitter_user>', 'twitter_password': '<twitter_pass>'})
import twitter import urllib2 NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT" def retrieve_and_post(conf): post = False pull_url = NOAA_URL.replace('*station_id*', conf['station']) request = urllib2.Request(pull_url, None) response = urllib2.urlopen(request) metar = response.read().split('\n')[1] # NOAA includes a "real" timestamp as the first line of the response if getattr(conf, 'hashtag', False): metar = '%s #%s' % (metar, conf['hashtag']) api = twitter.Api(username=conf['twitter_user'], password=conf['twitter_password']) # get the last posted message and make sure it's different before attempting to post. Twitter isn't supposed to allow dupes through but I'm seeing it happen anyway past_statuses = api.GetUserTimeline(conf['twitter_user']) if past_statuses[-0].text != metar: post = True if post: api.PostUpdate(metar) if __name__ == '__main__': retrieve_and_post({'station': '<station_id>', 'twitter_user': '<twitter_user>', 'twitter_password': '<twitter_pass>'})
Check if there is url fragment and added portrait
<link rel="stylesheet" type="text/css" href="<?=$this->getThemePath()?>/css/services.css"> <?php $this->inc('header.php'); ?> <div id="content"> <div id="container"> <div id="intro"> <?php $b = new Area('Content'); $b->display($c); ?> </div> <div class="panel-group" id="accordion"> <?php $b = new Area('Accordion'); $b->display($c); ?> </div><!-- row --> <?php $this->inc('elements/footer.php'); ?> </div><!-- content --> <?php Loader::element('footer_required'); ?> <script src="<?=$this->getThemePath()?>/js/bootstrap.js"></script> </div> </body> </html> <script type="text/javascript"> $(document).ready(function() { var anchor = window.location.hash.replace("#", ""); $("#" + anchor).collapse('show'); if(anchor !== "") { function goToByScroll(id){ $('html,body').animate({scrollTop: $("#"+id).offset().top - 130},'slow'); } setTimeout(function(){ goToByScroll(anchor); },1000); } }); </script>
<link rel="stylesheet" type="text/css" href="<?=$this->getThemePath()?>/css/services.css"> <?php $this->inc('header.php'); ?> <div id="content"> <div id="container"> <div id="intro"> <?php $b = new Area('Content'); $b->display($c); ?> </div> <div class="panel-group" id="accordion"> <?php $b = new Area('Accordion'); $b->display($c); ?> </div><!-- row --> <?php $this->inc('elements/footer.php'); ?> </div><!-- content --> <?php Loader::element('footer_required'); ?> <script src="<?=$this->getThemePath()?>/js/bootstrap.js"></script> </div> </body> </html> <script type="text/javascript"> $(document).ready(function() { var anchor = window.location.hash.replace("#", ""); $("#" + anchor).collapse('show'); function goToByScroll(id){ $('html,body').animate({scrollTop: $("#"+id).offset().top - 130},'slow'); } setTimeout(function(){ goToByScroll(anchor); },1000); }); </script>
Use yandex.com as a smoke tests server for https requests
var Asker = require('../lib/asker'), ask = Asker, assert = require('chai').assert; module.exports = { '#isRunning getter returns actual value of the private field _isRunning' : function(done) { var request = new Asker(); assert.strictEqual(request._isRunning, null, 'default _isRunning state is `null`'); assert.strictEqual(request.isRunning, false, 'value returned by isRunning getter equals private field value'); request._isRunning = true; assert.strictEqual(request.isRunning, true, 'value returned by isRunning getter equals private field value'); done(); }, 'sanity check for https client' : function(done) { ask({ url : 'https://www.yandex.com/', timeout : 3000 }, function(error, response) { assert.isNull(error); assert.strictEqual(response.statusCode, 200); assert.ok(response.data.length > 0); done(); }); } };
var Asker = require('../lib/asker'), ask = Asker, assert = require('chai').assert; module.exports = { '#isRunning getter returns actual value of the private field _isRunning' : function(done) { var request = new Asker(); assert.strictEqual(request._isRunning, null, 'default _isRunning state is `null`'); assert.strictEqual(request.isRunning, false, 'value returned by isRunning getter equals private field value'); request._isRunning = true; assert.strictEqual(request.isRunning, true, 'value returned by isRunning getter equals private field value'); done(); }, 'sanity check for https client' : function(done) { ask({ url : 'https://mail.yandex.ru/', timeout : 3000 }, function(error, response) { assert.isNull(error); assert.strictEqual(response.statusCode, 200); assert.ok(response.data.length > 0); done(); }); } };
Fix `iconClasses` and `iconText` tests
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('bs-datetimepicker', 'Integration | Component | bs datetimepicker', { integration: true }); test('it renders iconClasses and iconText', function(assert) { assert.expect(2); this.render(hbs`{{bs-datetimepicker date='01/01/2016' iconClasses='material-icons' iconText='date-range'}}`); assert.equal(this.$('.input-group-addon i').attr('class'), 'material-icons'); assert.equal(this.$('.input-group-addon i').text().trim(), 'date-range'); }); test('it renders with default icon classes', function(assert) { assert.expect(1); this.render(hbs`{{bs-datetimepicker date='01/01/2016'}}`); assert.equal(this.$('.input-group-addon i').attr('class'), 'glyphicon glyphicon-calendar'); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('bs-datetimepicker', 'Integration | Component | bs datetimepicker', { integration: true }); test('it renders iconClasses and iconText', function(assert) { assert.expect(2); this.render(hbs`{{bs-datetimepicker date='01/01/2016' classes='material-icons' iconText='date-range'}}`); assert.equal(this.$('.input-group-addon i').attr('class'), 'material-icons'); // Slice off the zero-width-non-joiner character assert.equal(this.$('.input-group-addon i').text().trim().slice(0, -1), 'date-range'); }); test('it renders with default icon classes', function(assert) { assert.expect(1); this.render(hbs`{{bs-datetimepicker date='01/01/2016'}}`); assert.equal(this.$('.input-group-addon i').attr('class'), 'glyphicon glyphicon-calendar'); });
Fix order of default index directories When attempting to "extend" scaffolds, local required scaffolds might be overwritten in the index if they exists in both local and global vendor. This created unwanted situations.
<?php namespace Aedart\Scaffold\Traits; use Composer\Factory; /** * Directories To Index * * Utility that tells what directories should be indexed by default * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Scaffold\Traits */ trait DirectoriesToIndex { /** * Returns a list of directory paths in which scaffold files * are to be searched for, in order to build an index * * @return string[] */ public function directories() { $composerConfig = Factory::createConfig(null, getcwd()); $vendorDir = $composerConfig->get('vendor-dir'); $globalVendorDir = Factory::createConfig(null, $composerConfig->get('home'))->get('vendor-dir'); return [ // The "global" vendor directory inside the composer home $globalVendorDir, // The vendor folder inside the current working directory $vendorDir, // The current working directory of where this command // is being executed from getcwd() . DIRECTORY_SEPARATOR, ]; } }
<?php namespace Aedart\Scaffold\Traits; use Composer\Factory; /** * Directories To Index * * Utility that tells what directories should be indexed by default * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Scaffold\Traits */ trait DirectoriesToIndex { /** * Returns a list of directory paths in which scaffold files * are to be searched for, in order to build an index * * @return string[] */ public function directories() { $composerConfig = Factory::createConfig(null, getcwd()); $vendorDir = $composerConfig->get('vendor-dir'); $globalVendorDir = Factory::createConfig(null, $composerConfig->get('home'))->get('vendor-dir'); return [ // The current working directory of where this command // is being executed from getcwd() . DIRECTORY_SEPARATOR, // The vendor folder inside the current working directory $vendorDir, // The "global" vendor directory inside the composer home $globalVendorDir ]; } }
Add "config file was not fount" error handler
# coding: utf-8 import os.path import yaml import logging CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'settings.yaml') logger = logging.getLogger(__name__) try: with open(CONFIG_PATH, 'r') as fh: config = yaml.load(fh) except FileNotFoundError: logging.error('Config file was not found: settings.yaml') logging.error('You must create it first') exit(1) # Jira settings JIRA_URL = config['jira']['url'] JIRA_USER = config['jira']['user'] JIRA_PASS = config['jira']['pass'] JIRA_PROJECT = config['jira']['project'] # SMTP settings SMTP_HOST = config['smtp']['host'] SMTP_PORT = config['smtp']['port'] SMTP_USER = config['smtp']['user'] SMTP_PASS = config['smtp']['pass'] # Mail settings EMAIL_FROM = config['email']['from'] EMAIL_TO = config['email']['to'] DAILY_SUBJECT = config['email']['daily_subject'] QUEUE_SUBJECT = config['email']['queue_subject'] AGES_SUBJECT = config['email']['ages_subject'] WEEKLY_SUBJECT = config['email']['weekly_subject'] # Team settings TEAM = [x['mail'] for x in config['team']] FUNC = [x['mail'] for x in config['team'] if x['role'] == 'manual'] AUTO = [x['mail'] for x in config['team'] if x['role'] == 'auto']
# coding: utf-8 import os.path import yaml CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'settings.yaml') with open(CONFIG_PATH, 'r') as fh: config = yaml.load(fh) # Jira settings JIRA_URL = config['jira']['url'] JIRA_USER = config['jira']['user'] JIRA_PASS = config['jira']['pass'] JIRA_PROJECT = config['jira']['project'] # SMTP settings SMTP_HOST = config['smtp']['host'] SMTP_PORT = config['smtp']['port'] SMTP_USER = config['smtp']['user'] SMTP_PASS = config['smtp']['pass'] # Mail settings EMAIL_FROM = config['email']['from'] EMAIL_TO = config['email']['to'] DAILY_SUBJECT = config['email']['daily_subject'] QUEUE_SUBJECT = config['email']['queue_subject'] AGES_SUBJECT = config['email']['ages_subject'] WEEKLY_SUBJECT = config['email']['weekly_subject'] # Team settings TEAM = [x['mail'] for x in config['team']] FUNC = [x['mail'] for x in config['team'] if x['role'] == 'manual'] AUTO = [x['mail'] for x in config['team'] if x['role'] == 'auto']
Refactor Tag Manager with registered components.
/** * Tag Manager module initialization. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import domReady from '@wordpress/dom-ready'; import { addFilter } from '@wordpress/hooks'; /** * Internal dependencies */ import './datastore'; import Data from 'googlesitekit-data'; import { SetupMain } from './components/setup'; import { SettingsEdit, SettingsView } from './components/settings'; import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants'; import { fillFilterWithComponent } from '../../util'; addFilter( 'googlesitekit.ModuleSetup-tagmanager', 'googlesitekit.TagManagerModuleSetup', fillFilterWithComponent( SetupMain ) ); domReady( () => { Data.dispatch( CORE_MODULES ).registerModule( 'tagmanager', { settingsEditComponent: SettingsEdit, settingsViewComponent: SettingsView, } ); } );
/** * Tag Manager module initialization. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { addFilter } from '@wordpress/hooks'; /** * Internal dependencies */ import { fillFilterWithComponent } from '../../util'; import './datastore'; import { SetupMain } from './components/setup'; import { SettingsMain } from './components/settings'; addFilter( 'googlesitekit.ModuleSetup-tagmanager', 'googlesitekit.TagManagerModuleSetup', fillFilterWithComponent( SetupMain ) ); addFilter( 'googlesitekit.ModuleSettingsDetails-tagmanager', 'googlesitekit.TagManagerModuleSettings', fillFilterWithComponent( SettingsMain ) );
Fix Access Group's Mapper modal
/*! Copyright (C) 2017 Google Inc. Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function (can, GGRC) { 'use strict'; GGRC.Components('mappingTypeSelector', { tag: 'mapping-type-selector', template: can.view( GGRC.mustache_path + '/components/mapping-controls/mapping-type-selector.mustache' ), viewModel: { disabled: false, readonly: false, types: [], selectedType: '' }, init: function () { var selectedType = this.viewModel.selectedType; var types = this.viewModel.types; var groups = ['business', 'entities', 'governance']; var values = []; groups.forEach(function (name) { var groupItems = types.attr(name + '.items'); values = values.concat(_.pluck(groupItems, 'value')); }); if (values.indexOf(selectedType) < 0) { this.viewModel.attr('selectedType', values[0]); } } }); })(window.can, window.GGRC);
/*! Copyright (C) 2017 Google Inc. Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function (can, GGRC) { 'use strict'; GGRC.Components('mappingTypeSelector', { tag: 'mapping-type-selector', template: can.view( GGRC.mustache_path + '/components/mapping-controls/mapping-type-selector.mustache' ), scope: { disabled: false, readonly: false, types: [], selectedType: '' }, events: { init: function () { // We might need to add some specific logic for disabled/enable DropDown items } } }); })(window.can, window.GGRC);
Change paths in PML-XML tool
#!/usr/bin/env/python import sys import os.path import subprocess # Read in a pml file and save to an xml file def translate_pml_file(xml_file, pml_file): pml_path = os.path.abspath(pml_file.name) xml_path = os.path.abspath(xml_file.name) # Call XML generator # TODO: Remove abs-path return_code = subprocess.call("/opt/pml-bnfc/xml/Pmlxml %s %s" % (xml_path, pml_path), shell=True) if return_code != 0: print "Error occured reading PML file, exiting." sys.exit(1) def main(): import argparse parser = argparse.ArgumentParser(description="Program to output the ast of a PML program in XML format") parser.add_argument('-x', '--xml', required=True, type=file, help="Output abstract syntax tree in XML format") parser.add_argument('-p', '--pml', required=True, type=file, help="Input PML file") try: args = parser.parse_args() translate_pml_file(args.xml, args.pml) except IOError, msg: parser.error(str(msg)) if __name__ == "__main__": main()
#!/usr/bin/env/python import sys import os.path import subprocess # Read in a pml file and save to an xml file def translate_pml_file(xml_file, pml_file): pml_path = os.path.abspath(pml_file.name) xml_path = os.path.abspath(xml_file.name) # Call XML generator return_code = subprocess.call("Pmlxml %s %s" % (xml_path, pml_path), shell=True) if return_code != 0: print "Error occured reading PML file, exiting." sys.exit(1) def main(): import argparse parser = argparse.ArgumentParser(description="Program to output the ast of a PML program in XML format") parser.add_argument('-x', '--xml', required=True, type=file, help="Output abstract syntax tree in XML format") parser.add_argument('-p', '--pml', required=True, type=file, help="Input PML file") try: args = parser.parse_args() translate_pml_file(args.xml, args.pml) except IOError, msg: parser.error(str(msg)) if __name__ == "__main__": main()
Fix Coarse Dirt not letting plants be placed on top of itself
package ganymedes01.etfuturum.blocks; import ganymedes01.etfuturum.EtFuturum; import ganymedes01.etfuturum.IConfigurable; import ganymedes01.etfuturum.core.utils.Utils; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.ForgeDirection; public class CoarseDirt extends Block implements IConfigurable { public CoarseDirt() { super(Material.ground); setHardness(0.5F); setStepSound(soundTypeGravel); setBlockTextureName("coarse_dirt"); setBlockName(Utils.getUnlocalisedName("coarse_dirt")); setCreativeTab(EtFuturum.enableCoarseDirt ? EtFuturum.creativeTab : null); } @Override public boolean canSustainPlant(IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plant) { return Blocks.dirt.canSustainPlant(world, x, y, z, direction, plant); } @Override public boolean isEnabled() { return EtFuturum.enableCoarseDirt; } }
package ganymedes01.etfuturum.blocks; import ganymedes01.etfuturum.EtFuturum; import ganymedes01.etfuturum.IConfigurable; import ganymedes01.etfuturum.core.utils.Utils; import net.minecraft.block.Block; import net.minecraft.block.material.Material; public class CoarseDirt extends Block implements IConfigurable { public CoarseDirt() { super(Material.ground); setHardness(0.5F); setStepSound(soundTypeGravel); setBlockTextureName("coarse_dirt"); setBlockName(Utils.getUnlocalisedName("coarse_dirt")); setCreativeTab(EtFuturum.enableCoarseDirt ? EtFuturum.creativeTab : null); } @Override public boolean isEnabled() { return EtFuturum.enableCoarseDirt; } }
Clean out the mako temp dirs before running tests
""" Helper functions for test tasks """ from paver.easy import sh, task from pavelib.utils.envs import Env __test__ = False # do not collect @task def clean_test_files(): """ Clean fixture files used by tests and .pyc files """ sh("git clean -fqdx test_root/logs test_root/data test_root/staticfiles test_root/uploads") sh("find . -type f -name \"*.pyc\" -delete") sh("rm -rf test_root/log/auto_screenshots/*") sh("rm -rf /tmp/mako_[cl]ms") def clean_dir(directory): """ Clean coverage files, to ensure that we don't use stale data to generate reports. """ # We delete the files but preserve the directory structure # so that coverage.py has a place to put the reports. sh('find {dir} -type f -delete'.format(dir=directory)) @task def clean_reports_dir(): """ Clean coverage files, to ensure that we don't use stale data to generate reports. """ # We delete the files but preserve the directory structure # so that coverage.py has a place to put the reports. reports_dir = Env.REPORT_DIR.makedirs_p() clean_dir(reports_dir) @task def clean_mongo(): """ Clean mongo test databases """ sh("mongo {repo_root}/scripts/delete-mongo-test-dbs.js".format(repo_root=Env.REPO_ROOT))
""" Helper functions for test tasks """ from paver.easy import sh, task from pavelib.utils.envs import Env __test__ = False # do not collect @task def clean_test_files(): """ Clean fixture files used by tests and .pyc files """ sh("git clean -fqdx test_root/logs test_root/data test_root/staticfiles test_root/uploads") sh("find . -type f -name \"*.pyc\" -delete") sh("rm -rf test_root/log/auto_screenshots/*") def clean_dir(directory): """ Clean coverage files, to ensure that we don't use stale data to generate reports. """ # We delete the files but preserve the directory structure # so that coverage.py has a place to put the reports. sh('find {dir} -type f -delete'.format(dir=directory)) @task def clean_reports_dir(): """ Clean coverage files, to ensure that we don't use stale data to generate reports. """ # We delete the files but preserve the directory structure # so that coverage.py has a place to put the reports. reports_dir = Env.REPORT_DIR.makedirs_p() clean_dir(reports_dir) @task def clean_mongo(): """ Clean mongo test databases """ sh("mongo {repo_root}/scripts/delete-mongo-test-dbs.js".format(repo_root=Env.REPO_ROOT))
Remove hard-coded SNS topic ARN
var SNS = require('aws-sdk/clients/sns'); exports.lambda_handler = function(event, context, callback) { var sns = new SNS(); console.log("About to process " + event.Records.length + " events"); event.Records.forEach(function(record) { if (record.eventName == "INSERT") { try { var author = record.dynamodb.NewImage.name.S; } catch (e) { return callback(e, "Error extracting author name from update stream"); } sns.publish({ TopicArn: process.env.AUTHOR_REFRESH_TOPIC_ARN, Message: author }, function(err, data) { if (err) { console.log("Error publishing to topic: " + err); } else { console.log("Sent message for author " + author); } }); } else { console.log("Skipping record -- record.eventName: " + record.eventName); } }); callback(null, "done"); };
var SNS = require('aws-sdk/clients/sns'); exports.lambda_handler = function(event, context, callback) { var sns = new SNS(); console.log("About to process " + event.Records.length + " events"); event.Records.forEach(function(record) { if (record.eventName == "INSERT") { try { var author = record.dynamodb.NewImage.name.S; } catch (e) { return callback(e, "Error extracting author name from update stream"); } sns.publish({ TopicArn: "arn:aws:sns:eu-west-1:285774518219:author_added", Message: author }, function(err, data) { if (err) { console.log("Error publishing to topic: " + err); } else { console.log("Sent message for author " + author); } }); } else { console.log("Skipping record -- record.eventName: " + record.eventName); } }); callback(null, "done"); };
Remove npm start's earth icon in case of unsupport environment
'use strict' const webpack = require('webpack') const webpackDevMiddleware = require('webpack-dev-middleware') const webpackHotMiddleware = require('webpack-hot-middleware') const express = require('express') const config = require('./webpack.config') const compiler = webpack(config) const app = express() const port = 3990 app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath, stats: { colors: true, }, })) app.use(webpackHotMiddleware(compiler)) app.get('/', (req, res) => { res.sendFile(`${__dirname}/src/index.html`) }) app.get('/api/*', (req, res) => { // Imitate RESTful API pattern let path = req.path path = /\/comics\/[\d]+(\/episodes)?/.test(path) ? `${path}/data` : path res.sendFile(`${__dirname}/src${path}`) }) app.listen(port, (error) => { if (error) { console.error(error) } else { console.info('==> Open up http://localhost:%s/ in your browser.', port) } })
'use strict' const webpack = require('webpack') const webpackDevMiddleware = require('webpack-dev-middleware') const webpackHotMiddleware = require('webpack-hot-middleware') const express = require('express') const config = require('./webpack.config') const compiler = webpack(config) const app = express() const port = 3990 app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath, stats: { colors: true, }, })) app.use(webpackHotMiddleware(compiler)) app.get('/', (req, res) => { res.sendFile(`${__dirname}/src/index.html`) }) app.get('/api/*', (req, res) => { // Imitate RESTful API pattern let path = req.path path = /\/comics\/[\d]+(\/episodes)?/.test(path) ? `${path}/data` : path res.sendFile(`${__dirname}/src${path}`) }) app.listen(port, (error) => { if (error) { console.error(error) } else { console.info('==> 🌎 Open up http://localhost:%s/ in your browser.', port) } })
Fix function name for PUT .../layer
package router import( "github.com/ricallinson/forgery" "github.com/spacedock-io/registry/images" "github.com/spacedock-io/registry/repositories" "github.com/spacedock-io/registry/auth" ) func Routes(server *f.Server) { /* Home page */ server.Get("/", func(req *f.Request, res *f.Response, next func()) { res.Send("docker-registry server") }) /* Ping */ server.Get("/v1/_ping", func(req *f.Request, res *f.Response, next func()) { res.Send("true") }) /* Images Routes */ server.Get("/v1/images/:id/ancestry", auth.Secure(images.GetAncestry)) server.Get("/v1/images/:id/layer", auth.Secure(images.GetLayer)) server.Put("/v1/images/:id/layer", auth.Secure(images.PutLayer)) server.Get("/v1/images/:id/json", auth.Secure(images.GetJson)) server.Put("/v1/images/:id/json", auth.Secure(images.PutJson)) server.Get("/v1/repositories/:namespace/:repo/tags", auth.Secure(repositories.GetTags)) server.Get("/v1/repositories/:namespace/:repo/tags/:tag", auth.Secure(repositories.GetTag)) server.Put("/v1/repositories/:namespace/:repo/tags/:tag", auth.Secure(repositories.CreateTag)) }
package router import( "github.com/ricallinson/forgery" "github.com/spacedock-io/registry/images" "github.com/spacedock-io/registry/repositories" "github.com/spacedock-io/registry/auth" ) func Routes(server *f.Server) { /* Home page */ server.Get("/", func(req *f.Request, res *f.Response, next func()) { res.Send("docker-registry server") }) /* Ping */ server.Get("/v1/_ping", func(req *f.Request, res *f.Response, next func()) { res.Send("true") }) /* Images Routes */ server.Get("/v1/images/:id/ancestry", auth.Secure(images.GetAncestry)) server.Get("/v1/images/:id/layer", auth.Secure(images.GetLayer)) server.Put("/v1/images/:id/layer", auth.Secure(images.GetLayer)) server.Get("/v1/images/:id/json", auth.Secure(images.GetJson)) server.Put("/v1/images/:id/json", auth.Secure(images.PutJson)) server.Get("/v1/repositories/:namespace/:repo/tags", auth.Secure(repositories.GetTags)) server.Get("/v1/repositories/:namespace/:repo/tags/:tag", auth.Secure(repositories.GetTag)) server.Put("/v1/repositories/:namespace/:repo/tags/:tag", auth.Secure(repositories.CreateTag)) }
Fix wrong exchange of cartbox-domelement
var onReady = require('kwf/on-ready'); var $ = require('jQuery'); var getKwcRenderUrl = require('kwf/get-kwc-render-url'); onReady.onRender('.kwcClass',function(el) { var url = getKwcRenderUrl(); $.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) { $(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) { $.ajax({ url: url, data: { componentId: el.data('component-id') }, success: function(response) { $('.kwcClass').html(response); onReady.callOnContentReady(el, {newRender: true}); } }); }, el)); }, el)); }, { priority: 0 }); //call after Kwc.Form.Component
var onReady = require('kwf/on-ready'); var $ = require('jQuery'); var getKwcRenderUrl = require('kwf/get-kwc-render-url'); onReady.onRender('.kwcClass',function(el) { var url = getKwcRenderUrl(); $.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) { $(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) { $.ajax({ url: url, data: { componentId: el.data('component-id') }, success: function(response) { el.html(response); onReady.callOnContentReady(el, {newRender: true}); } }); }, el)); }, el)); }, { priority: 0 }); //call after Kwc.Form.Component
Add fields to driller list serializer
from rest_framework import serializers from registries.models import Organization from gwells.models import ProvinceState class DrillerListSerializer(serializers.ModelSerializer): """ Serializer for Driller model "list" view. """ province_state = serializers.ReadOnlyField(source="province_state.code") class Meta: model = Organization # Using all fields for now fields = ( #'who_created', #'when_created', #'who_updated', #'when_updated', 'org_guid', 'name', 'street_address', 'city', 'province_state', 'postal_code', 'main_tel', #'fax_tel', #'website_url', #'certificate_authority', )
from rest_framework import serializers from registries.models import Organization from gwells.models import ProvinceState class DrillerListSerializer(serializers.ModelSerializer): province_state = serializers.ReadOnlyField() class Meta: model = Organization # Using all fields for now fields = ( #'who_created', #'when_created', #'who_updated', #'when_updated', 'name', 'street_address', 'city', 'province_state', 'postal_code', 'main_tel', 'fax_tel', 'website_url', 'certificate_authority', )
[tests] Use public API in tests
from unittest import TestCase from asserts import assert_equal from htmlgen import Image from test_htmlgen.util import parse_short_tag class ImageTest(TestCase): def test_attributes(self): image = Image("my-image.png", "Alternate text") assert_equal("my-image.png", image.url) assert_equal("Alternate text", image.alternate_text) def test_attributes_default_alt(self): image = Image("my-image.png") assert_equal("", image.alternate_text) def test_with_alt(self): image = Image("my-image.png", "Alternate text") tag = parse_short_tag(str(image)) assert_equal("img", tag.name) assert_equal("my-image.png", image.get_attribute("src")) assert_equal("Alternate text", image.get_attribute("alt")) def test_without_alt(self): image = Image("my-image.png") tag = parse_short_tag(str(image)) assert_equal("img", tag.name) assert_equal("my-image.png", image.get_attribute("src")) assert_equal("", image.get_attribute("alt"))
from unittest import TestCase from asserts import assert_equal from htmlgen import Image from test_htmlgen.util import parse_short_tag class ImageTest(TestCase): def test_attributes(self): image = Image("my-image.png", "Alternate text") assert_equal("my-image.png", image.url) assert_equal("Alternate text", image.alternate_text) def test_attributes_default_alt(self): image = Image("my-image.png") assert_equal("", image.alternate_text) def test_with_alt(self): image = Image("my-image.png", "Alternate text") tag = parse_short_tag(str(image)) assert_equal("img", tag.name) assert_equal("my-image.png", image._attributes["src"]) assert_equal("Alternate text", image._attributes["alt"]) def test_without_alt(self): image = Image("my-image.png") tag = parse_short_tag(str(image)) assert_equal("img", tag.name) assert_equal("my-image.png", image._attributes["src"]) assert_equal("", image._attributes["alt"])
Update the numpy requirement since we use numpy.isin, which is only available in numpy 1.13.0 onwards.
from setuptools import setup setup( name = 'PyFVCOM', packages = ['PyFVCOM'], version = '2.1.0', description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."), author = 'Pierre Cazenave', author_email = 'pica@pml.ac.uk', url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM', download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0', keywords = ['fvcom', 'unstructured grid', 'mesh'], license = 'MIT', platforms = 'any', install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy>=1.13.0', 'matplotlib', 'netCDF4', 'lxml', 'pyproj', 'pytz', 'networkx', 'UTide', 'pandas', 'cmocean'], classifiers = [] )
from setuptools import setup setup( name = 'PyFVCOM', packages = ['PyFVCOM'], version = '2.1.0', description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."), author = 'Pierre Cazenave', author_email = 'pica@pml.ac.uk', url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM', download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0', keywords = ['fvcom', 'unstructured grid', 'mesh'], license = 'MIT', platforms = 'any', install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy>=1.10.0', 'matplotlib', 'netCDF4', 'lxml', 'pyproj', 'pytz', 'networkx', 'UTide', 'pandas', 'cmocean'], classifiers = [] )
Use UnixDocket in OkHttp as well
package com.github.dockerjava.okhttp; import com.github.dockerjava.transport.UnixSocket; import javax.net.SocketFactory; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; class UnixSocketFactory extends SocketFactory { private final String socketPath; UnixSocketFactory(String socketPath) { this.socketPath = socketPath; } @Override public Socket createSocket() { try { return UnixSocket.get(socketPath); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Socket createSocket(String s, int i) { throw new UnsupportedOperationException(); } @Override public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) { throw new UnsupportedOperationException(); } @Override public Socket createSocket(InetAddress inetAddress, int i) { throw new UnsupportedOperationException(); } @Override public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) { throw new UnsupportedOperationException(); } }
package com.github.dockerjava.okhttp; import com.github.dockerjava.transport.DomainSocket; import javax.net.SocketFactory; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; class UnixSocketFactory extends SocketFactory { private final String socketPath; UnixSocketFactory(String socketPath) { this.socketPath = socketPath; } @Override public Socket createSocket() { try { return DomainSocket.get(socketPath); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Socket createSocket(String s, int i) { throw new UnsupportedOperationException(); } @Override public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) { throw new UnsupportedOperationException(); } @Override public Socket createSocket(InetAddress inetAddress, int i) { throw new UnsupportedOperationException(); } @Override public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) { throw new UnsupportedOperationException(); } }
Add a lasting effect to each eligible card
const DrawCard = require('../../drawcard.js'); class YoungHarrier extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Prevent other characters from being dishonored', cost: ability.costs.dishonorSelf(), handler: () => { this.game.addMessage('{0} dishonors {1} to prevent Crane characters from being dishonored this phase', this.controller, this); this.controller.cardsInPlay.each(card => { if(card.isFaction('crane')) { this.untilEndOfPhase(ability => ({ match: card, effect: ability.effects.cannotBeDishonored() })); } }); } }); } } YoungHarrier.id = 'young-harrier'; module.exports = YoungHarrier;
const DrawCard = require('../../drawcard.js'); class YoungHarrier extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Prevent other characters from being dishonored', cost: ability.costs.dishonorSelf(), handler: () => { this.game.addMessage('{0} dishonors {1} to prevent Crane characters from being dishonored this phase', this.controller, this); this.untilEndOfPhase(ability => ({ match: card => card.factions['crane'] >= 0 && card.controller === this.controller && card.getType() === 'character', effect: ability.effects.cannotBecomeDishonored() })); } }); } } YoungHarrier.id = 'young-harrier'; module.exports = YoungHarrier;
Fix broken syntax highlighting regexes
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . $(function() { var parser = function(text) { text = text.replace(/^([^\(]*)+/, '<span class="mixin-name">$1</span>'); text = text.replace(/(:\s*)([^,\)]+)/g, '$1<span class="default-value">$2</span>'); text = text.replace(/([^>]\$([^:,\) ]+))/g, '<span class="variable-name">$1</span>'); return text; }; $(".table-mixins td.file > a").each(function() { var $this = $(this); $this.html(parser($this.html())); }); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . $(function() { var parser = function(text) { text = text.replace(/^([^\(]*)+/, '<span class="mixin-name">$1</span>'); text = text.replace(/\$([^:,\) ]+)/g, '<span class="variable-name">$1</span>'); text = text.replace(/(:\s*)([^,\)]+)/g, '$1<span class="default-value">$2</span>'); return text; }; $(".table-mixins td.file > a").each(function() { var $this = $(this); $this.html(parser($this.html())); }); });
Update example service to follow up with the docs
<?php namespace App\Theme\Setup; /* |----------------------------------------------------------- | Theme Custom Services |----------------------------------------------------------- | | This file is for registering your third-parity services | or custom logic within theme container, so they can | be easily used for a theme template files later. | */ use function App\Theme\theme; use Tonik\Gin\Foundation\Theme; /** * Service handler for retrieving posts of specific post type. * * @return void */ function bind_books_service() { /** * Binds service for retrieving posts of specific post type. * * @param \Tonik\Gin\Foundation\Theme $theme Instance of the service container * @param array $parameters Parameters passed on service resolving * * @return \WP_Post[] */ theme()->bind('books', function (Theme $theme, $parameters) { return new WP_Query([ 'post_type' => 'book', ]); }); } add_action('init', 'App\Theme\Setup\bind_books_service');
<?php namespace App\Theme\Setup; /* |----------------------------------------------------------- | Theme Custom Services |----------------------------------------------------------- | | This file is for registering your third-parity services | or custom logic within theme container, so they can | be easily used for a theme template files later. | */ use function App\Theme\theme; use Tonik\Gin\Foundation\Theme; /** * Binding handler for book's genres service. * * @return void */ function bind_books_genres_service() { /** * Binds service for retrieving genres of the specific book. * * @param \Tonik\Gin\Foundation\Theme $theme Instance of the service container * @param array $parameters Parameters passed on service resolving * * @return \WP_term[] */ theme()->bind('book/genres', function (Theme $theme, $parameters) { return wp_get_post_terms($parameters['id'], 'book_grene'); }); } add_action('init', 'App\Theme\Setup\bind_books_genres_service');
Increment minor version to 2.14 to prepare for a new release. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=156319538
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 14; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 13; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
Add target blank for footer links
import React, { Component } from 'react'; class Footer extends Component { render() { if (this.props.data) { var networks = this.props.data.social.map(function (network) { return ( <span key={network.name} className="m-4"> <a href={network.url} target="_blank" rel="noopener noreferrer"> <i className={network.class}></i> </a> </span> ); }); } return ( <footer> <div className="col-md-12"> <div className="social-links">{networks}</div> <div className="copyright py-4 text-center"> <div className="container"> <small>Copyright &copy; Davina Griss</small> </div> </div> </div> </footer> ); } } export default Footer;
import React, { Component } from 'react'; class Footer extends Component { render() { if (this.props.data) { var networks = this.props.data.social.map(function (network) { return ( <span key={network.name} className="m-4"> <a href={network.url}> <i className={network.class}></i> </a> </span> ); }); } return ( <footer> <div className="col-md-12"> <div className="social-links">{networks}</div> <div className="copyright py-4 text-center"> <div className="container"> <small>Copyright &copy; Davina Griss</small> </div> </div> </div> </footer> ); } } export default Footer;
Add version check for notebook path
//---------------------------------------------------------------------------- // Copyright (C) 2012 The IPython Development Team // // Distributed under the terms of the BSD License. The full license is in // the file COPYING, distributed as part of this software. //---------------------------------------------------------------------------- // convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab "using strict"; nbconvertPrintView = function(){ var kernel = IPython.notebook.kernel; var name = IPython.notebook.notebook_name; if (IPython.version[0] == "2") { var path = IPython.notebook.notebookPath(); if (path.length > 0) { path = path.concat('/'); } } else { var path = ""; } var command = 'import os; os.system(\"ipython nbconvert --to html ' + name + '\")'; function callback(out_type, out_data) { var url = '/files/' + path + name.split('.ipynb')[0] + '.html'; var win=window.open(url, '_blank'); win.focus(); } kernel.execute(command, { shell: { reply : callback } }); }; IPython.toolbar.add_buttons_group([ { id : 'doPrintView', label : 'Create static print view', icon : 'icon-print', callback : nbconvertPrintView } ]);
//---------------------------------------------------------------------------- // Copyright (C) 2012 The IPython Development Team // // Distributed under the terms of the BSD License. The full license is in // the file COPYING, distributed as part of this software. //---------------------------------------------------------------------------- // convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab "using strict"; nbconvertPrintView = function(){ var kernel = IPython.notebook.kernel; var name = IPython.notebook.notebook_name; var path = IPython.notebook.notebookPath(); if (path.length > 0) { path = path.concat('/'); } var command = 'import os; os.system(\"ipython nbconvert --to html ' + name + '\")'; function callback(out_type, out_data) { console.log('out:', out_data); var url = '/files/' + path + name.split('.ipynb')[0] + '.html'; var win=window.open(url, '_blank'); win.focus(); } kernel.execute(command, { shell: { reply : callback } }); }; IPython.toolbar.add_buttons_group([ { id : 'doPrintView', label : 'Create static print view', icon : 'icon-print', callback : nbconvertPrintView } ]);
Replace UseDiego config with Backend. [#106033010] Signed-off-by: Natalie J. Bennett <e5fc036b158c983344048075b2b1e5c6083fede5@pivotal.io>
package app_helpers import ( "strings" "time" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" "github.com/cloudfoundry-incubator/cf-test-helpers/helpers" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" ) func guidForAppName(appName string) string { cfApp := cf.Cf("app", appName, "--guid") Expect(cfApp.Wait()).To(Exit(0)) appGuid := strings.TrimSpace(string(cfApp.Out.Contents())) Expect(appGuid).NotTo(Equal("")) return appGuid } func ConditionallyEnableDiego(appName string) { config := helpers.LoadConfig() if config.Backend == "diego" { guid := guidForAppName(appName) Eventually(cf.Cf("curl", "/v2/apps/"+guid, "-X", "PUT", "-d", `{"diego": true}`)).Should(Exit(0)) } else if config.Backend == "dea" { guid := guidForAppName(appName) Eventually(cf.Cf("curl", "/v2/apps/"+guid, "-X", "PUT", "-d", `{"diego": false}`)).Should(Exit(0)) } } func AppReport(appName string, timeout time.Duration) { Eventually(cf.Cf("app", appName, "--guid"), timeout).Should(Exit()) Eventually(cf.Cf("logs", appName, "--recent"), timeout).Should(Exit()) }
package app_helpers import ( "strings" "time" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" "github.com/cloudfoundry-incubator/cf-test-helpers/helpers" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" ) func guidForAppName(appName string) string { cfApp := cf.Cf("app", appName, "--guid") Expect(cfApp.Wait()).To(Exit(0)) appGuid := strings.TrimSpace(string(cfApp.Out.Contents())) Expect(appGuid).NotTo(Equal("")) return appGuid } func ConditionallyEnableDiego(appName string) { config := helpers.LoadConfig() if config.UseDiego { guid := guidForAppName(appName) Eventually(cf.Cf("curl", "/v2/apps/"+guid, "-X", "PUT", "-d", `{"diego": true}`)).Should(Exit(0)) } } func AppReport(appName string, timeout time.Duration) { Eventually(cf.Cf("app", appName, "--guid"), timeout).Should(Exit()) Eventually(cf.Cf("logs", appName, "--recent"), timeout).Should(Exit()) }
Return empty ID instead of null
/* * This file is part of libbluray * Copyright (C) 2012 libbluray * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ package com.aacsla.bluray.online; import org.videolan.Libbluray; import org.videolan.Logger; public class DeviceAttribute { public DeviceAttribute() { } public byte[] getDeviceBindingID() { byte bid[] = Libbluray.getAacsData(Libbluray.AACS_DEVICE_BINDING_ID); if (bid == null) { Logger.getLogger(DeviceAttribute.class.getName()).warning("getDeviceBindingID() failed"); return new byte[16]; } return bid; } }
/* * This file is part of libbluray * Copyright (C) 2012 libbluray * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ package com.aacsla.bluray.online; import org.videolan.Libbluray; import org.videolan.Logger; public class DeviceAttribute { public DeviceAttribute() { } public byte[] getDeviceBindingID() { byte bid[] = Libbluray.getAacsData(Libbluray.AACS_DEVICE_BINDING_ID); if (bid == null) { Logger.getLogger(DeviceAttribute.class.getName()).warning("getDeviceBindingID() failed"); } return bid; } }
Remove cache bust, except for debug
// For any third party dependencies, like jQuery, place them in the lib folder. // Configure loading modules from the lib directory, // except for 'app' ones, which are in a sibling // directory. requirejs.config({ // enforceDefine: true, baseUrl: 'scripts/lib', paths: { jquery: 'https://code.jquery.com/jquery-3.2.1.slim.min', lodash: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min', seedRandom: 'https://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.3/seedrandom.min', threejs: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min', dobuki: 'https://jacklehamster.github.io/dok/out/dok.min', jsgif: 'jsgif/gif' }, urlArgs: (location.search.match(/\bdebug\b/g)) ? "bust=" + Date.now() : '', }); define(function() { // Start loading the main app file. Put all of // your application logic in there. requirejs(['scripts/main.js']); });
// For any third party dependencies, like jQuery, place them in the lib folder. // Configure loading modules from the lib directory, // except for 'app' ones, which are in a sibling // directory. requirejs.config({ // enforceDefine: true, baseUrl: 'scripts/lib', paths: { jquery: 'https://code.jquery.com/jquery-3.2.1.slim.min', lodash: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min', seedRandom: 'https://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.3/seedrandom.min', threejs: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min', dobuki: 'https://jacklehamster.github.io/dok/out/dok.min', jsgif: 'jsgif/gif' }, urlArgs: "bust=" + Date.now(), catchError:false, }); define(function() { // Start loading the main app file. Put all of // your application logic in there. requirejs(['scripts/main.js']); });
Verify waitFor does not reschedule the check after timing out
const sleep = require('./sleep') const waitFor = require('./waitFor') describe('Utils > waitFor', () => { it('waits for the condition', async () => { let conditionValid = false setTimeout(() => { conditionValid = true }, 6) await expect(waitFor(() => conditionValid, { delay: 5 })) }) it('rejects the promise if the callback fail', async () => { await expect( waitFor( () => { throw new Error('callback failed!') }, { delay: 1 } ) ).rejects.toHaveProperty('message', 'callback failed!') }) it('rejects the promise if the callback never succeeds', async () => { const condition = jest.fn().mockReturnValue(false) await expect(waitFor(condition, { delay: 1, maxWait: 2 })).rejects.toHaveProperty( 'message', 'Timeout' ) // Verify that the check is not rescheduled after a timeout await sleep(10) expect(condition).toHaveBeenCalledTimes(2) }) it('rejects the promise with a custom timeout message', async () => { await expect( waitFor(() => false, { delay: 1, maxWait: 2, timeoutMessage: 'foo bar' }) ).rejects.toHaveProperty('message', 'foo bar') }) })
const waitFor = require('./waitFor') describe('Utils > waitFor', () => { it('waits for the condition', async () => { let conditionValid = false setTimeout(() => { conditionValid = true }, 6) await expect(waitFor(() => conditionValid, { delay: 5 })) }) it('rejects the promise if the callback fail', async () => { await expect( waitFor( () => { throw new Error('callback failed!') }, { delay: 1 } ) ).rejects.toHaveProperty('message', 'callback failed!') }) it('rejects the promise if the callback never succeeds', async () => { await expect(waitFor(() => false, { delay: 1, maxWait: 2 })).rejects.toHaveProperty( 'message', 'Timeout' ) }) it('rejects the promise with a custom timeout message', async () => { await expect( waitFor(() => false, { delay: 1, maxWait: 2, timeoutMessage: 'foo bar' }) ).rejects.toHaveProperty('message', 'foo bar') }) })
Add period at end of plug-in description This is consistent with other plug-in descriptions. Contributes to issue CURA-1190.
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view."), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view"), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
Convert readme since pypi doesnt support markdown
import setuptools try: import pypandoc LONG_DESC = pypandoc.convert("README.md", "rst") except(IOError, ImportError, RuntimeError): LONG_DESC = open('README.md').read() setuptools.setup( name="tvtid", version="0.1.6", author="Christian Kirkegaard", author_email="christian@lowpoly.dk", description="Library and cli tool for querying tvtid.dk", long_description=LONG_DESC, license="MIT", url="https://github.com/kirkegaard/tvtid.py", download_url="https://github.com/kirkegaard/tvtid.py", install_requires=[ 'python-dateutil', 'fuzzywuzzy[speedup]', 'requests', 'requests_cache' ], classifiers=[ "Environment :: X11 Applications", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], py_modules=["tvtid"], entry_points={ "console_scripts": [ "tvtid=tvtid:main" ] }, python_requires=">=3.5", include_package_data=True )
import setuptools try: import pypandoc LONG_DESC = pypandoc.convert("README.md", "rst") except(IOError, ImportError, RuntimeError): LONG_DESC = open('README.md').read() setuptools.setup( name="tvtid", version="0.1.5", author="Christian Kirkegaard", author_email="christian@lowpoly.dk", description="Library and cli tool for querying tvtid.dk", long_description=LONG_DESC, license="MIT", url="https://github.com/kirkegaard/tvtid.py", download_url="https://github.com/kirkegaard/tvtid.py", install_requires=[ 'python-dateutil', 'fuzzywuzzy[speedup]', 'requests', 'requests_cache' ], classifiers=[ "Environment :: X11 Applications", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], py_modules=["tvtid"], entry_points={ "console_scripts": [ "tvtid=tvtid:main" ] }, python_requires=">=3.5", include_package_data=True )
Remove logging to stdout when performing tests During tests it logs to /dev/null in order to avoid bottleneck Change-Id: I4fd54cf1f2c572b9750d63450da67ef06101a8d8
# -*- encoding: utf-8 -*- # # Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import uuid DEBUG = False LOG_FILE = '/dev/null' SQLALCHEMY_DATABASE_URI = "postgresql:///%s?host=%s" % ( uuid.uuid4(), os.path.abspath(os.environ['DCI_DB_DIR']) ) # detect if we are using docker_compose if os.environ.get('DB_PORT'): import dci.server.settings SQLALCHEMY_DATABASE_URI = dci.server.settings.SQLALCHEMY_DATABASE_URI SQLALCHEMY_DATABASE_URI += "_test"
# -*- encoding: utf-8 -*- # # Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import uuid SQLALCHEMY_DATABASE_URI = "postgresql:///%s?host=%s" % ( uuid.uuid4(), os.path.abspath(os.environ['DCI_DB_DIR']) ) # detect if we are using docker_compose if os.environ.get('DB_PORT'): import dci.server.settings SQLALCHEMY_DATABASE_URI = dci.server.settings.SQLALCHEMY_DATABASE_URI SQLALCHEMY_DATABASE_URI += "_test"
Declare ractive debug flag to false
import { getByLabelText, getByText, getByTestId, queryByTestId, wait, getQueriesForElement, fireEvent } from '@testing-library/dom'; import '@testing-library/jest-dom/extend-expect'; import Ractive from 'ractive'; Ractive.DEBUG = false; Ractive.components.counter = Ractive.extend({ template: ` <div> <button on-click="@this.add('count')"> {{count}} </button> </div> `, data: function(){ return { count: 0 } } }); function render(Component) { const div = document.createElement('div'); div.id = 'app'; const r = new Ractive({ target: div, template: ` <div> <counter /> </div> ` }); return div; } // tests: test('counter increments', () => { const div = render(); const { getByText } = getQueriesForElement(div); const counter = getByText('0'); fireEvent.click(counter); expect(counter).toHaveTextContent('1'); fireEvent.click(counter) expect(counter).toHaveTextContent('2'); });
import { getByLabelText, getByText, getByTestId, queryByTestId, wait, getQueriesForElement, fireEvent } from '@testing-library/dom'; import '@testing-library/jest-dom/extend-expect'; import Ractive from 'ractive'; Ractive.components.counter = Ractive.extend({ template: ` <div> <button on-click="@this.add('count')"> {{count}} </button> </div> `, data: function(){ return { count: 0 } } }); function render(Component) { const div = document.createElement('div'); div.id = 'app'; const r = new Ractive({ target: div, template: ` <div> <counter /> </div> ` }); return div; } // tests: test('counter increments', () => { const div = render(); const { getByText } = getQueriesForElement(div); const counter = getByText('0'); fireEvent.click(counter); expect(counter).toHaveTextContent('1'); fireEvent.click(counter) expect(counter).toHaveTextContent('2'); });
Make message field as required
'use strict'; var mongoose = require('mongoose'); const WAITING_FOR_PRINT = 'WAITING_FOR_PRINT'; const PRINTED_WAITING_FOR_SEND = 'PRINTED_WAITING_FOR_SEND'; const SENT = 'SENT'; var statusKeys = [ WAITING_FOR_PRINT, PRINTED_WAITING_FOR_SEND, SENT ]; var cardSchema = mongoose.Schema({ message: { type: String, required: true }, senderAddress: { type: String, required: true }, receiverAddress: { type: String, required: true }, createdOn: { type: Date, default: Date.now }, statusKey: { type: String, enum: statusKeys, default: WAITING_FOR_PRINT, required: true } }); var Card = mongoose.model('Card', cardSchema); module.exports = Card;
'use strict'; var mongoose = require('mongoose'); const WAITING_FOR_PRINT = 'WAITING_FOR_PRINT'; const PRINTED_WAITING_FOR_SEND = 'PRINTED_WAITING_FOR_SEND'; const SENT = 'SENT'; var statusKeys = [ WAITING_FOR_PRINT, PRINTED_WAITING_FOR_SEND, SENT ]; var cardSchema = mongoose.Schema({ message: String, senderAddress: { type:String, required: true }, receiverAddress: { type:String, required: true }, createdOn: { type: Date, default: Date.now }, statusKey: { type: String, enum: statusKeys, default: WAITING_FOR_PRINT, required: true } }); var Card = mongoose.model('Card', cardSchema); module.exports = Card;
Make this slightly less as simple as possible
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\Metadata; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class AnnotationReader implements Reader { /** * @psalm-param class-string $className */ public function forClass(string $className): MetadataCollection { $result = []; return MetadataCollection::fromArray($result); } /** * @psalm-param class-string $className */ public function forMethod(string $className, string $methodName): MetadataCollection { $result = []; return MetadataCollection::fromArray($result); } }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\Metadata; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class AnnotationReader implements Reader { /** * @psalm-param class-string $className */ public function forClass(string $className): MetadataCollection { return MetadataCollection::fromArray([]); } /** * @psalm-param class-string $className */ public function forMethod(string $className, string $methodName): MetadataCollection { return MetadataCollection::fromArray([]); } }
Print a newline after an error message
package main import ( "fmt" "os" "github.com/spf13/cobra" "github.com/squaremo/flux/common/store" "github.com/squaremo/flux/common/store/etcdstore" ) func main() { store := etcdstore.NewFromEnv() var topCmd = &cobra.Command{ Use: "fluxctl", Short: "control flux", Long: `Define services and enrol instances in them`, } addSubCommands(topCmd, store) if err := topCmd.Execute(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func addSubCommand(c commandOpts, cmd *cobra.Command, st store.Store) { c.setStore(st) cmd.AddCommand(c.makeCommand()) } func addSubCommands(cmd *cobra.Command, store store.Store) { addSubCommand(&addOpts{}, cmd, store) addSubCommand(&listOpts{}, cmd, store) addSubCommand(&queryOpts{}, cmd, store) addSubCommand(&rmOpts{}, cmd, store) addSubCommand(&selectOpts{}, cmd, store) addSubCommand(&deselectOpts{}, cmd, store) }
package main import ( "fmt" "os" "github.com/spf13/cobra" "github.com/squaremo/flux/common/store" "github.com/squaremo/flux/common/store/etcdstore" ) func main() { store := etcdstore.NewFromEnv() var topCmd = &cobra.Command{ Use: "fluxctl", Short: "control flux", Long: `Define services and enrol instances in them`, } addSubCommands(topCmd, store) if err := topCmd.Execute(); err != nil { exitWithErrorf(err.Error()) } } func addSubCommand(c commandOpts, cmd *cobra.Command, st store.Store) { c.setStore(st) cmd.AddCommand(c.makeCommand()) } func addSubCommands(cmd *cobra.Command, store store.Store) { addSubCommand(&addOpts{}, cmd, store) addSubCommand(&listOpts{}, cmd, store) addSubCommand(&queryOpts{}, cmd, store) addSubCommand(&rmOpts{}, cmd, store) addSubCommand(&selectOpts{}, cmd, store) addSubCommand(&deselectOpts{}, cmd, store) } func exitWithErrorf(format string, vals ...interface{}) { fmt.Fprintf(os.Stderr, format, vals...) os.Exit(1) }
[FIX] Fix registration text in the wrong position
import React from 'react'; import '../../scss/_hero.scss'; class Home extends React.Component { render() { return ( <main className='hero' style={{height: '200%', width: '100%'}}> <div className='hero image' style={{height: '200%', width: '100%'}}></div> <div className='title text padding'> The Amazing G<span className='em'>Race</span> </div> <div className='date text padding'> 7th December, 2017 </div> <div className='registration text padding'> Registration opens <br/> <span className='em'>Monday 18th September, 2017</span> </div> </main> ); } } export default Home;
import React from 'react'; import '../../scss/_hero.scss'; class Home extends React.Component { render() { return ( <main className='hero' style={{height: '200%', width: '100%'}}> <div className='hero image' style={{height: '200%', width: '100%'}}></div> <div className='title text padding'> The Amazing G<span className='em'>Race</span> </div> <div className='date text padding'> 7th December, 2017 </div> Registration opens <div className='registration text padding'> <br/> <span className='em'>Monday 18th September, 2017</span> </div> </main> ); } } export default Home;
Use single var for requires
var gulp = require('gulp'), config = require('../config'), plumber = require('gulp-plumber'), jscs = require('gulp-jscs'), jshint = require('gulp-jshint'), stylish = require('jshint-stylish'), handleError = require('../util/handle-errors'); gulp.task('jshint', function() { var allJavascript = Array.prototype.concat(config.source, config.gulp, config.tests); return gulp.src(allJavascript) .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter(stylish)) .on('error', handleError); }); gulp.task('jscs', function () { var allJavascript = Array.prototype.concat(config.source, config.gulp, config.tests); return gulp.src(allJavascript) .pipe(plumber()) .pipe(jscs()) .on('error', handleError); }); gulp.task('lint', ['jshint', 'jscs']);
var gulp = require('gulp'); var config = require('../config'); var plumber = require('gulp-plumber'); var jscs = require('gulp-jscs'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); var handleError = require('../util/handle-errors'); gulp.task('jshint', function() { var allJavascript = Array.prototype.concat(config.source, config.gulp, config.tests); return gulp.src(allJavascript) .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter(stylish)) .on('error', handleError); }); gulp.task('jscs', function () { var allJavascript = Array.prototype.concat(config.source, config.gulp, config.tests); return gulp.src(allJavascript) .pipe(plumber()) .pipe(jscs()) .on('error', handleError); }); gulp.task('lint', ['jshint', 'jscs']);
Remove box geometry offset arguments.
'use strict'; module.exports = function addBoxGeometry( geometry, width, height, depth ) { var halfWidth = width / 2; var halfHeight = height / 2; var halfDepth = depth / 2; var vertices = [ // Counterclockwise from far left. // Bottom. -halfWidth, -halfHeight, -halfDepth, -halfWidth, -halfHeight, halfDepth, halfWidth, -halfHeight, halfDepth, halfWidth, -halfHeight, -halfDepth, // Top. -halfWidth, halfHeight, -halfDepth, -halfWidth, halfHeight, halfDepth, halfWidth, halfHeight, halfDepth, halfWidth, halfHeight, -halfDepth ]; var faces = [ // Sides. [ 0, 1, 5, 4 ], [ 1, 2, 6, 5 ], [ 2, 3, 7, 6 ], [ 3, 0, 4, 7 ], // Top. [ 4, 5, 6, 7 ], // Bottom. [ 0, 3, 2, 1 ] ]; return geometry.push( vertices, faces ); };
'use strict'; module.exports = function addBoxGeometry( geometry, width, height, depth, dx, dy, dz ) { dx = dx || 0; dy = dy || 0; dz = dz || 0; var halfWidth = width / 2; var halfHeight = height / 2; var halfDepth = depth / 2; var vertices = [ // Counterclockwise from far left. // Bottom. -halfWidth, -halfHeight, -halfDepth, -halfWidth, -halfHeight, halfDepth, halfWidth, -halfHeight, halfDepth, halfWidth, -halfHeight, -halfDepth, // Top. -halfWidth, halfHeight, -halfDepth, -halfWidth, halfHeight, halfDepth, halfWidth, halfHeight, halfDepth, halfWidth, halfHeight, -halfDepth ]; for ( var i = 0; i < vertices.length; i += 3 ) { vertices[ i ] += dx; vertices[ i + 1 ] += dy; vertices[ i + 2 ] += dz; } var faces = [ // Sides. [ 0, 1, 5, 4 ], [ 1, 2, 6, 5 ], [ 2, 3, 7, 6 ], [ 3, 0, 4, 7 ], // Top. [ 4, 5, 6, 7 ], // Bottom. [ 0, 3, 2, 1 ] ]; return geometry.push( vertices, faces ); };
Fix no response due to newlines
'use strict'; var net = require('net'); module.exports = { get: get }; function get(opts, text, callback) { var socket = new net.Socket(); socket.connect(opts.port, opts.host, function () { socket.setNoDelay(true); socket.write(text.replace(/\r?\n|\r|\t/g, ' ') + '\n'); }); socket.on('data', function (data) { var re = /<([A-Z]+?)>(.+?)<\/\1>/g; var str = data.toString(); var res = {}; res.raw = str; var m; var entities = { LOCATION: [], ORGANIZATION: [], DATE: [], MONEY: [], PERSON: [], PERCENT: [], TIME: [] }; var _parsed = []; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } _parsed.push(m); entities[m[1]].push(m[2]); } res._parsed = _parsed; res.entities = entities; socket.destroy(); callback(undefined, res); }); socket.on('error', function (err) { callback(err, undefined); }); }
'use strict'; var net = require('net'); module.exports = { get: get }; function get(opts, text, callback) { var socket = new net.Socket(); socket.connect(opts.port, opts.host, function () { socket.setNoDelay(true); socket.write(text + '\n'); }); socket.on('data', function (data) { var re = /<([A-Z]+?)>(.+?)<\/\1>/g; var str = data.toString(); var res = {}; res.raw = str; var m; var entities = { LOCATION: [], ORGANIZATION: [], DATE: [], MONEY: [], PERSON: [], PERCENT: [], TIME: [] }; var _parsed = []; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } _parsed.push(m); entities[m[1]].push(m[2]); } res._parsed = _parsed; res.entities = entities; socket.destroy(); callback(undefined, res); }); socket.on('error', function (err) { callback(err, undefined); }); }
Use view() instead of $view Fixes "Method [share] does not exist on view." exception.
<?php namespace App\Http\ViewComposers; use Creativeorange\Gravatar\Facades\Gravatar; class AuthComposer { /** * Bind data to the view. * * @return void */ public function compose() { view()->share('isGuest', auth()->guest()); view()->share('signedIn', auth()->check()); view()->share('user', auth()->user()); if (auth()->user()) { view()->share('gravatarURL', Gravatar::get(auth()->user()->email, ['size' => 24, 'secure' => true])); view()->share('appointments', auth()->user()->appointments()->active()->get()); } else { view()->share('gravatarURL', 'http://placehold.it/150x150'); view()->share('appointments', []); } } }
<?php namespace App\Http\ViewComposers; use Creativeorange\Gravatar\Facades\Gravatar; use Illuminate\View\View; class AuthComposer { /** * Bind data to the view. * * @param View $view * * @return void */ public function compose(View $view) { $view->share('isGuest', auth()->guest()); $view->share('signedIn', auth()->check()); $view->share('user', auth()->user()); if (auth()->user()) { $view->share('gravatarURL', Gravatar::get(auth()->user()->email, ['size' => 24, 'secure' => true])); $view->share('appointments', auth()->user()->appointments()->active()->get()); } else { $view->share('gravatarURL', 'http://placehold.it/150x150'); $view->share('appointments', []); } } }
Set click listener to button and show name in a toast
package com.smartdragons.interactivestory; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText mNameField; private Button mStartButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNameField = (EditText) findViewById(R.id.nameEditText); mStartButton = (Button) findViewById(R.id.startButton); mStartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = mNameField.getText().toString(); Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show(); } }); } }
package com.smartdragons.interactivestory; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Use path given as argument
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import glob import re import os import sys import numpy as np import matplotlib.pyplot as plt if len(sys.argv) == 1: print('Usage: plot.py path/to/build/profiling') sys.exit(0) csv_files = glob.glob(os.path.join(sys.argv[1], '*.csv')) fig = plt.figure() ax = fig.add_subplot(111) colors = iter(plt.cm.rainbow(np.linspace(0,1,len(csv_files)))) p = re.compile(r'profiling_(.*?)_(.*?)\.csv') ms_to_s = 1.0 / 1000.0 for csv_file in csv_files: data = np.genfromtxt(csv_file, delimiter=',', skip_header=1).transpose() j = data[0] N = data[1] avg = data[2] std = data[3] m = p.search(csv_file) name = m.group(2) name = name.replace('_', ' ') ax.errorbar(N, avg*ms_to_s, yerr=std*ms_to_s, label=name, color=next(colors), marker='o') ax.grid(True) ax.set_xlabel('N') ax.set_ylabel('Timing [s]') ax.set_xscale('log') ax.set_yscale('log') ax.legend(loc='best') plt.show()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import glob import re import numpy as np import matplotlib.pyplot as plt csv_files = glob.glob('*.csv') fig = plt.figure() ax = fig.add_subplot(111) colors = iter(plt.cm.rainbow(np.linspace(0,1,len(csv_files)))) p = re.compile(r'profiling_(.*?)_(.*?)\.csv') ms_to_s = 1.0 / 1000.0 for csv_file in csv_files: data = np.genfromtxt(csv_file, delimiter=',', skip_header=1).transpose() j = data[0] N = data[1] avg = data[2] std = data[3] m = p.search(csv_file) name = m.group(2) name = name.replace('_', ' ') ax.errorbar(N, avg*ms_to_s, yerr=std*ms_to_s, label=name, color=next(colors), marker='o') ax.grid(True) ax.set_xlabel('N') ax.set_ylabel('Timing [s]') ax.set_xscale('log') ax.set_yscale('log') ax.legend(loc='best') plt.show()
Change Tok to Token for readability.
package syntax import "github.com/ksco/slua/scanner" type SyntaxTree interface{} type ( Chunk struct { Block SyntaxTree } Block struct { Stmts []SyntaxTree } DoStatement struct { Block SyntaxTree } WhileStatement struct { Exp SyntaxTree Block SyntaxTree } IfStatement struct { Exp SyntaxTree TrueBranch SyntaxTree FalseBranch SyntaxTree } ElseifStatement struct { Exp SyntaxTree TrueBranch SyntaxTree FalseBranch SyntaxTree } ElseStatement struct { Block SyntaxTree } LocalNameListStatement struct { NameList SyntaxTree ExpList SyntaxTree } AssignmentStatement struct { VarList SyntaxTree ExpList SyntaxTree } VarList struct { VarList []SyntaxTree } Terminator struct { Token *scanner.Token } BinaryExpression struct { Left SyntaxTree Right SyntaxTree OpToken *scanner.Token } UnaryExpression struct { Exp SyntaxTree OpToken *scanner.Token } NameList struct { Names []*scanner.Token } ExpressionList struct { ExpList []SyntaxTree } )
package syntax import "github.com/ksco/slua/scanner" type SyntaxTree interface{} type ( Chunk struct { Block SyntaxTree } Block struct { Stmts []SyntaxTree } DoStatement struct { Block SyntaxTree } WhileStatement struct { Exp SyntaxTree Block SyntaxTree } IfStatement struct { Exp SyntaxTree TrueBranch SyntaxTree FalseBranch SyntaxTree } ElseifStatement struct { Exp SyntaxTree TrueBranch SyntaxTree FalseBranch SyntaxTree } ElseStatement struct { Block SyntaxTree } LocalNameListStatement struct { NameList SyntaxTree ExpList SyntaxTree } AssignmentStatement struct { VarList SyntaxTree ExpList SyntaxTree } VarList struct { VarList []SyntaxTree } Terminator struct { Tok *scanner.Token } BinaryExpression struct { Left SyntaxTree Right SyntaxTree OpToken *scanner.Token } UnaryExpression struct { Exp SyntaxTree OpToken *scanner.Token } NameList struct { Names []*scanner.Token } ExpressionList struct { ExpList []SyntaxTree } )
Make address not required on OrganizationSerializer
from django.core.exceptions import ValidationError from ovp_core import validators as core_validators from ovp_core.serializers import GoogleAddressSerializer, GoogleAddressCityStateSerializer from ovp_organizations import models from rest_framework import serializers from rest_framework import permissions class OrganizationCreateSerializer(serializers.ModelSerializer): address = GoogleAddressSerializer( validators=[core_validators.address_validate], required=False, ) class Meta: model = models.Organization fields = ['id', 'owner', 'name', 'website', 'facebook_page', 'address', 'details', 'description', 'type'] def create(self, validated_data): # Address address_data = validated_data.pop('address', None) if address_data: address_sr = GoogleAddressSerializer(data=address_data) address = address_sr.create(address_data) validated_data['address'] = address # Organization organization = models.Organization.objects.create(**validated_data) return organization #class NonprofitUpdateSerializer(NonprofitCreateSerializer): # class Meta: # model = models.Nonprofit # permission_classes = (permissions.IsAuthenticated,) # fields = ['name', 'image', 'cover', 'details', 'description', 'websitefacebook_page', 'google_page', 'twitter_handle'] class OrganizationSearchSerializer(serializers.ModelSerializer): address = GoogleAddressCityStateSerializer() class Meta: model = models.Organization fields = ['id', 'owner', 'name', 'website', 'facebook_page', 'address', 'details', 'description', 'type']
from django.core.exceptions import ValidationError from ovp_core import validators as core_validators from ovp_core.serializers import GoogleAddressSerializer, GoogleAddressCityStateSerializer from ovp_organizations import models from rest_framework import serializers from rest_framework import permissions class OrganizationCreateSerializer(serializers.ModelSerializer): address = GoogleAddressSerializer( validators=[core_validators.address_validate] ) class Meta: model = models.Organization fields = ['id', 'owner', 'name', 'website', 'facebook_page', 'address', 'details', 'description', 'type'] def create(self, validated_data): # Address address_data = validated_data.pop('address', {}) address_sr = GoogleAddressSerializer(data=address_data) address = address_sr.create(address_data) validated_data['address'] = address # Organization organization = models.Organization.objects.create(**validated_data) return organization #class NonprofitUpdateSerializer(NonprofitCreateSerializer): # class Meta: # model = models.Nonprofit # permission_classes = (permissions.IsAuthenticated,) # fields = ['name', 'image', 'cover', 'details', 'description', 'websitefacebook_page', 'google_page', 'twitter_handle'] class OrganizationSearchSerializer(serializers.ModelSerializer): address = GoogleAddressCityStateSerializer() class Meta: model = models.Organization fields = ['id', 'owner', 'name', 'website', 'facebook_page', 'address', 'details', 'description', 'type']
Use server value from request instead of super global variable
<?php /* * This file is part of the ONGR package. * * (c) NFQ Technologies UAB <info@nfq.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ONGR\SettingsBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\HttpFoundation\Request; /** * Environment variables pass, overrides default variables with environment ones. */ class EnvironmentVariablesPass implements CompilerPassInterface { /** * Finds environment variables prefixed with ongr__ and changes default ones. * * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { $request = Request::createFromGlobals(); foreach ($request->server as $key => $value) { if (0 === strpos($key, 'ongr__')) { $param = strtolower(str_replace('__', '.', substr($key, 6))); $container->setParameter($param, $value); } } } }
<?php /* * This file is part of the ONGR package. * * (c) NFQ Technologies UAB <info@nfq.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ONGR\SettingsBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Environment variables pass, overrides default variables with environment ones. */ class EnvironmentVariablesPass implements CompilerPassInterface { /** * Finds environment variables prefixed with ongr__ and changes default ones. * * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { foreach ($_SERVER as $key => $value) { if (0 === strpos($key, 'ongr__')) { $param = strtolower(str_replace('__', '.', substr($key, 6))); $container->setParameter($param, $value); } } } }
Update logs to talk about IP instead of public IP When logging we don't know whether we use a private or public ip, just the ip itself.
package oci import ( "context" "fmt" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" ) type stepInstanceInfo struct{} func (s *stepInstanceInfo) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { var ( driver = state.Get("driver").(Driver) ui = state.Get("ui").(packer.Ui) id = state.Get("instance_id").(string) ) ip, err := driver.GetInstanceIP(id) if err != nil { err = fmt.Errorf("Error getting instance's IP: %s", err) ui.Error(err.Error()) state.Put("error", err) return multistep.ActionHalt } state.Put("instance_ip", ip) ui.Say(fmt.Sprintf("Instance has IP: %s.", ip)) return multistep.ActionContinue } func (s *stepInstanceInfo) Cleanup(state multistep.StateBag) { // no cleanup }
package oci import ( "context" "fmt" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" ) type stepInstanceInfo struct{} func (s *stepInstanceInfo) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { var ( driver = state.Get("driver").(Driver) ui = state.Get("ui").(packer.Ui) id = state.Get("instance_id").(string) ) ip, err := driver.GetInstanceIP(id) if err != nil { err = fmt.Errorf("Error getting instance's public IP: %s", err) ui.Error(err.Error()) state.Put("error", err) return multistep.ActionHalt } state.Put("instance_ip", ip) ui.Say(fmt.Sprintf("Instance has public IP: %s.", ip)) return multistep.ActionContinue } func (s *stepInstanceInfo) Cleanup(state multistep.StateBag) { // no cleanup }
Use sqlite3 for 'other' database test config
# https://docs.djangoproject.com/en/1.7/internals/contributing/writing-code/unit-tests/#using-another-settings-module DATABASES = { 'default': { 'ENGINE': 'django_fdbsql', 'NAME': 'django_default', 'OPTIONS': { 'supports_sequence_reset': True, 'use_sequence_reset_function': True, }, }, # Nothing adapter specific, only used to confirm multiple DATABASES work. 'other': { 'ENGINE': 'django.db.backends.sqlite3', } } # And also add 'south' to ALWAYS_INSTALLED_APPS in runtests.py SKIP_SOUTH_TESTS = False SOUTH_DATABASE_ADAPTERS = { 'default': 'django_fdbsql.south_fdbsql' } SECRET_KEY = "django_tests_secret_key" PASSWORD_HASHERS = ( # Preferred, faster for tests 'django.contrib.auth.hashers.MD5PasswordHasher', # Required by 1.4.x tests 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', )
DATABASES = { 'default': { 'ENGINE': 'django_fdbsql', 'NAME': 'django_default', 'OPTIONS': { 'supports_sequence_reset': True, 'use_sequence_reset_function': True, }, }, 'other': { 'ENGINE': 'django_fdbsql', 'NAME': 'django_other', } } # And also add 'south' to ALWAYS_INSTALLED_APPS in runtests.py SKIP_SOUTH_TESTS = False SOUTH_DATABASE_ADAPTERS = { 'default': 'django_fdbsql.south_fdbsql' } SECRET_KEY = "django_tests_secret_key" PASSWORD_HASHERS = ( # Preferred, faster for tests 'django.contrib.auth.hashers.MD5PasswordHasher', # Required by 1.4.x tests 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', )
Add ability to generate DAG file via command line
package org.ethereum; import org.ethereum.cli.CLIInterface; import org.ethereum.config.SystemProperties; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.mine.Ethash; import java.io.IOException; import java.net.URISyntaxException; /** * @author Roman Mandeleil * @since 14.11.2014 */ public class Start { public static void main(String args[]) throws IOException, URISyntaxException { CLIInterface.call(args); final SystemProperties config = SystemProperties.getDefault(); final boolean actionBlocksLoader = !config.blocksLoader().equals(""); final boolean actionGenerateDag = config.getConfig().hasPath("ethash.blockNumber"); if (actionBlocksLoader || actionGenerateDag) { config.setSyncEnabled(false); config.setDiscoveryEnabled(false); } Ethereum ethereum = EthereumFactory.createEthereum(); if (actionBlocksLoader) { ethereum.getBlockLoader().loadBlocks(); } else if (actionGenerateDag) { new Ethash(config, config.getConfig().getLong("ethash.blockNumber")).getFullDataset(); // DAG file has been created, lets exit System.exit(0); } } }
package org.ethereum; import org.ethereum.cli.CLIInterface; import org.ethereum.config.SystemProperties; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import java.io.IOException; import java.net.URISyntaxException; /** * @author Roman Mandeleil * @since 14.11.2014 */ public class Start { public static void main(String args[]) throws IOException, URISyntaxException { CLIInterface.call(args); if (!SystemProperties.getDefault().blocksLoader().equals("")) { SystemProperties.getDefault().setSyncEnabled(false); SystemProperties.getDefault().setDiscoveryEnabled(false); } Ethereum ethereum = EthereumFactory.createEthereum(); if (!SystemProperties.getDefault().blocksLoader().equals("")) ethereum.getBlockLoader().loadBlocks(); } }
Update test: Add `ACME_API_BASE_URL` constant
var ACME = require( '..' ) var assert = require( 'assert' ) var nock = require( 'nock' ) var ACME_API_BASE_URL = 'https://api.example.com' suite( 'ACME', function() { var client = new ACME.Client({ baseUrl: ACME_API_BASE_URL, }) test( 'throws an error if baseUrl is not a string', function() { assert.throws( function() { new ACME.Client({ baseUrl: 42 }) }) assert.throws( function() { new ACME.Client({ baseUrl: {} }) }) }) test( '#getDirectory()', function( next ) { var payload = { 'new-authz': ACME_API_BASE_URL + '/acme/new-authz', 'new-cert': ACME_API_BASE_URL + '/acme/new-cert', 'new-reg': ACME_API_BASE_URL + '/acme/new-reg', 'revoke-cert': ACME_API_BASE_URL + '/acme/revoke-cert' } nock( ACME_API_BASE_URL ) .get( '/directory' ) .reply( 200, payload ) client.getDirectory( function( error, data ) { assert.ifError( error ) assert.ok( data ) assert.deepStrictEqual( payload, data ) next() }) }) })
var ACME = require( '..' ) var assert = require( 'assert' ) var nock = require( 'nock' ) suite( 'ACME', function() { var client = new ACME({ baseUrl: 'https://api.example.com', }) test( 'throws an error if baseUrl is not a string', function() { assert.throws( function() { new ACME.Client({ baseUrl: 42 }) }) assert.throws( function() { new ACME.Client({ baseUrl: {} }) }) }) test( '#getDirectory()', function( next ) { var payload = { 'new-authz': 'https://api.example.com/acme/new-authz', 'new-cert': 'https://api.example.com/acme/new-cert', 'new-reg': 'https://api.example.com/acme/new-reg', 'revoke-cert': 'https://api.example.com/acme/revoke-cert' } nock( 'https://api.example.com' ) .get( '/directory' ) .reply( 200, payload ) client.getDirectory( function( error, data ) { assert.ifError( error ) assert.ok( data ) assert.deepStrictEqual( payload, data ) next() }) }) })
Fix empty file names messin stuff up.
from django.conf import settings from django.views.static import serve from django.http import HttpResponse from django.views.decorators.csrf import csrf_view_exempt import json import os from projects.models import Project from projects.tasks import update_docs from projects.utils import get_project_path, find_file @csrf_view_exempt def github_build(request): obj = json.loads(request.POST['payload']) name = obj['repository']['name'] url = obj['repository']['url'] project = Project.objects.get(github_repo=url) update_docs.delay(slug=project.slug) return HttpResponse('Build Started') def serve_docs(request, username, project_slug, filename): proj = Project.objects.get(slug=project_slug, user__username=username) project = proj.slug path = get_project_path(proj) if not filename: filename = "index.html" filename = filename.rstrip('/') doc_base = os.path.join(path, project) for possible_path in ['docs', 'doc']: for pos_build in ['build', '_build', '.build']: if os.path.exists(os.path.join(doc_base, '%s/%s/html' % (possible_path, pos_build))): final_path = os.path.join(doc_base, '%s/%s/html' % (possible_path, pos_build)) return serve(request, filename, final_path)
from django.conf import settings from django.views.static import serve from django.http import HttpResponse from django.views.decorators.csrf import csrf_view_exempt import json import os from projects.models import Project from projects.tasks import update_docs from projects.utils import get_project_path, find_file @csrf_view_exempt def github_build(request): obj = json.loads(request.POST['payload']) name = obj['repository']['name'] url = obj['repository']['url'] project = Project.objects.get(github_repo=url) update_docs.delay(slug=project.slug) return HttpResponse('Build Started') def serve_docs(request, username, project_slug, filename="index.html"): proj = Project.objects.get(slug=project_slug, user__username=username) project = proj.slug path = get_project_path(proj) filename = filename.rstrip('/') doc_base = os.path.join(path, project) for possible_path in ['docs', 'doc']: for pos_build in ['build', '_build', '.build']: if os.path.exists(os.path.join(doc_base, '%s/%s/html' % (possible_path, pos_build))): final_path = os.path.join(doc_base, '%s/%s/html' % (possible_path, pos_build)) return serve(request, filename, final_path)