text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Disable security for OPTIONS requests.
package info.agrueneberg.fhir.configurations; import info.agrueneberg.fhir.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .anyRequest().authenticated() .and() .httpBasic(); } }
package info.agrueneberg.fhir.configurations; import info.agrueneberg.fhir.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } }
Set a presence message that's useful
'use strict'; const Discord = require('discord.js'); const client = new Discord.Client(); const winston = require('winston'); require('dotenv').config(); winston.configure({ transports: [ new (winston.transports.Console)({ level: 'debug', timestamp: true, }), new (winston.transports.File)({ filename: 'sgs_bot.log', }), ], }); const channelHandler = require('./event_handlers/channel_handler'); const messageHandler = require('./event_handlers/message_handler'); const presenceHandler = require('./event_handlers/presence_handler'); client.on('ready', () => { winston.log('info', 'Logged into Discord as %s', client.user.tag); // set a useful presence message client.user.setPresence({ status: 'online', afk: false, game: { name: `Ask me for ${process.env.COMMAND_PREFIX}help`, url: '', }, }).then(() => { winston.log('info', 'Presence set.'); }); winston.log('info', 'Using %s as prefix for commands', process.env.COMMAND_PREFIX); }); client.on('voiceStateUpdate', channelHandler.handleVoiceStateUpdate); client.on('message', messageHandler.dispatchMessage); client.on('presenceUpdate', presenceHandler); client.login(process.env.DISCORD_KEY);
'use strict'; const Discord = require('discord.js'); const client = new Discord.Client(); const winston = require('winston'); require('dotenv').config(); winston.configure({ transports: [ new (winston.transports.Console)({ level: 'debug', timestamp: true, }), new (winston.transports.File)({ filename: 'sgs_bot.log', }), ], }); const channelHandler = require('./event_handlers/channel_handler'); const messageHandler = require('./event_handlers/message_handler'); const presenceHandler = require('./event_handlers/presence_handler'); client.on('ready', () => { winston.log('info', 'Logged into Discord as %s', client.user.tag); // set creepy presence client.user.setPresence({ status: 'online', afk: false, game: { name: '100% fresh dank memes', url: '', }, }).then(() => { winston.log('info', 'Presence set.'); }); winston.log('info', 'Using %s as prefix for commands', process.env.COMMAND_PREFIX); }); client.on('voiceStateUpdate', channelHandler.handleVoiceStateUpdate); client.on('message', messageHandler.dispatchMessage); client.on('presenceUpdate', presenceHandler); client.login(process.env.DISCORD_KEY);
Add test for Set constructor
<?php declare(strict_types = 1); namespace Vinnia\Util\Tests; use PHPUnit\Framework\TestCase; use Vinnia\Util\Set; class SetTest extends TestCase { public function testHashesObjects() { $set = new Set(); $a = [1]; $b = [1]; $set->add($a); $this->assertEquals(true, $set->contains($b)); } public function testAddingTheSameValueTwiceDoesNotIncreaseCount() { $set = new Set(1); $this->assertCount(1, $set); $set->add(1); $this->assertCount(1, $set); } public function testNullIsUnique() { $set = new Set(null); $this->assertCount(1, $set); $set->add(null); $this->assertCount(1, $set); } public function testConstructorUsesHashFunction() { $set = new Set(1, 2, 3); $set->add(1); $this->assertCount(3, $set); } }
<?php declare(strict_types = 1); namespace Vinnia\Util\Tests; use PHPUnit\Framework\TestCase; use Vinnia\Util\Set; class SetTest extends TestCase { public function testHashesObjects() { $set = new Set(); $a = [1]; $b = [1]; $set->add($a); $this->assertEquals(true, $set->contains($b)); } public function testAddingTheSameValueTwiceDoesNotIncreaseCount() { $set = new Set(1); $this->assertCount(1, $set); $set->add(1); $this->assertCount(1, $set); } public function testNullIsUnique() { $set = new Set(null); $this->assertCount(1, $set); $set->add(null); $this->assertCount(1, $set); } }
Remove the data-id attribute on HTML export
import DocumentConfigurator from './DocumentConfigurator' import DocumentModel from './DocumentModel' import DocumentJSONConverter from './DocumentJSONConverter' import DocumentHTMLImporter from './DocumentHTMLImporter' import DocumentHTMLExporter from './DocumentHTMLExporter' function importJSON (content) { let doc = new DocumentModel() let jsonConverter = new DocumentJSONConverter() jsonConverter.importDocument(doc, content) return doc } function exportJSON (doc) { let jsonConverter = new DocumentJSONConverter() return jsonConverter.exportDocument(doc) } function importHTML (content) { let htmlImporter = new DocumentHTMLImporter({ configurator: new DocumentConfigurator() }) return htmlImporter.importDocument(content) } function exportHTML (doc) { let htmlExporter = new DocumentHTMLExporter({ configurator: new DocumentConfigurator() }) let html = htmlExporter.exportDocument(doc) html = html.replace(/ data-id=".+?"/g, '') return html } export { importJSON, exportJSON, importHTML, exportHTML }
import DocumentConfigurator from './DocumentConfigurator' import DocumentModel from './DocumentModel' import DocumentJSONConverter from './DocumentJSONConverter' import DocumentHTMLImporter from './DocumentHTMLImporter' import DocumentHTMLExporter from './DocumentHTMLExporter' function importJSON (content) { let doc = new DocumentModel() let jsonConverter = new DocumentJSONConverter() jsonConverter.importDocument(doc, content) return doc } function exportJSON (doc) { let jsonConverter = new DocumentJSONConverter() return jsonConverter.exportDocument(doc) } function importHTML (content) { let htmlImporter = new DocumentHTMLImporter({ configurator: new DocumentConfigurator() }) return htmlImporter.importDocument(content) } function exportHTML (doc) { let htmlExporter = new DocumentHTMLExporter({ configurator: new DocumentConfigurator() }) return htmlExporter.exportDocument(doc) } export { importJSON, exportJSON, importHTML, exportHTML }
Allow RedisBungee to give the console an IOException instead of a unhelpful exception + NPE combo.
/** * Copyright © 2013 tuxed <write@imaginarycode.com> * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */ package com.imaginarycode.minecraft.redisbungee.util; import com.google.common.io.ByteStreams; import com.google.gson.reflect.TypeToken; import com.imaginarycode.minecraft.redisbungee.RedisBungee; import java.io.IOException; import java.lang.reflect.Type; import java.net.URL; import java.net.URLConnection; import java.util.*; public class NameFetcher { public static List<String> nameHistoryFromUuid(UUID uuid) throws IOException { URLConnection connection = new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "").toLowerCase() + "/names").openConnection(); String text = new String(ByteStreams.toByteArray(connection.getInputStream())); Type listType = new TypeToken<List<String>>() {}.getType(); return RedisBungee.getGson().fromJson(text, listType); } }
/** * Copyright © 2013 tuxed <write@imaginarycode.com> * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */ package com.imaginarycode.minecraft.redisbungee.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.net.URL; import java.net.URLConnection; import java.util.*; public class NameFetcher { public static List<String> nameHistoryFromUuid(UUID uuid) { URLConnection connection; try { connection = new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "").toLowerCase() + "/names" ).openConnection(); String text = new Scanner(connection.getInputStream()).useDelimiter("\\Z").next(); Type listType = new TypeToken<List<String>>() { }.getType(); List<String> list = new Gson().fromJson(text, listType); return list; } catch (IOException e) { e.printStackTrace(); } return null; } }
Hide unnecessary elements in main when account "exists" Exists check is a stub for now
package edu.erau.hackriddle.cryptapic; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private EditText userField; private EditText passField; private Button accountButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); userField = (EditText) findViewById(R.id.editUsername); passField = (EditText) findViewById(R.id.editPassword); accountButton = (Button) findViewById(R.id.accountButton); if (keysExist()) { userField.setVisibility(View.GONE); accountButton.setVisibility(View.GONE); } } private boolean keysExist() { return true; //true; TODO real condition-- do keys exist } public void attemptLogin(View view) { //Going to auth later... Intent gallery = new Intent(this, GalleryView.class); startActivity(gallery); } public void recoverAccount(View view) { Intent accountExists = new Intent(this, AccountExists.class); startActivity(accountExists); } }
package edu.erau.hackriddle.cryptapic; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private EditText userField; private EditText passField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void attemptLogin(View view) { //Going to auth later... Intent gallery = new Intent(this, GalleryView.class); startActivity(gallery); } public void recoverAccount(View view) { Intent accountExists = new Intent(this, AccountExists.class); startActivity(accountExists); } }
Set default scenarios directory to within root of project.
import os from django.conf import settings __author__ = 'nreed' url_dict = { 'validate': 'http://127.0.0.1:8000/om_validate/validate/', 'scenarios': getattr(settings, "PROJECT_ROOT", '') + '/scenarios/', 'openmalaria': getattr(settings, "PROJECT_ROOT", '') + '/om_validate/bin/' } def check_dir(local_dir, typ): if local_dir is None or local_dir == '': return url_dict[typ] if os.name == "nt": if not local_dir.endswith('\\'): local_dir += '\\' else: if not local_dir.endswith('/'): local_dir += '/' return local_dir def check_url(url, typ): if url is None or url == '': return url_dict[typ] if not url.endswith('/'): url += '/' return url
import os from django.conf import settings __author__ = 'nreed' url_dict = { 'validate': 'http://127.0.0.1:8000/om_validate/validate/', 'scenarios': '/home/nreed/scenarios/', 'openmalaria': getattr(settings, "PROJECT_ROOT", '') + '/om_validate/bin/' } def check_dir(local_dir, typ): if local_dir is None or local_dir == '': return url_dict[typ] if os.name == "nt": if not local_dir.endswith('\\'): local_dir += '\\' else: if not local_dir.endswith('/'): local_dir += '/' return local_dir def check_url(url, typ): if url is None or url == '': return url_dict[typ] if not url.endswith('/'): url += '/' return url
Make ball bounce off ceiling and floor
package pong; import java.awt.Color; import java.awt.Graphics2D; import java.util.Random; public class Ball { private float x, y; private float angle; private float size; private float speed; private Color color; public Ball() { Random r = new Random(); this.angle = (float) (r.nextFloat() * 2 * Math.PI); this.size = 13; this.speed = 2; this.x = Screen.WIDTH / 2 - this.size / 2; this.y = Screen.HEIGHT / 2 - this.size / 2; this.color = Color.WHITE; } public void draw(Graphics2D g2d) { g2d.setColor(color); g2d.fillRect( (int) this.x, (int) this.y, (int) this.size, (int) this.size); } public void tick() { if (this.x + this.size > Screen.WIDTH) { // game over, one point to left } else if (this.x < 0) { // game over, one point to right } if (this.y + this.size > Screen.HEIGHT || this.y < 0) { this.angle = (float) (Math.PI - this.angle); } float d = this.speed; float dx = (float) (d * Math.sin(this.angle)); float dy = (float) (d * Math.cos(this.angle)); this.x += dx; this.y += dy; } }
package pong; import java.awt.Color; import java.awt.Graphics2D; import java.util.Random; public class Ball { private float x, y; private float angle; private float size; private Color color; public Ball() { Random r = new Random(); this.angle = (float) (r.nextFloat() * 2 * Math.PI); this.size = 13; this.x = Screen.WIDTH / 2 - this.size / 2; this.y = Screen.HEIGHT / 2 - this.size / 2; this.color = Color.WHITE; } public void draw(Graphics2D g2d) { g2d.setColor(color); g2d.fillRect( (int) this.x, (int) this.y, (int) this.size, (int) this.size); } public void tick() { } }
text-effects[depth]: Remove blur if blur radius is 0. This gets rid of visual artifacts that occur when a transform is combined with a blur of radius 0.
/*exported DepthElement*/ var DepthElement = (function() { 'use strict'; function DepthElement( options ) { options = options || {}; this.el = options.el; if ( this.el && typeof this.el === 'string' ) { this.el = document.querySelector( this.el ); } if ( !this.el ) { return; } this.z = options.z; this.setTransform(); } DepthElement.prototype.setTransform = function() { var transform = 'translateZ(' + this.z + 'px)'; this.el.style.webkitTransform = transform; this.el.style.transform = transform; }; DepthElement.prototype.setBlurRadius = function( blurRadius ) { var blur = blurRadius ? 'blur(' + blurRadius + 'px)' : ''; this.el.style.webkitFilter = blur; this.el.style.filter = blur; }; return DepthElement; }) ();
/*exported DepthElement*/ var DepthElement = (function() { 'use strict'; function DepthElement( options ) { options = options || {}; this.el = options.el; if ( this.el && typeof this.el === 'string' ) { this.el = document.querySelector( this.el ); } if ( !this.el ) { return; } this.z = options.z; this.setTransform(); } DepthElement.prototype.setTransform = function() { var transform = 'translateZ(' + this.z + 'px)'; this.el.style.webkitTransform = transform; this.el.style.transform = transform; }; DepthElement.prototype.setBlurRadius = function( blurRadius ) { var blur = 'blur(' + blurRadius + 'px)'; this.el.style.webkitFilter = blur; this.el.style.filter = blur; }; return DepthElement; }) ();
Make locale id a string
<?php /* * This file is part of Laravel Translator. * * (c) Vincent Klaiber <hello@vinkla.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** * This is the locales table seeder class. * * @author Vincent Klaiber <hello@vinkla.com> */ class CreateLocalesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('locales', function (Blueprint $table) { $table->string('id', 2)->index()->primary(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('locales'); } }
<?php /* * This file is part of Laravel Translator. * * (c) Vincent Klaiber <hello@vinkla.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** * This is the locales table seeder class. * * @author Vincent Klaiber <hello@vinkla.com> */ class CreateLocalesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('locales', function (Blueprint $table) { $table->increments('id'); $table->string('language', 2); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('locales'); } }
Test for write new html
var assert = require('assert') var fs = require('fs') var writeNewHtml = require('./../writeNewHtml') describe('writeNewHtml', () => { it('should write html file to wf/',done => { var html = `<!DOCTYPE> <html> <body> <script class="923ad49f0ca1962716d34bd60433de8a207570f7"></script> </body> </html>` fs.mkdir(__dirname + '/wf', err => { writeNewHtml(html, 'test/wf/index'); var wroteHtml = fs.statSync(__dirname + '/wf/index.html').isFile() fs.unlink(__dirname + '/wf/index.html', err => { fs.rmdir(__dirname + '/wf', err => { assert.equal(true, wroteHtml) done() }) }) }) }) })
var assert = require('assert') var fs = require('fs') var writeNewHtml = require('./../writeNewHtml') describe('writeNewHtml', () => { it('should write html file to wf/',done => { var html = `<!DOCTYPE> <html> <body> <script class="923ad49f0ca1962716d34bd60433de8a207570f7"></script> </body> </html>` fs.mkdir(__dirname + '/wf', err => { writeNewHtml(html, 'test/wf/index'); setTimeout(() => { var wroteHtml = fs.statSync(__dirname + '/wt/index.html').isFile() fs.unlink(__dirname + '/wf/index.html', err => { console.log('unlinking...') fs.rmdir(__dirname + '/wf', err => { assert.equal(true, wroteHtml) done() }) }) }, 1500) }) }) })
Delete import that no longer used
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len, strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
Add Vuex to externals on build
/* eslint-env node */ const path = require('path'); module.exports = { context: path.resolve(__dirname, 'src'), entry: './index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'vuex-connect.js', libraryTarget: 'umd' }, resolve: { modulesDirectories: ['node_modules'], extensions: ['', '.js'] }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' } ] }, externals: { vue: { root: 'Vue', commonjs2: 'vue', commonjs: 'vue', amd: 'vue' }, vuex: { root: 'Vuex', commonjs2: 'vuex', commonjs: 'vuex', amd: 'vuex' } } };
/* eslint-env node */ const path = require('path'); module.exports = { context: path.resolve(__dirname, 'src'), entry: './index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'vuex-connect.js', libraryTarget: 'umd' }, resolve: { modulesDirectories: ['node_modules'], extensions: ['', '.js'] }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' } ] }, externals: { vue: { root: 'Vue', commonjs2: 'vue', commonjs: 'vue', amd: 'vue' } } };
Update test to reflect spaces without quotes in dataset.
import sys sys.path.insert(1, "../../") import h2o, tests def length_check(): # Connect to a pre-existing cluster frame = h2o.import_file(path=h2o.locate("smalldata/junit/cars_trim.csv"), col_types=["string","numeric","numeric","numeric","numeric","numeric","numeric","numeric"]) # single column (frame) length_frame = frame["name"].length() assert length_frame[0,0] == 26, "Expected 26, but got {}".format(length_frame[0,0]) assert length_frame[1,0] == 19, "Expected 19, but got {}".format(length_frame[1,0]) assert length_frame[2,0] == 19, "Expected 19, but got {}".format(length_frame[2,0]) # single column (vec) vec = frame["name"] trimmed_vec = vec.trim() length_vec = trimmed_vec.length() assert length_vec[0,0] == 23, "Expected 23, but got {}".format(length_vec[0,0]) assert length_vec[1,0] == 18, "Expected 18, but got {}".format(length_vec[1,0]) assert length_vec[2,0] == 18, "Expected 18, but got {}".format(length_vec[2,0]) if __name__ == "__main__": tests.run_test(sys.argv, length_check)
import sys sys.path.insert(1, "../../") import h2o, tests def length_check(): # Connect to a pre-existing cluster frame = h2o.import_file(path=h2o.locate("smalldata/junit/cars_trim.csv"), col_types=["string","numeric","numeric","numeric","numeric","numeric","numeric","numeric"]) # single column (frame) length_frame = frame["name"].length() assert length_frame[0,0] == 28, "Expected 28, but got {}".format(length_frame[0,0]) assert length_frame[1,0] == 27, "Expected 27, but got {}".format(length_frame[1,0]) assert length_frame[2,0] == 19, "Expected 19, but got {}".format(length_frame[2,0]) # single column (vec) vec = frame["name"] trimmed_vec = vec.trim() length_vec = trimmed_vec.length() assert length_vec[0,0] == 23, "Expected 23, but got {}".format(length_vec[0,0]) assert length_vec[1,0] == 18, "Expected 18, but got {}".format(length_vec[1,0]) assert length_vec[2,0] == 18, "Expected 18, but got {}".format(length_vec[2,0]) if __name__ == "__main__": tests.run_test(sys.argv, length_check)
Update Operation Outcome to include mandatory element
package uk.gov.hscic; import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt; import ca.uhn.fhir.model.dstu2.resource.OperationOutcome; import ca.uhn.fhir.model.dstu2.valueset.IssueSeverityEnum; import ca.uhn.fhir.model.dstu2.valueset.IssueTypeEnum; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; public class OperationOutcomeFactory { private OperationOutcomeFactory() { } public static BaseServerResponseException buildOperationOutcomeException(BaseServerResponseException exception, String code, IssueTypeEnum issueTypeEnum) { CodeableConceptDt codeableConceptDt = new CodeableConceptDt(SystemURL.VS_GPC_ERROR_WARNING_CODE, code) .setText(exception.getMessage()); codeableConceptDt.getCodingFirstRep().setDisplay(code); OperationOutcome operationOutcome = new OperationOutcome(); operationOutcome.addIssue() .setSeverity(IssueSeverityEnum.ERROR) .setCode(issueTypeEnum) .setDetails(codeableConceptDt); operationOutcome.getMeta() .addProfile(SystemURL.SD_GPC_OPERATIONOUTCOME); exception.setOperationOutcome(operationOutcome); return exception; } }
package uk.gov.hscic; import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt; import ca.uhn.fhir.model.dstu2.resource.OperationOutcome; import ca.uhn.fhir.model.dstu2.valueset.IssueSeverityEnum; import ca.uhn.fhir.model.dstu2.valueset.IssueTypeEnum; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; public class OperationOutcomeFactory { private OperationOutcomeFactory() { } public static BaseServerResponseException buildOperationOutcomeException(BaseServerResponseException exception, String code, IssueTypeEnum issueTypeEnum) { CodeableConceptDt codeableConceptDt = new CodeableConceptDt(SystemURL.VS_GPC_ERROR_WARNING_CODE, code) .setText(exception.getMessage()); OperationOutcome operationOutcome = new OperationOutcome(); operationOutcome.addIssue() .setSeverity(IssueSeverityEnum.ERROR) .setCode(issueTypeEnum) .setDetails(codeableConceptDt); operationOutcome.getMeta() .addProfile(SystemURL.SD_GPC_OPERATIONOUTCOME); exception.setOperationOutcome(operationOutcome); return exception; } }
Gather startDate parameter and pass into controller
<?php /** * mbp-logging-reports.php * * A producer to create reports based on logged data in mb-logging-api. */ use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users; date_default_timezone_set('America/New_York'); define('CONFIG_PATH', __DIR__ . '/messagebroker-config'); // Load up the Composer autoload magic require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/mbp-logging-reports.config.inc'; if (isset($_GET['source'])) { $sources[0] = $_GET['source']; } elseif (isset($argv[1])) { $sources[0] = $argv[1]; } if ($sources[0] == 'all') { $sources = [ 'niche', 'afterschool' ]; } if (isset($_GET['startDate'])) { $startDate = $_GET['startDate']; } elseif (isset($argv[2])) { $startDate = $argv[2]; } echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL; try { // Kick off $mbpLoggingReport = new MBP_LoggingReports_Users(); // Gather digest message mailing list $mbpLoggingReport->report('runningMonth', $sources, $startDate); } catch(Exception $e) { echo $e->getMessage(), PHP_EOL; } echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
<?php /** * mbp-logging-reports.php * * A producer to create reports based on logged data in mb-logging-api. */ use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users; date_default_timezone_set('America/New_York'); define('CONFIG_PATH', __DIR__ . '/messagebroker-config'); // Load up the Composer autoload magic require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/mbp-logging-reports.config.inc'; if (isset($_GET['source'])) { $sources[0] = $_GET['source']; } elseif (isset($argv[1])) { $sources[0] = $argv[1]; } if ($sources[0] == 'all') { $sources = [ 'niche', 'afterschool' ]; } echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL; try { // Kick off $mbpLoggingReport = new MBP_LoggingReports_Users(); // Gather digest message mailing list $mbpLoggingReport->report('runningMonth', $sources); } catch(Exception $e) { echo $e->getMessage(), PHP_EOL; } echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
Make the test window bigger in Java.
/** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.tests.java; import playn.core.PlayN; import playn.java.JavaPlatform; import playn.tests.core.TestsGame; public class TestsGameJava { public static void main(String[] args) { JavaPlatform.Config config = new JavaPlatform.Config(); if (args.length > 0) { config.scaleFactor = Float.parseFloat(args[0]); } config.width = 800; config.height = 600; JavaPlatform platform = JavaPlatform.register(config); platform.setTitle("Tests"); PlayN.run(new TestsGame()); } }
/** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.tests.java; import playn.core.PlayN; import playn.java.JavaPlatform; import playn.tests.core.TestsGame; public class TestsGameJava { public static void main(String[] args) { JavaPlatform.Config config = new JavaPlatform.Config(); if (args.length > 0) { config.scaleFactor = Float.parseFloat(args[0]); } JavaPlatform platform = JavaPlatform.register(config); platform.setTitle("Tests"); PlayN.run(new TestsGame()); } }
Address @truncs comment on Generic Type naming
/* * Copyright (c) 2015 Uber Technologies, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.uber.tchannel.api; public interface RequestHandler<RequestT, ResponseT> { ResponseT handle(RequestT request); }
/* * Copyright (c) 2015 Uber Technologies, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.uber.tchannel.api; public interface RequestHandler<REQUEST_TYPE, RESPONSE_TYPE> { RESPONSE_TYPE handle(REQUEST_TYPE request); }
Use protocol relative adzerk url
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.adzerk_url.format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
Fix the Charset to UTF-8
package org.pacey.dropwizardpebble; import com.mitchellbosecke.pebble.PebbleEngine; import com.mitchellbosecke.pebble.error.PebbleException; import io.dropwizard.Configuration; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Locale; public class PebbleViewRenderer<T extends Configuration> implements ViewRenderer<T> { private final PebbleEngineConfigurable<T> pebbleEngineConfigurable; private final TemplateResolver templateResolver; private PebbleEngine pebbleEngine; public PebbleViewRenderer(PebbleEngineConfigurable<T> pebbleEngineConfigurable, TemplateResolver templateResolver) { this.pebbleEngineConfigurable = pebbleEngineConfigurable; this.templateResolver = templateResolver; } public void configure(LifecycleEnvironment lifecycleEnvironment, T configuration) { final PebbleEngine.Builder builder = new PebbleEngine.Builder(); this.pebbleEngine = pebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder); } public void render(PebbleView pebbleView, Locale locale, OutputStream output) throws IOException, PebbleException { try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output, Charset.forName("UTF-8"))) { pebbleEngine.getTemplate(templateResolver.resolve(pebbleView)).evaluate(outputStreamWriter, pebbleView.getContext(), locale); } } }
package org.pacey.dropwizardpebble; import com.mitchellbosecke.pebble.PebbleEngine; import com.mitchellbosecke.pebble.error.PebbleException; import io.dropwizard.Configuration; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Locale; public class PebbleViewRenderer<T extends Configuration> implements ViewRenderer<T> { private final PebbleEngineConfigurable<T> pebbleEngineConfigurable; private final TemplateResolver templateResolver; private PebbleEngine pebbleEngine; public PebbleViewRenderer(PebbleEngineConfigurable<T> pebbleEngineConfigurable, TemplateResolver templateResolver) { this.pebbleEngineConfigurable = pebbleEngineConfigurable; this.templateResolver = templateResolver; } public void configure(LifecycleEnvironment lifecycleEnvironment, T configuration) { final PebbleEngine.Builder builder = new PebbleEngine.Builder(); this.pebbleEngine = pebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder); } public void render(PebbleView pebbleView, Locale locale, OutputStream output) throws IOException, PebbleException { try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output)) { pebbleEngine.getTemplate(templateResolver.resolve(pebbleView)).evaluate(outputStreamWriter, pebbleView.getContext(), locale); } } }
Clear form scope on success
/* global angular */ (function () { "use strict"; angular .module("helloApp.controllers", []) .controller("signUpCtrl", signUpController); signUpController.$inject = ["$scope", "$http", "$log", "toastr"]; function signUpController ($scope, $http, $log, toast) { $scope.doSignup = function (model) { $http.post("/signup", model) .then(function(response) { toast.success("User with id: " + response.data.Id + " created", "Alls ok"); $scope.model = null; }); } $scope.testFunction = function () { return true; }; } })();
/* global angular */ (function () { "use strict"; angular .module("helloApp.controllers", []) .controller("signUpCtrl", signUpController); signUpController.$inject = ["$scope", "$http", "$log", "toastr"]; function signUpController ($scope, $http, $log, toast) { $scope.doSignup = function (model) { $http.post("/signup", model) .then(function(response) { toast.success('User with id: ' + response.data.Id + ' created', 'Alls ok'); }); } $scope.testFunction = function () { return true; }; } })();
Fix secret key generation for superuser created with mangage.py
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) def make_secret_key(): return uuid.uuid4().hex class UserProfile(models.Model): user = models.OneToOneField(User) secret_key = models.CharField(max_length=32, blank=False, default=make_secret_key, help_text='Secret key for feed and API access') class Meta: db_table = 'comics_user_profile' def __unicode__(self): return u'User profile for %s' % self.user def generate_new_secret_key(self): self.secret_key = make_secret_key()
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) class UserProfile(models.Model): user = models.OneToOneField(User) secret_key = models.CharField(max_length=32, blank=False, help_text='Secret key for feed and API access') class Meta: db_table = 'comics_user_profile' def __init__(self, *args, **kwargs): super(UserProfile, self).__init__(*args, **kwargs) if self.secret_key is None: self.generate_new_secret_key() def __unicode__(self): return u'User profile for %s' % self.user def generate_new_secret_key(self): self.secret_key = uuid.uuid4().hex
Comment out returned value annotations
'use strict'; /** * Evaluate the arctangent of the quotient of two numbers. * * @module @stdlib/math/base/special/atan2 * * @example * var v = atan2( 2.0, 2.0 ); // => atan( 1.0 ) * // returns ~0.785 * * v = atan2( 6.0, 2.0 ); // => atan( 3.0 ) * // returns ~1.249 * * v = atan2( -1.0, -1.0 ); // => atan( 1.0 ) - PI * // returns ~-2.356 * * v = atan2( 3.0, 0.0 ); // => PI / 2 * // returns ~1.571 * * v = atan2( -2.0, 0.0 ); // => - PI / 2 * // returns ~-1.571 * * v = atan2( 0.0, 0.0 ); * // returns 0.0 * * v = atan2( 3.0, NaN ); * // returns NaN * * v = atan2( NaN, 2.0 ); * // returns NaN */ // MODULES // var atan2 = require( './atan2.js' ); // EXPORTS // module.exports = atan2;
'use strict'; /** * Evaluate the arctangent of the quotient of two numbers. * * @module @stdlib/math/base/special/atan2 * * @example * var v = atan2( 2.0, 2.0 ); // => atan( 1.0 ) * // returns ~0.785 * * v = atan2( 6.0, 2.0 ); // => atan( 3.0 ) * // returns ~1.249 * * v = atan2( -1.0, -1.0 ); // => atan( 1.0 ) - PI * // returns ~-2.356 * * v = atan2( 3.0, 0.0 ); => PI / 2 * // returns ~1.571 * * v = atan2( -2.0, 0.0 ); => - PI / 2 * // returns ~-1.571 * * v = atan2( 0.0, 0.0 ); * // returns 0.0 * * v = atan2( 3.0, NaN ); * // returns NaN * * v = atan2( NaN, 2.0 ); * // returns NaN */ // MODULES // var atan2 = require( './atan2.js' ); // EXPORTS // module.exports = atan2;
Remove cap letter from generator command option
'use strict'; var CreateTask = require('../../lib/tasks/create-cordova-project'); var camelize = require('../../lib/utils/string.js').camelize; module.exports = { name: 'ember-cordova', availableOptions: [ { name: 'name', type: String }, { name: 'cordovaid', type: String } ], normalizeEntityName: function() { // h/t mirage // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function(options) { var projectName = this.project.name(); var create = new CreateTask({ id: options.cordovaid || camelize(projectName), name: options.name || camelize(projectName), project: this.project, ui: this.ui }); return create.run(); } };
'use strict'; var CreateTask = require('../../lib/tasks/create-cordova-project'); var camelize = require('../../lib/utils/string.js').camelize; module.exports = { name: 'ember-cordova', availableOptions: [ { name: 'name', type: String }, { name: 'cordovaId', type: String } ], normalizeEntityName: function() { // h/t mirage // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function(options) { var projectName = this.project.name(); var create = new CreateTask({ id: options.cordovaId || camelize(projectName), name: options.name || camelize(projectName), project: this.project, ui: this.ui }); return create.run(); } };
Verify is $bean is_subclass_of SugarBean so we can check access
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {suite_check_access} function plugin * * Type: function<br> * Name: suite_check_access<br> * Purpose: Check if the current user has access to a record * * @author Jose C. Massón <jose AT gcoop DOT coop> * @param array * @param Smarty */ function smarty_function_suite_check_access($params, &$smarty) { if (empty($params['module'])) { $smarty->trigger_error("sugar_check_access: missing 'module' parameter"); return; } if (empty($params['record'])) { $smarty->trigger_error("sugar_check_access: missing 'record' parameter"); return; } if (empty($params['action'])) { $smarty->trigger_error("sugar_check_access: missing 'module' parameter"); return; } $ret = false; $bean = BeanFactory::getBean($params['module'], $params['record']); if (is_subclass_of($bean, 'SugarBean')) { $ret = (bool) $bean->ACLAccess($params['action']); } return $ret; }
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {suite_check_access} function plugin * * Type: function<br> * Name: suite_check_access<br> * Purpose: Check if the current user has access to a record * * @author Jose C. Massón <jose AT gcoop DOT coop> * @param array * @param Smarty */ function smarty_function_suite_check_access($params, &$smarty) { if (empty($params['module'])) { $smarty->trigger_error("sugar_check_access: missing 'module' parameter"); return; } if (empty($params['record'])) { $smarty->trigger_error("sugar_check_access: missing 'record' parameter"); return; } if (empty($params['action'])) { $smarty->trigger_error("sugar_check_access: missing 'module' parameter"); return; } $ret = false; $bean = BeanFactory::getBean($params['module'], $params['record']); $ret = (bool) $bean->ACLAccess($params['action']); return $ret; }
Fix imports to work with Python3
"""Portal Service Layer The service layer provides an API on top of Django models to build useful outputs for consumers such as views. This layer helps keep views thin, encourages reusability across views, simplifies testing, and eases separation of concerns for models. Have a look at this example on SO for a high-level example: http://stackoverflow.com/questions/12578908/separation-of-business-logic-and-data-access-in-django/12579490#12579490 I usually implement a service layer in between views and models. This acts like your project's API and gives you a good helicopter view of what is going on. I inherited this practice from a colleague of mine that uses this layering technique a lot with Java projects (JSF), e.g: models.py class Book: author = models.ForeignKey(User) title = models.CharField(max_length=125) class Meta: app_label = "library" services.py from library.models import Book def get_books(limit=None, **filters): simple service function for retrieving books can be widely extended if limit: return Book.objects.filter(**filters)[:limit] return Book.objects.filter(**filters) views.py from library.services import get_books class BookListView(ListView): simple view, e.g. implement a _build and _apply filters function queryset = get_books() """ from .overview import overview from .meterruns_export import meterruns_export
"""Portal Service Layer The service layer provides an API on top of Django models to build useful outputs for consumers such as views. This layer helps keep views thin, encourages reusability across views, simplifies testing, and eases separation of concerns for models. Have a look at this example on SO for a high-level example: http://stackoverflow.com/questions/12578908/separation-of-business-logic-and-data-access-in-django/12579490#12579490 I usually implement a service layer in between views and models. This acts like your project's API and gives you a good helicopter view of what is going on. I inherited this practice from a colleague of mine that uses this layering technique a lot with Java projects (JSF), e.g: models.py class Book: author = models.ForeignKey(User) title = models.CharField(max_length=125) class Meta: app_label = "library" services.py from library.models import Book def get_books(limit=None, **filters): simple service function for retrieving books can be widely extended if limit: return Book.objects.filter(**filters)[:limit] return Book.objects.filter(**filters) views.py from library.services import get_books class BookListView(ListView): simple view, e.g. implement a _build and _apply filters function queryset = get_books() """ from overview import overview from meterruns_export import meterruns_export
Use configured message to show configuration
package org.konstructs.example; import akka.actor.UntypedActor; import akka.actor.Props; import konstructs.plugin.Config; import konstructs.plugin.PluginConstructor; import konstructs.api.SayFilter; import konstructs.api.Say; public class MyPlugin extends UntypedActor { private String responseText; private String pluginName; public MyPlugin(String pluginName, String responseText) { this.responseText = responseText; this.pluginName = pluginName; } public void onReceive(Object message) { if(message instanceof SayFilter) { SayFilter say = (SayFilter)message; String text = say.message().text(); say.continueWith(new Say(text + " <- " + responseText), getSender()); } else { unhandled(message); } } @PluginConstructor public static Props props(String pluginName, @Config(key = "response-text") String responseText) { return Props.create(MyPlugin.class, pluginName, responseText); } }
package org.konstructs.example; import akka.actor.UntypedActor; import akka.actor.Props; import konstructs.plugin.Config; import konstructs.plugin.PluginConstructor; import konstructs.api.SayFilter; import konstructs.api.Say; public class MyPlugin extends UntypedActor { private String responseText; private String pluginName; public MyPlugin(String pluginName, String responseText) { this.responseText = responseText; this.pluginName = pluginName; } public void onReceive(Object message) { if(message instanceof SayFilter) { SayFilter say = (SayFilter)message; String text = say.message().text(); say.continueWith(new Say("Did you just say: " + text + "?"), getSender()); } else { unhandled(message); } } @PluginConstructor public static Props props(String pluginName, @Config(key = "response-text") String responseText) { return Props.create(MyPlugin.class, pluginName, responseText); } }
Fix formatting of error in venv_hook
""" This file serves as a hook into virtualenvs that do NOT have sitetools installed. It is added to the $PYTHONPATH by the `dev` command so that new virtualenvs can refer to the sitetools from the old virtualenv. It tries to play nice by looking for the next sitecustomize module. """ import imp import os import sys import warnings try: try: import sitetools._startup except ImportError: # Pull in the sitetools that goes with this sitecustomize. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Let this ImportError raise. import sitetools._startup except Exception as e: warnings.warn("Error while importing sitetools._startup: %s" % e) # Be a good citizen and find the next sitecustomize module. my_path = os.path.dirname(os.path.abspath(__file__)) clean_path = [x for x in sys.path if os.path.abspath(x) != my_path] try: args = imp.find_module('sitecustomize', clean_path) except ImportError: pass else: imp.load_module('sitecustomize', *args)
""" This file serves as a hook into virtualenvs that do NOT have sitetools installed. It is added to the $PYTHONPATH by the `dev` command so that new virtualenvs can refer to the sitetools from the old virtualenv. It tries to play nice by looking for the next sitecustomize module. """ import imp import os import sys import warnings try: try: import sitetools._startup except ImportError: # Pull in the sitetools that goes with this sitecustomize. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Let this ImportError raise. import sitetools._startup except Exception as e: warnings.warn("Error while importing sitetools._startup: %e" % e) # Be a good citizen and find the next sitecustomize module. my_path = os.path.dirname(os.path.abspath(__file__)) clean_path = [x for x in sys.path if os.path.abspath(x) != my_path] try: args = imp.find_module('sitecustomize', clean_path) except ImportError: pass else: imp.load_module('sitecustomize', *args)
Add backup code in case network is down
#!/usr/bin/env python # `json` is a module that helps us use the JSON data format. import json # `requests` is a module for interacting with the Internet import requests def main(): url = 'https://www.govtrack.us/api/v2/bill?congress=112&order_by=-current_status_date' # Read the `requests` documentation for information. I promise it # isn't that scary. # http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content # Request the data r = requests.get(url) # Since we know our data will be JSON, let's automatically convert # it to a Python dict. data = r.json() # If the network is down, we can use a local version of this # file. #with open('bills.json', 'r') as f: # data = json.load(f) # `json.dumps()` is a way to print a Python dict in a more # human-readable way. print json.dumps(data, indent=4) if __name__ == '__main__': main()
#!/usr/bin/env python # `json` is a module that helps us use the JSON data format. import json # `requests` is a module for interacting with the Internet import requests def main(): url = 'https://www.govtrack.us/api/v2/bill?congress=112&order_by=-current_status_date' # Read the `requests` documentation for information. I promise it # isn't that scary. # http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content # Request the data r = requests.get(url) # Since we know our data will be JSON, let's automatically convert # it to a Python dict. data = r.json() # `json.dumps()` is a way to print a Python dict in a more # human-readable way. print json.dumps(data, indent=4) if __name__ == '__main__': main()
Fix code highlighting in note previews
var updatePreviewTarget = function(data, status) { $('.spinner').hide(); $('#preview-target').html(data); $('#preview-target code').each(function(i, block) { hljs.highlightBlock(block); }); renderLatexExpressions(); } var renderLatexExpressions = function() { $('.latex-container').each( function(index) { katex.render( this.textContent, this, { displayMode: $(this).data('displaymode') == 'block' } ); } ); } var main = function() { $('div code').each(function(i, block) { hljs.highlightBlock(block); }); $('button#preview').click( function() { $('#preview-target').html(''); $('.spinner').show(); $('h1.preview').text($('input[name=title]').val()) $.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget); } ); renderLatexExpressions(); $("textarea[name='footnotes']").focusin(function(){ $(this).height($(this).height() + 300); }).focusout(function(){ $(this).height($(this).height() - 300); }); }; function searchRedirect(event, searchpage) { var term = (arguments.length == 2) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value; window.location = '/search/' + term + '/'; event.preventDefault(event); } $(main);
var updatePreviewTarget = function(data, status) { $('.spinner').hide(); $('#preview-target').html(data); renderLatexExpressions(); } var renderLatexExpressions = function() { $('.latex-container').each( function(index) { katex.render( this.textContent, this, { displayMode: $(this).data('displaymode') == 'block' } ); } ); } var main = function() { $('div code').each(function(i, block) { hljs.highlightBlock(block); }); $('button#preview').click( function() { $('#preview-target').html(''); $('.spinner').show(); $('h1.preview').text($('input[name=title]').val()) $.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget); } ); renderLatexExpressions(); $("textarea[name='footnotes']").focusin(function(){ $(this).height($(this).height() + 300); }).focusout(function(){ $(this).height($(this).height() - 300); }); }; function searchRedirect(event, searchpage) { var term = (arguments.length == 2) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value; window.location = '/search/' + term + '/'; event.preventDefault(event); } $(main);
Add feature: support for pasting structure at a given location
package me.jacobcrofts.simplestructureloader.api; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.bukkit.Location; import org.bukkit.block.Block; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import me.jacobcrofts.simplestructureloader.util.SavedBlock; import me.jacobcrofts.simplestructureloader.util.Selection; public final class StructureAPI { private StructureAPI() {} public static void writeToFile(String path, Selection selection) throws IOException { FileWriter writer = new FileWriter(path); writer.write(selection.toJSON().toJSONString()); writer.close(); } public static JSONArray readFromFile(String path) throws FileNotFoundException, IOException, ParseException { return (JSONArray) new JSONParser().parse(new FileReader(path)); } @SuppressWarnings("deprecation") public static void placeStructure(Selection selection, Location baseLocation) { for (SavedBlock block : selection.getSavedBlocks()) { Block realBlock = baseLocation.add(block.getRelativeX(), block.getRelativeY(), block.getRelativeZ()).getBlock(); realBlock.setType(block.getType()); realBlock.setData(block.getData()); } } }
package me.jacobcrofts.simplestructureloader.api; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import me.jacobcrofts.simplestructureloader.util.Selection; public final class StructureAPI { private StructureAPI() {} public static void writeToFile(String path, Selection selection) throws IOException { FileWriter writer = new FileWriter(path); writer.write(selection.toJSON().toJSONString()); writer.close(); } public static JSONArray readFromFile(String path) throws FileNotFoundException, IOException, ParseException { return (JSONArray) new JSONParser().parse(new FileReader(path)); } public static void placeStructure(Selection selection) { // TODO } }
Test caching with categories API callback (we aren't updating categories anyway).
<?php namespace App\Http\Controllers; use App\Models\Category as Category; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class CategoriesController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index() { $json = \Cache::rememberForever('categories_json', function() { return ['data' => ['categories' => Category::categoryAsc()->get()]]; }); return \Response::json($json); } /** * Get the category JSON by a given category_id * route: api/categories/<category_id> * @param int $category_id * @return json {"success": true or false, "data": {"category": category}}; */ public function show($categoryd) { $category = Category::find($categoryId); if ($category == NULL) { return \Response::json(array("success" => false)); } return \Response::json(["success" => true, "data" => array("category" => $category)]); } }
<?php namespace App\Http\Controllers; use App\Models\Category as Category; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class CategoriesController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index() { return \Response::json(array("data" => array("categories" => Category::categoryAsc()->get()))); } /** * Get the category JSON by a given category_id * route: api/categories/<category_id> * @param int $category_id * @return json {"success": true or false, "data": {"category": category}}; */ public function show($categoryd) { $category = Category::find($categoryId); if ($category == NULL) { return \Response::json(array("success" => false)); } return \Response::json(["success" => true, "data" => array("category" => $category)]); } }
Fix race condition in api causing bad counts in dashboard. A CheckEvent triggers both a refresh of the count in the api and in the dashboard - the dashboard asking the api for a fresher value. When using websockets, the response from MongoDB could happen after the request from the dashboard. The fix forces the dashboard to wait if a refresh was just triggered.
/** * Module dependencies. */ var express = require('express'), Check = require('../../models/check') CheckEvent = require('../../models/checkEvent'); var app = module.exports = express.createServer(); // middleware app.configure(function(){ app.use(app.router); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // up count var upCount; var refreshUpCount = function(callback) { Check.count({}, function(err, total) { Check.count({ isUp: true}, function(err, nbUp) { upCount = { up: nbUp, down: total - nbUp, total: total }; callback(); }); }); } CheckEvent.on('insert', function() { upCount = undefined; }); app.get('/check/count', function(req, res) { if (upCount) { res.json(upCount); } else { refreshUpCount(function() { res.json(upCount); }); } }); // Routes require('./routes/check')(app); require('./routes/tag')(app); require('./routes/ping')(app); if (!module.parent) { app.listen(3000); console.log('Express started on port 3000'); }
/** * Module dependencies. */ var express = require('express'), Check = require('../../models/check') CheckEvent = require('../../models/checkEvent'); var app = module.exports = express.createServer(); // middleware app.configure(function(){ app.use(app.router); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // up count var upCount; var refreshUpCount = function() { Check.count({}, function(err, total) { Check.count({ isUp: true}, function(err, nbUp) { upCount = { up: nbUp, down: total - nbUp, total: total }; }); }); } refreshUpCount(); CheckEvent.on('insert', refreshUpCount); app.get('/check/count', function(req, res) { res.json(upCount); }); // Routes require('./routes/check')(app); require('./routes/tag')(app); require('./routes/ping')(app); if (!module.parent) { app.listen(3000); console.log('Express started on port 3000'); }
Fix isEmpty bug for non string properties
package mil.nga.giat.mage.sdk.datastore.observation; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.ArrayList; import mil.nga.giat.mage.sdk.datastore.Property; @DatabaseTable(tableName = "observation_properties") public class ObservationProperty extends Property { @DatabaseField(foreign = true, uniqueCombo = true) private ObservationForm observationForm; public ObservationProperty() { // ORMLite needs a no-arg constructor } public ObservationProperty(String pKey, Serializable pValue) { super(pKey, pValue); } public ObservationForm getObservation() { return observationForm; } public void setObservationForm(ObservationForm observationForm) { this.observationForm = observationForm; } public boolean isEmpty() { Serializable value = getValue(); if (value instanceof String) { return StringUtils.isBlank(value.toString()); } else if (value instanceof ArrayList) { return ((ArrayList) value).size() == 0; } else { return value == null; } } }
package mil.nga.giat.mage.sdk.datastore.observation; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.ArrayList; import mil.nga.giat.mage.sdk.datastore.Property; @DatabaseTable(tableName = "observation_properties") public class ObservationProperty extends Property { @DatabaseField(foreign = true, uniqueCombo = true) private ObservationForm observationForm; public ObservationProperty() { // ORMLite needs a no-arg constructor } public ObservationProperty(String pKey, Serializable pValue) { super(pKey, pValue); } public ObservationForm getObservation() { return observationForm; } public void setObservationForm(ObservationForm observationForm) { this.observationForm = observationForm; } public boolean isEmpty() { Serializable value = getValue(); if (value instanceof String) { return StringUtils.isBlank(value.toString()); } else if (value instanceof ArrayList) { return ((ArrayList) value).size() == 0; } else { return value != null; } } }
Allow a call to purchase with only a transactionReference for recurring payments
<?php namespace Omnipay\Pacnet\Message; /** * Pacnet Authorize Request */ class AuthorizeRequest extends SubmitRequest { public function getData() { $data = parent::getData(); $data['PymtType'] = 'cc_preauth'; if ( ! $this->getTransactionReference()) { $this->validate('card'); $data['CardBrand'] = $this->getCard()->getBrand(); $data['CardNumber'] = $this->getCard()->getNumber(); $data['ExpiryDate'] = $this->getCard()->getExpiryDate('my'); if ($this->getCard()->getCvv()) { $data['CVV2'] = $this->getCard()->getCvv(); } if ($this->getCard()->getName()) { $data['AccountName'] = $this->getCard()->getName(); } } else { $data['TemplateNumber'] = $this->getTransactionReference(); } $data['Signature'] = $this->generateSignature($data); return $data; } }
<?php namespace Omnipay\Pacnet\Message; /** * Pacnet Authorize Request */ class AuthorizeRequest extends SubmitRequest { public function getData() { $data = parent::getData(); $this->validate('card'); $data['PymtType'] = 'cc_preauth'; $data['CardBrand'] = $this->getCard()->getBrand(); $data['CardNumber'] = $this->getCard()->getNumber(); $data['ExpiryDate'] = $this->getCard()->getExpiryDate('my'); if ($this->getCard()->getCvv()) { $data['CVV2'] = $this->getCard()->getCvv(); } if ($this->getCard()->getName()) { $data['AccountName'] = $this->getCard()->getName(); } $data['Signature'] = $this->generateSignature($data); return $data; } }
Add ability to set server port
var http = require('http'); var path = require('path'); var fs = require('fs'); var shoe = require('shoe'); var Stweam = require('stweam'); var habitat = require('habitat'); var ecstatic = require('ecstatic'); var argv = require('yargs') .demand('track') .describe('track', 'Set the phrases that will determine what is delivered from Twitter') .default('port', 3000) .describe('port', 'Set the port the server will bind to') .argv; var env = habitat.load(path.join(__dirname, '../.env')); var server = http.createServer( ecstatic({ root: path.join(__dirname, '../static') }) ).listen(argv.port, function(){ var address = server.address(); console.log('chirp listening at http://%s:%d/', address.address, address.port); }); var twitter = new Stweam({ consumerKey: env.get('chirpConsumerKey'), consumerSecret: env.get('chirpConsumerSecret'), token: env.get('chirpToken'), tokenSecret: env.get('chirpTokenSecret') }); twitter.on('info', function(msg){ console.log(msg); }); twitter .track(argv.track) .start(); var sock = shoe(function(stream){ twitter.pipe(stream); }); sock.install(server, '/tweets');
var http = require('http'); var path = require('path'); var fs = require('fs'); var shoe = require('shoe'); var Stweam = require('stweam'); var habitat = require('habitat'); var ecstatic = require('ecstatic'); var argv = require('yargs') .demand('track') .describe('track', 'Set the phrases that will determine what is delivered from Twitter') .argv; var env = habitat.load(path.join(__dirname, '../.env')); var server = http.createServer( ecstatic({ root: path.join(__dirname, '../static') }) ).listen(3000); console.log('chirp listening on port 3000'); var twitter = new Stweam({ consumerKey: env.get('chirpConsumerKey'), consumerSecret: env.get('chirpConsumerSecret'), token: env.get('chirpToken'), tokenSecret: env.get('chirpTokenSecret') }); twitter.on('info', function(msg){ console.log(msg); }); twitter .track(argv.track) .start(); var sock = shoe(function(stream){ twitter.pipe(stream); }); sock.install(server, '/tweets');
Add missing space before paren
/* * grunt-css-flip * https://github.com/twbs/grunt-css-flip * * Copyright (c) 2014 Chris Rebert * Licensed under the MIT License. */ 'use strict'; var flip = require('css-flip'); module.exports = function (grunt) { grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () { var options = this.options({}); this.files.forEach(function (f) { var originalCss = grunt.file.read(f.src); var flippedCss = null; try { flippedCss = flip(originalCss, options); } catch (err) { grunt.fail.warn(err); } grunt.file.write(f.dest, flippedCss); grunt.log.writeln('File "' + f.dest.cyan + '" created.'); }); }); };
/* * grunt-css-flip * https://github.com/twbs/grunt-css-flip * * Copyright (c) 2014 Chris Rebert * Licensed under the MIT License. */ 'use strict'; var flip = require('css-flip'); module.exports = function(grunt) { grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () { var options = this.options({}); this.files.forEach(function (f) { var originalCss = grunt.file.read(f.src); var flippedCss = null; try { flippedCss = flip(originalCss, options); } catch (err) { grunt.fail.warn(err); } grunt.file.write(f.dest, flippedCss); grunt.log.writeln('File "' + f.dest.cyan + '" created.'); }); }); };
Refactor tagged service IDs sorter.
<?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\UtilsBundle\DependencyInjection\Compiler; use Darvin\Utils\DependencyInjection\TaggedServiceIdsSorter; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Add slug handlers compiler pass */ class AddSlugHandlersPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container): void { $manager = $container->getDefinition('darvin_utils.sluggable.manager.entity'); foreach (array_keys((new TaggedServiceIdsSorter())->sort($container->findTaggedServiceIds('darvin_utils.slug_handler'))) as $id) { $manager->addMethodCall('addSlugHandler', [new Reference($id)]); } } }
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015-2018, 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\UtilsBundle\DependencyInjection\Compiler; use Darvin\Utils\DependencyInjection\TaggedServiceIdsSorter; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Add slug handlers compiler pass */ class AddSlugHandlersPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $ids = $container->findTaggedServiceIds('darvin_utils.slug_handler'); (new TaggedServiceIdsSorter())->sort($ids); $manager = $container->getDefinition('darvin_utils.sluggable.manager.entity'); foreach (array_keys($ids) as $id) { $manager->addMethodCall('addSlugHandler', [new Reference($id)]); } } }
Compress the images to be sent
import matplotlib # Do not use X for plotting matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(timestamp, close, color='r', marker='.', label="close") ax2.plot(timestamp, score, color='b', marker='.', label="score") plt.title("%s: score %0.2f" % (symbol, score[-1])) fig.autofmt_xdate() ax1.xaxis.set_major_formatter(DateFormatter("%H:%M")) ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() ax1.legend(h1 + h2, l1 + l2) jpg_file = NamedTemporaryFile(delete=False, suffix='.jpg') jpg_file.close() fig.set_dpi(100) fig.set_size_inches(10, 4) fig.set_tight_layout(True) fig.savefig(jpg_file.name, quality=50) plt.close(fig) return jpg_file.name
import matplotlib # Do not use X for plotting matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(timestamp, close, color='r', marker='.', label="close") ax2.plot(timestamp, score, color='b', marker='.', label="score") plt.title("%s: score %0.2f" % (symbol, score[-1])) fig.autofmt_xdate() ax1.xaxis.set_major_formatter(DateFormatter("%H:%M")) ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() ax1.legend(h1 + h2, l1 + l2) png_file = NamedTemporaryFile(delete=False, suffix='.png') png_file.close() fig.set_dpi(100) fig.set_size_inches(10, 4) fig.set_tight_layout(True) fig.savefig(png_file.name) plt.close(fig) return png_file.name
[CLI] Print out the interface name
#!/usr/bin/env node import pcap from 'pcap'; import yargs from 'yargs'; import ArpProbes from './ArpProbes'; import MacAddresses from './MacAddresses'; import NetworkInterfaces from './NetworkInterfaces'; if (require.main === module) { let parser = yargs .usage('Usage: $0 <command> [options]') .command('scan', 'Scan for ARP probes') .example( '$0 scan -i wlan0', 'Scan for ARP probes on the given network interface' ) .help('h') .alias('h', 'help') .version(() => require('../package.json').version) .alias('i', 'interface') .nargs('i', 1) .default('i', NetworkInterfaces.getDefault()) .describe('i', 'The network interface on which to listen'); let { argv } = parser; let commands = new Set(argv._); if (!commands.size) { console.log(parser.help()); } else if (commands.has('scan')) { let interfaceName = argv.interface; let pcapSession = ArpProbes.createCaptureSession(interfaceName); pcapSession.addListener('packet', rawPacket => { let packet = pcap.decode(rawPacket); let sourceMacAddress = MacAddresses.getEthernetSource(packet); console.log('Detected an ARP probe from %s', sourceMacAddress); }); console.log('Scanning for ARP probes on %s...', interfaceName); } }
#!/usr/bin/env node import pcap from 'pcap'; import yargs from 'yargs'; import ArpProbes from './ArpProbes'; import MacAddresses from './MacAddresses'; import NetworkInterfaces from './NetworkInterfaces'; if (require.main === module) { let parser = yargs .usage('Usage: $0 <command> [options]') .command('scan', 'Scan for ARP probes') .example( '$0 scan -i wlan0', 'Scan for ARP probes on the given network interface' ) .help('h') .alias('h', 'help') .version(() => require('../package.json').version) .alias('i', 'interface') .nargs('i', 1) .default('i', NetworkInterfaces.getDefault()) .describe('i', 'The network interface on which to listen'); let { argv } = parser; let commands = new Set(argv._); if (!commands.size) { console.log(parser.help()); } else if (commands.has('scan')) { let pcapSession = ArpProbes.createCaptureSession(argv.interface); pcapSession.addListener('packet', rawPacket => { let packet = pcap.decode(rawPacket); let sourceMacAddress = MacAddresses.getEthernetSource(packet); console.log('Detected an ARP probe from %s', sourceMacAddress); }); console.log('Scanning for ARP probes...'); } }
Change url and param name
package org.pdxfinder.admin.controllers; import org.pdxfinder.admin.pojos.MappingContainer; import org.pdxfinder.services.MappingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; /* * Created by csaba on 09/07/2018. */ @RestController public class AjaxController { private MappingService mappingService; @Value("${diagnosis.mappings.file}") private String savedDiagnosisMappingsFile; @Autowired public AjaxController(MappingService mappingService) { this.mappingService = mappingService; } @RequestMapping(value = "/api/missingmapping/diagnosis") @ResponseBody public MappingContainer getMissingMappings(@RequestParam("ds") Optional<String> dataSource){ String ds = null; if(dataSource.isPresent() && !dataSource.get().isEmpty()){ ds = dataSource.get(); } return mappingService.getMissingMappings(ds); } }
package org.pdxfinder.admin.controllers; import org.pdxfinder.admin.pojos.MappingContainer; import org.pdxfinder.services.MappingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; /* * Created by csaba on 09/07/2018. */ @RestController public class AjaxController { private MappingService mappingService; @Value("${diagnosis.mappings.file}") private String savedDiagnosisMappingsFile; @Autowired public AjaxController(MappingService mappingService) { this.mappingService = mappingService; } @RequestMapping(value = "/getmissingdiagnosismappings") @ResponseBody public MappingContainer getMissingMappings(@RequestParam("datasource") Optional<String> dataSource){ String ds = null; if(dataSource.isPresent() && !dataSource.get().isEmpty()){ ds = dataSource.get(); } return mappingService.getMissingMappings(ds); } }
Fix failing test because of new fields
/* * Copyright 2015 Blazebit. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blazebit.persistence; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.blazebit.persistence.entity.Document; /** * * @author Christian Beikov * @since 1.1.0 */ public class GroupByTest extends AbstractCoreTest { @Test public void testGroupByEntitySelect() { CriteriaBuilder<Long> criteria = cbf.create(em, Long.class).from(Document.class, "d"); criteria.groupBy("d.owner"); assertEquals("SELECT d FROM Document d JOIN d.owner owner_1 GROUP BY owner_1, d.age, d.archived, d.creationDate, d.creationDate2, d.documentType, d.id, d.idx, d.intIdEntity, d.lastModified, d.lastModified2, d.name, d.nonJoinable, d.owner", criteria.getQueryString()); criteria.getResultList(); } }
/* * Copyright 2015 Blazebit. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blazebit.persistence; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.blazebit.persistence.entity.Document; /** * * @author Christian Beikov * @since 1.1.0 */ public class GroupByTest extends AbstractCoreTest { @Test public void testGroupByEntitySelect() { CriteriaBuilder<Long> criteria = cbf.create(em, Long.class).from(Document.class, "d"); criteria.groupBy("d.owner"); assertEquals("SELECT d FROM Document d JOIN d.owner owner_1 GROUP BY owner_1, d.age, d.archived, d.creationDate, d.documentType, d.id, d.idx, d.intIdEntity, d.lastModified, d.name, d.nonJoinable, d.owner", criteria.getQueryString()); criteria.getResultList(); } }
Make variable names more descriptive
var openBlockList = function (blog) { $('document').ready( function () { $("#blocked_blogs > .accordion_trigger_wrapper > .accordion_trigger").click(); block(blog); }); } var block = function (blog) { $("#blocked_blogs > .accordion_content > .block-input > .text > #block").val(blog); setTimeout(function () { $("#blocked_blogs > .accordion_content > .block-input > .block-button").click(); }, 500); } var activate = function () { console.log ("activate"); var usersToBeBlockedStr = window.prompt("Please input comma separated list of users to be blocked",""); var usersToBeBlockedStr = usersToBeBlockedStr.replace(" ", ""); var usersToBeBlocked = usersToBeBlockedStr.split(","); openBlockList(usersToBeBlocked[0]); var i = 1; var inter = setInterval (function () { console.log (i + " -- " + usersToBeBlocked[i]); block(usersToBeBlocked[i++]); if (i >= usersToBeBlocked.length) { clearInterval(inter); console.log ("exit"); } }, 1100); } activate ();
var openBlockList = function (blog) { $('document').ready( function () { $("#blocked_blogs > .accordion_trigger_wrapper > .accordion_trigger").click(); block(blog); }); } var block = function (blog) { $("#blocked_blogs > .accordion_content > .block-input > .text > #block").val(blog); setTimeout(function () { $("#blocked_blogs > .accordion_content > .block-input > .block-button").click(); }, 500); } var activate = function () { console.log ("activate"); var str = window.prompt("Please input comma separated list of users to be blocked",""); var str = str.replace(" ", ""); var arr = str.split(","); openBlockList(arr[0]); var i = 1; var inter = setInterval (function () { console.log (i + " -- " + arr[i]); block(arr[i++]); if (i >= arr.length) { clearInterval(inter); console.log ("exit"); } }, 1100); } activate ();
Read for service token from stdin.
import eventlet eventlet.monkey_patch() # NOLINT import importlib import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() token = sys.stdin.readline().strip() name = sys.argv[1] module = importlib.import_module(name) meta = module.__meta__ config = get_config(meta.get("config")) app = meta["class"](token, config) signal.signal(signal.SIGTERM, lambda x, y: app.on_service_stop()) signal.signal(signal.SIGINT, lambda x, y: app.on_service_stop()) app.before_service_start() app.on_service_start() def handle_main(): configure_logging() main_app = create_app() main_app.start()
import eventlet eventlet.monkey_patch() # NOLINT import importlib import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() name = sys.argv[1] module = importlib.import_module(name) meta = module.__meta__ config = get_config(meta.get("config")) app = meta["class"](config) signal.signal(signal.SIGTERM, lambda x, y: app.on_service_stop()) signal.signal(signal.SIGINT, lambda x, y: app.on_service_stop()) app.before_service_start() app.on_service_start() def handle_main(): configure_logging() main_app = create_app() main_app.start()
Fix typo in exception name
# # Copyright (c) 2011 rPath, Inc. # # All Rights Reserved # BAD_REQUEST = 400 NOT_FOUND = 404 INTERNAL_SERVER_ERROR = 500 class RbuilderError(Exception): "An unknown error has occured." status = INTERNAL_SERVER_ERROR def __init__(self, **kwargs): cls = self.__class__ self.msg = cls.__doc__ self.kwargs = kwargs def __str__(self): try: return self.msg % self.kwargs except TypeError: return self.msg class CollectionPageNotFound(RbuilderError): "The requested page of the collection was not found." status = NOT_FOUND class UnknownFilterOperator(RbuilderError): "%(filter)s is an invalid filter operator." status = BAD_REQUEST class InvalidFilterValue(RbuilderError): "%(value)s in an invalid value for filter operator %(filter)s" status = BAD_REQUEST
# # Copyright (c) 2011 rPath, Inc. # # All Rights Reserved # BAD_REQUEST = 400 NOT_FOUND = 404 INTERNAL_SERVER_ERROR = 500 class RbuilderError(Exception): "An unknown error has occured." status = INTERNAL_SERVER_ERROR def __init__(self, **kwargs): cls = self.__class__ self.msg = cls.__doc__ self.kwargs = kwargs def __str__(self): try: return self.msg % self.kwargs except TypeError: return self.msg class CollectionPageNotFound(RbuilderError): "The requested page of the collection was not found." status = NOT_FOUND class UknownFilterOperator(RbuilderError): "%(filter)s is an invalid filter operator." status = BAD_REQUEST class InvalidFilterValue(RbuilderError): "%(value)s in an invalid value for filter operator %(filter)s" status = BAD_REQUEST
Remove unnecessary project root variable from webpack resolve script
import json import os import wiki DJANGO_WIKI_STATIC = os.path.join(os.path.dirname(wiki.__file__), 'static') WEBPACK_RESOLVE_FILE = 'webpack-extra-resolve.json' # This whole file is essentially just a big ugly hack. # For webpack to properly build wiki static files it needs the absolute path to the wiki # static folder. And since we're using virtualenvs there is no easy way to find this folder # without running python code def create_resolve_file(): # Write to json file which will be read by webpack with open(WEBPACK_RESOLVE_FILE, 'w') as f: f.write(json.dumps({ 'paths': [ DJANGO_WIKI_STATIC ] })) if __name__ == '__main__': # Only run if file is executed directly create_resolve_file()
import json import os import wiki PROJECT_ROOT_DIRECTORY = os.path.dirname(globals()['__file__']) DJANGO_WIKI_STATIC = os.path.join(os.path.dirname(wiki.__file__), 'static') # This whole file is essentially just a big ugly hack. # For webpack to properly build wiki static files it needs the absolute path to the wiki # static folder. And since we're using virtualenvs there is no easy way to find this folder # without running python code def create_resolve_file(): # Write to json file which will be read by webpack with open(os.path.join(PROJECT_ROOT_DIRECTORY, 'webpack-extra-resolve.json'), 'w') as f: f.write(json.dumps({ 'paths': [ DJANGO_WIKI_STATIC ] })) if __name__ == '__main__': # Only run if file is executed directly create_resolve_file()
Add AbstractSanitizer/AbstractValidator class to import path
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from .__version__ import __author__, __copyright__, __email__, __license__, __version__ from ._base import AbstractSanitizer, AbstractValidator from ._common import ( Platform, ascii_symbols, normalize_platform, replace_ansi_escape, replace_unprintable_char, unprintable_ascii_chars, validate_null_string, validate_pathtype, ) from ._filename import FileNameSanitizer, is_valid_filename, sanitize_filename, validate_filename from ._filepath import ( FilePathSanitizer, is_valid_filepath, sanitize_file_path, sanitize_filepath, validate_file_path, validate_filepath, ) from ._ltsv import sanitize_ltsv_label, validate_ltsv_label from ._symbol import replace_symbol, validate_symbol from .error import ( ErrorReason, InvalidCharError, InvalidLengthError, InvalidReservedNameError, NullNameError, ReservedNameError, ValidationError, ValidReservedNameError, )
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from .__version__ import __author__, __copyright__, __email__, __license__, __version__ from ._common import ( Platform, ascii_symbols, normalize_platform, replace_ansi_escape, replace_unprintable_char, unprintable_ascii_chars, validate_null_string, validate_pathtype, ) from ._filename import FileNameSanitizer, is_valid_filename, sanitize_filename, validate_filename from ._filepath import ( FilePathSanitizer, is_valid_filepath, sanitize_file_path, sanitize_filepath, validate_file_path, validate_filepath, ) from ._ltsv import sanitize_ltsv_label, validate_ltsv_label from ._symbol import replace_symbol, validate_symbol from .error import ( ErrorReason, InvalidCharError, InvalidLengthError, InvalidReservedNameError, NullNameError, ReservedNameError, ValidationError, ValidReservedNameError, )
Move GameboardController.playerName to a getter
class GameboardController { constructor(Game, GlobalEvents) { "ngInject"; this.currentAnswer = ''; this.currentMangledWord = Game.currentWord.mangled; this.game = Game; this.remainingTime = Game.remainingSeconds; this.score = 0; GlobalEvents.on(Game.NEW_WORD, (newWord) => this.onNewWord(newWord)); GlobalEvents.on(Game.SCORE_UPDATED, (newScore) => this.onNewScore(newScore)); GlobalEvents.on(Game.TIME_UPDATED, (newTime) => this.onTimeUpdated(newTime)); GlobalEvents.on(Game.TIME_IS_UP, () => this.onTimeIsUp()); } get playerName() { return this.game.playerName; } onAnswerChange() { this.game.setAnswer(this.currentAnswer); } onNewScore(newScore) { this.score = newScore; } onNewWord(newWord) { this.currentAnswer = ''; this.currentMangledWord = newWord.mangled; } onTimeIsUp() { // TODO } onTimeUpdated(newTime) { this.remainingTime = newTime; } } export default GameboardController;
class GameboardController { constructor(Game, GlobalEvents) { "ngInject"; this.currentAnswer = ''; this.currentMangledWord = Game.currentWord.mangled; this.game = Game; this.playerName = Game.playerName; this.remainingTime = Game.remainingSeconds; this.score = 0; GlobalEvents.on(Game.NEW_WORD, (newWord) => this.onNewWord(newWord)); GlobalEvents.on(Game.SCORE_UPDATED, (newScore) => this.onNewScore(newScore)); GlobalEvents.on(Game.TIME_UPDATED, (newTime) => this.onTimeUpdated(newTime)); GlobalEvents.on(Game.TIME_IS_UP, () => this.onTimeIsUp()); } onAnswerChange() { this.game.setAnswer(this.currentAnswer); } onNewScore(newScore) { this.score = newScore; } onNewWord(newWord) { this.currentAnswer = ''; this.currentMangledWord = newWord.mangled; } onTimeIsUp() { // TODO } onTimeUpdated(newTime) { this.remainingTime = newTime; } } export default GameboardController;
Make sure to call normalize() on the path before validating
package me.izstas.rfs.server.service; import java.nio.file.Path; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import me.izstas.rfs.server.config.security.RfsUserDetails; @Service public class PathService { /** * Makes sure the provided path is in the user's root. * @throws BadPathException if the path is not the user's root */ public void validateUserPath(Path path) { Path currentPath = path.toAbsolutePath().normalize(); Path rootPath = getUserRoot().toAbsolutePath().normalize(); do { if (currentPath.equals(rootPath)) { return; } } while ((currentPath = currentPath.getParent()) != null); // If we've reached this line, the provided path is not in the user's root throw new BadPathException(); } /** * Resolves the provided path against the user's root and validates it with {@link #validateUserPath(Path)}. */ public Path resolveUserPath(String path) { Path resolvedPath = getUserRoot().resolve(path); validateUserPath(resolvedPath); return resolvedPath; } private Path getUserRoot() { return ((RfsUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getRoot(); } }
package me.izstas.rfs.server.service; import java.nio.file.Path; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import me.izstas.rfs.server.config.security.RfsUserDetails; @Service public class PathService { /** * Makes sure the provided path is in the user's root. * @throws BadPathException if the path is not the user's root */ public void validateUserPath(Path path) { Path currentPath = path.toAbsolutePath(); Path rootPath = getUserRoot().toAbsolutePath(); do { if (currentPath.equals(rootPath)) { return; } } while ((currentPath = currentPath.getParent()) != null); // If we've reached this line, the provided path is not in the user's root throw new BadPathException(); } /** * Resolves the provided path against the user's root and validates it with {@link #validateUserPath(Path)}. */ public Path resolveUserPath(String path) { Path resolvedPath = getUserRoot().resolve(path); validateUserPath(resolvedPath); return resolvedPath; } private Path getUserRoot() { return ((RfsUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getRoot(); } }
Allow environment variables to be accessed via `getenv()` function. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Illuminate\Config; /** * PHP $_ENV loader for protecting sensitive configuration options. * * Inspired by the wonderful "Dotenv" library by Vance Lucas. */ class EnvironmentVariables { /** * The environment loader implementation. * * @var \Illuminate\Config\EnvironmentLoaderInterface $loader */ protected $loader; /** * The server environment instance. * * @param \Illuminate\Config\EnvironmentLoaderInterface $loader * @return void */ public function __construct(EnvironmentVariablesLoaderInterface $loader) { $this->loader = $loader; } /** * Load the server variables for a given environment. * * @param string $environment */ public function load($environment = null) { foreach ($this->loader->load($environment) as $key => $value) { $_ENV[$key] = $value; $_SERVER[$key] = $value; putenv("{$key}={$value}"); } } }
<?php namespace Illuminate\Config; /** * PHP $_ENV loader for protecting sensitive configuration options. * * Inspired by the wonderful "Dotenv" library by Vance Lucas. */ class EnvironmentVariables { /** * The environment loader implementation. * * @var \Illuminate\Config\EnvironmentLoaderInterface $loader */ protected $loader; /** * The server environment instance. * * @param \Illuminate\Config\EnvironmentLoaderInterface $loader * @return void */ public function __construct(EnvironmentVariablesLoaderInterface $loader) { $this->loader = $loader; } /** * Load the server variables for a given environment. * * @param string $environment */ public function load($environment = null) { foreach ($this->loader->load($environment) as $key => $value) { $_ENV[$key] = $value; $_SERVER[$key] = $value; } } }
Update debug message to be less incorrect
var email = require('emailjs') , debug = require('debug')('wifi-chat:mailer') var config = null , server = null var connect = function() { debug('Connecting to mail server', config.email.connection) server = email.server.connect(config.email.connection) } var setConfig = function(configuration) { config = configuration connect() } var sendMail = function(to, subject, template, substitutions, callback) { var content = template.replace(new RegExp('%url%', 'g'), config.url) Object.keys(substitutions || {}).forEach(function(key) { content = content.replace(new RegExp('%' + key + '%', 'g'), substitutions[key]) }) var message = { text: content, from: config.email.sendAddress, to: to, subject: subject } debug('Sending email', message) server.send(message, callback) } module.exports = { setConfig: setConfig, sendMail: sendMail }
var email = require('emailjs') , debug = require('debug')('wifi-chat:mailer') var config = null , server = null var connect = function() { debug('Connecting to mail server', config.email.connection) server = email.server.connect(config.email.connection) } var setConfig = function(configuration) { config = configuration connect() } var sendMail = function(to, subject, template, substitutions, callback) { var content = template.replace(new RegExp('%url%', 'g'), config.url) Object.keys(substitutions || {}).forEach(function(key) { content = content.replace(new RegExp('%' + key + '%', 'g'), substitutions[key]) }) var message = { text: content, from: config.email.sendAddress, to: to, subject: subject } debug('Sending password reset email', message) server.send(message, callback) } module.exports = { setConfig: setConfig, sendMail: sendMail }
Fix tests failing from different tab_size
import sublime from unittest import TestCase class TestHelper(TestCase): def setUp(self): self.view = sublime.active_window().new_file() self.view.settings().set("tab_size", 2) def tearDown(self): if self.view: self.view.set_scratch(True) self.view.window().run_command('close_file') def set_text(self, lines): for line in lines: self.view.run_command('move_to', { 'to': 'bol', 'extend': True }) self.view.run_command('insert', { 'characters': line + "\n" }) def check_command(self, text, start, end, extend_selection=False, indent_offset=0): self.set_text(text) self.view.sel().clear() self.view.sel().add(sublime.Region(start[0], start[1])) self.view.run_command(self.command(), { 'extend_selection': extend_selection, 'indent_offset': indent_offset }) self.assertEqual(self.view.sel()[0], sublime.Region(end[0], end[1]))
import sublime from unittest import TestCase class TestHelper(TestCase): def setUp(self): self.view = sublime.active_window().new_file() def tearDown(self): if self.view: self.view.set_scratch(True) self.view.window().run_command('close_file') def set_text(self, lines): for line in lines: self.view.run_command('move_to', { 'to': 'bol', 'extend': True }) self.view.run_command('insert', { 'characters': line + "\n" }) def check_command(self, text, start, end, extend_selection=False, indent_offset=0): tab_size = self.view.settings().get("tab_size") self.set_text(text) self.view.sel().clear() self.view.sel().add(sublime.Region(start[0], start[1])) self.view.run_command(self.command(), { 'extend_selection': extend_selection, 'indent_offset': indent_offset }) self.assertEqual(self.view.sel()[0], sublime.Region(end[0], end[1]))
Fix wrong unit test value
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less from nose.tools import raises, assert_true, assert_equal from UliEngineering.Physics.NTC import * from UliEngineering.Exceptions import * import functools import numpy as np class TestNTC(object): def test_ntc_resistance(self): # Values arbitrarily from Murata NCP15WB473D03RC assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000) assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79) assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66) assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less from nose.tools import raises, assert_true, assert_equal from UliEngineering.Physics.NTC import * from UliEngineering.Exceptions import * import functools import numpy as np class TestNTC(object): def test_ntc_resistance(self): # Values arbitrarily from Murata NCP15WB473D03RC assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000) assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79) assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66) assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280)
Test the htmlmin class is injectable
<?php /** * This file is part of Laravel HTMLMin by Graham Campbell. * * 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 * * 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. */ namespace GrahamCampbell\Tests\HTMLMin; use GrahamCampbell\TestBench\Traits\ServiceProviderTestCaseTrait; /** * This is the service provider test class. * * @package Laravel-HTMLMin * @author Graham Campbell * @copyright Copyright 2013-2014 Graham Campbell * @license https://github.com/GrahamCampbell/Laravel-HTMLMin/blob/master/LICENSE.md * @link https://github.com/GrahamCampbell/Laravel-HTMLMin */ class ServiceProviderTest extends AbstractTestCase { use ServiceProviderTestCaseTrait; public function testHTMLMinIsInjectable() { $this->assertIsInjectable('GrahamCampbell\HTMLMin\HTMLMin'); } }
<?php /** * This file is part of Laravel HTMLMin by Graham Campbell. * * 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 * * 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. */ namespace GrahamCampbell\Tests\HTMLMin; use GrahamCampbell\TestBench\Traits\ServiceProviderTestCaseTrait; /** * This is the service provider test class. * * @package Laravel-HTMLMin * @author Graham Campbell * @copyright Copyright 2013-2014 Graham Campbell * @license https://github.com/GrahamCampbell/Laravel-HTMLMin/blob/master/LICENSE.md * @link https://github.com/GrahamCampbell/Laravel-HTMLMin */ class ServiceProviderTest extends AbstractTestCase { use ServiceProviderTestCaseTrait; }
Change java client MIN_BUFFER_SIZE to 1MB
package seaweedfs.client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; public class ByteBufferPool { private static final int MIN_BUFFER_SIZE = 1 * 1024 * 1024; private static final Logger LOG = LoggerFactory.getLogger(ByteBufferPool.class); private static final List<ByteBuffer> bufferList = new ArrayList<>(); public static synchronized ByteBuffer request(int bufferSize) { if (bufferSize < MIN_BUFFER_SIZE) { bufferSize = MIN_BUFFER_SIZE; } LOG.debug("requested new buffer {}", bufferSize); if (bufferList.isEmpty()) { return ByteBuffer.allocate(bufferSize); } ByteBuffer buffer = bufferList.remove(bufferList.size() - 1); if (buffer.capacity() >= bufferSize) { return buffer; } LOG.info("add new buffer from {} to {}", buffer.capacity(), bufferSize); bufferList.add(0, buffer); return ByteBuffer.allocate(bufferSize); } public static synchronized void release(ByteBuffer obj) { ((Buffer)obj).clear(); bufferList.add(0, obj); } }
package seaweedfs.client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; public class ByteBufferPool { private static final int MIN_BUFFER_SIZE = 8 * 1024 * 1024; private static final Logger LOG = LoggerFactory.getLogger(ByteBufferPool.class); private static final List<ByteBuffer> bufferList = new ArrayList<>(); public static synchronized ByteBuffer request(int bufferSize) { if (bufferSize < MIN_BUFFER_SIZE) { bufferSize = MIN_BUFFER_SIZE; } LOG.debug("requested new buffer {}", bufferSize); if (bufferList.isEmpty()) { return ByteBuffer.allocate(bufferSize); } ByteBuffer buffer = bufferList.remove(bufferList.size() - 1); if (buffer.capacity() >= bufferSize) { return buffer; } LOG.info("add new buffer from {} to {}", buffer.capacity(), bufferSize); bufferList.add(0, buffer); return ByteBuffer.allocate(bufferSize); } public static synchronized void release(ByteBuffer obj) { ((Buffer)obj).clear(); bufferList.add(0, obj); } }
Remove spread operator for wider node coverage
'use strict' const _ = require('lodash') const Database = require('./database') const inflection = require('inflection') /** * Defines the Model class to be extended on a per-model basis */ class Model extends Database.Model { /** * Returns the database instance. * * @returns {Bookshelf} - a bookshelf instance */ static get database () { return Database } /** * Register a model with the Bookshelf registry to prevent circular dependency issues. * * Most models should be exported with this method. * * Example: * class User extends Model { * // ... * } * * module.exports = Model.register('User', User); */ static register () { return Database.model.apply(Database, arguments) } /** * Returns the database table name to be used for the model. The name is inferred based on the * model name, underscoring and pluralizing the name. * * @example * class BlogPost extends Model {} * let blogPost = new BlogPost(); * blogPost.tableName * // => "blog_posts" * * @returns {String} The table name */ get tableName () { let modelName = this.constructor.name let tableized = inflection.tableize(modelName) return _.compact([this.schemaName, tableized]).join('.') } /** * Returns the `id` column/attribute on the model * * @type {string} */ get idAttribute () { return 'id' } } module.exports = Model
'use strict' const _ = require('lodash') const Database = require('./database') const inflection = require('inflection') /** * Defines the Model class to be extended on a per-model basis */ class Model extends Database.Model { /** * Returns the database instance. * * @returns {Bookshelf} - a bookshelf instance */ static get database () { return Database } /** * Register a model with the Bookshelf registry to prevent circular dependency issues. * * Most models should be exported with this method. * * Example: * class User extends Model { * // ... * } * * module.exports = Model.register('User', User); */ static register (...args) { return Database.model(...args) } /** * Returns the database table name to be used for the model. The name is inferred based on the * model name, underscoring and pluralizing the name. * * @example * class BlogPost extends Model {} * let blogPost = new BlogPost(); * blogPost.tableName * // => "blog_posts" * * @returns {String} The table name */ get tableName () { let modelName = this.constructor.name let tableized = inflection.tableize(modelName) return _.compact([this.schemaName, tableized]).join('.') } /** * Returns the `id` column/attribute on the model * * @type {string} */ get idAttribute () { return 'id' } } module.exports = Model
Update entry updated at field git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@57660 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
<?php /** * @package Core * @subpackage model.interfaces */ interface IIndexable extends IBaseObject { const FIELD_TYPE_STRING = 'string'; const FIELD_TYPE_INTEGER = 'int'; const FIELD_TYPE_DATETIME = 'datetime'; /** * Is the id as used and know by Kaltura * @return string */ public function getId(); /** * Is the id as used and know by the indexing server * @return int */ public function getIntId(); /** * @return string */ public function getEntryId(); /** * @return string object propel name */ public function getObjectIndexName(); /** * @return array while the key is the index attribute name and the value is the getter name * For example array('name' => 'title') if name should be retrieved by getTitle() getter */ public function getIndexFieldsMap(); /** * @return string field type, string, int or timestamp */ public function getIndexFieldType($field); /** * @param int $time * @return IIndexable */ public function setUpdatedAt($time); /** * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException */ public function save(PropelPDO $con = null); }
<?php /** * @package Core * @subpackage model.interfaces */ interface IIndexable extends IBaseObject { const FIELD_TYPE_STRING = 'string'; const FIELD_TYPE_INTEGER = 'int'; const FIELD_TYPE_DATETIME = 'datetime'; /** * Is the id as used and know by Kaltura * @return string */ public function getId(); /** * Is the id as used and know by the indexing server * @return int */ public function getIntId(); /** * @return string */ public function getEntryId(); /** * @return string object propel name */ public function getObjectIndexName(); /** * @return array while the key is the index attribute name and the value is the getter name * For example array('name' => 'title') if name should be retrieved by getTitle() getter */ public function getIndexFieldsMap(); /** * @return string field type, string, int or timestamp */ public function getIndexFieldType($field); }
Return single result in getInfo function
<?php namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; /** * TraitTypeRepository * * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom * repository methods below. */ class TraitTypeRepository extends EntityRepository { public function getNumber(){ $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt'); return $query->getSingleScalarResult(); } /** * @param $trait_type_id * @return array type, format, trait_type_id and ontology_url of specific trait */ public function getInfo($trait_type_id){ $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('t.id AS trait_type_id', 't.type', 't.ontologyUrl', 'IDENTITY(t.traitFormat) AS trait_format_id', 't.description', 't.unit') ->from('AppBundle\Entity\TraitType', 't') ->where('t.id = :trait_type_id') ->setParameter('trait_type_id', $trait_type_id); $query = $qb->getQuery(); return $query->getSingleResult(); } }
<?php namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; /** * TraitTypeRepository * * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom * repository methods below. */ class TraitTypeRepository extends EntityRepository { public function getNumber(){ $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt'); return $query->getSingleScalarResult(); } /** * @param $trait_type_id * @return array type, format, trait_type_id and ontology_url of specific trait */ public function getInfo($trait_type_id){ $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('t.id AS trait_type_id', 't.type', 't.ontologyUrl', 'IDENTITY(t.traitFormat) AS trait_format_id', 't.description', 't.unit') ->from('AppBundle\Entity\TraitType', 't') ->where('t.id = :trait_type_id') ->setParameter('trait_type_id', $trait_type_id); $query = $qb->getQuery(); return $query->getResult(); } }
Make event handler passive for better scrolling
import icons from './generated/icons.js'; import { draw } from './draw.js'; function initIcons(state) { const $right = $('#right'); $.each(icons, (index, icon) => { const $iconOuter = $('<div>') .addClass('icon_outer') .data('ix', icon.ix); const styleClass = icon.st + ' fa-' + icon.id; const $icon = $('<div>') .addClass('icon hover') .data('ix', icon.ix) .append($('<i>').addClass(styleClass)); $icon.append( $('<div>') .addClass('icon_text underline') .text(icon.id), ); $iconOuter.append($icon); $right.append($iconOuter); }); function iconClicked() { const icon = icons[$(this).data('ix')]; if (!state.stackedselected) { state.icon = icon; } else { state.stackedicon = icon; } draw(); } $('.icon').each((index, elem) => { elem.addEventListener('click', iconClicked, { passive: true }); elem.addEventListener('touchstart', iconClicked, { passive: true }); }); } export { initIcons };
import icons from './generated/icons.js'; import { draw } from './draw.js'; function initIcons(state) { const $right = $('#right'); $.each(icons, (index, icon) => { const $iconOuter = $('<div>') .addClass('icon_outer') .data('ix', icon.ix); const styleClass = icon.st + ' fa-' + icon.id; const $icon = $('<div>') .addClass('icon hover') .data('ix', icon.ix) .append($('<i>').addClass(styleClass)); $icon.append( $('<div>') .addClass('icon_text underline') .text(icon.id), ); $iconOuter.append($icon); $right.append($iconOuter); }); $('.icon').on('click touchstart', event => { const icon = icons[$(event.currentTarget).data('ix')]; if (!state.stackedSelected) { state.icon = icon; } else { state.stackedIcon = icon; } draw(); }); } export { initIcons };
refactor(verification): Refactor to query straight for user - Implement get_user - Change to make a single query to find the token, using a join to the user's email
from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" try: token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return token.user def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" user_model = get_user_model() kwargs = { 'user__%s' % user_model.USERNAME_FIELD: email, 'token': pin } return SingleUseToken.objects.get(**kwargs) def get_user(self, user_id): """Get user from id.""" user_model = get_user_model() try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None
from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" user_model = get_user_model() kwargs = { user_model.USERNAME_FIELD: email } try: user = user_model.objects.get(**kwargs) except user_model.DoesNotExist: return None # Now that we have the user, check that we have a token try: token = self._get_token(user, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return user def _get_token(self, user, pin): """Get the token for corresponding user and pin.""" return SingleUseToken.objects.get(user=user, token=pin)
Change package name before publishing to PyPI
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2010 Sebastian Krysmanski # Copyright (C) 2012 Greg Lavallee # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # from setuptools import setup PACKAGE = 'TracTicketGuidelines' VERSION = '1.0.0' setup( name=PACKAGE, version=VERSION, author='Sebastian Krysmanski', url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin', description="Adds your ticket guidelines to the ticket view. The " "guidelines are specified in the wiki pages " "'TicketGuidelines/NewShort' and " "'TicketGuidelines/ModifyShort'.", keywords='trac plugin', license='Modified BSD', install_requires=['Trac'], packages=['ticketguidelines'], package_data={'ticketguidelines': ['htdocs/*']}, entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE}, )
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2010 Sebastian Krysmanski # Copyright (C) 2012 Greg Lavallee # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # from setuptools import setup PACKAGE = 'TicketGuidelinesPlugin' VERSION = '1.0.0' setup( name=PACKAGE, version=VERSION, author='Sebastian Krysmanski', url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin', description="Adds your ticket guidelines to the ticket view. The " "guidelines are specified in the wiki pages " "'TicketGuidelines/NewShort' and " "'TicketGuidelines/ModifyShort'.", keywords='trac plugin', license='Modified BSD', install_requires=['Trac'], packages=['ticketguidelines'], package_data={'ticketguidelines': ['htdocs/*']}, entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE}, )
Enable rtl for proper localizations
/* Hebrew translation for the jQuery Timepicker Addon */ /* Written by Lior Lapid */ (function($) { $.timepicker.regional["he"] = { timeOnlyTitle: "בחירת זמן", timeText: "שעה", hourText: "שעות", minuteText: "דקות", secondText: "שניות", millisecText: "אלפית השנייה", timezoneText: "אזור זמן", currentText: "עכשיו", closeText:"סגור", timeFormat: "hh:mm tt", amNames: ['לפנה"צ', 'AM', 'A'], pmNames: ['אחה"צ', 'PM', 'P'], ampm: false, isRTL: true }; $.timepicker.setDefaults($.timepicker.regional["he"]); })(jQuery);
/* Hebrew translation for the jQuery Timepicker Addon */ /* Written by Lior Lapid */ (function($) { $.timepicker.regional["he"] = { timeOnlyTitle: "בחירת זמן", timeText: "שעה", hourText: "שעות", minuteText: "דקות", secondText: "שניות", millisecText: "אלפית השנייה", timezoneText: "אזור זמן", currentText: "עכשיו", closeText:"סגור", timeFormat: "hh:mm tt", amNames: ['לפנה"צ', 'AM', 'A'], pmNames: ['אחה"צ', 'PM', 'P'], ampm: false, isRTL: false }; $.timepicker.setDefaults($.timepicker.regional["he"]); })(jQuery);
Remove demo-related jQuery from library code
var tablePrefix = '__dear_'; function createTable(tableName) { if (!localStorage[tableName]) { localStorage[tablePrefix + tableName] = '{}'; } } function readTable(tableName) { // Read tableModel from local storage return JSON.parse(localStorage[tablePrefix + tableName]); } function writeTable(tableName, tableModel) { // Write tableModel to local storage localStorage[tablePrefix + tableName] = JSON.stringify(tableModel); } function createRecord(tableName, recordName, value) { var tableModel = readTable(tableName); if (!tableModel[recordName]) { tableModel[recordName] = value; } writeTable(tableName, tableModel); } function writeRecord(tableName, recordName, value) { var tableModel = readTable(tableName); tableModel[recordName] = value; writeTable(tableName, tableModel); } function deleteRecord(tableName, recordName) { var tableModel = readTable(tableName); delete tableModel[recordName]; writeTable(tableName, tableModel); } function deleteTable(tableName) { delete localStorage[tablePrefix + tableName]; } function listTables() { return Object.keys(localStorage).filter(function(str) { return str.slice(0, tablePrefix.length) == tablePrefix; }).map(function(str) { return str.slice(tablePrefix.length); }); }
var tablePrefix = '__dear_'; function createTable(tableName) { if (!localStorage[tableName]) { localStorage[tablePrefix + tableName] = '{}'; } } function readTable(tableName) { // Read tableModel from local storage return JSON.parse(localStorage[tablePrefix + tableName]); } function writeTable(tableName, tableModel) { // Write tableModel to local storage localStorage[tablePrefix + tableName] = JSON.stringify(tableModel); } function createRecord(tableName, recordName, value) { var tableModel = readTable(tableName); if (!tableModel[recordName]) { tableModel[recordName] = value; } writeTable(tableName, tableModel); } function writeRecord(tableName, recordName, value) { var tableModel = readTable(tableName); tableModel[recordName] = value; writeTable(tableName, tableModel); } function deleteRecord(tableName, recordName) { var tableModel = readTable(tableName); delete tableModel[recordName]; writeTable(tableName, tableModel); } function deleteTable(tableName) { delete localStorage[tablePrefix + tableName]; $('#changeTable option[value=' + tableName + ']').remove(); } function listTables() { return Object.keys(localStorage).filter(function(str) { return str.slice(0, tablePrefix.length) == tablePrefix; }).map(function(str) { return str.slice(tablePrefix.length); }); }
Revert "increasing webdriver timeout on fake-service" This reverts commit a39a4b40a947db655c84af6eb62d5870cfd8b32c.
# # Copyright (c) 2014 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Pixelated. If not, see <http://www.gnu.org/licenses/>. from selenium import webdriver def before_feature(context, feature): #context.browser = webdriver.Firefox() context.browser = webdriver.PhantomJS() context.browser.set_window_size(1280, 1024) context.browser.implicitly_wait(5) context.browser.set_page_load_timeout(60) # wait for data context.browser.get('http://localhost:4567/') def after_feature(context, feature): context.browser.quit() def take_screenshot(context): context.browser.save_screenshot('/tmp/screenshot.jpeg') def save_source(context): with open('/tmp/source.html', 'w') as out: out.write(context.browser.page_source.encode('utf8'))
# # Copyright (c) 2014 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Pixelated. If not, see <http://www.gnu.org/licenses/>. from selenium import webdriver def before_feature(context, feature): #context.browser = webdriver.Firefox() context.browser = webdriver.PhantomJS() context.browser.set_window_size(1280, 1024) context.browser.implicitly_wait(10) context.browser.set_page_load_timeout(120) # wait for data context.browser.get('http://localhost:4567/') def after_feature(context, feature): context.browser.quit() def take_screenshot(context): context.browser.save_screenshot('/tmp/screenshot.jpeg') def save_source(context): with open('/tmp/source.html', 'w') as out: out.write(context.browser.page_source.encode('utf8'))
FIX import order - cyclic dependencies
""" :mod:`asl.application.initializers` -- ASL initializers ======================================================= :platform: Unix, Windows :synopsis: The Atteq Service Layer initialization infrastructure .. moduleauthor:: Martin Babka <babka@atteq.com> """ injection_views = [] injection_modules = [] def injection_view(f): """ Adds the view to the list of Injector-enabled views to add to the Flask app. :param callable f: The decorated view function. """ injection_views.append(f) return f def injection_module(f): """ Adds the module to the list of injection enabled modules. The decorated function is then called in the initialization phase and can create and initialize the object which will be able to be injected. :param callable f: The decorated initializing function. """ injection_modules.append(f) return f from .logger_initializer import LoggerInitializer from .unittest_initializer import UnitTestInitializer from .library_initializer import LibraryInitializer from .database_initializer import DatabaseInitializer from .application_initializer import ApplicationInitializer from .service_initializer import ServiceInitializer from .cache_initializer import CacheInitializer from .context_initializer import ContextInitializer
""" :mod:`asl.application.initializers` -- ASL initializers ======================================================= :platform: Unix, Windows :synopsis: The Atteq Service Layer initialization infrastructure .. moduleauthor:: Martin Babka <babka@atteq.com> """ from .logger_initializer import LoggerInitializer from .unittest_initializer import UnitTestInitializer from .library_initializer import LibraryInitializer from .database_initializer import DatabaseInitializer from .application_initializer import ApplicationInitializer from .service_initializer import ServiceInitializer from .cache_initializer import CacheInitializer from .context_initializer import ContextInitializer injection_views = [] injection_modules = [] def injection_view(f): """ Adds the view to the list of Injector-enabled views to add to the Flask app. :param callable f: The decorated view function. """ injection_views.append(f) return f def injection_module(f): """ Adds the module to the list of injection enabled modules. The decorated function is then called in the initialization phase and can create and initialize the object which will be able to be injected. :param callable f: The decorated initializing function. """ injection_modules.append(f) return f
Fix status bug with the new quick update.
Hummingbird.QuickUpdateItemController = Ember.ObjectController.extend({ loading: false, isComplete: Hummingbird.computed.propertyEqual('episodesWatched', "anime.episodeCount"), percentComplete: function() { var episodesWatched = this.get('episodesWatched'), episodeCount = this.get('anime.episodeCount'); if (episodeCount) { return Math.ceil(100 * episodesWatched / episodeCount); } else { return "?"; } }.property('episodesWatched', 'anime.episodeCount'), nextEpisodeNumber: function() { return this.get('episodesWatched') + 1; }.property('episodesWatched'), actions: { markViewed: function() { var libraryEntry = this.get('model'), self = this; libraryEntry.set('episodesWatched', this.get('nextEpisodeNumber')); if (this.get('isComplete')) { libraryEntry.set('status', "Completed"); } else { libraryEntry.set('status', "Currently Watching"); } this.set('loading', true); libraryEntry.save().then(function() { self.set('loading', false); }); } } });
Hummingbird.QuickUpdateItemController = Ember.ObjectController.extend({ loading: false, isComplete: Hummingbird.computed.propertyEqual('episodesWatched', "anime.episodeCount"), percentComplete: function() { var episodesWatched = this.get('episodesWatched'), episodeCount = this.get('anime.episodeCount'); if (episodeCount) { return Math.ceil(100 * episodesWatched / episodeCount); } else { return "?"; } }.property('episodesWatched', 'anime.episodeCount'), nextEpisodeNumber: function() { return this.get('episodesWatched') + 1; }.property('episodesWatched'), actions: { markViewed: function() { var libraryEntry = this.get('model'), self = this; libraryEntry.set('episodesWatched', this.get('nextEpisodeNumber')); if (this.get('isComplete')) { libraryEntry.set('status', "Completed"); } else { libraryEntry.set('status', "Plan to Watch"); } this.set('loading', true); libraryEntry.save().then(function() { self.set('loading', false); }); } } });
Change exercise 4 question 1
from learntools.core import * import tensorflow as tf # Free class Q1(CodingProblem): _solution = "" def check(self): pass class Q2A(ThoughtExperiment): _hint = r"Stacking the second layer expanded the receptive field by one neuron on each side, giving $3+1+1=5$ for each dimension. If you expanded by one neuron again, what would you get?" _solution = r"The third layer would have a $7 \times 7$ receptive field." class Q2B(ThoughtExperiment): _hint = r"This pooling layer collapses a $2 \times 2$ patch into a single pixel, effectively *doubling* the number of connections along each dimension. " _solution = r"Doubling a $7 \times 7$ field produces a $14 \times 14$ field for the final outputs." Q2 = MultipartProblem(Q2A, Q2B) class Q3(CodingProblem): _hint = "You just need a list of numbers, maybe three to five." _solution = CS(""" kernel = tf.constant([0.1, 0.2, 0.3, 0.4]) """) def check(self): pass qvars = bind_exercises(globals(), [ Q1, Q2, Q3, ], var_format='q_{n}', ) __all__ = list(qvars)
from learntools.core import * import tensorflow as tf class Q1A(ThoughtExperiment): _solution = "" class Q1B(ThoughtExperiment): _solution = "" Q1 = MultipartProblem(Q1A, Q1B) class Q2A(ThoughtExperiment): _hint = r"Stacking the second layer expanded the receptive field by one neuron on each side, giving $3+1+1=5$ for each dimension. If you expanded by one neuron again, what would you get?" _solution = r"The third layer would have a $7 \times 7$ receptive field." class Q2B(ThoughtExperiment): _hint = r"This pooling layer collapses a $2 \times 2$ patch into a single pixel, effectively *doubling* the number of connections along each dimension. " _solution = r"Doubling a $7 \times 7$ field produces a $14 \times 14$ field for the final outputs." Q2 = MultipartProblem(Q2A, Q2B) class Q3(CodingProblem): _hint = "You just need a list of numbers, maybe three to five." _solution = CS(""" kernel = tf.constant([0.1, 0.2, 0.3, 0.4]) """) def check(self): pass qvars = bind_exercises(globals(), [ Q1, Q2, Q3, ], var_format='q_{n}', ) __all__ = list(qvars)
Add hypergeometric parameter limits to limit test for multivariate distributions.
<?php namespace MathPHP\Tests\Probability\Distribution\Multivariate; use MathPHP\Probability\Distribution\Multivariate; class LimitsTest extends \PHPUnit\Framework\TestCase { /** * Limits should look like: * (a,b) * [a,b) * (a,b] * [a,b] */ private function limitTest(array $limits) { foreach ($limits as $parameter => $limit) { $this->assertRegExp('/^ ([[(]) (.+) , (.+?) ([])]) $/x', $limit); } } /** * @test Limits constant is correct format */ public function testDirichletParameterLimits() { $this->limitTest(Multivariate\Dirichlet::PARAMETER_LIMITS); } /** * @test Limits constant is correct format */ public function testDirichletSupportLimits() { $this->limitTest(Multivariate\Dirichlet::SUPPORT_LIMITS); } /** * @test Limits constant is correct format */ public function testHypergeometricParameterLimits() { $this->limitTest(Multivariate\Hypergeometric::PARAMETER_LIMITS); } }
<?php namespace MathPHP\Tests\Probability\Distribution\Multivariate; use MathPHP\Probability\Distribution\Multivariate; class LimitsTest extends \PHPUnit\Framework\TestCase { /** * Limits should look like: * (a,b) * [a,b) * (a,b] * [a,b] */ private function limitTest($limits) { foreach ($limits as $parameter => $limit) { $this->assertRegExp('/^ ([[(]) (.+) , (.+?) ([])]) $/x', $limit); } } /** * @test Limits constant is correct format */ public function testDirichletParameterLimits() { $this->limitTest(Multivariate\Dirichlet::PARAMETER_LIMITS); } /** * @test Limits constant is correct format */ public function testDirichletSupportLimits() { $this->limitTest(Multivariate\Dirichlet::SUPPORT_LIMITS); } }
Use a constant time comparison in the API auth
from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ProjectKey class KeyAuthentication(BasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: raise AuthenticationFailed('Invalid api key') if not constant_time_compare(pk.secret_key, password): raise AuthenticationFailed('Invalid api key') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk) def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm
from django.contrib.auth.models import AnonymousUser from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ProjectKey class KeyAuthentication(BasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: raise AuthenticationFailed('Invalid api key') if pk.secret_key != password: raise AuthenticationFailed('Invalid api key') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk) def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm
Use an atomic update operation
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { // just count the number of votes for now var baseScore = object.votes; // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); } } Meteor.methods({ voteForPost: function(post){ var userId = this.userId(); if(!userId) return false; // atomically update the post's votes var query = {_id: post._id, voters: {$ne: userId}}; var update = {$push: {voters: userId}, $inc: {votes: 1}}; Posts.update(query, update); // now update the post's score post = Posts.findOne(post._id); Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); return true; } });
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { // just count the number of votes for now var baseScore = MyVotes.find({votedFor: object._id}).count(); // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); } } Meteor.methods({ voteForPost: function(post){ var user = this.userId(); if(!user) return false; var myvote = MyVotes.findOne({votedFor: post._id, user: user}); if(myvote) return false; MyVotes.insert({votedFor: post._id, user: user, vote: 1}); Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); return true; } });
Fix using wrong index for map selection
package core.entities.menus; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.MessageChannel; public class MapPickMenuManager extends MenuManager<MapPickMenuController, MapPickMenu> { private boolean picking = false; public MapPickMenuManager(Member owner, MapPickMenuController controller) { super(owner, controller); } @Override protected void createMenu() { MessageChannel channel = owner.getUser().openPrivateChannel().complete(); menu = new MapPickMenu(channel, this, controller.getPickStyle()); } @Override protected <T> void menuAction(int pageIndex, T action) { if(!picking) { return; } int fieldIndex = (int)action; int mapIndex = (pageIndex * getOptions().getPageMaxSize()) + fieldIndex; if(mapIndex >= controller.getMapPool().size()) { return; } controller.chooseMap(mapIndex); getOptions().removeOption(pageIndex, fieldIndex); controller.managerActionTaken(this); } public void nextTurn() { picking = !picking; } public boolean canPick() { return picking; } }
package core.entities.menus; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.MessageChannel; public class MapPickMenuManager extends MenuManager<MapPickMenuController, MapPickMenu> { private boolean picking = false; public MapPickMenuManager(Member owner, MapPickMenuController controller) { super(owner, controller); } @Override protected void createMenu() { MessageChannel channel = owner.getUser().openPrivateChannel().complete(); menu = new MapPickMenu(channel, this, controller.getPickStyle()); } @Override protected <T> void menuAction(int pageIndex, T action) { if(!picking) { return; } int fieldIndex = (int)action; int mapIndex = (pageIndex * getOptions().getPageMaxSize()) + fieldIndex; if(mapIndex >= controller.getMapPool().size()) { return; } controller.chooseMap(mapIndex); getOptions().removeOption(pageIndex, mapIndex); controller.managerActionTaken(this); } public void nextTurn() { picking = !picking; } public boolean canPick() { return picking; } }
Add nodes in reverse order.
// Only U/I related JS goes here. function sectionNode(ctx, page) { page.nodesKnown = page.nodesKnown || _.sortBy(instances(ctx, "nodeKnown"), "name").reverse(); page.nodesWanted = page.nodesWanted || _.sortBy(instances(ctx, "nodeWanted"), "name").reverse(); page.obj = findObj(ctx, page.nodesKnown, "nodeKnown", page.ident) || findObj(ctx, page.nodesWanted, "nodeWanted", page.ident); main(ctx, page, "sectionNode"); sectionNodeEventHandlers(ctx, page.r); } function sectionNodeEventHandlers(ctx, r) { r.on({ "newNodeKnown": function(event) { var names = (event.node.value || "").trim(); if (!names) { return; } _.each(names.split(","), function(name) { var nodeKnown = ctx.newObj("nodeKnown", { "name": name }).result; var nodesKnown = r.get("nodesKnown").push(nodeKnown); r.update("nodesKnown"); renderObj(ctx, r, nodeKnown); event.node.value = ""; event.node.focus(); }); } }); }
// Only U/I related JS goes here. function sectionNode(ctx, page) { page.nodesKnown = page.nodesKnown || _.sortBy(instances(ctx, "nodeKnown"), "name").reverse(); page.nodesWanted = page.nodesWanted || _.sortBy(instances(ctx, "nodeWanted"), "name").reverse(); page.obj = findObj(ctx, page.nodesKnown, "nodeKnown", page.ident) || findObj(ctx, page.nodesWanted, "nodeWanted", page.ident); main(ctx, page, "sectionNode"); sectionNodeEventHandlers(ctx, page.r); } function sectionNodeEventHandlers(ctx, r) { r.on({ "newNodeKnown": function(event) { var names = (event.node.value || "").trim(); if (!names) { return; } _.each(names.split(","), function(name) { var nodeKnown = ctx.newObj("nodeKnown", { "name": name }).result; var nodesKnown = r.get("nodesKnown").unshift(nodeKnown); r.update("nodesKnown"); renderObj(ctx, r, nodeKnown); event.node.value = ""; event.node.focus(); }); } }); }
Revert "Make logs dir if missing" This reverts commit ad9191f5c4cb65994aebcab2953f79c885c35248.
<?php function debug_collectionInfoStart($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data\n", $log); } } function debug_collectionInfoEnd($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Finished collecting data\n\n", $log); } } function debug_collectionInterval($debug, $interval, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log); } } function debug($echo, $log) { if ($echo != "" && $echo !== NULL) { echo $echo; } if ($log == TRUE) { if (!file_exists("logs/debug.log")) { $dbglog = fopen("logs/debug.log", "w"); fclose($dbglog); } file_put_contents("logs/debug.log", date("r") . " - " . $echo, FILE_APPEND); } } ?>
<?php function debug_collectionInfoStart($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data\n", $log); } } function debug_collectionInfoEnd($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Finished collecting data\n\n", $log); } } function debug_collectionInterval($debug, $interval, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log); } } function debug($echo, $log) { if ($echo != "" && $echo !== NULL) { echo $echo; } if ($log == TRUE) { if (!file_exists("logs/debug.log")) { mkdir("logs"); $dbglog = fopen("logs/debug.log", "w"); fclose($dbglog); } file_put_contents("logs/debug.log", date("r") . " - " . $echo, FILE_APPEND); } } ?>
Throw FilterException instead of ApplicationException when allocated sequence counter is starved
package org.bricolages.streaming.filter; import org.bricolages.streaming.ApplicationError; import org.bricolages.streaming.SequencialNumberRepository; import lombok.*; class SequenceOp extends SingleColumnOp { static final void register(OpBuilder builder) { builder.registerOperator("sequence", (def) -> new SequenceOp(def, builder.sequencialNumberRepository) ); } long currentValue; long upperValue; SequenceOp(OperatorDefinition def) { super(def); } SequenceOp(OperatorDefinition def, SequencialNumberRepository repo) { this(def); val seq = repo.allocate(); this.currentValue = seq.getLastValue(); this.upperValue = seq.getNextValue(); } private long getNextValue() throws FilterException { currentValue ++; if (currentValue > upperValue) { throw new FilterException("sequence number is starved"); } return currentValue; } @Override public Object applyValue(Object value, Record record) throws FilterException { return getNextValue(); } }
package org.bricolages.streaming.filter; import org.bricolages.streaming.ApplicationError; import org.bricolages.streaming.SequencialNumberRepository; import lombok.*; class SequenceOp extends SingleColumnOp { static final void register(OpBuilder builder) { builder.registerOperator("sequence", (def) -> new SequenceOp(def, builder.sequencialNumberRepository) ); } long currentValue; long upperValue; SequenceOp(OperatorDefinition def) { super(def); } SequenceOp(OperatorDefinition def, SequencialNumberRepository repo) { this(def); val seq = repo.allocate(); this.currentValue = seq.getLastValue(); this.upperValue = seq.getNextValue(); } private long getNextValue() { currentValue ++; if (currentValue > upperValue) { throw new ApplicationError("sequence number is starved"); } return currentValue; } @Override public Object applyValue(Object value, Record record) throws FilterException { return getNextValue(); } }
Correct the argument order in EmptyChangeEx.super call When refactoring exceptions, this one was overlooked, leading to a format string bug. PiperOrigin-RevId: 189939495 Change-Id: I94172b07dbfcb23827efef78b858bab92eb9bd62
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.copybara.exception; /** * An exception thrown by destinations when they detect that there is no change to submit. Usually * this means that the change was already applied. */ public class EmptyChangeException extends ValidationException { public EmptyChangeException(String message) { super(message); } public EmptyChangeException(Throwable cause, String message) { super(cause, message); } public EmptyChangeException(Throwable cause, String message, Object... args) { super(cause, message, args); } }
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.copybara.exception; /** * An exception thrown by destinations when they detect that there is no change to submit. Usually * this means that the change was already applied. */ public class EmptyChangeException extends ValidationException { public EmptyChangeException(String message) { super(message); } public EmptyChangeException(Throwable cause, String message) { super(message, cause); } }
Add -dev suffix to version Makes it clear that there has not been an official release yet.
#!/usr/bin/env python3 from setuptools import setup setup( name="smartbot", version="1.0.0-dev", description="A supposedly smart IRC bot.", url="https://github.com/tomleese/smartbot", author="Tom Leese", author_email="tom@tomleese.me.uk", packages=["smartbot", "smartbot.backends", "smartbot.plugins", "smartbot.stores", "smartbot.utils"], install_requires=[ "PyYaml", "lxml", "requests==2.1.0", "isodate", "textblob", "twython", "cssselect" ], entry_points = { "console_scripts": ["smartbot = smartbot:main"] } )
#!/usr/bin/env python3 from setuptools import setup setup( name="smartbot", version="1.0.0", description="A supposedly smart IRC bot.", url="https://github.com/tomleese/smartbot", author="Tom Leese", author_email="tom@tomleese.me.uk", packages=["smartbot", "smartbot.backends", "smartbot.plugins", "smartbot.stores", "smartbot.utils"], install_requires=[ "PyYaml", "lxml", "requests==2.1.0", "isodate", "textblob", "twython", "cssselect" ], entry_points = { "console_scripts": ["smartbot = smartbot:main"] } )
Make stub creation more concise
'use strict'; var expect = require('chai').expect , twilioCaller = require('../../lib/twilio-caller') , sinon = require('sinon') , mockery = require('mockery'); describe('twilio-caller', function () { describe('#call', function () { var twilio = require('twilio'); var twilioStub = () => ({ calls: new TwilioClientStub() }); var TwilioClientStub = sinon.stub(); var createSpy = sinon.spy(); TwilioClientStub.prototype.create = createSpy; before(function (done) { mockery.enable(); mockery.warnOnUnregistered(false); mockery.registerMock('twilio', twilioStub); done(); }); after(function (done) { mockery.deregisterMock('twilio'); mockery.disable(); done(); }); it('makes a call to client:agent3', function () { twilioCaller.call('agent3', 'callback-url'); expect(createSpy.calledWith({ from: 'my-twilio-number', to: 'client:agent3', url: 'callback-url' })).to.be.true; }); }); });
'use strict'; var expect = require('chai').expect , twilioCaller = require('../../lib/twilio-caller') , sinon = require('sinon') , mockery = require('mockery'); describe('twilio-caller', function () { describe('#call', function () { var twilio = require('twilio'); var twilioStub = function(accountSid, authToken) { return { calls: new TwilioClientStub() } }; var TwilioClientStub = sinon.stub(); var createSpy = sinon.spy(); TwilioClientStub.prototype.create = createSpy; before(function (done) { mockery.enable(); mockery.warnOnUnregistered(false); mockery.registerMock('twilio', twilioStub); done(); }); after(function (done) { mockery.deregisterMock('twilio'); mockery.disable(); done(); }); it('makes a call to client:agent3', function () { twilioCaller.call('agent3', 'callback-url'); expect(createSpy.calledWith({ from: 'my-twilio-number', to: 'client:agent3', url: 'callback-url' })).to.be.true; }); }); });
Change Ti.Platform.name to Ti.Platform.osname in Anvil for Tizen calls
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ module.exports = new function() { var finish; var valueOf; this.init = function(testUtils) { finish = testUtils.finish; valueOf = testUtils.valueOf; } this.name = "jss"; this.tests = [ {name: "platform_jss_dirs"} ] this.platform_jss_dirs = function(testRun) { var test = Ti.UI.createView({ id: "test" }); valueOf(testRun, test).shouldNotBeNull(); if (Ti.Platform.name == "android") { valueOf(testRun, test.backgroundColor).shouldBe("red"); } else if (Ti.Platform.osname == "tizen") { // In Tizen, test.backgroundColor is undefined by default. valueOf(testRun, test.backgroundColor).shouldBeUndefined(); } else { valueOf(testRun, test.backgroundColor).shouldBe("blue"); } finish(testRun); } }
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ module.exports = new function() { var finish; var valueOf; this.init = function(testUtils) { finish = testUtils.finish; valueOf = testUtils.valueOf; } this.name = "jss"; this.tests = [ {name: "platform_jss_dirs"} ] this.platform_jss_dirs = function(testRun) { var test = Ti.UI.createView({ id: "test" }); valueOf(testRun, test).shouldNotBeNull(); if (Ti.Platform.name == "android") { valueOf(testRun, test.backgroundColor).shouldBe("red"); } else if (Ti.Platform.name == "tizen") { // In Tizen, test.backgroundColor is undefined by default. valueOf(testRun, test.backgroundColor).shouldBeUndefined(); } else { valueOf(testRun, test.backgroundColor).shouldBe("blue"); } finish(testRun); } }
Load settings only on "plugin_loaded" Since sublime caches settings internally and subsequent "load_settings" calls don't refer to the disk, it doesn't make sense to load the settings each time a command gets executed.
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): now = datetime.now() timestamp = now.strftime(settings.get('session_name_dateformat')) return '_'.join(['session', timestamp]) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) serialize.dump(session_name, session) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data())
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session class SaveSession(sublime_plugin.ApplicationCommand): def run(self): settings.load() sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): now = datetime.now() timestamp = now.strftime(settings.get('session_name_dateformat')) return '_'.join(['session', timestamp]) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) serialize.dump(session_name, session) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data())
Use cb instead of res.json
function getUser(login, cb) { checkPrivilege(req.session.user.login, function(err, privilege) { users.find({ following: req.session.user.login }, function(err, following) { users.findOne({ login: req.session.user.login }, function(error, user) { var amount = privilege.count; if (user.following) { amount -= user.following.length; } cb(null, { privilege: privilege, following: following, amount: amount, user: user }); }); }); }); } module.exports = getUser;
function getUser(login, cb) { checkPrivilege(req.session.user.login, function(err, privilege) { users.find({ following: req.session.user.login }, function(err, following) { users.findOne({ login: req.session.user.login }, function(error, user) { var amount = privilege.count; if (user.following) { amount -= user.following.length; } res.json({ privilege: privilege, following: following, amount: amount, user: user }); }); }); }); } module.exports = getUser;
Improve cache for hashed js files
const SIX_MONTHS_IN_SECONDS = 15552000; const STATIC_ASSET_PATHS = [ '/public/font/font-v1.css', '/public/font/v1/300.woff', '/public/font/v1/300i.woff', '/public/font/v1/400.woff', '/public/font/v1/400i.woff', '/public/font/v1/700.woff', '/public/font/v1/700i.woff', '/public/favicon.png', '/public/img/busy.gif', '/public/img/fileRenderPlaceholder.png', '/public/img/gerbil-happy.png', '/public/img/gerbil-sad.png', '/public/img/placeholder.png', '/public/img/placeholderTx.gif', '/public/img/thumbnail-broken.png', '/public/img/thumbnail-missing.png', '/public/img/total-background.png', ]; async function redirectMiddleware(ctx, next) { const { request: { url }, } = ctx; const HASHED_JS_REGEX = /^\/public\/.*[a-fA-F0-9]{12}\.js$/i; if (STATIC_ASSET_PATHS.includes(url) || HASHED_JS_REGEX.test(url)) { ctx.set('Cache-Control', `public, max-age=${SIX_MONTHS_IN_SECONDS}`); } return next(); } module.exports = redirectMiddleware;
const SIX_MONTHS_IN_SECONDS = 15552000; const STATIC_ASSET_PATHS = [ '/public/font/font-v1.css', '/public/font/v1/300.woff', '/public/font/v1/300i.woff', '/public/font/v1/400.woff', '/public/font/v1/400i.woff', '/public/font/v1/700.woff', '/public/font/v1/700i.woff', '/public/favicon.png', '/public/img/busy.gif', '/public/img/fileRenderPlaceholder.png', '/public/img/gerbil-happy.png', '/public/img/gerbil-sad.png', '/public/img/placeholder.png', '/public/img/placeholderTx.gif', '/public/img/thumbnail-broken.png', '/public/img/thumbnail-missing.png', '/public/img/total-background.png', ]; async function redirectMiddleware(ctx, next) { const { request: { url }, } = ctx; if (STATIC_ASSET_PATHS.includes(url) || (url.startsWith('/public/ui-') && url.endsWith('.js'))) { ctx.set('Cache-Control', `public, max-age=${SIX_MONTHS_IN_SECONDS}`); } return next(); } module.exports = redirectMiddleware;
Use the `message` attribute if present when creating a GraphQLError
import raven from 'raven' import {GraphQLError} from 'graphql/error' import {parseQueryError} from 'src/server/db/errors' import {getPlayerById} from 'src/server/db/player' import {getLatestCycleForChapter} from 'src/server/db/cycle' const sentry = new raven.Client(process.env.SENTRY_SERVER_DSN) export async function assertPlayersCurrentCycleInState(currentUser, state) { const player = await getPlayerById(currentUser.id, {mergeChapter: true}) const cycleInReflection = await getLatestCycleForChapter(player.chapter.id)('state') .eq(state) if (!cycleInReflection) { throw new GraphQLError(`This action is not allowed when the cycle is not in the ${state} state`) } } export function handleError(unparsedError, defaultMsg) { const err = parseQueryError(unparsedError) if (err.name === 'BadInputError' || err.name === 'LGCustomQueryError') { throw err } console.error(err.stack || err) sentry.captureException(err) throw new GraphQLError(defaultMsg || err.message || err) }
import raven from 'raven' import {GraphQLError} from 'graphql/error' import {parseQueryError} from 'src/server/db/errors' import {getPlayerById} from 'src/server/db/player' import {getLatestCycleForChapter} from 'src/server/db/cycle' const sentry = new raven.Client(process.env.SENTRY_SERVER_DSN) export async function assertPlayersCurrentCycleInState(currentUser, state) { const player = await getPlayerById(currentUser.id, {mergeChapter: true}) const cycleInReflection = await getLatestCycleForChapter(player.chapter.id)('state') .eq(state) if (!cycleInReflection) { throw new GraphQLError(`This action is not allowed when the cycle is not in the ${state} state`) } } export function handleError(unparsedError, defaultMsg) { const err = parseQueryError(unparsedError) if (err.name === 'BadInputError' || err.name === 'LGCustomQueryError') { throw err } console.error(err.stack) sentry.captureException(err) throw new GraphQLError(defaultMsg || err) }
Fix native modules && use string instead of require to require plugin
'use strict' const modifyBabelPreset = require('modify-babel-preset') const mergeByEnv = require('./lib/mergeByEnv') const modifiedReactPreset = modifyBabelPreset('babel-preset-react', { 'babel-plugin-transform-react-jsx': { pragma: 'createElement' } }) module.exports = mergeByEnv({ presets: [ ['babel-preset-es2015', {modules: false}], 'babel-preset-es2016', 'babel-preset-es2017', modifiedReactPreset ], plugins: [ 'babel-plugin-transform-decorators-legacy', 'babel-plugin-transform-object-rest-spread' ], env: { production: { plugins: [ 'babel-plugin-transform-react-constant-elements', 'babel-plugin-transform-react-inline-elements', 'babel-plugin-transform-react-remove-prop-types' ] }, test: { plugins: [ 'babel-plugin-istanbul' ] }, development: { plugins: [ 'babel-plugin-tcomb' ] } } })
'use strict' const modifyBabelPreset = require('modify-babel-preset') const mergeByEnv = require('./lib/mergeByEnv') const modifiedReactPreset = modifyBabelPreset('babel-preset-react', { 'babel-plugin-transform-react-jsx': { pragma: 'createElement' } }) module.exports = mergeByEnv({ presets: [ [require('babel-preset-es2015'), {modules: false}], require('babel-preset-es2016'), require('babel-preset-es2017'), modifiedReactPreset ], plugins: [ require('babel-plugin-transform-decorators-legacy').default, require('babel-plugin-transform-object-rest-spread') ], env: { production: { plugins: [ require('babel-plugin-transform-react-constant-elements'), require('babel-plugin-transform-react-inline-elements'), require('babel-plugin-transform-react-remove-prop-types').default ] }, test: { plugins: [ require('babel-plugin-istanbul') ] }, development: { plugins: [ require('babel-plugin-tcomb').default ] } } })
Store error id in session
import traceback import sys from django.views.debug import ExceptionReporter from django.http import Http404 from erroneous.models import Error class LoggingExceptionHandler(object): """ The logging exception handler """ @staticmethod def create_from_exception(sender, request=None, *args, **kwargs): """ Handles the exception upon receiving the signal. """ kind, info, data = sys.exc_info() if not issubclass(kind, Http404): error = Error.objects.create( kind=kind.__name__, html=ExceptionReporter(request, kind, info, data).get_traceback_html(), path=request.build_absolute_uri(), info=info, data='\n'.join(traceback.format_exception(kind, info, data)), ) error.save() if request: request.session['error_id'] = error.pk
import traceback import sys from django.views.debug import ExceptionReporter from django.http import Http404 from erroneous.models import Error class LoggingExceptionHandler(object): """ The logging exception handler """ @staticmethod def create_from_exception(sender, request=None, *args, **kwargs): """ Handles the exception upon receiving the signal. """ kind, info, data = sys.exc_info() if not issubclass(kind, Http404): error = Error.objects.create( kind=kind.__name__, html=ExceptionReporter(request, kind, info, data).get_traceback_html(), path=request.build_absolute_uri(), info=info, data='\n'.join(traceback.format_exception(kind, info, data)), ) error.save()
Move static methods to be after instance methods
/** * Controller Object to dispatch actions to view/Contact and model/Contacts. * @constructor */ var ContactsController = function() { }; ContactsController.prototype = { setup: function() { var addContact = new AddContactForm(); }, /** * @description Fetches all existing contacts from LocalStorage. */ fetchAll: function() { var contacts = []; var total = localStorage.length; for (i = 0; i < total; i++) { var contact = {}; var key = localStorage.key(i); if (key !== 'debug') { contact.key = key; contact.value = JSON.parse(localStorage.getItem((i + 1).toString())); contacts.push(contact); } } return contacts; }, /** * @description Adds all existing contacts to table. Intended for use * on startup. */ renderAll: function() { var contacts = this.fetchAll(); contacts.forEach(function(currentValue) { var contact = new ContactView(currentValue.key, currentValue.value); }); } }; ContactsController.remove = function(id) { ContactModel.remove(id); ContactView.remove(id); }; ContactsController.render = function(id, contact) { var contactView = new ContactView(id, contact); }; module.exports = ContactsController; // Keep requires after the exports to prevent cirular dependency issues var ContactModel = require('../model/Contacts'); var ContactView = require('../view/Contact'); var AddContactForm = require('../view/AddContactForm');
/** * Controller Object to dispatch actions to view/Contact and model/Contacts. * @constructor */ var ContactsController = function() { }; ContactsController.remove = function(id) { ContactModel.remove(id); ContactView.remove(id); }; ContactsController.render = function(id, contact) { var contactView = new ContactView(id, contact); }; ContactsController.prototype = { setup: function() { var addContact = new AddContactForm(); }, /** * @description Fetches all existing contacts from LocalStorage. */ fetchAll: function() { var contacts = []; var total = localStorage.length; for (i = 0; i < total; i++) { var contact = {}; var key = localStorage.key(i); if (key !== 'debug') { contact.key = key; contact.value = JSON.parse(localStorage.getItem((i + 1).toString())); contacts.push(contact); } } return contacts; }, /** * @description Adds all existing contacts to table. Intended for use * on startup. */ renderAll: function() { var contacts = this.fetchAll(); contacts.forEach(function(currentValue) { var contact = new ContactView(currentValue.key, currentValue.value); }); } }; module.exports = ContactsController; // Keep requires after the exports to prevent cirular dependency issues var ContactModel = require('../model/Contacts'); var ContactView = require('../view/Contact'); var AddContactForm = require('../view/AddContactForm');
Replace Debug class to make Sylius work again :dancer:
<?php use App\Kernel; use Symfony\Component\ErrorHandler\Debug; use Symfony\Component\HttpFoundation\Request; require dirname(__DIR__).'/config/bootstrap.php'; if ($_SERVER['APP_DEBUG']) { umask(0000); Debug::enable(); } if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) { Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); } if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) { Request::setTrustedHosts([$trustedHosts]); } $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use App\Kernel; use Symfony\Component\Debug\Debug; use Symfony\Component\HttpFoundation\Request; require dirname(__DIR__).'/config/bootstrap.php'; if ($_SERVER['APP_DEBUG']) { umask(0000); Debug::enable(); } if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) { Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); } if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) { Request::setTrustedHosts([$trustedHosts]); } $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Add link to a11y statement This is a legal requirement for the client. Resolves: https://dxw.zendesk.com/agent/tickets/10049 Resolves: https://trello.com/c/SJFUZtxT
<nav> <ul id="menu-footer" class="menu"> <li class="menu-all-government-blogs"><a href="https://www.blog.gov.uk">All GOV.UK blogs</a></li> <li class="menu-all-government-blog-posts"><a href="https://www.blog.gov.uk/all-posts/">All GOV.UK blog posts</a></li> <li class="menu-gov-uk"><a href="https://www.gov.uk">GOV.UK</a></li> <li class="menu-all-departments"><a href="https://www.gov.uk/government/organisations">All departments</a></li> <li class="menu-all-policies"><a href="https://www.gov.uk/government/policies">All policies</a></li> <li class="menu-cookies"><a href="https://www.blog.gov.uk/cookies">Cookies</a></li> <li class="menu-a11y"><a href="/accessibility-statement/">Accessibility statement</a></li> </ul> </nav>
<nav> <ul id="menu-footer" class="menu"> <li class="menu-all-government-blogs"><a href="https://www.blog.gov.uk">All GOV.UK blogs</a></li> <li class="menu-all-government-blog-posts"><a href="https://www.blog.gov.uk/all-posts/">All GOV.UK blog posts</a></li> <li class="menu-gov-uk"><a href="https://www.gov.uk">GOV.UK</a></li> <li class="menu-all-departments"><a href="https://www.gov.uk/government/organisations">All departments</a></li> <li class="menu-all-policies"><a href="https://www.gov.uk/government/policies">All policies</a></li> <li class="menu-cookies"><a href="https://www.blog.gov.uk/cookies">Cookies</a></li> </ul> </nav>
Update samples creation for intent rename Update intent --> task, code comment
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) phrases = [ 'Tell me a joke', 'Tell me a joke', 'I\'d like to hear a joke', 'Do you know any good jokes?', 'Joke', 'Tell joke', 'Tell me something funny', 'Make me laugh', 'I want to hear a joke', 'Can I hear a joke?', 'I like jokes', 'I\'d like to hear a punny joke' ] # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list # Replace 'UDXXX...' with the SID for the task you just created. for phrase in phrases: sample = client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .samples \ .create(language='en-us', tagged_text=phrase) print(sample.sid)
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) phrases = [ 'Tell me a joke', 'Tell me a joke', 'I\'d like to hear a joke', 'Do you know any good jokes?', 'Joke', 'Tell joke', 'Tell me something funny', 'Make me laugh', 'I want to hear a joke', 'Can I hear a joke?', 'I like jokes', 'I\'d like to hear a punny joke' ] # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list for phrase in phrases: sample = client.preview.understand \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .tasks('tell-a-joke') \ .samples \ .create(language='en-us', tagged_text=phrase) print(sample.sid)
Add Button with the Spinner story.
/** * Site Kit by Google, Copyright 2022 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. */ /** * Internal dependencies */ import SpinnerButton from './SpinnerButton'; const Template = ( args ) => <SpinnerButton { ...args } />; export const DefaultButton = Template.bind( {} ); DefaultButton.storyName = 'Default Button'; DefaultButton.args = { children: 'Default Button', onClick: () => new Promise( ( resolve ) => setTimeout( resolve, 5000 ) ), }; export const ButtonWithSpinner = Template.bind( {} ); ButtonWithSpinner.storyName = 'Button with the Spinner'; ButtonWithSpinner.args = { children: 'Spinner Button', isSaving: true, }; export default { title: 'Components/SpinnerButton', component: SpinnerButton, };
/** * Site Kit by Google, Copyright 2022 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. */ /** * Internal dependencies */ import SpinnerButton from './SpinnerButton'; const Template = ( args ) => <SpinnerButton { ...args } />; export const DefaultButton = Template.bind( {} ); DefaultButton.storyName = 'Default Button'; DefaultButton.args = { children: 'Default Button', onClick: () => new Promise( ( resolve ) => setTimeout( resolve, 5000 ) ), }; export default { title: 'Components/SpinnerButton', component: SpinnerButton, };
Allow to filter expert requests by state [WAL-1041]
import django_filters from nodeconductor.core import filters as core_filters from . import models class ExpertProviderFilter(django_filters.FilterSet): customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid') customer_uuid = django_filters.UUIDFilter(name='customer__uuid') class Meta(object): model = models.ExpertProvider fields = [] class ExpertRequestFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') project = core_filters.URLFilter(view_name='project-detail', name='project__uuid') project_uuid = django_filters.UUIDFilter(name='project__uuid') class Meta(object): model = models.ExpertRequest fields = ['state'] class ExpertBidFilter(django_filters.FilterSet): request = core_filters.URLFilter(view_name='expert-request-detail', name='request__uuid') request_uuid = django_filters.UUIDFilter(name='request__uuid') class Meta(object): model = models.ExpertBid fields = []
import django_filters from nodeconductor.core import filters as core_filters from . import models class ExpertProviderFilter(django_filters.FilterSet): customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid') customer_uuid = django_filters.UUIDFilter(name='customer__uuid') class Meta(object): model = models.ExpertProvider fields = [] class ExpertRequestFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') project = core_filters.URLFilter(view_name='project-detail', name='project__uuid') project_uuid = django_filters.UUIDFilter(name='project__uuid') class Meta(object): model = models.ExpertRequest fields = [] class ExpertBidFilter(django_filters.FilterSet): request = core_filters.URLFilter(view_name='expert-request-detail', name='request__uuid') request_uuid = django_filters.UUIDFilter(name='request__uuid') class Meta(object): model = models.ExpertBid fields = []
Remove require of removed module
var timerStart = performance.now(); try { var settings = require('_settings'); var controller = require('stage_controller'); var creeps = require('stage_creeps'); var spawners = require('stage_spawners'); controller.pre(); creeps(); spawners(); controller.post(); } catch (e) { console.log('Caught exception:'); if (typeof e === "object") { if (e.stack) { if (e.name && e.message) { console.log(e.name + ': ' + e.message); } console.log(e.stack); } else { console.log(e, JSON.stringify(e)); } } else { console.log(e); } } var timerEnd = performance.now(); var timerDiff = timerEnd - timerStart; if (timerDiff > settings.roundTimeLimit) { console.log('Warning: Round ' + Game.time + ' took ' + timerDiff + ' ms to complete'); }
var timerStart = performance.now(); try { var settings = require('_settings'); var controller = require('stage_controller'); var debug = require('stage_debug'); var creeps = require('stage_creeps'); var spawners = require('stage_spawners'); controller.pre(); creeps(); spawners(); controller.post(); } catch (e) { console.log('Caught exception:'); if (typeof e === "object") { if (e.stack) { if (e.name && e.message) { console.log(e.name + ': ' + e.message); } console.log(e.stack); } else { console.log(e, JSON.stringify(e)); } } else { console.log(e); } } var timerEnd = performance.now(); var timerDiff = timerEnd - timerStart; if (timerDiff > settings.roundTimeLimit) { console.log('Warning: Round ' + Game.time + ' took ' + timerDiff + ' ms to complete'); }
Add membership types, and profile visibility
var keystone = require('keystone'), Types = keystone.Field.Types; /** * User Model * ========== */ var User = new keystone.List('User'); User.add({ name: { type: Types.Name, required: true, index: true }, email: { type: Types.Email, initial: true, required: true, index: true }, password: { type: Types.Password, initial: true, required: true }, groups: { type: Types.Relationship, ref: 'UserGroup', many: true }, registeredOn: { type: Types.Date, default: Date.now, noedit: true } }, 'Membership', { membershipType: { type: Types.Select, options: 'unpaid, student, regular', required: true, emptyOption: false, default: 'unpaid' }, paidUntil: { type: Types.Date }, }, 'Profile', { visibility: { type: Types.Select, options: [{value: 0, label: 'Committee only'}, {value: 1, label: 'Members only'}, {value: 2, label: 'Public'}], required: true, emptyOption: false, default: 0, initial: true }, }, 'Permissions', { isAdmin: { type: Boolean, label: 'Can access Keystone', index: true } }); // Provide access to Keystone User.schema.virtual('canAccessKeystone').get(function() { return this.isAdmin; }); /** * Relationships */ User.relationship({ ref: 'Post', path: 'author' }); /** * Registration */ User.defaultColumns = 'name, email, isAdmin'; User.register();
var keystone = require('keystone'), Types = keystone.Field.Types; /** * User Model * ========== */ var User = new keystone.List('User'); User.add({ name: { type: Types.Name, required: true, index: true }, email: { type: Types.Email, initial: true, required: true, index: true }, password: { type: Types.Password, initial: true, required: true }, groups: { type: Types.Relationship, ref: 'UserGroup', many: true }, registeredOn: { type: Types.Date, default: Date.now, noedit: true }, paidUntil: { type: Types.Date }, }, 'Permissions', { isAdmin: { type: Boolean, label: 'Can access Keystone', index: true } }); // Provide access to Keystone User.schema.virtual('canAccessKeystone').get(function() { return this.isAdmin; }); /** * Relationships */ User.relationship({ ref: 'Post', path: 'author' }); /** * Registration */ User.defaultColumns = 'name, email, isAdmin'; User.register();
Fix list to tuple type
package org.cafebabepy.runtime.object; import org.cafebabepy.runtime.PyObject; import org.cafebabepy.runtime.Python; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Created by yotchang4s on 2017/06/19. */ public class PyTupleObject extends AbstractPyObjectObject { private final List<PyObject> list; public PyTupleObject(Python runtime, PyObject... value) { super(runtime, runtime.typeOrThrow("builtins.tuple")); this.list = Collections.unmodifiableList(Arrays.asList(value)); } public List<PyObject> getList() { return this.list; } public PyObject get(PyIntObject i) { return this.list.get(i.getIntValue()); } public PyObject getLen() { return this.runtime.number(list.size()); } @Override public String asJavaString() { return this.list.stream() .map(PyObject::asJavaString) .collect(Collectors.joining(",", "(", ")")); } }
package org.cafebabepy.runtime.object; import org.cafebabepy.runtime.PyObject; import org.cafebabepy.runtime.Python; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Created by yotchang4s on 2017/06/19. */ public class PyTupleObject extends AbstractPyObjectObject { private final List<PyObject> list; public PyTupleObject(Python runtime, PyObject... value) { super(runtime, runtime.typeOrThrow("builtins.list")); this.list = Collections.unmodifiableList(Arrays.asList(value)); } public List<PyObject> getList() { return this.list; } public PyObject get(PyIntObject i) { return this.list.get(i.getIntValue()); } public PyObject getLen() { return this.runtime.number(list.size()); } @Override public String asJavaString() { return this.list.stream() .map(PyObject::asJavaString) .collect(Collectors.joining(",", "(", ")")); } }
Add apikey when creating a user
# -*- coding: utf8 -*- from flask.ext.security import UserMixin, RoleMixin from ..models import db from uuid import uuid4 roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) apikey = db.Column(db.String(36), nullable=False) def __init__(self, *args, **kwargs): kwargs['apikey'] = str(uuid4()) super(self.__class__, self).__init__(**kwargs) def get_user_from_api_key(self, apikey): user = self.user_model.query.filter_by(apikey=apikey) return user.get() or None
# -*- coding: utf8 -*- from flask.ext.security import UserMixin, RoleMixin from ..models import db roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) apikey = db.Column(db.String(36), nullable=False) def get_user_from_api_key(self, apikey): user = self.user_model.query.filter_by(apikey=apikey) return user.get() or None
Fix issue releated to create and update of the version
<?php namespace Jira\Service; use Jira\HttpClient; class Version { /** * @var HttpClient */ protected $client; /** * Project constructor. * @param HttpClient $client */ public function __construct($client) { $this->client = $client; } /** * @param string $versionId * @return object */ public function getVersion($versionId) { return $this->client->request('GET','/rest/api/2/version/'. urlencode($versionId)); } /** * Update the version * * @param object $version */ public function updateVersion($version) { $this->client->request('PUT','/rest/api/2/version/'. $version->id, [ 'json' => json_decode(json_encode($version), true) ]); } /** * Create a new version * * @param object $version */ public function createVersion($version) { $this->client->request('POST','/rest/api/2/version', [ 'json' => json_decode(json_encode($version), true) ]); } }
<?php namespace Jira\Service; use Jira\HttpClient; class Version { /** * @var HttpClient */ protected $client; /** * Project constructor. * @param HttpClient $client */ public function __construct($client) { $this->client = $client; } /** * @param string $versionId * @return object */ public function getVersion($versionId) { return $this->client->request('GET','/rest/api/2/version/'. urlencode($versionId)); } /** * Update the version * * @param object $version */ public function updateVersion($version) { $this->client->request('PUT','/rest/api/2/version/'. $version->id, ['body' => json_decode(json_encode($version), true)]); } /** * Create a new version * * @param object $version */ public function createVersion($version) { $this->client->request('POST','/rest/api/2/version', ['body' => json_decode(json_encode($version), true)]); } }
Add search bar to static about/help pages
var imagespace = imagespace || {}; _.extend(imagespace, { models: {}, collections: {}, views: {}, router: new Backbone.Router(), events: _.clone(Backbone.Events), userData: { images: [] }, solrIdToUrl: function (id) { var parts = id.split('/'), file = parts[parts.length - 1]; if (id.indexOf('cmuImages') !== -1) { file = 'cmuImages/' + file; } return imagespace.prefix + file; }, urlToSolrId: function (url) { var parts = url.split('/'), file = parts[parts.length - 1]; if (file.length < 30) { return; } if (url.indexOf('cmuImages') !== -1) { file = 'cmuImages/' + file; } return imagespace.solrPrefix + file; } }); girder.router.enabled(false); imagespace.router.route('page/:name', 'page', function (name) { imagespace.headerView.render(); $('#g-app-body-container').html(imagespace.templates[name]); });
var imagespace = imagespace || {}; _.extend(imagespace, { models: {}, collections: {}, views: {}, router: new Backbone.Router(), events: _.clone(Backbone.Events), userData: { images: [] }, solrIdToUrl: function (id) { var parts = id.split('/'), file = parts[parts.length - 1]; if (id.indexOf('cmuImages') !== -1) { file = 'cmuImages/' + file; } return imagespace.prefix + file; }, urlToSolrId: function (url) { var parts = url.split('/'), file = parts[parts.length - 1]; if (file.length < 30) { return; } if (url.indexOf('cmuImages') !== -1) { file = 'cmuImages/' + file; } return imagespace.solrPrefix + file; } }); girder.router.enabled(false); imagespace.router.route('page/:name', 'page', function (name) { $('#g-app-body-container').html(imagespace.templates[name]); });
Fix usage with external React on 0.13+
var deepForceUpdate = require('./deepForceUpdate'); var isRequestPending = false; module.exports = function requestForceUpdateAll(getRootInstances, React) { if (isRequestPending) { return; } /** * Forces deep re-render of all mounted React components. * Hat's off to Omar Skalli (@Chetane) for suggesting this approach: * https://gist.github.com/Chetane/9a230a9fdcdca21a4e29 */ function forceUpdateAll() { isRequestPending = false; var rootInstances = getRootInstances(), rootInstance; for (var key in rootInstances) { if (rootInstances.hasOwnProperty(key)) { rootInstance = rootInstances[key]; // `|| rootInstance` for React 0.12 and earlier rootInstance = rootInstance._reactInternalInstance || rootInstance; deepForceUpdate(rootInstance, React); } } } setTimeout(forceUpdateAll); };
var deepForceUpdate = require('./deepForceUpdate'); var isRequestPending = false; module.exports = function requestForceUpdateAll(getRootInstances, React) { if (isRequestPending) { return; } /** * Forces deep re-render of all mounted React components. * Hat's off to Omar Skalli (@Chetane) for suggesting this approach: * https://gist.github.com/Chetane/9a230a9fdcdca21a4e29 */ function forceUpdateAll() { isRequestPending = false; var rootInstances = getRootInstances(), rootInstance; for (var key in rootInstances) { if (rootInstances.hasOwnProperty(key)) { deepForceUpdate(rootInstances[key], React); } } } setTimeout(forceUpdateAll); };
Set custom exception's prototype chain properly
(function (GoL, _) { "use strict"; var cellNameToSymbol = { Alive: '*', Dead: '.' }; function InvalidArgument(message) { this.name = 'InvalidArgument'; this.message = message; } InvalidArgument.prototype = new Error(); function invertObject(object) { return _(object).chain() .map(function (val, key) { return [val, key]; }) .reduce(function (memo, valKey) { memo[valKey[0]] = valKey[1]; return memo; }, {}) .value(); } GoL.Support = { InvalidArgument: InvalidArgument, CellTypes: cellNameToSymbol, invertObject: invertObject, validateCanvas: function (canvas) { if (!canvas || !_.isFunction(canvas.getContext)) { throw new InvalidArgument('Not a canvas element'); } return canvas; }, parseCellGrid: function (layout) { throw 'TODO: Implement me'; } }; })(GameOfLife, _);
(function (GoL, _) { "use strict"; var cellNameToSymbol = { Alive: '*', Dead: '.' }; function InvalidArgument(message) { this.prototype = Error.prototype; this.name = 'InvalidArgument'; this.message = message; this.toString = function () { return this.name + ': ' + this.message; }; } function invertObject(object) { return _(object).chain() .map(function (val, key) { return [val, key]; }) .reduce(function (memo, valKey) { memo[valKey[0]] = valKey[1]; return memo; }, {}) .value(); } GoL.Support = { InvalidArgument: InvalidArgument, CellTypes: cellNameToSymbol, invertObject: invertObject, validateCanvas: function (canvas) { if (!canvas || !_.isFunction(canvas.getContext)) { throw new InvalidArgument('Not a canvas element'); } return canvas; }, parseCellGrid: function (layout) { throw 'TODO: Implement me'; } }; })(GameOfLife, _);
Enhance coding style and add use Log https://codeclimate.com/github/alariva/timegrid/app/BookingStrategy.php#all
<?php namespace App; use Carbon\Carbon; use App\BookingStrategyTimeslot; use App\BookingStrategyDateslot; use Log; class BookingStrategy { private $strategy = null; public function __construct($strategyId) { switch ($strategyId) { case 'timeslot': $this->strategy = new BookingStrategyTimeslot(); break; case 'dateslot': $this->strategy = new BookingStrategyDateslot(); break; default: Log::warning("BookingStrategy: __construct: Illegal strategy:{$this->strategy}"); break; } } public function makeReservation(User $issuer, Business $business, $data) { return $this->strategy->makeReservation($issuer, $business, $data); } } interface BookingStrategyInterface { public function makeReservation(User $issuer, Business $business, $data); }
<?php namespace App; use Carbon\Carbon; use App\BookingStrategyTimeslot; use App\BookingStrategyDateslot; class BookingStrategy { private $strategy = null; public function __construct($strategyId) { switch ($strategyId) { case 'timeslot': $this->strategy = new BookingStrategyTimeslot(); break; case 'dateslot': $this->strategy = new BookingStrategyDateslot(); break; default: Log::warning("BookingStrategy: __construct: Illegal strategy:{$this->strategy}"); break; } } public function makeReservation(User $issuer, Business $business, $data) { return $this->strategy->makeReservation($issuer, $business, $data); } } interface BookingStrategyInterface { public function makeReservation(User $issuer, Business $business, $data); }
Add a remote option to Say
from pyheufybot.module_interface import Module, ModulePriority, ModuleType class ModuleSpawner(Module): def __init__(self, bot): self.bot = bot self.name = "Say" self.trigger = "say|sayremote" self.moduleType = ModuleType.COMMAND self.modulePriority = ModulePriority.NORMAL self.messageTypes = ["PRIVMSG"] self.helpText = "Usage: say <message>/sayremote <target> <message> | Makes the bot say the given line." def execute(self, message): if message.params[0].lower() == "say": if len(message.params) == 1: self.bot.msg(message.replyTo, "Say what?") else: self.bot.msg(message.replyTo, " ".join(message.params[1:])) elif message.params[0].lower() == "sayremote": if len(message.params) < 3: self.bot.msg(message.replyTo, "Say what?") else: self.bot.msg(message.params[1], " ".join(message.params[2:])) return True
from pyheufybot.module_interface import Module, ModulePriority, ModuleType class ModuleSpawner(Module): def __init__(self, bot): self.bot = bot self.name = "Say" self.trigger = "say" self.moduleType = ModuleType.COMMAND self.modulePriotity = ModulePriority.NORMAL self.messageTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line." def execute(self, message): if len(message.params) == 1: self.bot.msg(message.replyTo, "Say what?") else: self.bot.msg(message.replyTo, " ".join(message.params[1:])) return True