text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Set pyRiffle version to 0.2.2.
from setuptools import setup, Extension setup( name="pyRiffle", version="0.2.2", description="Riffle client libraries for interacting over a fabric", author="Exis", url="http://www.exis.io", license="MIT", packages=["riffle"], include_package_data=True, install_requires=[ 'docopt>=0.6.2', 'greenlet>=0.4.9', 'PyYAML>=3.11' ], entry_points={ 'console_scripts': [ 'exis = exis:main' ] }, classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules" ] )
from setuptools import setup, Extension setup( name="pyRiffle", version="0.2.1", description="Riffle client libraries for interacting over a fabric", author="Exis", url="http://www.exis.io", license="MIT", packages=["riffle"], include_package_data=True, install_requires=[ 'docopt>=0.6.2', 'greenlet>=0.4.9', 'PyYAML>=3.11' ], entry_points={ 'console_scripts': [ 'exis = exis:main' ] }, classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules" ] )
Fix getting and setting Go env vars during build
package main import ( "os" "path/filepath" ) // goGenerate executes the command "go generate" func goGenerate() { cmd("go", "generate").Run() } // goBuild executes the command "go build" for the desired // target OS and architecture, and writes the generated // executable to the 'outDir' directory. func goBuild(name string, version string, goos string, goarch string) { os.Setenv("GOOS", goos) os.Setenv("GOARCH", goarch) out := distPath(name, version, goos, goarch) cmd("go", "build", "-o", out, "-ldflags", "-X main.version="+version).Run() } // distPath constructs a file path for a given target func distPath(name string, version string, os string, arch string) string { return filepath.Join("dist", buildName(name, version, os, arch), name+exeSuffix()) } // exeSuffix returns ".exe" if the GOOS // environment variable is set to // "windows". func exeSuffix() string { if goOS() == "windows" { return ".exe" } return "" } // goOS returns the value of GOOS func goOS() string { return cmd("go", "env", "GOOS").OutputLine() } // goArch returns the value of GOARCH func goArch() string { return cmd("go", "env", "GOARCH").OutputLine() }
package main import ( "os" "path/filepath" ) // goGenerate executes the command "go generate" func goGenerate() { cmd("go", "generate").Run() } // goBuild executes the command "go build" for the desired // target OS and architecture, and writes the generated // executable to the 'outDir' directory. func goBuild(name string, version string, goos string, goarch string) { os.Setenv("goos", goos) os.Setenv("goarch", goarch) out := distPath(name, version, goos, goarch) cmd("go", "build", "-o", out, "-ldflags", "-X main.version="+version).Run() } // distPath constructs a file path for a given target func distPath(name string, version string, os string, arch string) string { return filepath.Join("dist", buildName(name, version, os, arch), name+exeSuffix()) } // exeSuffix returns ".exe" if the GOOS // environment variable is set to // "windows". func exeSuffix() string { if os.Getenv("GOOS") == "windows" { return ".exe" } return "" } // goOS returns the value of GOOS func goOS() string { return cmd("go", "env", "GOOS").OutputLine() } // goArch returns the value of GOARCH func goArch() string { return cmd("go", "env", "GOARCH").OutputLine() }
Fix error on initial startup
/** * * * @author Knut Kohl <github@knutkohl.de> * @copyright 2012-2014 Knut Kohl * @license MIT License (MIT) http://opensource.org/licenses/MIT * @version 1.0.0 */ var PVLngVersion = '{VERSION}', PVLngAPI = 'http://{SERVERNAME}/api/latest/', PVLngAPIkey = '{APIKEY}', /* Inititilize Pines Notify labels here with I18N */ pnotify_defaults_labels_stick = '{{Stick}}', pnotify_defaults_labels_close = '{{Close}}', DecimalSeparator = '{DSEP}', ThousandSeparator = '{TSEP}', language = '{LANGUAGE}', /* May be empty on 1st start */ latitude = +'{raw:LATITUDE}', longitude = +'{raw:LONGITUDE}', verbose = '{VERBOSE}', user = '{USER}';
/** * * * @author Knut Kohl <github@knutkohl.de> * @copyright 2012-2014 Knut Kohl * @license MIT License (MIT) http://opensource.org/licenses/MIT * @version 1.0.0 */ var PVLngVersion = '{VERSION}', PVLngAPI = 'http://{SERVERNAME}/api/latest/', PVLngAPIkey = '{APIKEY}', /* Inititilize Pines Notify labels here with I18N */ pnotify_defaults_labels_stick = '{{Stick}}', pnotify_defaults_labels_close = '{{Close}}', DecimalSeparator = '{DSEP}', ThousandSeparator = '{TSEP}', language = '{LANGUAGE}', latitude = {raw:LATITUDE}, longitude = {raw:LONGITUDE}, verbose = '{VERBOSE', user = '{USER}';
Make the plugin work when loading the config fails
package org.monospark.actioncontrol.category; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import org.monospark.actioncontrol.config.ConfigParseException; import org.monospark.actioncontrol.config.ConfigParser; import org.spongepowered.api.entity.living.player.Player; public final class CategoryRegistry { private static final String PERMISSION_BASE = "actioncontrol.category."; private Set<Category> allCategories; CategoryRegistry() {} public void loadCategories(Path path) throws ConfigParseException { Path categoriesFile = path.resolve("config.json"); File file = categoriesFile.toFile(); try { if(!file.exists()) { path.toFile().mkdir(); file.createNewFile(); this.allCategories = Collections.emptySet(); } else { this.allCategories = ConfigParser.parseConfig(categoriesFile); } } catch (IOException e) { this.allCategories = Collections.emptySet(); throw new ConfigParseException(e); } } public Set<Category> getCategories(Player p) { return allCategories.stream() .filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true) .collect(Collectors.toSet()); } }
package org.monospark.actioncontrol.category; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import org.monospark.actioncontrol.config.ConfigParseException; import org.monospark.actioncontrol.config.ConfigParser; import org.spongepowered.api.entity.living.player.Player; public final class CategoryRegistry { private static final String PERMISSION_BASE = "actioncontrol.category."; private Set<Category> allCategories; CategoryRegistry() {} public void loadCategories(Path path) throws ConfigParseException { Path categoriesFile = path.resolve("config.json"); File file = categoriesFile.toFile(); try { if(!file.exists()) { path.toFile().mkdir(); file.createNewFile(); this.allCategories = Collections.emptySet(); } else { this.allCategories = ConfigParser.parseConfig(categoriesFile); } } catch (IOException e) { throw new ConfigParseException(e); } } public Set<Category> getCategories(Player p) { return allCategories.stream() .filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true) .collect(Collectors.toSet()); } }
Revert "bump gunicorn max_requests to 600" This reverts commit ffbfe0d6f2ca83346693a788b14562eb332d0cbd.
import multiprocessing preload_app = True workers = multiprocessing.cpu_count() * 2 + 1 worker_class = 'gevent' keepalive = 60 timeout = 900 max_requests = 120 # defaults to 30 sec, setting to 5 minutes to fight `GreenletExit`s graceful_timeout = 5*60 # cryptically, setting forwarded_allow_ips (to the ip of the hqproxy0) # gets gunicorn to set https on redirects when appropriate. See: # http://docs.gunicorn.org/en/latest/configure.html#secure-scheme-headers # http://docs.gunicorn.org/en/latest/configure.html#forwarded-allow-ips forwarded_allow_ips = '10.176.162.109' def post_fork(server, worker): # hacky way to address gunicorn gevent requests hitting django too early before urls are loaded # see: https://github.com/benoitc/gunicorn/issues/527#issuecomment-19601046 from django.core.urlresolvers import resolve resolve('/')
import multiprocessing preload_app = True workers = multiprocessing.cpu_count() * 2 + 1 worker_class = 'gevent' keepalive = 60 timeout = 900 max_requests = 600 # defaults to 30 sec, setting to 5 minutes to fight `GreenletExit`s graceful_timeout = 5*60 # cryptically, setting forwarded_allow_ips (to the ip of the hqproxy0) # gets gunicorn to set https on redirects when appropriate. See: # http://docs.gunicorn.org/en/latest/configure.html#secure-scheme-headers # http://docs.gunicorn.org/en/latest/configure.html#forwarded-allow-ips forwarded_allow_ips = '10.176.162.109' def post_fork(server, worker): # hacky way to address gunicorn gevent requests hitting django too early before urls are loaded # see: https://github.com/benoitc/gunicorn/issues/527#issuecomment-19601046 from django.core.urlresolvers import resolve resolve('/')
Prepare development of new version.
# -*- coding: utf-8 -*- # Copyright © 2009 Ben Finney <ben+python@benfinney.id.au> # Copyright © 2006 Robert Niederreiter # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # later as published by the Python Software Foundation. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details. """ Library to implement a well-behaved Unix daemon process This library implements PEP [no number yet], Standard daemon process library. A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. An instance of the `DaemonContext` holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state. Simple example of usage:: import daemon from spam import do_main_program with daemon.DaemonContext() as daemon_context: do_main_program() """ from daemon import DaemonContext version = "1.4.3"
# -*- coding: utf-8 -*- # Copyright © 2009 Ben Finney <ben+python@benfinney.id.au> # Copyright © 2006 Robert Niederreiter # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # later as published by the Python Software Foundation. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details. """ Library to implement a well-behaved Unix daemon process This library implements PEP [no number yet], Standard daemon process library. A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. An instance of the `DaemonContext` holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state. Simple example of usage:: import daemon from spam import do_main_program with daemon.DaemonContext() as daemon_context: do_main_program() """ from daemon import DaemonContext version = "1.4.2"
Add method to encrypt files
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def encrypt_file(self, input_file, output_file, recipient): args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file] subprocess.call(args) def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
Add Python 3 only classifier
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: readme = f.read() setup( name='manuale', version='1.0.1.dev0', license='MIT', description="A fully manual Let's Encrypt/ACME client", long_description=readme, url='https://github.com/veeti/manuale', author="Veeti Paananen", author_email='veeti.paananen@rojekti.fi', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3 :: Only', ], packages=['manuale'], install_requires=[ 'cryptography >= 1.0', 'requests', ], entry_points={ 'console_scripts': [ 'manuale = manuale.cli:main', ], }, )
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: readme = f.read() setup( name='manuale', version='1.0.1.dev0', license='MIT', description="A fully manual Let's Encrypt/ACME client", long_description=readme, url='https://github.com/veeti/manuale', author="Veeti Paananen", author_email='veeti.paananen@rojekti.fi', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], packages=['manuale'], install_requires=[ 'cryptography >= 1.0', 'requests', ], entry_points={ 'console_scripts': [ 'manuale = manuale.cli:main', ], }, )
Fix get showDevMenu on worker
/* eslint-disable no-underscore-dangle */ import { avoidWarnForRequire } from './utils'; import { toggleNetworkInspect } from './networkInspect'; let availableDevMenuMethods = {}; export const checkAvailableDevMenuMethods = async (enableNetworkInspect = false) => { const done = await avoidWarnForRequire('NativeModules', 'AsyncStorage'); const NativeModules = window.__DEV__ ? window.require('NativeModules') : {}; const AsyncStorage = window.__DEV__ ? window.require('AsyncStorage') : {}; done(); // RN 0.43 use DevSettings, DevMenu will be deprecated const DevSettings = NativeModules.DevSettings || NativeModules.DevMenu; // Currently `show dev menu` is only on DevMenu const showDevMenu = (DevSettings && DevSettings.show) || (NativeModules.DevMenu && NativeModules.DevMenu.show) || undefined; const methods = { ...DevSettings, show: showDevMenu, networkInspect: toggleNetworkInspect, clearAsyncStorage: () => AsyncStorage.clear().catch(f => f), }; const result = Object.keys(methods).filter(key => !!methods[key]); availableDevMenuMethods = methods; toggleNetworkInspect(enableNetworkInspect); postMessage({ __AVAILABLE_METHODS_CAN_CALL_BY_RNDEBUGGER__: result }); }; export const invokeDevMenuMethod = (name, args = []) => { const method = availableDevMenuMethods[name]; if (method) method(...args); };
/* eslint-disable no-underscore-dangle */ import { avoidWarnForRequire } from './utils'; import { toggleNetworkInspect } from './networkInspect'; let availableDevMenuMethods = {}; export const checkAvailableDevMenuMethods = async (enableNetworkInspect = false) => { const done = await avoidWarnForRequire('NativeModules', 'AsyncStorage'); const NativeModules = window.__DEV__ ? window.require('NativeModules') : {}; const AsyncStorage = window.__DEV__ ? window.require('AsyncStorage') : {}; done(); // RN 0.43 use DevSettings, DevMenu will be deprecated const DevSettings = NativeModules.DevSettings || NativeModules.DevMenu; // Currently `show dev menu` is only on DevMenu const showDevMenu = (DevSettings && DevSettings.show) || NativeModules.DevMenu ? NativeModules.DevMenu.show : undefined; const methods = { ...DevSettings, show: showDevMenu, networkInspect: toggleNetworkInspect, clearAsyncStorage: () => AsyncStorage.clear().catch(f => f), }; const result = Object.keys(methods).filter(key => !!methods[key]); availableDevMenuMethods = methods; toggleNetworkInspect(enableNetworkInspect); postMessage({ __AVAILABLE_METHODS_CAN_CALL_BY_RNDEBUGGER__: result }); }; export const invokeDevMenuMethod = (name, args = []) => { const method = availableDevMenuMethods[name]; if (method) method(...args); };
Test that we actually create a senseknocker bug.
# {{{ Imports from mysite.base.tests import make_twill_url, TwillTests # }}} class Form(TwillTests): fixtures = ['person-paulproteus.json', 'user-paulproteus.json'] def test_form_post_handler(self): client = self.login_with_client() bug_data = {'before': 'I was singing "Ave Maria" to a potful of dal.', 'expected_behavior': 'I expected the dal to be stirred.', 'actual_behavior': 'Instead, burnination.'} json = client.post('/senseknocker/handle_form', bug_data) # Check there exists at least one bug with the given characteristics # in the DB. (There can be more than one, hypothechnically.) self.assert_(list(senseknocker.Bug.objects.filter( before=bug_data['before'], expected_behavior=bug_data['expected_behavior'], actual_behavior=bug_data['actual_behavior'] ))) self.assertEqual(json.content, '[{"success": 1}]')
# {{{ Imports from mysite.base.tests import make_twill_url, TwillTests # }}} class Form(TwillTests): fixtures = ['person-paulproteus.json', 'user-paulproteus.json'] def test_form_post_handler(self): client = self.login_with_client() json = client.post('/senseknocker/handle_form', { 'before': 'I was singing "Ave Maria" to a potful of dal.', 'expected_behavior': 'I expected the dal to be stirred.', 'actual_behavior': 'Instead, burnination.'}) # Once we have a bug tracker, # check that the POST handler actually added a bug. self.assertEqual(json.content, '[{"success": 1}]')
Make debug toolbar use local jquery
from .base import * # noqa DEBUG = True ALLOWED_HOSTS = ['*'] try: import dj_database_url DATABASES = {'default': dj_database_url.config( default='postgres://postgres:postgres@db:5432/postgres')} except ImportError: pass EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Disable caching while in development CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } # set up Django Debug Toolbar if installed try: import debug_toolbar # noqa MIDDLEWARE += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) INSTALLED_APPS += ( 'debug_toolbar', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': lambda *args, **kwargs: True, 'JQUERY_URL': '', # Use local jQuery } except ImportError: pass
from .base import * # noqa DEBUG = True ALLOWED_HOSTS = ['*'] try: import dj_database_url DATABASES = {'default': dj_database_url.config( default='postgres://postgres:postgres@db:5432/postgres')} except ImportError: pass EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Disable caching while in development CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } # set up Django Debug Toolbar if installed try: import debug_toolbar # noqa MIDDLEWARE += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) INSTALLED_APPS += ( 'debug_toolbar', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': lambda *args, **kwargs: True } except ImportError: pass
NXP-3067: Allow batching in core queries
/* * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * 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. * * Contributors: * Nuxeo - initial API and implementation * * $Id: JOOoConvertPluginImpl.java 18651 2007-05-13 20:28:53Z sfermigier $ */ package org.nuxeo.ecm.platform.cache.server.bd; import java.util.ArrayList; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; public class GhostDocumentsList extends ArrayList<DocumentModel> implements DocumentModelList { private static final long serialVersionUID = -1907319974461744723L; public long totalSize() { return size(); } }
/* * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * 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. * * Contributors: * Nuxeo - initial API and implementation * * $Id: JOOoConvertPluginImpl.java 18651 2007-05-13 20:28:53Z sfermigier $ */ package org.nuxeo.ecm.platform.cache.server.bd; import java.util.ArrayList; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; public class GhostDocumentsList extends ArrayList<DocumentModel> implements DocumentModelList { private static final long serialVersionUID = -1907319974461744723L; }
Fix max width of overflowing specimens on Firefox
import React, {Component, PropTypes} from 'react'; export default class Span extends Component { render() { const {children, span} = this.props; const style = { boxSizing: 'border-box', display: 'flex', flexBasis: span && window.innerWidth > 640 ? `calc(${span / 6 * 100}% - 10px)` : 'calc(100% - 10px)', // Bug fix for Firefox; width and flexBasis don't work on horizontally scrolling code blocks maxWidth: span && window.innerWidth > 640 ? `calc(${span / 6 * 100}% - 10px)` : 'calc(100% - 10px)', flexWrap: 'wrap', margin: '24px 10px 0 0', padding: 0, position: 'relative' }; return ( <div {...this.props} style={{...style, ...this.props.style}}> {children} </div> ); } } Span.propTypes = { span: PropTypes.number, children: PropTypes.node.isRequired, style: PropTypes.object };
import React, {Component, PropTypes} from 'react'; export default class Span extends Component { render() { const {children, span} = this.props; const style = { boxSizing: 'border-box', display: 'flex', flexBasis: span && window.innerWidth > 640 ? `calc(${span / 6 * 100}% - 10px)` : 'calc(100% - 10px)', flexWrap: 'wrap', margin: '24px 10px 0 0', padding: 0, position: 'relative' }; return ( <div {...this.props} style={{...style, ...this.props.style}}> {children} </div> ); } } Span.propTypes = { span: PropTypes.number, children: PropTypes.node.isRequired, style: PropTypes.object };
Use converter from the EntityUtils
package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.Activity; import com.epam.ta.reportportal.ws.model.ActivityResource; import java.util.function.Function; import static com.epam.ta.reportportal.commons.EntityUtils.TO_DATE; public final class ActivityConverter { private ActivityConverter() { //static only } public static final Function<Activity, ActivityResource> TO_RESOURCE = activity -> { ActivityResource resource = new ActivityResource(); resource.setActivityId(activity.getId().toString()); resource.setLastModifiedDate(TO_DATE.apply(activity.getCreatedAt())); resource.setObjectType(activity.getActivityEntityType().name()); resource.setActionType(activity.getAction()); resource.setProjectRef(activity.getProjectId().toString()); resource.setUserRef(activity.getUserId().toString()); resource.setLoggedObjectRef(activity.getObjectId().toString()); resource.setDetails(activity.getDetails()); return resource; }; }
package com.epam.ta.reportportal.ws.converter.converters; import com.epam.ta.reportportal.entity.Activity; import com.epam.ta.reportportal.ws.model.ActivityResource; import java.sql.Date; import java.time.ZoneId; import java.util.function.Function; public final class ActivityConverter { private ActivityConverter() { //static only } public static final Function<Activity, ActivityResource> TO_RESOURCE = activity -> { ActivityResource resource = new ActivityResource(); resource.setActivityId(activity.getId().toString()); resource.setLastModifiedDate(Date.from(activity.getCreatedAt().atZone(ZoneId.systemDefault()).toInstant())); resource.setObjectType(activity.getEntity().name()); resource.setActionType(activity.getAction()); resource.setProjectRef(activity.getProjectId().toString()); resource.setUserRef(activity.getUserId().toString()); resource.setLoggedObjectRef(activity.getObjectId().toString()); resource.setDetails(activity.getDetails()); return resource; }; }
[assets] Remove useless flag on get asset types call
import client from '@/store/api/client' export default { getAssetTypes (callback) { client.get('/api/data/asset-types', callback) }, getAssetType (assetTypeId, callback) { client.get(`/api/data/entity-types/${assetTypeId}`, callback) }, newAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.ppost('/api/data/entity-types', data) }, updateAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.pput(`/api/data/entity-types/${assetType.id}`, data) }, deleteAssetType (assetType, callback) { return client.pdel(`/api/data/entity-types/${assetType.id}`) } }
import client from '@/store/api/client' export default { getAssetTypes (callback) { client.get('/api/data/asset-types?relations=true', callback) }, getAssetType (assetTypeId, callback) { client.get(`/api/data/entity-types/${assetTypeId}`, callback) }, newAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.ppost('/api/data/entity-types', data) }, updateAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.pput(`/api/data/entity-types/${assetType.id}`, data) }, deleteAssetType (assetType, callback) { return client.pdel(`/api/data/entity-types/${assetType.id}`) } }
Add refresh_token OAuth grant by default
<?php namespace App\Entity\OAuth; use FOS\OAuthServerBundle\Entity\Client as BaseClient; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="ClientRepository") */ class Client extends BaseClient { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", unique=true) */ private $name; /** * @ORM\Column(type="boolean") */ private $preApproved; public function __construct() { parent::__construct(); $this->allowedGrantTypes[] = \OAuth2\OAuth2::GRANT_TYPE_REFRESH_TOKEN; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; return $this; } public function isPreApproved() { return $this->preApproved; } public function setPreApproved($preApproved) { $this->preApproved = $preApproved; return $this; } }
<?php namespace App\Entity\OAuth; use FOS\OAuthServerBundle\Entity\Client as BaseClient; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="ClientRepository") */ class Client extends BaseClient { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", unique=true) */ private $name; /** * @ORM\Column(type="boolean") */ private $preApproved; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; return $this; } public function isPreApproved() { return $this->preApproved; } public function setPreApproved($preApproved) { $this->preApproved = $preApproved; return $this; } }
Add some extras to the Markdown parser
from markdown2 import markdown from docutils.core import publish_parts from textile import textile def rst(string): """Wraps the ReST parser in Docutils. Note that Docutils wraps its output in a `<div class='document'>`.""" return publish_parts( source=string, settings_overrides={ 'file_insertion_enabled': 0, 'raw_enabled': 0, '--template': '%(body)s', }, writer_name='html' )['html_body'] def md(string): return markdown(string, extras=[ 'fenced-code-blocks', 'footnotes', 'smarty-pants', 'wiki-tables', ]) # A tuple containing all supported formats. # Each line goes (format name, tuple of possible file extensions, formatter) # where formatter is a callable that takes a string and returns a HTML string PAGE_FORMATS = ( ('Markdown', ('mdown', 'markdown', 'md', 'mdn', 'mkdn', 'mkd', 'mdn'), md), ('reStructuredText', ('rst', 'rest'), rst), ('Textile', ('textile'), textile), ('HTML', ('html', 'htm'), lambda x: x), ) def format(page): """Converts a giki page object into HTML.""" for name, fmts, formatter in PAGE_FORMATS: if page.fmt in fmts: return formatter(page.content) else: return "<code><pre>{}</pre></code>".format(page.content.replace('&', '&nbsp;').replace('<', '&lt;'))
from markdown2 import markdown from docutils.core import publish_parts from textile import textile def rst(string): """Wraps the ReST parser in Docutils. Note that Docutils wraps its output in a `<div class='document'>`.""" return publish_parts( source=string, settings_overrides={ 'file_insertion_enabled': 0, 'raw_enabled': 0, '--template': '%(body)s', }, writer_name='html' )['html_body'] # A tuple containing all supported formats. # Each line goes (format name, tuple of possible file extensions, formatter) # where formatter is a callable that takes a string and returns a HTML string PAGE_FORMATS = ( ('Markdown', ('mdown', 'markdown', 'md', 'mdn', 'mkdn', 'mkd', 'mdn'), markdown), ('reStructuredText', ('rst', 'rest'), rst), ('Textile', ('textile'), textile), ('HTML', ('html', 'htm'), lambda x: x), ) def format(page): """Converts a giki page object into HTML.""" for name, fmts, formatter in PAGE_FORMATS: if page.fmt in fmts: return formatter(page.content) else: return "<code><pre>{}</pre></code>".format(page.content.replace('&', '&nbsp;').replace('<', '&lt;'))
Fix add_todo_if_empty test helper action creator
from __future__ import absolute_import from .action_types import ( ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR, UNKNOWN_ACTION, ) def add_todo(text): return {'type': ADD_TODO, 'text': text} def add_todo_if_empty(text): def anon(dispatch, get_state): if len(get_state()) == 0: dispatch(add_todo(text)) return anon def dispatch_in_middle(bound_dispatch_fn): return { 'type': DISPATCH_IN_MIDDLE, 'bound_dispatch_fn': bound_dispatch_fn, } def throw_error(): return { 'type': THROW_ERROR, } def unknown_action(): return { 'type': UNKNOWN_ACTION, }
from __future__ import absolute_import from .action_types import ( ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR, UNKNOWN_ACTION, ) def add_todo(text): return {'type': ADD_TODO, 'text': text} def add_todo_if_empty(text): def anon(dispatch, get_state): if len(get_state()) == 0: add_todo(text) return anon def dispatch_in_middle(bound_dispatch_fn): return { 'type': DISPATCH_IN_MIDDLE, 'bound_dispatch_fn': bound_dispatch_fn, } def throw_error(): return { 'type': THROW_ERROR, } def unknown_action(): return { 'type': UNKNOWN_ACTION, }
Remove extra space for method call.
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub (r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
Fix for create membership issue when used in TaskListener::notify()
/* 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.activiti.engine.impl.persistence.entity; import java.io.Serializable; /** * @author Tom Baeyens * @author Joram Barrez */ public class MembershipEntityImpl extends AbstractEntityNoRevision implements MembershipEntity, Serializable { private static final long serialVersionUID = 1L; protected String userId; protected String groupId; public MembershipEntityImpl() { } public Object getPersistentState() { // membership is not updatable return MembershipEntityImpl.class; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } }
/* 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.activiti.engine.impl.persistence.entity; import java.io.Serializable; /** * @author Tom Baeyens * @author Joram Barrez */ public class MembershipEntityImpl extends AbstractEntityNoRevision implements MembershipEntity, Serializable { private static final long serialVersionUID = 1L; protected String userId; protected String groupId; public MembershipEntityImpl() { } public Object getPersistentState() { // membership is not updatable return MembershipEntityImpl.class; } public String getId() { // membership doesn't have an id return null; } public void setId(String id) { // membership doesn't have an id } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } }
Test the insert block fn
'use strict'; describe('Controller: FormDropAreaCtrl', function () { // load the controller's module beforeEach(module('confRegistrationWebApp')); var FormDropAreaCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); scope.conference = { registrationPages: [ { id: 'page1', blocks: [ { id: 'block1' } ] }, { id: 'page2', blocks: [ { id: 'block2' } ] } ] }; FormDropAreaCtrl = $controller('FormDropAreaCtrl', { $scope: scope }); })); it('should have a function to move a block', function () { scope.moveBlock('block2', 'page1', 0); expect(scope.conference.registrationPages[0].blocks.length).toBe(2); expect(scope.conference.registrationPages[0].blocks[0].id).toBe('block2'); }); it('should have a function to insert a block', function () { scope.insertBlock('textQuestion', 'page2', 1); expect(scope.conference.registrationPages[1].blocks.length).toBe(2); expect(scope.conference.registrationPages[1].blocks[1].type).toBe('textQuestion'); }); });
'use strict'; describe('Controller: FormDropAreaCtrl', function () { // load the controller's module beforeEach(module('confRegistrationWebApp')); var FormDropAreaCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); scope.conference = { registrationPages: [ { id: 'page1', blocks: [ { id: 'block1' } ] }, { id: 'page2', blocks: [ { id: 'block2' } ] } ] }; FormDropAreaCtrl = $controller('FormDropAreaCtrl', { $scope: scope }); })); it('should have a function to move a block', function () { scope.moveBlock('block2', 'page1', 0); expect(scope.conference.registrationPages[0].blocks.length).toBe(2); expect(scope.conference.registrationPages[0].blocks[0].id).toBe('block2'); }); });
Use ecmascript 6, cancel interval
require('normalize.css'); require('styles/App.css'); import React from 'react'; let someUnusedStuff = 'hello'; let yeomanImage = require('../images/yeoman.png'); const colors = ['red', 'white', 'green']; let currentIndex = 0; function nextColor() { let color = colors[currentIndex % colors.length]; currentIndex = currentIndex + 1; return color; } const one = 1; const moreStuff = [{}] class AppComponent extends React.Component { constructor(props, context) { super(props, context); this.state = { background: nextColor() }; } componentDidMount() { let self = this; this.interval = setInterval(() => self.setState({background: nextColor()}), 3000); } componentDidUnmount() { clearInterval(this.interval); } render() { return ( <div className="index"> <img src={yeomanImage} alt="Yeoman Generator" /> <div className="notice" style={{ background: this.state.background }}>Please edit <code>src/components/Main.js</code> to get started!</div> </div> ); } } AppComponent.defaultProps = { }; export default AppComponent;
require('normalize.css'); require('styles/App.css'); import React from 'react'; let someUnusedStuff = 'hello'; let yeomanImage = require('../images/yeoman.png'); const colors = ['red', 'white', 'green']; let currentIndex = 0; function nextColor() { let color = colors[currentIndex % colors.length]; currentIndex = currentIndex + 1; return color; } const one = 1; const moreStuff = [{}] console.info([1,2,3].map(console.info)); class AppComponent extends React.Component { constructor(props, context) { super(props, context); this.state = { background: nextColor() }; } componentDidMount() { let self = this; setInterval(function () { self.setState({background: nextColor()}); }, 3000); } render() { return ( <div className="index"> <img src={yeomanImage} alt="Yeoman Generator" /> <div className="notice" style={{ background: this.state.background }}>Please edit <code>src/components/Main.js</code> to get started!</div> </div> ); } } AppComponent.defaultProps = { }; export default AppComponent;
Return local shard tree from FindPrimaryShard Added a new ShardLeaderStateChanged message that includes the Shard's DataTree as an Optional. If the shard is the leader, it returns it's local DataTree, oherwise returns absent. The ShardManager now returns a LocalPrimaryShardFound response to FindPrimary if the shard's DataTree is present. Otherwise it returns RemotePrimaryShardFound (renamed from PrimaryFound). Change-Id: I4413aacfff3d3d2ee89df7c4a3a1d7f7c3d2c486 Signed-off-by: Tom Pantelis <8fc992100aff336363d341c5498f75ab4da389ae@brocade.com> (cherry picked from commit fdddb482b07c3ee2f3ca853d09ee9a6ecdd7eb2a)
/* * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.notifications; import com.google.common.base.Preconditions; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * A local message initiated internally from the RaftActor when some state of a leader has changed. * * @author Thomas Pantelis */ public class LeaderStateChanged { private final String memberId; private final String leaderId; public LeaderStateChanged(@Nonnull String memberId, @Nullable String leaderId) { this.memberId = Preconditions.checkNotNull(memberId); this.leaderId = leaderId; } public @Nonnull String getMemberId() { return memberId; } public @Nullable String getLeaderId() { return leaderId; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("LeaderStateChanged [memberId=").append(memberId).append(", leaderId=").append(leaderId) .append("]"); return builder.toString(); } }
/* * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.notifications; import java.io.Serializable; /** * A message initiated internally from the RaftActor when some state of a leader has changed * * @author Thomas Pantelis */ public class LeaderStateChanged implements Serializable { private static final long serialVersionUID = 1L; private final String memberId; private final String leaderId; public LeaderStateChanged(String memberId, String leaderId) { this.memberId = memberId; this.leaderId = leaderId; } public String getMemberId() { return memberId; } public String getLeaderId() { return leaderId; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("LeaderStateChanged [memberId=").append(memberId).append(", leaderId=").append(leaderId) .append("]"); return builder.toString(); } }
Verify that the cart does not contain an unavailable item
import { Store } from 'consus-core/flux'; import StudentStore from './student-store'; import ItemStore from './item-store'; let checkouts = []; let checkoutsByActionId = new Object(null); class CheckoutStore extends Store { getCheckoutByActionId(actionId) { return checkoutsByActionId[actionId]; } } const store = new CheckoutStore(); store.registerHandler('NEW_CHECKOUT', data => { let checkout = { studentId: data.studentId, itemAddresses: data.itemAddresses }; data.itemAddresses.forEach(itemAddress => { if (ItemStore.getItemByAddress(itemAddress).status !== 'AVAILABLE') { throw new Error('An item in the cart is not available for checkout.'); } }); if (StudentStore.hasOverdueItem(data.studentId)) { throw new Error('Student has overdue item'); } else { checkoutsByActionId[data.actionId] = checkout; checkouts.push(checkout); } }); export default store;
import { Store } from 'consus-core/flux'; import StudentStore from './student-store'; let checkouts = []; let checkoutsByActionId = new Object(null); class CheckoutStore extends Store { getCheckoutByActionId(actionId) { return checkoutsByActionId[actionId]; } } const store = new CheckoutStore(); store.registerHandler('NEW_CHECKOUT', data => { let checkout = { studentId: data.studentId, itemAddresses: data.itemAddresses }; if (StudentStore.hasOverdueItem(data.studentId)){ throw new Error('Student has overdue item'); }else { checkoutsByActionId[data.actionId] = checkout; checkouts.push(checkout); } }); export default store;
Change AddressBook in comments to Emeraldo
package seedu.address.storage; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.model.ReadOnlyEmeraldo; import java.io.IOException; import java.util.Optional; /** * Represents a storage for {@link seedu.address.model.AddressBook}. */ public interface EmeraldoStorage { /** * Returns the file path of the data file. */ String getEmeraldoFilePath(); /** * Returns Emeraldo data as a {@link ReadOnlyEmeraldo}. * Returns {@code Optional.empty()} if storage file is not found. * @throws DataConversionException if the data in storage is not in the expected format. * @throws IOException if there was any problem when reading from the storage. */ Optional<ReadOnlyEmeraldo> readEmeraldo() throws DataConversionException, IOException; /** * @see #getEmeraldoFilePath() */ Optional<ReadOnlyEmeraldo> readEmeraldo(String filePath) throws DataConversionException, IOException; /** * Saves the given {@link ReadOnlyEmeraldo} to the storage. * @param addressBook cannot be null. * @throws IOException if there was any problem writing to the file. */ void saveAddressBook(ReadOnlyEmeraldo addressBook) throws IOException; /** * @see #saveAddressBook(ReadOnlyEmeraldo) */ void saveAddressBook(ReadOnlyEmeraldo addressBook, String filePath) throws IOException; }
package seedu.address.storage; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.model.ReadOnlyEmeraldo; import java.io.IOException; import java.util.Optional; /** * Represents a storage for {@link seedu.address.model.AddressBook}. */ public interface EmeraldoStorage { /** * Returns the file path of the data file. */ String getEmeraldoFilePath(); /** * Returns AddressBook data as a {@link ReadOnlyEmeraldo}. * Returns {@code Optional.empty()} if storage file is not found. * @throws DataConversionException if the data in storage is not in the expected format. * @throws IOException if there was any problem when reading from the storage. */ Optional<ReadOnlyEmeraldo> readEmeraldo() throws DataConversionException, IOException; /** * @see #getEmeraldoFilePath() */ Optional<ReadOnlyEmeraldo> readEmeraldo(String filePath) throws DataConversionException, IOException; /** * Saves the given {@link ReadOnlyEmeraldo} to the storage. * @param addressBook cannot be null. * @throws IOException if there was any problem writing to the file. */ void saveAddressBook(ReadOnlyEmeraldo addressBook) throws IOException; /** * @see #saveAddressBook(ReadOnlyEmeraldo) */ void saveAddressBook(ReadOnlyEmeraldo addressBook, String filePath) throws IOException; }
Allow underscores and dashes in element names
package com.marklogic.hector; import com.marklogic.spring.batch.columnmap.ColumnMapSerializer; import org.apache.commons.lang3.StringEscapeUtils; import java.util.Map; public class XmlStringColumnMapSerializer implements ColumnMapSerializer { @Override public String serializeColumnMap(Map<String, Object> columnMap, String rootLocalName) { String content = ""; String rootName = rootLocalName.length() == 0 ? "record" : rootLocalName; content = "<" + rootName + ">\n"; for (Map.Entry<String, Object> entry : transformColumnMap(columnMap).entrySet()) { String elName = entry.getKey().replaceAll("[^A-Za-z0-9\\_\\-]", ""); content += "<" + elName + ">" + StringEscapeUtils.escapeXml11(entry.getValue().toString()) + "</" + elName + ">\n"; } content += "</" + rootName + ">"; return content; } //The strategy is to extend this class and overwrite this method. protected Map<String, Object> transformColumnMap(Map<String, Object> columnMap) { return columnMap; } }
package com.marklogic.hector; import com.marklogic.spring.batch.columnmap.ColumnMapSerializer; import org.apache.commons.lang3.StringEscapeUtils; import java.util.Map; public class XmlStringColumnMapSerializer implements ColumnMapSerializer { @Override public String serializeColumnMap(Map<String, Object> columnMap, String rootLocalName) { String content = ""; String rootName = rootLocalName.length() == 0 ? "record" : rootLocalName; content = "<" + rootName + ">\n"; for (Map.Entry<String, Object> entry : transformColumnMap(columnMap).entrySet()) { String elName = entry.getKey().replaceAll("[^A-Za-z0-9]", ""); content += "<" + elName + ">" + StringEscapeUtils.escapeXml11(entry.getValue().toString()) + "</" + elName + ">\n"; } content += "</" + rootName + ">"; return content; } //The strategy is to extend this class and overwrite this method. protected Map<String, Object> transformColumnMap(Map<String, Object> columnMap) { return columnMap; } }
Edit path to DB, index.html
// server.js "use strict"; const jsonServer = require('json-server'); const server = jsonServer.create(); const router = jsonServer.router('app/db.json') const middlewares = jsonServer.defaults(); const path = require("path"); const PORT = 3000; const HOST_NAME = "localhost"; const HOST = `${HOST_NAME}:${PORT}`; // To handle POST, PUT and PATCH you need to use a body-parser // You can use the one used by JSON Server server.use(jsonServer.bodyParser); // Set default middlewares (logger, static, cors and no-cache) server.use(middlewares); // Use default router server.use("/api", router); // Add custom routes before JSON Server router server.get('/', (req, res) => { res.sendFile(path.join(__dirname, "app/index.html")); }) server.listen(PORT, () => { console.log(`JSON Server is running on ${HOST}`); });
// server.js "use strict"; const jsonServer = require('json-server'); const server = jsonServer.create(); const router = jsonServer.router('db.json') const middlewares = jsonServer.defaults(); const path = require("path"); const PORT = 3000; const HOST_NAME = "localhost"; const HOST = `${HOST_NAME}:${PORT}`; // To handle POST, PUT and PATCH you need to use a body-parser // You can use the one used by JSON Server server.use(jsonServer.bodyParser); // Set default middlewares (logger, static, cors and no-cache) server.use(middlewares); // Use default router server.use("/api", router); // Add custom routes before JSON Server router server.get('/', (req, res) => { res.sendFile(path.join(__dirname, "index.html")); }) server.listen(PORT, () => { console.log(`JSON Server is running on ${HOST}`); });
Fix name is already in use on php5.5.9
<?php namespace Metrique\Meta; use Illuminate\Contracts\View\View; use Metrique\Meta\Contracts\MetaRepositoryInterface as Repository; class MetaViewComposer { /** * The meta repository implementation. * * @var Repository */ protected $meta; /** * Create a new profile composer. * * @param Repository $meta * @return void */ public function __construct(Repository $meta) { // Dependencies automatically resolved by service container... $this->meta = $meta; } /** * Bind data to the view. * * @param View $view * @return void */ public function compose(View $view) { $view->with('meta', $this->meta); } }
<?php namespace Metrique\Meta; use Illuminate\Contracts\View\View; use Metrique\Meta\Contracts\MetaRepositoryInterface as MetaRepository; class MetaViewComposer { /** * The meta repository implementation. * * @var MetaRepository */ protected $meta; /** * Create a new profile composer. * * @param UserRepository $users * @return void */ public function __construct(MetaRepository $meta) { // Dependencies automatically resolved by service container... $this->meta = $meta; } /** * Bind data to the view. * * @param View $view * @return void */ public function compose(View $view) { $view->with('meta', $this->meta); } }
Sort timetable pages in example app
const _ = require('lodash'); const gtfs = require('gtfs'); const router = require('express').Router(); const config = require('../config'); const utils = require('../lib/utils'); /* * Show all agencies */ router.get('/', (req, res, next) => { gtfs.agencies((err, agencies) => { if (err) return next(err); return res.render('agencies', { agencies: _.sortBy(agencies, 'agency_name') }); }); }); /* * Show all timetable pages for an agency */ router.get('/timetablepages', (req, res, next) => { const agencyKey = req.query.agency_key; utils.getTimetablePages(agencyKey).then((timetablePages) => { const sortedTimetablePages = _.sortBy(timetablePages, 'route_label'); res.render('timetablepages', { agencyKey, timetablePages: sortedTimetablePages }); }, next); }); /* * Show a specific timetable page */ router.get('/timetablepage', (req, res, next) => { const agencyKey = req.query.agency_key; const timetablePageId = req.query.timetable_page_id; utils.getTimetablePage(agencyKey, timetablePageId).then((timetablePage) => { utils.generateHTML(agencyKey, timetablePage, config, (err, html) => { if (err) return next(err); res.send(html); }); }, next); }); module.exports = router;
const _ = require('lodash'); const gtfs = require('gtfs'); const router = require('express').Router(); const config = require('../config'); const utils = require('../lib/utils'); /* * Show all agencies */ router.get('/', (req, res, next) => { gtfs.agencies((err, agencies) => { if (err) return next(err); return res.render('agencies', { agencies: _.sortBy(agencies, 'agency_name') }); }); }); /* * Show all timetable pages for an agency */ router.get('/timetablepages', (req, res, next) => { const agencyKey = req.query.agency_key; utils.getTimetablePages(agencyKey).then((timetablePages) => { res.render('timetablepages', { agencyKey, timetablePages }); }, next); }); /* * Show a specific timetable page */ router.get('/timetablepage', (req, res, next) => { const agencyKey = req.query.agency_key; const timetablePageId = req.query.timetable_page_id; utils.getTimetablePage(agencyKey, timetablePageId).then((timetablePage) => { utils.generateHTML(agencyKey, timetablePage, config, (err, html) => { if (err) return next(err); res.send(html); }); }, next); }); module.exports = router;
Handle both synchronous and asynchronous processing
import Velocity from 'velocity-animate'; export default function vq(el, props, opts = null) { if (!opts) { opts = props.o; props = props.p; } opts = clone(opts); return function(done) { opts.complete = done; Velocity(el, props, opts); }; } export function sequence(seq) { const head = seq[0]; const tail = seq.slice(1); if (typeof head !== 'function') return; if (head.length > 0) { // Ensure there is a callback function as 1st argument head(function() { sequence(tail); }); } else { head(); sequence(tail); } } function clone(obj) { const result = {}; Object.keys(obj).forEach(function(key) { if (obj[key] && typeof obj[key] === 'object') { result[key] = clone(obj[key]); } else { result[key] = obj[key]; } }); return result; }
import Velocity from 'velocity-animate'; export default function vq(el, props, opts = null) { if (!opts) { opts = props.o; props = props.p; } opts = clone(opts); return function(done) { opts.complete = done; Velocity(el, props, opts); }; } export function sequence(seq) { const head = seq[0]; const tail = seq.slice(1); if (typeof head !== 'function') return; head(function() { sequence(tail); }); } function clone(obj) { const result = {}; Object.keys(obj).forEach(function(key) { if (obj[key] && typeof obj[key] === 'object') { result[key] = clone(obj[key]); } else { result[key] = obj[key]; } }); return result; }
Migrate old passwords without "set_unusable_password"
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-10-11 17:28 from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def forwards_func(apps, schema_editor): User = apps.get_model('auth', 'User') old_password_patterns = ( 'sha1$', # RTD's production database doesn't have any of these # but they are included for completeness 'md5$', 'crypt$', ) for pattern in old_password_patterns: users = User.objects.filter(password__startswith=pattern) for user in users: user.password = make_password(None) user.save() class Migration(migrations.Migration): dependencies = [ ('core', '0004_ad-opt-out'), ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.RunPython(forwards_func), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-10-11 17:28 from __future__ import unicode_literals from django.db import migrations def forwards_func(apps, schema_editor): User = apps.get_model('auth', 'User') old_password_patterns = ( 'sha1$', # RTD's production database doesn't have any of these # but they are included for completeness 'md5$', 'crypt$', ) for pattern in old_password_patterns: users = User.objects.filter(password__startswith=pattern) for user in users: user.set_unusable_password() user.save() class Migration(migrations.Migration): dependencies = [ ('core', '0004_ad-opt-out'), ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.RunPython(forwards_func), ]
Fix plug-in type and description key 't Was a typo. Contributes to issue CURA-1190.
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import SimpleView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Simple View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."), "api": 2 }, "view": { "name": i18n_catalog.i18nc("@item:inmenu", "Simple"), "visible": False } } def register(app): return { "view": SimpleView.SimpleView() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import SimpleView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": i18n_catalog.i18nc("@label", "Simple View"), "author": "Ultimaker", "version": "1.0", "decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."), "api": 2 }, "view": { "name": i18n_catalog.i18nc("@item:inmenu", "Simple"), "visible": False } } def register(app): return { "view": SimpleView.SimpleView() }
Use the correct `host` when falling back
'use strict'; const net = require('net'); const isAvailable = options => new Promise((resolve, reject) => { const server = net.createServer(); server.unref(); server.on('error', reject); server.listen(options, () => { const {port} = server.address(); server.close(() => { resolve(port); }); }); }); const getPort = (options = {}) => { if (typeof options.port === 'number') { options.port = [options.port]; } return (options.port || []).reduce( (seq, port) => seq.catch( () => isAvailable(Object.assign({}, options, {port})) ), Promise.reject() ); }; module.exports = options => options ? getPort(options).catch(() => getPort(Object.assign(options, {port: 0}))) : getPort({port: 0});
'use strict'; const net = require('net'); const isAvailable = options => new Promise((resolve, reject) => { const server = net.createServer(); server.unref(); server.on('error', reject); server.listen(options, () => { const {port} = server.address(); server.close(() => { resolve(port); }); }); }); const getPort = (options = {}) => { if (typeof options.port === 'number') { options.port = [options.port]; } return (options.port || []).reduce( (seq, port) => seq.catch( () => isAvailable(Object.assign({}, options, {port})) ), Promise.reject() ); }; module.exports = options => options ? getPort(options).catch(() => getPort({port: 0})) : getPort({port: 0});
Add tests requested by @joernhees
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") value = Literal(float("inf")) # g1 is a simple graph with one attribute having an infinite value g1 = Graph() g1.add((bob, PROV.value, value)) # Build g2 out of the deserialisation of g1 serialisation g2 = Graph() g2.parse(data=g1.serialize(format='turtle'), format='turtle') self.assertTrue(g1.serialize( format='turtle') == g2.serialize(format='turtle')) self.assertTrue(to_isomorphic(g1) == to_isomorphic(g2)) self.assertTrue(Literal(float("inf")).n3().split("^")[0] == '"INF"') self.assertTrue(Literal(float("-inf")).n3().split("^")[0] == '"-INF"') if __name__ == "__main__": unittest.main()
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") value = Literal(float("inf")) # g1 is a simple graph with one attribute having an infinite value g1 = Graph() g1.add((bob, PROV.value, value)) # Build g2 out of the deserialisation of g1 serialisation g2 = Graph() g2.parse(data=g1.serialize(format='turtle'), format='turtle') self.assertTrue(g1.serialize( format='turtle') == g2.serialize(format='turtle')) self.assertTrue(to_isomorphic(g1) == to_isomorphic(g2)) if __name__ == "__main__": unittest.main()
Change hardcoding of cherry to reflect borders instead
gamePieces = {}; gamePieces.createTeleport = function() { starOne = game.add.sprite(10, game.world.height - 300, 'star'); starOne.anchor.setTo(0.5, 0.5); starOne.scale.setTo(1,1); starTwo = game.add.sprite(790, game.world.height - 300, 'star'); starTwo.anchor.setTo(0.5, 0.5); starTwo.scale.setTo(1,1); } gamePieces.createOneDot = function() { dot = game.add.sprite(Math.random()*700, Math.random()*500, 'diamond'); dot.anchor.setTo(0.5, 0.5); dots.push(dot); }; gamePieces.createMultipleDots = function(count) { for(var i = 0; i < count; i++){ gamePieces.createOneDot(); } }; gamePieces.createPowerUp = function() { cherry = game.add.sprite(Math.random()*700, Math.random()*500, 'star'); cherry.anchor.setTo(0.5, 0.5); powerUp.push(cherry); };
gamePieces = {}; gamePieces.createTeleport = function() { starOne = game.add.sprite(10, game.world.height - 300, 'star'); starOne.anchor.setTo(0.5, 0.5); starOne.scale.setTo(1,1); starTwo = game.add.sprite(790, game.world.height - 300, 'star'); starTwo.anchor.setTo(0.5, 0.5); starTwo.scale.setTo(1,1); } gamePieces.createOneDot = function() { dot = game.add.sprite(Math.random()*800, Math.random()*600, 'diamond'); dot.anchor.setTo(0.5, 0.5); dots.push(dot); }; gamePieces.createMultipleDots = function(count) { for(var i = 0; i < count; i++){ gamePieces.createOneDot(); } }; gamePieces.createPowerUp = function() { cherry = game.add.sprite(250, 200, 'star'); cherry.anchor.setTo(0.5, 0.5); powerUp.push(cherry); };
Add 'type' field to tab enumeration JSON protocol Review URL: https://codereview.chromium.org/12036084
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String faviconUrl(); String title(); String url(); String thumbnailUrl(); // TODO: consider adding enum here String type(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String faviconUrl(); String title(); String url(); String thumbnailUrl(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
Change ruleName in at-mixin-argumentless-call-parentheses to match name of the rule at-mixin-argumentless-call-parentheses had an extra no- in its ruleName that caused the rule to fail with an ignore message rather than an error. Fixes #106
import { utils } from "stylelint" import { namespace } from "../../utils" export const ruleName = namespace("at-mixin-argumentless-call-parentheses") export const messages = utils.ruleMessages(ruleName, { expected: mixin => `Expected parentheses in mixin "${mixin}" call`, rejected: mixin => `Unexpected parentheses in argumentless mixin "${mixin}" call`, }) export default function (value) { return (root, result) => { const validOptions = utils.validateOptions(result, ruleName, { actual: value, possible: [ "always", "never" ], }) if (!validOptions) { return } root.walkAtRules("include", mixinCall => { // If it is "No parens in argumentless calls" if (value === "never" && mixinCall.params.search(/\(\s*?\)\s*?$/) === -1) { return } // If it is "Always use parens" if (value === "always" && mixinCall.params.search(/\(/) !== -1) { return } const mixinName = /\s*(\S*?)\s*(?:\(|$)/.exec(mixinCall.params)[1] utils.report({ message: messages[value === "never" ? "rejected" : "expected"](mixinName), node: mixinCall, result, ruleName, }) }) } }
import { utils } from "stylelint" import { namespace } from "../../utils" export const ruleName = namespace("at-mixin-no-argumentless-call-parentheses") export const messages = utils.ruleMessages(ruleName, { expected: mixin => `Expected parentheses in mixin "${mixin}" call`, rejected: mixin => `Unexpected parentheses in argumentless mixin "${mixin}" call`, }) export default function (value) { return (root, result) => { const validOptions = utils.validateOptions(result, ruleName, { actual: value, possible: [ "always", "never" ], }) if (!validOptions) { return } root.walkAtRules("include", mixinCall => { // If it is "No parens in argumentless calls" if (value === "never" && mixinCall.params.search(/\(\s*?\)\s*?$/) === -1) { return } // If it is "Always use parens" if (value === "always" && mixinCall.params.search(/\(/) !== -1) { return } const mixinName = /\s*(\S*?)\s*(?:\(|$)/.exec(mixinCall.params)[1] utils.report({ message: messages[value === "never" ? "rejected" : "expected"](mixinName), node: mixinCall, result, ruleName, }) }) } }
Add newline between func defs.
# -*- coding: utf-8 -*- """Config-like for paver tool.""" from paver.easy import task, sh, path # noqa # pylint: disable=invalid-name cli_command_name = 'serverauditor' @task def lint(): """Check code style and conventions.""" sh('prospector') @task def bats(): """Run tests on CLI usage.""" sh('bats --tap tests/integration') @task def nosetests(): """Run unit tests.""" sh('nosetests') @task def completion_tests(): """Run integration tests for bash completion.""" sh('nosetests tests/integration/completion/bash/') @task def coverage(): """Run test and collect coverage.""" sh('nosetests --with-coverage') sh('coverage xml') @task def create_compeletion(info): """Generate bash completion.""" completion_dir = path('contrib/completion/bash') if not completion_dir.exists(): completion_dir.makedirs_p() completion_path = completion_dir / cli_command_name if completion_path.exists(): info('Completion exists') else: sh('{} complete > {}'.format(cli_command_name, completion_path)) @task def clean_compeletion(info): """Generate bash completion.""" completion_path = path('contrib/bash/complete') / cli_command_name completion_path.remove() info('Completion exists')
# -*- coding: utf-8 -*- """Config-like for paver tool.""" from paver.easy import task, sh, path # noqa # pylint: disable=invalid-name cli_command_name = 'serverauditor' @task def lint(): """Check code style and conventions.""" sh('prospector') @task def bats(): """Run tests on CLI usage.""" sh('bats --tap tests/integration') @task def nosetests(): """Run unit tests.""" sh('nosetests') @task def completion_tests(): """Run integration tests for bash completion.""" sh('nosetests tests/integration/completion/bash/') @task def coverage(): """Run test and collect coverage.""" sh('nosetests --with-coverage') sh('coverage xml') @task def create_compeletion(info): """Generate bash completion.""" completion_dir = path('contrib/completion/bash') if not completion_dir.exists(): completion_dir.makedirs_p() completion_path = completion_dir / cli_command_name if completion_path.exists(): info('Completion exists') else: sh('{} complete > {}'.format(cli_command_name, completion_path)) @task def clean_compeletion(info): """Generate bash completion.""" completion_path = path('contrib/bash/complete') / cli_command_name completion_path.remove() info('Completion exists')
Fix pep8 on articles new man admin: E302 expected 2 blank lines
from django.utils.translation import ugettext_lazy as _ from ella.core.newman_admin import ListingInlineAdmin, PublishableAdmin,\ RelatedInlineAdmin from ella.articles.models import Article import ella_newman class ArticleAdmin(PublishableAdmin): fieldsets = ( (_("Article heading"), {'fields': ('title', )}), (_("Updated, slug"), {'fields': ('last_updated', 'slug',), 'classes': ('collapsed',)}), (_("Metadata"), {'fields': ('photo', 'category', 'authors', 'source')}), (_("Dates"), {'fields': (('publish_from', 'publish_to'), 'static')}), (_("Content"), {'fields': ('description', 'content')}), ) inlines = [ListingInlineAdmin, RelatedInlineAdmin] rich_text_fields = {'small': ('description',), None: ('content',)} ella_newman.site.register(Article, ArticleAdmin)
from django.utils.translation import ugettext_lazy as _ from ella.core.newman_admin import ListingInlineAdmin, PublishableAdmin,\ RelatedInlineAdmin from ella.articles.models import Article import ella_newman class ArticleAdmin(PublishableAdmin): fieldsets = ( (_("Article heading"), {'fields': ('title', )}), (_("Updated, slug"), {'fields': ('last_updated', 'slug',), 'classes': ('collapsed',)}), (_("Metadata"), {'fields': ('photo', 'category', 'authors', 'source')}), (_("Dates"), {'fields': (('publish_from', 'publish_to'), 'static')}), (_("Content"), {'fields': ('description', 'content')}), ) inlines = [ListingInlineAdmin, RelatedInlineAdmin] rich_text_fields = {'small': ('description',), None: ('content',)} ella_newman.site.register(Article, ArticleAdmin)
[geventhttpclient] Remove strong dependency to geventhttpclient>=1.0a We can remove the strong dependency on 1.0a, Deepinder Setia manage this fix in https://bugs.launchpad.net/opencontrail/+bug/1306715 Refs: http://lists.opencontrail.org/pipermail/dev_lists.opencontrail.org/2014-April/000930.html And already merged in Juniper/contrail-third-party#16 And for packaging Juniper/contrail-packages#31
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # from setuptools import setup setup( name='vnc_cfg_api_server', version='0.1dev', packages=[ 'vnc_cfg_api_server', 'vnc_cfg_api_server.gen', ], package_data={'': ['*.html', '*.css', '*.xml']}, zip_safe=False, long_description="VNC Configuration API Server Implementation", install_requires=[ 'lxml>=2.3.2', 'gevent==0.13.6', 'geventhttpclient>=1.0a', 'pycassa>=1.7.2', 'netaddr>=0.7.5', 'bitarray==0.8.0', 'psutil==0.4.1', ], entry_points = { 'console_scripts' : [ 'contrail-api = vnc_cfg_api_server.vnc_cfg_api_server:server_main', ], }, )
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # from setuptools import setup setup( name='vnc_cfg_api_server', version='0.1dev', packages=[ 'vnc_cfg_api_server', 'vnc_cfg_api_server.gen', ], package_data={'': ['*.html', '*.css', '*.xml']}, zip_safe=False, long_description="VNC Configuration API Server Implementation", install_requires=[ 'lxml>=2.3.2', 'gevent==0.13.6', 'geventhttpclient==1.0a', 'pycassa>=1.7.2', 'netaddr>=0.7.5', 'bitarray==0.8.0', 'psutil==0.4.1', ], entry_points = { 'console_scripts' : [ 'contrail-api = vnc_cfg_api_server.vnc_cfg_api_server:server_main', ], }, )
Add editorial improvements to CSS ontology generation Implements suggestions in https://github.com/w3c/webref/pull/327
// Convert JSON on CVSS to Turtle for Css property namespace const cssData = require( '../ed/css/CSS.json') // console.log(JSON.stringify(cssData).slice(0,100)) function camelCasify (str) { var result = str[0] for (let i=1; i < str.length; i++) { result += str[i-1] === '-' ? str[i].toUpperCase() : str[i] } return result.replace('-','') } console.log(`@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>. @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>. @prefix css: <http://www.w3.org/ns/css#> . <> rdfs:comment """This ontology allows CSS properties to be expressed in RDF. The same camelcase convention is used as is used by the subproperties of the style property in browser JS implementations. """ . `) for (const prop in cssData.properties) { const camel = cssData.properties[prop].styleDeclaration.pop() // console.log(` Property ${prop} - ${camel}`) console.log(`css:${camel} a rdf:Property; rdfs:label "${prop}"; spec:values`) }
// Convert JSON on CVSS to Turtle for Css property namespace const cssData = require( '../ed/css/CSS.json') // console.log(JSON.stringify(cssData).slice(0,100)) function camelCasify (str) { var result = str[0] for (let i=1; i < str.length; i++) { result += str[i-1] === '-' ? str[i].toUpperCase() : str[i] } return result.replace('-','') } console.log(`@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>. @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>. @prefix css: <http://www.w3.org/ns/css#> . <> rdfs:comment """This ontology allows CSS properties to be expressed in RDF. The same camelcase convention is usede as is used by the subproperties of the style property in browser JS implementations. """ . `) for (const prop in cssData.properties) { const camel = camelCasify(prop) // console.log(` Property ${prop} - ${camel}`) console.log(`css:${camel} a rdf:Property; rdfs:label "${prop}"; spec:values`) }
Fix "isWindows is not a function" on electron Fix "isWindows is not a function" on electron
/*! * global-prefix <https://github.com/jonschlinkert/global-prefix> * * Copyright (c) 2015 Jon Schlinkert. * Licensed under the MIT license. */ 'use strict'; /** * This is the code used internally by npm to * resolve the global prefix. */ var isWindows = require('is-windows'); var path = require('path'); var prefix; if (process.env.PREFIX) { prefix = process.env.PREFIX; } else if (isWindows === true || isWindows()) { // c:\node\node.exe --> prefix=c:\node\ prefix = path.dirname(process.execPath); } else { // /usr/local/bin/node --> prefix=/usr/local prefix = path.dirname(path.dirname(process.execPath)); // destdir only is respected on Unix if (process.env.DESTDIR) { prefix = path.join(process.env.DESTDIR, prefix); } } module.exports = prefix;
/*! * global-prefix <https://github.com/jonschlinkert/global-prefix> * * Copyright (c) 2015 Jon Schlinkert. * Licensed under the MIT license. */ 'use strict'; /** * This is the code used internally by npm to * resolve the global prefix. */ var isWindows = require('is-windows'); var path = require('path'); var prefix; if (process.env.PREFIX) { prefix = process.env.PREFIX; } else if (isWindows()) { // c:\node\node.exe --> prefix=c:\node\ prefix = path.dirname(process.execPath); } else { // /usr/local/bin/node --> prefix=/usr/local prefix = path.dirname(path.dirname(process.execPath)); // destdir only is respected on Unix if (process.env.DESTDIR) { prefix = path.join(process.env.DESTDIR, prefix); } } module.exports = prefix;
Revert "bump version for impending release" This reverts commit c9c46f1bd4593cd1b13df404b2dba89c75c4f1ec.
from setuptools import setup import sys setup( # Basic package information. name = 'zdesk', author = 'Brent Woodruff', version = '2.3.0', author_email = 'brent@fprimex.com', packages = ['zdesk'], include_package_data = True, install_requires = ['requests'], license='LICENSE.txt', url = 'https://github.com/fprimex/zdesk', keywords = 'zendesk api helpdesk', description = 'Zendesk API generated directly from developer.zendesk.com', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
from setuptools import setup import sys setup( # Basic package information. name = 'zdesk', author = 'Brent Woodruff', version = '2.4.0', author_email = 'brent@fprimex.com', packages = ['zdesk'], include_package_data = True, install_requires = ['requests'], license='LICENSE.txt', url = 'https://github.com/fprimex/zdesk', keywords = 'zendesk api helpdesk', description = 'Zendesk API generated directly from developer.zendesk.com', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Drop the UUID; just use urandom
# Sample untracked-keys file # If you get errors trying to 'import apikeys', do the following: # 1) Copy this file to apikeys.py (keeping it in the package directory) # 2) Replace all of the example values with real ones # 3) Generate your own cookie key, possibly using urandom as per below # You should then be able to start the server. db_connect_string = "" cookie_monster = "uqHHRiRIUyCIcB0RJJcv+T/Qc3wJS0p/jsyE1x36qBIa" # Generated like this: # import base64, os; print(base64.b64encode(os.urandom(33))) # These settings are used only for the sending of emails. The server will # start with them at the defaults, but all email sending will fail. system_email = 'server@example.com' admin_email = 'username@example.com' # Will use default settings if SMTP_SERVER_PORT == 'localhost' SMTP_SERVER_PORT = "smtp.gmail.com:587" SMTP_USERNAME = "email@gmail.com" SMTP_PASSWORD = "yourpassword"
# Sample untracked-keys file # If you get errors trying to 'import apikeys', do the following: # 1) Copy this file to apikeys.py (keeping it in the package directory) # 2) Replace all of the example values with real ones # 3) Generate your own cookie key, possibly using urandom as per below # You should then be able to start the server. db_connect_string = "" cookie_monster = "llsfZyohQDa4kRdCCqnoV3gpD8jaHUY0kfkKI3pZlZ4=" # in Python you can generate like this: # import base64 # import uuid # print(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)) # Thanks to https://gist.github.com/didip/823887 # Alternative way to generate a similar-length nonce: # import base64, os; print(base64.b64encode(os.urandom(33))) # These settings are used only for the sending of emails. The server will # start with them at the defaults, but all email sending will fail. system_email = 'server@example.com' admin_email = 'username@example.com' # Will use default settings if SMTP_SERVER_PORT == 'localhost' SMTP_SERVER_PORT = "smtp.gmail.com:587" SMTP_USERNAME = "email@gmail.com" SMTP_PASSWORD = "yourpassword"
Make all value strings numbers, for real this time closes #1 [ci skip]
'use strict'; var MongoClient = require('mongodb').MongoClient; var dbURL = process.env.MONGOLAB_URI || 'mongodb://localhost:27017/openAQ'; MongoClient.connect(dbURL, function (err, db) { if (err) { return console.error(err); } console.info('Connected to database.'); // Find values that are stored as string and convert to numbers var measurementsCollection = db.collection('measurements'); var bulk = measurementsCollection.initializeUnorderedBulkOp(); measurementsCollection.find({value: {$type: 2}}).toArray(function (e, ms) { ms.forEach(function (m) { var number = Number(m.value); bulk.find({_id: m._id}).updateOne({$set: {value: number}}); }); bulk.execute(function (err, result) { if (err) { console.error(err); return db.close(); } console.info('Measurements updated:', result.nModified); return db.close(); }); }); });
'use strict'; var MongoClient = require('mongodb').MongoClient; var dbURL = process.env.MONGOLAB_URI || 'mongodb://localhost:27017/openAQ'; var measurementsCollection; MongoClient.connect(dbURL, function (err, db) { if (err) { return console.error(err); } console.info('Connected to database.'); // Get collection and ensure indexes measurementsCollection = db.collection('measurements'); measurementsCollection.find({}).toArray(function (e, ms) { for (var i = 0; i < ms.length; i++) { var m = ms[i]; if (typeof m.value !== 'number') { console.info('Saving new value: ', i + 1); m.value = Number(m.value); measurementsCollection.save(m); } } db.close(); }); });
Remove unnecesary endianness from attribute type writer
package radius import "io" // AttributeType defines types for an Attribute type AttributeType int64 const ( // Attributes for RFC2866/Radius accounting AccountingStatusType AttributeType = 40 AccountingDelayTime AttributeType = 41 AccountingInputOctets AttributeType = 42 AccountingOutputOctets AttributeType = 43 AccountingSessionID AttributeType = 44 AccountingAuthentic AttributeType = 45 AccountingSessionTime AttributeType = 46 AccountingInputPackets AttributeType = 47 AccountingOutputPackets AttributeType = 48 AccountingTerminateCause AttributeType = 49 AccountingMultiSessionID AttributeType = 50 AccountingMultiLinkCount AttributeType = 51 // -- ) // Write writes the attribute type to the given writer func (a AttributeType) Write(w io.Writer) error { _, err := w.Write([]byte{byte(a)}) return err }
package radius import ( "encoding/binary" "io" ) // AttributeType defines types for an Attribute type AttributeType int64 const ( // Attributes for RFC2866/Radius accounting AccountingStatusType AttributeType = 40 AccountingDelayTime AttributeType = 41 AccountingInputOctets AttributeType = 42 AccountingOutputOctets AttributeType = 43 AccountingSessionID AttributeType = 44 AccountingAuthentic AttributeType = 45 AccountingSessionTime AttributeType = 46 AccountingInputPackets AttributeType = 47 AccountingOutputPackets AttributeType = 48 AccountingTerminateCause AttributeType = 49 AccountingMultiSessionID AttributeType = 50 AccountingMultiLinkCount AttributeType = 51 // -- ) // Write writes the attribute type to the given writer func (a AttributeType) Write(w io.Writer) error { return binary.Write(w, binary.BigEndian, int8(a)) }
Stop bear island triggering on plots and crashing. We need to rethink whether or not we should be raising cardEntersPlay for plots
const DrawCard = require('../../../drawcard.js'); class BearIsland extends DrawCard { setupCardAbilities(ability) { this.reaction({ when: { onCardEntersPlay: (event, card) => card.getType() !== 'plot' && card.controller === this.controller && card.isLoyal() && this.game.currentPhase === 'marshal' }, limit: ability.limit.perPhase(2), handler: () => { this.game.addGold(this.controller, 1); this.game.addMessage('{0} uses {1} to gain 1 gold', this.controller, this); } }); } } BearIsland.code = '04042'; module.exports = BearIsland;
const DrawCard = require('../../../drawcard.js'); class BearIsland extends DrawCard { setupCardAbilities(ability) { this.reaction({ when: { onCardEntersPlay: (event, card) => card.controller === this.controller && card.isLoyal() && this.game.currentPhase === 'marshal' }, limit: ability.limit.perPhase(2), handler: () => { this.game.addGold(this.controller, 1); this.game.addMessage('{0} uses {1} to gain 1 gold', this.controller, this); } }); } } BearIsland.code = '04042'; module.exports = BearIsland;
Fix bug introduced in previous commit.
/** * Copyright 2014 Ian Davies * * 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. */ define([], function() { var PageController = ['$scope', 'auth', 'api', function($scope, auth, api) { $scope.contentVersion = api.contentVersion.get(); $scope.$watch("contentVersion.liveVersion", function() { $scope.versionChange = null; }); $scope.setVersion = function() { $scope.versionChange = "IN_PROGRESS" api.contentVersion.set({version: $scope.contentVersion.liveVersion}, {}).$promise.then(function(data) { $scope.contentVersion = api.contentVersion.get(); $scope.contentVersion.$promise.then(function() { $scope.versionChange = "SUCCESS" }); }).catch(function(e) { console.error(e); $scope.versionChange = "ERROR" }); } }] return { PageController: PageController, }; })
/** * Copyright 2014 Ian Davies * * 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. */ define([], function() { var PageController = ['$scope', 'auth', 'api', function($scope, auth, api) { $scope.contentVersion = api.contentVersion.get(); $scope.$watch("contentVersion.liveVersion", function() { $scope.versionChange = null; }); $scope.setVersion = function() { $scope.versionChange = "IN_PROGRESS" api.contentVersion.set({version: $scope.contentVersion.liveVersion}, {}).$promise.then(function(data) { $scope.contentVersion = api.contentVersion.get().$promise.then(function() { $scope.versionChange = "SUCCESS" }); }).catch(function(e) { console.error(e); $scope.versionChange = "ERROR" }); } }] return { PageController: PageController, }; })
Allow for underscores in magic method names
<?php /* * This file is part of Feefo. * * (c) Blue Bay Travel <developers@bluebaytravel.co.uk> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace BlueBayTravel\Feefo; class FeefoItem { /** * Array of data. * * @var array */ protected $data = []; /** * Create a new feefo item instance. * * @param array $data * * @return void */ public function __construct(array $data) { $this->data = $data; } /** * Magic method to get back from Feefo item. * * @param string $key * * @return mixed */ public function __get($key) { $safeKey = str_replace('_', '', strtoupper($key)); if (isset($data[$safeKey])) { return $data[$safeKey]; } } }
<?php /* * This file is part of Feefo. * * (c) Blue Bay Travel <developers@bluebaytravel.co.uk> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace BlueBayTravel\Feefo; class FeefoItem { /** * Array of data. * * @var array */ protected $data = []; /** * Create a new feefo item instance. * * @param array $data * * @return void */ public function __construct(array $data) { $this->data = $data; } /** * Magic method to get back from Feefo item. * * @param string $key * * @return mixed */ public function __get($key) { $safeKey = strtoupper($key); if (isset($data[$safeKey])) { return $data[$safeKey]; } } }
Fix for one line HTTP responses
package io.reon.http; import java.io.IOException; import java.io.InputStream; public class ResponseReader extends MessageReader { public ResponseReader(InputStream is) { super(is); } public Response read() throws IOException { Response resp = parse(readHeader()); if (resp == null) return null; return ResponseBuilder.with(resp).withBody(input).build(); } public static Response parse(String req) throws HttpBadRequestException { if (req == null || req.length() == 0) return null; String[] lines = req.split("\\r\\n", 2); String[] segments = lines[0].split(" "); String protocolVersion = segments[0]; StatusCode sc = StatusCode.byValue(Integer.parseInt(segments[1])); String reason = null; if(segments.length>=3) { reason = lines[0].substring(lines[0].indexOf(segments[2])); } Headers headers; if (lines.length > 1) { headers = Headers.parse(lines[1]); } else { headers = new Headers(); } return new Response(protocolVersion, sc, reason, headers); } }
package io.reon.http; import java.io.IOException; import java.io.InputStream; public class ResponseReader extends MessageReader { public ResponseReader(InputStream is) { super(is); } public Response read() throws IOException { Response resp = parse(readHeader()); if (resp == null) return null; return ResponseBuilder.with(resp).withBody(input).build(); } public static Response parse(String req) throws HttpBadRequestException { if (req == null || req.length() == 0) return null; String[] lines = req.split("\\r\\n", 2); String[] segments = lines[0].split(" "); String protocolVersion = segments[0]; StatusCode sc = StatusCode.byValue(Integer.parseInt(segments[1])); String reason = null; if(segments.length>=3) { reason = lines[0].substring(lines[0].indexOf(segments[2])); } Headers headers = Headers.parse(lines[1]); return new Response(protocolVersion, sc, reason, headers); } }
Add sqs to list of supported drivers Just forgotten I presume.
<?php return array( /* |-------------------------------------------------------------------------- | Default Queue Driver |-------------------------------------------------------------------------- | | The Laravel queue API supports a variety of back-ends via an unified | API, giving you convenient access to each back-end using the same | syntax for each one. Here you may set the default queue driver. | | Supported: "sync", "beanstalkd", "sqs" | */ 'default' => 'sync', /* |-------------------------------------------------------------------------- | Queue Connections |-------------------------------------------------------------------------- | | Here you may configure the connection information for each server that | is used by your application. A default configuration has been added | for each back-end shipped with Laravel. You are free to add more. | */ 'connections' => array( 'sync' => array( 'driver' => 'sync', ), 'beanstalkd' => array( 'driver' => 'beanstalkd', 'host' => 'localhost', 'queue' => 'default', ), 'sqs' => array( 'driver' => 'sqs', 'key' => 'your-public-key', 'secret' => 'your-secret-key', 'queue' => 'your-queue-url', 'region' => 'us-east-1', ), ), );
<?php return array( /* |-------------------------------------------------------------------------- | Default Queue Driver |-------------------------------------------------------------------------- | | The Laravel queue API supports a variety of back-ends via an unified | API, giving you convenient access to each back-end using the same | syntax for each one. Here you may set the default queue driver. | | Supported: "sync", "beanstalkd" | */ 'default' => 'sync', /* |-------------------------------------------------------------------------- | Queue Connections |-------------------------------------------------------------------------- | | Here you may configure the connection information for each server that | is used by your application. A default configuration has been added | for each back-end shipped with Laravel. You are free to add more. | */ 'connections' => array( 'sync' => array( 'driver' => 'sync', ), 'beanstalkd' => array( 'driver' => 'beanstalkd', 'host' => 'localhost', 'queue' => 'default', ), 'sqs' => array( 'driver' => 'sqs', 'key' => 'your-public-key', 'secret' => 'your-secret-key', 'queue' => 'your-queue-url', 'region' => 'us-east-1', ), ), );
Fix to redirect to homepage when no referer is defined
<?php /** * Created by Amal Raghav <amal.raghav@gmail.com> * Date: 11/06/11 */ namespace Flock\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Extra; use Symfony\Component\HttpFoundation\Request; /** * @Extra\Route("/auth") */ class AuthController extends Controller { /** * @Extra\Route("/login", name="flock_login") * @return \Symfony\Bundle\FrameworkBundle\Controller\Response */ public function indexAction() { return $this->render('FlockMainBundle:Default:index.html.twig', array()); } /** * @Extra\Route("/twitter", name="twitter_auth") * * @param \Symfony\Component\HttpFoundation\Request $request * @return void */ public function twitterAction(Request $request) { $redirectTo = $request->headers->get('referer') ?: '/'; return new RedirectResponse($redirectTo); } }
<?php /** * Created by Amal Raghav <amal.raghav@gmail.com> * Date: 11/06/11 */ namespace Flock\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Extra; use Symfony\Component\HttpFoundation\Request; /** * @Extra\Route("/auth") */ class AuthController extends Controller { /** * @Extra\Route("/login", name="flock_login") * @return \Symfony\Bundle\FrameworkBundle\Controller\Response */ public function indexAction() { return $this->render('FlockMainBundle:Default:index.html.twig', array()); } /** * @Extra\Route("/twitter", name="twitter_auth") * * @param \Symfony\Component\HttpFoundation\Request $request * @return void */ public function twitterAction(Request $request) { return new RedirectResponse($request->headers->get('referer')); } }
Remove moreover.com as the website no longer exists.
<?php defined('SYSPATH') or die('No direct script access.'); return array( /** * Gzip can dramatically reduce the size of the sitemap. We recommend you use * this option with more than 1,000 entries. Gzipped entries are computed by * appending the .gz extension to the url (sitemap.xml.gz) */ 'gzip' => array ( 'enabled' => TRUE, /* * From 1-9 */ 'level' => 9 ), /** * Array of URLs to ping. This lets the provider know you have updated your * sitemap. sprintf string. */ 'ping' => array ( 'Google' => 'http://www.google.com/webmasters/tools/ping?sitemap=%s', 'Yahoo' => 'http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=%s', 'Ask' => 'http://submissions.ask.com/ping?sitemap=%s', 'Bing' => 'http://www.bing.com/webmaster/ping.aspx?siteMap=%s' ) );
<?php defined('SYSPATH') or die('No direct script access.'); return array( /** * Gzip can dramatically reduce the size of the sitemap. We recommend you use * this option with more than 1,000 entries. Gzipped entries are computed by * appending the .gz extension to the url (sitemap.xml.gz) */ 'gzip' => array ( 'enabled' => TRUE, /* * From 1-9 */ 'level' => 9 ), /** * Array of URLs to ping. This lets the provider know you have updated your * sitemap. sprintf string. */ 'ping' => array ( 'Google' => 'http://www.google.com/webmasters/tools/ping?sitemap=%s', 'Yahoo' => 'http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=%s', 'Ask' => 'http://submissions.ask.com/ping?sitemap=%s', 'Bing' => 'http://www.bing.com/webmaster/ping.aspx?siteMap=%s', 'MoreOver' => 'http://api.moreover.com/ping?u=%s' ) );
Add help_text and required=False to the PIN field
from django import forms class IndexForm(forms.Form): usos_auth_pin = forms.IntegerField( label='USOS Authorization PIN', help_text='If not filled out, then only the cache is used. Note that ' 'this means that some IDs may fail to be looked up.', required=False) id_list = forms.CharField( widget=forms.Textarea, label='ID List', help_text='List of students IDs to query, one per line.') student_id_regex = forms.CharField( label='Student ID regex', help_text='Regular expression used to match the student ID in each ' 'line. If cannot match (or a student is not found in the ' 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'}))
from django import forms class IndexForm(forms.Form): usos_auth_pin = forms.IntegerField(label='USOS Authorization PIN') id_list = forms.CharField( widget=forms.Textarea, label='ID List', help_text='List of students IDs to query, one per line.') student_id_regex = forms.CharField( label='Student ID regex', help_text='Regular expression used to match the student ID in each ' 'line. If cannot match (or a student is not found in the ' 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'}))
Change KMS::Key to accept a standard Tags
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, Tags from .validators import boolean try: from awacs.aws import Policy policytypes = (dict, Policy) except ImportError: policytypes = dict, class Alias(AWSObject): resource_type = "AWS::KMS::Alias" props = { 'AliasName': (basestring, True), 'TargetKeyId': (basestring, True) } class Key(AWSObject): resource_type = "AWS::KMS::Key" props = { 'Description': (basestring, False), 'Enabled': (boolean, False), 'EnableKeyRotation': (boolean, False), 'KeyPolicy': (policytypes, True), 'Tags': ((Tags, list), False) }
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject from .validators import boolean try: from awacs.aws import Policy policytypes = (dict, Policy) except ImportError: policytypes = dict, class Alias(AWSObject): resource_type = "AWS::KMS::Alias" props = { 'AliasName': (basestring, True), 'TargetKeyId': (basestring, True) } class Key(AWSObject): resource_type = "AWS::KMS::Key" props = { 'Description': (basestring, False), 'Enabled': (boolean, False), 'EnableKeyRotation': (boolean, False), 'KeyPolicy': (policytypes, True), 'Tags': (list, False) }
Add default method for finding strings rather than byte[]
// BSD License (http://lemurproject.org/galago-license) package org.lemurproject.galago.core.index; import org.lemurproject.galago.core.retrieval.iterator.BaseIterator; import org.lemurproject.galago.utility.ByteUtil; import java.io.IOException; /** * Each iterator from an index has an extra two methods, * getValueString() and nextKey(), that allows the data from * the index to be easily printed. DumpIndex uses this functionality * to dump the contents of any Galago index. * * (2/22/2011, irmarc): Refactored into the index package to indicate this is functionality * that a disk-based iterator should have. * * @author trevor, irmarc */ public interface KeyIterator extends Comparable<KeyIterator> { // moves iterator to some particular key public boolean findKey(byte[] key) throws IOException; default boolean findKey(String key) throws IOException { return findKey(ByteUtil.fromString(key)); } // moves iterator to a particular key (forward direction only) public boolean skipToKey(byte[] key) throws IOException; // moves iterator to the next key public boolean nextKey() throws IOException; // true if the iterator has moved past the last key public boolean isDone(); // resets iterator to the first key public void reset() throws IOException; // Access to key data public byte[] getKey() throws IOException; public String getKeyString() throws IOException; // Access to the key's value. (Not all may be implemented) public byte[] getValueBytes() throws IOException; public String getValueString() throws IOException; public BaseIterator getValueIterator() throws IOException; }
// BSD License (http://lemurproject.org/galago-license) package org.lemurproject.galago.core.index; import org.lemurproject.galago.core.retrieval.iterator.BaseIterator; import java.io.IOException; /** * Each iterator from an index has an extra two methods, * getValueString() and nextKey(), that allows the data from * the index to be easily printed. DumpIndex uses this functionality * to dump the contents of any Galago index. * * (2/22/2011, irmarc): Refactored into the index package to indicate this is functionality * that a disk-based iterator should have. * * @author trevor, irmarc */ public interface KeyIterator extends Comparable<KeyIterator> { // moves iterator to some particular key public boolean findKey(byte[] key) throws IOException; // moves iterator to a particular key (forward direction only) public boolean skipToKey(byte[] key) throws IOException; // moves iterator to the next key public boolean nextKey() throws IOException; // true if the iterator has moved past the last key public boolean isDone(); // resets iterator to the first key public void reset() throws IOException; // Access to key data public byte[] getKey() throws IOException; public String getKeyString() throws IOException; // Access to the key's value. (Not all may be implemented) public byte[] getValueBytes() throws IOException; public String getValueString() throws IOException; public BaseIterator getValueIterator() throws IOException; }
Fix the cli batch processing yield
'use strict'; var co6 = require('co6'); var fs = co6.promisifyAll(require('fs')); var os = require('os'); var parse = require('./parse'); var server = require('../server'); /* * Run the command line application. */ co6.main(function *() { var options = parse(process.argv); var source = options.source || 'MangaRack.txt'; var tasks = options.args.length ? args(options) : yield batch(source); yield server(tasks, options.workers || os.cpus().length, console.log); console.log('Completed!'); }); /** * Process the arguments. * @param {!Options} options * @return {!Array.<!{address: string, !Options}>} */ function args(options) { var tasks = []; options.args.forEach(function (address) { tasks.push({address: address, options: options}); }); console.log('meh'); return tasks; } /** * Process the batch file. * @param {string} path * @return {!Array.<!{address: string, !Options}>} */ function *batch(path) { var tasks = []; if (!(yield fs.existsAsync(path))) return tasks; (yield fs.readFileAsync(path, 'utf8')).split('\n').forEach(function (n) { var lineOptions = parse(n.split(' ')); lineOptions.args.forEach(function (address) { tasks.push({address: address, options: lineOptions}); }); }); return tasks; }
'use strict'; var co6 = require('co6'); var fs = co6.promisifyAll(require('fs')); var os = require('os'); var parse = require('./parse'); var server = require('../server'); /* * Run the command line application. */ co6.main(function *() { var options = parse(process.argv); var source = options.source || 'MangaRack.txt'; var tasks = options.args.length ? args(options) : yield batch(source); yield server(tasks, options.workers || os.cpus().length, console.log); console.log('Completed!'); }); /** * Process the arguments. * @param {!Options} options * @return {!Array.<!{address: string, !Options}>} */ function args(options) { var tasks = []; options.args.forEach(function (address) { tasks.push({address: address, options: options}); }); console.log('meh'); return tasks; } /** * Process the batch file. * @param {string} filePath * @return {!Array.<!{address: string, !Options}>} */ function *batch(filePath) { var tasks = []; if (!(yield fs.existsAsync(filePath))) return tasks; yield fs.readFileAsync(filePath, 'utf8').split('\n').forEach(function (n) { var lineOptions = parse(n.split(' ')); lineOptions.args.forEach(function (address) { tasks.push({address: address, options: lineOptions}); }); }); return tasks; }
Update karma typescript es6 transform presets
module.exports = function(config) { config.set({ frameworks: ['mocha', 'chai', 'karma-typescript', 'sinon'], browsers: ['ChromeHeadless', 'FirefoxHeadless'], files: [ './node_modules/@webcomponents/webcomponentsjs/bundles/webcomponents-sd-ce.js', { pattern: 'src/*.ts' }, { pattern: 'test/*.ts' }, ], reporters: ['progress', 'karma-typescript'], singleRun: true, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, concurrency: Infinity, preprocessors: { '**/*.ts': ['karma-typescript'], }, karmaTypescriptConfig: { compilerOptions: { target: 'esnext', lib: ['esnext', 'dom'], }, bundlerOptions: { transforms: [require('karma-typescript-es6-transform')({ presets: ['@babel/preset-env'] })], }, }, }); }
module.exports = function(config) { config.set({ frameworks: ['mocha', 'chai', 'karma-typescript', 'sinon'], browsers: ['ChromeHeadless', 'FirefoxHeadless'], files: [ './node_modules/@webcomponents/webcomponentsjs/bundles/webcomponents-sd-ce.js', { pattern: 'src/*.ts' }, { pattern: 'test/*.ts' }, ], reporters: ['progress', 'karma-typescript'], singleRun: true, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, concurrency: Infinity, preprocessors: { '**/*.ts': ['karma-typescript'], }, karmaTypescriptConfig: { compilerOptions: { target: 'esnext', lib: ['esnext', 'dom'], }, bundlerOptions: { transforms: [require('karma-typescript-es6-transform')({ presets: 'env' })], }, }, }); }
Revert removal of @Plugin in test
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.test; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.plugins.Plugin; /** * */ @Plugin(name="ExtendedLevel", category=Level.CATEGORY) public class ExtendedLevels { public static final Level NOTE = Level.forName("NOTE", 350); public static final Level DETAIL = Level.forName("DETAIL", 450); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.test; import org.apache.logging.log4j.Level; /** * */ public class ExtendedLevels { public static final Level NOTE = Level.forName("NOTE", 350); public static final Level DETAIL = Level.forName("DETAIL", 450); }
Add TODO comment for char limits
from django import forms from registration import constants class CompanyForm(forms.Form): company_number = forms.CharField( label='Company number', help_text=('This is the 8-digit number on the company certificate of ' 'incorporation.'), max_length=8, min_length=8, ) class CompanyBasicInfoForm(forms.Form): # TODO: ED-145 # Make sure all fields have char limits once the models are defined company_name = forms.CharField() website = forms.URLField() description = forms.CharField(widget=forms.Textarea) class AimsForm(forms.Form): aim_one = forms.ChoiceField(choices=constants.AIMS) aim_two = forms.ChoiceField(choices=constants.AIMS) class UserForm(forms.Form): name = forms.CharField(label='Full name') email = forms.EmailField(label='Email address') password = forms.CharField(widget=forms.PasswordInput()) terms_agreed = forms.BooleanField() referrer = forms.CharField(required=False, widget=forms.HiddenInput())
from django import forms from registration import constants class CompanyForm(forms.Form): company_number = forms.CharField( label='Company number', help_text=('This is the 8-digit number on the company certificate of ' 'incorporation.'), max_length=8, min_length=8, ) class CompanyBasicInfoForm(forms.Form): company_name = forms.CharField() website = forms.URLField() description = forms.CharField(widget=forms.Textarea) class AimsForm(forms.Form): aim_one = forms.ChoiceField(choices=constants.AIMS) aim_two = forms.ChoiceField(choices=constants.AIMS) class UserForm(forms.Form): name = forms.CharField(label='Full name') email = forms.EmailField(label='Email address') password = forms.CharField(widget=forms.PasswordInput()) terms_agreed = forms.BooleanField() referrer = forms.CharField(required=False, widget=forms.HiddenInput())
Change User Agent to comply with specification
# -*- coding: utf-8 -*- import logging import os import queue import threading listening_port = 8444 send_outgoing_connections = True listen_for_connections = True data_directory = 'minode_data/' source_directory = os.path.dirname(os.path.realpath(__file__)) trusted_peer = None # trusted_peer = ('127.0.0.1', 8444) log_level = logging.INFO magic_bytes = b'\xe9\xbe\xb4\xd9' protocol_version = 3 services = 3 # NODE_NETWORK, NODE_SSL stream = 1 nonce = os.urandom(8) user_agent = b'/MiNode:0.2.1/' timeout = 600 header_length = 24 nonce_trials_per_byte = 1000 payload_length_extra_bytes = 1000 shutting_down = False vector_advertise_queue = queue.Queue() address_advertise_queue = queue.Queue() connections = set() connections_lock = threading.Lock() hosts = set() core_nodes = set() node_pool = set() unchecked_node_pool = set() outgoing_connections = 8 connection_limit = 150 objects = {} objects_lock = threading.Lock()
# -*- coding: utf-8 -*- import logging import os import queue import threading listening_port = 8444 send_outgoing_connections = True listen_for_connections = True data_directory = 'minode_data/' source_directory = os.path.dirname(os.path.realpath(__file__)) trusted_peer = None # trusted_peer = ('127.0.0.1', 8444) log_level = logging.INFO magic_bytes = b'\xe9\xbe\xb4\xd9' protocol_version = 3 services = 3 # NODE_NETWORK, NODE_SSL stream = 1 nonce = os.urandom(8) user_agent = b'MiNode-v0.2.0' timeout = 600 header_length = 24 nonce_trials_per_byte = 1000 payload_length_extra_bytes = 1000 shutting_down = False vector_advertise_queue = queue.Queue() address_advertise_queue = queue.Queue() connections = set() connections_lock = threading.Lock() hosts = set() core_nodes = set() node_pool = set() unchecked_node_pool = set() outgoing_connections = 8 connection_limit = 150 objects = {} objects_lock = threading.Lock()
Use grunt newline logger functions
module.exports = function(grunt) { return { LOG_SUCCESS: 0, LOG_DEBUG: -1, LOG_INFO: -2, LOG_NOTICE: -3, LOG_ERROR: -4, LOG_CRITICAL: -5, log: function(msg, level) { switch ( level ) { case this.LOG_CRITICAL: grunt.fail.fatal(msg); break; case this.LOG_ERROR: grunt.log.errorlns(msg); break; case this.LOG_DEBUG: grunt.verbose.writeln(msg); break; case this.LOG_INFO: grunt.log.writeln(msg); break; case this.LOG_NOTICE: grunt.log.writeln(msg); break; case this.LOG_SUCCESS: grunt.log.oklns(msg); break; } } }; };
module.exports = function(grunt) { return { LOG_SUCCESS: 0, LOG_DEBUG: -1, LOG_INFO: -2, LOG_NOTICE: -3, LOG_ERROR: -4, LOG_CRITICAL: -5, log: function(msg, level) { switch ( level ) { case this.LOG_CRITICAL: grunt.fail.fatal(msg); break; case this.LOG_ERROR: grunt.log.errorlns(msg); break; case this.LOG_DEBUG: grunt.verbose.write(msg); break; case this.LOG_INFO: grunt.log.write(msg); break; case this.LOG_NOTICE: grunt.log.write(msg); break; case this.LOG_SUCCESS: grunt.log.oklns(msg); break; } } }; };
Make 'follow' default home page.
/// <reference path="../typings/angularjs/angular.d.ts"/> angular.module('MyModule', ['ngRoute']); angular.module('MyModule').config(function ($routeProvider) { $routeProvider.when("/main", { controller: "maincontroller", templateUrl: "app/views/main.html" }); $routeProvider.when("/collisions", { controller: "collisioncontroller", templateUrl: "app/views/shapes.html" }); $routeProvider.when("/velocity", { controller: "velocitycontroller", templateUrl: "app/views/shapes.html" }); $routeProvider.when("/ballpit", { controller: "ballpitcontroller", templateUrl: "app/views/ballpit.html" }); $routeProvider.when("/facing", { controller: "facingcontroller", templateUrl: "app/views/facing.html" }); $routeProvider.when("/follow", { controller: "followcontroller", templateUrl: "app/views/follow.html" }); $routeProvider.when("/flock", { controller: "flockcontroller", templateUrl: "app/views/flock.html" }); $routeProvider.otherwise({ redirectTo: "/follow" }); });
/// <reference path="../typings/angularjs/angular.d.ts"/> angular.module('MyModule', ['ngRoute']); angular.module('MyModule').config(function ($routeProvider) { $routeProvider.when("/main", { controller: "maincontroller", templateUrl: "app/views/main.html" }); $routeProvider.when("/collisions", { controller: "collisioncontroller", templateUrl: "app/views/shapes.html" }); $routeProvider.when("/velocity", { controller: "velocitycontroller", templateUrl: "app/views/shapes.html" }); $routeProvider.when("/ballpit", { controller: "ballpitcontroller", templateUrl: "app/views/ballpit.html" }); $routeProvider.when("/facing", { controller: "facingcontroller", templateUrl: "app/views/facing.html" }); $routeProvider.when("/follow", { controller: "followcontroller", templateUrl: "app/views/follow.html" }); $routeProvider.when("/flock", { controller: "flockcontroller", templateUrl: "app/views/flock.html" }); $routeProvider.otherwise({ redirectTo: "/ballpit" }); });
Fix directory disappear while moving
<?php /* Allen Disk 1.4 Copyright (C) 2012~2014 Allen Chou Author: Allen Chou ( http://allenchou.cc ) License: MIT License */ include('config.php'); if(!session_id()) session_start(); $res = $GLOBALS['db']->select('dir',array('id' => $_GET["id"])); if($_SESSION["login"] && $_SESSION["username"] == $res[0]["owner"] && isset($_GET['dir']) && isset($_GET['id'])){ $result = $GLOBALS['db']->update('dir',array('parent' => $_GET['dir']), array('id' => $_GET['id'])); echo json_encode(array( "success" => $result, "message" => $result ? "成功移動。" : "移動失敗。" )); } else { echo json_encode(array( "success" => false, "message" => "你不是資料夾的擁有者。" )); }
<?php /* Allen Disk 1.4 Copyright (C) 2012~2014 Allen Chou Author: Allen Chou ( http://allenchou.cc ) License: MIT License */ include('config.php'); if(!session_id()) session_start(); $res = $GLOBALS['db']->select('dir',array('id' => $_GET["id"])); if($_SESSION["login"] && $_SESSION["username"] == $res[0]["owner"]){ $result = $GLOBALS['db']->update('dir',array('parent' => $_GET['dir']), array('id' => $_GET['id'])); echo json_encode(array( "success" => $result, "message" => $result ? "成功移動。" : "移動失敗。" )); } else { echo json_encode(array( "success" => false, "message" => "你不是資料夾的擁有者。" )); }
Fix CI for logs E2E with v2 manifests
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def get_spec_path(check_root): manifest = json.loads(read_file(path_join(check_root, 'manifest.json'))) assets = manifest.get('assets', {}) if 'integration' in assets: relative_spec_path = assets['integration'].get('configuration', {}).get('spec', '') else: relative_spec_path = assets.get('configuration', {}).get('spec', '') if not relative_spec_path: raise ValueError('No config spec defined') spec_path = path_join(check_root, *relative_spec_path.split('/')) if not file_exists(spec_path): raise ValueError('No config spec found') return spec_path
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def get_spec_path(check_root): manifest = json.loads(read_file(path_join(check_root, 'manifest.json'))) relative_spec_path = manifest.get('assets', {}).get('configuration', {}).get('spec', '') if not relative_spec_path: raise ValueError('No config spec defined') spec_path = path_join(check_root, *relative_spec_path.split('/')) if not file_exists(spec_path): raise ValueError('No config spec found') return spec_path
Install github verison of boto in aws cookbook (for now)
import os from kokki import * # Package("python-boto") Execute("pip install git+http://github.com/boto/boto.git#egg=boto", not_if = 'python -c "import boto"') Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig", only_if = os.path.exists("/usr/lib/pymodules/python2.6/boto")) # Mount volumes and format is necessary for vol in env.config.aws.volumes: env.cookbooks.aws.EBSVolume(vol['volume_id'], availability_zone = env.config.aws.availability_zone, device = vol['device'], action = "attach") if vol.get('fstype'): if vol['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % vol, not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol) if vol.get('mount_point'): Mount(vol['mount_point'], device = vol['device'], fstype = vol.get('fstype'), options = vol.get('fsoptions', ["noatime"]), action = ["mount", "enable"])
from kokki import * Package("python-boto") # Mount volumes and format is necessary for vol in env.config.aws.volumes: env.cookbooks.aws.EBSVolume(vol['volume_id'], availability_zone = env.config.aws.availability_zone, device = vol['device'], action = "attach") if vol.get('fstype'): if vol['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % vol, not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol) if vol.get('mount_point'): Mount(vol['mount_point'], device = vol['device'], fstype = vol.get('fstype'), options = vol.get('fsoptions', ["noatime"]), action = ["mount", "enable"])
Switch void filters to make them work correcty
package in.twizmwaz.cardinal.module.modules.filter.type; import in.twizmwaz.cardinal.GameHandler; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import in.twizmwaz.cardinal.module.modules.filter.parsers.GenericFilterParser; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*; public class VoidFilter extends FilterModule { public VoidFilter(final GenericFilterParser parser) { super(parser.getName()); } @Override public FilterState evaluate(final Object object) { if (object instanceof Block) { Block check = new Location(GameHandler.getGameHandler().getMatchWorld(), ((Block) object).getX(), 0, ((Block) object).getZ()).getBlock(); return check.getType() == Material.AIR ? ALLOW : DENY; } else return ABSTAIN; } }
package in.twizmwaz.cardinal.module.modules.filter.type; import in.twizmwaz.cardinal.GameHandler; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import in.twizmwaz.cardinal.module.modules.filter.parsers.GenericFilterParser; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*; public class VoidFilter extends FilterModule { public VoidFilter(final GenericFilterParser parser) { super(parser.getName()); } @Override public FilterState evaluate(final Object object) { if (object instanceof Block) { Block check = new Location(GameHandler.getGameHandler().getMatchWorld(), ((Block) object).getX(), 0, ((Block) object).getZ()).getBlock(); return check.getType() == Material.AIR ? DENY : ALLOW; } else return ABSTAIN; } }
Use assert to typecheck options param
<?php namespace SearchApi\Builders; use SearchApi\Builders\QueryBuilder; /** * Responsible for building a query string for SolrSearch */ class SolrQueryBuilder implements QueryBuilder { /** * Build a query string from provided search terms and search options. * Returns a query string for a SOLR server. * * @param SearchTerm[]|null $searchTerms Search terms to search * @param SearchApi\Models\SearchOptions|null $options Query options */ function build( $searchTerms, $options = null ) { $keywordStrings = ''; assert( gettype( $options ) === 'NULL' || gettype( $options ) === 'object' ); foreach ( $searchTerms as &$word ) { $keywordStrings = $keywordStrings . $word->value . '%20'; } return '?q=collector%3A(' . $keywordStrings . ')&wt=json&indent=true'; } }
<?php namespace SearchApi\Builders; use SearchApi\Builders\QueryBuilder; /** * Responsible for building a query string for SolrSearch */ class SolrQueryBuilder implements QueryBuilder { /** * Build a query string from provided search terms and search options. * Returns a query string for a SOLR server. * * @param SearchTerm[]|null $searchTerms Search terms to search * @param SearchApi\Models\SearchOptions|null $options Query options */ function build( $searchTerms, $options = null ) { $keywordStrings = ''; error_log( var_dump( $options ) ); foreach ( $searchTerms as &$word ) { $keywordStrings = $keywordStrings . $word->value . '%20'; } return '?q=collector%3A(' . $keywordStrings . ')&wt=json&indent=true'; } }
Return response without calling scripts if the input data is invalid
"use strict" const path = require('path'); const exec = require('child_process').exec; const setSSID = (req, res) => { const ssid = req.body['ssid'].trim(); let responseData = { ssidSetSuccessful : true, msg : 'Successfully set the ssid id to ' + ssid } if (typeof ssid === "undefined" || ssid.length < 1) { responseData.ssidSetSuccessful = false; responseData.msg = "Empty ssid not allowed!"; res.status(200).json(responseData); } const cmd = path.join(__dirname, '../../CDN/modeChange.sh') + ' apmode ' + ssid // executing the bash script for updating SSID exec(cmd, { shell: '/bin/bash' }, (err, stdout, stderr) => { console.log('Error: ' + err); console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if(err) { responseData.ssidSetSuccessful = false; responseData.msg = err; } res.status(200).json(responseData); }); } module.exports = { setSSID }
"use strict" const path = require('path'); const exec = require('child_process').exec; const setSSID = (req, res) => { const ssid = req.body['ssid'].trim(); let responseData = { ssidSetSuccessful : true, msg : 'Successfully set the ssid id to ' + ssid } if (typeof ssid === "undefined" || ssid.length < 1) { responseData.ssidSetSuccessful = false; responseData.msg = "Empty ssid not allowed!"; } const cmd = path.join(__dirname, '../../CDN/modeChange.sh') + ' apmode ' + ssid // executing the bash script for updating SSID exec(cmd, { shell: '/bin/bash' }, (err, stdout, stderr) => { console.log('Error: ' + err); console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if(err) { responseData.ssidSetSuccessful = false; responseData.msg = err; } res.status(200).json(responseData); }); } module.exports = { setSSID }
Use PSR container interface where possible.
<?php declare(strict_types=1); /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015-2019, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\ContentBundle\Translatable; use Darvin\Utils\Locale\LocaleProviderInterface; use Psr\Container\ContainerInterface; /** * Translatable current locale callable */ class CurrentLocaleCallable { /** * @var \Psr\Container\ContainerInterface */ private $container; /** * @param \Psr\Container\ContainerInterface $container DI container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * @return string */ public function __invoke(): string { return $this->getLocaleProvider()->getCurrentLocale(); } /** * @return \Darvin\Utils\Locale\LocaleProviderInterface */ private function getLocaleProvider(): LocaleProviderInterface { return $this->container->get('darvin_utils.locale.provider'); } }
<?php declare(strict_types=1); /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015-2019, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\ContentBundle\Translatable; use Darvin\Utils\Locale\LocaleProviderInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Translatable current locale callable */ class CurrentLocaleCallable { /** * @var \Symfony\Component\DependencyInjection\ContainerInterface */ private $container; /** * @param \Symfony\Component\DependencyInjection\ContainerInterface $container DI container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * @return string */ public function __invoke(): string { return $this->getLocaleProvider()->getCurrentLocale(); } /** * @return \Darvin\Utils\Locale\LocaleProviderInterface */ private function getLocaleProvider(): LocaleProviderInterface { return $this->container->get('darvin_utils.locale.provider'); } }
Allow render_fields to override the default template.
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) if template is None: template = self.template fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): if template is None: template = self.template fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
Remove unnessary line from home page
import React from 'react' import { getSiteProps } from 'react-static' // import logoImg from '../logo.png' export default getSiteProps(() => ( <div> <div id="social-media-links"> <a target="_blank" href="https://www.linkedin.com/in/tanay-prabhudesai-1029b073/"><i className="fa fa-linkedin" aria-hidden="true"></i></a> <a target="_blank" href="https://plus.google.com/+TanayPrabhuDesai"><i className="fa fa-google" aria-hidden="true"></i></a> <a target="_blank" href="https://twitter.com/tanayseven"><i className="fa fa-twitter" aria-hidden="true"></i></a> <a target="_blank" href="https://github.com/tanayseven"><i className="fa fa-github" aria-hidden="true"></i></a> </div> <p>Hi, I'm Tanay PrabhuDesai.</p> <p>I'm a software engineer based in Pune, India.</p> </div> ))
import React from 'react' import { getSiteProps } from 'react-static' // import logoImg from '../logo.png' export default getSiteProps(() => ( <div> <div id="social-media-links"> <a target="_blank" href="https://www.linkedin.com/in/tanay-prabhudesai-1029b073/"><i className="fa fa-linkedin" aria-hidden="true"></i></a> <a target="_blank" href="https://plus.google.com/+TanayPrabhuDesai"><i className="fa fa-google" aria-hidden="true"></i></a> <a target="_blank" href="https://twitter.com/tanayseven"><i className="fa fa-twitter" aria-hidden="true"></i></a> <a target="_blank" href="https://github.com/tanayseven"><i className="fa fa-github" aria-hidden="true"></i></a> </div> <p>Hi, I'm Tanay PrabhuDesai.</p> <p>I'm a software engineer based in Pune, India.</p> <p>This website is generated using <a href="https://github.com/tanayseven/personal_website/">Frozen Flask</a></p> </div> ))
Fix event administration for assist users
<?php namespace Calendar\View\Helper\Cell\Render; use Zend\View\Helper\AbstractHelper; class Event extends AbstractHelper { public function __invoke($user, $event, array $cellLinkParams) { $view = $this->getView(); if ($user && $user->can('admin.event')) { return $view->calendarCellRenderEventForPrivileged($event); } else { $eid = $event->need('eid'); $cellLabel = $event->getMeta('name', '?'); $cellUrl = $view->url('event', ['eid' => $eid]); $cellClass = 'cc-event cc-group-' . $eid; return $view->calendarCellLink($cellLabel, $cellUrl, $cellClass); } } }
<?php namespace Calendar\View\Helper\Cell\Render; use Zend\View\Helper\AbstractHelper; class Event extends AbstractHelper { public function __invoke($user, $event, array $cellLinkParams) { $view = $this->getView(); if ($user && $user->can('admin.events')) { return $view->calendarCellRenderEventForPrivileged($event); } else { $eid = $event->need('eid'); $cellLabel = $event->getMeta('name', '?'); $cellUrl = $view->url('event', ['eid' => $eid]); $cellClass = 'cc-event cc-group-' . $eid; return $view->calendarCellLink($cellLabel, $cellUrl, $cellClass); } } }
Use javascript to force focus on an element, because the action chains seems take no effect!
#--IMPORT_ALL_FROM_FUTURE--# ''' @date 2014-11-16 @author Hong-she Liang <starofrainnight@gmail.com> ''' # Import the global selenium unit, not our selenium . global_selenium = __import__('selenium') import types import time def set_attribute(self, name, value): value = value.replace(r"'", r"\'") # Replace all r"'" with r"\'" value = value.replace("\n", r"\n") value = value.replace("\r", r"\r") value = value.replace("\t", r"\t") script = "arguments[0].setAttribute('%s', '%s');" % (name, value) self._parent.execute_script(script, self) def force_focus(self): self._parent.execute_script("arguments[0].focus();", self); def force_click(self): self._parent.execute_script("arguments[0].click();", self);
#--IMPORT_ALL_FROM_FUTURE--# ''' @date 2014-11-16 @author Hong-she Liang <starofrainnight@gmail.com> ''' # Import the global selenium unit, not our selenium . global_selenium = __import__('selenium') import types import time def set_attribute(self, name, value): value = value.replace(r"'", r"\'") # Replace all r"'" with r"\'" value = value.replace("\n", r"\n") value = value.replace("\r", r"\r") value = value.replace("\t", r"\t") script = "arguments[0].setAttribute('%s', '%s')" % (name, value) self._parent.execute_script(script, self) def force_focus(self): global_selenium.webdriver.ActionChains(self._parent).move_to_element(self).perform() def force_click(self): self._parent.execute_script("arguments[0].click();", self);
Remove autowiring deprecation warning this remove deprecation message (`Autowiring-types are deprecated since Symfony 3.3 and will be removed in 4.0. Use aliases instead.`)
<?php /* * This file is part of the OverblogGraphQLBundle package. * * (c) Overblog <http://github.com/overblog/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Overblog\GraphQLBundle\DependencyInjection\Compiler; use GraphQL\Executor\Promise\PromiseAdapter; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel; class AutowiringTypesPass implements CompilerPassInterface { /** * You can modify the container here before it is dumped to PHP code. * * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { version_compare(Kernel::VERSION, '3.3.0', '>=') ? $container->setAlias(PromiseAdapter::class, 'overblog_graphql.promise_adapter') : $container->findDefinition('overblog_graphql.promise_adapter')->setAutowiringTypes([PromiseAdapter::class]) ; } }
<?php /* * This file is part of the OverblogGraphQLBundle package. * * (c) Overblog <http://github.com/overblog/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Overblog\GraphQLBundle\DependencyInjection\Compiler; use GraphQL\Executor\Promise\PromiseAdapter; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class AutowiringTypesPass implements CompilerPassInterface { /** * You can modify the container here before it is dumped to PHP code. * * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { $container->findDefinition('overblog_graphql.promise_adapter')->setAutowiringTypes([PromiseAdapter::class]); } }
Fix response handling when Content-Type header not present
export default class HttpApi { constructor (prefix = '') { this.prefix = prefix this.opts = { credentials: 'same-origin', headers: new Headers({ 'Content-Type': 'application/json', }) } return this.callApi } callApi = (method, url, opts = {}) => { opts = Object.assign({}, this.opts, opts) opts.method = method if (typeof opts.body === 'object') { opts.body = JSON.stringify(opts.body) } return fetch(`/api/${this.prefix}${url}`, opts) .then(res => { if (res.ok) { const type = res.headers.get('Content-Type') return (type && type.includes('application/json')) ? res.json() : res.text() } // error return res.text().then(txt => { return Promise.reject(new Error(txt)) }) }) } }
export default class HttpApi { constructor (prefix = '') { this.prefix = prefix this.opts = { credentials: 'same-origin', headers: new Headers({ 'Content-Type': 'application/json', }) } return this.callApi } callApi = (method, url, opts = {}) => { opts = Object.assign({}, this.opts, opts) opts.method = method if (typeof opts.body === 'object') { opts.body = JSON.stringify(opts.body) } return fetch(`/api/${this.prefix}${url}`, opts) .then(res => { if (res.status >= 200 && res.status < 300) { // success if (res.headers.get('Content-Type').includes('application/json')) { return res.json() } else { return res } } // error return res.text().then(txt => { return Promise.reject(new Error(txt)) }) }) } }
Use is instead of instanceof to determine if it is an array
import _ from 'lodash' import mergeDefaults from 'merge-defaults' import is from 'is_js' _.mergeDefaults = mergeDefaults class ConfigManager { constructor() { this.Riak = { nodes: ["localhost:8098"] } this.GremlinServer = { port: 8182, host: "localhost", options: {} } } setRiakCluster(nodes) { if(arguments.length === 1 && is.array(nodes)) this.Riak.nodes = nodes else this.Riak.nodes = [].slice.call(arguments) } setGremlinClientConfig(port, host, options) { this.GremlinServer = _.mergeDefaults({ port: port, host: host, options: options } || {}, this.GremlinServer) } } export default new ConfigManager()
import _ from 'lodash' import mergeDefaults from 'merge-defaults' _.mergeDefaults = mergeDefaults class ConfigManager { constructor() { this.Riak = { nodes: ["localhost:8098"] } this.GremlinServer = { port: 8182, host: "localhost", options: {} } } setRiakCluster(nodes) { if(arguments.length === 1 && nodes instanceof Array) this.Riak.nodes = nodes else this.Riak.nodes = [].slice.call(arguments) } setGremlinClientConfig(port, host, options) { this.GremlinServer = _.mergeDefaults({ port: port, host: host, options: options } || {}, this.GremlinServer) } } export default new ConfigManager()
Set tokenpro back to true on logout
var app = angular.module('controller.accounts', ['ionic']); app.controller('AccountsCtrl', function($scope, $state, $window, RequestService, AccountsService, LoadingService) { LoadingService.show(); RequestService .request("GET", '/accounts?all=true', true) .then(function(data) { // Success console.log("Success-Accounts!"); AccountsService.setAccounts(data.accounts); $scope.accounts = data.accounts; LoadingService.hide(); }, function(data) { // Failure alert("Failure-Accounts."); console.log(data); LoadingService.hide(); }); $scope.logOut = function() { delete $window.localStorage.githubtoken; delete $window.localStorage.travistoken; $window.localStorage.travispro = true; $state.go('welcome'); }; });
var app = angular.module('controller.accounts', ['ionic']); app.controller('AccountsCtrl', function($scope, $state, $window, RequestService, AccountsService, LoadingService) { LoadingService.show(); RequestService .request("GET", '/accounts?all=true', true) .then(function(data) { // Success console.log("Success-Accounts!"); AccountsService.setAccounts(data.accounts); $scope.accounts = data.accounts; LoadingService.hide(); }, function(data) { // Failure alert("Failure-Accounts."); console.log(data); LoadingService.hide(); }); $scope.logOut = function() { delete $window.localStorage.githubtoken; delete $window.localStorage.travistoken; delete $window.localStorage.travispro; $state.go('welcome'); }; });
Check for secret_key and secret_value in CI Variable native list js spec
import $ from 'jquery'; import setupNativeFormVariableList from '~/ci_variable_list/native_form_variable_list'; describe('NativeFormVariableList', () => { preloadFixtures('pipeline_schedules/edit.html.raw'); let $wrapper; beforeEach(() => { loadFixtures('pipeline_schedules/edit.html.raw'); $wrapper = $('.js-ci-variable-list-section'); setupNativeFormVariableList({ container: $wrapper, formField: 'schedule', }); }); describe('onFormSubmit', () => { it('should clear out the `name` attribute on the inputs for the last empty row on form submission (avoid BE validation)', () => { const $row = $wrapper.find('.js-row'); expect($row.find('.js-ci-variable-input-key').attr('name')).toBe('schedule[variables_attributes][][secret_key]'); expect($row.find('.js-ci-variable-input-value').attr('name')).toBe('schedule[variables_attributes][][secret_value]'); $wrapper.closest('form').trigger('trigger-submit'); expect($row.find('.js-ci-variable-input-key').attr('name')).toBe(''); expect($row.find('.js-ci-variable-input-value').attr('name')).toBe(''); }); }); });
import $ from 'jquery'; import setupNativeFormVariableList from '~/ci_variable_list/native_form_variable_list'; describe('NativeFormVariableList', () => { preloadFixtures('pipeline_schedules/edit.html.raw'); let $wrapper; beforeEach(() => { loadFixtures('pipeline_schedules/edit.html.raw'); $wrapper = $('.js-ci-variable-list-section'); setupNativeFormVariableList({ container: $wrapper, formField: 'schedule', }); }); describe('onFormSubmit', () => { it('should clear out the `name` attribute on the inputs for the last empty row on form submission (avoid BE validation)', () => { const $row = $wrapper.find('.js-row'); expect($row.find('.js-ci-variable-input-key').attr('name')).toBe('schedule[variables_attributes][][key]'); expect($row.find('.js-ci-variable-input-value').attr('name')).toBe('schedule[variables_attributes][][value]'); $wrapper.closest('form').trigger('trigger-submit'); expect($row.find('.js-ci-variable-input-key').attr('name')).toBe(''); expect($row.find('.js-ci-variable-input-value').attr('name')).toBe(''); }); }); });
Add : Load for redis
#!/usr/bin/python import redis import re import ast def dump_redis(): conn = redis.StrictRedis() out = {} for key in conn.keys(): if re.search(":[0-9]*$", key) is not None: out[key] = conn.smembers(key) #print '"%s":%s' % (key, conn.smembers(key)) else: out[key] = conn.get(key) #print '"%s":%s' % (key, conn.get(key)) # Todo : write dump.py with data = out or use JSON print out return out def load_redis(): conn = redis.StrictRedis() # dump.py should be generated by a previous dump_redis run # you have to name the variable data then. data = {...} from dump import data for key in data: if re.search(":[0-9]*$", key) is not None: conn.sadd(key, data[key]) else: conn.set(key, data[key]) #dump_redis() load_redis()
#!/usr/bin/python import redis import re import ast def dump_redis(): conn = redis.StrictRedis() out = {} for key in conn.keys(): if re.search(":[0-9]*$", key) is not None: out[key] = conn.smembers(key) #print '"%s":%s' % (key, conn.smembers(key)) else: out[key] = conn.get(key) #print '"%s":%s' % (key, conn.get(key)) print out return out def load_redis(): conn = redis.StrictRedis() from dump import data for key in data: if re.search(":[0-9]*$", key) is not None: conn.sadd(key, data[key]) else: conn.set(key, data[key]) #dump_redis() load_redis()
Use last vowel, instead of first
var isVowel = require('is-vowel'); var khaan = module.exports = { splitAtVowels: function ( word ) { var output = []; var current = ''; for ( var i = 0; i < word.length; i++ ) { var c = word[i]; if ( isVowel( c ) ) { if ( current !== '' ) { output.push( current ); } current = ''; } current += c; } output.push( current ); return output; }, elongate: function ( word, number ) { word = word ? word : 'khan'; number = number ? number: 2; var arr = this.splitAtVowels( word ); if ( arr.length < 2 ) { return word; } var fin = arr.pop(); var ini = arr.join( '' ); var med = Array( number ).join( fin[0] ); return ini + med + fin; }, khan: function ( word, number ) { word = word ? word : 'khan'; number = number ? number : 5; return this.elongate( word, number).toUpperCase() + '!'; } };
var isVowel = require('is-vowel'); var khaan = module.exports = { splitAtVowels: function ( word ) { var output = []; var current = ''; for ( var i = 0; i < word.length; i++ ) { var c = word[i]; if ( isVowel( c ) ) { if ( current !== '' ) { output.push( current ); } current = ''; } current += c; } output.push( current ); return output; }, elongate: function ( word, number ) { word = word ? word : 'khan'; number = number ? number: 2; var arr = this.splitAtVowels( word ); if ( arr.length < 2 ) { return word; } var ini = arr.shift(); var med = Array( number ).join( arr[0][0] ); var fin = arr.join( '' ); return ini + med + fin; }, khan: function ( word, number ) { word = word ? word : 'khan'; number = number ? number : 5; return this.elongate( word, number).toUpperCase() + '!'; } };
Allow setting channel name parameter on ERR_NOTONCHANNEL
var extend = req('/lib/utilities/extend'), ReplyMessage = req('/lib/messages/reply'), Replies = req('/lib/constants/replies'), NotOnChannelError = req('/lib/errors/not-on-channel'); class NotOnChannelMessage extends ReplyMessage { setChannelName(channel_name) { this.channel_name = channel_name; return this; } getChannelName() { return this.channel_name; } getValuesForParameters() { return { channel_name: this.getChannelName() }; } setValuesFromParameters(parameters) { this.setChannelName(parameters.get('channel_name')); } toError() { return new NotOnChannelError(this.getChannelName()); } } extend(NotOnChannelMessage.prototype, { reply: Replies.ERR_NOTONCHANNEL, abnf: '<channel-name> " :You\'re not on that channel"', channel_name: null }); module.exports = NotOnChannelMessage;
var extend = req('/lib/utilities/extend'), ReplyMessage = req('/lib/messages/reply'), Replies = req('/lib/constants/replies'), NotOnChannelError = req('/lib/errors/not-on-channel'); class NotOnChannelMessage extends ReplyMessage { getValuesForParameters() { return { channel_name: this.getChannelName() }; } setValuesFromParameters(parameters) { this.setChannelName(parameters.get('channel_name')); } toError() { return new NotOnChannelError(this.getChannelName()); } } extend(NotOnChannelMessage.prototype, { reply: Replies.ERR_NOTONCHANNEL, abnf: '<channel-name> " :You\'re not on that channel"' }); module.exports = NotOnChannelMessage;
Make all Handlebars methods static Fixes notice
<?php class Handlebars { static function print_templates() { self::print_results(); self::print_error(); } static function print_results() { ?> <script id="results-template" type="text/x-handlebars-template"> <div class="row"> {{#each results}} <div class="result span6"> <h3>{{title}}</h3> <div class="average">{{average}}%</div> {{#if high}} <div class="range">{{low}} – {{high}}</div> {{/if}} <img src="{{chart}}" class="chart-image" alt="{{average}}"> </div> {{/each}} </div> </script> <?php } static function print_error() { ?> <script id="error-template" type="text/x-handlebars-template"> <div class="row"> <div class="span4 offset4 alert alert-error"><p>Oops, it looks like something went wrong.</p> <p>{{error.message}}</p></div> </div> </script> <?php } }
<?php class Handlebars { static function print_templates() { self::print_results(); self::print_error(); } function print_results() { ?> <script id="results-template" type="text/x-handlebars-template"> <div class="row"> {{#each results}} <div class="result span6"> <h3>{{title}}</h3> <div class="average">{{average}}%</div> {{#if high}} <div class="range">{{low}} – {{high}}</div> {{/if}} <img src="{{chart}}" class="chart-image" alt="{{average}}"> </div> {{/each}} </div> </script> <?php } function print_error() { ?> <script id="error-template" type="text/x-handlebars-template"> <div class="row"> <div class="span4 offset4 alert alert-error"><p>Oops, it looks like something went wrong.</p> <p>{{error.message}}</p></div> </div> </script> <?php } }
Fix capitalization in class name.
<?php use Jenssegers\Mongodb\Model as Eloquent; class Token extends Eloquent { protected $collection = 'tokens'; protected $guarded = array('key'); public static function randomKey($size) { do { $key = openssl_random_pseudo_bytes ( $size , $strongEnough ); } while( !$strongEnough ); $key = str_replace( '+', '', base64_encode($key) ); $key = str_replace( '/', '', $key ); return base64_encode($key); } public static function getInstance() { $token = new Token(); $token->key = Token::randomKey(32); return $token; } public static function userFor($token) { $token = Token::where('key', '=', $token)->first(); if ( empty($token) ) return null; return User::find($token->user_id); } public static function isUserToken( $user_id, $token ) { return Token::where('user_id', '=', $user_id) ->where('key', '=', $token) ->exists(); } }
<?php use Jenssegers\Mongodb\Model as Eloquent; class Token extends ELoquent { protected $collection = 'tokens'; protected $guarded = array('key'); public static function randomKey($size) { do { $key = openssl_random_pseudo_bytes ( $size , $strongEnough ); } while( !$strongEnough ); $key = str_replace( '+', '', base64_encode($key) ); $key = str_replace( '/', '', $key ); return base64_encode($key); } public static function getInstance() { $token = new Token(); $token->key = Token::randomKey(32); return $token; } public static function userFor($token) { $token = Token::where('key', '=', $token)->first(); if ( empty($token) ) return null; return User::find($token->user_id); } public static function isUserToken( $user_id, $token ) { return Token::where('user_id', '=', $user_id) ->where('key', '=', $token) ->exists(); } }
Remove character escape with template string.
function addRandomQuote() { const quotes = [ `Now. Say my name. Heisenberg. You're god damn right`, 'I am the danger.', 'You see, but you do not observe.', 'There’s a woman lying dead. Perfectly sound analysis but I was hoping you’d go deeper.', `You're treading on some mighty thin ice here.` ]; // Pick a random quote. const quote = quotes[Math.floor(Math.random() * quotes.length)]; // Add it to the page. const quoteContainer = document.getElementById('quote-container'); quoteContainer.innerText = quote; } // Image gallery const imageSources = [ 'senya-gorgeous.jpg', 'senya-superman.jpg', 'senya-dissapointed.jpg' ]; let catImage; let imageSelector; function setPhoto() { for (let selector of imageSelector) { if (selector.checked) { catImage.src = 'images/' + imageSources[selector.value]; break; } } } window.onload = function() { catImage = document.getElementById('cat-photo'); imageSelector = document.getElementsByName('cat-photo-id'); for (let selector of imageSelector) { selector.onchange = setPhoto; } setPhoto(); }
function addRandomQuote() { const quotes = [ `Now. Say my name. Heisenberg. You're god damn right`, 'I am the danger.', 'You see, but you do not observe.', 'There’s a woman lying dead. Perfectly sound analysis but I was hoping you’d go deeper.', 'You\'re treading on some mighty thin ice here.' ]; // Pick a random quote. const quote = quotes[Math.floor(Math.random() * quotes.length)]; // Add it to the page. const quoteContainer = document.getElementById('quote-container'); quoteContainer.innerText = quote; } // Image gallery const imageSources = [ 'senya-gorgeous.jpg', 'senya-superman.jpg', 'senya-dissapointed.jpg' ]; let catImage; let imageSelector; function setPhoto() { for (let selector of imageSelector) { if (selector.checked) { catImage.src = 'images/' + imageSources[selector.value]; break; } } } window.onload = function() { catImage = document.getElementById('cat-photo'); imageSelector = document.getElementsByName('cat-photo-id'); for (let selector of imageSelector) { selector.onchange = setPhoto; } setPhoto(); }
Make Google Calendar Answer Generator eligible to be a Quick Link
/*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */ /*global _, HostAdapter, hostAdapter */ function pad(num, length, def) { 'use strict'; return _('' + (num || def)).pad(length, '0'); } function generateResults(recognitionResults, q, context) { 'use strict'; var recognitionResult = recognitionResults['com.solveforall.recognition.date.DateRange']; if (!recognitionResult || (recognitionResult.length === 0)) { console.warn("No recognition result found"); return []; } var dateRange = recognitionResult[0]; var start = dateRange.start; if (!start) { console.warn("No start date found"); return []; } var now = new Date(); var paddedMonth = pad(start.month, 2, now.getMonth() + 1); var paddedDay = pad(start.dayOfMonth, 2, now.getDate()); var year = '' + (start.year || now.getFullYear()); return [{ label: 'Google Calendar', iconUrl: 'http://calendar.google.com/googlecalendar/images/favicon_v2010_8.ico', tooltip: 'View a date in Google Calendar', uri: 'https://www.google.com/calendar/render?tab=mc&date=' + year + paddedMonth + paddedDay, embeddable: false, relevance: dateRange.recognitionLevel }]; }
/*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */ /*global _, HostAdapter, hostAdapter */ function pad(num, length, def) { 'use strict'; return _('' + (num || def)).pad(length, '0'); } function generateResults(recognitionResults, q, context) { 'use strict'; var recognitionResult = recognitionResults['com.solveforall.recognition.date.DateRange']; if (!recognitionResult || (recognitionResult.length === 0)) { console.warn("No recognition result found"); return []; } var dateRange = recognitionResult[0]; var start = dateRange.start; if (!start) { console.warn("No start date found"); return []; } var now = new Date(); var paddedMonth = pad(start.month, 2, now.getMonth() + 1); var paddedDay = pad(start.dayOfMonth, 2, now.getDate()); var year = '' + (start.year || now.getFullYear()); return [{ label: 'Calendar', iconUrl: 'http://calendar.google.com/googlecalendar/images/favicon_v2010_8.ico', summaryHtml: 'Google Calendar', uri: 'https://www.google.com/calendar/render?tab=mc&date=' + year + paddedMonth + paddedDay, embeddable: false, relevance: dateRange.recognitionLevel }]; }
Add ApiKey to Users page in Django Admin
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django_digest.models import PartialDigest, UserNonce from .models import DomainPermissionsMirror, HQApiKey class DDUserNonceAdmin(admin.ModelAdmin): list_display = ('user', 'nonce', 'count', 'last_used_at') class DDPartialDigestAdmin(admin.ModelAdmin): list_display = ('user', 'partial_digest', 'confirmed') search_fields = ('login',) admin.site.register(UserNonce, DDUserNonceAdmin) admin.site.register(PartialDigest, DDPartialDigestAdmin) class ApiKeyInline(admin.TabularInline): model = HQApiKey readonly_fields = ['key', 'created'] extra = 1 class CustomUserAdmin(UserAdmin): inlines = [ ApiKeyInline, ] def has_add_permission(self, request): return False admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) class DomainPermissionsMirrorAdmin(admin.ModelAdmin): list_display = ['source', 'mirror'] list_filter = ['source', 'mirror'] admin.site.register(DomainPermissionsMirror, DomainPermissionsMirrorAdmin)
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django_digest.models import PartialDigest, UserNonce from .models import DomainPermissionsMirror class DDUserNonceAdmin(admin.ModelAdmin): list_display = ('user', 'nonce', 'count', 'last_used_at') class DDPartialDigestAdmin(admin.ModelAdmin): list_display = ('user', 'partial_digest', 'confirmed') search_fields = ('login',) admin.site.register(UserNonce, DDUserNonceAdmin) admin.site.register(PartialDigest, DDPartialDigestAdmin) class CustomUserAdmin(UserAdmin): def has_add_permission(self, request): return False admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) class DomainPermissionsMirrorAdmin(admin.ModelAdmin): list_display = ['source', 'mirror'] list_filter = ['source', 'mirror'] admin.site.register(DomainPermissionsMirror, DomainPermissionsMirrorAdmin)
Add JSX as a resolvable extension
const path = require('path'); const webpack = require('webpack'); module.exports = { context: path.resolve(__dirname), entry: { app: './index.js', }, output: { path: path.resolve(__dirname, './dist'), filename: 'florence.bundle.js', }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } },{ test: /\.jsx$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react', 'es2015'] } }] }, resolve: { // implicitly tell babel to load jsx extensions: ['.js', '.jsx'] } };
const path = require('path'); const webpack = require('webpack'); module.exports = { context: path.resolve(__dirname), entry: { app: './index.js', }, output: { path: path.resolve(__dirname, './dist'), filename: 'florence.bundle.js', }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } },{ test: /\.jsx$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react', 'es2015'] } }] } };
Fix error screen usage assignment
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Icon from './Icon'; import InlineCode from './code/InlineCode'; const Container = styled.div` display: flex; width: 100%; height: 100%; `; const Center = styled.div` margin: auto; color: ${({ theme }) => theme.colors.grayLightText}; text-align: center; `; const Message = styled.div` margin: auto; margin-bottom: 1em; text-align: center; color: inherit; font-size: 1.2em; `; class ErrorScreen extends React.Component { static propTypes = { reason: PropTypes.string, }; static defaultProps = { reason: 'Unknown error', }; render() { return ( <Container> <Center> <Icon size={80} name="attention" /> <Message>We couldn&apos;t load that data</Message> <InlineCode>{this.props.reason}</InlineCode> </Center> </Container> ); } } ErrorScreen.usage = ` # ErrorScreen This is something I (Grant) wrote while testing out some proof of concept UI. It's not approved by UX. Check with UX to see if they want a different error experience. \`\`\` <ErrorScreen reason="404 not found" /> \`\`\` `; export default ErrorScreen;
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Icon from './Icon'; import InlineCode from './code/InlineCode'; const Container = styled.div` display: flex; width: 100%; height: 100%; `; const Center = styled.div` margin: auto; color: ${({ theme }) => theme.colors.grayLightText}; text-align: center; `; const Message = styled.div` margin: auto; margin-bottom: 1em; text-align: center; color: inherit; font-size: 1.2em; `; class ErrorScreen extends React.Component { static propTypes = { reason: PropTypes.string, }; static defaultProps = { reason: 'Unknown error', }; render() { return ( <Container> <Center> <Icon size={80} name="attention" /> <Message>We couldn&apos;t load that data</Message> <InlineCode>{this.props.reason}</InlineCode> </Center> </Container> ); } } ErrorScreen.usage` # ErrorScreen This is something I (Grant) wrote while testing out some proof of concept UI. It's not approved by UX. Check with UX to see if they want a different error experience. \`\`\` <ErrorScreen reason="404 not found" /> \`\`\` `; export default ErrorScreen;
Remove unused scene from unit test
import { GltfLoader, Resource } from "../../Source/Cesium.js"; import { ModelExperimental } from "../../Source/Cesium.js"; describe("Scene/ModelExperimental", function () { var boxTexturedGlbUrl = "./Data/Models/GltfLoader/BoxTextured/glTF-Binary/BoxTextured.glb"; it("initializes from Uint8Array", function () { spyOn(GltfLoader.prototype, "load"); var resource = Resource.createIfNeeded(boxTexturedGlbUrl); var loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function (buffer) { var model = new ModelExperimental({ gltf: new Uint8Array(buffer), }); expect(GltfLoader.prototype.load).toHaveBeenCalled(); model._readyPromise.then(function () { expect(model._sceneGraph).toBeDefined(); expect(model._resourcesLoaded).toEqual(true); }); }); }); });
import { GltfLoader, Resource } from "../../Source/Cesium.js"; import { ModelExperimental } from "../../Source/Cesium.js"; import createScene from "../createScene.js"; describe("Scene/ModelExperimental", function () { var boxTexturedGlbUrl = "./Data/Models/GltfLoader/BoxTextured/glTF-Binary/BoxTextured.glb"; var scene; beforeAll(function () { scene = createScene(); }); it("initializes from Uint8Array", function () { spyOn(GltfLoader.prototype, "load"); var resource = Resource.createIfNeeded(boxTexturedGlbUrl); var loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function (buffer) { var model = new ModelExperimental({ gltf: new Uint8Array(buffer), }); expect(GltfLoader.prototype.load).toHaveBeenCalled(); model._readyPromise.then(function () { expect(model._sceneGraph).toBeDefined(); expect(model._resourcesLoaded).toEqual(true); }); }); }); });
[android] Access modifier fix for android API
package com.mapswithme.maps.api; import android.content.Context; import android.content.Intent; // TODO add javadoc for public interface public class MWMResponse { private MWMPoint mPoint; public MWMPoint getPoint() { return mPoint; } public boolean hasPoint() { return mPoint != null; } @Override public String toString() { return "MWMResponse [mSelectedPoint=" + mPoint + "]"; } public static MWMResponse extractFromIntent(Context context, Intent intent) { final MWMResponse response = new MWMResponse(); // parse status // parse point final double lat = intent.getDoubleExtra(Const.EXTRA_MWM_RESPONSE_POINT_LAT, 0); final double lon = intent.getDoubleExtra(Const.EXTRA_MWM_RESPONSE_POINT_LON, 0); final String name = intent.getStringExtra(Const.EXTRA_MWM_RESPONSE_POINT_NAME); final String id = intent.getStringExtra(Const.EXTRA_MWM_RESPONSE_POINT_ID); response.mPoint = new MWMPoint(lat, lon, name, id); return response; } private MWMResponse() {} }
package com.mapswithme.maps.api; import android.content.Context; import android.content.Intent; // TODO add javadoc for public interface public class MWMResponse { private MWMPoint mPoint; public MWMPoint getPoint() { return mPoint; } public boolean hasPoint() { return mPoint != null; } @Override public String toString() { return "MWMResponse [mSelectedPoint=" + mPoint + "]"; } static MWMResponse extractFromIntent(Context context, Intent intent) { final MWMResponse response = new MWMResponse(); // parse status // parse point final double lat = intent.getDoubleExtra(Const.EXTRA_MWM_RESPONSE_POINT_LAT, 0); final double lon = intent.getDoubleExtra(Const.EXTRA_MWM_RESPONSE_POINT_LON, 0); final String name = intent.getStringExtra(Const.EXTRA_MWM_RESPONSE_POINT_NAME); final String id = intent.getStringExtra(Const.EXTRA_MWM_RESPONSE_POINT_ID); response.mPoint = new MWMPoint(lat, lon, name, id); return response; } private MWMResponse() {} }
Fix hot loading for base theme
// Hot loading HRM Patch import "react-hot-loader/patch" // fetch polyfill import "whatwg-fetch" import metadata from "../src/metadata.js" import routes from "../src/routes.js" import store from "../src/store.js" import phenomicClient from "phenomic/lib/client" phenomicClient({ metadata, routes, store }) // md files processed via phenomic-loader to JSON & generate collection let mdContext = require.context("../content", true, /\.md$/) mdContext.keys().forEach(mdContext) // hot loading if (module.hot) { // hot load md module.hot.accept(mdContext.id, () => { mdContext = require.context("../content", true, /\.md$/) const mdHotUpdater = require("phenomic/lib/client/hot-md").default const requireUpdate = mdHotUpdater(mdContext, window.__COLLECTION__, store) mdContext.keys().forEach(requireUpdate) }) // hot load app module.hot.accept( [ "../src/metadata.js", "../src/routes.js", "../src/store.js" ], () => phenomicClient({ metadata, routes, store }) ) }
// Hot loading HRM Patch import "react-hot-loader/patch" // fetch polyfill import "whatwg-fetch" import metadata from "../src/metadata.js" import routes from "../src/routes.js" import store from "../src/store.js" import phenomicClient from "phenomic/lib/client" phenomicClient({ metadata, routes, store }) // md files processed via phenomic-loader to JSON && generate collection const mdContext = require.context("../content", true, /\.md$/) mdContext.keys().forEach(mdContext) // hot loading if (module.hot) { // hot load md const mdHotUpdater = require("phenomic/lib/client/hot-md").default module.hot.accept(mdContext.id, () => { // mdContext = require.context("../content", true, /\.md$/) const requireUpdate = mdHotUpdater(mdContext, window.__COLLECTION__, store) mdContext.keys().forEach(requireUpdate) }) module.hot.accept( [ "../src/metadata.js", "../src/routes.js", "../src/store.js" ], () => phenomicClient({ metadata, routes, store }) ) }
Fix Minecraft ItemStacks being serialized
package roycurtis.signshopexport.json; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; public class Exclusions implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); // Ignore book page contents return name.equalsIgnoreCase("pages") // Ignore unsupported tags || name.equalsIgnoreCase("unhandledTags") // Ignore redundant data object || name.equalsIgnoreCase("data") // Ignore hide flags || name.equalsIgnoreCase("hideFlag") // Ignore shield patterns || name.equalsIgnoreCase("blockEntityTag"); } @Override public boolean shouldSkipClass(Class<?> clazz) { String name = clazz.getSimpleName(); if ( name.equalsIgnoreCase("ItemStack") ) if ( clazz.getTypeName().startsWith("net.minecraft.server") ) return true; return name.equalsIgnoreCase("ChatComponentText"); } }
package roycurtis.signshopexport.json; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; public class Exclusions implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); // Ignore book page contents return name.equalsIgnoreCase("pages") // Ignore unsupported tags || name.equalsIgnoreCase("unhandledTags") // Ignore redundant data object || name.equalsIgnoreCase("data") // Ignore hide flags || name.equalsIgnoreCase("hideFlag") // Ignore shield patterns || name.equalsIgnoreCase("blockEntityTag"); } @Override public boolean shouldSkipClass(Class<?> clazz) { String name = clazz.getSimpleName(); return name.equalsIgnoreCase("ChatComponentText"); } }
Resolve config from envvar relative to cwd
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from logging import getLogger import os import pwm db = SQLAlchemy() _logger = getLogger('pwm_server') class PWMApp(Flask): def bootstrap(self): """ Initialize database tables for both pwm_server and pwm. """ from .models import Certificate with self.app_context(): db.metadata.create_all(db.engine, tables=[Certificate.__table__, pwm.Domain.__table__]) def create_app(config_file=None): app = PWMApp(__name__) app.config['WTF_CSRF_ENABLED'] = False if config_file: config_path = os.path.join(os.getcwd(), config_file) _logger.debug('Loading config from %s', config_path) else: _logger.debug('Loading config from envvar, file %s', os.environ['PWM_SERVER_CONFIG_FILE']) config_path = os.path.join(os.getcwd(), os.environ['PWM_SERVER_CONFIG_FILE']) app.config.from_pyfile(config_path) from . import views app.register_blueprint(views.mod) db.init_app(app) return app
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from logging import getLogger import os import pwm db = SQLAlchemy() _logger = getLogger('pwm_server') class PWMApp(Flask): def bootstrap(self): """ Initialize database tables for both pwm_server and pwm. """ from .models import Certificate with self.app_context(): db.metadata.create_all(db.engine, tables=[Certificate.__table__, pwm.Domain.__table__]) def create_app(config_file=None): app = PWMApp(__name__) app.config['WTF_CSRF_ENABLED'] = False if config_file: config_path = os.path.join(os.getcwd(), config_file) _logger.debug('Loading config from %s', config_path) app.config.from_pyfile(config_path) else: _logger.debug('Loading config from envvar, file %s', os.environ['PWM_SERVER_CONFIG_FILE']) app.config.from_envvar('PWM_SERVER_CONFIG_FILE') from . import views app.register_blueprint(views.mod) db.init_app(app) return app
Add comment to indexAction in Home controller
<?php namespace App\Controllers; use App\Framework\Mvc\Controller\BasicController; use App\Services\Instagram\InstagramService; class HomeController extends BasicController { /** * Request photos based on hashtag * * @param string $hashtag * @return array */ public function indexAction($hashtag) { // If there is no hashtag parameter, $tag is assigned as "Salvador" $hashtag = (empty($hashtag["_GET"]["hashtag"])) ? "Salvador" : $hashtag["_GET"]["hashtag"]; $this->app->container->singleton('InstagramService', function () { return new InstagramService(); }); $instagram = $this->app->InstagramService; $result = $instagram->getPhotosBasedOnTag($hashtag); // Show hashtag name echo "<b>Hashtag:</b> #" . $hashtag . "<br />"; $result = json_decode($result, true); // Show 20 photos foreach ($result["data"] as $data) { echo "<img src=".$data["images"]["low_resolution"]["url"]." alt=".$data["caption"]["text"].">"; } } }
<?php namespace App\Controllers; use App\Framework\Mvc\Controller\BasicController; use App\Services\Instagram\InstagramService; class HomeController extends BasicController { public function indexAction($hashtag) { // If there is no hashtag parameter, $tag is assigned as "Salvador" $hashtag = (empty($hashtag["_GET"]["hashtag"])) ? "Salvador" : $hashtag["_GET"]["hashtag"]; $this->app->container->singleton('InstagramService', function () { return new InstagramService(); }); $instagram = $this->app->InstagramService; $result = $instagram->getPhotosBasedOnTag($hashtag); // Show hashtag name echo "<b>Hashtag:</b> #" . $hashtag . "<br />"; // Show 20 photos foreach ($result->data as $data) { echo "<img src=".$data->images->low_resolution->url." alt=".$data->caption->text.">"; } } }
Add basic competition object without additional info
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.data; import com.google.auto.value.AutoValue; /** * A summary of a competition the user is in */ @AutoValue public abstract class CompetitionSummary { public static CompetitionSummary create(long id, String competitionName, String organiserName, String organiserEmail, long startDate, long endDate, int rank, int rankYesterday, int netWorth, int amountAvailable) { return new AutoValue_CompetitionSummary(id, competitionName, organiserName, organiserEmail, startDate, endDate, rank, rankYesterday, netWorth, amountAvailable); } public abstract long id(); public abstract String competitionName(); public abstract String organiserName(); public abstract String organiserEmail(); public abstract long startDate(); public abstract long endDate(); public abstract int rank(); public abstract int rankYesterday(); public abstract int netWorth(); public abstract int amountAvailable(); }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.data; /** * A summary of a competition the user is in */ @AutoValue public abstract class CompetitionSummary { public static CompetitionSummary create(long id, String competitionName, String organiserName, String organiserEmail, long startDate, long endDate, int rank, int rankYesterday, int netWorth, int amountAvailable) { return new AutoValue_CompetitionSummary(id, competitionName, organiserName, organiserEmail, startDate, endDate, rank, rankYesterday, netWorth, amountAvailable); } public abstract long id(); public abstract String competitionName(); public abstract String organiserName(); public abstract String organiserEmail(); public abstract long startDate(); public abstract long endDate(); public abstract int rank(); public abstract int netWorth(); public abstract int amountAvailable(); }
Add blacklist to wcloud client
package main import ( "time" ) // Deployment describes a deployment type Deployment struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` ImageName string `json:"image_name"` Version string `json:"version"` Priority int `json:"priority"` State string `json:"status"` LogKey string `json:"-"` } // Config for the deployment system for a user. type Config struct { RepoURL string `json:"repo_url" yaml:"repo_url"` RepoPath string `json:"repo_path" yaml:"repo_path"` RepoKey string `json:"repo_key" yaml:"repo_key"` KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"` Notifications []NotificationConfig `json:"notifications" yaml:"notifications"` // Globs of files not to change, relative to the route of the repo ConfigFileBlackList []string `json:"config_file_black_list" yaml:"config_file_black_list"` } // NotificationConfig describes how to send notifications type NotificationConfig struct { SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"` SlackUsername string `json:"slack_username" yaml:"slack_username"` }
package main import ( "time" ) // Deployment describes a deployment type Deployment struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` ImageName string `json:"image_name"` Version string `json:"version"` Priority int `json:"priority"` State string `json:"status"` LogKey string `json:"-"` } // Config for the deployment system for a user. type Config struct { RepoURL string `json:"repo_url" yaml:"repo_url"` RepoPath string `json:"repo_path" yaml:"repo_path"` RepoKey string `json:"repo_key" yaml:"repo_key"` KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"` Notifications []NotificationConfig `json:"notifications" yaml:"notifications"` } // NotificationConfig describes how to send notifications type NotificationConfig struct { SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"` SlackUsername string `json:"slack_username" yaml:"slack_username"` }
Tweak formatting in Android template Reviewed By: mkonicek Differential Revision:D2812482 Ninja: Doesn't affect any fb apps or code, purely for open source fb-gh-sync-id: 4d190354112e3f002405686769dcc409e3394c3c
package <%= package %>; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import java.util.Arrays; import java.util.List; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "<%= name %>"; } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } }
package <%= package %>; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import java.util.Arrays; import java.util.List; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "<%= name %>"; } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage()); } }
Use name side1 for sidebar slot
<?php /** * This comment block is used just to make IDE suggestions to work * @var $this \Ip\View */ ?> <?php echo $this->subview('_header.php'); ?> <?php if ('search' == $site->getCurrentZoneName()) { $layout = 'singleColumn'; } else { $layout = $this->getThemeOption('layout', 'doubleColumn'); } ?> <div role="main" class="<?php echo $layout ?>"> <div class="main"> <?php echo $this->generateBlock('main')->exampleContent('MAIN'); ?> </div> <?php if ($layout == 'doubleColumn') { ?> <aside> <?php echo $this->generateBlock('side1')->exampleContent('Side1'); ?> </aside> <?php } ?> </div> <?php echo $this->subview('_footer.php'); ?>
<?php /** * This comment block is used just to make IDE suggestions to work * @var $this \Ip\View */ ?> <?php echo $this->subview('_header.php'); ?> <?php if ('search' == $site->getCurrentZoneName()) { $layout = 'singleColumn'; } else { $layout = $this->getThemeOption('layout', 'doubleColumn'); } ?> <div role="main" class="<?php echo $layout ?>"> <div class="main"> <?php echo $this->generateBlock('main')->exampleContent('MAIN'); ?> </div> <?php if ($layout == 'doubleColumn') { ?> <aside> <?php echo $this->generateBlock('main2')->exampleContent('main2'); ?> </aside> <?php } ?> </div> <?php echo $this->subview('_footer.php'); ?>
Use `path` helper for URLConf
import django.views.static from django.conf import settings from django.urls import include, path from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView admin.autodiscover() urlpatterns = [ path('', TemplateView.as_view(template_name='base.html')), path('admin/', admin.site.urls), {%- if cookiecutter.use_djangocms == 'y' %} path('', include('cms.urls')), {%- endif %} ] if settings.DEBUG: import debug_toolbar urlpatterns = [ path('media/<path:path>/', django.views.static.serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), path('__debug__/', include(debug_toolbar.urls)), ] + staticfiles_urlpatterns() + urlpatterns
import django.views.static from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView admin.autodiscover() urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='base.html')), url(r'^admin/', admin.site.urls), {%- if cookiecutter.use_djangocms == 'y' %} url(r'^', include('cms.urls')), {%- endif %} ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^media/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^__debug__/', include(debug_toolbar.urls)), ] + staticfiles_urlpatterns() + urlpatterns