commit
stringlengths
40
40
old_file
stringlengths
6
152
new_file
stringlengths
6
152
old_contents
stringlengths
1.5k
3.26k
new_contents
stringlengths
22
2.94k
subject
stringlengths
18
317
message
stringlengths
20
1.49k
lang
stringclasses
10 values
license
stringclasses
13 values
repos
stringlengths
7
33.9k
config
stringclasses
10 values
content
stringlengths
1.79k
5.86k
0b264c9c64a02cad2a6fb00d21005f5dea698cec
Sources/WebP/WebPDecoder+Platform.swift
Sources/WebP/WebPDecoder+Platform.swift
import Foundation import CWebP #if os(macOS) || os(iOS) import CoreGraphics extension WebPDecoder { public func decode(_ webPData: Data, options: WebPDecoderOptions) throws -> CGImage { let feature = try WebPImageInspector.inspect(webPData) let height: Int = options.useScaling ? options.scaledHeight : feature.height let width: Int = options.useScaling ? options.scaledWidth : feature.width let decodedData: Data = try decode(byrgbA: webPData, options: options) return try decodedData.withUnsafeBytes { rawPtr in guard let bindedBasePtr = rawPtr.baseAddress?.assumingMemoryBound(to: UInt8.self) else { throw WebPError.unexpectedPointerError } let provider = CGDataProvider(dataInfo: nil, data: bindedBasePtr, size: decodedData.count, releaseData: { (_, _, _) in })! let bitmapInfo = CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue ) let colorSpace = CGColorSpaceCreateDeviceRGB() let renderingIntent = CGColorRenderingIntent.defaultIntent let bytesPerPixel = 4 return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8 * bytesPerPixel, bytesPerRow: bytesPerPixel * width, space: colorSpace, bitmapInfo: bitmapInfo, provider: provider, decode: nil, shouldInterpolate: false, intent: renderingIntent)! } } } #endif
import Foundation import CWebP #if os(macOS) || os(iOS) import CoreGraphics extension WebPDecoder { public func decode(_ webPData: Data, options: WebPDecoderOptions) throws -> CGImage { let feature = try WebPImageInspector.inspect(webPData) let height: Int = options.useScaling ? options.scaledHeight : feature.height let width: Int = options.useScaling ? options.scaledWidth : feature.width let decodedData: CFData = try decode(byrgbA: webPData, options: options) as CFData let provider = CGDataProvider(data: decodedData)! let bitmapInfo = CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue ) let colorSpace = CGColorSpaceCreateDeviceRGB() let renderingIntent = CGColorRenderingIntent.defaultIntent let bytesPerPixel = 4 let cgImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8 * bytesPerPixel, bytesPerRow: bytesPerPixel * width, space: colorSpace, bitmapInfo: bitmapInfo, provider: provider, decode: nil, shouldInterpolate: false, intent: renderingIntent)! return cgImage } } #endif
Use CFData to instantiate CGDataProvider
Use CFData to instantiate CGDataProvider In order to fix the issue that CGDataProvider reads the memory kept by decoded Data asynchornously, meaning that decoded data will be automatically released as per how Swift treats value semantics. This change instead uses another initialiser of CGDataProvider which reads Data (as CFData) sychronously. This way we don't have to be worried about the timing of releasing memory allocated in C-layer and released by value semantics's move.
Swift
mit
ainame/Swift-WebP,ainame/Swift-WebP,ainame/Swift-WebP
swift
## Code Before: import Foundation import CWebP #if os(macOS) || os(iOS) import CoreGraphics extension WebPDecoder { public func decode(_ webPData: Data, options: WebPDecoderOptions) throws -> CGImage { let feature = try WebPImageInspector.inspect(webPData) let height: Int = options.useScaling ? options.scaledHeight : feature.height let width: Int = options.useScaling ? options.scaledWidth : feature.width let decodedData: Data = try decode(byrgbA: webPData, options: options) return try decodedData.withUnsafeBytes { rawPtr in guard let bindedBasePtr = rawPtr.baseAddress?.assumingMemoryBound(to: UInt8.self) else { throw WebPError.unexpectedPointerError } let provider = CGDataProvider(dataInfo: nil, data: bindedBasePtr, size: decodedData.count, releaseData: { (_, _, _) in })! let bitmapInfo = CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue ) let colorSpace = CGColorSpaceCreateDeviceRGB() let renderingIntent = CGColorRenderingIntent.defaultIntent let bytesPerPixel = 4 return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8 * bytesPerPixel, bytesPerRow: bytesPerPixel * width, space: colorSpace, bitmapInfo: bitmapInfo, provider: provider, decode: nil, shouldInterpolate: false, intent: renderingIntent)! } } } #endif ## Instruction: Use CFData to instantiate CGDataProvider In order to fix the issue that CGDataProvider reads the memory kept by decoded Data asynchornously, meaning that decoded data will be automatically released as per how Swift treats value semantics. This change instead uses another initialiser of CGDataProvider which reads Data (as CFData) sychronously. This way we don't have to be worried about the timing of releasing memory allocated in C-layer and released by value semantics's move. ## Code After: import Foundation import CWebP #if os(macOS) || os(iOS) import CoreGraphics extension WebPDecoder { public func decode(_ webPData: Data, options: WebPDecoderOptions) throws -> CGImage { let feature = try WebPImageInspector.inspect(webPData) let height: Int = options.useScaling ? options.scaledHeight : feature.height let width: Int = options.useScaling ? options.scaledWidth : feature.width let decodedData: CFData = try decode(byrgbA: webPData, options: options) as CFData let provider = CGDataProvider(data: decodedData)! let bitmapInfo = CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue ) let colorSpace = CGColorSpaceCreateDeviceRGB() let renderingIntent = CGColorRenderingIntent.defaultIntent let bytesPerPixel = 4 let cgImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8 * bytesPerPixel, bytesPerRow: bytesPerPixel * width, space: colorSpace, bitmapInfo: bitmapInfo, provider: provider, decode: nil, shouldInterpolate: false, intent: renderingIntent)! return cgImage } } #endif
a05dafc3003d9133549d4d0e43c1a04b5734588a
src/settings/handlers/ConfigSettingsHandler.js
src/settings/handlers/ConfigSettingsHandler.js
/* Copyright 2017 Travis Ralston Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import SettingsHandler from "./SettingsHandler"; import SdkConfig from "../../SdkConfig"; /** * Gets and sets settings at the "config" level. This handler does not make use of the * roomId parameter. */ export default class ConfigSettingsHandler extends SettingsHandler { getValue(settingName, roomId) { const config = SdkConfig.get() || {}; // Special case themes if (settingName === "theme") { return config["default_theme"]; } const settingsConfig = config["settingDefaults"]; if (!settingsConfig || !settingsConfig[settingName]) return null; return settingsConfig[settingName]; } setValue(settingName, roomId, newValue) { throw new Error("Cannot change settings at the config level"); } canSetValue(settingName, roomId) { return false; } isSupported() { return true; // SdkConfig is always there } }
/* Copyright 2017 Travis Ralston Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import SettingsHandler from "./SettingsHandler"; import SdkConfig from "../../SdkConfig"; import {isNullOrUndefined} from "matrix-js-sdk/src/utils"; /** * Gets and sets settings at the "config" level. This handler does not make use of the * roomId parameter. */ export default class ConfigSettingsHandler extends SettingsHandler { getValue(settingName, roomId) { const config = SdkConfig.get() || {}; // Special case themes if (settingName === "theme") { return config["default_theme"]; } const settingsConfig = config["settingDefaults"]; if (!settingsConfig || isNullOrUndefined(settingsConfig[settingName])) return null; return settingsConfig[settingName]; } setValue(settingName, roomId, newValue) { throw new Error("Cannot change settings at the config level"); } canSetValue(settingName, roomId) { return false; } isSupported() { return true; // SdkConfig is always there } }
Check for null config settings a bit safer
Check for null config settings a bit safer Fixes https://github.com/vector-im/riot-web/issues/12254
JavaScript
apache-2.0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk
javascript
## Code Before: /* Copyright 2017 Travis Ralston Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import SettingsHandler from "./SettingsHandler"; import SdkConfig from "../../SdkConfig"; /** * Gets and sets settings at the "config" level. This handler does not make use of the * roomId parameter. */ export default class ConfigSettingsHandler extends SettingsHandler { getValue(settingName, roomId) { const config = SdkConfig.get() || {}; // Special case themes if (settingName === "theme") { return config["default_theme"]; } const settingsConfig = config["settingDefaults"]; if (!settingsConfig || !settingsConfig[settingName]) return null; return settingsConfig[settingName]; } setValue(settingName, roomId, newValue) { throw new Error("Cannot change settings at the config level"); } canSetValue(settingName, roomId) { return false; } isSupported() { return true; // SdkConfig is always there } } ## Instruction: Check for null config settings a bit safer Fixes https://github.com/vector-im/riot-web/issues/12254 ## Code After: /* Copyright 2017 Travis Ralston Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import SettingsHandler from "./SettingsHandler"; import SdkConfig from "../../SdkConfig"; import {isNullOrUndefined} from "matrix-js-sdk/src/utils"; /** * Gets and sets settings at the "config" level. This handler does not make use of the * roomId parameter. */ export default class ConfigSettingsHandler extends SettingsHandler { getValue(settingName, roomId) { const config = SdkConfig.get() || {}; // Special case themes if (settingName === "theme") { return config["default_theme"]; } const settingsConfig = config["settingDefaults"]; if (!settingsConfig || isNullOrUndefined(settingsConfig[settingName])) return null; return settingsConfig[settingName]; } setValue(settingName, roomId, newValue) { throw new Error("Cannot change settings at the config level"); } canSetValue(settingName, roomId) { return false; } isSupported() { return true; // SdkConfig is always there } }
52f772e954ae26a70fe914ea00e4280660938c6a
telemetry/src/main/kotlin/org/strykeforce/thirdcoast/telemetry/grapher/ClientHandler.kt
telemetry/src/main/kotlin/org/strykeforce/thirdcoast/telemetry/grapher/ClientHandler.kt
package org.strykeforce.thirdcoast.telemetry.grapher import mu.KotlinLogging import okio.Buffer import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetSocketAddress import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit.MILLISECONDS private val logger = KotlinLogging.logger {} /** Handles data streaming with Grapher client. */ class ClientHandler(private val port: Int, private val socket: DatagramSocket) { private var scheduler: ScheduledExecutorService? = null /** * Start streaming the items specified in the subscription. * * @param subscription Items to stream to client */ fun start(subscription: Subscription) { if (scheduler != null) return val address = InetSocketAddress(subscription.client, port) val packet = DatagramPacket(ByteArray(0), 0, address) val buffer = Buffer() val runnable = { subscription.measurementsToJson(buffer) val bytes = buffer.readByteArray() packet.setData(bytes, 0, bytes.size) socket.send(packet) } scheduler = Executors.newSingleThreadScheduledExecutor().also { it.scheduleAtFixedRate(runnable, 0, 5, MILLISECONDS) } logger.info { "sending graph data to ${subscription.client}:$port" } } /** Stop streaming to client. */ fun shutdown() { scheduler?.let { it.shutdown() } scheduler = null logger.info("stopped streaming graph data") } }
package org.strykeforce.thirdcoast.telemetry.grapher import mu.KotlinLogging import okio.Buffer import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetSocketAddress import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit.MILLISECONDS private const val PERIOD = 5L // milliseconds private val logger = KotlinLogging.logger {} /** Handles data streaming with Grapher client. */ class ClientHandler(private val port: Int, private val socket: DatagramSocket) { private var scheduler: ScheduledExecutorService? = null /** * Start streaming the items specified in the subscription. * * @param subscription Items to stream to client */ fun start(subscription: Subscription) { if (scheduler != null) return val address = InetSocketAddress(subscription.client, port) val packet = DatagramPacket(ByteArray(0), 0, address) val buffer = Buffer() val runnable = { subscription.measurementsToJson(buffer) val bytes = buffer.readByteArray() packet.setData(bytes, 0, bytes.size) socket.send(packet) } scheduler = Executors.newSingleThreadScheduledExecutor().also { it.scheduleAtFixedRate(runnable, 0, PERIOD, MILLISECONDS) } logger.info { "sending graph data to ${subscription.client}:$port" } } /** Stop streaming to client. */ fun shutdown() { scheduler?.let { it.shutdown() } scheduler = null logger.info("stopped streaming graph data") } }
Move period value to constant
Move period value to constant
Kotlin
mit
strykeforce/thirdcoast,strykeforce/thirdcoast,strykeforce/thirdcoast
kotlin
## Code Before: package org.strykeforce.thirdcoast.telemetry.grapher import mu.KotlinLogging import okio.Buffer import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetSocketAddress import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit.MILLISECONDS private val logger = KotlinLogging.logger {} /** Handles data streaming with Grapher client. */ class ClientHandler(private val port: Int, private val socket: DatagramSocket) { private var scheduler: ScheduledExecutorService? = null /** * Start streaming the items specified in the subscription. * * @param subscription Items to stream to client */ fun start(subscription: Subscription) { if (scheduler != null) return val address = InetSocketAddress(subscription.client, port) val packet = DatagramPacket(ByteArray(0), 0, address) val buffer = Buffer() val runnable = { subscription.measurementsToJson(buffer) val bytes = buffer.readByteArray() packet.setData(bytes, 0, bytes.size) socket.send(packet) } scheduler = Executors.newSingleThreadScheduledExecutor().also { it.scheduleAtFixedRate(runnable, 0, 5, MILLISECONDS) } logger.info { "sending graph data to ${subscription.client}:$port" } } /** Stop streaming to client. */ fun shutdown() { scheduler?.let { it.shutdown() } scheduler = null logger.info("stopped streaming graph data") } } ## Instruction: Move period value to constant ## Code After: package org.strykeforce.thirdcoast.telemetry.grapher import mu.KotlinLogging import okio.Buffer import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetSocketAddress import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit.MILLISECONDS private const val PERIOD = 5L // milliseconds private val logger = KotlinLogging.logger {} /** Handles data streaming with Grapher client. */ class ClientHandler(private val port: Int, private val socket: DatagramSocket) { private var scheduler: ScheduledExecutorService? = null /** * Start streaming the items specified in the subscription. * * @param subscription Items to stream to client */ fun start(subscription: Subscription) { if (scheduler != null) return val address = InetSocketAddress(subscription.client, port) val packet = DatagramPacket(ByteArray(0), 0, address) val buffer = Buffer() val runnable = { subscription.measurementsToJson(buffer) val bytes = buffer.readByteArray() packet.setData(bytes, 0, bytes.size) socket.send(packet) } scheduler = Executors.newSingleThreadScheduledExecutor().also { it.scheduleAtFixedRate(runnable, 0, PERIOD, MILLISECONDS) } logger.info { "sending graph data to ${subscription.client}:$port" } } /** Stop streaming to client. */ fun shutdown() { scheduler?.let { it.shutdown() } scheduler = null logger.info("stopped streaming graph data") } }
60830d0e9ae55207a2d6c38ad6f509b411b10c42
page/4search.html
page/4search.html
--- layout: default title: Search permalink: /search/ icon: search type: page --- <div class="page clearfix"> <div class="left"> <h1>{{page.title}}</h1> <hr> <p> Search by the keyword you entered. </p> <p> Matching conditions are <strong>title</strong> of the article or <strong>contents</strong> of the article. </p> <hr> <!-- Html Elements for Search --> <div id="search-container"> <input type="text" id="search-input" placeholder="Search"> <ul id="results-container"></ul> </div> <!-- Script pointing to jekyll-search.js --> <script src="/js/jekyll-search.js" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: '/search.json', searchResultTemplate: '<li><a href="{url}" title="{desc}">{title}</a></li>', noResultsText: 'No results found', limit: 20, fuzzy: false, exclude: [] }) </script> <style> input[type=text], select { width: 40%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } </style> </div> </div>
--- layout: default title: Search permalink: /search/ icon: search type: page --- <div class="page clearfix"> <div class="left"> <h1>{{page.title}}</h1> <hr> <p> Search by the keyword you entered. </p> <p> Matching conditions are <strong>title</strong> of the article or <strong>contents</strong> of the article. </p> <hr> <!-- Html Elements for Search --> <div id="search-container"> <input type="text" id="search-input" placeholder="Search"> <ul id="results-container"></ul> </div> <!-- Script pointing to jekyll-search.js --> <script src="/js/jekyll-search.js" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: '/search.json', searchResultTemplate: '<li><a href="{url}">{title}</a></li>', noResultsText: 'No results found', limit: 20, fuzzy: false, exclude: [] }) </script> <style> input[type=text], select { width: 40%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } </style> </div> </div>
Update search.html that Remove `title="{desc}"` attribute
Update search.html that Remove `title="{desc}"` attribute
HTML
mit
goodGid/goodGid.github.io,goodGid/goodGid.github.io,goodGid/goodGid.github.io
html
## Code Before: --- layout: default title: Search permalink: /search/ icon: search type: page --- <div class="page clearfix"> <div class="left"> <h1>{{page.title}}</h1> <hr> <p> Search by the keyword you entered. </p> <p> Matching conditions are <strong>title</strong> of the article or <strong>contents</strong> of the article. </p> <hr> <!-- Html Elements for Search --> <div id="search-container"> <input type="text" id="search-input" placeholder="Search"> <ul id="results-container"></ul> </div> <!-- Script pointing to jekyll-search.js --> <script src="/js/jekyll-search.js" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: '/search.json', searchResultTemplate: '<li><a href="{url}" title="{desc}">{title}</a></li>', noResultsText: 'No results found', limit: 20, fuzzy: false, exclude: [] }) </script> <style> input[type=text], select { width: 40%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } </style> </div> </div> ## Instruction: Update search.html that Remove `title="{desc}"` attribute ## Code After: --- layout: default title: Search permalink: /search/ icon: search type: page --- <div class="page clearfix"> <div class="left"> <h1>{{page.title}}</h1> <hr> <p> Search by the keyword you entered. </p> <p> Matching conditions are <strong>title</strong> of the article or <strong>contents</strong> of the article. </p> <hr> <!-- Html Elements for Search --> <div id="search-container"> <input type="text" id="search-input" placeholder="Search"> <ul id="results-container"></ul> </div> <!-- Script pointing to jekyll-search.js --> <script src="/js/jekyll-search.js" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: '/search.json', searchResultTemplate: '<li><a href="{url}">{title}</a></li>', noResultsText: 'No results found', limit: 20, fuzzy: false, exclude: [] }) </script> <style> input[type=text], select { width: 40%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } </style> </div> </div>
663e6925ab8b4634c2169ca764e38b2df2bf3140
src/Kunstmaan/MediaBundle/Repository/MediaRepository.php
src/Kunstmaan/MediaBundle/Repository/MediaRepository.php
<?php namespace Kunstmaan\MediaBundle\Repository; use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\EntityRepository; use Kunstmaan\MediaBundle\Entity\Media; /** * MediaRepository */ class MediaRepository extends EntityRepository { /** * @param Media $media */ public function save(Media $media) { $em = $this->getEntityManager(); $em->persist($media); $em->flush(); } /** * @param Media $media */ public function delete(Media $media) { $em = $this->getEntityManager(); $media->setDeleted(true); $em->persist($media); $em->flush(); } /** * @param int $mediaId * * @return object * * @throws EntityNotFoundException */ public function getMedia($mediaId) { $media = $this->find($mediaId); if (!$media) { throw new EntityNotFoundException(); } return $media; } /** * @param int $pictureId * * @return object * * @throws EntityNotFoundException */ public function getPicture($pictureId) { $em = $this->getEntityManager(); $picture = $em->getRepository(\Kunstmaan\MediaBundle\Entity\Image::class)->find($pictureId); if (!$picture) { throw new EntityNotFoundException(); } return $picture; } /** * Finds all Media that has their deleted flag set to 1 * and have their remove_from_file_system flag set to 0 * * @return object[] */ public function findAllDeleted() { return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]); } }
<?php namespace Kunstmaan\MediaBundle\Repository; use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\EntityRepository; use Kunstmaan\MediaBundle\Entity\Media; /** * MediaRepository */ class MediaRepository extends EntityRepository { /** * @param Media $media */ public function save(Media $media) { $em = $this->getEntityManager(); $em->persist($media); $em->flush(); } /** * @param Media $media */ public function delete(Media $media) { $em = $this->getEntityManager(); $media->setDeleted(true); $em->persist($media); $em->flush(); } /** * @param int $mediaId * * @return object * * @throws EntityNotFoundException */ public function getMedia($mediaId) { $media = $this->find($mediaId); if (!$media) { throw new EntityNotFoundException(); } return $media; } /** * Finds all Media that has their deleted flag set to 1 * and have their remove_from_file_system flag set to 0 * * @return object[] */ public function findAllDeleted() { return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]); } }
Remove non working method which causes issues
[MediaBundle] Remove non working method which causes issues
PHP
mit
Kunstmaan/KunstmaanBundlesCMS,Kunstmaan/KunstmaanBundlesCMS,dbeerten/KunstmaanBundlesCMS,insiders/KunstmaanBundlesCMS,insiders/KunstmaanBundlesCMS,Numkil/KunstmaanBundlesCMS,Numkil/KunstmaanBundlesCMS,dbeerten/KunstmaanBundlesCMS,FVKVN/KunstmaanBundlesCMS,dbeerten/KunstmaanBundlesCMS,Numkil/KunstmaanBundlesCMS,dbeerten/KunstmaanBundlesCMS,FVKVN/KunstmaanBundlesCMS,FVKVN/KunstmaanBundlesCMS,insiders/KunstmaanBundlesCMS,Numkil/KunstmaanBundlesCMS,FVKVN/KunstmaanBundlesCMS,insiders/KunstmaanBundlesCMS,Kunstmaan/KunstmaanBundlesCMS,Kunstmaan/KunstmaanBundlesCMS
php
## Code Before: <?php namespace Kunstmaan\MediaBundle\Repository; use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\EntityRepository; use Kunstmaan\MediaBundle\Entity\Media; /** * MediaRepository */ class MediaRepository extends EntityRepository { /** * @param Media $media */ public function save(Media $media) { $em = $this->getEntityManager(); $em->persist($media); $em->flush(); } /** * @param Media $media */ public function delete(Media $media) { $em = $this->getEntityManager(); $media->setDeleted(true); $em->persist($media); $em->flush(); } /** * @param int $mediaId * * @return object * * @throws EntityNotFoundException */ public function getMedia($mediaId) { $media = $this->find($mediaId); if (!$media) { throw new EntityNotFoundException(); } return $media; } /** * @param int $pictureId * * @return object * * @throws EntityNotFoundException */ public function getPicture($pictureId) { $em = $this->getEntityManager(); $picture = $em->getRepository(\Kunstmaan\MediaBundle\Entity\Image::class)->find($pictureId); if (!$picture) { throw new EntityNotFoundException(); } return $picture; } /** * Finds all Media that has their deleted flag set to 1 * and have their remove_from_file_system flag set to 0 * * @return object[] */ public function findAllDeleted() { return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]); } } ## Instruction: [MediaBundle] Remove non working method which causes issues ## Code After: <?php namespace Kunstmaan\MediaBundle\Repository; use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\EntityRepository; use Kunstmaan\MediaBundle\Entity\Media; /** * MediaRepository */ class MediaRepository extends EntityRepository { /** * @param Media $media */ public function save(Media $media) { $em = $this->getEntityManager(); $em->persist($media); $em->flush(); } /** * @param Media $media */ public function delete(Media $media) { $em = $this->getEntityManager(); $media->setDeleted(true); $em->persist($media); $em->flush(); } /** * @param int $mediaId * * @return object * * @throws EntityNotFoundException */ public function getMedia($mediaId) { $media = $this->find($mediaId); if (!$media) { throw new EntityNotFoundException(); } return $media; } /** * Finds all Media that has their deleted flag set to 1 * and have their remove_from_file_system flag set to 0 * * @return object[] */ public function findAllDeleted() { return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]); } }
e041fe96fa524b2954b9b33c434aafc245dfedae
lib/cupertino/provisioning_portal/helpers.rb
lib/cupertino/provisioning_portal/helpers.rb
module Commander::UI alias :pw :password end class String include Term::ANSIColor end module Cupertino module ProvisioningPortal module Helpers def agent unless @agent @agent = Cupertino::ProvisioningPortal::Agent.new @agent.instance_eval do def username @username ||= ask "Username:" end def password @password ||= pw "Password:" end def team teams = [] page.form_with(:name => 'saveTeamSelection').radiobuttons.each do |radio| name = page.search("label[for=\"#{radio.dom_id}\"]").first.text.strip teams << [name, radio.value] end name = choose "Select a team:", *teams.collect(&:first) @team ||= teams.detect{|e| e.first == name}.last end end end @agent end def pluralize(n, singular, plural = nil) n.to_i == 1 ? "1 #{singular}" : "#{n} #{plural || singular + 's'}" end def try return unless block_given? begin yield rescue UnsuccessfulAuthenticationError say_error "Could not authenticate with Apple Developer Center. Check that your username & password are correct, and that your membership is valid and all pending Terms of Service & agreements are accepted. If this problem continues, try logging into https://developer.apple.com/membercenter/ from a browser to see what's going on." and abort end end end end end
module Commander::UI alias :pw :password end class String include Term::ANSIColor end module Cupertino module ProvisioningPortal module Helpers def agent unless @agent @agent = Cupertino::ProvisioningPortal::Agent.new @agent.instance_eval do def username @username ||= ask "Username:" end def password @password ||= pw "Password:" end def team teams = [] page.form_with(:name => 'saveTeamSelection').radiobuttons.each do |radio| primary = page.search(".label-primary[for=\"#{radio.dom_id}\"]").first.text.strip secondary = page.search(".label-secondary[for=\"#{radio.dom_id}\"]").first.text.strip name = "#{primary}, #{secondary}" teams << [name, radio.value] end name = choose "Select a team:", *teams.collect(&:first) @team ||= teams.detect{|e| e.first == name}.last end end end @agent end def pluralize(n, singular, plural = nil) n.to_i == 1 ? "1 #{singular}" : "#{n} #{plural || singular + 's'}" end def try return unless block_given? begin yield rescue UnsuccessfulAuthenticationError say_error "Could not authenticate with Apple Developer Center. Check that your username & password are correct, and that your membership is valid and all pending Terms of Service & agreements are accepted. If this problem continues, try logging into https://developer.apple.com/membercenter/ from a browser to see what's going on." and abort end end end end end
Add support for multiple teams with the same primary name
Add support for multiple teams with the same primary name Change-Id: Ie70c29e16cbe41081fe13c1a1c0ae084cbef863f
Ruby
mit
radex/download-profiles,yaoxiaoyong/cupertino,Suninus/cupertino,tenforwardconsulting/cupertino,nomad/cupertino,zerok/cupertino
ruby
## Code Before: module Commander::UI alias :pw :password end class String include Term::ANSIColor end module Cupertino module ProvisioningPortal module Helpers def agent unless @agent @agent = Cupertino::ProvisioningPortal::Agent.new @agent.instance_eval do def username @username ||= ask "Username:" end def password @password ||= pw "Password:" end def team teams = [] page.form_with(:name => 'saveTeamSelection').radiobuttons.each do |radio| name = page.search("label[for=\"#{radio.dom_id}\"]").first.text.strip teams << [name, radio.value] end name = choose "Select a team:", *teams.collect(&:first) @team ||= teams.detect{|e| e.first == name}.last end end end @agent end def pluralize(n, singular, plural = nil) n.to_i == 1 ? "1 #{singular}" : "#{n} #{plural || singular + 's'}" end def try return unless block_given? begin yield rescue UnsuccessfulAuthenticationError say_error "Could not authenticate with Apple Developer Center. Check that your username & password are correct, and that your membership is valid and all pending Terms of Service & agreements are accepted. If this problem continues, try logging into https://developer.apple.com/membercenter/ from a browser to see what's going on." and abort end end end end end ## Instruction: Add support for multiple teams with the same primary name Change-Id: Ie70c29e16cbe41081fe13c1a1c0ae084cbef863f ## Code After: module Commander::UI alias :pw :password end class String include Term::ANSIColor end module Cupertino module ProvisioningPortal module Helpers def agent unless @agent @agent = Cupertino::ProvisioningPortal::Agent.new @agent.instance_eval do def username @username ||= ask "Username:" end def password @password ||= pw "Password:" end def team teams = [] page.form_with(:name => 'saveTeamSelection').radiobuttons.each do |radio| primary = page.search(".label-primary[for=\"#{radio.dom_id}\"]").first.text.strip secondary = page.search(".label-secondary[for=\"#{radio.dom_id}\"]").first.text.strip name = "#{primary}, #{secondary}" teams << [name, radio.value] end name = choose "Select a team:", *teams.collect(&:first) @team ||= teams.detect{|e| e.first == name}.last end end end @agent end def pluralize(n, singular, plural = nil) n.to_i == 1 ? "1 #{singular}" : "#{n} #{plural || singular + 's'}" end def try return unless block_given? begin yield rescue UnsuccessfulAuthenticationError say_error "Could not authenticate with Apple Developer Center. Check that your username & password are correct, and that your membership is valid and all pending Terms of Service & agreements are accepted. If this problem continues, try logging into https://developer.apple.com/membercenter/ from a browser to see what's going on." and abort end end end end end
453cf75dfb20fcd03c1d16e54b8d062dd1af0737
opal/clearwater/application.rb
opal/clearwater/application.rb
require 'clearwater/store' require 'clearwater/router' require 'clearwater/controller' require 'clearwater/view' module Clearwater class Application attr_reader :store, :router, :controller def initialize options={} @store = options.fetch(:store) { Store.new } @router = options.fetch(:router) { Router.new } @controller = options.fetch(:controller) { ApplicationController.new } router.application = self controller.router = router end def call render_current_url trap_clicks watch_url end def trap_clicks Element['body'].on :click, 'a' do |event| unless event.meta_key || event.ctrl_key || event.shift_key || event.alt_key remote_url = %r{^\w+://|^//} href = event.current_target[:href] event.prevent_default unless href.to_s =~ remote_url if href.nil? || href.empty? # Do nothing. There is nowhere to go. elsif href == router.current_path # Do nothing. We clicked a link to right here. elsif href.to_s =~ remote_url # Don't try to route remote URLs else router.navigate_to href end end end end def watch_url check_rerender = proc do render_current_url end %x{ window.onpopstate = check_rerender } end def render_current_url router.set_outlets controller && controller.call end end end
require 'clearwater/store' require 'clearwater/router' require 'clearwater/controller' require 'clearwater/view' module Clearwater class Application attr_reader :store, :router, :controller def initialize options={} @store = options.fetch(:store) { Store.new } @router = options.fetch(:router) { Router.new } @controller = options.fetch(:controller) { ApplicationController.new } router.application = self controller.router = router end def call render_current_url trap_clicks watch_url end def trap_clicks Element['body'].on :click, 'a' do |event| unless event.meta_key || event.ctrl_key || event.shift_key || event.alt_key remote_url = %r{^\w+://|^//} href = event.current_target[:href] event.prevent_default unless href.to_s =~ remote_url if href.nil? || href.empty? # Do nothing. There is nowhere to go. elsif href == router.current_path # Do nothing. We clicked a link to right here. elsif href.to_s =~ remote_url # Don't try to route remote URLs. Just let the browser do its thing. else router.navigate_to href end end end end def watch_url check_rerender = proc do render_current_url end %x{ window.onpopstate = check_rerender } end def render_current_url router.set_outlets controller && controller.call end end end
Clarify why we don't handle some clicks
Clarify why we don't handle some clicks
Ruby
mit
clearwater-rb/clearwater,elia/clearwater,elia/clearwater,clearwater-rb/clearwater
ruby
## Code Before: require 'clearwater/store' require 'clearwater/router' require 'clearwater/controller' require 'clearwater/view' module Clearwater class Application attr_reader :store, :router, :controller def initialize options={} @store = options.fetch(:store) { Store.new } @router = options.fetch(:router) { Router.new } @controller = options.fetch(:controller) { ApplicationController.new } router.application = self controller.router = router end def call render_current_url trap_clicks watch_url end def trap_clicks Element['body'].on :click, 'a' do |event| unless event.meta_key || event.ctrl_key || event.shift_key || event.alt_key remote_url = %r{^\w+://|^//} href = event.current_target[:href] event.prevent_default unless href.to_s =~ remote_url if href.nil? || href.empty? # Do nothing. There is nowhere to go. elsif href == router.current_path # Do nothing. We clicked a link to right here. elsif href.to_s =~ remote_url # Don't try to route remote URLs else router.navigate_to href end end end end def watch_url check_rerender = proc do render_current_url end %x{ window.onpopstate = check_rerender } end def render_current_url router.set_outlets controller && controller.call end end end ## Instruction: Clarify why we don't handle some clicks ## Code After: require 'clearwater/store' require 'clearwater/router' require 'clearwater/controller' require 'clearwater/view' module Clearwater class Application attr_reader :store, :router, :controller def initialize options={} @store = options.fetch(:store) { Store.new } @router = options.fetch(:router) { Router.new } @controller = options.fetch(:controller) { ApplicationController.new } router.application = self controller.router = router end def call render_current_url trap_clicks watch_url end def trap_clicks Element['body'].on :click, 'a' do |event| unless event.meta_key || event.ctrl_key || event.shift_key || event.alt_key remote_url = %r{^\w+://|^//} href = event.current_target[:href] event.prevent_default unless href.to_s =~ remote_url if href.nil? || href.empty? # Do nothing. There is nowhere to go. elsif href == router.current_path # Do nothing. We clicked a link to right here. elsif href.to_s =~ remote_url # Don't try to route remote URLs. Just let the browser do its thing. else router.navigate_to href end end end end def watch_url check_rerender = proc do render_current_url end %x{ window.onpopstate = check_rerender } end def render_current_url router.set_outlets controller && controller.call end end end
7513968732441a2bd3ecd720d821e12a1311a38b
installer/js/setup/repositories/RepositoryList.js
installer/js/setup/repositories/RepositoryList.js
import React, { Component, PropTypes } from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList;
import React, { Component, PropTypes } from 'react'; import Progress from 'material-ui/CircularProgress'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories, loading: false })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> {this.state.loading && <div style={{ textAlign: 'center' }}> <Progress size={60} thickness={5} /> </div>} <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList;
Add a loader while loading repositories
Add a loader while loading repositories
JavaScript
mit
marmelab/sedbot.js
javascript
## Code Before: import React, { Component, PropTypes } from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList; ## Instruction: Add a loader while loading repositories ## Code After: import React, { Component, PropTypes } from 'react'; import Progress from 'material-ui/CircularProgress'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories, loading: false })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> {this.state.loading && <div style={{ textAlign: 'center' }}> <Progress size={60} thickness={5} /> </div>} <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList;
7249234061e8791ccbee5d0e3b8578d8595e43f8
tests/unit/classes/ModuleLoader.js
tests/unit/classes/ModuleLoader.js
var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { before(function(done) { var source = path.resolve(__dirname, '..', 'test-module') , dest = path.resolve(__dirname, '..', '..', '..', 'modules', 'test-module'); // Copy the test-module into the modules folder ncp(source, dest, done); }); it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); });
var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); });
Remove old code for copying test-module
chore(cleanup): Remove old code for copying test-module
JavaScript
mit
CleverStack/node-seed
javascript
## Code Before: var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { before(function(done) { var source = path.resolve(__dirname, '..', 'test-module') , dest = path.resolve(__dirname, '..', '..', '..', 'modules', 'test-module'); // Copy the test-module into the modules folder ncp(source, dest, done); }); it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); }); ## Instruction: chore(cleanup): Remove old code for copying test-module ## Code After: var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); });
e9af8f85f2d39e08b3a068f07ecdb22962680c74
buildSrc/src/main/kotlin/com/bmuschko/gradle/docker/FunctionalTestPlugin.kt
buildSrc/src/main/kotlin/com/bmuschko/gradle/docker/FunctionalTestPlugin.kt
package com.bmuschko.gradle.docker import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.tasks.GroovySourceSet import org.gradle.api.tasks.testing.Test import org.gradle.kotlin.dsl.* class FunctionalTestPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { val sourceSets = project.the<JavaPluginConvention>().sourceSets val testRuntimeClasspath by configurations val functionalTestSourceSet = sourceSets.create("functionalTest") { withConvention(GroovySourceSet::class) { groovy.srcDir("src/functTest/groovy") } resources.srcDir("src/functTest/resources") compileClasspath += sourceSets["main"]!!.output + testRuntimeClasspath runtimeClasspath += output + compileClasspath } val functionalTest by tasks.creating(Test::class) { description = "Runs the functional tests" group = "verification" testClassesDirs = functionalTestSourceSet.output.classesDirs classpath = functionalTestSourceSet.runtimeClasspath mustRunAfter("test", "integrationTest") reports { html.destination = file("${html.destination}/functional") junitXml.destination = file("${junitXml.destination}/functional") } testLogging { showStandardStreams = true events("started", "passed", "failed") } } tasks["check"].dependsOn(functionalTest) } }
package com.bmuschko.gradle.docker import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.tasks.GroovySourceSet import org.gradle.api.tasks.testing.Test import org.gradle.kotlin.dsl.* class FunctionalTestPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { val sourceSets = project.the<JavaPluginConvention>().sourceSets val testRuntimeClasspath by configurations val functionalTestSourceSet = sourceSets.create("functionalTest") { withConvention(GroovySourceSet::class) { groovy.srcDir("src/functTest/groovy") } resources.srcDir("src/functTest/resources") compileClasspath += sourceSets["main"]!!.output + sourceSets["testSetup"]!!.output + testRuntimeClasspath runtimeClasspath += output + compileClasspath } val functionalTest by tasks.creating(Test::class) { description = "Runs the functional tests" group = "verification" testClassesDirs = functionalTestSourceSet.output.classesDirs classpath = functionalTestSourceSet.runtimeClasspath mustRunAfter("test", "integrationTest") reports { html.destination = file("${html.destination}/functional") junitXml.destination = file("${junitXml.destination}/functional") } testLogging { showStandardStreams = true events("started", "passed", "failed") } } tasks["check"].dependsOn(functionalTest) } }
Add test setup output to compile classpath
Add test setup output to compile classpath
Kotlin
apache-2.0
bmuschko/gradle-docker-plugin,bmuschko/gradle-docker-plugin,bmuschko/gradle-docker-plugin
kotlin
## Code Before: package com.bmuschko.gradle.docker import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.tasks.GroovySourceSet import org.gradle.api.tasks.testing.Test import org.gradle.kotlin.dsl.* class FunctionalTestPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { val sourceSets = project.the<JavaPluginConvention>().sourceSets val testRuntimeClasspath by configurations val functionalTestSourceSet = sourceSets.create("functionalTest") { withConvention(GroovySourceSet::class) { groovy.srcDir("src/functTest/groovy") } resources.srcDir("src/functTest/resources") compileClasspath += sourceSets["main"]!!.output + testRuntimeClasspath runtimeClasspath += output + compileClasspath } val functionalTest by tasks.creating(Test::class) { description = "Runs the functional tests" group = "verification" testClassesDirs = functionalTestSourceSet.output.classesDirs classpath = functionalTestSourceSet.runtimeClasspath mustRunAfter("test", "integrationTest") reports { html.destination = file("${html.destination}/functional") junitXml.destination = file("${junitXml.destination}/functional") } testLogging { showStandardStreams = true events("started", "passed", "failed") } } tasks["check"].dependsOn(functionalTest) } } ## Instruction: Add test setup output to compile classpath ## Code After: package com.bmuschko.gradle.docker import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.tasks.GroovySourceSet import org.gradle.api.tasks.testing.Test import org.gradle.kotlin.dsl.* class FunctionalTestPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { val sourceSets = project.the<JavaPluginConvention>().sourceSets val testRuntimeClasspath by configurations val functionalTestSourceSet = sourceSets.create("functionalTest") { withConvention(GroovySourceSet::class) { groovy.srcDir("src/functTest/groovy") } resources.srcDir("src/functTest/resources") compileClasspath += sourceSets["main"]!!.output + sourceSets["testSetup"]!!.output + testRuntimeClasspath runtimeClasspath += output + compileClasspath } val functionalTest by tasks.creating(Test::class) { description = "Runs the functional tests" group = "verification" testClassesDirs = functionalTestSourceSet.output.classesDirs classpath = functionalTestSourceSet.runtimeClasspath mustRunAfter("test", "integrationTest") reports { html.destination = file("${html.destination}/functional") junitXml.destination = file("${junitXml.destination}/functional") } testLogging { showStandardStreams = true events("started", "passed", "failed") } } tasks["check"].dependsOn(functionalTest) } }
b1a3412e78ed1267a4a2dd5a06b273e05848dc3b
fliptheswitch-app/src/main/java/com/github/michaelengland/fliptheswitch/app/FeaturesActivity.java
fliptheswitch-app/src/main/java/com/github/michaelengland/fliptheswitch/app/FeaturesActivity.java
package com.github.michaelengland.fliptheswitch.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.github.michaelengland.fliptheswitch.Feature; import com.github.michaelengland.fliptheswitch.FlipTheSwitch; public class FeaturesActivity extends AppCompatActivity { private FlipTheSwitch flipTheSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); flipTheSwitch = new FlipTheSwitch(this); setContentView(R.layout.activitiy_features); } @Override protected void onStart() { super.onStart(); getResetButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { flipTheSwitch.resetAllFeatures(); } }); FeaturesAdapter adapter = new FeaturesAdapter(getLayoutInflater(), FlipTheSwitch.getDefaultFeatures(), new FeaturesAdapter.OnFeatureToggledListener() { @Override public void onFeatureToggled(Feature feature, boolean enabled) { flipTheSwitch.setFeatureEnabled(feature.getName(), enabled); } }); getListView().setAdapter(adapter); } private ListView getListView() { return (ListView) findViewById(R.id.activity_features_list_view); } private Button getResetButton() { return (Button) findViewById(R.id.toolbar_reset_button); } }
package com.github.michaelengland.fliptheswitch.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.github.michaelengland.fliptheswitch.Feature; import com.github.michaelengland.fliptheswitch.FlipTheSwitch; public class FeaturesActivity extends AppCompatActivity { private FlipTheSwitch flipTheSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { Class.forName("com.github.michaelengland.fliptheswitch.Features"); } catch (ClassNotFoundException ignored) { } flipTheSwitch = new FlipTheSwitch(this); setContentView(R.layout.activitiy_features); } @Override protected void onStart() { super.onStart(); getResetButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { flipTheSwitch.resetAllFeatures(); } }); FeaturesAdapter adapter = new FeaturesAdapter(getLayoutInflater(), FlipTheSwitch.getDefaultFeatures(), new FeaturesAdapter.OnFeatureToggledListener() { @Override public void onFeatureToggled(Feature feature, boolean enabled) { flipTheSwitch.setFeatureEnabled(feature.getName(), enabled); } }); getListView().setAdapter(adapter); } private ListView getListView() { return (ListView) findViewById(R.id.activity_features_list_view); } private Button getResetButton() { return (Button) findViewById(R.id.toolbar_reset_button); } }
Fix bug with features not appearing when feature app loaded before main app
Fix bug with features not appearing when feature app loaded before main app - Trigger class initialization of generated features file before showing features app
Java
apache-2.0
michaelengland/FlipTheSwitch-Android,michaelengland/FlipTheSwitch-Android
java
## Code Before: package com.github.michaelengland.fliptheswitch.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.github.michaelengland.fliptheswitch.Feature; import com.github.michaelengland.fliptheswitch.FlipTheSwitch; public class FeaturesActivity extends AppCompatActivity { private FlipTheSwitch flipTheSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); flipTheSwitch = new FlipTheSwitch(this); setContentView(R.layout.activitiy_features); } @Override protected void onStart() { super.onStart(); getResetButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { flipTheSwitch.resetAllFeatures(); } }); FeaturesAdapter adapter = new FeaturesAdapter(getLayoutInflater(), FlipTheSwitch.getDefaultFeatures(), new FeaturesAdapter.OnFeatureToggledListener() { @Override public void onFeatureToggled(Feature feature, boolean enabled) { flipTheSwitch.setFeatureEnabled(feature.getName(), enabled); } }); getListView().setAdapter(adapter); } private ListView getListView() { return (ListView) findViewById(R.id.activity_features_list_view); } private Button getResetButton() { return (Button) findViewById(R.id.toolbar_reset_button); } } ## Instruction: Fix bug with features not appearing when feature app loaded before main app - Trigger class initialization of generated features file before showing features app ## Code After: package com.github.michaelengland.fliptheswitch.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.github.michaelengland.fliptheswitch.Feature; import com.github.michaelengland.fliptheswitch.FlipTheSwitch; public class FeaturesActivity extends AppCompatActivity { private FlipTheSwitch flipTheSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { Class.forName("com.github.michaelengland.fliptheswitch.Features"); } catch (ClassNotFoundException ignored) { } flipTheSwitch = new FlipTheSwitch(this); setContentView(R.layout.activitiy_features); } @Override protected void onStart() { super.onStart(); getResetButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { flipTheSwitch.resetAllFeatures(); } }); FeaturesAdapter adapter = new FeaturesAdapter(getLayoutInflater(), FlipTheSwitch.getDefaultFeatures(), new FeaturesAdapter.OnFeatureToggledListener() { @Override public void onFeatureToggled(Feature feature, boolean enabled) { flipTheSwitch.setFeatureEnabled(feature.getName(), enabled); } }); getListView().setAdapter(adapter); } private ListView getListView() { return (ListView) findViewById(R.id.activity_features_list_view); } private Button getResetButton() { return (Button) findViewById(R.id.toolbar_reset_button); } }
03f91b9d5c497edea2cd96ab44ac89a31c8c4753
src/start/global.php
src/start/global.php
<?php use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Event; use Orchestra\Support\Messages; use Orchestra\Foundation\Services\UserMetaRepository; App::make('orchestra.memory')->extend('user', function ($app, $name) { return new UserMetaRepository($app, $name); }); /* |-------------------------------------------------------------------------- | Bind Installation Interface |-------------------------------------------------------------------------- | | These interface allow Orchestra Platform installation process to be | customized by the application when there a requirement for it. | */ App::bind('Orchestra\Foundation\Installation\InstallerInterface', function () { return new Orchestra\Foundation\Installation\Installer(App::make('app')); }); App::bind('Orchestra\Foundation\Installation\RequirementInterface', function () { return new Orchestra\Foundation\Installation\Requirement(App::make('app')); }); /* |-------------------------------------------------------------------------- | Inject Safe Mode Notification |-------------------------------------------------------------------------- | | This event listener would allow Orchestra Platform to display notification | if the application is running on safe mode. | */ Event::listen('composing: *', function () { if ('on' === App::make('session')->get('orchestra.safemode')) { $messages = App::make('orchestra.messages')->retrieve(); ($messages instanceof Messages) or $messages = new Messages; $messages->add('info', trans('orchestra/foundation::response.safe-mode')); $messages->save(); } });
<?php use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Event; use Orchestra\Support\Messages; use Orchestra\Foundation\Services\UserMetaRepository; App::make('orchestra.memory')->extend('user', function ($app, $name) { return new UserMetaRepository($app, $name); }); /* |-------------------------------------------------------------------------- | Bind Installation Interface |-------------------------------------------------------------------------- | | These interface allow Orchestra Platform installation process to be | customized by the application when there a requirement for it. | */ App::bind('Orchestra\Foundation\Installation\InstallerInterface', function () { return new Orchestra\Foundation\Installation\Installer(App::make('app')); }); App::bind('Orchestra\Foundation\Installation\RequirementInterface', function () { return new Orchestra\Foundation\Installation\Requirement(App::make('app')); }); /* |-------------------------------------------------------------------------- | Inject Safe Mode Notification |-------------------------------------------------------------------------- | | This event listener would allow Orchestra Platform to display notification | if the application is running on safe mode. | */ Event::listen('composing: *', function () { if ('on' === App::make('session')->get('orchestra.safemode')) { App::make('orchestra.messages')->extend(function ($messages) { $messages->add('info', trans('orchestra/foundation::response.safe-mode')); }); } });
Improve safe mode notification using the new Orchestra\Messages::extend() API
Improve safe mode notification using the new Orchestra\Messages::extend() API Signed-off-by: crynobone <[email protected]>
PHP
mit
orchestral/foundation,orchestral/foundation,orchestral/foundation,stevebauman/foundation
php
## Code Before: <?php use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Event; use Orchestra\Support\Messages; use Orchestra\Foundation\Services\UserMetaRepository; App::make('orchestra.memory')->extend('user', function ($app, $name) { return new UserMetaRepository($app, $name); }); /* |-------------------------------------------------------------------------- | Bind Installation Interface |-------------------------------------------------------------------------- | | These interface allow Orchestra Platform installation process to be | customized by the application when there a requirement for it. | */ App::bind('Orchestra\Foundation\Installation\InstallerInterface', function () { return new Orchestra\Foundation\Installation\Installer(App::make('app')); }); App::bind('Orchestra\Foundation\Installation\RequirementInterface', function () { return new Orchestra\Foundation\Installation\Requirement(App::make('app')); }); /* |-------------------------------------------------------------------------- | Inject Safe Mode Notification |-------------------------------------------------------------------------- | | This event listener would allow Orchestra Platform to display notification | if the application is running on safe mode. | */ Event::listen('composing: *', function () { if ('on' === App::make('session')->get('orchestra.safemode')) { $messages = App::make('orchestra.messages')->retrieve(); ($messages instanceof Messages) or $messages = new Messages; $messages->add('info', trans('orchestra/foundation::response.safe-mode')); $messages->save(); } }); ## Instruction: Improve safe mode notification using the new Orchestra\Messages::extend() API Signed-off-by: crynobone <[email protected]> ## Code After: <?php use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Event; use Orchestra\Support\Messages; use Orchestra\Foundation\Services\UserMetaRepository; App::make('orchestra.memory')->extend('user', function ($app, $name) { return new UserMetaRepository($app, $name); }); /* |-------------------------------------------------------------------------- | Bind Installation Interface |-------------------------------------------------------------------------- | | These interface allow Orchestra Platform installation process to be | customized by the application when there a requirement for it. | */ App::bind('Orchestra\Foundation\Installation\InstallerInterface', function () { return new Orchestra\Foundation\Installation\Installer(App::make('app')); }); App::bind('Orchestra\Foundation\Installation\RequirementInterface', function () { return new Orchestra\Foundation\Installation\Requirement(App::make('app')); }); /* |-------------------------------------------------------------------------- | Inject Safe Mode Notification |-------------------------------------------------------------------------- | | This event listener would allow Orchestra Platform to display notification | if the application is running on safe mode. | */ Event::listen('composing: *', function () { if ('on' === App::make('session')->get('orchestra.safemode')) { App::make('orchestra.messages')->extend(function ($messages) { $messages->add('info', trans('orchestra/foundation::response.safe-mode')); }); } });
03913013e30c31a646def283cdec44f153adb572
src/test/java/org/realityforge/jeo/geolatte/jpa/eclipselink/DatabaseTestUtil.java
src/test/java/org/realityforge/jeo/geolatte/jpa/eclipselink/DatabaseTestUtil.java
package org.realityforge.jeo.geolatte.jpa.eclipselink; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class DatabaseTestUtil { static Properties initDatabaseProperties() { final Properties properties = new Properties(); properties.put( "javax.persistence.jdbc.driver", "org.postgis.DriverWrapperAutoprobe" ); final String databaseUrl = "jdbc:postgresql_autogis://127.0.0.1:5432/geolatte_test"; setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl ); setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" ); setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null ); properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() ); return properties; } private static void setProperty( final Properties properties, final String key, final String systemPropertyKey, final String defaultValue ) { final String value = System.getProperty( systemPropertyKey, defaultValue ); if ( null != value ) { properties.put( key, value ); } } public static EntityManager createEntityManager( final String persistenceUnitName ) { final Properties properties = initDatabaseProperties(); final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties ); return factory.createEntityManager(); } }
package org.realityforge.jeo.geolatte.jpa.eclipselink; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class DatabaseTestUtil { static Properties initDatabaseProperties() { final Properties properties = new Properties(); properties.put( "javax.persistence.jdbc.driver", "org.postgresql.Driver" ); final String databaseUrl = "jdbc:postgresql://127.0.0.1:5432/geolatte_test"; setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl ); setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" ); setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null ); properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() ); return properties; } private static void setProperty( final Properties properties, final String key, final String systemPropertyKey, final String defaultValue ) { final String value = System.getProperty( systemPropertyKey, defaultValue ); if ( null != value ) { properties.put( key, value ); } } public static EntityManager createEntityManager( final String persistenceUnitName ) { final Properties properties = initDatabaseProperties(); final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties ); return factory.createEntityManager(); } }
Revert to using the base postgres driver in tests
Revert to using the base postgres driver in tests
Java
apache-2.0
realityforge/geolatte-geom-eclipselink,realityforge/geolatte-geom-jpa,realityforge/geolatte-geom-jpa,realityforge/geolatte-geom-eclipselink
java
## Code Before: package org.realityforge.jeo.geolatte.jpa.eclipselink; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class DatabaseTestUtil { static Properties initDatabaseProperties() { final Properties properties = new Properties(); properties.put( "javax.persistence.jdbc.driver", "org.postgis.DriverWrapperAutoprobe" ); final String databaseUrl = "jdbc:postgresql_autogis://127.0.0.1:5432/geolatte_test"; setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl ); setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" ); setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null ); properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() ); return properties; } private static void setProperty( final Properties properties, final String key, final String systemPropertyKey, final String defaultValue ) { final String value = System.getProperty( systemPropertyKey, defaultValue ); if ( null != value ) { properties.put( key, value ); } } public static EntityManager createEntityManager( final String persistenceUnitName ) { final Properties properties = initDatabaseProperties(); final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties ); return factory.createEntityManager(); } } ## Instruction: Revert to using the base postgres driver in tests ## Code After: package org.realityforge.jeo.geolatte.jpa.eclipselink; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class DatabaseTestUtil { static Properties initDatabaseProperties() { final Properties properties = new Properties(); properties.put( "javax.persistence.jdbc.driver", "org.postgresql.Driver" ); final String databaseUrl = "jdbc:postgresql://127.0.0.1:5432/geolatte_test"; setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl ); setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" ); setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null ); properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() ); return properties; } private static void setProperty( final Properties properties, final String key, final String systemPropertyKey, final String defaultValue ) { final String value = System.getProperty( systemPropertyKey, defaultValue ); if ( null != value ) { properties.put( key, value ); } } public static EntityManager createEntityManager( final String persistenceUnitName ) { final Properties properties = initDatabaseProperties(); final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties ); return factory.createEntityManager(); } }
c17b8e6141d2832b9920eb143de2937993fb8865
linguist/models/base.py
linguist/models/base.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.CharField( max_length=100, verbose_name=_('identifier'), help_text=_('The registered model identifier.')) object_id = models.IntegerField( verbose_name=_('The object ID'), help_text=_('The object ID of this translation')) locale = models.CharField( max_length=10, verbose_name=_('locale'), choices=settings.SUPPORTED_LOCALES, default=settings.DEFAULT_LOCALE, help_text=_('The locale for this translation')) field_name = models.CharField( max_length=100, verbose_name=_('field name'), help_text=_('The model field name for this translation.')) content = models.TextField( verbose_name=_('content'), null=True, help_text=_('The translated content for the field.')) class Meta: abstract = True app_label = 'linguist' verbose_name = _('translation') verbose_name_plural = _('translations') unique_together = (('identifier', 'object_id', 'locale', 'field_name'),) def __str__(self): return '%s:%d:%s:%s' % ( self.identifier, self.object_id, self.field_name, self.locale)
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.CharField( max_length=100, verbose_name=_('identifier'), help_text=_('The registered model identifier.')) object_id = models.IntegerField( verbose_name=_('The object ID'), help_text=_('The object ID of this translation')) language = models.CharField( max_length=10, verbose_name=_('locale'), choices=settings.SUPPORTED_LANGUAGES, default=settings.DEFAULT_LANGUAGE, help_text=_('The language for this translation')) field_name = models.CharField( max_length=100, verbose_name=_('field name'), help_text=_('The model field name for this translation.')) content = models.TextField( verbose_name=_('content'), null=True, help_text=_('The translated content for the field.')) class Meta: abstract = True app_label = 'linguist' verbose_name = _('translation') verbose_name_plural = _('translations') unique_together = (('identifier', 'object_id', 'language', 'field_name'),) def __str__(self): return '%s:%d:%s:%s' % ( self.identifier, self.object_id, self.field_name, self.language)
Rename locale field to language.
Rename locale field to language.
Python
mit
ulule/django-linguist
python
## Code Before: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.CharField( max_length=100, verbose_name=_('identifier'), help_text=_('The registered model identifier.')) object_id = models.IntegerField( verbose_name=_('The object ID'), help_text=_('The object ID of this translation')) locale = models.CharField( max_length=10, verbose_name=_('locale'), choices=settings.SUPPORTED_LOCALES, default=settings.DEFAULT_LOCALE, help_text=_('The locale for this translation')) field_name = models.CharField( max_length=100, verbose_name=_('field name'), help_text=_('The model field name for this translation.')) content = models.TextField( verbose_name=_('content'), null=True, help_text=_('The translated content for the field.')) class Meta: abstract = True app_label = 'linguist' verbose_name = _('translation') verbose_name_plural = _('translations') unique_together = (('identifier', 'object_id', 'locale', 'field_name'),) def __str__(self): return '%s:%d:%s:%s' % ( self.identifier, self.object_id, self.field_name, self.locale) ## Instruction: Rename locale field to language. ## Code After: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.CharField( max_length=100, verbose_name=_('identifier'), help_text=_('The registered model identifier.')) object_id = models.IntegerField( verbose_name=_('The object ID'), help_text=_('The object ID of this translation')) language = models.CharField( max_length=10, verbose_name=_('locale'), choices=settings.SUPPORTED_LANGUAGES, default=settings.DEFAULT_LANGUAGE, help_text=_('The language for this translation')) field_name = models.CharField( max_length=100, verbose_name=_('field name'), help_text=_('The model field name for this translation.')) content = models.TextField( verbose_name=_('content'), null=True, help_text=_('The translated content for the field.')) class Meta: abstract = True app_label = 'linguist' verbose_name = _('translation') verbose_name_plural = _('translations') unique_together = (('identifier', 'object_id', 'language', 'field_name'),) def __str__(self): return '%s:%d:%s:%s' % ( self.identifier, self.object_id, self.field_name, self.language)
2af5d7f81ab18d10395607f6e94ef4f0da7b9c68
src/Auth/Registrar.php
src/Auth/Registrar.php
<?php namespace LaraParse\Auth; use Illuminate\Contracts\Auth\Registrar as RegistrarContract; use Illuminate\Contracts\Validation\Factory as ValidationFactory; use Illuminate\Support\MessageBag; use LaraParse\Subclasses\User; use Parse\ParseException; class Registrar implements RegistrarContract { /** * @var \Illuminate\Contracts\Validation\Factory */ private $validator; /** * @param \Illuminate\Contracts\Validation\Factory $validator */ public function __construct(ValidationFactory $validator) { $this->validator = $validator; } /** * Get a validator for an incoming registration request. * * @param array $data * * @return \Illuminate\Contracts\Validation\Validator */ public function validator(array $data) { $messages = [ 'parse_user_unique' => 'Testing message.', ]; $rules = [ 'email' => ['required', 'email', 'max:255', 'parse_user_unique'], 'password' => ['required', 'confirmed', 'min:6'], ]; return $this->validator->make($data, $rules, $messages); } /** * Create a new user instance after a valid registration. * * @param array $data * * @return User */ public function create(array $data) { $user = new User; $user->username = $data['email']; $user->password = $data['password']; $user->signUp(); return $user; } }
<?php namespace LaraParse\Auth; use Illuminate\Contracts\Auth\Registrar as RegistrarContract; use Illuminate\Contracts\Validation\Factory as ValidationFactory; use LaraParse\Subclasses\User; use Parse\ParseObject; class Registrar implements RegistrarContract { /** * @var \Illuminate\Contracts\Validation\Factory */ private $validator; /** * @param \Illuminate\Contracts\Validation\Factory $validator */ public function __construct(ValidationFactory $validator) { $this->validator = $validator; } /** * Get a validator for an incoming registration request. * * @param array $data * * @return \Illuminate\Contracts\Validation\Validator */ public function validator(array $data) { $messages = [ 'parse_user_unique' => 'Testing message.', ]; $rules = [ 'email' => ['required', 'email', 'max:255', 'parse_user_unique'], 'password' => ['required', 'confirmed', 'min:6'], ]; return $this->validator->make($data, $rules, $messages); } /** * Create a new user instance after a valid registration. * * @param array $data * * @return User */ public function create(array $data) { $userSubclass = ParseObject::getRegisteredSubclass('_User'); $user = new $userSubclass; $user->username = $data['email']; $user->password = $data['password']; $user->signUp(); return $user; } }
Update registrar to dynamically fetch registered `_User` subclass
Update registrar to dynamically fetch registered `_User` subclass
PHP
mit
redkyo017/LaraParse,HipsterJazzbo/LaraParse
php
## Code Before: <?php namespace LaraParse\Auth; use Illuminate\Contracts\Auth\Registrar as RegistrarContract; use Illuminate\Contracts\Validation\Factory as ValidationFactory; use Illuminate\Support\MessageBag; use LaraParse\Subclasses\User; use Parse\ParseException; class Registrar implements RegistrarContract { /** * @var \Illuminate\Contracts\Validation\Factory */ private $validator; /** * @param \Illuminate\Contracts\Validation\Factory $validator */ public function __construct(ValidationFactory $validator) { $this->validator = $validator; } /** * Get a validator for an incoming registration request. * * @param array $data * * @return \Illuminate\Contracts\Validation\Validator */ public function validator(array $data) { $messages = [ 'parse_user_unique' => 'Testing message.', ]; $rules = [ 'email' => ['required', 'email', 'max:255', 'parse_user_unique'], 'password' => ['required', 'confirmed', 'min:6'], ]; return $this->validator->make($data, $rules, $messages); } /** * Create a new user instance after a valid registration. * * @param array $data * * @return User */ public function create(array $data) { $user = new User; $user->username = $data['email']; $user->password = $data['password']; $user->signUp(); return $user; } } ## Instruction: Update registrar to dynamically fetch registered `_User` subclass ## Code After: <?php namespace LaraParse\Auth; use Illuminate\Contracts\Auth\Registrar as RegistrarContract; use Illuminate\Contracts\Validation\Factory as ValidationFactory; use LaraParse\Subclasses\User; use Parse\ParseObject; class Registrar implements RegistrarContract { /** * @var \Illuminate\Contracts\Validation\Factory */ private $validator; /** * @param \Illuminate\Contracts\Validation\Factory $validator */ public function __construct(ValidationFactory $validator) { $this->validator = $validator; } /** * Get a validator for an incoming registration request. * * @param array $data * * @return \Illuminate\Contracts\Validation\Validator */ public function validator(array $data) { $messages = [ 'parse_user_unique' => 'Testing message.', ]; $rules = [ 'email' => ['required', 'email', 'max:255', 'parse_user_unique'], 'password' => ['required', 'confirmed', 'min:6'], ]; return $this->validator->make($data, $rules, $messages); } /** * Create a new user instance after a valid registration. * * @param array $data * * @return User */ public function create(array $data) { $userSubclass = ParseObject::getRegisteredSubclass('_User'); $user = new $userSubclass; $user->username = $data['email']; $user->password = $data['password']; $user->signUp(); return $user; } }
f375f18def97a3a0fa5737485484e0f89f45d844
src/components/Activity.js
src/components/Activity.js
import React, { Component, PropTypes } from 'react'; import moment from 'moment'; import TagList from './TagList'; class Activity extends Component { render() { const { timestamp, activity, deleteActivity, editActivity, isEditing, cancelEdit } = this.props; const { description, tags = [] } = activity; return ( <div> <div className="row row--middle row--start"> <div className="col--auto flex align-items--center"> <div className="flex cursor--pointer" onClick={isEditing ? () => cancelEdit() : () => editActivity(timestamp) } > {description} </div> { isEditing && ( <span className="flex cursor--pointer font--12 ml p- color--blue" onClick={() => cancelEdit()} > cancel </span> ) } { !isEditing && ( <span className="flex cursor--pointer font--12 ml p- color--blue" onClick={() => editActivity(timestamp)} > edit </span> ) } <span className="flex cursor--pointer ml-- p- color-red" onClick={() => deleteActivity(timestamp)} > &times; </span> </div> </div> <TagList tags={tags} /> </div> ); } } Activity.propTypes = { timestamp: PropTypes.string.isRequired, activity: PropTypes.object.isRequired, deleteActivity: PropTypes.func.isRequired, editActivity: PropTypes.func.isRequired, isEditing: PropTypes.bool.isRequired, cancelEdit: PropTypes.func.isRequired, } export default Activity;
import React, { Component, PropTypes } from 'react'; import moment from 'moment'; import TagList from './TagList'; import Row from './layout/Row'; import Column from './layout/Column'; class Activity extends Component { render() { const { timestamp, activity, deleteActivity, editActivity, isEditing, cancelEdit } = this.props; const { description, tags = [] } = activity; return ( <div> <Row middle start> <Column span={12} className="cursor--pointer p- bg--clouds" onClick={isEditing ? () => cancelEdit() : () => editActivity(timestamp) } > {description} </Column> </Row> <TagList tags={tags} /> </div> ); } } Activity.propTypes = { timestamp: PropTypes.string.isRequired, activity: PropTypes.object.isRequired, deleteActivity: PropTypes.func.isRequired, editActivity: PropTypes.func.isRequired, isEditing: PropTypes.bool.isRequired, cancelEdit: PropTypes.func.isRequired, } export default Activity;
Remove buttons/links on activity description
Remove buttons/links on activity description
JavaScript
mit
mknudsen01/today,mknudsen01/today
javascript
## Code Before: import React, { Component, PropTypes } from 'react'; import moment from 'moment'; import TagList from './TagList'; class Activity extends Component { render() { const { timestamp, activity, deleteActivity, editActivity, isEditing, cancelEdit } = this.props; const { description, tags = [] } = activity; return ( <div> <div className="row row--middle row--start"> <div className="col--auto flex align-items--center"> <div className="flex cursor--pointer" onClick={isEditing ? () => cancelEdit() : () => editActivity(timestamp) } > {description} </div> { isEditing && ( <span className="flex cursor--pointer font--12 ml p- color--blue" onClick={() => cancelEdit()} > cancel </span> ) } { !isEditing && ( <span className="flex cursor--pointer font--12 ml p- color--blue" onClick={() => editActivity(timestamp)} > edit </span> ) } <span className="flex cursor--pointer ml-- p- color-red" onClick={() => deleteActivity(timestamp)} > &times; </span> </div> </div> <TagList tags={tags} /> </div> ); } } Activity.propTypes = { timestamp: PropTypes.string.isRequired, activity: PropTypes.object.isRequired, deleteActivity: PropTypes.func.isRequired, editActivity: PropTypes.func.isRequired, isEditing: PropTypes.bool.isRequired, cancelEdit: PropTypes.func.isRequired, } export default Activity; ## Instruction: Remove buttons/links on activity description ## Code After: import React, { Component, PropTypes } from 'react'; import moment from 'moment'; import TagList from './TagList'; import Row from './layout/Row'; import Column from './layout/Column'; class Activity extends Component { render() { const { timestamp, activity, deleteActivity, editActivity, isEditing, cancelEdit } = this.props; const { description, tags = [] } = activity; return ( <div> <Row middle start> <Column span={12} className="cursor--pointer p- bg--clouds" onClick={isEditing ? () => cancelEdit() : () => editActivity(timestamp) } > {description} </Column> </Row> <TagList tags={tags} /> </div> ); } } Activity.propTypes = { timestamp: PropTypes.string.isRequired, activity: PropTypes.object.isRequired, deleteActivity: PropTypes.func.isRequired, editActivity: PropTypes.func.isRequired, isEditing: PropTypes.bool.isRequired, cancelEdit: PropTypes.func.isRequired, } export default Activity;
5847e9db8f316fdee6493fefc9cbc64a1e6a28de
km_api/know_me/serializers/subscription_serializers.py
km_api/know_me/serializers/subscription_serializers.py
import hashlib import logging from django.utils.translation import ugettext from rest_framework import serializers from know_me import models, subscriptions logger = logging.getLogger(__name__) class AppleSubscriptionSerializer(serializers.ModelSerializer): """ Serializer for an Apple subscription. """ class Meta: fields = ( "id", "time_created", "time_updated", "expiration_time", "receipt_data", ) model = models.SubscriptionAppleData def validate(self, data): """ Ensure the provided receipt data corresponds to a valid Apple receipt. Returns: The validated data. """ validated_data = data.copy() receipt_data = validated_data["receipt_data"] data_hash = hashlib.sha256(receipt_data.encode()).hexdigest() if models.SubscriptionAppleData.objects.filter( receipt_data_hash=data_hash ).exists(): logger.warning( "Duplicate Apple receipt submitted with hash: %s", data_hash ) raise serializers.ValidationError( { "receipt_data": ugettext( "This receipt has already been used." ) } ) try: receipt = subscriptions.validate_apple_receipt(receipt_data) except subscriptions.ReceiptException as e: raise serializers.ValidationError( code=e.code, detail={"receipt_data": e.msg} ) validated_data["expiration_time"] = receipt.expires_date return validated_data
import hashlib import logging from django.utils.translation import ugettext from rest_framework import serializers from know_me import models, subscriptions logger = logging.getLogger(__name__) class AppleSubscriptionSerializer(serializers.ModelSerializer): """ Serializer for an Apple subscription. """ class Meta: fields = ( "id", "time_created", "time_updated", "expiration_time", "receipt_data", ) model = models.SubscriptionAppleData read_only_fields = ("expiration_time",) def validate(self, data): """ Ensure the provided receipt data corresponds to a valid Apple receipt. Returns: The validated data. """ validated_data = data.copy() receipt_data = validated_data["receipt_data"] data_hash = hashlib.sha256(receipt_data.encode()).hexdigest() if models.SubscriptionAppleData.objects.filter( receipt_data_hash=data_hash ).exists(): logger.warning( "Duplicate Apple receipt submitted with hash: %s", data_hash ) raise serializers.ValidationError( { "receipt_data": ugettext( "This receipt has already been used." ) } ) try: receipt = subscriptions.validate_apple_receipt(receipt_data) except subscriptions.ReceiptException as e: raise serializers.ValidationError( code=e.code, detail={"receipt_data": e.msg} ) validated_data["expiration_time"] = receipt.expires_date return validated_data
Mark apple receipt expiration time as read only.
Mark apple receipt expiration time as read only.
Python
apache-2.0
knowmetools/km-api,knowmetools/km-api,knowmetools/km-api,knowmetools/km-api
python
## Code Before: import hashlib import logging from django.utils.translation import ugettext from rest_framework import serializers from know_me import models, subscriptions logger = logging.getLogger(__name__) class AppleSubscriptionSerializer(serializers.ModelSerializer): """ Serializer for an Apple subscription. """ class Meta: fields = ( "id", "time_created", "time_updated", "expiration_time", "receipt_data", ) model = models.SubscriptionAppleData def validate(self, data): """ Ensure the provided receipt data corresponds to a valid Apple receipt. Returns: The validated data. """ validated_data = data.copy() receipt_data = validated_data["receipt_data"] data_hash = hashlib.sha256(receipt_data.encode()).hexdigest() if models.SubscriptionAppleData.objects.filter( receipt_data_hash=data_hash ).exists(): logger.warning( "Duplicate Apple receipt submitted with hash: %s", data_hash ) raise serializers.ValidationError( { "receipt_data": ugettext( "This receipt has already been used." ) } ) try: receipt = subscriptions.validate_apple_receipt(receipt_data) except subscriptions.ReceiptException as e: raise serializers.ValidationError( code=e.code, detail={"receipt_data": e.msg} ) validated_data["expiration_time"] = receipt.expires_date return validated_data ## Instruction: Mark apple receipt expiration time as read only. ## Code After: import hashlib import logging from django.utils.translation import ugettext from rest_framework import serializers from know_me import models, subscriptions logger = logging.getLogger(__name__) class AppleSubscriptionSerializer(serializers.ModelSerializer): """ Serializer for an Apple subscription. """ class Meta: fields = ( "id", "time_created", "time_updated", "expiration_time", "receipt_data", ) model = models.SubscriptionAppleData read_only_fields = ("expiration_time",) def validate(self, data): """ Ensure the provided receipt data corresponds to a valid Apple receipt. Returns: The validated data. """ validated_data = data.copy() receipt_data = validated_data["receipt_data"] data_hash = hashlib.sha256(receipt_data.encode()).hexdigest() if models.SubscriptionAppleData.objects.filter( receipt_data_hash=data_hash ).exists(): logger.warning( "Duplicate Apple receipt submitted with hash: %s", data_hash ) raise serializers.ValidationError( { "receipt_data": ugettext( "This receipt has already been used." ) } ) try: receipt = subscriptions.validate_apple_receipt(receipt_data) except subscriptions.ReceiptException as e: raise serializers.ValidationError( code=e.code, detail={"receipt_data": e.msg} ) validated_data["expiration_time"] = receipt.expires_date return validated_data
ae08b2ccbfb023bd208a2d938151fdcfe0c8e333
app/workers/publisher_poll.rb
app/workers/publisher_poll.rb
require 'app/services/connection_builder' require 'app/services/publisher_update' module Citygram::Workers class PublisherPoll include Sidekiq::Worker sidekiq_options retry: 5 MAX_PAGE_NUMBER = 10 NEXT_PAGE_HEADER = 'Next-Page'.freeze def perform(publisher_id, endpoint, page_number = 1) # fetch publisher record or raise publisher = Publisher.first!(id: publisher_id) # prepare a connection for the given url, # or the publisher endpoint if no url is given connection = Citygram::Services::ConnectionBuilder.json("request.publisher.#{publisher.id}", url: endpoint) # execute the request or raise response = connection.get # save any new events feature_collection = response.body Citygram::Services::PublisherUpdate.call(feature_collection.fetch('features'), publisher) # OPTIONAL PAGINATION: # # iff successful to this point, and a next page is given # queue up a job to retrieve the next page # next_page = response.headers[NEXT_PAGE_HEADER] if next_page.present? && valid_next_page?(next_page, endpoint) && page_number < MAX_PAGE_NUMBER self.class.perform_async(publisher_id, next_page, page_number + 1) end end private def valid_next_page?(next_page, current_page) next_page = URI.parse(next_page) current_page = URI.parse(current_page) next_page.host == current_page.host && next_page != current_page end end end
require 'app/services/connection_builder' require 'app/services/publisher_update' module Citygram::Workers class PublisherPoll include Sidekiq::Worker sidekiq_options retry: 5 MAX_PAGE_NUMBER = 10 NEXT_PAGE_HEADER = 'Next-Page'.freeze def perform(publisher_id, url, page_number = 1) # fetch publisher record or raise publisher = Publisher.first!(id: publisher_id) # prepare a connection for the given url connection = Citygram::Services::ConnectionBuilder.json("request.publisher.#{publisher.id}", url: url) # execute the request or raise response = connection.get # save any new events feature_collection = response.body Citygram::Services::PublisherUpdate.call(feature_collection.fetch('features'), publisher) # OPTIONAL PAGINATION: # # iff successful to this point, and a next page is given # queue up a job to retrieve the next page # next_page = response.headers[NEXT_PAGE_HEADER] if next_page.present? && valid_next_page?(next_page, url) && page_number < MAX_PAGE_NUMBER self.class.perform_async(publisher_id, next_page, page_number + 1) end end private def valid_next_page?(next_page, current_page) next_page = URI.parse(next_page) current_page = URI.parse(current_page) next_page.host == current_page.host && next_page != current_page end end end
Rename variable and update comments
Rename variable and update comments
Ruby
mit
BetaNYC/citygram-nyc,codefortulsa/citygram,elberdev/citygram-nyc,chriswhong/citygram,BetaNYC/citygram-nyc,beetz12/citygram,shravan20084312/citygram,BetaNYC/citygram-nyc,elberdev/citygram-nyc,shravan20084312/citygram,beetz12/citygram,chriswhong/citygram,BetaNYC/citygram-nyc,openchattanooga/citygram,codeforamerica/citygram,codeforamerica/citygram,codefortulsa/citygram,openchattanooga/citygram,elberdev/citygram-nyc,codeforamerica/citygram,beetz12/citygram,shravan20084312/citygram,codefortulsa/citygram,codeforamerica/citygram
ruby
## Code Before: require 'app/services/connection_builder' require 'app/services/publisher_update' module Citygram::Workers class PublisherPoll include Sidekiq::Worker sidekiq_options retry: 5 MAX_PAGE_NUMBER = 10 NEXT_PAGE_HEADER = 'Next-Page'.freeze def perform(publisher_id, endpoint, page_number = 1) # fetch publisher record or raise publisher = Publisher.first!(id: publisher_id) # prepare a connection for the given url, # or the publisher endpoint if no url is given connection = Citygram::Services::ConnectionBuilder.json("request.publisher.#{publisher.id}", url: endpoint) # execute the request or raise response = connection.get # save any new events feature_collection = response.body Citygram::Services::PublisherUpdate.call(feature_collection.fetch('features'), publisher) # OPTIONAL PAGINATION: # # iff successful to this point, and a next page is given # queue up a job to retrieve the next page # next_page = response.headers[NEXT_PAGE_HEADER] if next_page.present? && valid_next_page?(next_page, endpoint) && page_number < MAX_PAGE_NUMBER self.class.perform_async(publisher_id, next_page, page_number + 1) end end private def valid_next_page?(next_page, current_page) next_page = URI.parse(next_page) current_page = URI.parse(current_page) next_page.host == current_page.host && next_page != current_page end end end ## Instruction: Rename variable and update comments ## Code After: require 'app/services/connection_builder' require 'app/services/publisher_update' module Citygram::Workers class PublisherPoll include Sidekiq::Worker sidekiq_options retry: 5 MAX_PAGE_NUMBER = 10 NEXT_PAGE_HEADER = 'Next-Page'.freeze def perform(publisher_id, url, page_number = 1) # fetch publisher record or raise publisher = Publisher.first!(id: publisher_id) # prepare a connection for the given url connection = Citygram::Services::ConnectionBuilder.json("request.publisher.#{publisher.id}", url: url) # execute the request or raise response = connection.get # save any new events feature_collection = response.body Citygram::Services::PublisherUpdate.call(feature_collection.fetch('features'), publisher) # OPTIONAL PAGINATION: # # iff successful to this point, and a next page is given # queue up a job to retrieve the next page # next_page = response.headers[NEXT_PAGE_HEADER] if next_page.present? && valid_next_page?(next_page, url) && page_number < MAX_PAGE_NUMBER self.class.perform_async(publisher_id, next_page, page_number + 1) end end private def valid_next_page?(next_page, current_page) next_page = URI.parse(next_page) current_page = URI.parse(current_page) next_page.host == current_page.host && next_page != current_page end end end
6b5becadb3452dcd02dc4044db82632cf0f03a64
lib/sfn/config/update.rb
lib/sfn/config/update.rb
require 'sfn' module Sfn class Config # Update command configuration class Update < Validate attribute( :apply_stack, String, :multiple => true, :description => 'Apply outputs from stack to input parameters' ) attribute( :parameter, Smash, :multiple => true, :description => '[DEPRECATED - use `parameters`] Pass template parameters directly (ParamName:ParamValue)', :coerce => lambda{|v, inst| result = inst.data[:parameter] || Array.new case v when String v.split(',').each do |item| result.push(Smash[*item.split(/[=:]/, 2)]) end else result.push(v.to_smash) end {:bogo_multiple => result} } ) attribute( :parameters, Smash, :description => 'Pass template parameters directly (ParamName:ParamValue)', :coerce => lambda{|v| case v when String Smash[v.split(',').map{|x| v.split(/[=:]/, 2)}] when Hash v.to_smash else v end } ) attribute( :plan, [TrueClass, FalseClass], :default => true, :description => 'Provide planning information prior to update' ) attribute( :compile_parameters, Smash, :description => 'Pass template compile time parameters directly (ParamName:ParamValue)', :coerce => lambda{|v| case v when String Smash[v.split(',').map{|x| v.split(/[=:]/, 2)}] when Hash v.to_smash else v end } ) end end end
require 'sfn' module Sfn class Config # Update command configuration class Update < Validate attribute( :apply_stack, String, :multiple => true, :description => 'Apply outputs from stack to input parameters' ) attribute( :parameter, Smash, :multiple => true, :description => '[DEPRECATED - use `parameters`] Pass template parameters directly (ParamName:ParamValue)', :coerce => lambda{|v, inst| result = inst.data[:parameter] || Array.new case v when String v.split(',').each do |item| result.push(Smash[*item.split(/[=:]/, 2)]) end else result.push(v.to_smash) end {:bogo_multiple => result} } ) attribute( :parameters, Smash, :description => 'Pass template parameters directly' ) attribute( :plan, [TrueClass, FalseClass], :default => true, :description => 'Provide planning information prior to update' ) attribute( :compile_parameters, Smash, :description => 'Pass template compile time parameters directly' ) end end end
Remove loading customization from Hash type attributes
Remove loading customization from Hash type attributes
Ruby
apache-2.0
sparkleformation/sfn
ruby
## Code Before: require 'sfn' module Sfn class Config # Update command configuration class Update < Validate attribute( :apply_stack, String, :multiple => true, :description => 'Apply outputs from stack to input parameters' ) attribute( :parameter, Smash, :multiple => true, :description => '[DEPRECATED - use `parameters`] Pass template parameters directly (ParamName:ParamValue)', :coerce => lambda{|v, inst| result = inst.data[:parameter] || Array.new case v when String v.split(',').each do |item| result.push(Smash[*item.split(/[=:]/, 2)]) end else result.push(v.to_smash) end {:bogo_multiple => result} } ) attribute( :parameters, Smash, :description => 'Pass template parameters directly (ParamName:ParamValue)', :coerce => lambda{|v| case v when String Smash[v.split(',').map{|x| v.split(/[=:]/, 2)}] when Hash v.to_smash else v end } ) attribute( :plan, [TrueClass, FalseClass], :default => true, :description => 'Provide planning information prior to update' ) attribute( :compile_parameters, Smash, :description => 'Pass template compile time parameters directly (ParamName:ParamValue)', :coerce => lambda{|v| case v when String Smash[v.split(',').map{|x| v.split(/[=:]/, 2)}] when Hash v.to_smash else v end } ) end end end ## Instruction: Remove loading customization from Hash type attributes ## Code After: require 'sfn' module Sfn class Config # Update command configuration class Update < Validate attribute( :apply_stack, String, :multiple => true, :description => 'Apply outputs from stack to input parameters' ) attribute( :parameter, Smash, :multiple => true, :description => '[DEPRECATED - use `parameters`] Pass template parameters directly (ParamName:ParamValue)', :coerce => lambda{|v, inst| result = inst.data[:parameter] || Array.new case v when String v.split(',').each do |item| result.push(Smash[*item.split(/[=:]/, 2)]) end else result.push(v.to_smash) end {:bogo_multiple => result} } ) attribute( :parameters, Smash, :description => 'Pass template parameters directly' ) attribute( :plan, [TrueClass, FalseClass], :default => true, :description => 'Provide planning information prior to update' ) attribute( :compile_parameters, Smash, :description => 'Pass template compile time parameters directly' ) end end end
573f3fd726c7bf1495bfdfeb2201317abc2949e4
src/parser/menu_item.py
src/parser/menu_item.py
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def target_is_reference(self): # If it is not another possibility, it is a reference return not self.target_is_sitemap() and \ not self.target_is_url() and \ self.target is not None def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))
Remove previously added method because finally not used...
Remove previously added method because finally not used...
Python
mit
epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp
python
## Code Before: """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def target_is_reference(self): # If it is not another possibility, it is a reference return not self.target_is_sitemap() and \ not self.target_is_url() and \ self.target is not None def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc')) ## Instruction: Remove previously added method because finally not used... ## Code After: """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))
c5950f7361e34736c07a6b8ccd731e9349469cfc
packages/twitter/twitter_client.js
packages/twitter/twitter_client.js
Twitter = {}; // Request Twitter credentials for the user // @param options {optional} XXX support options.requestPermissions // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Twitter.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'twitter'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback( new ServiceConfiguration.ConfigError()); return; } var credentialToken = Random.secret(); // We need to keep credentialToken across the next two 'steps' so we're adding // a credentialToken parameter to the url and the callback url that we'll be returned // to by oauth provider var loginStyle = OAuth._loginStyle('twitter', config, options); // url to app, enters "step 1" as described in // packages/accounts-oauth1-helper/oauth1_server.js var loginUrl = '/_oauth/twitter/?requestTokenAndRedirect=true' + '&state=' + OAuth._stateParam(loginStyle, credentialToken); OAuth.launchLogin({ loginService: "twitter", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: credentialRequestCompleteCallback, credentialToken: credentialToken }); };
Twitter = {}; // Request Twitter credentials for the user // @param options {optional} XXX support options.requestPermissions // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Twitter.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'twitter'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback( new ServiceConfiguration.ConfigError()); return; } var credentialToken = Random.secret(); // We need to keep credentialToken across the next two 'steps' so we're adding // a credentialToken parameter to the url and the callback url that we'll be returned // to by oauth provider var loginStyle = OAuth._loginStyle('twitter', config, options); // url to app, enters "step 1" as described in // packages/accounts-oauth1-helper/oauth1_server.js var loginUrl = Meteor.absoluteUrl( '_oauth/twitter/?requestTokenAndRedirect=true' + '&state=' + OAuth._stateParam(loginStyle, credentialToken)); OAuth.launchLogin({ loginService: "twitter", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: credentialRequestCompleteCallback, credentialToken: credentialToken }); };
Use `Meteor.absoluteUrl` for Twitter login URL
Use `Meteor.absoluteUrl` for Twitter login URL Fixes Twitter login on Cordova
JavaScript
mit
luohuazju/meteor,baiyunping333/meteor,baysao/meteor,DCKT/meteor,AnthonyAstige/meteor,benjamn/meteor,iman-mafi/meteor,HugoRLopes/meteor,pjump/meteor,skarekrow/meteor,yonglehou/meteor,AnjirHossain/meteor,meteor-velocity/meteor,cbonami/meteor,TribeMedia/meteor,henrypan/meteor,devgrok/meteor,jirengu/meteor,jdivy/meteor,hristaki/meteor,guazipi/meteor,brdtrpp/meteor,AnthonyAstige/meteor,GrimDerp/meteor,codingang/meteor,lorensr/meteor,udhayam/meteor,kengchau/meteor,Paulyoufu/meteor-1,meteor-velocity/meteor,sunny-g/meteor,sdeveloper/meteor,tdamsma/meteor,h200863057/meteor,yalexx/meteor,evilemon/meteor,steedos/meteor,chasertech/meteor,qscripter/meteor,pandeysoni/meteor,aramk/meteor,jagi/meteor,JesseQin/meteor,sclausen/meteor,Theviajerock/meteor,ashwathgovind/meteor,henrypan/meteor,skarekrow/meteor,LWHTarena/meteor,cbonami/meteor,mjmasn/meteor,cherbst/meteor,AlexR1712/meteor,dev-bobsong/meteor,skarekrow/meteor,mirstan/meteor,sitexa/meteor,tdamsma/meteor,papimomi/meteor,emmerge/meteor,Paulyoufu/meteor-1,michielvanoeffelen/meteor,cherbst/meteor,chengxiaole/meteor,udhayam/meteor,chengxiaole/meteor,michielvanoeffelen/meteor,SeanOceanHu/meteor,karlito40/meteor,somallg/meteor,TechplexEngineer/meteor,pjump/meteor,daslicht/meteor,deanius/meteor,yyx990803/meteor,shadedprofit/meteor,jrudio/meteor,cherbst/meteor,yyx990803/meteor,aldeed/meteor,karlito40/meteor,framewr/meteor,eluck/meteor,juansgaitan/meteor,neotim/meteor,HugoRLopes/meteor,esteedqueen/meteor,johnthepink/meteor,baysao/meteor,yiliaofan/meteor,allanalexandre/meteor,whip112/meteor,jirengu/meteor,codedogfish/meteor,daslicht/meteor,ndarilek/meteor,alexbeletsky/meteor,daltonrenaldo/meteor,AnjirHossain/meteor,meteor-velocity/meteor,ljack/meteor,lassombra/meteor,AnjirHossain/meteor,JesseQin/meteor,alphanso/meteor,shmiko/meteor,chasertech/meteor,daltonrenaldo/meteor,stevenliuit/meteor,stevenliuit/meteor,alexbeletsky/meteor,devgrok/meteor,pandeysoni/meteor,aramk/meteor,AnthonyAstige/meteor,paul-barry-kenzan/meteor,jenalgit/meteor,codingang/meteor,yalexx/meteor,akintoey/meteor,elkingtonmcb/meteor,lassombra/meteor,Urigo/meteor,guazipi/meteor,chiefninew/meteor,mirstan/meteor,Prithvi-A/meteor,chinasb/meteor,cog-64/meteor,Puena/meteor,JesseQin/meteor,arunoda/meteor,allanalexandre/meteor,chinasb/meteor,kidaa/meteor,chiefninew/meteor,framewr/meteor,mubassirhayat/meteor,Paulyoufu/meteor-1,papimomi/meteor,jrudio/meteor,meteor-velocity/meteor,jg3526/meteor,AnjirHossain/meteor,4commerce-technologies-AG/meteor,esteedqueen/meteor,benjamn/meteor,codedogfish/meteor,youprofit/meteor,devgrok/meteor,yiliaofan/meteor,HugoRLopes/meteor,servel333/meteor,Jonekee/meteor,brdtrpp/meteor,henrypan/meteor,yanisIk/meteor,jg3526/meteor,dfischer/meteor,elkingtonmcb/meteor,yanisIk/meteor,servel333/meteor,aleclarson/meteor,tdamsma/meteor,meonkeys/meteor,l0rd0fwar/meteor,somallg/meteor,bhargav175/meteor,IveWong/meteor,yinhe007/meteor,D1no/meteor,yonglehou/meteor,stevenliuit/meteor,Theviajerock/meteor,Prithvi-A/meteor,jirengu/meteor,JesseQin/meteor,PatrickMcGuinness/meteor,sitexa/meteor,nuvipannu/meteor,eluck/meteor,williambr/meteor,chiefninew/meteor,shrop/meteor,meteor-velocity/meteor,tdamsma/meteor,daslicht/meteor,bhargav175/meteor,newswim/meteor,lassombra/meteor,Jeremy017/meteor,chmac/meteor,mubassirhayat/meteor,SeanOceanHu/meteor,cbonami/meteor,vjau/meteor,baiyunping333/meteor,sunny-g/meteor,mauricionr/meteor,yinhe007/meteor,jeblister/meteor,Hansoft/meteor,neotim/meteor,cog-64/meteor,youprofit/meteor,codingang/meteor,devgrok/meteor,yonglehou/meteor,youprofit/meteor,sclausen/meteor,Prithvi-A/meteor,yonglehou/meteor,wmkcc/meteor,justintung/meteor,karlito40/meteor,servel333/meteor,jdivy/meteor,whip112/meteor,udhayam/meteor,chengxiaole/meteor,lassombra/meteor,modulexcite/meteor,hristaki/meteor,shadedprofit/meteor,elkingtonmcb/meteor,rabbyalone/meteor,baysao/meteor,jenalgit/meteor,DCKT/meteor,juansgaitan/meteor,fashionsun/meteor,lawrenceAIO/meteor,vjau/meteor,planet-training/meteor,alexbeletsky/meteor,HugoRLopes/meteor,calvintychan/meteor,servel333/meteor,codedogfish/meteor,pjump/meteor,esteedqueen/meteor,kidaa/meteor,AlexR1712/meteor,jg3526/meteor,SeanOceanHu/meteor,udhayam/meteor,joannekoong/meteor,eluck/meteor,baiyunping333/meteor,queso/meteor,aldeed/meteor,ashwathgovind/meteor,tdamsma/meteor,aldeed/meteor,TechplexEngineer/meteor,steedos/meteor,yiliaofan/meteor,meonkeys/meteor,brdtrpp/meteor,mirstan/meteor,sitexa/meteor,aramk/meteor,l0rd0fwar/meteor,ashwathgovind/meteor,TechplexEngineer/meteor,dandv/meteor,jirengu/meteor,jrudio/meteor,joannekoong/meteor,zdd910/meteor,jirengu/meteor,AlexR1712/meteor,akintoey/meteor,msavin/meteor,ljack/meteor,DAB0mB/meteor,calvintychan/meteor,vjau/meteor,udhayam/meteor,LWHTarena/meteor,alphanso/meteor,judsonbsilva/meteor,stevenliuit/meteor,lassombra/meteor,mauricionr/meteor,TribeMedia/meteor,oceanzou123/meteor,alphanso/meteor,michielvanoeffelen/meteor,rabbyalone/meteor,shadedprofit/meteor,shadedprofit/meteor,saisai/meteor,dev-bobsong/meteor,lorensr/meteor,AnthonyAstige/meteor,shrop/meteor,jenalgit/meteor,alexbeletsky/meteor,cbonami/meteor,pjump/meteor,newswim/meteor,williambr/meteor,qscripter/meteor,yyx990803/meteor,sclausen/meteor,karlito40/meteor,katopz/meteor,rozzzly/meteor,nuvipannu/meteor,jagi/meteor,fashionsun/meteor,4commerce-technologies-AG/meteor,DAB0mB/meteor,Quicksteve/meteor,daslicht/meteor,Theviajerock/meteor,lpinto93/meteor,msavin/meteor,calvintychan/meteor,elkingtonmcb/meteor,michielvanoeffelen/meteor,pandeysoni/meteor,pandeysoni/meteor,4commerce-technologies-AG/meteor,Jonekee/meteor,Prithvi-A/meteor,chiefninew/meteor,HugoRLopes/meteor,alphanso/meteor,jagi/meteor,DAB0mB/meteor,msavin/meteor,johnthepink/meteor,PatrickMcGuinness/meteor,AnthonyAstige/meteor,akintoey/meteor,Ken-Liu/meteor,l0rd0fwar/meteor,Puena/meteor,DCKT/meteor,alexbeletsky/meteor,shadedprofit/meteor,Hansoft/meteor,AlexR1712/meteor,saisai/meteor,eluck/meteor,newswim/meteor,Hansoft/meteor,cog-64/meteor,kencheung/meteor,IveWong/meteor,benstoltz/meteor,zdd910/meteor,shadedprofit/meteor,Hansoft/meteor,sclausen/meteor,Urigo/meteor,devgrok/meteor,chasertech/meteor,yyx990803/meteor,D1no/meteor,brdtrpp/meteor,Paulyoufu/meteor-1,emmerge/meteor,planet-training/meteor,Theviajerock/meteor,DCKT/meteor,whip112/meteor,henrypan/meteor,meonkeys/meteor,daslicht/meteor,williambr/meteor,guazipi/meteor,deanius/meteor,juansgaitan/meteor,lieuwex/meteor,colinligertwood/meteor,tdamsma/meteor,arunoda/meteor,tdamsma/meteor,kengchau/meteor,benjamn/meteor,chengxiaole/meteor,framewr/meteor,Jeremy017/meteor,yyx990803/meteor,somallg/meteor,newswim/meteor,paul-barry-kenzan/meteor,saisai/meteor,chmac/meteor,chengxiaole/meteor,shmiko/meteor,kencheung/meteor,colinligertwood/meteor,JesseQin/meteor,jirengu/meteor,fashionsun/meteor,johnthepink/meteor,cherbst/meteor,dfischer/meteor,GrimDerp/meteor,lpinto93/meteor,shmiko/meteor,sclausen/meteor,Profab/meteor,ericterpstra/meteor,aramk/meteor,neotim/meteor,sunny-g/meteor,LWHTarena/meteor,Jonekee/meteor,mjmasn/meteor,jenalgit/meteor,daltonrenaldo/meteor,whip112/meteor,jeblister/meteor,Eynaliyev/meteor,esteedqueen/meteor,chinasb/meteor,ljack/meteor,dev-bobsong/meteor,yiliaofan/meteor,imanmafi/meteor,mubassirhayat/meteor,kengchau/meteor,namho102/meteor,IveWong/meteor,shrop/meteor,namho102/meteor,aldeed/meteor,dev-bobsong/meteor,daslicht/meteor,dboyliao/meteor,h200863057/meteor,akintoey/meteor,l0rd0fwar/meteor,yonas/meteor-freebsd,newswim/meteor,nuvipannu/meteor,paul-barry-kenzan/meteor,shrop/meteor,ljack/meteor,Profab/meteor,Jeremy017/meteor,codedogfish/meteor,Paulyoufu/meteor-1,ashwathgovind/meteor,yonglehou/meteor,evilemon/meteor,sitexa/meteor,Jeremy017/meteor,vacjaliu/meteor,ndarilek/meteor,GrimDerp/meteor,Quicksteve/meteor,LWHTarena/meteor,dandv/meteor,meonkeys/meteor,yiliaofan/meteor,dboyliao/meteor,jeblister/meteor,katopz/meteor,Puena/meteor,luohuazju/meteor,dboyliao/meteor,jenalgit/meteor,Urigo/meteor,chengxiaole/meteor,AnjirHossain/meteor,nuvipannu/meteor,yinhe007/meteor,skarekrow/meteor,kidaa/meteor,bhargav175/meteor,bhargav175/meteor,arunoda/meteor,ljack/meteor,yonglehou/meteor,brdtrpp/meteor,lpinto93/meteor,Prithvi-A/meteor,SeanOceanHu/meteor,servel333/meteor,Ken-Liu/meteor,4commerce-technologies-AG/meteor,iman-mafi/meteor,justintung/meteor,johnthepink/meteor,cbonami/meteor,lorensr/meteor,Quicksteve/meteor,oceanzou123/meteor,steedos/meteor,chmac/meteor,lassombra/meteor,Prithvi-A/meteor,imanmafi/meteor,devgrok/meteor,wmkcc/meteor,lpinto93/meteor,karlito40/meteor,jeblister/meteor,Jeremy017/meteor,imanmafi/meteor,Hansoft/meteor,benstoltz/meteor,jrudio/meteor,jagi/meteor,judsonbsilva/meteor,pjump/meteor,oceanzou123/meteor,codingang/meteor,wmkcc/meteor,SeanOceanHu/meteor,dboyliao/meteor,pjump/meteor,steedos/meteor,Theviajerock/meteor,Urigo/meteor,oceanzou123/meteor,vacjaliu/meteor,yonas/meteor-freebsd,juansgaitan/meteor,arunoda/meteor,pandeysoni/meteor,skarekrow/meteor,dandv/meteor,iman-mafi/meteor,lawrenceAIO/meteor,yonas/meteor-freebsd,jenalgit/meteor,cherbst/meteor,colinligertwood/meteor,dandv/meteor,TechplexEngineer/meteor,katopz/meteor,codedogfish/meteor,michielvanoeffelen/meteor,neotim/meteor,allanalexandre/meteor,IveWong/meteor,framewr/meteor,EduShareOntario/meteor,mauricionr/meteor,EduShareOntario/meteor,mirstan/meteor,Puena/meteor,youprofit/meteor,ashwathgovind/meteor,dfischer/meteor,dfischer/meteor,justintung/meteor,esteedqueen/meteor,yyx990803/meteor,lpinto93/meteor,queso/meteor,DCKT/meteor,benstoltz/meteor,lawrenceAIO/meteor,Quicksteve/meteor,chasertech/meteor,brettle/meteor,aleclarson/meteor,queso/meteor,johnthepink/meteor,Hansoft/meteor,AnjirHossain/meteor,luohuazju/meteor,allanalexandre/meteor,henrypan/meteor,DCKT/meteor,TribeMedia/meteor,4commerce-technologies-AG/meteor,chiefninew/meteor,benjamn/meteor,yanisIk/meteor,cherbst/meteor,luohuazju/meteor,chiefninew/meteor,lieuwex/meteor,qscripter/meteor,evilemon/meteor,Ken-Liu/meteor,luohuazju/meteor,PatrickMcGuinness/meteor,sitexa/meteor,Eynaliyev/meteor,paul-barry-kenzan/meteor,steedos/meteor,yonas/meteor-freebsd,mjmasn/meteor,nuvipannu/meteor,chmac/meteor,williambr/meteor,Urigo/meteor,Theviajerock/meteor,yonglehou/meteor,ericterpstra/meteor,DAB0mB/meteor,DAB0mB/meteor,cog-64/meteor,sdeveloper/meteor,katopz/meteor,youprofit/meteor,yalexx/meteor,Puena/meteor,brettle/meteor,colinligertwood/meteor,henrypan/meteor,yalexx/meteor,esteedqueen/meteor,udhayam/meteor,h200863057/meteor,rozzzly/meteor,chiefninew/meteor,eluck/meteor,shmiko/meteor,esteedqueen/meteor,stevenliuit/meteor,jg3526/meteor,newswim/meteor,alexbeletsky/meteor,rabbyalone/meteor,imanmafi/meteor,framewr/meteor,akintoey/meteor,aramk/meteor,zdd910/meteor,luohuazju/meteor,D1no/meteor,rozzzly/meteor,colinligertwood/meteor,neotim/meteor,mauricionr/meteor,iman-mafi/meteor,sdeveloper/meteor,mubassirhayat/meteor,EduShareOntario/meteor,yinhe007/meteor,l0rd0fwar/meteor,nuvipannu/meteor,cog-64/meteor,oceanzou123/meteor,dboyliao/meteor,yinhe007/meteor,PatrickMcGuinness/meteor,JesseQin/meteor,joannekoong/meteor,jdivy/meteor,Jonekee/meteor,johnthepink/meteor,pandeysoni/meteor,namho102/meteor,framewr/meteor,AnthonyAstige/meteor,Prithvi-A/meteor,bhargav175/meteor,steedos/meteor,sitexa/meteor,lieuwex/meteor,jg3526/meteor,sdeveloper/meteor,baiyunping333/meteor,baysao/meteor,jdivy/meteor,Eynaliyev/meteor,sunny-g/meteor,h200863057/meteor,baiyunping333/meteor,justintung/meteor,hristaki/meteor,l0rd0fwar/meteor,jdivy/meteor,whip112/meteor,vjau/meteor,jeblister/meteor,queso/meteor,benjamn/meteor,karlito40/meteor,juansgaitan/meteor,vjau/meteor,Ken-Liu/meteor,somallg/meteor,mjmasn/meteor,qscripter/meteor,mubassirhayat/meteor,colinligertwood/meteor,Profab/meteor,chengxiaole/meteor,Urigo/meteor,dandv/meteor,msavin/meteor,AnthonyAstige/meteor,queso/meteor,jdivy/meteor,lieuwex/meteor,Profab/meteor,dboyliao/meteor,sclausen/meteor,evilemon/meteor,PatrickMcGuinness/meteor,justintung/meteor,allanalexandre/meteor,Hansoft/meteor,vacjaliu/meteor,yonas/meteor-freebsd,TechplexEngineer/meteor,ericterpstra/meteor,chmac/meteor,zdd910/meteor,chinasb/meteor,rabbyalone/meteor,kengchau/meteor,D1no/meteor,jagi/meteor,DAB0mB/meteor,AlexR1712/meteor,modulexcite/meteor,cog-64/meteor,paul-barry-kenzan/meteor,lorensr/meteor,Puena/meteor,lieuwex/meteor,dfischer/meteor,imanmafi/meteor,yonas/meteor-freebsd,judsonbsilva/meteor,brdtrpp/meteor,shrop/meteor,devgrok/meteor,brettle/meteor,papimomi/meteor,codedogfish/meteor,Eynaliyev/meteor,planet-training/meteor,Profab/meteor,mjmasn/meteor,stevenliuit/meteor,shadedprofit/meteor,henrypan/meteor,oceanzou123/meteor,jenalgit/meteor,TechplexEngineer/meteor,steedos/meteor,lorensr/meteor,katopz/meteor,saisai/meteor,yonas/meteor-freebsd,dboyliao/meteor,judsonbsilva/meteor,judsonbsilva/meteor,guazipi/meteor,dev-bobsong/meteor,D1no/meteor,lawrenceAIO/meteor,kencheung/meteor,qscripter/meteor,lawrenceAIO/meteor,papimomi/meteor,sunny-g/meteor,ljack/meteor,joannekoong/meteor,DCKT/meteor,chinasb/meteor,Quicksteve/meteor,chinasb/meteor,fashionsun/meteor,skarekrow/meteor,katopz/meteor,evilemon/meteor,luohuazju/meteor,vacjaliu/meteor,Theviajerock/meteor,saisai/meteor,TechplexEngineer/meteor,IveWong/meteor,benstoltz/meteor,guazipi/meteor,deanius/meteor,neotim/meteor,elkingtonmcb/meteor,benstoltz/meteor,aramk/meteor,Profab/meteor,TribeMedia/meteor,shrop/meteor,LWHTarena/meteor,jrudio/meteor,EduShareOntario/meteor,4commerce-technologies-AG/meteor,jrudio/meteor,emmerge/meteor,sunny-g/meteor,cherbst/meteor,mirstan/meteor,planet-training/meteor,saisai/meteor,baiyunping333/meteor,benstoltz/meteor,dboyliao/meteor,chmac/meteor,paul-barry-kenzan/meteor,arunoda/meteor,papimomi/meteor,brdtrpp/meteor,baiyunping333/meteor,ndarilek/meteor,zdd910/meteor,elkingtonmcb/meteor,DAB0mB/meteor,deanius/meteor,mirstan/meteor,guazipi/meteor,vjau/meteor,SeanOceanHu/meteor,benstoltz/meteor,EduShareOntario/meteor,calvintychan/meteor,sunny-g/meteor,ashwathgovind/meteor,emmerge/meteor,ericterpstra/meteor,HugoRLopes/meteor,qscripter/meteor,baysao/meteor,SeanOceanHu/meteor,IveWong/meteor,ndarilek/meteor,jdivy/meteor,meonkeys/meteor,calvintychan/meteor,sdeveloper/meteor,jeblister/meteor,iman-mafi/meteor,hristaki/meteor,williambr/meteor,wmkcc/meteor,whip112/meteor,meteor-velocity/meteor,yinhe007/meteor,brettle/meteor,Profab/meteor,AnthonyAstige/meteor,eluck/meteor,cbonami/meteor,wmkcc/meteor,shrop/meteor,chasertech/meteor,Paulyoufu/meteor-1,juansgaitan/meteor,mauricionr/meteor,yalexx/meteor,Ken-Liu/meteor,chmac/meteor,meteor-velocity/meteor,aldeed/meteor,lpinto93/meteor,servel333/meteor,Quicksteve/meteor,iman-mafi/meteor,Ken-Liu/meteor,shmiko/meteor,Ken-Liu/meteor,rozzzly/meteor,GrimDerp/meteor,GrimDerp/meteor,GrimDerp/meteor,codingang/meteor,Quicksteve/meteor,kidaa/meteor,Eynaliyev/meteor,jagi/meteor,daltonrenaldo/meteor,jagi/meteor,lieuwex/meteor,sunny-g/meteor,GrimDerp/meteor,fashionsun/meteor,ashwathgovind/meteor,papimomi/meteor,daslicht/meteor,fashionsun/meteor,arunoda/meteor,planet-training/meteor,ljack/meteor,Jeremy017/meteor,EduShareOntario/meteor,planet-training/meteor,PatrickMcGuinness/meteor,lorensr/meteor,TribeMedia/meteor,modulexcite/meteor,AnjirHossain/meteor,alexbeletsky/meteor,D1no/meteor,qscripter/meteor,Jeremy017/meteor,emmerge/meteor,kengchau/meteor,kengchau/meteor,colinligertwood/meteor,msavin/meteor,Eynaliyev/meteor,williambr/meteor,PatrickMcGuinness/meteor,nuvipannu/meteor,4commerce-technologies-AG/meteor,chiefninew/meteor,allanalexandre/meteor,evilemon/meteor,rabbyalone/meteor,kidaa/meteor,vacjaliu/meteor,chasertech/meteor,akintoey/meteor,msavin/meteor,yinhe007/meteor,arunoda/meteor,stevenliuit/meteor,vjau/meteor,codingang/meteor,dandv/meteor,Jonekee/meteor,mubassirhayat/meteor,karlito40/meteor,h200863057/meteor,johnthepink/meteor,lieuwex/meteor,calvintychan/meteor,somallg/meteor,shmiko/meteor,karlito40/meteor,ljack/meteor,lorensr/meteor,eluck/meteor,skarekrow/meteor,elkingtonmcb/meteor,fashionsun/meteor,yanisIk/meteor,yanisIk/meteor,namho102/meteor,judsonbsilva/meteor,AlexR1712/meteor,guazipi/meteor,vacjaliu/meteor,ndarilek/meteor,brettle/meteor,joannekoong/meteor,IveWong/meteor,yyx990803/meteor,pjump/meteor,D1no/meteor,ericterpstra/meteor,AlexR1712/meteor,meonkeys/meteor,ndarilek/meteor,yalexx/meteor,emmerge/meteor,Urigo/meteor,deanius/meteor,kencheung/meteor,daltonrenaldo/meteor,ericterpstra/meteor,sdeveloper/meteor,kencheung/meteor,wmkcc/meteor,baysao/meteor,allanalexandre/meteor,deanius/meteor,namho102/meteor,rozzzly/meteor,somallg/meteor,lassombra/meteor,evilemon/meteor,lawrenceAIO/meteor,imanmafi/meteor,alphanso/meteor,joannekoong/meteor,jirengu/meteor,michielvanoeffelen/meteor,hristaki/meteor,papimomi/meteor,kidaa/meteor,LWHTarena/meteor,imanmafi/meteor,TribeMedia/meteor,codedogfish/meteor,Eynaliyev/meteor,dev-bobsong/meteor,kencheung/meteor,michielvanoeffelen/meteor,lpinto93/meteor,katopz/meteor,yanisIk/meteor,mubassirhayat/meteor,cog-64/meteor,daltonrenaldo/meteor,codingang/meteor,kidaa/meteor,daltonrenaldo/meteor,Puena/meteor,rabbyalone/meteor,whip112/meteor,rozzzly/meteor,baysao/meteor,mirstan/meteor,jg3526/meteor,meonkeys/meteor,bhargav175/meteor,brdtrpp/meteor,newswim/meteor,h200863057/meteor,tdamsma/meteor,wmkcc/meteor,zdd910/meteor,jeblister/meteor,Jonekee/meteor,alphanso/meteor,yanisIk/meteor,yalexx/meteor,queso/meteor,saisai/meteor,sitexa/meteor,framewr/meteor,zdd910/meteor,judsonbsilva/meteor,JesseQin/meteor,benjamn/meteor,Eynaliyev/meteor,servel333/meteor,benjamn/meteor,mjmasn/meteor,mauricionr/meteor,planet-training/meteor,modulexcite/meteor,msavin/meteor,sclausen/meteor,dfischer/meteor,hristaki/meteor,modulexcite/meteor,somallg/meteor,justintung/meteor,alphanso/meteor,oceanzou123/meteor,kengchau/meteor,queso/meteor,eluck/meteor,hristaki/meteor,kencheung/meteor,Paulyoufu/meteor-1,sdeveloper/meteor,juansgaitan/meteor,emmerge/meteor,brettle/meteor,l0rd0fwar/meteor,EduShareOntario/meteor,daltonrenaldo/meteor,justintung/meteor,somallg/meteor,mjmasn/meteor,yanisIk/meteor,HugoRLopes/meteor,udhayam/meteor,mubassirhayat/meteor,deanius/meteor,aramk/meteor,ndarilek/meteor,pandeysoni/meteor,alexbeletsky/meteor,neotim/meteor,yiliaofan/meteor,HugoRLopes/meteor,LWHTarena/meteor,planet-training/meteor,namho102/meteor,rabbyalone/meteor,vacjaliu/meteor,akintoey/meteor,Jonekee/meteor,bhargav175/meteor,chinasb/meteor,h200863057/meteor,ericterpstra/meteor,TribeMedia/meteor,cbonami/meteor,joannekoong/meteor,williambr/meteor,shmiko/meteor,lawrenceAIO/meteor,jg3526/meteor,modulexcite/meteor,dandv/meteor,youprofit/meteor,aldeed/meteor,modulexcite/meteor,aleclarson/meteor,rozzzly/meteor,dev-bobsong/meteor,brettle/meteor,servel333/meteor,paul-barry-kenzan/meteor,mauricionr/meteor,yiliaofan/meteor,D1no/meteor,aldeed/meteor,SeanOceanHu/meteor,namho102/meteor,dfischer/meteor,allanalexandre/meteor,ndarilek/meteor,youprofit/meteor,chasertech/meteor,iman-mafi/meteor,calvintychan/meteor
javascript
## Code Before: Twitter = {}; // Request Twitter credentials for the user // @param options {optional} XXX support options.requestPermissions // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Twitter.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'twitter'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback( new ServiceConfiguration.ConfigError()); return; } var credentialToken = Random.secret(); // We need to keep credentialToken across the next two 'steps' so we're adding // a credentialToken parameter to the url and the callback url that we'll be returned // to by oauth provider var loginStyle = OAuth._loginStyle('twitter', config, options); // url to app, enters "step 1" as described in // packages/accounts-oauth1-helper/oauth1_server.js var loginUrl = '/_oauth/twitter/?requestTokenAndRedirect=true' + '&state=' + OAuth._stateParam(loginStyle, credentialToken); OAuth.launchLogin({ loginService: "twitter", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: credentialRequestCompleteCallback, credentialToken: credentialToken }); }; ## Instruction: Use `Meteor.absoluteUrl` for Twitter login URL Fixes Twitter login on Cordova ## Code After: Twitter = {}; // Request Twitter credentials for the user // @param options {optional} XXX support options.requestPermissions // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Twitter.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'twitter'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback( new ServiceConfiguration.ConfigError()); return; } var credentialToken = Random.secret(); // We need to keep credentialToken across the next two 'steps' so we're adding // a credentialToken parameter to the url and the callback url that we'll be returned // to by oauth provider var loginStyle = OAuth._loginStyle('twitter', config, options); // url to app, enters "step 1" as described in // packages/accounts-oauth1-helper/oauth1_server.js var loginUrl = Meteor.absoluteUrl( '_oauth/twitter/?requestTokenAndRedirect=true' + '&state=' + OAuth._stateParam(loginStyle, credentialToken)); OAuth.launchLogin({ loginService: "twitter", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: credentialRequestCompleteCallback, credentialToken: credentialToken }); };
92c0fdd6eeeb2d42a0aef3f2aa0250f71f53df18
src/demos/vehicle/m113/M113_SimplePowertrain.cpp
src/demos/vehicle/m113/M113_SimplePowertrain.cpp
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Simple powertrain model for the M113 vehicle. // - simple speed-torque curve // - no torque converter // - no transmission box // // ============================================================================= #include "m113/M113_SimplePowertrain.h" using namespace chrono; using namespace chrono::vehicle; namespace m113 { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double M113_SimplePowertrain::m_max_torque = 1000; const double M113_SimplePowertrain::m_max_speed = 3000; const double M113_SimplePowertrain::m_fwd_gear_ratio = 0.3; const double M113_SimplePowertrain::m_rev_gear_ratio = -0.3; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- M113_SimplePowertrain::M113_SimplePowertrain() : ChSimplePowertrain() { } } // end namespace m113
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Simple powertrain model for the M113 vehicle. // - simple speed-torque curve // - no torque converter // - no transmission box // // ============================================================================= #include "m113/M113_SimplePowertrain.h" using namespace chrono; using namespace chrono::vehicle; namespace m113 { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double M113_SimplePowertrain::m_max_torque = 1000; const double M113_SimplePowertrain::m_max_speed = 3000 * CH_C_2PI; const double M113_SimplePowertrain::m_fwd_gear_ratio = 0.1; const double M113_SimplePowertrain::m_rev_gear_ratio = -0.3; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- M113_SimplePowertrain::M113_SimplePowertrain() : ChSimplePowertrain() { } } // end namespace m113
Adjust M113 simple powertrain parameters.
Adjust M113 simple powertrain parameters. - Max. engine speed must be specified in rad/s - Decrease gear ratio (to include the effect of the unmodeled transmission)
C++
bsd-3-clause
armanpazouki/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,dariomangoni/chrono,rserban/chrono,projectchrono/chrono,rserban/chrono,tjolsen/chrono,rserban/chrono,andrewseidl/chrono,jcmadsen/chrono,Milad-Rakhsha/chrono,tjolsen/chrono,armanpazouki/chrono,amelmquist/chrono,tjolsen/chrono,jcmadsen/chrono,dariomangoni/chrono,jcmadsen/chrono,rserban/chrono,rserban/chrono,projectchrono/chrono,armanpazouki/chrono,andrewseidl/chrono,amelmquist/chrono,projectchrono/chrono,amelmquist/chrono,amelmquist/chrono,Milad-Rakhsha/chrono,jcmadsen/chrono,Milad-Rakhsha/chrono,andrewseidl/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,tjolsen/chrono,armanpazouki/chrono,jcmadsen/chrono,jcmadsen/chrono,dariomangoni/chrono,dariomangoni/chrono,amelmquist/chrono,tjolsen/chrono,armanpazouki/chrono,projectchrono/chrono,projectchrono/chrono,rserban/chrono,Milad-Rakhsha/chrono,andrewseidl/chrono,armanpazouki/chrono,projectchrono/chrono,amelmquist/chrono,rserban/chrono,jcmadsen/chrono,andrewseidl/chrono
c++
## Code Before: // ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Simple powertrain model for the M113 vehicle. // - simple speed-torque curve // - no torque converter // - no transmission box // // ============================================================================= #include "m113/M113_SimplePowertrain.h" using namespace chrono; using namespace chrono::vehicle; namespace m113 { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double M113_SimplePowertrain::m_max_torque = 1000; const double M113_SimplePowertrain::m_max_speed = 3000; const double M113_SimplePowertrain::m_fwd_gear_ratio = 0.3; const double M113_SimplePowertrain::m_rev_gear_ratio = -0.3; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- M113_SimplePowertrain::M113_SimplePowertrain() : ChSimplePowertrain() { } } // end namespace m113 ## Instruction: Adjust M113 simple powertrain parameters. - Max. engine speed must be specified in rad/s - Decrease gear ratio (to include the effect of the unmodeled transmission) ## Code After: // ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Simple powertrain model for the M113 vehicle. // - simple speed-torque curve // - no torque converter // - no transmission box // // ============================================================================= #include "m113/M113_SimplePowertrain.h" using namespace chrono; using namespace chrono::vehicle; namespace m113 { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double M113_SimplePowertrain::m_max_torque = 1000; const double M113_SimplePowertrain::m_max_speed = 3000 * CH_C_2PI; const double M113_SimplePowertrain::m_fwd_gear_ratio = 0.1; const double M113_SimplePowertrain::m_rev_gear_ratio = -0.3; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- M113_SimplePowertrain::M113_SimplePowertrain() : ChSimplePowertrain() { } } // end namespace m113
46d2977eb56472962889e81053d26870432ab81a
src/Furniture/FactoryBundle/Security/Voter/ViewFactoryVoter.php
src/Furniture/FactoryBundle/Security/Voter/ViewFactoryVoter.php
<?php namespace Furniture\FactoryBundle\Security\Voter; use Furniture\UserBundle\Entity\User; use Furniture\FactoryBundle\Entity\Factory; use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter; class ViewFactoryVoter extends AbstractVoter { /** * {@inheritDoc} */ protected function getSupportedClasses() { return [Factory::class]; } /** * {@inheritDoc} */ protected function getSupportedAttributes() { return ['ACTIVE_RELATION']; } /** * {@inheritDoc} */ protected function isGranted($attribute, $factory, $user = null) { /** @var \Furniture\FactoryBundle\Entity\Factory $factory */ if (!$user || !$user instanceof User) { return false; } switch ($attribute) { case 'ACTIVE_RELATION': if (!$user->isRetailer()) { return false; } $factoryRetailerRelation = $factory->getRetailerRelationByRetailer( $user ->getRetailerUserProfile() ->getRetailerProfile() ); if ($factory->isEnabled() && (($factoryRetailerRelation && $factoryRetailerRelation->isActive() && $factoryRetailerRelation->isFactoryAccept()) || $factory->getDefaultRelation()->isAccessProducts()) ) { return true; } return false; default: return false; } } }
<?php namespace Furniture\FactoryBundle\Security\Voter; use Furniture\UserBundle\Entity\User; use Furniture\FactoryBundle\Entity\Factory; use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter; class ViewFactoryVoter extends AbstractVoter { /** * {@inheritDoc} */ protected function getSupportedClasses() { return [Factory::class]; } /** * {@inheritDoc} */ protected function getSupportedAttributes() { return ['ACTIVE_RELATION']; } /** * {@inheritDoc} */ protected function isGranted($attribute, $factory, $user = null) { /** @var \Furniture\FactoryBundle\Entity\Factory $factory */ if (!$user || !$user instanceof User) { return false; } switch ($attribute) { case 'ACTIVE_RELATION': if (!$user->isRetailer()) { return false; } $factoryRetailerRelation = $factory->getRetailerRelationByRetailer( $user ->getRetailerUserProfile() ->getRetailerProfile() ); if ($factory->isEnabled() && (($factoryRetailerRelation && $factoryRetailerRelation->isActive() && $factoryRetailerRelation->isFactoryAccept() && $factoryRetailerRelation->isAccessProducts()) || $factory->getDefaultRelation()->isAccessProducts()) ) { return true; } return false; default: return false; } } }
Update factory voter ACTIVE_RELATION statement
Update factory voter ACTIVE_RELATION statement
PHP
mit
Viktor-s/f,Viktor-s/f,Viktor-s/f,Viktor-s/f,Viktor-s/f
php
## Code Before: <?php namespace Furniture\FactoryBundle\Security\Voter; use Furniture\UserBundle\Entity\User; use Furniture\FactoryBundle\Entity\Factory; use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter; class ViewFactoryVoter extends AbstractVoter { /** * {@inheritDoc} */ protected function getSupportedClasses() { return [Factory::class]; } /** * {@inheritDoc} */ protected function getSupportedAttributes() { return ['ACTIVE_RELATION']; } /** * {@inheritDoc} */ protected function isGranted($attribute, $factory, $user = null) { /** @var \Furniture\FactoryBundle\Entity\Factory $factory */ if (!$user || !$user instanceof User) { return false; } switch ($attribute) { case 'ACTIVE_RELATION': if (!$user->isRetailer()) { return false; } $factoryRetailerRelation = $factory->getRetailerRelationByRetailer( $user ->getRetailerUserProfile() ->getRetailerProfile() ); if ($factory->isEnabled() && (($factoryRetailerRelation && $factoryRetailerRelation->isActive() && $factoryRetailerRelation->isFactoryAccept()) || $factory->getDefaultRelation()->isAccessProducts()) ) { return true; } return false; default: return false; } } } ## Instruction: Update factory voter ACTIVE_RELATION statement ## Code After: <?php namespace Furniture\FactoryBundle\Security\Voter; use Furniture\UserBundle\Entity\User; use Furniture\FactoryBundle\Entity\Factory; use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter; class ViewFactoryVoter extends AbstractVoter { /** * {@inheritDoc} */ protected function getSupportedClasses() { return [Factory::class]; } /** * {@inheritDoc} */ protected function getSupportedAttributes() { return ['ACTIVE_RELATION']; } /** * {@inheritDoc} */ protected function isGranted($attribute, $factory, $user = null) { /** @var \Furniture\FactoryBundle\Entity\Factory $factory */ if (!$user || !$user instanceof User) { return false; } switch ($attribute) { case 'ACTIVE_RELATION': if (!$user->isRetailer()) { return false; } $factoryRetailerRelation = $factory->getRetailerRelationByRetailer( $user ->getRetailerUserProfile() ->getRetailerProfile() ); if ($factory->isEnabled() && (($factoryRetailerRelation && $factoryRetailerRelation->isActive() && $factoryRetailerRelation->isFactoryAccept() && $factoryRetailerRelation->isAccessProducts()) || $factory->getDefaultRelation()->isAccessProducts()) ) { return true; } return false; default: return false; } } }
fd3cfa0e7103825791413aa14324c4fae91a42c3
src/edu/wpi/first/wpilibj/templates/commands/ReadSetCamera.java
src/edu/wpi/first/wpilibj/templates/commands/ReadSetCamera.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.camera.AxisCamera; /** * * @author profplump */ public class ReadSetCamera extends CommandBase { public ReadSetCamera() { requires(mainCamera); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { AxisCamera camera = mainCamera.getCamera(); System.err.println("Brightness: " + camera.getBrightness()); System.err.println("ColorLevel: " + camera.getColorLevel()); System.err.println("Compression: " + camera.getCompression()); System.err.println("ExposureControl: " + camera.getExposureControl()); System.err.println("ExposurePriority: " + camera.getExposurePriority()); System.err.println("MaxFPS: " + camera.getMaxFPS()); System.err.println("Resolution: " + camera.getResolution()); System.err.println("Rotation: " + camera.getRotation()); System.err.println("WhiteBalance: " + camera.getWhiteBalance()); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.camera.AxisCamera; /** * * @author profplump */ public class ReadSetCamera extends CommandBase { public ReadSetCamera() { requires(mainCamera); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { AxisCamera camera = mainCamera.getCamera(); System.err.println("Brightness: " + camera.getBrightness()); System.err.println("ColorLevel: " + camera.getColorLevel()); System.err.println("Compression: " + camera.getCompression()); System.err.println("ExposureControl: " + camera.getExposureControl()); System.err.println("ExposurePriority: " + camera.getExposurePriority()); System.err.println("MaxFPS: " + camera.getMaxFPS()); System.err.println("Resolution: " + camera.getResolution()); System.err.println("Rotation: " + camera.getRotation()); System.err.println("WhiteBalance: " + camera.getWhiteBalance()); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { this.execute(); return true; } // Called once after isFinished returns true protected void end() { } }
Exit quickly to avoid side effects
Exit quickly to avoid side effects
Java
bsd-3-clause
FIRST-4030/2013
java
## Code Before: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.camera.AxisCamera; /** * * @author profplump */ public class ReadSetCamera extends CommandBase { public ReadSetCamera() { requires(mainCamera); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { AxisCamera camera = mainCamera.getCamera(); System.err.println("Brightness: " + camera.getBrightness()); System.err.println("ColorLevel: " + camera.getColorLevel()); System.err.println("Compression: " + camera.getCompression()); System.err.println("ExposureControl: " + camera.getExposureControl()); System.err.println("ExposurePriority: " + camera.getExposurePriority()); System.err.println("MaxFPS: " + camera.getMaxFPS()); System.err.println("Resolution: " + camera.getResolution()); System.err.println("Rotation: " + camera.getRotation()); System.err.println("WhiteBalance: " + camera.getWhiteBalance()); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } } ## Instruction: Exit quickly to avoid side effects ## Code After: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.camera.AxisCamera; /** * * @author profplump */ public class ReadSetCamera extends CommandBase { public ReadSetCamera() { requires(mainCamera); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { AxisCamera camera = mainCamera.getCamera(); System.err.println("Brightness: " + camera.getBrightness()); System.err.println("ColorLevel: " + camera.getColorLevel()); System.err.println("Compression: " + camera.getCompression()); System.err.println("ExposureControl: " + camera.getExposureControl()); System.err.println("ExposurePriority: " + camera.getExposurePriority()); System.err.println("MaxFPS: " + camera.getMaxFPS()); System.err.println("Resolution: " + camera.getResolution()); System.err.println("Rotation: " + camera.getRotation()); System.err.println("WhiteBalance: " + camera.getWhiteBalance()); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { this.execute(); return true; } // Called once after isFinished returns true protected void end() { } }
070d24c18b88d4e73c9cb75284c5915c5f68ffb0
classes/Infrastructure/Templating/TwigExtension.php
classes/Infrastructure/Templating/TwigExtension.php
<?php declare(strict_types=1); /** * Copyright (c) 2013-2017 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Infrastructure\Templating; use OpenCFP\PathInterface; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Twig_Extension; use Twig_SimpleFunction; class TwigExtension extends Twig_Extension { /** * @var RequestStack */ private $requestStack; /** * @var UrlGeneratorInterface */ private $urlGenerator; /** * @var PathInterface */ private $path; public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path) { $this->requestStack = $requestStack; $this->urlGenerator = $urlGenerator; $this->path = $path; } public function getFunctions() { return [ new Twig_SimpleFunction('uploads', function ($path) { return $this->path->downloadFromPath() . $path; }), new Twig_SimpleFunction('assets', function ($path) { return '/assets/' . $path; }), new Twig_SimpleFunction('active', function ($route) { return $this->urlGenerator->generate($route) === $this->requestStack->getCurrentRequest()->getRequestUri(); }), ]; } }
<?php declare(strict_types=1); /** * Copyright (c) 2013-2017 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Infrastructure\Templating; use OpenCFP\PathInterface; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Twig_Extension; use Twig_SimpleFunction; class TwigExtension extends Twig_Extension { /** * @var RequestStack */ private $requestStack; /** * @var UrlGeneratorInterface */ private $urlGenerator; /** * @var PathInterface */ private $path; public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path) { $this->requestStack = $requestStack; $this->urlGenerator = $urlGenerator; $this->path = $path; } public function getFunctions() { return [ new Twig_SimpleFunction('uploads', function ($path) { return $this->path->downloadFromPath() . $path; }), new Twig_SimpleFunction('assets', function ($path) { return $this->path->webAssetsPath() . $path; }), new Twig_SimpleFunction('active', function ($route) { return $this->urlGenerator->generate($route) === $this->requestStack->getCurrentRequest()->getRequestUri(); }), ]; } }
Implement web assets in the twig function
Implement web assets in the twig function
PHP
mit
GrUSP/opencfp,GrUSP/opencfp,localheinz/opencfp,GrUSP/opencfp,PHPBenelux/opencfp,opencfp/opencfp,opencfp/opencfp,PHPBenelux/opencfp,localheinz/opencfp,opencfp/opencfp,PHPBenelux/opencfp,PHPBenelux/opencfp,localheinz/opencfp,localheinz/opencfp,GrUSP/opencfp
php
## Code Before: <?php declare(strict_types=1); /** * Copyright (c) 2013-2017 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Infrastructure\Templating; use OpenCFP\PathInterface; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Twig_Extension; use Twig_SimpleFunction; class TwigExtension extends Twig_Extension { /** * @var RequestStack */ private $requestStack; /** * @var UrlGeneratorInterface */ private $urlGenerator; /** * @var PathInterface */ private $path; public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path) { $this->requestStack = $requestStack; $this->urlGenerator = $urlGenerator; $this->path = $path; } public function getFunctions() { return [ new Twig_SimpleFunction('uploads', function ($path) { return $this->path->downloadFromPath() . $path; }), new Twig_SimpleFunction('assets', function ($path) { return '/assets/' . $path; }), new Twig_SimpleFunction('active', function ($route) { return $this->urlGenerator->generate($route) === $this->requestStack->getCurrentRequest()->getRequestUri(); }), ]; } } ## Instruction: Implement web assets in the twig function ## Code After: <?php declare(strict_types=1); /** * Copyright (c) 2013-2017 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Infrastructure\Templating; use OpenCFP\PathInterface; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Twig_Extension; use Twig_SimpleFunction; class TwigExtension extends Twig_Extension { /** * @var RequestStack */ private $requestStack; /** * @var UrlGeneratorInterface */ private $urlGenerator; /** * @var PathInterface */ private $path; public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path) { $this->requestStack = $requestStack; $this->urlGenerator = $urlGenerator; $this->path = $path; } public function getFunctions() { return [ new Twig_SimpleFunction('uploads', function ($path) { return $this->path->downloadFromPath() . $path; }), new Twig_SimpleFunction('assets', function ($path) { return $this->path->webAssetsPath() . $path; }), new Twig_SimpleFunction('active', function ($route) { return $this->urlGenerator->generate($route) === $this->requestStack->getCurrentRequest()->getRequestUri(); }), ]; } }
9ef6195b246a6ee1c9fb6128bf2c31b524004658
address-lookup-field/address-lookup-field.html
address-lookup-field/address-lookup-field.html
<link rel="import" href="../../polymer/polymer.html" /> <dom-module id="address-lookup-field"> <template> <paper-input label="Search for an address" name="alfField" id="alfField" type="text" value="" required> <label>Search for an address</label> </template> <style> :host { } label { z-index: 1; width: 100%; pointer-events: none; } </style> <script> Polymer({ is: "address-lookup-field", properties: { googleMapsKey: { type: String }, autoComplete: { type: Object } }, observers: [ ], ready: function() { this.initAutoComplete(); }, initAutoComplete() { // Create the autocomplete object, restricting the search to geographical location types. var input = this.$.alfField.querySelector('input'); this.autoComplete = new google.maps.places.Autocomplete( input, { types: ['geocode'] } ); this.autoComplete.addListener('place_changed', this.selectAddress.bind(this)); }, selectAddress: function () { var place = this.autoComplete.getPlace(); this.dataHost.addressLookupLocation = place.geometry.location; this.fire('foundplace', place); } }); </script> </dom-module>
<link rel="import" href="../../polymer/polymer.html" /> <dom-module id="address-lookup-field"> <template> <paper-input label="Enter an address" name="alfField" id="alfField" type="text" value="" required> <label>Enter an address</label> </template> <style> :host { } label { z-index: 1; width: 100%; pointer-events: none; } </style> <script> Polymer({ is: "address-lookup-field", properties: { googleMapsKey: { type: String }, autoComplete: { type: Object } }, observers: [ ], ready: function() { this.initAutoComplete(); }, initAutoComplete() { // Create the autocomplete object, restricting the search to geographical location types. var input = this.$.alfField.querySelector('input'); this.autoComplete = new google.maps.places.Autocomplete( input, { types: ['geocode'] } ); this.autoComplete.addListener('place_changed', this.selectAddress.bind(this)); }, selectAddress: function () { var place = this.autoComplete.getPlace(); this.dataHost.addressLookupLocation = place.geometry.location; this.fire('foundplace', place); } }); </script> </dom-module>
Change map lookup address label
Change map lookup address label
HTML
mit
ParcelForMe/p4m-widgets,ParcelForMe/p4m-widgets,ParcelForMe/p4m-widgets
html
## Code Before: <link rel="import" href="../../polymer/polymer.html" /> <dom-module id="address-lookup-field"> <template> <paper-input label="Search for an address" name="alfField" id="alfField" type="text" value="" required> <label>Search for an address</label> </template> <style> :host { } label { z-index: 1; width: 100%; pointer-events: none; } </style> <script> Polymer({ is: "address-lookup-field", properties: { googleMapsKey: { type: String }, autoComplete: { type: Object } }, observers: [ ], ready: function() { this.initAutoComplete(); }, initAutoComplete() { // Create the autocomplete object, restricting the search to geographical location types. var input = this.$.alfField.querySelector('input'); this.autoComplete = new google.maps.places.Autocomplete( input, { types: ['geocode'] } ); this.autoComplete.addListener('place_changed', this.selectAddress.bind(this)); }, selectAddress: function () { var place = this.autoComplete.getPlace(); this.dataHost.addressLookupLocation = place.geometry.location; this.fire('foundplace', place); } }); </script> </dom-module> ## Instruction: Change map lookup address label ## Code After: <link rel="import" href="../../polymer/polymer.html" /> <dom-module id="address-lookup-field"> <template> <paper-input label="Enter an address" name="alfField" id="alfField" type="text" value="" required> <label>Enter an address</label> </template> <style> :host { } label { z-index: 1; width: 100%; pointer-events: none; } </style> <script> Polymer({ is: "address-lookup-field", properties: { googleMapsKey: { type: String }, autoComplete: { type: Object } }, observers: [ ], ready: function() { this.initAutoComplete(); }, initAutoComplete() { // Create the autocomplete object, restricting the search to geographical location types. var input = this.$.alfField.querySelector('input'); this.autoComplete = new google.maps.places.Autocomplete( input, { types: ['geocode'] } ); this.autoComplete.addListener('place_changed', this.selectAddress.bind(this)); }, selectAddress: function () { var place = this.autoComplete.getPlace(); this.dataHost.addressLookupLocation = place.geometry.location; this.fire('foundplace', place); } }); </script> </dom-module>
05e348e716c2acb50265d10029365a3b7f8be94b
src/auth-module/actions.js
src/auth-module/actions.js
export default function makeAuthActions (feathersClient) { return { authenticate (store, data) { const { commit, state, dispatch } = store commit('setAuthenticatePending') if (state.errorOnAuthenticate) { commit('clearAuthenticateError') } return feathersClient.authenticate(data) .then(response => { commit('setAccessToken', response.accessToken) // Decode the token and set the payload, but return the response return feathersClient.passport.verifyJWT(response.accessToken) .then(payload => { commit('setPayload', payload) // Populate the user if the userService was provided if (state.userService && payload.hasOwnProperty('userId')) { return dispatch('populateUser', payload.userId) .then(() => { commit('unsetAuthenticatePending') return response }) } else { commit('unsetAuthenticatePending') } return response }) }) .catch(error => { commit('setAuthenticateError', error) commit('unsetAuthenticatePending') return Promise.reject(error) }) }, populateUser ({ commit, state }, userId) { return feathersClient.service(state.userService) .get(userId) .then(user => { commit('setUser', user) return user }) }, logout ({commit}) { commit('setLogoutPending') return feathersClient.logout() .then(response => { commit('logout') commit('unsetLogoutPending') return response }) .catch(error => { return Promise.reject(error) }) } } }
export default function makeAuthActions (feathersClient) { return { authenticate (store, data) { const { commit, state, dispatch } = store commit('setAuthenticatePending') if (state.errorOnAuthenticate) { commit('clearAuthenticateError') } return feathersClient.authenticate(data) .then(response => { if (response.accessToken) { commit('setAccessToken', response.accessToken) // Decode the token and set the payload, but return the response return feathersClient.passport.verifyJWT(response.accessToken) .then(payload => { commit('setPayload', payload) // Populate the user if the userService was provided if (state.userService && payload.hasOwnProperty('userId')) { return dispatch('populateUser', payload.userId) .then(() => { commit('unsetAuthenticatePending') return response }) } else { commit('unsetAuthenticatePending') } return response }) // If there was not an accessToken in the response, allow the response to pass through to handle two-factor-auth } else { return response } }) .catch(error => { commit('setAuthenticateError', error) commit('unsetAuthenticatePending') return Promise.reject(error) }) }, populateUser ({ commit, state }, userId) { return feathersClient.service(state.userService) .get(userId) .then(user => { commit('setUser', user) return user }) }, logout ({commit}) { commit('setLogoutPending') return feathersClient.logout() .then(response => { commit('logout') commit('unsetLogoutPending') return response }) .catch(error => { return Promise.reject(error) }) } } }
Prepare for two-factor auth scenarios
Prepare for two-factor auth scenarios
JavaScript
mit
feathers-plus/feathers-vuex,feathers-plus/feathers-vuex
javascript
## Code Before: export default function makeAuthActions (feathersClient) { return { authenticate (store, data) { const { commit, state, dispatch } = store commit('setAuthenticatePending') if (state.errorOnAuthenticate) { commit('clearAuthenticateError') } return feathersClient.authenticate(data) .then(response => { commit('setAccessToken', response.accessToken) // Decode the token and set the payload, but return the response return feathersClient.passport.verifyJWT(response.accessToken) .then(payload => { commit('setPayload', payload) // Populate the user if the userService was provided if (state.userService && payload.hasOwnProperty('userId')) { return dispatch('populateUser', payload.userId) .then(() => { commit('unsetAuthenticatePending') return response }) } else { commit('unsetAuthenticatePending') } return response }) }) .catch(error => { commit('setAuthenticateError', error) commit('unsetAuthenticatePending') return Promise.reject(error) }) }, populateUser ({ commit, state }, userId) { return feathersClient.service(state.userService) .get(userId) .then(user => { commit('setUser', user) return user }) }, logout ({commit}) { commit('setLogoutPending') return feathersClient.logout() .then(response => { commit('logout') commit('unsetLogoutPending') return response }) .catch(error => { return Promise.reject(error) }) } } } ## Instruction: Prepare for two-factor auth scenarios ## Code After: export default function makeAuthActions (feathersClient) { return { authenticate (store, data) { const { commit, state, dispatch } = store commit('setAuthenticatePending') if (state.errorOnAuthenticate) { commit('clearAuthenticateError') } return feathersClient.authenticate(data) .then(response => { if (response.accessToken) { commit('setAccessToken', response.accessToken) // Decode the token and set the payload, but return the response return feathersClient.passport.verifyJWT(response.accessToken) .then(payload => { commit('setPayload', payload) // Populate the user if the userService was provided if (state.userService && payload.hasOwnProperty('userId')) { return dispatch('populateUser', payload.userId) .then(() => { commit('unsetAuthenticatePending') return response }) } else { commit('unsetAuthenticatePending') } return response }) // If there was not an accessToken in the response, allow the response to pass through to handle two-factor-auth } else { return response } }) .catch(error => { commit('setAuthenticateError', error) commit('unsetAuthenticatePending') return Promise.reject(error) }) }, populateUser ({ commit, state }, userId) { return feathersClient.service(state.userService) .get(userId) .then(user => { commit('setUser', user) return user }) }, logout ({commit}) { commit('setLogoutPending') return feathersClient.logout() .then(response => { commit('logout') commit('unsetLogoutPending') return response }) .catch(error => { return Promise.reject(error) }) } } }
8f45810947c0229764fd397b349a1db4dc7f3c5f
Psr4Autoloader.php
Psr4Autoloader.php
<?php /** * @file * @version 0.1 * @copyright 2017 CN-Consult GmbH * @author Yannick Lapp <[email protected]> */ /** * Class Psr4Autoloader */ class Psr4Autoloader { private $prefixes = array(); /** * register all prefixes that are saved in the object */ public function register() { spl_autoload_register( function ($_class) { foreach ($this->prefixes as $prefix=>$baseDirectory) { // check whether class uses the namespace prefix $len = strlen($prefix); if (strncmp($prefix, $_class, $len) === 0) { $relativeClass = substr($_class, $len); $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php'; if (file_exists($file)) { require_once $file; } } } } ); } /** * add a namespace to the list * * @param string $_prefix namespace prefix * @param string $_baseDir filepath prefix */ public function addNamespace($_prefix, $_baseDir) { // initialize the namespace prefix array if (isset($this->prefixes[$_prefix]) === false) { $this->prefixes[$_prefix] = array(); } $this->prefixes[$_prefix] = $_baseDir; } }
<?php /** * @file * @version 0.1 * @copyright 2017 CN-Consult GmbH * @author Yannick Lapp <[email protected]> */ /** * Class Psr4Autoloader */ class Psr4Autoloader { private $prefixes = array(); /** * register all prefixes that are saved in the object */ public function register() { spl_autoload_register( function ($_class) { foreach ($this->prefixes as $prefix=>$baseDirectory) { // check whether class uses one of the namespace prefixes $len = strlen($prefix); if (strncmp($prefix, $_class, $len) === 0) { $relativeClass = substr($_class, $len); $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php'; if (file_exists($file)) require_once $file; } } } ); } /** * add a namespace to the list * * @param string $_prefix namespace prefix * @param string $_baseDir filepath prefix */ public function addNamespace($_prefix, $_baseDir) { if (isset($this->prefixes[$_prefix]) === false) { $this->prefixes[$_prefix] = $_baseDir; } } }
Remove unnecessary code from autloader
Remove unnecessary code from autloader Removed unnecessary code.
PHP
mit
ylapp1/GameOfLife
php
## Code Before: <?php /** * @file * @version 0.1 * @copyright 2017 CN-Consult GmbH * @author Yannick Lapp <[email protected]> */ /** * Class Psr4Autoloader */ class Psr4Autoloader { private $prefixes = array(); /** * register all prefixes that are saved in the object */ public function register() { spl_autoload_register( function ($_class) { foreach ($this->prefixes as $prefix=>$baseDirectory) { // check whether class uses the namespace prefix $len = strlen($prefix); if (strncmp($prefix, $_class, $len) === 0) { $relativeClass = substr($_class, $len); $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php'; if (file_exists($file)) { require_once $file; } } } } ); } /** * add a namespace to the list * * @param string $_prefix namespace prefix * @param string $_baseDir filepath prefix */ public function addNamespace($_prefix, $_baseDir) { // initialize the namespace prefix array if (isset($this->prefixes[$_prefix]) === false) { $this->prefixes[$_prefix] = array(); } $this->prefixes[$_prefix] = $_baseDir; } } ## Instruction: Remove unnecessary code from autloader Removed unnecessary code. ## Code After: <?php /** * @file * @version 0.1 * @copyright 2017 CN-Consult GmbH * @author Yannick Lapp <[email protected]> */ /** * Class Psr4Autoloader */ class Psr4Autoloader { private $prefixes = array(); /** * register all prefixes that are saved in the object */ public function register() { spl_autoload_register( function ($_class) { foreach ($this->prefixes as $prefix=>$baseDirectory) { // check whether class uses one of the namespace prefixes $len = strlen($prefix); if (strncmp($prefix, $_class, $len) === 0) { $relativeClass = substr($_class, $len); $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php'; if (file_exists($file)) require_once $file; } } } ); } /** * add a namespace to the list * * @param string $_prefix namespace prefix * @param string $_baseDir filepath prefix */ public function addNamespace($_prefix, $_baseDir) { if (isset($this->prefixes[$_prefix]) === false) { $this->prefixes[$_prefix] = $_baseDir; } } }
3c95e770810132d11a4e418cec4c8eea64bdb8b5
core/src/main/java/io/undertow/server/handlers/HttpTraceHandler.java
core/src/main/java/io/undertow/server/handlers/HttpTraceHandler.java
package io.undertow.server.handlers; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.util.Methods; /** * A handler that handles HTTP trace requests * * @author Stuart Douglas */ public class HttpTraceHandler implements HttpHandler { private final HttpHandler handler; public HttpTraceHandler(final HttpHandler handler) { this.handler = handler; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if(exchange.getRequestMethod().equals(Methods.TRACE)) { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http"); StringBuilder body = new StringBuilder("TRACE "); body.append(exchange.getRequestURI()); if(!exchange.getQueryString().isEmpty()) { body.append('?'); body.append(exchange.getQueryString()); } body.append(exchange.getProtocol().toString()); body.append("\r\n"); for(HeaderValues header : exchange.getRequestHeaders()) { for(String value : header) { body.append(header.getHeaderName()); body.append(": "); body.append(value); body.append("\r\n"); } } body.append("\r\n"); } else { handler.handleRequest(exchange); } } }
package io.undertow.server.handlers; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.util.Methods; /** * A handler that handles HTTP trace requests * * @author Stuart Douglas */ public class HttpTraceHandler implements HttpHandler { private final HttpHandler handler; public HttpTraceHandler(final HttpHandler handler) { this.handler = handler; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if(exchange.getRequestMethod().equals(Methods.TRACE)) { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http"); StringBuilder body = new StringBuilder("TRACE "); body.append(exchange.getRequestURI()); if(!exchange.getQueryString().isEmpty()) { body.append('?'); body.append(exchange.getQueryString()); } body.append(exchange.getProtocol().toString()); body.append("\r\n"); for(HeaderValues header : exchange.getRequestHeaders()) { for(String value : header) { body.append(header.getHeaderName()); body.append(": "); body.append(value); body.append("\r\n"); } } body.append("\r\n"); exchange.getResponseSender().send(body.toString()); } else { handler.handleRequest(exchange); } } }
Fix bug in trace handler
Fix bug in trace handler
Java
apache-2.0
baranowb/undertow,wildfly-security-incubator/undertow,darranl/undertow,Karm/undertow,TomasHofman/undertow,rhusar/undertow,aradchykov/undertow,ctomc/undertow,pedroigor/undertow,amannm/undertow,grassjedi/undertow,n1hility/undertow,jstourac/undertow,nkhuyu/undertow,golovnin/undertow,nkhuyu/undertow,TomasHofman/undertow,ctomc/undertow,jasonchaffee/undertow,biddyweb/undertow,grassjedi/undertow,jstourac/undertow,soul2zimate/undertow,baranowb/undertow,popstr/undertow,soul2zimate/undertow,stuartwdouglas/undertow,ctomc/undertow,jasonchaffee/undertow,marschall/undertow,jamezp/undertow,jstourac/undertow,rhatlapa/undertow,rhatlapa/undertow,yonglehou/undertow,stuartwdouglas/undertow,pferraro/undertow,TomasHofman/undertow,biddyweb/undertow,aradchykov/undertow,undertow-io/undertow,nkhuyu/undertow,Karm/undertow,rhatlapa/undertow,wildfly-security-incubator/undertow,soul2zimate/undertow,aldaris/undertow,popstr/undertow,popstr/undertow,jamezp/undertow,biddyweb/undertow,marschall/undertow,golovnin/undertow,stuartwdouglas/undertow,pferraro/undertow,msfm/undertow,wildfly-security-incubator/undertow,baranowb/undertow,darranl/undertow,n1hility/undertow,golovnin/undertow,rogerchina/undertow,msfm/undertow,rogerchina/undertow,marschall/undertow,aldaris/undertow,pedroigor/undertow,aldaris/undertow,undertow-io/undertow,grassjedi/undertow,yonglehou/undertow,jasonchaffee/undertow,emag/codereading-undertow,n1hility/undertow,rhusar/undertow,undertow-io/undertow,amannm/undertow,rogerchina/undertow,yonglehou/undertow,rhusar/undertow,aradchykov/undertow,pferraro/undertow,msfm/undertow,emag/codereading-undertow,amannm/undertow,Karm/undertow,jamezp/undertow,darranl/undertow,pedroigor/undertow
java
## Code Before: package io.undertow.server.handlers; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.util.Methods; /** * A handler that handles HTTP trace requests * * @author Stuart Douglas */ public class HttpTraceHandler implements HttpHandler { private final HttpHandler handler; public HttpTraceHandler(final HttpHandler handler) { this.handler = handler; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if(exchange.getRequestMethod().equals(Methods.TRACE)) { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http"); StringBuilder body = new StringBuilder("TRACE "); body.append(exchange.getRequestURI()); if(!exchange.getQueryString().isEmpty()) { body.append('?'); body.append(exchange.getQueryString()); } body.append(exchange.getProtocol().toString()); body.append("\r\n"); for(HeaderValues header : exchange.getRequestHeaders()) { for(String value : header) { body.append(header.getHeaderName()); body.append(": "); body.append(value); body.append("\r\n"); } } body.append("\r\n"); } else { handler.handleRequest(exchange); } } } ## Instruction: Fix bug in trace handler ## Code After: package io.undertow.server.handlers; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.util.Methods; /** * A handler that handles HTTP trace requests * * @author Stuart Douglas */ public class HttpTraceHandler implements HttpHandler { private final HttpHandler handler; public HttpTraceHandler(final HttpHandler handler) { this.handler = handler; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if(exchange.getRequestMethod().equals(Methods.TRACE)) { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http"); StringBuilder body = new StringBuilder("TRACE "); body.append(exchange.getRequestURI()); if(!exchange.getQueryString().isEmpty()) { body.append('?'); body.append(exchange.getQueryString()); } body.append(exchange.getProtocol().toString()); body.append("\r\n"); for(HeaderValues header : exchange.getRequestHeaders()) { for(String value : header) { body.append(header.getHeaderName()); body.append(": "); body.append(value); body.append("\r\n"); } } body.append("\r\n"); exchange.getResponseSender().send(body.toString()); } else { handler.handleRequest(exchange); } } }
f636420211821faeb3e26a501fbe5a9a7e3eef5e
normal_admin/user_admin.py
normal_admin/user_admin.py
__author__ = 'weijia' from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate ERROR_MESSAGE = _("Please enter the correct username and password " "for a staff account. Note that both fields are case-sensitive.") class UserAdminAuthenticationForm(AdminAuthenticationForm): """ Same as Django's AdminAuthenticationForm but allows to login any user who is not staff. """ def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: try: self.user_cache = authenticate(username=username, password=password) except: # The following is for userena as it uses different param self.user_cache = authenticate(identification=username, password=password) if self.user_cache is None: raise forms.ValidationError(message) elif not self.user_cache.is_active: raise forms.ValidationError(message) self.check_for_test_cookie() return self.cleaned_data class UserAdmin(AdminSite): # Anything we wish to add or override login_form = UserAdminAuthenticationForm def has_permission(self, request): return request.user.is_active
from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate __author__ = 'weijia' ERROR_MESSAGE = _("Please enter the correct username and password " "for a staff account. Note that both fields are case-sensitive.") class UserAdminAuthenticationForm(AdminAuthenticationForm): """ Same as Django's AdminAuthenticationForm but allows to login any user who is not staff. """ def clean(self): try: return super(UserAdminAuthenticationForm, self).clean() except: username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: try: self.user_cache = authenticate(username=username, password=password) except: # The following is for userena as it uses different param self.user_cache = authenticate(identification=username, password=password) if self.user_cache is None: raise forms.ValidationError(message) elif not self.user_cache.is_active: raise forms.ValidationError(message) self.check_for_test_cookie() return self.cleaned_data # For Django 1.8 def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name} ) class UserAdmin(AdminSite): # Anything we wish to add or override login_form = UserAdminAuthenticationForm def has_permission(self, request): return request.user.is_active
Fix login error in Django 1.8.
Fix login error in Django 1.8.
Python
bsd-3-clause
weijia/normal_admin,weijia/normal_admin
python
## Code Before: __author__ = 'weijia' from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate ERROR_MESSAGE = _("Please enter the correct username and password " "for a staff account. Note that both fields are case-sensitive.") class UserAdminAuthenticationForm(AdminAuthenticationForm): """ Same as Django's AdminAuthenticationForm but allows to login any user who is not staff. """ def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: try: self.user_cache = authenticate(username=username, password=password) except: # The following is for userena as it uses different param self.user_cache = authenticate(identification=username, password=password) if self.user_cache is None: raise forms.ValidationError(message) elif not self.user_cache.is_active: raise forms.ValidationError(message) self.check_for_test_cookie() return self.cleaned_data class UserAdmin(AdminSite): # Anything we wish to add or override login_form = UserAdminAuthenticationForm def has_permission(self, request): return request.user.is_active ## Instruction: Fix login error in Django 1.8. ## Code After: from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate __author__ = 'weijia' ERROR_MESSAGE = _("Please enter the correct username and password " "for a staff account. Note that both fields are case-sensitive.") class UserAdminAuthenticationForm(AdminAuthenticationForm): """ Same as Django's AdminAuthenticationForm but allows to login any user who is not staff. """ def clean(self): try: return super(UserAdminAuthenticationForm, self).clean() except: username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: try: self.user_cache = authenticate(username=username, password=password) except: # The following is for userena as it uses different param self.user_cache = authenticate(identification=username, password=password) if self.user_cache is None: raise forms.ValidationError(message) elif not self.user_cache.is_active: raise forms.ValidationError(message) self.check_for_test_cookie() return self.cleaned_data # For Django 1.8 def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name} ) class UserAdmin(AdminSite): # Anything we wish to add or override login_form = UserAdminAuthenticationForm def has_permission(self, request): return request.user.is_active
e28a8281bf0ef2c55acdababed95af3867b74c01
johannes-code-generator/src/main/java/ch/johannes/FileUtil.java
johannes-code-generator/src/main/java/ch/johannes/FileUtil.java
package ch.johannes; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class FileUtil { public static String readFileInPackage(Object instanceOfPackage, String filename) { try { Package aPackage = instanceOfPackage.getClass().getPackage(); String packageName = aPackage.getName(); String resourceName = "/".concat(packageName.replace('.', '/')).concat("/").concat(filename); InputStream resourceAsStream = instanceOfPackage.getClass().getResourceAsStream(resourceName); if (resourceAsStream == null) { throw new IllegalArgumentException(String.format("Couldn't find resource '%s' in package '%s' (%s).", filename, packageName, resourceName)); } return readInputStream(resourceAsStream); } catch (IOException e) { throw new IllegalArgumentException("Couldn't find or read resource " + filename, e); } } private static String readInputStream(InputStream inputStream) throws IOException { BufferedInputStream bis = new BufferedInputStream(inputStream); ByteArrayOutputStream buf = new ByteArrayOutputStream(); try { int result = bis.read(); while (result != -1) { buf.write((byte) result); result = bis.read(); } return buf.toString(); } finally { bis.close(); buf.close(); } } }
package ch.johannes; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class FileUtil { public static String readFileInPackage(Object instanceOfPackage, String filename) { Package aPackage = instanceOfPackage.getClass().getPackage(); String packageName = aPackage.getName(); String resourceName = "/".concat(packageName.replace('.', '/')).concat("/").concat(filename); try(InputStream resourceAsStream = instanceOfPackage.getClass().getResourceAsStream(resourceName)) { if (resourceAsStream == null) { throw new IllegalArgumentException(String.format("Couldn't find resource '%s' in package '%s' (%s).", filename, packageName, resourceName)); } return readInputStream(resourceAsStream); } catch (IOException e) { throw new IllegalArgumentException("Couldn't find or read resource " + filename, e); } } private static String readInputStream(InputStream inputStream) throws IOException { try (BufferedInputStream bis = new BufferedInputStream(inputStream); ByteArrayOutputStream buf = new ByteArrayOutputStream()) { int result = bis.read(); while (result != -1) { buf.write((byte) result); result = bis.read(); } return buf.toString(); } } }
Use new style try finally to close resources
Use new style try finally to close resources
Java
mit
tschoenti/johannes
java
## Code Before: package ch.johannes; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class FileUtil { public static String readFileInPackage(Object instanceOfPackage, String filename) { try { Package aPackage = instanceOfPackage.getClass().getPackage(); String packageName = aPackage.getName(); String resourceName = "/".concat(packageName.replace('.', '/')).concat("/").concat(filename); InputStream resourceAsStream = instanceOfPackage.getClass().getResourceAsStream(resourceName); if (resourceAsStream == null) { throw new IllegalArgumentException(String.format("Couldn't find resource '%s' in package '%s' (%s).", filename, packageName, resourceName)); } return readInputStream(resourceAsStream); } catch (IOException e) { throw new IllegalArgumentException("Couldn't find or read resource " + filename, e); } } private static String readInputStream(InputStream inputStream) throws IOException { BufferedInputStream bis = new BufferedInputStream(inputStream); ByteArrayOutputStream buf = new ByteArrayOutputStream(); try { int result = bis.read(); while (result != -1) { buf.write((byte) result); result = bis.read(); } return buf.toString(); } finally { bis.close(); buf.close(); } } } ## Instruction: Use new style try finally to close resources ## Code After: package ch.johannes; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class FileUtil { public static String readFileInPackage(Object instanceOfPackage, String filename) { Package aPackage = instanceOfPackage.getClass().getPackage(); String packageName = aPackage.getName(); String resourceName = "/".concat(packageName.replace('.', '/')).concat("/").concat(filename); try(InputStream resourceAsStream = instanceOfPackage.getClass().getResourceAsStream(resourceName)) { if (resourceAsStream == null) { throw new IllegalArgumentException(String.format("Couldn't find resource '%s' in package '%s' (%s).", filename, packageName, resourceName)); } return readInputStream(resourceAsStream); } catch (IOException e) { throw new IllegalArgumentException("Couldn't find or read resource " + filename, e); } } private static String readInputStream(InputStream inputStream) throws IOException { try (BufferedInputStream bis = new BufferedInputStream(inputStream); ByteArrayOutputStream buf = new ByteArrayOutputStream()) { int result = bis.read(); while (result != -1) { buf.write((byte) result); result = bis.read(); } return buf.toString(); } } }
67303672d04d7eece4736a9bc672e006cbc87976
app/Http/Controllers/SearchController.php
app/Http/Controllers/SearchController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Classes\EsiConnection; use Illuminate\Support\Facades\Log; class SearchController extends Controller { public function search(Request $request) { $esi = new EsiConnection; $result = $esi->esi->setQueryString([ 'categories' => 'character', 'search' => $request->q, 'strict' => 'true', ])->invoke('get', '/search/'); Log::info('SearchController: results returned by /search query', [ 'result' => $result, ]); // If there are more than ten matching results, we want them to keep typing. if (isset($result) && isset($result->character)) { $character_id = $result->character[0]; $character = $esi->esi->invoke('get', '/characters/{character_id}/', [ 'character_id' => $character_id, ]); $character->id = $character_id; $portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [ 'character_id' => $character_id, ]); $character->portrait = $portrait->px128x128; $corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [ 'corporation_id' => $character->corporation_id, ]); $character->corporation = $corporation->corporation_name; return $character; } else { return 'No matches returned, API may be unreachable...'; } } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Classes\EsiConnection; use Illuminate\Support\Facades\Log; class SearchController extends Controller { public function search(Request $request) { $esi = new EsiConnection; $result = $esi->esi->setQueryString([ 'categories' => 'character', 'search' => $request->q, 'strict' => 'true', ])->invoke('get', '/search/'); Log::info('SearchController: results returned by /search query', [ 'result' => $result, ]); // If there are more than ten matching results, we want them to keep typing. if (isset($result) && isset($result->character)) { $character_id = $result->character[0]; $character = $esi->esi->invoke('get', '/characters/{character_id}/', [ 'character_id' => $character_id, ]); $character->id = $character_id; $portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [ 'character_id' => $character_id, ]); $character->portrait = $portrait->px128x128; $corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [ 'corporation_id' => $character->corporation_id, ]); $character->corporation = $corporation->name; return $character; } else { return 'No matches returned, API may be unreachable...'; } } }
Update property of corporation name returned in search.
Update property of corporation name returned in search.
PHP
mit
matthewpennell/moon-mining-manager,matthewpennell/moon-mining-manager
php
## Code Before: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Classes\EsiConnection; use Illuminate\Support\Facades\Log; class SearchController extends Controller { public function search(Request $request) { $esi = new EsiConnection; $result = $esi->esi->setQueryString([ 'categories' => 'character', 'search' => $request->q, 'strict' => 'true', ])->invoke('get', '/search/'); Log::info('SearchController: results returned by /search query', [ 'result' => $result, ]); // If there are more than ten matching results, we want them to keep typing. if (isset($result) && isset($result->character)) { $character_id = $result->character[0]; $character = $esi->esi->invoke('get', '/characters/{character_id}/', [ 'character_id' => $character_id, ]); $character->id = $character_id; $portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [ 'character_id' => $character_id, ]); $character->portrait = $portrait->px128x128; $corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [ 'corporation_id' => $character->corporation_id, ]); $character->corporation = $corporation->corporation_name; return $character; } else { return 'No matches returned, API may be unreachable...'; } } } ## Instruction: Update property of corporation name returned in search. ## Code After: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Classes\EsiConnection; use Illuminate\Support\Facades\Log; class SearchController extends Controller { public function search(Request $request) { $esi = new EsiConnection; $result = $esi->esi->setQueryString([ 'categories' => 'character', 'search' => $request->q, 'strict' => 'true', ])->invoke('get', '/search/'); Log::info('SearchController: results returned by /search query', [ 'result' => $result, ]); // If there are more than ten matching results, we want them to keep typing. if (isset($result) && isset($result->character)) { $character_id = $result->character[0]; $character = $esi->esi->invoke('get', '/characters/{character_id}/', [ 'character_id' => $character_id, ]); $character->id = $character_id; $portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [ 'character_id' => $character_id, ]); $character->portrait = $portrait->px128x128; $corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [ 'corporation_id' => $character->corporation_id, ]); $character->corporation = $corporation->name; return $character; } else { return 'No matches returned, API may be unreachable...'; } } }
047483d9897e75f8284c39e8477a285763da7b37
heufybot/modules/util/commandhandler.py
heufybot/modules/util/commandhandler.py
from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = "CommandHandler" def actions(self): return [ ("message-channel", 1, self.handleChannelMessage), ("message-user", 1, self.handlePrivateMessage) ] def handleChannelMessage(self, server, channel, user, messageBody): message = { "server": server, "source": channel.name, "channel": channel, "user": user, "body": messageBody } self._handleCommand(message) def handlePrivateMessage(self, server, user, messageBody): message = { "server": server, "source": user.nick, "user": user, "body": messageBody } self._handleCommand(message) def _handleCommand(self, message): commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!") if not message["body"].startswith(commandPrefix): return # We don't need to be handling things that aren't bot commands params = message["body"].split() message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):] del params[0] message["params"] = params self.bot.moduleHandler.runProcessingAction("botmessage", message) commandHandler = CommandHandler()
from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = "CommandHandler" def actions(self): return [ ("message-channel", 1, self.handleChannelMessage), ("message-user", 1, self.handlePrivateMessage) ] def handleChannelMessage(self, server, channel, user, messageBody): message = { "server": server, "source": channel.name, "channel": channel, "user": user, "body": messageBody } self._handleCommand(message) def handlePrivateMessage(self, server, user, messageBody): message = { "server": server, "source": user.nick, "user": user, "body": messageBody } self._handleCommand(message) def _handleCommand(self, message): commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!") botNick = self.bot.servers[message["server"]].nick.lower() params = message["body"].split() if message["body"].startswith(commandPrefix): message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):] del params[0] elif message["body"].lower().startswith(botNick): message["command"] = params[1] del params[0:2] else: return # We don't need to be handling things that aren't bot commands message["params"] = params self.bot.moduleHandler.runProcessingAction("botmessage", message) commandHandler = CommandHandler()
Make the bot respond to its name
Make the bot respond to its name Implements GH-7
Python
mit
Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot
python
## Code Before: from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = "CommandHandler" def actions(self): return [ ("message-channel", 1, self.handleChannelMessage), ("message-user", 1, self.handlePrivateMessage) ] def handleChannelMessage(self, server, channel, user, messageBody): message = { "server": server, "source": channel.name, "channel": channel, "user": user, "body": messageBody } self._handleCommand(message) def handlePrivateMessage(self, server, user, messageBody): message = { "server": server, "source": user.nick, "user": user, "body": messageBody } self._handleCommand(message) def _handleCommand(self, message): commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!") if not message["body"].startswith(commandPrefix): return # We don't need to be handling things that aren't bot commands params = message["body"].split() message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):] del params[0] message["params"] = params self.bot.moduleHandler.runProcessingAction("botmessage", message) commandHandler = CommandHandler() ## Instruction: Make the bot respond to its name Implements GH-7 ## Code After: from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = "CommandHandler" def actions(self): return [ ("message-channel", 1, self.handleChannelMessage), ("message-user", 1, self.handlePrivateMessage) ] def handleChannelMessage(self, server, channel, user, messageBody): message = { "server": server, "source": channel.name, "channel": channel, "user": user, "body": messageBody } self._handleCommand(message) def handlePrivateMessage(self, server, user, messageBody): message = { "server": server, "source": user.nick, "user": user, "body": messageBody } self._handleCommand(message) def _handleCommand(self, message): commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!") botNick = self.bot.servers[message["server"]].nick.lower() params = message["body"].split() if message["body"].startswith(commandPrefix): message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):] del params[0] elif message["body"].lower().startswith(botNick): message["command"] = params[1] del params[0:2] else: return # We don't need to be handling things that aren't bot commands message["params"] = params self.bot.moduleHandler.runProcessingAction("botmessage", message) commandHandler = CommandHandler()
a00a62f147489141cfb7d3fb2d10e08e8f161e01
demo/js/components/workbench-new.js
demo/js/components/workbench-new.js
angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = ""; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = "The YDS component is not properly configured." + "Please check the corresponding documentation section"; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == "") scope.lang = "en"; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ "css/highcharts-editor.min.css", "lib/highcharts-editor.js" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0]); }); }); } } } ]);
angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = ""; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = "The YDS component is not properly configured." + "Please check the corresponding documentation section"; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == "") scope.lang = "en"; var editorOptions = { features: "import templates customize export" }; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ "css/highcharts-editor.min.css", "lib/highcharts-editor.js" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0], editorOptions); }); }); } } } ]);
Disable steps that are not needed in Highcharts Editor
Disable steps that are not needed in Highcharts Editor
JavaScript
apache-2.0
YourDataStories/components-visualisation,YourDataStories/components-visualisation,YourDataStories/components-visualisation
javascript
## Code Before: angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = ""; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = "The YDS component is not properly configured." + "Please check the corresponding documentation section"; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == "") scope.lang = "en"; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ "css/highcharts-editor.min.css", "lib/highcharts-editor.js" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0]); }); }); } } } ]); ## Instruction: Disable steps that are not needed in Highcharts Editor ## Code After: angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = ""; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = "The YDS component is not properly configured." + "Please check the corresponding documentation section"; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == "") scope.lang = "en"; var editorOptions = { features: "import templates customize export" }; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ "css/highcharts-editor.min.css", "lib/highcharts-editor.js" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0], editorOptions); }); }); } } } ]);
8e6c6d0291cdeae0a79b007a802f72f17a89134b
Wangscape/noise/module/codecs/CurveWrapperCodec.cpp
Wangscape/noise/module/codecs/CurveWrapperCodec.cpp
namespace spotify { namespace json { using CurveWrapper = noise::module::Wrapper<noise::module::Curve>; codec::object_t<CurveWrapper> default_codec_t<CurveWrapper>::codec() { auto codec = codec::object<CurveWrapper>(); codec.required("type", codec::eq<std::string>("Curve")); codec.required("SourceModule", codec::ignore_t<int>()); codec.optional("ControlPoints", [](const CurveWrapper& mw) { std::vector<std::pair<double, double>> all_control_points; const noise::module::ControlPoint* raw_control_points = mw.module->GetControlPointArray(); const int control_point_count = mw.module->GetControlPointCount(); for (int i = 0; i < control_point_count; i++) { const noise::module::ControlPoint control_point = raw_control_points[i]; all_control_points.push_back({control_point.inputValue, control_point.outputValue}); } return all_control_points; }, [](CurveWrapper& mw, std::vector<std::pair<double, double>> all_control_points) { for (std::pair<double, double> control_point : all_control_points) { mw.module->AddControlPoint(control_point.first, control_point.second); } }, default_codec<std::vector<std::pair<double, double>>>()); return codec; } } }
namespace spotify { namespace json { using CurveWrapper = noise::module::Wrapper<noise::module::Curve>; codec::object_t<CurveWrapper> default_codec_t<CurveWrapper>::codec() { auto codec = codec::object<CurveWrapper>(); codec.required("type", codec::eq<std::string>("Curve")); codec.required("SourceModule", codec::ignore_t<int>()); codec.optional("ControlPoints", [](const CurveWrapper& mw) { std::vector<std::pair<double, double>> all_control_points; const noise::module::ControlPoint* raw_control_points = mw.module->GetControlPointArray(); const int control_point_count = mw.module->GetControlPointCount(); std::transform(raw_control_points, raw_control_points + control_point_count, std::inserter(all_control_points, all_control_points.begin()), [](noise::module::ControlPoint control_point) { return std::make_pair(control_point.inputValue, control_point.outputValue); }); return all_control_points; }, [](CurveWrapper& mw, std::vector<std::pair<double, double>> all_control_points) { for (std::pair<double, double> control_point : all_control_points) { mw.module->AddControlPoint(control_point.first, control_point.second); } }, default_codec<std::vector<std::pair<double, double>>>()); return codec; } } }
Use std::transform in Curve codec
Use std::transform in Curve codec
C++
mit
Wangscape/Wangscape,Wangscape/Wangscape,Wangscape/Wangscape,serin-delaunay/Wangscape,serin-delaunay/Wangscape
c++
## Code Before: namespace spotify { namespace json { using CurveWrapper = noise::module::Wrapper<noise::module::Curve>; codec::object_t<CurveWrapper> default_codec_t<CurveWrapper>::codec() { auto codec = codec::object<CurveWrapper>(); codec.required("type", codec::eq<std::string>("Curve")); codec.required("SourceModule", codec::ignore_t<int>()); codec.optional("ControlPoints", [](const CurveWrapper& mw) { std::vector<std::pair<double, double>> all_control_points; const noise::module::ControlPoint* raw_control_points = mw.module->GetControlPointArray(); const int control_point_count = mw.module->GetControlPointCount(); for (int i = 0; i < control_point_count; i++) { const noise::module::ControlPoint control_point = raw_control_points[i]; all_control_points.push_back({control_point.inputValue, control_point.outputValue}); } return all_control_points; }, [](CurveWrapper& mw, std::vector<std::pair<double, double>> all_control_points) { for (std::pair<double, double> control_point : all_control_points) { mw.module->AddControlPoint(control_point.first, control_point.second); } }, default_codec<std::vector<std::pair<double, double>>>()); return codec; } } } ## Instruction: Use std::transform in Curve codec ## Code After: namespace spotify { namespace json { using CurveWrapper = noise::module::Wrapper<noise::module::Curve>; codec::object_t<CurveWrapper> default_codec_t<CurveWrapper>::codec() { auto codec = codec::object<CurveWrapper>(); codec.required("type", codec::eq<std::string>("Curve")); codec.required("SourceModule", codec::ignore_t<int>()); codec.optional("ControlPoints", [](const CurveWrapper& mw) { std::vector<std::pair<double, double>> all_control_points; const noise::module::ControlPoint* raw_control_points = mw.module->GetControlPointArray(); const int control_point_count = mw.module->GetControlPointCount(); std::transform(raw_control_points, raw_control_points + control_point_count, std::inserter(all_control_points, all_control_points.begin()), [](noise::module::ControlPoint control_point) { return std::make_pair(control_point.inputValue, control_point.outputValue); }); return all_control_points; }, [](CurveWrapper& mw, std::vector<std::pair<double, double>> all_control_points) { for (std::pair<double, double> control_point : all_control_points) { mw.module->AddControlPoint(control_point.first, control_point.second); } }, default_codec<std::vector<std::pair<double, double>>>()); return codec; } } }
538eba46a493c254d44b364a051146dd387a990a
src/material-ui/MuiNumber.js
src/material-ui/MuiNumber.js
/** * Created by steve on 15/09/15. */ import React from 'react'; var utils = require('../utils'); var classNames = require('classnames'); import ValidationMixin from '../ValidationMixin'; class MuiNumber extends React.Component { render() { let formClasses = classNames('form-group', { 'has-error' : this.props.valid === false }, this.props.form.htmlClass, { 'has-success' : this.props.valid === true && this.props.value != null}); let labelClasses = classNames('control-label', this.props.form.labelHtmlClass); let fieldClasses = classNames('form-control', this.props.form.fieldHtmlClass); let help = this.props.form.description || ''; if(!this.props.valid || this.props.form.description) { help = ( <div className="help-block"> {this.props.error || this.props.form.description} </div> ) } return ( <div className={formClasses}> <label className={labelClasses}>{this.props.form.title}</label> <input type={this.props.form.type} onChange={this.props.onChangeValidate} step={this.props.form.step} className={fieldClasses} defaultValue={this.props.value} id={this.props.form.key.slice(-1)[0]} name={this.props.form.key.slice(-1)[0]}/> {help} </div> ); } } export default ValidationMixin(MuiNumber);
/** * Created by steve on 15/09/15. */ import React from 'react'; var utils = require('../utils'); var classNames = require('classnames'); import ValidationMixin from '../ValidationMixin'; const TextField = require('material-ui/lib/text-field'); /** * There is no default number picker as part of Material-UI. * Instead, use a TextField and validate. */ class MuiNumber extends React.Component { constructor(props) { super(props); this.preValidationCheck = this.preValidationCheck.bind(this); this.state = { lastSuccessfulValue : this.props.value } } isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } /** * Prevent the field from accepting non-numeric characters. * @param e */ preValidationCheck(e) { if (this.isNumeric(e.target.value)) { this.setState({ lastSuccessfulValue: e.target.value }); this.props.onChangeValidate(e); } else { this.refs.numberField.setValue(this.state.lastSuccessfulValue); } } render() { return ( <TextField type={this.props.form.type} floatingLabelText={this.props.form.title} hintText={this.props.form.placeholder} errorText={this.props.error} onChange={this.preValidationCheck} defaultValue={this.state.lastSuccessfulValue} ref="numberField"/> ); } } export default ValidationMixin(MuiNumber);
Add number input to mui
Add number input to mui
JavaScript
mit
Codafication/react-schema-form,networknt/react-schema-form,Codafication/react-schema-form,networknt/react-schema-form
javascript
## Code Before: /** * Created by steve on 15/09/15. */ import React from 'react'; var utils = require('../utils'); var classNames = require('classnames'); import ValidationMixin from '../ValidationMixin'; class MuiNumber extends React.Component { render() { let formClasses = classNames('form-group', { 'has-error' : this.props.valid === false }, this.props.form.htmlClass, { 'has-success' : this.props.valid === true && this.props.value != null}); let labelClasses = classNames('control-label', this.props.form.labelHtmlClass); let fieldClasses = classNames('form-control', this.props.form.fieldHtmlClass); let help = this.props.form.description || ''; if(!this.props.valid || this.props.form.description) { help = ( <div className="help-block"> {this.props.error || this.props.form.description} </div> ) } return ( <div className={formClasses}> <label className={labelClasses}>{this.props.form.title}</label> <input type={this.props.form.type} onChange={this.props.onChangeValidate} step={this.props.form.step} className={fieldClasses} defaultValue={this.props.value} id={this.props.form.key.slice(-1)[0]} name={this.props.form.key.slice(-1)[0]}/> {help} </div> ); } } export default ValidationMixin(MuiNumber); ## Instruction: Add number input to mui ## Code After: /** * Created by steve on 15/09/15. */ import React from 'react'; var utils = require('../utils'); var classNames = require('classnames'); import ValidationMixin from '../ValidationMixin'; const TextField = require('material-ui/lib/text-field'); /** * There is no default number picker as part of Material-UI. * Instead, use a TextField and validate. */ class MuiNumber extends React.Component { constructor(props) { super(props); this.preValidationCheck = this.preValidationCheck.bind(this); this.state = { lastSuccessfulValue : this.props.value } } isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } /** * Prevent the field from accepting non-numeric characters. * @param e */ preValidationCheck(e) { if (this.isNumeric(e.target.value)) { this.setState({ lastSuccessfulValue: e.target.value }); this.props.onChangeValidate(e); } else { this.refs.numberField.setValue(this.state.lastSuccessfulValue); } } render() { return ( <TextField type={this.props.form.type} floatingLabelText={this.props.form.title} hintText={this.props.form.placeholder} errorText={this.props.error} onChange={this.preValidationCheck} defaultValue={this.state.lastSuccessfulValue} ref="numberField"/> ); } } export default ValidationMixin(MuiNumber);
c9c9204381e65cecb8118e04ba45e69c20d5c3db
api-gateway-service/src/main/java/name/webdizz/fault/tolerance/gateway/endpoint/ProductDetailsEndpoint.java
api-gateway-service/src/main/java/name/webdizz/fault/tolerance/gateway/endpoint/ProductDetailsEndpoint.java
package name.webdizz.fault.tolerance.gateway.endpoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.AllArgsConstructor; import lombok.Data; import name.webdizz.fault.tolerance.inventory.client.InventoryRequester; import name.webdizz.fault.tolerance.inventory.client.command.TimeOutInventoryRequestCommand; import name.webdizz.fault.tolerance.inventory.domain.Inventory; import name.webdizz.fault.tolerance.inventory.domain.Product; import name.webdizz.fault.tolerance.inventory.domain.Store; @RestController @RequestMapping("/api/products") public class ProductDetailsEndpoint { private final InventoryRequester inventoryRequester; @Autowired public ProductDetailsEndpoint(final InventoryRequester inventoryRequester) { this.inventoryRequester = inventoryRequester; } @RequestMapping("/{store}/{product}") public ProductDetails inventory(@PathVariable("store") String storeId, @PathVariable("product") String productId) { Store store = new Store(storeId); Product product = new Product(productId); Inventory inventory = new TimeOutInventoryRequestCommand(inventoryRequester, store, product, 1000).execute(); return new ProductDetails(inventory); } @Data @AllArgsConstructor class ProductDetails { private Inventory inventory; } }
package name.webdizz.fault.tolerance.gateway.endpoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.AllArgsConstructor; import lombok.Data; import name.webdizz.fault.tolerance.inventory.client.InventoryRequester; import name.webdizz.fault.tolerance.inventory.client.command.CircuitBreakerInventoryRequestCommand; import name.webdizz.fault.tolerance.inventory.domain.Inventory; import name.webdizz.fault.tolerance.inventory.domain.Product; import name.webdizz.fault.tolerance.inventory.domain.Store; @RestController @RequestMapping("/api/products") public class ProductDetailsEndpoint { private final InventoryRequester inventoryRequester; @Autowired public ProductDetailsEndpoint(final InventoryRequester inventoryRequester) { this.inventoryRequester = inventoryRequester; } @RequestMapping("/{store}/{product}") public ProductDetails inventory(@PathVariable("store") String storeId, @PathVariable("product") String productId) { Store store = new Store(storeId); Product product = new Product(productId); Inventory inventory = new CircuitBreakerInventoryRequestCommand(inventoryRequester, store, product, false).execute(); return new ProductDetails(inventory); } @Data @AllArgsConstructor class ProductDetails { private Inventory inventory; } }
Switch to another command to call inventory service
Switch to another command to call inventory service
Java
apache-2.0
webdizz/fault-tolerance-talk
java
## Code Before: package name.webdizz.fault.tolerance.gateway.endpoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.AllArgsConstructor; import lombok.Data; import name.webdizz.fault.tolerance.inventory.client.InventoryRequester; import name.webdizz.fault.tolerance.inventory.client.command.TimeOutInventoryRequestCommand; import name.webdizz.fault.tolerance.inventory.domain.Inventory; import name.webdizz.fault.tolerance.inventory.domain.Product; import name.webdizz.fault.tolerance.inventory.domain.Store; @RestController @RequestMapping("/api/products") public class ProductDetailsEndpoint { private final InventoryRequester inventoryRequester; @Autowired public ProductDetailsEndpoint(final InventoryRequester inventoryRequester) { this.inventoryRequester = inventoryRequester; } @RequestMapping("/{store}/{product}") public ProductDetails inventory(@PathVariable("store") String storeId, @PathVariable("product") String productId) { Store store = new Store(storeId); Product product = new Product(productId); Inventory inventory = new TimeOutInventoryRequestCommand(inventoryRequester, store, product, 1000).execute(); return new ProductDetails(inventory); } @Data @AllArgsConstructor class ProductDetails { private Inventory inventory; } } ## Instruction: Switch to another command to call inventory service ## Code After: package name.webdizz.fault.tolerance.gateway.endpoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.AllArgsConstructor; import lombok.Data; import name.webdizz.fault.tolerance.inventory.client.InventoryRequester; import name.webdizz.fault.tolerance.inventory.client.command.CircuitBreakerInventoryRequestCommand; import name.webdizz.fault.tolerance.inventory.domain.Inventory; import name.webdizz.fault.tolerance.inventory.domain.Product; import name.webdizz.fault.tolerance.inventory.domain.Store; @RestController @RequestMapping("/api/products") public class ProductDetailsEndpoint { private final InventoryRequester inventoryRequester; @Autowired public ProductDetailsEndpoint(final InventoryRequester inventoryRequester) { this.inventoryRequester = inventoryRequester; } @RequestMapping("/{store}/{product}") public ProductDetails inventory(@PathVariable("store") String storeId, @PathVariable("product") String productId) { Store store = new Store(storeId); Product product = new Product(productId); Inventory inventory = new CircuitBreakerInventoryRequestCommand(inventoryRequester, store, product, false).execute(); return new ProductDetails(inventory); } @Data @AllArgsConstructor class ProductDetails { private Inventory inventory; } }
cb7d2d611397499548c1ecbaa9aa2202355cba08
src/index.js
src/index.js
import generateReducer from './generate-reducer'; import generateActionTypes from './generate-action-types'; import generateActionCreators from './generate-action-creators'; import {generateDefaultInitialState, xhrStatuses} from './utils'; const allowAllCrudOperations = { create: true, readOne: true, readMany: true, update: true, del: true }; // resourceName: a string representing the name of the resource. For instance, // "books". This will be the name of the store slice in Redux. // options: a list of options to configure the resource. Refer to the docs // for the complete list of options function simpleResource(resourceName, options = {}) { const {initialState, idAttribute, customHandlers, pluralForm, allowedOperations} = options; const initial = Object.assign({}, generateDefaultInitialState(), initialState); const idAttr = idAttribute || 'id'; const handlers = customHandlers || {}; const pluralName = pluralForm ? pluralForm : `${resourceName}s`; const allowedCrudOperations = { ...allowAllCrudOperations, ...allowedOperations }; const types = generateActionTypes(resourceName, pluralName, allowedCrudOperations); const actionCreators = generateActionCreators(allowedCrudOperations); return { actionCreators, actionTypes: types, initialState: initial, reducer: generateReducer({ pluralForm: pluralName, allowedOperations: allowedCrudOperations, idAttr, initialState, handlers, types, resourceName }), pluralForm: pluralName }; } export {xhrStatuses}; export default simpleResource;
import generateReducer from './generate-reducer'; import generateActionTypes from './generate-action-types'; import generateActionCreators from './generate-action-creators'; import {generateDefaultInitialState, xhrStatuses} from './utils'; const allowAllCrudOperations = { create: true, readOne: true, readMany: true, update: true, del: true }; // resourceName: a string representing the name of the resource. For instance, // "books". This will be the name of the store slice in Redux. // options: a list of options to configure the resource. Refer to the docs // for the complete list of options function simpleResource(resourceName, options = {}) { const {initialState, idAttribute, customHandlers, pluralForm, allowedOperations} = options; const initial = Object.assign({}, generateDefaultInitialState(), initialState); const idAttr = idAttribute || 'id'; const handlers = customHandlers || {}; const pluralName = pluralForm ? pluralForm : `${resourceName}s`; const allowedCrudOperations = { ...allowAllCrudOperations, ...allowedOperations }; const types = generateActionTypes(resourceName, pluralName, allowedCrudOperations); const actionCreators = generateActionCreators(allowedCrudOperations); return { actionCreators, actionTypes: types, initialState: initial, reducer: generateReducer({ pluralForm: pluralName, allowedOperations: allowedCrudOperations, initialState: initial, idAttr, handlers, types, resourceName }), pluralForm: pluralName }; } export {xhrStatuses}; export default simpleResource;
Fix an issue where initial state was not computed correctly
Fix an issue where initial state was not computed correctly
JavaScript
mit
jmeas/redux-simple-resource,jmeas/redux-simple-resource,JPorry/redux-simple-resource,jmeas/resourceful-redux,JPorry/redux-simple-resource,jmeas/resourceful-redux
javascript
## Code Before: import generateReducer from './generate-reducer'; import generateActionTypes from './generate-action-types'; import generateActionCreators from './generate-action-creators'; import {generateDefaultInitialState, xhrStatuses} from './utils'; const allowAllCrudOperations = { create: true, readOne: true, readMany: true, update: true, del: true }; // resourceName: a string representing the name of the resource. For instance, // "books". This will be the name of the store slice in Redux. // options: a list of options to configure the resource. Refer to the docs // for the complete list of options function simpleResource(resourceName, options = {}) { const {initialState, idAttribute, customHandlers, pluralForm, allowedOperations} = options; const initial = Object.assign({}, generateDefaultInitialState(), initialState); const idAttr = idAttribute || 'id'; const handlers = customHandlers || {}; const pluralName = pluralForm ? pluralForm : `${resourceName}s`; const allowedCrudOperations = { ...allowAllCrudOperations, ...allowedOperations }; const types = generateActionTypes(resourceName, pluralName, allowedCrudOperations); const actionCreators = generateActionCreators(allowedCrudOperations); return { actionCreators, actionTypes: types, initialState: initial, reducer: generateReducer({ pluralForm: pluralName, allowedOperations: allowedCrudOperations, idAttr, initialState, handlers, types, resourceName }), pluralForm: pluralName }; } export {xhrStatuses}; export default simpleResource; ## Instruction: Fix an issue where initial state was not computed correctly ## Code After: import generateReducer from './generate-reducer'; import generateActionTypes from './generate-action-types'; import generateActionCreators from './generate-action-creators'; import {generateDefaultInitialState, xhrStatuses} from './utils'; const allowAllCrudOperations = { create: true, readOne: true, readMany: true, update: true, del: true }; // resourceName: a string representing the name of the resource. For instance, // "books". This will be the name of the store slice in Redux. // options: a list of options to configure the resource. Refer to the docs // for the complete list of options function simpleResource(resourceName, options = {}) { const {initialState, idAttribute, customHandlers, pluralForm, allowedOperations} = options; const initial = Object.assign({}, generateDefaultInitialState(), initialState); const idAttr = idAttribute || 'id'; const handlers = customHandlers || {}; const pluralName = pluralForm ? pluralForm : `${resourceName}s`; const allowedCrudOperations = { ...allowAllCrudOperations, ...allowedOperations }; const types = generateActionTypes(resourceName, pluralName, allowedCrudOperations); const actionCreators = generateActionCreators(allowedCrudOperations); return { actionCreators, actionTypes: types, initialState: initial, reducer: generateReducer({ pluralForm: pluralName, allowedOperations: allowedCrudOperations, initialState: initial, idAttr, handlers, types, resourceName }), pluralForm: pluralName }; } export {xhrStatuses}; export default simpleResource;
142e361d2bcfbdc15939ad33c600bf943025f7b1
api/v1/serializers/no_project_serializer.py
api/v1/serializers/no_project_serializer.py
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .application_serializer import ApplicationSerializer from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): applications = serializers.SerializerMethodField('get_user_applications') instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_applications(self, atmo_user): return [ApplicationSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.application_set.filter(only_current(), projects=None)] def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('applications', 'instances', 'volumes')
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
Remove final references to application
Remove final references to application
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
python
## Code Before: from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .application_serializer import ApplicationSerializer from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): applications = serializers.SerializerMethodField('get_user_applications') instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_applications(self, atmo_user): return [ApplicationSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.application_set.filter(only_current(), projects=None)] def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('applications', 'instances', 'volumes') ## Instruction: Remove final references to application ## Code After: from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
77666e7ce307e8050a89cf08ddbe6c5429052cc6
src/main/java/org/literacyapp/model/gson/StudentImageGson.java
src/main/java/org/literacyapp/model/gson/StudentImageGson.java
package org.literacyapp.model.gson; import java.util.Calendar; import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson; public class StudentImageGson extends BaseEntityGson { private DeviceGson device; private Calendar timeCollected; private String imageFileUrl; private StudentImageFeatureGson studentImageFeature; private StudentImageCollectionEventGson studentImageCollectionEvent; public DeviceGson getDevice() { return device; } public void setDevice(DeviceGson device) { this.device = device; } public Calendar getTimeCollected() { return timeCollected; } public void setTimeCollected(Calendar timeCollected) { this.timeCollected = timeCollected; } public String getImageFileUrl() { return imageFileUrl; } public void setImageFileUrl(String imageFileUrl) { this.imageFileUrl = imageFileUrl; } public StudentImageFeatureGson getStudentImageFeature() { return studentImageFeature; } public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) { this.studentImageFeature = studentImageFeature; } public StudentImageCollectionEventGson getStudentImageCollectionEvent() { return studentImageCollectionEvent; } public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) { this.studentImageCollectionEvent = studentImageCollectionEvent; } }
package org.literacyapp.model.gson; import java.util.Calendar; import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson; public class StudentImageGson extends BaseEntityGson { private Calendar timeCollected; private String imageFileUrl; private StudentImageFeatureGson studentImageFeature; private StudentImageCollectionEventGson studentImageCollectionEvent; public Calendar getTimeCollected() { return timeCollected; } public void setTimeCollected(Calendar timeCollected) { this.timeCollected = timeCollected; } public String getImageFileUrl() { return imageFileUrl; } public void setImageFileUrl(String imageFileUrl) { this.imageFileUrl = imageFileUrl; } public StudentImageFeatureGson getStudentImageFeature() { return studentImageFeature; } public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) { this.studentImageFeature = studentImageFeature; } public StudentImageCollectionEventGson getStudentImageCollectionEvent() { return studentImageCollectionEvent; } public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) { this.studentImageCollectionEvent = studentImageCollectionEvent; } }
Remove device from student image
Remove device from student image
Java
apache-2.0
literacyapp-org/literacyapp-model
java
## Code Before: package org.literacyapp.model.gson; import java.util.Calendar; import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson; public class StudentImageGson extends BaseEntityGson { private DeviceGson device; private Calendar timeCollected; private String imageFileUrl; private StudentImageFeatureGson studentImageFeature; private StudentImageCollectionEventGson studentImageCollectionEvent; public DeviceGson getDevice() { return device; } public void setDevice(DeviceGson device) { this.device = device; } public Calendar getTimeCollected() { return timeCollected; } public void setTimeCollected(Calendar timeCollected) { this.timeCollected = timeCollected; } public String getImageFileUrl() { return imageFileUrl; } public void setImageFileUrl(String imageFileUrl) { this.imageFileUrl = imageFileUrl; } public StudentImageFeatureGson getStudentImageFeature() { return studentImageFeature; } public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) { this.studentImageFeature = studentImageFeature; } public StudentImageCollectionEventGson getStudentImageCollectionEvent() { return studentImageCollectionEvent; } public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) { this.studentImageCollectionEvent = studentImageCollectionEvent; } } ## Instruction: Remove device from student image ## Code After: package org.literacyapp.model.gson; import java.util.Calendar; import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson; public class StudentImageGson extends BaseEntityGson { private Calendar timeCollected; private String imageFileUrl; private StudentImageFeatureGson studentImageFeature; private StudentImageCollectionEventGson studentImageCollectionEvent; public Calendar getTimeCollected() { return timeCollected; } public void setTimeCollected(Calendar timeCollected) { this.timeCollected = timeCollected; } public String getImageFileUrl() { return imageFileUrl; } public void setImageFileUrl(String imageFileUrl) { this.imageFileUrl = imageFileUrl; } public StudentImageFeatureGson getStudentImageFeature() { return studentImageFeature; } public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) { this.studentImageFeature = studentImageFeature; } public StudentImageCollectionEventGson getStudentImageCollectionEvent() { return studentImageCollectionEvent; } public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) { this.studentImageCollectionEvent = studentImageCollectionEvent; } }
3c2ede21442b471f2028b9b01e14bbf187f99ce6
resources/views/search/index.blade.php
resources/views/search/index.blade.php
@extends('layout') @section('body') <h1>Search</h1> <form method="GET" class="tight"> <div class="row spacing-top-large"> <div class="column"> <input type="text" name="query" /> </div> <div class="column tight"> <input type="submit" value="Search" /> </div> </div> </form> @if (!empty($query)) @if (sizeof($earnings)) <h2 class="spacing-top-large spacing-bottom-medium">Earnings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($earnings as $earning) <tr> <td>{{ $earning->description }}</td> </tr> @endforeach </tbody> </table> @endif @if (sizeof($spendings)) <h2 class="spacing-top-large spacing-bottom-medium">Spendings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($spendings as $spending) <tr> <td>{{ $spending->description }}</td> </tr> @endforeach </tbody> </table> @endif @endif @endsection
@extends('layout') @section('body') <h1>Search</h1> <form method="GET" class="tight"> <div class="row spacing-top-large"> <div class="column"> <input type="text" name="query" /> </div> <div class="column tight"> <input type="submit" value="Search" /> </div> </div> </form> @if (!empty($query)) @if (sizeof($earnings)) <h2 class="spacing-top-large spacing-bottom-medium">Earnings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($earnings as $earning) <tr> <td>{{ $earning->description }}</td> </tr> @endforeach </tbody> </table> @endif @if (sizeof($spendings)) <h2 class="spacing-top-large spacing-bottom-medium">Spendings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($spendings as $spending) <tr> <td> <a href="/spendings/{{ $spending->id }}">{{ $spending->description }}</a> </td> </tr> @endforeach </tbody> </table> @endif @endif @endsection
Add hyperlink to spendings in search view
Add hyperlink to spendings in search view
PHP
mit
pix3ly/budget,pix3ly/budget
php
## Code Before: @extends('layout') @section('body') <h1>Search</h1> <form method="GET" class="tight"> <div class="row spacing-top-large"> <div class="column"> <input type="text" name="query" /> </div> <div class="column tight"> <input type="submit" value="Search" /> </div> </div> </form> @if (!empty($query)) @if (sizeof($earnings)) <h2 class="spacing-top-large spacing-bottom-medium">Earnings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($earnings as $earning) <tr> <td>{{ $earning->description }}</td> </tr> @endforeach </tbody> </table> @endif @if (sizeof($spendings)) <h2 class="spacing-top-large spacing-bottom-medium">Spendings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($spendings as $spending) <tr> <td>{{ $spending->description }}</td> </tr> @endforeach </tbody> </table> @endif @endif @endsection ## Instruction: Add hyperlink to spendings in search view ## Code After: @extends('layout') @section('body') <h1>Search</h1> <form method="GET" class="tight"> <div class="row spacing-top-large"> <div class="column"> <input type="text" name="query" /> </div> <div class="column tight"> <input type="submit" value="Search" /> </div> </div> </form> @if (!empty($query)) @if (sizeof($earnings)) <h2 class="spacing-top-large spacing-bottom-medium">Earnings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($earnings as $earning) <tr> <td>{{ $earning->description }}</td> </tr> @endforeach </tbody> </table> @endif @if (sizeof($spendings)) <h2 class="spacing-top-large spacing-bottom-medium">Spendings</h2> <table class="box"> <thead> <tr> <th>Description</th> </tr> </thread> <tbody> @foreach ($spendings as $spending) <tr> <td> <a href="/spendings/{{ $spending->id }}">{{ $spending->description }}</a> </td> </tr> @endforeach </tbody> </table> @endif @endif @endsection
2156fbea296484d528a1fbd1a2f4e4ac76af970d
salt/states/disk.py
salt/states/disk.py
''' Disk monitoring state Monitor the state of disk resources ''' def status(name, max=None, min=None): ''' Return the current disk usage stats for the named device ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = disk.usage() if not name in data: ret['result'] = False ret['comment'] += 'Named disk mount not present ' return ret if max: try: if isinstance(max, basestring): max = int(max.strip('%')) except Exception: ret['comment'] += 'Max argument must be an integer ' if min: try: if isinstance(min, basestring): min = int(min.strip('%')) except Exception: ret['comment'] += 'Min argument must be an integer ' if min and max: if min >= max: ret['comment'] += 'Min must be less than max' if ret['comment']: return ret cap = int(data[name]['capacity'].strip('%')) ret['data'] = data[name] if min: if cap < min: ret['comment'] = 'Disk is below minimum of {0} at {1}'.format( min, cap) return ret if max: if cap > max: ret['comment'] = 'Disk is below maximum of {0} at {1}'.format( max, cap) return ret ret['comment'] = 'Disk in acceptable range' ret['result'] = True return ret
''' Disk monitoring state Monitor the state of disk resources ''' def status(name, max=None, min=None): ''' Return the current disk usage stats for the named device ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = __salt__['disk.usage']() if not name in data: ret['result'] = False ret['comment'] += 'Named disk mount not present ' return ret if max: try: if isinstance(max, basestring): max = int(max.strip('%')) except Exception: ret['comment'] += 'Max argument must be an integer ' if min: try: if isinstance(min, basestring): min = int(min.strip('%')) except Exception: ret['comment'] += 'Min argument must be an integer ' if min and max: if min >= max: ret['comment'] += 'Min must be less than max' if ret['comment']: return ret cap = int(data[name]['capacity'].strip('%')) ret['data'] = data[name] if min: if cap < min: ret['comment'] = 'Disk is below minimum of {0} at {1}'.format( min, cap) return ret if max: if cap > max: ret['comment'] = 'Disk is below maximum of {0} at {1}'.format( max, cap) return ret ret['comment'] = 'Disk in acceptable range' ret['result'] = True return ret
Fix bad ref, forgot the __salt__ :P
Fix bad ref, forgot the __salt__ :P
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
python
## Code Before: ''' Disk monitoring state Monitor the state of disk resources ''' def status(name, max=None, min=None): ''' Return the current disk usage stats for the named device ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = disk.usage() if not name in data: ret['result'] = False ret['comment'] += 'Named disk mount not present ' return ret if max: try: if isinstance(max, basestring): max = int(max.strip('%')) except Exception: ret['comment'] += 'Max argument must be an integer ' if min: try: if isinstance(min, basestring): min = int(min.strip('%')) except Exception: ret['comment'] += 'Min argument must be an integer ' if min and max: if min >= max: ret['comment'] += 'Min must be less than max' if ret['comment']: return ret cap = int(data[name]['capacity'].strip('%')) ret['data'] = data[name] if min: if cap < min: ret['comment'] = 'Disk is below minimum of {0} at {1}'.format( min, cap) return ret if max: if cap > max: ret['comment'] = 'Disk is below maximum of {0} at {1}'.format( max, cap) return ret ret['comment'] = 'Disk in acceptable range' ret['result'] = True return ret ## Instruction: Fix bad ref, forgot the __salt__ :P ## Code After: ''' Disk monitoring state Monitor the state of disk resources ''' def status(name, max=None, min=None): ''' Return the current disk usage stats for the named device ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state data = __salt__['disk.usage']() if not name in data: ret['result'] = False ret['comment'] += 'Named disk mount not present ' return ret if max: try: if isinstance(max, basestring): max = int(max.strip('%')) except Exception: ret['comment'] += 'Max argument must be an integer ' if min: try: if isinstance(min, basestring): min = int(min.strip('%')) except Exception: ret['comment'] += 'Min argument must be an integer ' if min and max: if min >= max: ret['comment'] += 'Min must be less than max' if ret['comment']: return ret cap = int(data[name]['capacity'].strip('%')) ret['data'] = data[name] if min: if cap < min: ret['comment'] = 'Disk is below minimum of {0} at {1}'.format( min, cap) return ret if max: if cap > max: ret['comment'] = 'Disk is below maximum of {0} at {1}'.format( max, cap) return ret ret['comment'] = 'Disk in acceptable range' ret['result'] = True return ret
1ba14774b1ed483f512562ab83f91fab8b843db7
nazs/web/core/blocks.py
nazs/web/core/blocks.py
from django.utils.translation import ugettext as _ from achilles import blocks, tables import nazs register = blocks.Library('core') @register.block(template_name='web/core/welcome.html') def home(): return {'version': nazs.__version__} @register.block(template_name='web/core/apply_button.html') def apply_button(): return {'active': nazs.changed()} @register.block('modules') class Modules(tables.Table): id_field = 'name' # Module name name = tables.Column(verbose_name=_('Module')) # Module status status = tables.MergeColumn( verbose_name=_('Status'), columns=( ('install', tables.ActionColumn(verbose_name=_('Install'), action='core:install_module', visible=lambda m: not m.installed)), ('enable', tables.ActionColumn(verbose_name=_('Enable'), action='core:enable_module', visible=lambda m: m.installed and not m.enabled)), ('disable', tables.ActionColumn(verbose_name=_('Disable'), action='core:disable_module', visible=lambda m: m.installed and m.enabled)), ) ) def objects(self): return nazs.modules() def get_object(self, name): for module in nazs.modules(): if module.name == name: return module raise KeyError('Module %s not found' % name)
from django.utils.translation import ugettext as _ from achilles import blocks, tables import nazs register = blocks.Library('core') @register.block(template_name='web/core/welcome.html') def home(): return {'version': nazs.__version__} @register.block(template_name='web/core/apply_button.html') def apply_button(): return {'active': nazs.changed()} @register.block('modules') class Modules(tables.Table): id_field = 'name' # Module name name = tables.Column(verbose_name=_('Module')) # Module status status = tables.MergeColumn( verbose_name=_('Status'), columns=( ('install', tables.ActionColumn(verbose_name=_('Install'), action='core:install_module', classes='btn btn-sm btn-primary', visible=lambda m: not m.installed)), ('enable', tables.ActionColumn(verbose_name=_('Enable'), action='core:enable_module', classes='btn btn-sm btn-success', visible=lambda m: m.installed and not m.enabled)), ('disable', tables.ActionColumn(verbose_name=_('Disable'), action='core:disable_module', classes='btn btn-sm btn-danger', visible=lambda m: m.installed and m.enabled)), ) ) def objects(self): return nazs.modules() def get_object(self, name): for module in nazs.modules(): if module.name == name: return module raise KeyError('Module %s not found' % name)
Add proper css classes to action buttons
Add proper css classes to action buttons
Python
agpl-3.0
exekias/droplet,exekias/droplet,exekias/droplet
python
## Code Before: from django.utils.translation import ugettext as _ from achilles import blocks, tables import nazs register = blocks.Library('core') @register.block(template_name='web/core/welcome.html') def home(): return {'version': nazs.__version__} @register.block(template_name='web/core/apply_button.html') def apply_button(): return {'active': nazs.changed()} @register.block('modules') class Modules(tables.Table): id_field = 'name' # Module name name = tables.Column(verbose_name=_('Module')) # Module status status = tables.MergeColumn( verbose_name=_('Status'), columns=( ('install', tables.ActionColumn(verbose_name=_('Install'), action='core:install_module', visible=lambda m: not m.installed)), ('enable', tables.ActionColumn(verbose_name=_('Enable'), action='core:enable_module', visible=lambda m: m.installed and not m.enabled)), ('disable', tables.ActionColumn(verbose_name=_('Disable'), action='core:disable_module', visible=lambda m: m.installed and m.enabled)), ) ) def objects(self): return nazs.modules() def get_object(self, name): for module in nazs.modules(): if module.name == name: return module raise KeyError('Module %s not found' % name) ## Instruction: Add proper css classes to action buttons ## Code After: from django.utils.translation import ugettext as _ from achilles import blocks, tables import nazs register = blocks.Library('core') @register.block(template_name='web/core/welcome.html') def home(): return {'version': nazs.__version__} @register.block(template_name='web/core/apply_button.html') def apply_button(): return {'active': nazs.changed()} @register.block('modules') class Modules(tables.Table): id_field = 'name' # Module name name = tables.Column(verbose_name=_('Module')) # Module status status = tables.MergeColumn( verbose_name=_('Status'), columns=( ('install', tables.ActionColumn(verbose_name=_('Install'), action='core:install_module', classes='btn btn-sm btn-primary', visible=lambda m: not m.installed)), ('enable', tables.ActionColumn(verbose_name=_('Enable'), action='core:enable_module', classes='btn btn-sm btn-success', visible=lambda m: m.installed and not m.enabled)), ('disable', tables.ActionColumn(verbose_name=_('Disable'), action='core:disable_module', classes='btn btn-sm btn-danger', visible=lambda m: m.installed and m.enabled)), ) ) def objects(self): return nazs.modules() def get_object(self, name): for module in nazs.modules(): if module.name == name: return module raise KeyError('Module %s not found' % name)
eabacf889f89b4792c2b53d8ce4b7a13b5a85a8d
test/unit/edition/gov_uk_delivery_test.rb
test/unit/edition/gov_uk_delivery_test.rb
require "test_helper" require 'gds_api/test_helpers/gov_uk_delivery' class Edition::GovUkDeliveryTest < ActiveSupport::TestCase include GdsApi::TestHelpers::GovUkDelivery test "should notify govuk_delivery on publishing policies" do Edition::AuditTrail.whodunnit = create(:user) policy = create(:policy, topics: [create(:topic), create(:topic)]) policy.first_published_at = Time.zone.now policy.major_change_published_at = Time.zone.now policy.stubs(:govuk_delivery_tags).returns(['http://example.com/feed']) govuk_delivery_create_notification_success(['http://example.com/feed'], policy.title, '') policy.publish! end test "should notify govuk_delivery on publishing news articles" do news_article = create(:news_article) news_article.first_published_at = Time.zone.now news_article.major_change_published_at = Time.zone.now news_article.stubs(:govuk_delivery_tags).returns(['http://example.com/feed']) govuk_delivery_create_notification_success(['http://example.com/feed'], news_article.title, '') news_article.publish! end test "should notify govuk_delivery on publishing publications" do publication = create(:publication) publication.first_published_at = Time.zone.now publication.major_change_published_at = Time.zone.now publication.stubs(:govuk_delivery_tags).returns(['http://example.com/feed']) govuk_delivery_create_notification_success(['http://example.com/feed'], publication.title, '') publication.publish! end end
require "test_helper" require 'gds_api/test_helpers/gov_uk_delivery' class Edition::GovUkDeliveryTest < ActiveSupport::TestCase include GdsApi::TestHelpers::GovUkDelivery test "should notify govuk_delivery on publishing policies" do Edition::AuditTrail.whodunnit = create(:user) policy = create(:policy, topics: [create(:topic), create(:topic)]) policy.first_published_at = Time.zone.now policy.major_change_published_at = Time.zone.now policy.expects(:notify_govuk_delivery).once policy.publish! end test "should notify govuk_delivery on publishing news articles" do news_article = create(:news_article) news_article.first_published_at = Time.zone.now news_article.major_change_published_at = Time.zone.now news_article.expects(:notify_govuk_delivery).once news_article.publish! end test "should notify govuk_delivery on publishing publications" do publication = create(:publication) publication.first_published_at = Time.zone.now publication.major_change_published_at = Time.zone.now publication.expects(:notify_govuk_delivery).once publication.publish! end end
Change unit test to just check for invocation
Change unit test to just check for invocation
Ruby
mit
askl56/whitehall,robinwhittleton/whitehall,hotvulcan/whitehall,alphagov/whitehall,robinwhittleton/whitehall,alphagov/whitehall,hotvulcan/whitehall,alphagov/whitehall,askl56/whitehall,ggoral/whitehall,robinwhittleton/whitehall,ggoral/whitehall,alphagov/whitehall,ggoral/whitehall,robinwhittleton/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,YOTOV-LIMITED/whitehall,hotvulcan/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,hotvulcan/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall
ruby
## Code Before: require "test_helper" require 'gds_api/test_helpers/gov_uk_delivery' class Edition::GovUkDeliveryTest < ActiveSupport::TestCase include GdsApi::TestHelpers::GovUkDelivery test "should notify govuk_delivery on publishing policies" do Edition::AuditTrail.whodunnit = create(:user) policy = create(:policy, topics: [create(:topic), create(:topic)]) policy.first_published_at = Time.zone.now policy.major_change_published_at = Time.zone.now policy.stubs(:govuk_delivery_tags).returns(['http://example.com/feed']) govuk_delivery_create_notification_success(['http://example.com/feed'], policy.title, '') policy.publish! end test "should notify govuk_delivery on publishing news articles" do news_article = create(:news_article) news_article.first_published_at = Time.zone.now news_article.major_change_published_at = Time.zone.now news_article.stubs(:govuk_delivery_tags).returns(['http://example.com/feed']) govuk_delivery_create_notification_success(['http://example.com/feed'], news_article.title, '') news_article.publish! end test "should notify govuk_delivery on publishing publications" do publication = create(:publication) publication.first_published_at = Time.zone.now publication.major_change_published_at = Time.zone.now publication.stubs(:govuk_delivery_tags).returns(['http://example.com/feed']) govuk_delivery_create_notification_success(['http://example.com/feed'], publication.title, '') publication.publish! end end ## Instruction: Change unit test to just check for invocation ## Code After: require "test_helper" require 'gds_api/test_helpers/gov_uk_delivery' class Edition::GovUkDeliveryTest < ActiveSupport::TestCase include GdsApi::TestHelpers::GovUkDelivery test "should notify govuk_delivery on publishing policies" do Edition::AuditTrail.whodunnit = create(:user) policy = create(:policy, topics: [create(:topic), create(:topic)]) policy.first_published_at = Time.zone.now policy.major_change_published_at = Time.zone.now policy.expects(:notify_govuk_delivery).once policy.publish! end test "should notify govuk_delivery on publishing news articles" do news_article = create(:news_article) news_article.first_published_at = Time.zone.now news_article.major_change_published_at = Time.zone.now news_article.expects(:notify_govuk_delivery).once news_article.publish! end test "should notify govuk_delivery on publishing publications" do publication = create(:publication) publication.first_published_at = Time.zone.now publication.major_change_published_at = Time.zone.now publication.expects(:notify_govuk_delivery).once publication.publish! end end
5e72bf8392bc4844ba5abcd49eb63c55d19d4657
applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt
applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt
package com.example.billing.reocurringPayments import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController class Controller { @Autowired private lateinit var paymentGateway: com.example.payments.Gateway @Autowired private lateinit var counter: CounterService @Autowired private lateinit var service: Service @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST)) fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> { val responseHeaders = HttpHeaders() responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString()) service.thisMayFail() val response: ResponseEntity<String> if (paymentGateway.createReocurringPayment(data["amount"] as Int)) { counter.increment("billing.reocurringPayment.created") response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED) } else { response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST) } return response } }
package com.example.billing.reocurringPayments import com.example.payments.Gateway import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import javax.inject.Inject @RestController class Controller { private val paymentGateway: com.example.payments.Gateway private val counter: CounterService private val service: Service @Inject constructor(paymentGateway: Gateway, counterService: CounterService, service: Service) { this.paymentGateway = paymentGateway this.counter = counterService this.service = service } @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST)) fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> { val responseHeaders = HttpHeaders() responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString()) service.thisMayFail() val response: ResponseEntity<String> if (paymentGateway.createReocurringPayment(data["amount"] as Int)) { counter.increment("billing.reocurringPayment.created") response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED) } else { response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST) } return response } }
Use constructor injection so you can make instance variables vals
Use constructor injection so you can make instance variables vals
Kotlin
mit
mikegehard/user-management-evolution-kotlin,mikegehard/user-management-evolution-kotlin,mikegehard/user-management-evolution-kotlin
kotlin
## Code Before: package com.example.billing.reocurringPayments import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController class Controller { @Autowired private lateinit var paymentGateway: com.example.payments.Gateway @Autowired private lateinit var counter: CounterService @Autowired private lateinit var service: Service @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST)) fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> { val responseHeaders = HttpHeaders() responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString()) service.thisMayFail() val response: ResponseEntity<String> if (paymentGateway.createReocurringPayment(data["amount"] as Int)) { counter.increment("billing.reocurringPayment.created") response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED) } else { response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST) } return response } } ## Instruction: Use constructor injection so you can make instance variables vals ## Code After: package com.example.billing.reocurringPayments import com.example.payments.Gateway import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import javax.inject.Inject @RestController class Controller { private val paymentGateway: com.example.payments.Gateway private val counter: CounterService private val service: Service @Inject constructor(paymentGateway: Gateway, counterService: CounterService, service: Service) { this.paymentGateway = paymentGateway this.counter = counterService this.service = service } @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST)) fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> { val responseHeaders = HttpHeaders() responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString()) service.thisMayFail() val response: ResponseEntity<String> if (paymentGateway.createReocurringPayment(data["amount"] as Int)) { counter.increment("billing.reocurringPayment.created") response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED) } else { response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST) } return response } }
155b1e6b8d431f1169a3e71d08d93d76a3414c59
turbustat/statistics/vca_vcs/slice_thickness.py
turbustat/statistics/vca_vcs/slice_thickness.py
import numpy as np def change_slice_thickness(cube, slice_thickness=1.0): ''' Degrades the velocity resolution of a data cube. This is to avoid shot noise by removing velocity fluctuations at small thicknesses. Parameters ---------- cube : numpy.ndarray 3D data cube to degrade slice_thickness : float, optional Thicknesses of the new slices. Minimum is 1.0 Thickness must be integer multiple of the original cube size Returns ------- degraded_cube : numpy.ndarray Data cube degraded to new slice thickness ''' assert isinstance(slice_thickness, float) if slice_thickness < 1: slice_thickness == 1 print "Slice Thickness must be at least 1.0. Returning original cube." if slice_thickness == 1: return cube if cube.shape[0] % slice_thickness != 0: raise TypeError("Slice thickness must be integer multiple of dimension" " size % s" % (cube.shape[0])) slice_thickness = int(slice_thickness) # Want to average over velocity channels new_channel_indices = np.arange(0, cube.shape[0] / slice_thickness) degraded_cube = np.ones( (cube.shape[0] / slice_thickness, cube.shape[1], cube.shape[2])) for channel in new_channel_indices: old_index = int(channel * slice_thickness) channel = int(channel) degraded_cube[channel, :, :] = \ np.nanmean(cube[old_index:old_index + slice_thickness], axis=0) return degraded_cube
import numpy as np from astropy import units as u from spectral_cube import SpectralCube from astropy.convolution import Gaussian1DKernel def spectral_regrid_cube(cube, channel_width): fwhm_factor = np.sqrt(8 * np.log(2)) current_resolution = np.diff(cube.spectral_axis[:2])[0] target_resolution = channel_width.to(current_resolution.unit) diff_factor = np.abs(target_resolution / current_resolution).value pixel_scale = np.abs(current_resolution) gaussian_width = ((target_resolution**2 - current_resolution**2)**0.5 / pixel_scale / fwhm_factor) kernel = Gaussian1DKernel(gaussian_width) new_cube = cube.spectral_smooth(kernel) # Now define the new spectral axis at the new resolution num_chan = int(np.floor_divide(cube.shape[0], diff_factor)) new_specaxis = np.linspace(cube.spectral_axis.min().value, cube.spectral_axis.max().value, num_chan) * current_resolution.unit # Keep the same order (max to min or min to max) if current_resolution.value < 0: new_specaxis = new_specaxis[::-1] return new_cube.spectral_interpolate(new_specaxis, suppress_smooth_warning=True)
Add a corrected spectral regridding function that smooths before interpolating to a new spectral axis
Add a corrected spectral regridding function that smooths before interpolating to a new spectral axis
Python
mit
e-koch/TurbuStat,Astroua/TurbuStat
python
## Code Before: import numpy as np def change_slice_thickness(cube, slice_thickness=1.0): ''' Degrades the velocity resolution of a data cube. This is to avoid shot noise by removing velocity fluctuations at small thicknesses. Parameters ---------- cube : numpy.ndarray 3D data cube to degrade slice_thickness : float, optional Thicknesses of the new slices. Minimum is 1.0 Thickness must be integer multiple of the original cube size Returns ------- degraded_cube : numpy.ndarray Data cube degraded to new slice thickness ''' assert isinstance(slice_thickness, float) if slice_thickness < 1: slice_thickness == 1 print "Slice Thickness must be at least 1.0. Returning original cube." if slice_thickness == 1: return cube if cube.shape[0] % slice_thickness != 0: raise TypeError("Slice thickness must be integer multiple of dimension" " size % s" % (cube.shape[0])) slice_thickness = int(slice_thickness) # Want to average over velocity channels new_channel_indices = np.arange(0, cube.shape[0] / slice_thickness) degraded_cube = np.ones( (cube.shape[0] / slice_thickness, cube.shape[1], cube.shape[2])) for channel in new_channel_indices: old_index = int(channel * slice_thickness) channel = int(channel) degraded_cube[channel, :, :] = \ np.nanmean(cube[old_index:old_index + slice_thickness], axis=0) return degraded_cube ## Instruction: Add a corrected spectral regridding function that smooths before interpolating to a new spectral axis ## Code After: import numpy as np from astropy import units as u from spectral_cube import SpectralCube from astropy.convolution import Gaussian1DKernel def spectral_regrid_cube(cube, channel_width): fwhm_factor = np.sqrt(8 * np.log(2)) current_resolution = np.diff(cube.spectral_axis[:2])[0] target_resolution = channel_width.to(current_resolution.unit) diff_factor = np.abs(target_resolution / current_resolution).value pixel_scale = np.abs(current_resolution) gaussian_width = ((target_resolution**2 - current_resolution**2)**0.5 / pixel_scale / fwhm_factor) kernel = Gaussian1DKernel(gaussian_width) new_cube = cube.spectral_smooth(kernel) # Now define the new spectral axis at the new resolution num_chan = int(np.floor_divide(cube.shape[0], diff_factor)) new_specaxis = np.linspace(cube.spectral_axis.min().value, cube.spectral_axis.max().value, num_chan) * current_resolution.unit # Keep the same order (max to min or min to max) if current_resolution.value < 0: new_specaxis = new_specaxis[::-1] return new_cube.spectral_interpolate(new_specaxis, suppress_smooth_warning=True)
19a91f09b096fea15f35def7a978db43b4c4b9d5
assets/js/index.js
assets/js/index.js
/** * Main JS file for Casper behaviours */ /* globals jQuery, document */ (function ($, undefined) { "use strict"; var $document = $(document); $document.ready(function () { var $postContent = $(".post-content"); $postContent.fitVids(); $(".scroll-down").arctic_scroll(); $(".menu-button, .nav-cover, .nav-close").on("click", function(e){ e.preventDefault(); $("body").toggleClass("nav-opened nav-closed"); }); }); // Arctic Scroll by Paul Adam Davis // https://github.com/PaulAdamDavis/Arctic-Scroll $.fn.arctic_scroll = function (options) { var defaults = { elem: $(this), speed: 500 }, allOptions = $.extend(defaults, options); allOptions.elem.click(function (event) { event.preventDefault(); var $this = $(this), $htmlBody = $('html, body'), offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false, position = ($this.attr('data-position')) ? $this.attr('data-position') : false, toMove; if (offset) { toMove = parseInt(offset); $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed); } else if (position) { toMove = parseInt(position); $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed); } else { $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed); } }); }; })(jQuery);
/** * Main JS file for Casper behaviours */ /* globals jQuery, document */ (function ($, undefined) { "use strict"; var $document = $(document); $document.ready(function () { var $postContent = $(".post-content"); $postContent.fitVids(); $(".menu-button, .nav-cover, .nav-close").on("click", function(e){ e.preventDefault(); $("body").toggleClass("nav-opened nav-closed"); }); setTimeout(placeFootnotes, 1); $(window).resize(placeFootnotes); }); })(jQuery); var placeFootnotes = function() { if($('.footnotes').length > 0) { var numberOfFootnotes = $('.footnotes ol li').last().attr('id').substring($('.footnotes ol li').last().attr('id').indexOf(':')+1); var width = $(window).width(); if(width > 760) { for(var i=1; i<=numberOfFootnotes; i++) { var top = Math.floor($('#fnref\\:' + i).position().top); $('#fn\\:' + i).css('top', (top - 24) + 'px'); } $('a[href^="#fnref"]').remove(); } } }
Add function for placing footnotes
Add function for placing footnotes
JavaScript
mit
dvdhllbrg/tufte-ghost
javascript
## Code Before: /** * Main JS file for Casper behaviours */ /* globals jQuery, document */ (function ($, undefined) { "use strict"; var $document = $(document); $document.ready(function () { var $postContent = $(".post-content"); $postContent.fitVids(); $(".scroll-down").arctic_scroll(); $(".menu-button, .nav-cover, .nav-close").on("click", function(e){ e.preventDefault(); $("body").toggleClass("nav-opened nav-closed"); }); }); // Arctic Scroll by Paul Adam Davis // https://github.com/PaulAdamDavis/Arctic-Scroll $.fn.arctic_scroll = function (options) { var defaults = { elem: $(this), speed: 500 }, allOptions = $.extend(defaults, options); allOptions.elem.click(function (event) { event.preventDefault(); var $this = $(this), $htmlBody = $('html, body'), offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false, position = ($this.attr('data-position')) ? $this.attr('data-position') : false, toMove; if (offset) { toMove = parseInt(offset); $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed); } else if (position) { toMove = parseInt(position); $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed); } else { $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed); } }); }; })(jQuery); ## Instruction: Add function for placing footnotes ## Code After: /** * Main JS file for Casper behaviours */ /* globals jQuery, document */ (function ($, undefined) { "use strict"; var $document = $(document); $document.ready(function () { var $postContent = $(".post-content"); $postContent.fitVids(); $(".menu-button, .nav-cover, .nav-close").on("click", function(e){ e.preventDefault(); $("body").toggleClass("nav-opened nav-closed"); }); setTimeout(placeFootnotes, 1); $(window).resize(placeFootnotes); }); })(jQuery); var placeFootnotes = function() { if($('.footnotes').length > 0) { var numberOfFootnotes = $('.footnotes ol li').last().attr('id').substring($('.footnotes ol li').last().attr('id').indexOf(':')+1); var width = $(window).width(); if(width > 760) { for(var i=1; i<=numberOfFootnotes; i++) { var top = Math.floor($('#fnref\\:' + i).position().top); $('#fn\\:' + i).css('top', (top - 24) + 'px'); } $('a[href^="#fnref"]').remove(); } } }
ba0d89390c9c3b7f0e917e1c94de058617187447
lib/ganger/docker_container.rb
lib/ganger/docker_container.rb
module Ganger class DockerContainer attr_accessor :service_host, :service_port def initialize(container, docker_uri) @log = Logger.new(STDOUT) @container = container @name = @container.json["Name"].gsub('/', '') info "Created container with properties: #{container.json.to_s}" # Figure out host and port for the service in this container @service_host = URI.parse(docker_uri).host get_service_port info "Service host is: #{@service_host}; service port is #{@service_port}" end def dispose begin info "Dispose was called - stopping and removing container" @container.kill(:signal => "SIGKILL") @container.delete(:force => true) rescue => e fatal "Disposal of container failed with exception: #{e.class}: #{e.message}" end end private def get_service_port if @container.json["NetworkSettings"]["Ports"].nil? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].nil? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].empty? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first.nil? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first["HostPort"].nil? @service_port = nil info "No service port found - container is broken" else @service_port = @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first["HostPort"] info "Obtained service port: #{@service_port}" end end def info(msg) @log.info "#{@name}: #{msg}" end def fatal(msg) @log.fatal "#{@name}: #{msg}" end end end
module Ganger class DockerContainer attr_accessor :service_host, :service_port def initialize(container, docker_uri) @log = Logger.new(STDOUT) @container = container @name = @container.json["Name"].gsub('/', '') info "Created container with properties: #{container.json.to_s}" # Figure out host and port for the service in this container @service_host = URI.parse(docker_uri).host get_service_port info "Service host is: #{@service_host}; service port is #{@service_port}" end def dispose begin info "Dispose was called - stopping and removing container" @container.kill(:signal => "SIGKILL") @container.delete(:force => true) rescue => e fatal "Disposal of container failed with exception: #{e.class}: #{e.message}" end end private def get_service_port begin @service_port = @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first["HostPort"] info "Obtained service port: #{@service_port}" rescue @service_port = nil warn "Container is broken - could not obtain service port" end end def info(msg) @log.info "#{@name}: #{msg}" end def fatal(msg) @log.fatal "#{@name}: #{msg}" end end end
Simplify method for deciding a container is broken
Simplify method for deciding a container is broken
Ruby
mit
forward3d/ganger,forward3d/ganger
ruby
## Code Before: module Ganger class DockerContainer attr_accessor :service_host, :service_port def initialize(container, docker_uri) @log = Logger.new(STDOUT) @container = container @name = @container.json["Name"].gsub('/', '') info "Created container with properties: #{container.json.to_s}" # Figure out host and port for the service in this container @service_host = URI.parse(docker_uri).host get_service_port info "Service host is: #{@service_host}; service port is #{@service_port}" end def dispose begin info "Dispose was called - stopping and removing container" @container.kill(:signal => "SIGKILL") @container.delete(:force => true) rescue => e fatal "Disposal of container failed with exception: #{e.class}: #{e.message}" end end private def get_service_port if @container.json["NetworkSettings"]["Ports"].nil? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].nil? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].empty? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first.nil? || @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first["HostPort"].nil? @service_port = nil info "No service port found - container is broken" else @service_port = @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first["HostPort"] info "Obtained service port: #{@service_port}" end end def info(msg) @log.info "#{@name}: #{msg}" end def fatal(msg) @log.fatal "#{@name}: #{msg}" end end end ## Instruction: Simplify method for deciding a container is broken ## Code After: module Ganger class DockerContainer attr_accessor :service_host, :service_port def initialize(container, docker_uri) @log = Logger.new(STDOUT) @container = container @name = @container.json["Name"].gsub('/', '') info "Created container with properties: #{container.json.to_s}" # Figure out host and port for the service in this container @service_host = URI.parse(docker_uri).host get_service_port info "Service host is: #{@service_host}; service port is #{@service_port}" end def dispose begin info "Dispose was called - stopping and removing container" @container.kill(:signal => "SIGKILL") @container.delete(:force => true) rescue => e fatal "Disposal of container failed with exception: #{e.class}: #{e.message}" end end private def get_service_port begin @service_port = @container.json["NetworkSettings"]["Ports"][Ganger.configuration.docker_expose].first["HostPort"] info "Obtained service port: #{@service_port}" rescue @service_port = nil warn "Container is broken - could not obtain service port" end end def info(msg) @log.info "#{@name}: #{msg}" end def fatal(msg) @log.fatal "#{@name}: #{msg}" end end end
afaaefb39f111b0bf11b2946ba21cc748922a7a3
lib/fabrication/generator/active_record.rb
lib/fabrication/generator/active_record.rb
class Fabrication::Generator::ActiveRecord < Fabrication::Generator::Base def self.supports?(klass) defined?(ActiveRecord) && klass.ancestors.include?(ActiveRecord::Base) end def method_missing(method_name, *args, &block) method_name = method_name.to_s if block_given? options = args.first || {} count = options[:count] || 0 unless options[:force] || instance.class.columns.map(&:name).include?(method_name) # copy the original getter instance.instance_variable_set("@__#{method_name}_original", instance.method(method_name).clone) # store the block for lazy generation instance.instance_variable_set("@__#{method_name}_block", block) # redefine the getter instance.instance_eval %< def #{method_name} original_value = @__#{method_name}_original.call if @__#{method_name}_block if #{count} \>= 1 original_value = #{method_name}= (1..#{count}).map { |i| @__#{method_name}_block.call(self, i) } else original_value = #{method_name}= @__#{method_name}_block.call(self) end @__#{method_name}_block = nil @__#{method_name}_original.call end original_value end > else assign(method_name, options, &block) end else assign(method_name, args.first) end end protected def after_generation(options) instance.save if options[:save] end end
class Fabrication::Generator::ActiveRecord < Fabrication::Generator::Base def self.supports?(klass) defined?(ActiveRecord) && klass.ancestors.include?(ActiveRecord::Base) end def method_missing(method_name, *args, &block) method_name = method_name.to_s if block_given? options = args.first || {} unless options[:force] || instance.class.columns.map(&:name).include?(method_name) count = options[:count] || 0 # copy the original getter instance.instance_variable_set("@__#{method_name}_original", instance.method(method_name).clone) # store the block for lazy generation instance.instance_variable_set("@__#{method_name}_block", block) # redefine the getter instance.instance_eval %< def #{method_name} original_value = @__#{method_name}_original.call if @__#{method_name}_block if #{count} \>= 1 original_value = #{method_name}= (1..#{count}).map { |i| @__#{method_name}_block.call(self, i) } else original_value = #{method_name}= @__#{method_name}_block.call(self) end @__#{method_name}_block = nil @__#{method_name}_original.call end original_value end > else assign(method_name, options, &block) end else assign(method_name, args.first) end end protected def after_generation(options) instance.save if options[:save] end end
Move count determination into block that uses it
Move count determination into block that uses it
Ruby
mit
supremebeing7/fabrication,supremebeing7/fabrication,paulelliott/fabrication,damsonn/fabrication,damsonn/fabrication,gregburek/fabrication,gregburek/fabrication,paulelliott/fabrication
ruby
## Code Before: class Fabrication::Generator::ActiveRecord < Fabrication::Generator::Base def self.supports?(klass) defined?(ActiveRecord) && klass.ancestors.include?(ActiveRecord::Base) end def method_missing(method_name, *args, &block) method_name = method_name.to_s if block_given? options = args.first || {} count = options[:count] || 0 unless options[:force] || instance.class.columns.map(&:name).include?(method_name) # copy the original getter instance.instance_variable_set("@__#{method_name}_original", instance.method(method_name).clone) # store the block for lazy generation instance.instance_variable_set("@__#{method_name}_block", block) # redefine the getter instance.instance_eval %< def #{method_name} original_value = @__#{method_name}_original.call if @__#{method_name}_block if #{count} \>= 1 original_value = #{method_name}= (1..#{count}).map { |i| @__#{method_name}_block.call(self, i) } else original_value = #{method_name}= @__#{method_name}_block.call(self) end @__#{method_name}_block = nil @__#{method_name}_original.call end original_value end > else assign(method_name, options, &block) end else assign(method_name, args.first) end end protected def after_generation(options) instance.save if options[:save] end end ## Instruction: Move count determination into block that uses it ## Code After: class Fabrication::Generator::ActiveRecord < Fabrication::Generator::Base def self.supports?(klass) defined?(ActiveRecord) && klass.ancestors.include?(ActiveRecord::Base) end def method_missing(method_name, *args, &block) method_name = method_name.to_s if block_given? options = args.first || {} unless options[:force] || instance.class.columns.map(&:name).include?(method_name) count = options[:count] || 0 # copy the original getter instance.instance_variable_set("@__#{method_name}_original", instance.method(method_name).clone) # store the block for lazy generation instance.instance_variable_set("@__#{method_name}_block", block) # redefine the getter instance.instance_eval %< def #{method_name} original_value = @__#{method_name}_original.call if @__#{method_name}_block if #{count} \>= 1 original_value = #{method_name}= (1..#{count}).map { |i| @__#{method_name}_block.call(self, i) } else original_value = #{method_name}= @__#{method_name}_block.call(self) end @__#{method_name}_block = nil @__#{method_name}_original.call end original_value end > else assign(method_name, options, &block) end else assign(method_name, args.first) end end protected def after_generation(options) instance.save if options[:save] end end
ff55e9f788cfcdfc440724be64022787e404616e
src/at/create/android/ffc/http/FormBasedAuthentication.java
src/at/create/android/ffc/http/FormBasedAuthentication.java
package at.create.android.ffc.http; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** * @author Philipp Ullmann * Authenticate with username and password. */ public final class FormBasedAuthentication extends HttpBase { private static final String PATH = "/authentication"; private final String username; private final String password; /** * Stores the given parameters into instance variables. * @param username Username * @param password Password * @param baseUri Base uri to Fat Free CRM web application */ public FormBasedAuthentication(final String username, final String password, final String baseUri) { super(baseUri); this.username = username; this.password = password; } @Override protected String getUrl() { return baseUri + PATH; } /** * Authentication via username and password. * @return True if the authentication succeeded, otherwise false is returned. */ public boolean authenticate() { MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>(); formData.add("authentication[username]", username); formData.add("authentication[password]", password); formData.add("authentication[remember_me]", "1"); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders); ResponseEntity<String> response = restTemplate.exchange(getUrl(), HttpMethod.POST, requestEntity, String.class); return !response.getHeaders().getLocation().getPath().equals("/login"); } }
package at.create.android.ffc.http; import java.net.URI; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** * @author Philipp Ullmann * Authenticate with username and password. */ public final class FormBasedAuthentication extends HttpBase { private static final String PATH = "/authentication"; private final String username; private final String password; /** * Stores the given parameters into instance variables. * @param username Username * @param password Password * @param baseUri Base uri to Fat Free CRM web application */ public FormBasedAuthentication(final String username, final String password, final String baseUri) { super(baseUri); this.username = username; this.password = password; } @Override protected String getUrl() { return baseUri + PATH; } /** * Authentication via username and password. * @return True if the authentication succeeded, otherwise false is returned. */ public boolean authenticate() { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("authentication[username]", username); formData.add("authentication[password]", password); formData.add("authentication[remember_me]", "1"); restTemplate.getMessageConverters().add(new FormHttpMessageConverter()); URI uri = restTemplate.postForLocation(getUrl(), formData); return !uri.getPath().equals("/login"); } }
Use "FormHttpMessageConverter" for form based requests
Use "FormHttpMessageConverter" for form based requests
Java
agpl-3.0
create-mediadesign/FFC-Android-App
java
## Code Before: package at.create.android.ffc.http; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** * @author Philipp Ullmann * Authenticate with username and password. */ public final class FormBasedAuthentication extends HttpBase { private static final String PATH = "/authentication"; private final String username; private final String password; /** * Stores the given parameters into instance variables. * @param username Username * @param password Password * @param baseUri Base uri to Fat Free CRM web application */ public FormBasedAuthentication(final String username, final String password, final String baseUri) { super(baseUri); this.username = username; this.password = password; } @Override protected String getUrl() { return baseUri + PATH; } /** * Authentication via username and password. * @return True if the authentication succeeded, otherwise false is returned. */ public boolean authenticate() { MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>(); formData.add("authentication[username]", username); formData.add("authentication[password]", password); formData.add("authentication[remember_me]", "1"); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders); ResponseEntity<String> response = restTemplate.exchange(getUrl(), HttpMethod.POST, requestEntity, String.class); return !response.getHeaders().getLocation().getPath().equals("/login"); } } ## Instruction: Use "FormHttpMessageConverter" for form based requests ## Code After: package at.create.android.ffc.http; import java.net.URI; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** * @author Philipp Ullmann * Authenticate with username and password. */ public final class FormBasedAuthentication extends HttpBase { private static final String PATH = "/authentication"; private final String username; private final String password; /** * Stores the given parameters into instance variables. * @param username Username * @param password Password * @param baseUri Base uri to Fat Free CRM web application */ public FormBasedAuthentication(final String username, final String password, final String baseUri) { super(baseUri); this.username = username; this.password = password; } @Override protected String getUrl() { return baseUri + PATH; } /** * Authentication via username and password. * @return True if the authentication succeeded, otherwise false is returned. */ public boolean authenticate() { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("authentication[username]", username); formData.add("authentication[password]", password); formData.add("authentication[remember_me]", "1"); restTemplate.getMessageConverters().add(new FormHttpMessageConverter()); URI uri = restTemplate.postForLocation(getUrl(), formData); return !uri.getPath().equals("/login"); } }
36624a97b821586de10314fc00152b1f2d9a93f8
lib/microservice/index.js
lib/microservice/index.js
'use strict'; module.exports.Server = require('./server').Server; /* // server example let server = new Server(config.server); let service = new Service(server.events); yield server.bind(service); server.middleware.push(new Logging()); // Logging is custom middleware server.endpoints.register.middleware.push(new LogTime()); // custom middleware yield server.start(); // config { "server": { "events": { "provider": { "name" : "kafka", "config": { "groupId": "restore-chassis-example-server", "clientId": "restore-chassis-example-server", "connectionString": "localhost:9092" } } }, "endpoints": { "get": { transport: ["grpc"] }, "register": { transport: ["grpc"] } }, transports: [ { "name": "grpc", "config": { "proto": "/../protos/user.proto", "package": "user", "service": "User", "addr": "localhost:50051" } } ] }, "client": { "endpoints": { "get":{ "publisher": { "name": "static", "instances": ["localhost:50051"] }, "loadbalancer": [ { "name": "roundRobin" } ], "middleware": [ { "name": "retry", "max": 10, "timeout": 3000 } ] }, "register":{ "publisher": { "name": "static", "instances": ["localhost:50051"] }, "loadbalancer": [ { "name": "random", "seed": 1 } ], "middleware": [ { "name": "retry", "max": 10, "timeout": 3000 } ] }, } } } */
'use strict'; module.exports.Server = require('./server').Server;
Remove example text from microservice
Remove example text from microservice
JavaScript
mit
restorecommerce/chassis-srv,restorecommerce/chassis-srv
javascript
## Code Before: 'use strict'; module.exports.Server = require('./server').Server; /* // server example let server = new Server(config.server); let service = new Service(server.events); yield server.bind(service); server.middleware.push(new Logging()); // Logging is custom middleware server.endpoints.register.middleware.push(new LogTime()); // custom middleware yield server.start(); // config { "server": { "events": { "provider": { "name" : "kafka", "config": { "groupId": "restore-chassis-example-server", "clientId": "restore-chassis-example-server", "connectionString": "localhost:9092" } } }, "endpoints": { "get": { transport: ["grpc"] }, "register": { transport: ["grpc"] } }, transports: [ { "name": "grpc", "config": { "proto": "/../protos/user.proto", "package": "user", "service": "User", "addr": "localhost:50051" } } ] }, "client": { "endpoints": { "get":{ "publisher": { "name": "static", "instances": ["localhost:50051"] }, "loadbalancer": [ { "name": "roundRobin" } ], "middleware": [ { "name": "retry", "max": 10, "timeout": 3000 } ] }, "register":{ "publisher": { "name": "static", "instances": ["localhost:50051"] }, "loadbalancer": [ { "name": "random", "seed": 1 } ], "middleware": [ { "name": "retry", "max": 10, "timeout": 3000 } ] }, } } } */ ## Instruction: Remove example text from microservice ## Code After: 'use strict'; module.exports.Server = require('./server').Server;
97d941fd2857999afb85d7f3b0d90c1d3872595b
js/ChaptersDirective.js
js/ChaptersDirective.js
'use strict'; (function(app) { /** * Creates a new HTML element ov-index to create an openVeo player * index, with a list of presentation slides. * It requires ovPlayerDirectory global variable to be defined and have * a value corresponding to the path of the openVeo Player * root directory. * * e.g. * <ov-index></ov-index> */ function ovChapters(ovChaptersLink) { return { require: ['^ovPlayer', '^ovTabs'], restrict: 'E', templateUrl: ovPlayerDirectory + 'templates/chapters.html', scope: true, link: ovChaptersLink }; } app.factory('ovChaptersLink', function() { return function(scope, element, attrs, controllers) { // toggle chapter scope.open = function(chapter) { if (chapter.description && chapter.description != '') { if (!chapter.isOpen) angular.forEach(scope.chapters, function(value) { value.isOpen = false; }); chapter.isOpen = !chapter.isOpen; } }; /** * Seeks media to the given timecode. * @param Number timecode The timecode to seek to */ scope.goToTimecode = function(time) { var playerCtrl = controllers[0], tabsCtrl = controllers[1]; if (time <= 1) playerCtrl.setTime(time * scope.duration); tabsCtrl.selectTabs('media'); }; }; }); app.directive('ovChapters', ovChapters); ovChapters.$inject = ['ovChaptersLink']; })(angular.module('ov.player'));
'use strict'; (function(app) { /** * Creates a new HTML element ov-index to create an openVeo player * index, with a list of presentation slides. * It requires ovPlayerDirectory global variable to be defined and have * a value corresponding to the path of the openVeo Player * root directory. * * e.g. * <ov-index></ov-index> */ function ovChapters(ovChaptersLink) { return { require: ['^ovPlayer', '^ovTabs'], restrict: 'E', templateUrl: ovPlayerDirectory + 'templates/chapters.html', scope: true, link: ovChaptersLink }; } app.factory('ovChaptersLink', function() { return function(scope, element, attrs, controllers) { /** * Seeks media to the given timecode. * @param Number timecode The timecode to seek to */ scope.goToTimecode = function(time) { var playerCtrl = controllers[0], tabsCtrl = controllers[1]; if (time <= 1) playerCtrl.setTime(time * scope.duration); tabsCtrl.selectTabs('media'); }; }; }); app.directive('ovChapters', ovChapters); ovChapters.$inject = ['ovChaptersLink']; })(angular.module('ov.player'));
Remove unused open method on ovChapters directive
Remove unused open method on ovChapters directive
JavaScript
agpl-3.0
veo-labs/openveo-player,veo-labs/openveo-player,veo-labs/openveo-player
javascript
## Code Before: 'use strict'; (function(app) { /** * Creates a new HTML element ov-index to create an openVeo player * index, with a list of presentation slides. * It requires ovPlayerDirectory global variable to be defined and have * a value corresponding to the path of the openVeo Player * root directory. * * e.g. * <ov-index></ov-index> */ function ovChapters(ovChaptersLink) { return { require: ['^ovPlayer', '^ovTabs'], restrict: 'E', templateUrl: ovPlayerDirectory + 'templates/chapters.html', scope: true, link: ovChaptersLink }; } app.factory('ovChaptersLink', function() { return function(scope, element, attrs, controllers) { // toggle chapter scope.open = function(chapter) { if (chapter.description && chapter.description != '') { if (!chapter.isOpen) angular.forEach(scope.chapters, function(value) { value.isOpen = false; }); chapter.isOpen = !chapter.isOpen; } }; /** * Seeks media to the given timecode. * @param Number timecode The timecode to seek to */ scope.goToTimecode = function(time) { var playerCtrl = controllers[0], tabsCtrl = controllers[1]; if (time <= 1) playerCtrl.setTime(time * scope.duration); tabsCtrl.selectTabs('media'); }; }; }); app.directive('ovChapters', ovChapters); ovChapters.$inject = ['ovChaptersLink']; })(angular.module('ov.player')); ## Instruction: Remove unused open method on ovChapters directive ## Code After: 'use strict'; (function(app) { /** * Creates a new HTML element ov-index to create an openVeo player * index, with a list of presentation slides. * It requires ovPlayerDirectory global variable to be defined and have * a value corresponding to the path of the openVeo Player * root directory. * * e.g. * <ov-index></ov-index> */ function ovChapters(ovChaptersLink) { return { require: ['^ovPlayer', '^ovTabs'], restrict: 'E', templateUrl: ovPlayerDirectory + 'templates/chapters.html', scope: true, link: ovChaptersLink }; } app.factory('ovChaptersLink', function() { return function(scope, element, attrs, controllers) { /** * Seeks media to the given timecode. * @param Number timecode The timecode to seek to */ scope.goToTimecode = function(time) { var playerCtrl = controllers[0], tabsCtrl = controllers[1]; if (time <= 1) playerCtrl.setTime(time * scope.duration); tabsCtrl.selectTabs('media'); }; }; }); app.directive('ovChapters', ovChapters); ovChapters.$inject = ['ovChaptersLink']; })(angular.module('ov.player'));
32da3c0e2a537952ff9ff4701bbb5ec202c83e11
src/modules/selects/TagSelect/TagSelect.js
src/modules/selects/TagSelect/TagSelect.js
import React, { Component } from 'react' import { Creatable } from 'react-select' import R from 'ramda' class TagSelect extends Component { state = { multi: true, multiValue: [], options: this.props.options } componentWillReceiveProps = nextProps => { if (nextProps.edit && nextProps.input.value) { // because it could be user custom tag, we need to put in // into list of options: const computedOptions = (values, options) => { const allOptions = values.reduce((acc, value) => { const transformedValue = { value, label: value } acc.push(transformedValue) return acc }, options) return R.uniq(allOptions) } this.setState({ multiValue: nextProps.input.value, options: computedOptions(nextProps.input.value, nextProps.options) }) } } handleOnChange = value => { this.setState((prevState, props) => ({ multiValue: value })) this.props.input.onChange((value) ? value.split(',') : []) } render () { const { multi, multiValue } = this.state return ( <Creatable {...this.props} className='j-select' placeholder={this.props.placeholder} multi={multi} simpleValue options={this.state.options} onChange={this.handleOnChange} value={multiValue} /> ) } } export default TagSelect
import React, { Component } from 'react' import { Creatable } from 'react-select' import R from 'ramda' class TagSelect extends Component { state = { multi: true, multiValue: [], options: this.props.options } componentWillReceiveProps = nextProps => { if (nextProps.input.value) { // because it could be user custom tag, we need to put in // into list of options: const computedOptions = (values, options) => { const allOptions = values.reduce((acc, value) => { const transformedValue = { value, label: value } acc.push(transformedValue) return acc }, options) return R.uniq(allOptions) } this.setState({ multiValue: nextProps.input.value, options: computedOptions(nextProps.input.value, nextProps.options) }) } } handleOnChange = value => { this.setState((prevState, props) => ({ multiValue: value })) this.props.input.onChange((value) ? value.split(',') : []) } render () { const { multi, multiValue } = this.state return ( <Creatable {...this.props} className='j-select' placeholder={this.props.placeholder} multi={multi} simpleValue options={this.state.options} onChange={this.handleOnChange} value={multiValue} /> ) } } export default TagSelect
Update component state even when not editing
Update component state even when not editing
JavaScript
mit
hellofresh/janus-dashboard,hellofresh/janus-dashboard
javascript
## Code Before: import React, { Component } from 'react' import { Creatable } from 'react-select' import R from 'ramda' class TagSelect extends Component { state = { multi: true, multiValue: [], options: this.props.options } componentWillReceiveProps = nextProps => { if (nextProps.edit && nextProps.input.value) { // because it could be user custom tag, we need to put in // into list of options: const computedOptions = (values, options) => { const allOptions = values.reduce((acc, value) => { const transformedValue = { value, label: value } acc.push(transformedValue) return acc }, options) return R.uniq(allOptions) } this.setState({ multiValue: nextProps.input.value, options: computedOptions(nextProps.input.value, nextProps.options) }) } } handleOnChange = value => { this.setState((prevState, props) => ({ multiValue: value })) this.props.input.onChange((value) ? value.split(',') : []) } render () { const { multi, multiValue } = this.state return ( <Creatable {...this.props} className='j-select' placeholder={this.props.placeholder} multi={multi} simpleValue options={this.state.options} onChange={this.handleOnChange} value={multiValue} /> ) } } export default TagSelect ## Instruction: Update component state even when not editing ## Code After: import React, { Component } from 'react' import { Creatable } from 'react-select' import R from 'ramda' class TagSelect extends Component { state = { multi: true, multiValue: [], options: this.props.options } componentWillReceiveProps = nextProps => { if (nextProps.input.value) { // because it could be user custom tag, we need to put in // into list of options: const computedOptions = (values, options) => { const allOptions = values.reduce((acc, value) => { const transformedValue = { value, label: value } acc.push(transformedValue) return acc }, options) return R.uniq(allOptions) } this.setState({ multiValue: nextProps.input.value, options: computedOptions(nextProps.input.value, nextProps.options) }) } } handleOnChange = value => { this.setState((prevState, props) => ({ multiValue: value })) this.props.input.onChange((value) ? value.split(',') : []) } render () { const { multi, multiValue } = this.state return ( <Creatable {...this.props} className='j-select' placeholder={this.props.placeholder} multi={multi} simpleValue options={this.state.options} onChange={this.handleOnChange} value={multiValue} /> ) } } export default TagSelect
7b1a1e030e4cec8dba25b346cba14e256c02f798
src/main/java/org/littleshoot/proxy/mitm/HostNameMitmManager.java
src/main/java/org/littleshoot/proxy/mitm/HostNameMitmManager.java
package org.littleshoot.proxy.mitm; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.littleshoot.proxy.MitmManager; /** * {@link MitmManager} that uses the given host name to create a dynamic * certificate for. If a port is given, it will be truncated. */ public class HostNameMitmManager implements MitmManager { private BouncyCastleSslEngineSource sslEngineSource; public HostNameMitmManager() throws RootCertificateException { this(new Authority()); } public HostNameMitmManager(Authority authority) throws RootCertificateException { try { sslEngineSource = new BouncyCastleSslEngineSource(authority, true, true); } catch (final Exception e) { throw new RootCertificateException( "Errors during assembling root CA.", e); } } public SSLEngine serverSslEngine() { return sslEngineSource.newSslEngine(); } public SSLEngine clientSslEngineFor(SSLSession serverSslSession, String serverHostAndPort) { try { String serverName = serverHostAndPort.split(":")[0]; SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder(); return sslEngineSource.createCertForHost(serverName, san); } catch (Exception e) { throw new FakeCertificateException( "Creation dynamic certificate failed for " + serverHostAndPort, e); } } }
package org.littleshoot.proxy.mitm; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.littleshoot.proxy.MitmManager; /** * {@link MitmManager} that uses the given host name to create a dynamic * certificate for. If a port is given, it will be truncated. */ public class HostNameMitmManager implements MitmManager { private BouncyCastleSslEngineSource sslEngineSource; public HostNameMitmManager() throws RootCertificateException { this(new Authority()); } public HostNameMitmManager(Authority authority) throws RootCertificateException { try { boolean trustAllServers = false; boolean sendCerts = true; sslEngineSource = new BouncyCastleSslEngineSource(authority, trustAllServers, sendCerts); } catch (final Exception e) { throw new RootCertificateException( "Errors during assembling root CA.", e); } } public SSLEngine serverSslEngine() { return sslEngineSource.newSslEngine(); } public SSLEngine clientSslEngineFor(SSLSession serverSslSession, String serverHostAndPort) { try { String serverName = serverHostAndPort.split(":")[0]; SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder(); return sslEngineSource.createCertForHost(serverName, san); } catch (Exception e) { throw new FakeCertificateException( "Creation dynamic certificate failed for " + serverHostAndPort, e); } } }
Disable trust all servers by default.
Disable trust all servers by default.
Java
apache-2.0
ganskef/LittleProxy-mitm
java
## Code Before: package org.littleshoot.proxy.mitm; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.littleshoot.proxy.MitmManager; /** * {@link MitmManager} that uses the given host name to create a dynamic * certificate for. If a port is given, it will be truncated. */ public class HostNameMitmManager implements MitmManager { private BouncyCastleSslEngineSource sslEngineSource; public HostNameMitmManager() throws RootCertificateException { this(new Authority()); } public HostNameMitmManager(Authority authority) throws RootCertificateException { try { sslEngineSource = new BouncyCastleSslEngineSource(authority, true, true); } catch (final Exception e) { throw new RootCertificateException( "Errors during assembling root CA.", e); } } public SSLEngine serverSslEngine() { return sslEngineSource.newSslEngine(); } public SSLEngine clientSslEngineFor(SSLSession serverSslSession, String serverHostAndPort) { try { String serverName = serverHostAndPort.split(":")[0]; SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder(); return sslEngineSource.createCertForHost(serverName, san); } catch (Exception e) { throw new FakeCertificateException( "Creation dynamic certificate failed for " + serverHostAndPort, e); } } } ## Instruction: Disable trust all servers by default. ## Code After: package org.littleshoot.proxy.mitm; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.littleshoot.proxy.MitmManager; /** * {@link MitmManager} that uses the given host name to create a dynamic * certificate for. If a port is given, it will be truncated. */ public class HostNameMitmManager implements MitmManager { private BouncyCastleSslEngineSource sslEngineSource; public HostNameMitmManager() throws RootCertificateException { this(new Authority()); } public HostNameMitmManager(Authority authority) throws RootCertificateException { try { boolean trustAllServers = false; boolean sendCerts = true; sslEngineSource = new BouncyCastleSslEngineSource(authority, trustAllServers, sendCerts); } catch (final Exception e) { throw new RootCertificateException( "Errors during assembling root CA.", e); } } public SSLEngine serverSslEngine() { return sslEngineSource.newSslEngine(); } public SSLEngine clientSslEngineFor(SSLSession serverSslSession, String serverHostAndPort) { try { String serverName = serverHostAndPort.split(":")[0]; SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder(); return sslEngineSource.createCertForHost(serverName, san); } catch (Exception e) { throw new FakeCertificateException( "Creation dynamic certificate failed for " + serverHostAndPort, e); } } }
c4a72ff7935bcfd3eba2ad826003ebeb1eaa3681
android/src/main/java/victoralbertos/io/android/MainActivity.java
android/src/main/java/victoralbertos/io/android/MainActivity.java
package victoralbertos.io.android; import android.app.Activity; import android.os.Bundle; import io.reactivecache.ReactiveCache; import io.victoralbertos.jolyglot.GsonSpeaker; import java.util.ArrayList; import java.util.List; import rx.Observable; /** * Created by victor on 21/01/16. */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Create integration test for max mg limit and clearing expired data final ReactiveCache rxProviders = new ReactiveCache.Builder() .maxMBPersistence(50) .using(getApplicationContext().getFilesDir(), new GsonSpeaker()); /* for (int i = 0; i < 1000; i++) { String key = System.currentTimeMillis() + i + ""; rxProviders.getMocksEphemeralPaginate(createObservableMocks(100), new DynamicKey(key)) .subscribe(); }*/ } private Observable<List<Mock>> createObservableMocks(int size) { List<Mock> mocks = new ArrayList(size); for (int i = 0; i < size; i++) { mocks.add(new Mock("Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, " + "making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, " + "consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes " + "from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the " + "theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.")); } return Observable.just(mocks); } }
package victoralbertos.io.android; import android.app.Activity; /** * Created by victor on 21/01/16. */ public class MainActivity extends Activity { }
Remove reference from Android project
Remove reference from Android project
Java
apache-2.0
VictorAlbertos/RxCache
java
## Code Before: package victoralbertos.io.android; import android.app.Activity; import android.os.Bundle; import io.reactivecache.ReactiveCache; import io.victoralbertos.jolyglot.GsonSpeaker; import java.util.ArrayList; import java.util.List; import rx.Observable; /** * Created by victor on 21/01/16. */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Create integration test for max mg limit and clearing expired data final ReactiveCache rxProviders = new ReactiveCache.Builder() .maxMBPersistence(50) .using(getApplicationContext().getFilesDir(), new GsonSpeaker()); /* for (int i = 0; i < 1000; i++) { String key = System.currentTimeMillis() + i + ""; rxProviders.getMocksEphemeralPaginate(createObservableMocks(100), new DynamicKey(key)) .subscribe(); }*/ } private Observable<List<Mock>> createObservableMocks(int size) { List<Mock> mocks = new ArrayList(size); for (int i = 0; i < size; i++) { mocks.add(new Mock("Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, " + "making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, " + "consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes " + "from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the " + "theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.")); } return Observable.just(mocks); } } ## Instruction: Remove reference from Android project ## Code After: package victoralbertos.io.android; import android.app.Activity; /** * Created by victor on 21/01/16. */ public class MainActivity extends Activity { }
fa277cbc252361f75d15f718e9db81d8285152b3
source/assets/js/srf-a2z.js
source/assets/js/srf-a2z.js
export function init() { let triggers = document.querySelectorAll('.js-filter-bar-trigger'); for (let i = 0; i < triggers.length; i++) { let currentTrigger = triggers[i]; currentTrigger.addEventListener('click', function(e) { e.preventDefault(); const blockID = this.getAttribute('data-blockid'), allID = 'a2z-all', letterClass = 'filter-bar__letter', letterActiveClass = 'filter-bar__letter--active', blockClass = 'a2z-lists__block', hiddenClass = 'a2z-lists__block--hidden'; // styles clicked filter-bar-Element as active document.querySelectorAll('.' + letterClass).forEach(function(thisNode) { thisNode.classList.remove(letterActiveClass); }); this.classList.add(letterActiveClass); // show/hide selected Block of Elements if (blockID == allID) { document.querySelectorAll('.' + hiddenClass).forEach(function(thisNode) { thisNode.classList.remove(hiddenClass); }); } else { document.querySelectorAll('.' + blockClass + '[data-block="' + blockID + '"]').forEach(function(thisNode) { thisNode.classList.remove(hiddenClass); }); document.querySelectorAll('.' + blockClass + ':not([data-block="' + blockID + '"])').forEach(function(thisNode) { thisNode.classList.add(hiddenClass); }); } }); }; }
export function init() { let triggers = document.querySelectorAll('.js-filter-bar-trigger'); for (let i = 0; i < triggers.length; i++) { let currentTrigger = triggers[i]; currentTrigger.addEventListener('click', function(e) { e.preventDefault(); const blockID = this.getAttribute('data-blockid'), allID = 'a2z-all', letterClass = 'filter-bar__letter', letterActiveClass = 'filter-bar__letter--active', blockClass = 'a2z-lists__block', hiddenClass = 'a2z-lists__block--hidden'; // styles clicked filter-bar-Element as active document.querySelectorAll('.' + letterClass).forEach(function(thisNode) { thisNode.classList.remove(letterActiveClass); }); this.classList.add(letterActiveClass); // show/hide selected Block of Elements if (blockID === allID) { document.querySelectorAll('.' + hiddenClass).forEach(function(thisNode) { thisNode.closest('.js-collection').classList.remove(hiddenClass); }); } else { document.querySelectorAll('.' + blockClass + '[data-block="' + blockID + '"]').forEach(function(thisNode) { thisNode.closest('.js-collection').classList.remove(hiddenClass); }); document.querySelectorAll('.' + blockClass + ':not([data-block="' + blockID + '"])').forEach(function(thisNode) { thisNode.closest('.js-collection').classList.add(hiddenClass); }); } }); }; }
Move hide class to collection to remove margin-top spaces on hidden collections
Move hide class to collection to remove margin-top spaces on hidden collections SRFCMSAL-2500
JavaScript
mit
mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework
javascript
## Code Before: export function init() { let triggers = document.querySelectorAll('.js-filter-bar-trigger'); for (let i = 0; i < triggers.length; i++) { let currentTrigger = triggers[i]; currentTrigger.addEventListener('click', function(e) { e.preventDefault(); const blockID = this.getAttribute('data-blockid'), allID = 'a2z-all', letterClass = 'filter-bar__letter', letterActiveClass = 'filter-bar__letter--active', blockClass = 'a2z-lists__block', hiddenClass = 'a2z-lists__block--hidden'; // styles clicked filter-bar-Element as active document.querySelectorAll('.' + letterClass).forEach(function(thisNode) { thisNode.classList.remove(letterActiveClass); }); this.classList.add(letterActiveClass); // show/hide selected Block of Elements if (blockID == allID) { document.querySelectorAll('.' + hiddenClass).forEach(function(thisNode) { thisNode.classList.remove(hiddenClass); }); } else { document.querySelectorAll('.' + blockClass + '[data-block="' + blockID + '"]').forEach(function(thisNode) { thisNode.classList.remove(hiddenClass); }); document.querySelectorAll('.' + blockClass + ':not([data-block="' + blockID + '"])').forEach(function(thisNode) { thisNode.classList.add(hiddenClass); }); } }); }; } ## Instruction: Move hide class to collection to remove margin-top spaces on hidden collections SRFCMSAL-2500 ## Code After: export function init() { let triggers = document.querySelectorAll('.js-filter-bar-trigger'); for (let i = 0; i < triggers.length; i++) { let currentTrigger = triggers[i]; currentTrigger.addEventListener('click', function(e) { e.preventDefault(); const blockID = this.getAttribute('data-blockid'), allID = 'a2z-all', letterClass = 'filter-bar__letter', letterActiveClass = 'filter-bar__letter--active', blockClass = 'a2z-lists__block', hiddenClass = 'a2z-lists__block--hidden'; // styles clicked filter-bar-Element as active document.querySelectorAll('.' + letterClass).forEach(function(thisNode) { thisNode.classList.remove(letterActiveClass); }); this.classList.add(letterActiveClass); // show/hide selected Block of Elements if (blockID === allID) { document.querySelectorAll('.' + hiddenClass).forEach(function(thisNode) { thisNode.closest('.js-collection').classList.remove(hiddenClass); }); } else { document.querySelectorAll('.' + blockClass + '[data-block="' + blockID + '"]').forEach(function(thisNode) { thisNode.closest('.js-collection').classList.remove(hiddenClass); }); document.querySelectorAll('.' + blockClass + ':not([data-block="' + blockID + '"])').forEach(function(thisNode) { thisNode.closest('.js-collection').classList.add(hiddenClass); }); } }); }; }
daa2b3afd88532989782cc2555aa57b3cee1189c
spec/models/feature_spec.rb
spec/models/feature_spec.rb
require 'rails_helper' RSpec.describe Feature, type: :model do describe '.from_nns_data' do let(:nns_data) { {nameofneighbourhoodnetworkscheme: 'OWLS', easting: 427845, northing: 436087} } subject { described_class.from_nns_data(nns_data) } it 'creates a Feature' do expect(subject).to be_a(Feature) end it 'sets the name' do expect(subject.name).to eq('OWLS') end it 'sets the ftype' do expect(subject.ftype).to eq('nns') end it 'sets the lat/lng' do expect(subject.lat).to be_within(0.001).of(53.820) expect(subject.lng).to be_within(0.001).of(-1.578) end end describe '.from_changing_place_data' do let(:cp_data) { {location: 'Central Library', easting: 429859, northing: 433879} } subject { described_class.from_changing_place_data(cp_data) } it 'creates a Feature' do expect(subject).to be_a(Feature) end it 'sets the name' do expect(subject.name).to eq('Central Library') end it 'sets the ftype' do expect(subject.ftype).to eq('changing_place') end it 'sets the lat/lng' do expect(subject.lat).to be_within(0.001).of(53.800) expect(subject.lng).to be_within(0.001).of(-1.548) end end describe '.subtypes_for' do it 'finds only the relevant subtypes in alphabetical order' do %w{one two three four}.each {|s| create :feature, ftype: 'wibble', subtype: s} %w{five six seven}.each {|s| create :feature, ftype: 'wobble', subtype: s} expect(described_class.subtypes_for('wibble')).to eq(%w{four one three two}) end end end
require 'rails_helper' RSpec.describe Feature, type: :model do describe '.subtypes_for' do it 'finds only the relevant subtypes in alphabetical order' do %w{one two three four}.each {|s| create :feature, ftype: 'wibble', subtype: s} %w{five six seven}.each {|s| create :feature, ftype: 'wobble', subtype: s} expect(described_class.subtypes_for('wibble')).to eq(%w{four one three two}) end end end
Remove specs for old methods
Remove specs for old methods
Ruby
mit
fishpercolator/gsoh,fishpercolator/gsoh,fishpercolator/gsoh
ruby
## Code Before: require 'rails_helper' RSpec.describe Feature, type: :model do describe '.from_nns_data' do let(:nns_data) { {nameofneighbourhoodnetworkscheme: 'OWLS', easting: 427845, northing: 436087} } subject { described_class.from_nns_data(nns_data) } it 'creates a Feature' do expect(subject).to be_a(Feature) end it 'sets the name' do expect(subject.name).to eq('OWLS') end it 'sets the ftype' do expect(subject.ftype).to eq('nns') end it 'sets the lat/lng' do expect(subject.lat).to be_within(0.001).of(53.820) expect(subject.lng).to be_within(0.001).of(-1.578) end end describe '.from_changing_place_data' do let(:cp_data) { {location: 'Central Library', easting: 429859, northing: 433879} } subject { described_class.from_changing_place_data(cp_data) } it 'creates a Feature' do expect(subject).to be_a(Feature) end it 'sets the name' do expect(subject.name).to eq('Central Library') end it 'sets the ftype' do expect(subject.ftype).to eq('changing_place') end it 'sets the lat/lng' do expect(subject.lat).to be_within(0.001).of(53.800) expect(subject.lng).to be_within(0.001).of(-1.548) end end describe '.subtypes_for' do it 'finds only the relevant subtypes in alphabetical order' do %w{one two three four}.each {|s| create :feature, ftype: 'wibble', subtype: s} %w{five six seven}.each {|s| create :feature, ftype: 'wobble', subtype: s} expect(described_class.subtypes_for('wibble')).to eq(%w{four one three two}) end end end ## Instruction: Remove specs for old methods ## Code After: require 'rails_helper' RSpec.describe Feature, type: :model do describe '.subtypes_for' do it 'finds only the relevant subtypes in alphabetical order' do %w{one two three four}.each {|s| create :feature, ftype: 'wibble', subtype: s} %w{five six seven}.each {|s| create :feature, ftype: 'wobble', subtype: s} expect(described_class.subtypes_for('wibble')).to eq(%w{four one three two}) end end end
56a8b900570200e63ee460dd7e2962cba2450b16
preparation/tools/build_assets.py
preparation/tools/build_assets.py
from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert all not in args.resources or len(args.resources) == 1 for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert 'all' not in args.resources or len(args.resources) == 1 if 'all' in args.resources: args.resources = [name.replace('Resource', '') for name in names_registered()] for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
Fix bug with 'all' argument
Fix bug with 'all' argument
Python
mit
hatbot-team/hatbot_resources
python
## Code Before: from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert all not in args.resources or len(args.resources) == 1 for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main() ## Instruction: Fix bug with 'all' argument ## Code After: from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert 'all' not in args.resources or len(args.resources) == 1 if 'all' in args.resources: args.resources = [name.replace('Resource', '') for name in names_registered()] for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
beece5bc2a5dc0ca294f84dbbd59a219ff88268e
Kerner/Kerner/Extensions/UIFont+Extensions.swift
Kerner/Kerner/Extensions/UIFont+Extensions.swift
// // UIFont+Extensions.swift // Kerner // // Created by Taishi Ikai on 2017/09/02. // Copyright © 2017年 Ikai. All rights reserved. // import UIKit import CoreText public extension UIFont { public var altHalf: UIFont { let weight: UIFont.Weight = { var weight = UIFont.Weight.regular let usageAttribute = self.fontDescriptor.fontAttributes[ .init(rawValue: "NSCTFontUIUsageAttribute")] as? String ?? "" switch usageAttribute { case "CTFontEmphasizedUsage", "CTFontBoldUsage": weight = .bold default: break } return weight }() var familyName = self.familyName var pointSize = self.pointSize if familyName.starts(with: ".SF") { familyName = "Hiragino Sans" pointSize = pointSize - 1 } let featureSettings: [[UIFontDescriptor.FeatureKey: Int]] = [ [ .featureIdentifier: kTextSpacingType, .typeIdentifier: kAltHalfWidthTextSelector ] ] let traits: [UIFontDescriptor.TraitKey: CGFloat] = [ .weight: weight.rawValue ] let fontDescriptor = UIFontDescriptor(fontAttributes: [ .family: familyName, .traits: traits, .featureSettings: featureSettings, ]) return UIFont(descriptor: fontDescriptor, size: self.pointSize - 1) } }
// // UIFont+Extensions.swift // Kerner // // Created by Taishi Ikai on 2017/09/02. // Copyright © 2017年 Ikai. All rights reserved. // import UIKit import CoreText public extension UIFont { public var altHalf: UIFont { let weight: UIFont.Weight = { var weight = UIFont.Weight.regular let usageAttribute = self.fontDescriptor.fontAttributes[ .init(rawValue: "NSCTFontUIUsageAttribute")] as? String ?? "" switch usageAttribute { case "CTFontEmphasizedUsage", "CTFontBoldUsage": weight = .bold case "CTFontDemiUsage": weight = .bold default: break } return weight }() var familyName = self.familyName var pointSize = self.pointSize if familyName.starts(with: ".SF") { familyName = "Hiragino Sans" pointSize = pointSize - 1 } let featureSettings: [[UIFontDescriptor.FeatureKey: Int]] = [ [ .featureIdentifier: kTextSpacingType, .typeIdentifier: kAltHalfWidthTextSelector ] ] let traits: [UIFontDescriptor.TraitKey: CGFloat] = [ .weight: weight.rawValue ] let fontDescriptor = UIFontDescriptor(fontAttributes: [ .family: familyName, .traits: traits, .featureSettings: featureSettings, ]) return UIFont(descriptor: fontDescriptor, size: self.pointSize - 1) } }
Fix Hiragino Sans weight corrupted
Fix Hiragino Sans weight corrupted
Swift
mit
ikait/Kerner,ikait/Kerner
swift
## Code Before: // // UIFont+Extensions.swift // Kerner // // Created by Taishi Ikai on 2017/09/02. // Copyright © 2017年 Ikai. All rights reserved. // import UIKit import CoreText public extension UIFont { public var altHalf: UIFont { let weight: UIFont.Weight = { var weight = UIFont.Weight.regular let usageAttribute = self.fontDescriptor.fontAttributes[ .init(rawValue: "NSCTFontUIUsageAttribute")] as? String ?? "" switch usageAttribute { case "CTFontEmphasizedUsage", "CTFontBoldUsage": weight = .bold default: break } return weight }() var familyName = self.familyName var pointSize = self.pointSize if familyName.starts(with: ".SF") { familyName = "Hiragino Sans" pointSize = pointSize - 1 } let featureSettings: [[UIFontDescriptor.FeatureKey: Int]] = [ [ .featureIdentifier: kTextSpacingType, .typeIdentifier: kAltHalfWidthTextSelector ] ] let traits: [UIFontDescriptor.TraitKey: CGFloat] = [ .weight: weight.rawValue ] let fontDescriptor = UIFontDescriptor(fontAttributes: [ .family: familyName, .traits: traits, .featureSettings: featureSettings, ]) return UIFont(descriptor: fontDescriptor, size: self.pointSize - 1) } } ## Instruction: Fix Hiragino Sans weight corrupted ## Code After: // // UIFont+Extensions.swift // Kerner // // Created by Taishi Ikai on 2017/09/02. // Copyright © 2017年 Ikai. All rights reserved. // import UIKit import CoreText public extension UIFont { public var altHalf: UIFont { let weight: UIFont.Weight = { var weight = UIFont.Weight.regular let usageAttribute = self.fontDescriptor.fontAttributes[ .init(rawValue: "NSCTFontUIUsageAttribute")] as? String ?? "" switch usageAttribute { case "CTFontEmphasizedUsage", "CTFontBoldUsage": weight = .bold case "CTFontDemiUsage": weight = .bold default: break } return weight }() var familyName = self.familyName var pointSize = self.pointSize if familyName.starts(with: ".SF") { familyName = "Hiragino Sans" pointSize = pointSize - 1 } let featureSettings: [[UIFontDescriptor.FeatureKey: Int]] = [ [ .featureIdentifier: kTextSpacingType, .typeIdentifier: kAltHalfWidthTextSelector ] ] let traits: [UIFontDescriptor.TraitKey: CGFloat] = [ .weight: weight.rawValue ] let fontDescriptor = UIFontDescriptor(fontAttributes: [ .family: familyName, .traits: traits, .featureSettings: featureSettings, ]) return UIFont(descriptor: fontDescriptor, size: self.pointSize - 1) } }
d471d363fb9572fd72fd9d172aaca7c6d0e9fbd3
app/Providers/RouteServiceProvider.php
app/Providers/RouteServiceProvider.php
<?php namespace DoeSangue\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'DoeSangue\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. */ public function boot() { parent::boot(); } /** * Define the routes for the application. */ public function map() { $this->mapApiRoutes(); // $this->mapWebRoutes(); } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. */ protected function mapWebRoutes() { Route::group( [ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/web.php'); } ); } /** * Define the "api" routes for the application. * * These routes are typically stateless. */ protected function mapApiRoutes() { Route::group( [ 'middleware' => 'api', 'namespace' => $this->namespace, 'prefix' => 'api', ], function ($router) { include base_path('routes/api.php'); } ); } }
<?php namespace DoeSangue\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'DoeSangue\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. */ public function boot() { parent::boot(); } /** * Define the routes for the application. */ public function map() { $this->mapApiRoutes(); // $this->mapWebRoutes(); } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. */ /* protected function mapWebRoutes() { Route::group( [ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/web.php'); } ); } */ /** * Define the "api" routes for the application. * * These routes are typically stateless. */ protected function mapApiRoutes() { Route::group( [ 'middleware' => 'api', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/api.php'); } ); } }
Remove the api prefix
:art: Remove the api prefix [ci skip] This project is always a API Only so we don't need the prefix anymore.
PHP
mit
doesangueorg/doesangue-core,doesangueorg/doesangue-core,doesangueorg/doesangue-core
php
## Code Before: <?php namespace DoeSangue\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'DoeSangue\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. */ public function boot() { parent::boot(); } /** * Define the routes for the application. */ public function map() { $this->mapApiRoutes(); // $this->mapWebRoutes(); } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. */ protected function mapWebRoutes() { Route::group( [ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/web.php'); } ); } /** * Define the "api" routes for the application. * * These routes are typically stateless. */ protected function mapApiRoutes() { Route::group( [ 'middleware' => 'api', 'namespace' => $this->namespace, 'prefix' => 'api', ], function ($router) { include base_path('routes/api.php'); } ); } } ## Instruction: :art: Remove the api prefix [ci skip] This project is always a API Only so we don't need the prefix anymore. ## Code After: <?php namespace DoeSangue\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'DoeSangue\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. */ public function boot() { parent::boot(); } /** * Define the routes for the application. */ public function map() { $this->mapApiRoutes(); // $this->mapWebRoutes(); } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. */ /* protected function mapWebRoutes() { Route::group( [ 'middleware' => 'web', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/web.php'); } ); } */ /** * Define the "api" routes for the application. * * These routes are typically stateless. */ protected function mapApiRoutes() { Route::group( [ 'middleware' => 'api', 'namespace' => $this->namespace, ], function ($router) { include base_path('routes/api.php'); } ); } }
3409aa543b4f0a4c574afd7ff4fdd59d1bd8a4b0
tests/date_tests.py
tests/date_tests.py
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def __init__(self, formatname): super(TestDate, self).__init__() self.formatname = formatname def testMapEntry(self, formatname): """The test ported from date.py""" step = 1 if formatname in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatname] for code, convFunc in date.formats[formatname].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatname)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatname)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) def runTest(self): """method called by unittest""" self.testMapEntry(self.formatname) def suite(): """Setup the test suite and register all test to different instances""" suite = unittest.TestSuite() suite.addTests(TestDate(formatname) for formatname in date.formats) return suite if __name__ == '__main__': try: unittest.TextTestRunner().run(suite()) except SystemExit: pass
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def testMapEntry(self): """Test the validity of the pywikibot.date format maps.""" for formatName in date.formats: step = 1 if formatName in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatName] for code, convFunc in date.formats[formatName].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatName)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatName)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
Revert "Progressing dots to show test is running"
Revert "Progressing dots to show test is running" Breaks tests; https://travis-ci.org/wikimedia/pywikibot-core/builds/26752150 This reverts commit 93379dbf499c58438917728b74862f282c15dba4. Change-Id: Iacb4cc9e6999d265b46c558ed3999c1198f87de0
Python
mit
hasteur/g13bot_tools_new,smalyshev/pywikibot-core,h4ck3rm1k3/pywikibot-core,TridevGuha/pywikibot-core,npdoty/pywikibot,icyflame/batman,valhallasw/pywikibot-core,darthbhyrava/pywikibot-local,hasteur/g13bot_tools_new,xZise/pywikibot-core,npdoty/pywikibot,magul/pywikibot-core,happy5214/pywikibot-core,VcamX/pywikibot-core,h4ck3rm1k3/pywikibot-core,happy5214/pywikibot-core,jayvdb/pywikibot-core,Darkdadaah/pywikibot-core,Darkdadaah/pywikibot-core,hasteur/g13bot_tools_new,emijrp/pywikibot-core,wikimedia/pywikibot-core,jayvdb/pywikibot-core,trishnaguha/pywikibot-core,PersianWikipedia/pywikibot-core,magul/pywikibot-core,wikimedia/pywikibot-core
python
## Code Before: __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def __init__(self, formatname): super(TestDate, self).__init__() self.formatname = formatname def testMapEntry(self, formatname): """The test ported from date.py""" step = 1 if formatname in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatname] for code, convFunc in date.formats[formatname].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatname)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatname)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) def runTest(self): """method called by unittest""" self.testMapEntry(self.formatname) def suite(): """Setup the test suite and register all test to different instances""" suite = unittest.TestSuite() suite.addTests(TestDate(formatname) for formatname in date.formats) return suite if __name__ == '__main__': try: unittest.TextTestRunner().run(suite()) except SystemExit: pass ## Instruction: Revert "Progressing dots to show test is running" Breaks tests; https://travis-ci.org/wikimedia/pywikibot-core/builds/26752150 This reverts commit 93379dbf499c58438917728b74862f282c15dba4. Change-Id: Iacb4cc9e6999d265b46c558ed3999c1198f87de0 ## Code After: __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def testMapEntry(self): """Test the validity of the pywikibot.date format maps.""" for formatName in date.formats: step = 1 if formatName in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatName] for code, convFunc in date.formats[formatName].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatName)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatName)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
3f9cee9a5bf0b9e1a68ed6f493780b95d891f1f1
spec/features/profiles/preferences_spec.rb
spec/features/profiles/preferences_spec.rb
require 'spec_helper' describe 'Profile > Preferences' do let(:user) { create(:user) } before do sign_in(user) visit profile_preferences_path end describe 'User changes their syntax highlighting theme', js: true do it 'creates a flash message' do choose 'user_color_scheme_id_5' expect_preferences_saved_message end it 'updates their preference' do choose 'user_color_scheme_id_5' allowing_for_delay do visit page.current_path expect(page).to have_checked_field('user_color_scheme_id_5') end end end describe 'User changes their default dashboard', js: true do it 'creates a flash message' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' expect_preferences_saved_message end it 'updates their preference' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' allowing_for_delay do find('#logo').click expect(page).to have_content("You don't have starred projects yet") expect(page.current_path).to eq starred_dashboard_projects_path end find('.shortcuts-activity').trigger('click') expect(page).not_to have_content("You don't have starred projects yet") expect(page.current_path).to eq dashboard_projects_path end end def expect_preferences_saved_message page.within('.flash-container') do expect(page).to have_content('Preferences saved.') end end end
require 'spec_helper' describe 'Profile > Preferences', :js do let(:user) { create(:user) } before do sign_in(user) visit profile_preferences_path end describe 'User changes their syntax highlighting theme' do it 'creates a flash message' do choose 'user_color_scheme_id_5' wait_for_requests expect_preferences_saved_message end it 'updates their preference' do choose 'user_color_scheme_id_5' wait_for_requests refresh expect(page).to have_checked_field('user_color_scheme_id_5') end end describe 'User changes their default dashboard' do it 'creates a flash message' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' wait_for_requests expect_preferences_saved_message end it 'updates their preference' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' wait_for_requests find('#logo').click expect(page).to have_content("You don't have starred projects yet") expect(page.current_path).to eq starred_dashboard_projects_path find('.shortcuts-activity').trigger('click') expect(page).not_to have_content("You don't have starred projects yet") expect(page.current_path).to eq dashboard_projects_path end end def expect_preferences_saved_message page.within('.flash-container') do expect(page).to have_content('Preferences saved.') end end end
Fix Profile > Preferences feature specs
Fix Profile > Preferences feature specs Signed-off-by: Rémy Coutable <[email protected]>
Ruby
mit
axilleas/gitlabhq,jirutka/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,dreampet/gitlab,axilleas/gitlabhq,jirutka/gitlabhq,axilleas/gitlabhq,iiet/iiet-git,jirutka/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,t-zuehlsdorff/gitlabhq,iiet/iiet-git,dreampet/gitlab,mmkassem/gitlabhq,dreampet/gitlab,t-zuehlsdorff/gitlabhq,t-zuehlsdorff/gitlabhq,stoplightio/gitlabhq,iiet/iiet-git,stoplightio/gitlabhq,axilleas/gitlabhq,mmkassem/gitlabhq,iiet/iiet-git,jirutka/gitlabhq,dreampet/gitlab,t-zuehlsdorff/gitlabhq
ruby
## Code Before: require 'spec_helper' describe 'Profile > Preferences' do let(:user) { create(:user) } before do sign_in(user) visit profile_preferences_path end describe 'User changes their syntax highlighting theme', js: true do it 'creates a flash message' do choose 'user_color_scheme_id_5' expect_preferences_saved_message end it 'updates their preference' do choose 'user_color_scheme_id_5' allowing_for_delay do visit page.current_path expect(page).to have_checked_field('user_color_scheme_id_5') end end end describe 'User changes their default dashboard', js: true do it 'creates a flash message' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' expect_preferences_saved_message end it 'updates their preference' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' allowing_for_delay do find('#logo').click expect(page).to have_content("You don't have starred projects yet") expect(page.current_path).to eq starred_dashboard_projects_path end find('.shortcuts-activity').trigger('click') expect(page).not_to have_content("You don't have starred projects yet") expect(page.current_path).to eq dashboard_projects_path end end def expect_preferences_saved_message page.within('.flash-container') do expect(page).to have_content('Preferences saved.') end end end ## Instruction: Fix Profile > Preferences feature specs Signed-off-by: Rémy Coutable <[email protected]> ## Code After: require 'spec_helper' describe 'Profile > Preferences', :js do let(:user) { create(:user) } before do sign_in(user) visit profile_preferences_path end describe 'User changes their syntax highlighting theme' do it 'creates a flash message' do choose 'user_color_scheme_id_5' wait_for_requests expect_preferences_saved_message end it 'updates their preference' do choose 'user_color_scheme_id_5' wait_for_requests refresh expect(page).to have_checked_field('user_color_scheme_id_5') end end describe 'User changes their default dashboard' do it 'creates a flash message' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' wait_for_requests expect_preferences_saved_message end it 'updates their preference' do select 'Starred Projects', from: 'user_dashboard' click_button 'Save' wait_for_requests find('#logo').click expect(page).to have_content("You don't have starred projects yet") expect(page.current_path).to eq starred_dashboard_projects_path find('.shortcuts-activity').trigger('click') expect(page).not_to have_content("You don't have starred projects yet") expect(page.current_path).to eq dashboard_projects_path end end def expect_preferences_saved_message page.within('.flash-container') do expect(page).to have_content('Preferences saved.') end end end
00e5ca59b78be88293a9e41f4ad1f9283cc41021
src/main/java/com/royalrangers/controller/SubscribeController.java
src/main/java/com/royalrangers/controller/SubscribeController.java
package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Create subscriber") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Delete subscriber") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Add email to subscribers list") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Remove email from subscribers list") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
Fix API description for Subscribe Controller
Fix API description for Subscribe Controller
Java
apache-2.0
royalrangers-ck/rr-api,royalrangers-ck/rr-api
java
## Code Before: package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Create subscriber") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Delete subscriber") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } } ## Instruction: Fix API description for Subscribe Controller ## Code After: package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Add email to subscribers list") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Remove email from subscribers list") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
1c868c44100f794cd5eb189134df261582a928de
resources/views/pages/solve.blade.php
resources/views/pages/solve.blade.php
@extends('layouts.app') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"> Single trio {{ $trio->id }} </div> <div class="panel-body"> <ul> <li>ID: {{ $trio->id }}</li> <li>sentence1: {{ $trio->sentence1 }}</li> <li>sentence2: {{ $trio->sentence2 }}</li> <li>sentence3: {{ $trio->sentence3 }}</li> {{--<li>answer: {{ $trio->answer }}</li>--}} </ul> <form action="{{ action('SolveController@check', $trio->id) }}" class="form-horizontal" method="post" role="form"> {{ csrf_field() }} <fieldset> <div class="form-group"> <label class="col-md-4 control-label" for="answer">Answer</label> <div class="col-md-4"> <input class="form-control input-md" id="answer" name="answer" placeholder="" value="" required="true" type="text"> </div> </div> <div class="form-group"> <div class="col-md-2 col-md-offset-5"> <button class="btn btn-default" type="submit">Check</button> </div> </div> </fieldset> </form> </div> </div> </div> </div> @endsection
@extends('layouts.app') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"> Trio {{ $trio->id }} </div> <div class="panel-body"> <ul> <li>{{ $trio->sentence1 }}</li> <li>{{ $trio->sentence2 }}</li> <li>{{ $trio->sentence3 }}</li> {{--<li>answer: {{ $trio->answer }}</li>--}} </ul> <form action="{{ action('SolveController@check', $trio->id) }}" class="form-horizontal" method="post" role="form"> {{ csrf_field() }} <fieldset> <div class="form-group"> <label class="col-md-4 control-label" for="answer">Answer</label> <div class="col-md-4"> <input class="form-control input-md" id="answer" name="answer" placeholder="" value="" required="true" type="text"> </div> </div> <div class="form-group"> <div class="text-center"> <button class="btn btn-default" type="submit">Check</button> </div> </div> </fieldset> </form> </div> </div> </div> </div> @endsection
Clean up language, center answer button.
Clean up language, center answer button.
PHP
mit
AKAI-TRIOS/trios,AKAI-TRIOS/trios,AKAI-TRIOS/trios
php
## Code Before: @extends('layouts.app') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"> Single trio {{ $trio->id }} </div> <div class="panel-body"> <ul> <li>ID: {{ $trio->id }}</li> <li>sentence1: {{ $trio->sentence1 }}</li> <li>sentence2: {{ $trio->sentence2 }}</li> <li>sentence3: {{ $trio->sentence3 }}</li> {{--<li>answer: {{ $trio->answer }}</li>--}} </ul> <form action="{{ action('SolveController@check', $trio->id) }}" class="form-horizontal" method="post" role="form"> {{ csrf_field() }} <fieldset> <div class="form-group"> <label class="col-md-4 control-label" for="answer">Answer</label> <div class="col-md-4"> <input class="form-control input-md" id="answer" name="answer" placeholder="" value="" required="true" type="text"> </div> </div> <div class="form-group"> <div class="col-md-2 col-md-offset-5"> <button class="btn btn-default" type="submit">Check</button> </div> </div> </fieldset> </form> </div> </div> </div> </div> @endsection ## Instruction: Clean up language, center answer button. ## Code After: @extends('layouts.app') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"> Trio {{ $trio->id }} </div> <div class="panel-body"> <ul> <li>{{ $trio->sentence1 }}</li> <li>{{ $trio->sentence2 }}</li> <li>{{ $trio->sentence3 }}</li> {{--<li>answer: {{ $trio->answer }}</li>--}} </ul> <form action="{{ action('SolveController@check', $trio->id) }}" class="form-horizontal" method="post" role="form"> {{ csrf_field() }} <fieldset> <div class="form-group"> <label class="col-md-4 control-label" for="answer">Answer</label> <div class="col-md-4"> <input class="form-control input-md" id="answer" name="answer" placeholder="" value="" required="true" type="text"> </div> </div> <div class="form-group"> <div class="text-center"> <button class="btn btn-default" type="submit">Check</button> </div> </div> </fieldset> </form> </div> </div> </div> </div> @endsection
3781282b9c253c78551f720ab20c6771b25ebe64
Resources/public/js/profile.js
Resources/public/js/profile.js
$(function() { $('#btn-apigen').on('click', function(e) { var el = $(this); $.get(el.attr('href'), function (data) { el.prev().text(data); }) return false; }); $('#btn-remove-profile').on('click', function(e) { var el = $(this), message = el.attr('data-message'), doAction = function() { $.ajax({ url: Routing.generate('oro_api_delete_profile', { id: el.attr('data-id') }), type: 'DELETE', success: function (data) { window.location.href = Routing.generate('oro_user_index'); } }); }; if (!_.isUndefined(Oro.BootstrapModal)) { confirm = new Oro.BootstrapModal({ title: 'Delete Confirmation', content: message, okText: 'Yes, Delete' }); confirm.on('ok', doAction); confirm.open(); } else if (window.confirm(message)) { doAction(); } return false; }); $('#roles-list input') .on('click', function() { var inputs = $(this).closest('.controls'); inputs.find(':checkbox').attr('required', inputs.find(':checked').length > 0 ? null : 'required'); }) .triggerHandler('click'); $('#btn-enable input').on('change', function(e) { // if ($(this).is(':checked')) { // // } $('.status-enabled').toggleClass('hide'); $('.status-disabled').toggleClass('hide'); }); });
$(function() { $('#btn-apigen').on('click', function(e) { var el = $(this); $.get(el.attr('href'), function (data) { el.prev().text(data); }) return false; }); $('#btn-remove-profile').on('click', function(e) { var el = $(this), message = el.attr('data-message'), doAction = function() { $.ajax({ url: Routing.generate('oro_api_delete_profile', { id: el.attr('data-id') }), type: 'DELETE', success: function (data) { window.location.href = Routing.generate('oro_user_index'); } }); }; if (!_.isUndefined(Oro.BootstrapModal)) { var confirm = new Oro.BootstrapModal({ title: 'Delete Confirmation', content: message, okText: 'Yes, Delete', cancelText: 'Cancel' }); confirm.on('ok', doAction); confirm.open(); } else if (window.confirm(message)) { doAction(); } return false; }); $('#roles-list input') .on('click', function() { var inputs = $(this).closest('.controls'); inputs.find(':checkbox').attr('required', inputs.find(':checked').length > 0 ? null : 'required'); }) .triggerHandler('click'); $('#btn-enable input').on('change', function(e) { // if ($(this).is(':checked')) { // // } $('.status-enabled').toggleClass('hide'); $('.status-disabled').toggleClass('hide'); }); });
Delete confirmation message is not useful - added "Cancel" button on delete modal
BAP-687: Delete confirmation message is not useful - added "Cancel" button on delete modal
JavaScript
mit
northdakota/platform,Djamy/platform,mszajner/platform,morontt/platform,hugeval/platform,morontt/platform,orocrm/platform,geoffroycochard/platform,ramunasd/platform,trustify/oroplatform,northdakota/platform,mszajner/platform,Djamy/platform,akeneo/platform,mszajner/platform,hugeval/platform,trustify/oroplatform,orocrm/platform,geoffroycochard/platform,trustify/oroplatform,morontt/platform,geoffroycochard/platform,orocrm/platform,hugeval/platform,akeneo/platform,ramunasd/platform,umpirsky/platform,Djamy/platform,akeneo/platform,2ndkauboy/platform,northdakota/platform,2ndkauboy/platform,2ndkauboy/platform,ramunasd/platform,umpirsky/platform
javascript
## Code Before: $(function() { $('#btn-apigen').on('click', function(e) { var el = $(this); $.get(el.attr('href'), function (data) { el.prev().text(data); }) return false; }); $('#btn-remove-profile').on('click', function(e) { var el = $(this), message = el.attr('data-message'), doAction = function() { $.ajax({ url: Routing.generate('oro_api_delete_profile', { id: el.attr('data-id') }), type: 'DELETE', success: function (data) { window.location.href = Routing.generate('oro_user_index'); } }); }; if (!_.isUndefined(Oro.BootstrapModal)) { confirm = new Oro.BootstrapModal({ title: 'Delete Confirmation', content: message, okText: 'Yes, Delete' }); confirm.on('ok', doAction); confirm.open(); } else if (window.confirm(message)) { doAction(); } return false; }); $('#roles-list input') .on('click', function() { var inputs = $(this).closest('.controls'); inputs.find(':checkbox').attr('required', inputs.find(':checked').length > 0 ? null : 'required'); }) .triggerHandler('click'); $('#btn-enable input').on('change', function(e) { // if ($(this).is(':checked')) { // // } $('.status-enabled').toggleClass('hide'); $('.status-disabled').toggleClass('hide'); }); }); ## Instruction: BAP-687: Delete confirmation message is not useful - added "Cancel" button on delete modal ## Code After: $(function() { $('#btn-apigen').on('click', function(e) { var el = $(this); $.get(el.attr('href'), function (data) { el.prev().text(data); }) return false; }); $('#btn-remove-profile').on('click', function(e) { var el = $(this), message = el.attr('data-message'), doAction = function() { $.ajax({ url: Routing.generate('oro_api_delete_profile', { id: el.attr('data-id') }), type: 'DELETE', success: function (data) { window.location.href = Routing.generate('oro_user_index'); } }); }; if (!_.isUndefined(Oro.BootstrapModal)) { var confirm = new Oro.BootstrapModal({ title: 'Delete Confirmation', content: message, okText: 'Yes, Delete', cancelText: 'Cancel' }); confirm.on('ok', doAction); confirm.open(); } else if (window.confirm(message)) { doAction(); } return false; }); $('#roles-list input') .on('click', function() { var inputs = $(this).closest('.controls'); inputs.find(':checkbox').attr('required', inputs.find(':checked').length > 0 ? null : 'required'); }) .triggerHandler('click'); $('#btn-enable input').on('change', function(e) { // if ($(this).is(':checked')) { // // } $('.status-enabled').toggleClass('hide'); $('.status-disabled').toggleClass('hide'); }); });
1eddfa3be34d73d380d1a12b7bc8606da1a9e271
ckanext/orgdashboards/templates/dashboards/snippets/facet_list.html
ckanext/orgdashboards/templates/dashboards/snippets/facet_list.html
{# Construct a facet module populated with links to filtered results. name The field name identifying the facet field, eg. "tags" #} {% with items = h.get_facet_items_dict(name.value) %} <div class="col-md-2"> <select class="form-control orgdashboards-filters {{ organization_name|lower }}"> {% block facet_list_items %} {% with items = h.get_facet_items_dict(name.value) %} {% set extras={'name': c.name} %} <option value="{{ h.remove_url_param(key=name.value, controller=c.controller, action=c.action, extras=extras) }}">{{ name.name }}</option> {% if items %} {% for item in items %} {% set href = h.orgdashboards_replace_or_add_url_param(name.value, item.name) %} {% set label = label_function(item) if label_function else item.display_name %} {% set label_truncated = h.truncate(label, 22) if not label_function else label %} {% if item.active %} <option selected="selected" value="{{ href }}">{{ label }}</option> {% else %} <option value="{{ href }}">{{ label }}</option> {% endif %} {% endfor %} {% endif %} {% endwith %} {% endblock %} </select> </div> {% endwith %}
{# Construct a facet module populated with links to filtered results. name The field name identifying the facet field, eg. "tags" #} {% with items = h.get_facet_items_dict(name.value) %} <div class="col-md-2"> <select class="form-control orgdashboards-filters {{ organization_name|lower }}"> {% block facet_list_items %} {% with items = h.get_facet_items_dict(name.value) %} {% set extras={'name': c.name} %} <option value="{{ h.remove_url_param(key=name.value, controller=c.controller, action=c.action, extras=extras) }}">{{ name.name }}</option> {% if items %} {% for item in items %} {% set href = h.orgdashboards_replace_or_add_url_param(name=name.value, value=item.name, params=request.params.items(), controller=c.controller, action=c.action, context_name=c.name) %} {% set label = label_function(item) if label_function else item.display_name %} {% set label_truncated = h.truncate(label, 22) if not label_function else label %} {% if item.active %} <option selected="selected" value="{{ href }}">{{ label }}</option> {% else %} <option value="{{ href }}">{{ label }}</option> {% endif %} {% endfor %} {% endif %} {% endwith %} {% endblock %} </select> </div> {% endwith %}
Add additional parameters for orgdashboards_replace_or_add_url_param
Add additional parameters for orgdashboards_replace_or_add_url_param
HTML
agpl-3.0
ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards
html
## Code Before: {# Construct a facet module populated with links to filtered results. name The field name identifying the facet field, eg. "tags" #} {% with items = h.get_facet_items_dict(name.value) %} <div class="col-md-2"> <select class="form-control orgdashboards-filters {{ organization_name|lower }}"> {% block facet_list_items %} {% with items = h.get_facet_items_dict(name.value) %} {% set extras={'name': c.name} %} <option value="{{ h.remove_url_param(key=name.value, controller=c.controller, action=c.action, extras=extras) }}">{{ name.name }}</option> {% if items %} {% for item in items %} {% set href = h.orgdashboards_replace_or_add_url_param(name.value, item.name) %} {% set label = label_function(item) if label_function else item.display_name %} {% set label_truncated = h.truncate(label, 22) if not label_function else label %} {% if item.active %} <option selected="selected" value="{{ href }}">{{ label }}</option> {% else %} <option value="{{ href }}">{{ label }}</option> {% endif %} {% endfor %} {% endif %} {% endwith %} {% endblock %} </select> </div> {% endwith %} ## Instruction: Add additional parameters for orgdashboards_replace_or_add_url_param ## Code After: {# Construct a facet module populated with links to filtered results. name The field name identifying the facet field, eg. "tags" #} {% with items = h.get_facet_items_dict(name.value) %} <div class="col-md-2"> <select class="form-control orgdashboards-filters {{ organization_name|lower }}"> {% block facet_list_items %} {% with items = h.get_facet_items_dict(name.value) %} {% set extras={'name': c.name} %} <option value="{{ h.remove_url_param(key=name.value, controller=c.controller, action=c.action, extras=extras) }}">{{ name.name }}</option> {% if items %} {% for item in items %} {% set href = h.orgdashboards_replace_or_add_url_param(name=name.value, value=item.name, params=request.params.items(), controller=c.controller, action=c.action, context_name=c.name) %} {% set label = label_function(item) if label_function else item.display_name %} {% set label_truncated = h.truncate(label, 22) if not label_function else label %} {% if item.active %} <option selected="selected" value="{{ href }}">{{ label }}</option> {% else %} <option value="{{ href }}">{{ label }}</option> {% endif %} {% endfor %} {% endif %} {% endwith %} {% endblock %} </select> </div> {% endwith %}
88df3c35d0a4da35b881d5a5ea57af94aa15f6a4
src/c/admin-user-detail.js
src/c/admin-user-detail.js
window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'state', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: 'deleted', model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) ]), ]); } }; }(window.m, window._, window.c));
window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'state', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: 'deleted', model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), (item.deactivated_at) ? m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) : '' ]), ]); } }; }(window.m, window._, window.c));
Add validation to show reactivate button to AdminUser list
Add validation to show reactivate button to AdminUser list
JavaScript
mit
adrianob/catarse.js,sushant12/catarse.js,catarse/catarse.js,mikesmayer/cs2.js,thiagocatarse/catarse.js,vicnicius/catarse_admin,catarse/catarse_admin,vicnicius/catarse.js
javascript
## Code Before: window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'state', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: 'deleted', model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) ]), ]); } }; }(window.m, window._, window.c)); ## Instruction: Add validation to show reactivate button to AdminUser list ## Code After: window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'state', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: 'deleted', model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), (item.deactivated_at) ? m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) : '' ]), ]); } }; }(window.m, window._, window.c));
7796ea1f9f17fef73a5779b2827762e72d1c03b6
app/controllers/alchemy/api/elements_controller.rb
app/controllers/alchemy/api/elements_controller.rb
module Alchemy class Api::ElementsController < Api::BaseController # Returns all elements as json object # # You can either load all or only these for :page_id param # # If you want to only load a specific type of element pass ?named=an_element_name # def index if params[:page_id].present? @page = Page.find(params[:page_id]) @elements = @page.elements.not_nested else @elements = Element.not_nested.joins(:page_version).merge(PageVersion.published) end # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:named].present? @elements = @elements.named(params[:named]) end @elements = @elements.includes(*element_includes) render json: @elements, adapter: :json, root: "elements" end # Returns a json object for element # def show @element = Element.where(id: params[:id]).includes(*element_includes).first authorize! :show, @element respond_with @element end private def element_includes [ { nested_elements: [ { contents: { essence: :ingredient_association, }, }, :tags, ], }, { contents: { essence: :ingredient_association, }, }, :tags, ] end end end
module Alchemy class Api::ElementsController < Api::BaseController # Returns all elements as json object # # You can either load all or only these for :page_id param # # If you want to only load a specific type of element pass ?named=an_element_name # def index if params[:page_id].present? @page = Page.find(params[:page_id]) @elements = @page.elements.not_nested else @elements = Element.not_nested.joins(:page_version).merge(PageVersion.published) end # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:named].present? @elements = @elements.named(params[:named]) end @elements = @elements.includes(*element_includes).order(:position) render json: @elements, adapter: :json, root: "elements" end # Returns a json object for element # def show @element = Element.where(id: params[:id]).includes(*element_includes).first authorize! :show, @element respond_with @element end private def element_includes [ { nested_elements: [ { contents: { essence: :ingredient_association, }, }, :tags, ], }, { contents: { essence: :ingredient_association, }, }, :tags, ] end end end
Return elements in api controller ordered by position
Return elements in api controller ordered by position This would be expected anyway and fixes a flaky sepc.
Ruby
bsd-3-clause
robinboening/alchemy_cms,robinboening/alchemy_cms,AlchemyCMS/alchemy_cms,AlchemyCMS/alchemy_cms,robinboening/alchemy_cms,AlchemyCMS/alchemy_cms
ruby
## Code Before: module Alchemy class Api::ElementsController < Api::BaseController # Returns all elements as json object # # You can either load all or only these for :page_id param # # If you want to only load a specific type of element pass ?named=an_element_name # def index if params[:page_id].present? @page = Page.find(params[:page_id]) @elements = @page.elements.not_nested else @elements = Element.not_nested.joins(:page_version).merge(PageVersion.published) end # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:named].present? @elements = @elements.named(params[:named]) end @elements = @elements.includes(*element_includes) render json: @elements, adapter: :json, root: "elements" end # Returns a json object for element # def show @element = Element.where(id: params[:id]).includes(*element_includes).first authorize! :show, @element respond_with @element end private def element_includes [ { nested_elements: [ { contents: { essence: :ingredient_association, }, }, :tags, ], }, { contents: { essence: :ingredient_association, }, }, :tags, ] end end end ## Instruction: Return elements in api controller ordered by position This would be expected anyway and fixes a flaky sepc. ## Code After: module Alchemy class Api::ElementsController < Api::BaseController # Returns all elements as json object # # You can either load all or only these for :page_id param # # If you want to only load a specific type of element pass ?named=an_element_name # def index if params[:page_id].present? @page = Page.find(params[:page_id]) @elements = @page.elements.not_nested else @elements = Element.not_nested.joins(:page_version).merge(PageVersion.published) end # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:named].present? @elements = @elements.named(params[:named]) end @elements = @elements.includes(*element_includes).order(:position) render json: @elements, adapter: :json, root: "elements" end # Returns a json object for element # def show @element = Element.where(id: params[:id]).includes(*element_includes).first authorize! :show, @element respond_with @element end private def element_includes [ { nested_elements: [ { contents: { essence: :ingredient_association, }, }, :tags, ], }, { contents: { essence: :ingredient_association, }, }, :tags, ] end end end
9dbc810cb9036ab30aa9640c2f3d0b8f11974d68
lib/conditional_validation/validation_accessor.rb
lib/conditional_validation/validation_accessor.rb
module ConditionalValidation module ValidationAccessor extend ActiveSupport::Concern module ClassMethods # Macro method for defining an attr_accessor and various # enable/disable/predicate methods that wrap the attr_acessor for # determining when to run a set of validation on an ActiveRecord model. # # @param args [*accessors] the section names for which to define # validation accessors for # # @example # class User # validation_accessor :address_attributes # end # # # => Defines the following methods on instances of the User class: # # enable_address_attributes_validation # # disable_address_attributes_validation # # validate_on_address_attributes? def validation_accessor(*accessors) attr_accessor *accessors.map { |accessor| "_#{accessor}_validation_accessor" } accessors.each do |accessor| class_eval <<-METHODS, __FILE__, __LINE__ + 1 def enable_#{accessor}_validation self._#{accessor}_validation_accessor = true self end def disable_#{accessor}_validation self._#{accessor}_validation_accessor = false self end def validate_on_#{accessor}? !!_#{accessor}_validation_accessor end METHODS end end deprecate validation_accessor: :validation_flag, deprecator: ActiveSupport::Deprecation.new('1.0', 'Conditional Validation') end end end ActiveRecord::Base.send(:include, ConditionalValidation::ValidationAccessor)
module ConditionalValidation module ValidationAccessor extend ActiveSupport::Concern module ClassMethods # Macro method for defining an attr_accessor and various # enable/disable/predicate methods that wrap the attr_acessor for # determining when to run a set of validation on an ActiveRecord model. # # @param args [*accessors] the section names for which to define # validation accessors for # # @example # class User # validation_accessor :address_attributes # end # # # => Defines the following methods on instances of the User class: # # enable_address_attributes_validation # # disable_address_attributes_validation # # validate_on_address_attributes? def validation_accessor(*accessors) attr_accessor *accessors.map { |accessor| "_#{accessor}_validation_accessor" } accessors.each do |accessor| class_eval <<-METHODS, __FILE__, __LINE__ + 1 def enable_#{accessor}_validation self._#{accessor}_validation_accessor = true self end def disable_#{accessor}_validation self._#{accessor}_validation_accessor = false self end def validate_on_#{accessor}? !!_#{accessor}_validation_accessor end METHODS end end if ActiveSupport::Deprecation.respond_to?(:new) deprecate validation_accessor: :validation_flag, deprecator: ActiveSupport::Deprecation.new('1.0', 'Conditional Validation') end end end end ActiveRecord::Base.send(:include, ConditionalValidation::ValidationAccessor)
Remove deprecation warning for Rails 3.2
Remove deprecation warning for Rails 3.2 Rails 3.2's ActiveSupport::Deprecation is a module and not a class. So it cannot be passed as a deprecator object. Just removing the attempt to display this deprecation for Rails 3.2 for now.
Ruby
mit
pdobb/conditional_validation,pdobb/conditional_validation
ruby
## Code Before: module ConditionalValidation module ValidationAccessor extend ActiveSupport::Concern module ClassMethods # Macro method for defining an attr_accessor and various # enable/disable/predicate methods that wrap the attr_acessor for # determining when to run a set of validation on an ActiveRecord model. # # @param args [*accessors] the section names for which to define # validation accessors for # # @example # class User # validation_accessor :address_attributes # end # # # => Defines the following methods on instances of the User class: # # enable_address_attributes_validation # # disable_address_attributes_validation # # validate_on_address_attributes? def validation_accessor(*accessors) attr_accessor *accessors.map { |accessor| "_#{accessor}_validation_accessor" } accessors.each do |accessor| class_eval <<-METHODS, __FILE__, __LINE__ + 1 def enable_#{accessor}_validation self._#{accessor}_validation_accessor = true self end def disable_#{accessor}_validation self._#{accessor}_validation_accessor = false self end def validate_on_#{accessor}? !!_#{accessor}_validation_accessor end METHODS end end deprecate validation_accessor: :validation_flag, deprecator: ActiveSupport::Deprecation.new('1.0', 'Conditional Validation') end end end ActiveRecord::Base.send(:include, ConditionalValidation::ValidationAccessor) ## Instruction: Remove deprecation warning for Rails 3.2 Rails 3.2's ActiveSupport::Deprecation is a module and not a class. So it cannot be passed as a deprecator object. Just removing the attempt to display this deprecation for Rails 3.2 for now. ## Code After: module ConditionalValidation module ValidationAccessor extend ActiveSupport::Concern module ClassMethods # Macro method for defining an attr_accessor and various # enable/disable/predicate methods that wrap the attr_acessor for # determining when to run a set of validation on an ActiveRecord model. # # @param args [*accessors] the section names for which to define # validation accessors for # # @example # class User # validation_accessor :address_attributes # end # # # => Defines the following methods on instances of the User class: # # enable_address_attributes_validation # # disable_address_attributes_validation # # validate_on_address_attributes? def validation_accessor(*accessors) attr_accessor *accessors.map { |accessor| "_#{accessor}_validation_accessor" } accessors.each do |accessor| class_eval <<-METHODS, __FILE__, __LINE__ + 1 def enable_#{accessor}_validation self._#{accessor}_validation_accessor = true self end def disable_#{accessor}_validation self._#{accessor}_validation_accessor = false self end def validate_on_#{accessor}? !!_#{accessor}_validation_accessor end METHODS end end if ActiveSupport::Deprecation.respond_to?(:new) deprecate validation_accessor: :validation_flag, deprecator: ActiveSupport::Deprecation.new('1.0', 'Conditional Validation') end end end end ActiveRecord::Base.send(:include, ConditionalValidation::ValidationAccessor)
bf56aa46d5a9138ea873f904fd9b47043fb4c7dd
core/src/test/java/arez/MessageCollector.java
core/src/test/java/arez/MessageCollector.java
package arez; import java.io.File; import javax.annotation.Nonnull; import org.realityforge.braincheck.GuardMessageCollector; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import static org.testng.Assert.*; public final class MessageCollector extends TestListenerAdapter implements ITestListener { @Nonnull private final GuardMessageCollector _messages = createCollector(); @Override public void onTestStart( @Nonnull final ITestResult result ) { if ( shouldCheckDiagnosticMessages() ) { _messages.onTestStart(); } } @Override public void onTestSuccess( @Nonnull final ITestResult result ) { if ( shouldCheckDiagnosticMessages() ) { _messages.onTestComplete(); } } @Override public void onStart( @Nonnull final ITestContext context ) { if ( shouldCheckDiagnosticMessages() ) { _messages.onTestSuiteStart(); } } @Override public void onFinish( @Nonnull final ITestContext context ) { if ( 0 == context.getFailedTests().size() && shouldCheckDiagnosticMessages() ) { _messages.onTestSuiteComplete(); } } private boolean shouldCheckDiagnosticMessages() { return System.getProperty( "arez.check_diagnostic_messages", "true" ).equals( "true" ); } @Nonnull private GuardMessageCollector createCollector() { final boolean saveIfChanged = "true".equals( System.getProperty( "arez.output_fixture_data", "false" ) ); final String fixtureDir = System.getProperty( "arez.diagnostic_messages_file" ); assertNotNull( fixtureDir, "Expected System.getProperty( \"arez.diagnostic_messages_file\" ) to return location of diagnostic messages file" ); return new GuardMessageCollector( "Arez", new File( fixtureDir ), saveIfChanged ); } }
package arez; import java.io.File; import javax.annotation.Nonnull; import org.realityforge.braincheck.AbstractTestNGMessageCollector; import org.realityforge.braincheck.GuardMessageCollector; import static org.testng.Assert.*; public final class MessageCollector extends AbstractTestNGMessageCollector { @Override protected boolean shouldCheckDiagnosticMessages() { return System.getProperty( "arez.check_diagnostic_messages", "true" ).equals( "true" ); } @Nonnull @Override protected GuardMessageCollector createCollector() { final boolean saveIfChanged = "true".equals( System.getProperty( "arez.output_fixture_data", "false" ) ); final String fixtureDir = System.getProperty( "arez.diagnostic_messages_file" ); assertNotNull( fixtureDir, "Expected System.getProperty( \"arez.diagnostic_messages_file\" ) to return location of diagnostic messages file" ); return new GuardMessageCollector( "Arez", new File( fixtureDir ), saveIfChanged ); } }
Move to support provided by latest Braincheck
Move to support provided by latest Braincheck
Java
apache-2.0
realityforge/arez,realityforge/arez,realityforge/arez
java
## Code Before: package arez; import java.io.File; import javax.annotation.Nonnull; import org.realityforge.braincheck.GuardMessageCollector; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import static org.testng.Assert.*; public final class MessageCollector extends TestListenerAdapter implements ITestListener { @Nonnull private final GuardMessageCollector _messages = createCollector(); @Override public void onTestStart( @Nonnull final ITestResult result ) { if ( shouldCheckDiagnosticMessages() ) { _messages.onTestStart(); } } @Override public void onTestSuccess( @Nonnull final ITestResult result ) { if ( shouldCheckDiagnosticMessages() ) { _messages.onTestComplete(); } } @Override public void onStart( @Nonnull final ITestContext context ) { if ( shouldCheckDiagnosticMessages() ) { _messages.onTestSuiteStart(); } } @Override public void onFinish( @Nonnull final ITestContext context ) { if ( 0 == context.getFailedTests().size() && shouldCheckDiagnosticMessages() ) { _messages.onTestSuiteComplete(); } } private boolean shouldCheckDiagnosticMessages() { return System.getProperty( "arez.check_diagnostic_messages", "true" ).equals( "true" ); } @Nonnull private GuardMessageCollector createCollector() { final boolean saveIfChanged = "true".equals( System.getProperty( "arez.output_fixture_data", "false" ) ); final String fixtureDir = System.getProperty( "arez.diagnostic_messages_file" ); assertNotNull( fixtureDir, "Expected System.getProperty( \"arez.diagnostic_messages_file\" ) to return location of diagnostic messages file" ); return new GuardMessageCollector( "Arez", new File( fixtureDir ), saveIfChanged ); } } ## Instruction: Move to support provided by latest Braincheck ## Code After: package arez; import java.io.File; import javax.annotation.Nonnull; import org.realityforge.braincheck.AbstractTestNGMessageCollector; import org.realityforge.braincheck.GuardMessageCollector; import static org.testng.Assert.*; public final class MessageCollector extends AbstractTestNGMessageCollector { @Override protected boolean shouldCheckDiagnosticMessages() { return System.getProperty( "arez.check_diagnostic_messages", "true" ).equals( "true" ); } @Nonnull @Override protected GuardMessageCollector createCollector() { final boolean saveIfChanged = "true".equals( System.getProperty( "arez.output_fixture_data", "false" ) ); final String fixtureDir = System.getProperty( "arez.diagnostic_messages_file" ); assertNotNull( fixtureDir, "Expected System.getProperty( \"arez.diagnostic_messages_file\" ) to return location of diagnostic messages file" ); return new GuardMessageCollector( "Arez", new File( fixtureDir ), saveIfChanged ); } }
63abcc1a7a806e0665ce9382ff9a0ec480cd9576
hipstore/src/test/java/tech/lab23/hipstore/EntityStorageTest.kt
hipstore/src/test/java/tech/lab23/hipstore/EntityStorageTest.kt
package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } @Test fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } }
package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test @Throws(Exception::class) fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } @Test @Throws(Exception::class) fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } }
Implement unit tests for EntityStorage
Implement unit tests for EntityStorage
Kotlin
apache-2.0
samiuelson/Hipstore,samiuelson/Hipstore
kotlin
## Code Before: package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } @Test fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } } ## Instruction: Implement unit tests for EntityStorage ## Code After: package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test @Throws(Exception::class) fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } @Test @Throws(Exception::class) fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } }
d1cabe515d473b6f2766c06d9e1b74efd0f14c89
kakao/src/main/kotlin/com/agoda/kakao/delegate/Delegate.kt
kakao/src/main/kotlin/com/agoda/kakao/delegate/Delegate.kt
package com.agoda.kakao.delegate import com.agoda.kakao.intercept.Interceptor /** * Base delegate interface. * * Provides functionality of aggregating interceptors and invoking them on `check` * and `perform` invocations. * * @see Interceptor */ interface Delegate<T, C, P> { var interaction: T fun viewInterceptor(): Interceptor<T, C, P>? fun screenInterceptor(): Interceptor<T, C, P>? fun kakaoInterceptor(): Interceptor<T, C, P>? fun interceptCheck(assertion: C): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onCheck?.let { it.second(interaction, assertion) if (it.first) return true } } return false } fun interceptPerform(action: P): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onPerform?.let { it.second(interaction, action) if (it.first) return true } } return false } private fun interceptors(): List<Interceptor<T, C, P>> = mutableListOf<Interceptor<T, C, P>>().also { list -> viewInterceptor()?.let { list.add(it) } screenInterceptor()?.let { list.add(it) } kakaoInterceptor()?.let { list.add(it) } } }
package com.agoda.kakao.delegate import com.agoda.kakao.intercept.Interceptor /** * Base delegate interface. * * Provides functionality of aggregating interceptors and invoking them on `check` * and `perform` invocations. * * @see Interceptor */ interface Delegate<T, C, P> { var interaction: T fun viewInterceptor(): Interceptor<T, C, P>? fun screenInterceptor(): Interceptor<T, C, P>? fun kakaoInterceptor(): Interceptor<T, C, P>? fun interceptCheck(assertion: C): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onCheck?.let { it.second(interaction, assertion) if (it.first) return true } } return false } fun interceptPerform(action: P): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onPerform?.let { it.second(interaction, action) if (it.first) return true } } return false } private fun interceptors() = mutableListOf<Interceptor<T, C, P>>().also { list -> viewInterceptor()?.let { list.add(it) } screenInterceptor()?.let { list.add(it) } kakaoInterceptor()?.let { list.add(it) } } }
Remove return type form aggregation function
Remove return type form aggregation function
Kotlin
apache-2.0
agoda-com/Kakao
kotlin
## Code Before: package com.agoda.kakao.delegate import com.agoda.kakao.intercept.Interceptor /** * Base delegate interface. * * Provides functionality of aggregating interceptors and invoking them on `check` * and `perform` invocations. * * @see Interceptor */ interface Delegate<T, C, P> { var interaction: T fun viewInterceptor(): Interceptor<T, C, P>? fun screenInterceptor(): Interceptor<T, C, P>? fun kakaoInterceptor(): Interceptor<T, C, P>? fun interceptCheck(assertion: C): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onCheck?.let { it.second(interaction, assertion) if (it.first) return true } } return false } fun interceptPerform(action: P): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onPerform?.let { it.second(interaction, action) if (it.first) return true } } return false } private fun interceptors(): List<Interceptor<T, C, P>> = mutableListOf<Interceptor<T, C, P>>().also { list -> viewInterceptor()?.let { list.add(it) } screenInterceptor()?.let { list.add(it) } kakaoInterceptor()?.let { list.add(it) } } } ## Instruction: Remove return type form aggregation function ## Code After: package com.agoda.kakao.delegate import com.agoda.kakao.intercept.Interceptor /** * Base delegate interface. * * Provides functionality of aggregating interceptors and invoking them on `check` * and `perform` invocations. * * @see Interceptor */ interface Delegate<T, C, P> { var interaction: T fun viewInterceptor(): Interceptor<T, C, P>? fun screenInterceptor(): Interceptor<T, C, P>? fun kakaoInterceptor(): Interceptor<T, C, P>? fun interceptCheck(assertion: C): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onCheck?.let { it.second(interaction, assertion) if (it.first) return true } } return false } fun interceptPerform(action: P): Boolean { interceptors().forEach { interceptor -> interceptor.onAll?.let { it.second(interaction) if (it.first) return true } interceptor.onPerform?.let { it.second(interaction, action) if (it.first) return true } } return false } private fun interceptors() = mutableListOf<Interceptor<T, C, P>>().also { list -> viewInterceptor()?.let { list.add(it) } screenInterceptor()?.let { list.add(it) } kakaoInterceptor()?.let { list.add(it) } } }
f29b65fa18ae5bcae352ad1050a5b83d8ffffd53
modules/vf_audio/sources/vf_SampleSource.h
modules/vf_audio/sources/vf_SampleSource.h
/*============================================================================*/ /* Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib. See the file GNU_GPL_v2.txt for full licensing terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*============================================================================*/ #ifndef VF_SAMPLESOURCE_VFHEADER #define VF_SAMPLESOURCE_VFHEADER //============================================================================== /** Abstract source of audio samples. This interface is used to retrieve sequentual raw audio samples from an abstract source. It is intended as a facade for @ref AudioSource, with these features: - No thread safety; the caller is responsible for all synchronization. - The preparation state feature is removed (along with its methods). @ingroup vf_audio */ class SampleSource { public: /** Read the next block of samples. */ virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0; }; #endif
/*============================================================================*/ /* Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib. See the file GNU_GPL_v2.txt for full licensing terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*============================================================================*/ #ifndef VF_SAMPLESOURCE_VFHEADER #define VF_SAMPLESOURCE_VFHEADER //============================================================================== /** Abstract source of audio samples. This interface is used to retrieve sequentual raw audio samples from an abstract source. It is intended as a facade for @ref AudioSource, with these features: - No thread safety; the caller is responsible for all synchronization. - The preparation state feature is removed (along with its methods). @ingroup vf_audio */ class SampleSource { public: virtual ~SampleSource () { } /** Read the next block of samples. */ virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0; }; #endif
Make dtor virtual in SampleSource
Make dtor virtual in SampleSource
C
mit
vinniefalco/VFLib,spthaolt/VFLib,spthaolt/VFLib,vinniefalco/VFLib
c
## Code Before: /*============================================================================*/ /* Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib. See the file GNU_GPL_v2.txt for full licensing terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*============================================================================*/ #ifndef VF_SAMPLESOURCE_VFHEADER #define VF_SAMPLESOURCE_VFHEADER //============================================================================== /** Abstract source of audio samples. This interface is used to retrieve sequentual raw audio samples from an abstract source. It is intended as a facade for @ref AudioSource, with these features: - No thread safety; the caller is responsible for all synchronization. - The preparation state feature is removed (along with its methods). @ingroup vf_audio */ class SampleSource { public: /** Read the next block of samples. */ virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0; }; #endif ## Instruction: Make dtor virtual in SampleSource ## Code After: /*============================================================================*/ /* Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib. See the file GNU_GPL_v2.txt for full licensing terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*============================================================================*/ #ifndef VF_SAMPLESOURCE_VFHEADER #define VF_SAMPLESOURCE_VFHEADER //============================================================================== /** Abstract source of audio samples. This interface is used to retrieve sequentual raw audio samples from an abstract source. It is intended as a facade for @ref AudioSource, with these features: - No thread safety; the caller is responsible for all synchronization. - The preparation state feature is removed (along with its methods). @ingroup vf_audio */ class SampleSource { public: virtual ~SampleSource () { } /** Read the next block of samples. */ virtual void getNextAudioBlock (AudioSourceChannelInfo const& bufferToFill) = 0; }; #endif
a5bf81649c8611b61985154f113db61401454699
src/main/java/com/peak/salut/BackgroundDataJob.java
src/main/java/com/peak/salut/BackgroundDataJob.java
package com.peak.salut; import android.util.Log; import com.arasthel.asyncjob.AsyncJob; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.net.Socket; public class BackgroundDataJob implements AsyncJob.OnBackgroundJob{ private Salut salutInstance; private Socket clientSocket; private String data; public BackgroundDataJob(Salut salutInstance, Socket clientSocket) { this.clientSocket = clientSocket; this.salutInstance = salutInstance; } @Override public void doOnBackground() { try { //If this code is reached, a client has connected and transferred data. Log.v(Salut.TAG, "A device is sending data..."); BufferedInputStream bufferedRead = new BufferedInputStream(clientSocket.getInputStream()); DataInputStream dataStreamFromOtherDevice = new DataInputStream(bufferedRead); data = dataStreamFromOtherDevice.readUTF(); dataStreamFromOtherDevice.close(); Log.d(Salut.TAG, "\nSuccessfully received data.\n"); if(!data.isEmpty()) { salutInstance.dataReceiver.currentContext.runOnUiThread(new Runnable() { @Override public void run() { salutInstance.dataReceiver.dataCallback.onDataReceived(data); } }); } } catch(Exception ex) { Log.e(Salut.TAG, "An error occurred while trying to receive data."); ex.printStackTrace(); } finally { try { clientSocket.close(); } catch (Exception ex) { Log.e(Salut.TAG, "Failed to close data socket."); } } } }
package com.peak.salut; import android.util.Log; import com.arasthel.asyncjob.AsyncJob; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.net.Socket; public class BackgroundDataJob implements AsyncJob.OnBackgroundJob{ private Salut salutInstance; private Socket clientSocket; private String data; public BackgroundDataJob(Salut salutInstance, Socket clientSocket) { this.clientSocket = clientSocket; this.salutInstance = salutInstance; } @Override public void doOnBackground() { try { //If this code is reached, a client has connected and transferred data. Log.v(Salut.TAG, "A device is sending data..."); BufferedInputStream bufferedRead = new BufferedInputStream(clientSocket.getInputStream()); DataInputStream dataStreamFromOtherDevice = new DataInputStream(bufferedRead); data = dataStreamFromOtherDevice.readUTF(); dataStreamFromOtherDevice.close(); Log.d(Salut.TAG, "\nSuccessfully received data.\n"); if(!data.isEmpty()) { salutInstance.dataReceiver.dataCallback.onDataReceived(data); } } catch(Exception ex) { Log.e(Salut.TAG, "An error occurred while trying to receive data."); ex.printStackTrace(); } finally { try { clientSocket.close(); } catch (Exception ex) { Log.e(Salut.TAG, "Failed to close data socket."); } } } }
Fix to remove Activity as necessary arg
Fix to remove Activity as necessary arg
Java
mit
3sidedcube/Salut
java
## Code Before: package com.peak.salut; import android.util.Log; import com.arasthel.asyncjob.AsyncJob; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.net.Socket; public class BackgroundDataJob implements AsyncJob.OnBackgroundJob{ private Salut salutInstance; private Socket clientSocket; private String data; public BackgroundDataJob(Salut salutInstance, Socket clientSocket) { this.clientSocket = clientSocket; this.salutInstance = salutInstance; } @Override public void doOnBackground() { try { //If this code is reached, a client has connected and transferred data. Log.v(Salut.TAG, "A device is sending data..."); BufferedInputStream bufferedRead = new BufferedInputStream(clientSocket.getInputStream()); DataInputStream dataStreamFromOtherDevice = new DataInputStream(bufferedRead); data = dataStreamFromOtherDevice.readUTF(); dataStreamFromOtherDevice.close(); Log.d(Salut.TAG, "\nSuccessfully received data.\n"); if(!data.isEmpty()) { salutInstance.dataReceiver.currentContext.runOnUiThread(new Runnable() { @Override public void run() { salutInstance.dataReceiver.dataCallback.onDataReceived(data); } }); } } catch(Exception ex) { Log.e(Salut.TAG, "An error occurred while trying to receive data."); ex.printStackTrace(); } finally { try { clientSocket.close(); } catch (Exception ex) { Log.e(Salut.TAG, "Failed to close data socket."); } } } } ## Instruction: Fix to remove Activity as necessary arg ## Code After: package com.peak.salut; import android.util.Log; import com.arasthel.asyncjob.AsyncJob; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.net.Socket; public class BackgroundDataJob implements AsyncJob.OnBackgroundJob{ private Salut salutInstance; private Socket clientSocket; private String data; public BackgroundDataJob(Salut salutInstance, Socket clientSocket) { this.clientSocket = clientSocket; this.salutInstance = salutInstance; } @Override public void doOnBackground() { try { //If this code is reached, a client has connected and transferred data. Log.v(Salut.TAG, "A device is sending data..."); BufferedInputStream bufferedRead = new BufferedInputStream(clientSocket.getInputStream()); DataInputStream dataStreamFromOtherDevice = new DataInputStream(bufferedRead); data = dataStreamFromOtherDevice.readUTF(); dataStreamFromOtherDevice.close(); Log.d(Salut.TAG, "\nSuccessfully received data.\n"); if(!data.isEmpty()) { salutInstance.dataReceiver.dataCallback.onDataReceived(data); } } catch(Exception ex) { Log.e(Salut.TAG, "An error occurred while trying to receive data."); ex.printStackTrace(); } finally { try { clientSocket.close(); } catch (Exception ex) { Log.e(Salut.TAG, "Failed to close data socket."); } } } }
11ed8e54197d10cb8bf05790043f76d5c9737d59
src/Form.php
src/Form.php
<?php namespace Kameli\Quickpay; use InvalidArgumentException; class Form { const FORM_ACTION = 'https://payment.quickpay.net'; /** * @var array */ protected $parameters = [ 'version' => 'v10', ]; /** * @var array */ protected static $requiredParameters = [ 'version', 'merchant_id', 'agreement_id', 'order_id', 'amount', 'currency', 'continueurl', 'cancelurl', ]; /** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = array_merge($this->parameters, $parameters); } /** * @return string */ public function action() { return static::FORM_ACTION; } /** * Render the form * @return string */ public function render() { $missingParameters = array_diff(static::$requiredParameters, array_keys($this->parameters)); if (! empty($missingParameters)) { $message = 'Missing arguments for Quickpay Form: ' . implode(', ', $missingParameters); throw new InvalidArgumentException($message); } $fields = []; foreach ($this->parameters as $parameter => $value) { $fields[] = sprintf('<input type="hidden" name="%s" value="%s">', $parameter, $value); } return implode("\n", $fields); } /** * @return string */ public function __toString() { return $this->render(); } }
<?php namespace Kameli\Quickpay; use InvalidArgumentException; class Form { const FORM_ACTION = 'https://payment.quickpay.net'; /** * @var array */ protected $parameters = [ 'version' => 'v10', ]; /** * @var array */ protected static $requiredParameters = [ 'version', 'merchant_id', 'agreement_id', 'order_id', 'amount', 'currency', 'continueurl', 'cancelurl', ]; /** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = array_merge($this->parameters, $parameters); } /** * @return string */ public function action() { return static::FORM_ACTION; } /** * Render the form * @return string */ public function render() { $missingParameters = array_diff(static::$requiredParameters, array_keys($this->parameters)); if (! empty($missingParameters)) { $message = 'Missing arguments for Quickpay Form: ' . implode(', ', $missingParameters); throw new InvalidArgumentException($message); } $fields = []; foreach ($this->parameters as $parameter => $value) { $fields[] = sprintf('<input type="hidden" name="%s" value="%s">', $parameter, $value); } return implode("\n", $fields); } }
Drop __toString to allow exceptions
Drop __toString to allow exceptions
PHP
mit
danielboendergaard/quickpay-v10
php
## Code Before: <?php namespace Kameli\Quickpay; use InvalidArgumentException; class Form { const FORM_ACTION = 'https://payment.quickpay.net'; /** * @var array */ protected $parameters = [ 'version' => 'v10', ]; /** * @var array */ protected static $requiredParameters = [ 'version', 'merchant_id', 'agreement_id', 'order_id', 'amount', 'currency', 'continueurl', 'cancelurl', ]; /** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = array_merge($this->parameters, $parameters); } /** * @return string */ public function action() { return static::FORM_ACTION; } /** * Render the form * @return string */ public function render() { $missingParameters = array_diff(static::$requiredParameters, array_keys($this->parameters)); if (! empty($missingParameters)) { $message = 'Missing arguments for Quickpay Form: ' . implode(', ', $missingParameters); throw new InvalidArgumentException($message); } $fields = []; foreach ($this->parameters as $parameter => $value) { $fields[] = sprintf('<input type="hidden" name="%s" value="%s">', $parameter, $value); } return implode("\n", $fields); } /** * @return string */ public function __toString() { return $this->render(); } } ## Instruction: Drop __toString to allow exceptions ## Code After: <?php namespace Kameli\Quickpay; use InvalidArgumentException; class Form { const FORM_ACTION = 'https://payment.quickpay.net'; /** * @var array */ protected $parameters = [ 'version' => 'v10', ]; /** * @var array */ protected static $requiredParameters = [ 'version', 'merchant_id', 'agreement_id', 'order_id', 'amount', 'currency', 'continueurl', 'cancelurl', ]; /** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = array_merge($this->parameters, $parameters); } /** * @return string */ public function action() { return static::FORM_ACTION; } /** * Render the form * @return string */ public function render() { $missingParameters = array_diff(static::$requiredParameters, array_keys($this->parameters)); if (! empty($missingParameters)) { $message = 'Missing arguments for Quickpay Form: ' . implode(', ', $missingParameters); throw new InvalidArgumentException($message); } $fields = []; foreach ($this->parameters as $parameter => $value) { $fields[] = sprintf('<input type="hidden" name="%s" value="%s">', $parameter, $value); } return implode("\n", $fields); } }
9c09b01dcbd0a12db893ffa849b56ebadfa2eb4b
DependencyInjection/Configuration.php
DependencyInjection/Configuration.php
<?php namespace WorkerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('worker'); $rootNode ->children() ->arrayNode('providers') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('class')->isRequired()->end() ->arrayNode('arguments') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->arrayNode('queues') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('name')->isRequired()->end() ->scalarNode('provider')->isRequired()->end() ->end() ->end() ->end() ; return $treeBuilder; } }
<?php namespace WorkerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('worker'); $rootNode ->children() ->arrayNode('providers') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('class')->isRequired()->end() ->arrayNode('arguments') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->arrayNode('queues') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('name')->isRequired()->end() ->scalarNode('provider')->isRequired()->end() ->arrayNode('tags') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
Add tags list on queues
[QUEUE] Add tags list on queues
PHP
mit
acassan/worker-bundle
php
## Code Before: <?php namespace WorkerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('worker'); $rootNode ->children() ->arrayNode('providers') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('class')->isRequired()->end() ->arrayNode('arguments') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->arrayNode('queues') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('name')->isRequired()->end() ->scalarNode('provider')->isRequired()->end() ->end() ->end() ->end() ; return $treeBuilder; } } ## Instruction: [QUEUE] Add tags list on queues ## Code After: <?php namespace WorkerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('worker'); $rootNode ->children() ->arrayNode('providers') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('class')->isRequired()->end() ->arrayNode('arguments') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->arrayNode('queues') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('name')->isRequired()->end() ->scalarNode('provider')->isRequired()->end() ->arrayNode('tags') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
60352e8a3c41ec804ac1bd6b9f3af4bf611edc0b
profiles/views.py
profiles/views.py
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.views.generic import FormView, TemplateView from django.utils.datastructures import MultiValueDictKeyError from incuna.utils import get_class_from_path from profiles.models import Profile from profiles.utils import class_view_decorator try: ProfileForm = get_class_from_path(settings.PROFILE_FORM_CLASS) except AttributeError: from forms import ProfileForm @class_view_decorator(login_required) class ProfileView(TemplateView): template_name = 'profiles/profile.html' @class_view_decorator(login_required) class ProfileEdit(FormView): form_class = ProfileForm template_name = 'profiles/profile_form.html' def form_valid(self, form): instance = super(ProfileEdit, self).form_valid(form) self.request.user.message_set.create(message='Your profile has been updated.') return instance def get_context_data(self, **kwargs): context = super(ProfileEdit, self).get_context_data(**kwargs) context['site'] = Site.objects.get_current() return context def get_object(self): if isinstance(self.request.user, Profile): return self.request.user return self.request.user.profile def get_success_url(self): try: return self.request.GET['next'] except MultiValueDictKeyError: return reverse('profile')
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.utils.datastructures import MultiValueDictKeyError from django.views.generic import TemplateView, UpdateView from incuna.utils import get_class_from_path from profiles.models import Profile from profiles.utils import class_view_decorator try: ProfileForm = get_class_from_path(settings.PROFILE_FORM_CLASS) except AttributeError: from forms import ProfileForm @class_view_decorator(login_required) class ProfileView(TemplateView): template_name = 'profiles/profile.html' @class_view_decorator(login_required) class ProfileEdit(UpdateView): form_class = ProfileForm template_name = 'profiles/profile_form.html' def form_valid(self, form): instance = super(ProfileEdit, self).form_valid(form) self.request.user.message_set.create(message='Your profile has been updated.') return instance def get_context_data(self, **kwargs): context = super(ProfileEdit, self).get_context_data(**kwargs) context['site'] = Site.objects.get_current() return context def get_object(self): if isinstance(self.request.user, Profile): return self.request.user return self.request.user.profile def get_success_url(self): try: return self.request.GET['next'] except MultiValueDictKeyError: return reverse('profile')
Use an update view instead of form view
Use an update view instead of form view
Python
bsd-2-clause
incuna/django-extensible-profiles
python
## Code Before: from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.views.generic import FormView, TemplateView from django.utils.datastructures import MultiValueDictKeyError from incuna.utils import get_class_from_path from profiles.models import Profile from profiles.utils import class_view_decorator try: ProfileForm = get_class_from_path(settings.PROFILE_FORM_CLASS) except AttributeError: from forms import ProfileForm @class_view_decorator(login_required) class ProfileView(TemplateView): template_name = 'profiles/profile.html' @class_view_decorator(login_required) class ProfileEdit(FormView): form_class = ProfileForm template_name = 'profiles/profile_form.html' def form_valid(self, form): instance = super(ProfileEdit, self).form_valid(form) self.request.user.message_set.create(message='Your profile has been updated.') return instance def get_context_data(self, **kwargs): context = super(ProfileEdit, self).get_context_data(**kwargs) context['site'] = Site.objects.get_current() return context def get_object(self): if isinstance(self.request.user, Profile): return self.request.user return self.request.user.profile def get_success_url(self): try: return self.request.GET['next'] except MultiValueDictKeyError: return reverse('profile') ## Instruction: Use an update view instead of form view ## Code After: from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.utils.datastructures import MultiValueDictKeyError from django.views.generic import TemplateView, UpdateView from incuna.utils import get_class_from_path from profiles.models import Profile from profiles.utils import class_view_decorator try: ProfileForm = get_class_from_path(settings.PROFILE_FORM_CLASS) except AttributeError: from forms import ProfileForm @class_view_decorator(login_required) class ProfileView(TemplateView): template_name = 'profiles/profile.html' @class_view_decorator(login_required) class ProfileEdit(UpdateView): form_class = ProfileForm template_name = 'profiles/profile_form.html' def form_valid(self, form): instance = super(ProfileEdit, self).form_valid(form) self.request.user.message_set.create(message='Your profile has been updated.') return instance def get_context_data(self, **kwargs): context = super(ProfileEdit, self).get_context_data(**kwargs) context['site'] = Site.objects.get_current() return context def get_object(self): if isinstance(self.request.user, Profile): return self.request.user return self.request.user.profile def get_success_url(self): try: return self.request.GET['next'] except MultiValueDictKeyError: return reverse('profile')
f0237f1bf73fbbd5a284a80582ccef7b4ec31b3d
ExternalClientUi/src/main/java/Controller.java
ExternalClientUi/src/main/java/Controller.java
import converters.JsonConverter; import datamodel.Request; import httpserver.RequestSender; import httpserver.WebServer; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class Controller { public TextField response; private WebServer ws = new WebServer(); public TextField command; @FXML public TextArea results; public void runCommand(ActionEvent actionEvent) { results.setText(""); response.setText(""); ws.setResults(results); Thread th = new Thread() { @Override public void run() { String commandString = command.getText(); Request request = new Request(); request.setClientId("13"); request.setCommand(commandString); request.setResponseAddress("http://localhost:8008/jobFinished"); request.setProcessors(new String[] {"processors.XmlToJsonConverter","processors.TlsFilter"}); request.setAdapter("adapters.EventHubAdapter"); String requestJsonString = JsonConverter.objectToJsonString(request); String requestResponse = RequestSender.sendRequest("http://localhost:8000/job", request); Platform.runLater(new Runnable() { @Override public void run() { response.setText(requestResponse); } }); } }; th.start(); } }
import converters.JsonConverter; import datamodel.Request; import httpserver.RequestSender; import httpserver.WebServer; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class Controller { public TextField response; private WebServer ws = new WebServer(); public TextField command; @FXML public TextArea results; @FXML public void initialize(){ ws.setResults(results); } public void runCommand(ActionEvent actionEvent) { results.setText(""); response.setText(""); Thread th = new Thread() { @Override public void run() { String commandString = command.getText(); Request request = new Request(); request.setClientId("13"); request.setCommand(commandString); request.setResponseAddress("http://localhost:8008/jobFinished"); request.setProcessors(new String[] {"processors.XmlToJsonConverter","processors.TlsFilter"}); request.setAdapter("adapters.EventHubAdapter"); String requestJsonString = JsonConverter.objectToJsonString(request); String requestResponse = RequestSender.sendRequest("http://localhost:8000/job", request); Platform.runLater(new Runnable() { @Override public void run() { response.setText(requestResponse); } }); } }; th.start(); } }
Initialize set results before button action. The UI client can be used for receiving messages only.
Initialize set results before button action. The UI client can be used for receiving messages only.
Java
apache-2.0
IrimieBogdan/DistributedMonitoring,IrimieBogdan/DistributedMonitoring,IrimieBogdan/DistributedMonitoring
java
## Code Before: import converters.JsonConverter; import datamodel.Request; import httpserver.RequestSender; import httpserver.WebServer; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class Controller { public TextField response; private WebServer ws = new WebServer(); public TextField command; @FXML public TextArea results; public void runCommand(ActionEvent actionEvent) { results.setText(""); response.setText(""); ws.setResults(results); Thread th = new Thread() { @Override public void run() { String commandString = command.getText(); Request request = new Request(); request.setClientId("13"); request.setCommand(commandString); request.setResponseAddress("http://localhost:8008/jobFinished"); request.setProcessors(new String[] {"processors.XmlToJsonConverter","processors.TlsFilter"}); request.setAdapter("adapters.EventHubAdapter"); String requestJsonString = JsonConverter.objectToJsonString(request); String requestResponse = RequestSender.sendRequest("http://localhost:8000/job", request); Platform.runLater(new Runnable() { @Override public void run() { response.setText(requestResponse); } }); } }; th.start(); } } ## Instruction: Initialize set results before button action. The UI client can be used for receiving messages only. ## Code After: import converters.JsonConverter; import datamodel.Request; import httpserver.RequestSender; import httpserver.WebServer; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class Controller { public TextField response; private WebServer ws = new WebServer(); public TextField command; @FXML public TextArea results; @FXML public void initialize(){ ws.setResults(results); } public void runCommand(ActionEvent actionEvent) { results.setText(""); response.setText(""); Thread th = new Thread() { @Override public void run() { String commandString = command.getText(); Request request = new Request(); request.setClientId("13"); request.setCommand(commandString); request.setResponseAddress("http://localhost:8008/jobFinished"); request.setProcessors(new String[] {"processors.XmlToJsonConverter","processors.TlsFilter"}); request.setAdapter("adapters.EventHubAdapter"); String requestJsonString = JsonConverter.objectToJsonString(request); String requestResponse = RequestSender.sendRequest("http://localhost:8000/job", request); Platform.runLater(new Runnable() { @Override public void run() { response.setText(requestResponse); } }); } }; th.start(); } }
2b9fbf55bd93c0ad2f97767fed2094e4de229e37
Iterator/CustomFilterIterator.php
Iterator/CustomFilterIterator.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * CustomFilterIterator filters files by applying anonymous functions. * * The anonymous function receives a \SplFileInfo and must return false * to remove files. * * @author Fabien Potencier <[email protected]> */ class CustomFilterIterator extends \FilterIterator { private $filters = array(); /** * @param \Iterator $iterator The Iterator to filter * @param callable[] $filters An array of PHP callbacks * * @throws \InvalidArgumentException */ public function __construct(\Iterator $iterator, array $filters) { foreach ($filters as $filter) { if (!\is_callable($filter)) { throw new \InvalidArgumentException('Invalid PHP callback.'); } } $this->filters = $filters; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); foreach ($this->filters as $filter) { if (false === \call_user_func($filter, $fileinfo)) { return false; } } return true; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * CustomFilterIterator filters files by applying anonymous functions. * * The anonymous function receives a \SplFileInfo and must return false * to remove files. * * @author Fabien Potencier <[email protected]> */ class CustomFilterIterator extends \FilterIterator { private $filters = array(); /** * @param \Iterator $iterator The Iterator to filter * @param callable[] $filters An array of PHP callbacks * * @throws \InvalidArgumentException */ public function __construct(\Iterator $iterator, array $filters) { foreach ($filters as $filter) { if (!\is_callable($filter)) { throw new \InvalidArgumentException('Invalid PHP callback.'); } } $this->filters = $filters; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); foreach ($this->filters as $filter) { if (false === $filter($fileinfo)) { return false; } } return true; } }
Optimize perf by replacing call_user_func with dynamic vars
Optimize perf by replacing call_user_func with dynamic vars
PHP
mit
symfony/Finder
php
## Code Before: <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * CustomFilterIterator filters files by applying anonymous functions. * * The anonymous function receives a \SplFileInfo and must return false * to remove files. * * @author Fabien Potencier <[email protected]> */ class CustomFilterIterator extends \FilterIterator { private $filters = array(); /** * @param \Iterator $iterator The Iterator to filter * @param callable[] $filters An array of PHP callbacks * * @throws \InvalidArgumentException */ public function __construct(\Iterator $iterator, array $filters) { foreach ($filters as $filter) { if (!\is_callable($filter)) { throw new \InvalidArgumentException('Invalid PHP callback.'); } } $this->filters = $filters; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); foreach ($this->filters as $filter) { if (false === \call_user_func($filter, $fileinfo)) { return false; } } return true; } } ## Instruction: Optimize perf by replacing call_user_func with dynamic vars ## Code After: <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; /** * CustomFilterIterator filters files by applying anonymous functions. * * The anonymous function receives a \SplFileInfo and must return false * to remove files. * * @author Fabien Potencier <[email protected]> */ class CustomFilterIterator extends \FilterIterator { private $filters = array(); /** * @param \Iterator $iterator The Iterator to filter * @param callable[] $filters An array of PHP callbacks * * @throws \InvalidArgumentException */ public function __construct(\Iterator $iterator, array $filters) { foreach ($filters as $filter) { if (!\is_callable($filter)) { throw new \InvalidArgumentException('Invalid PHP callback.'); } } $this->filters = $filters; parent::__construct($iterator); } /** * Filters the iterator values. * * @return bool true if the value should be kept, false otherwise */ public function accept() { $fileinfo = $this->current(); foreach ($this->filters as $filter) { if (false === $filter($fileinfo)) { return false; } } return true; } }
6945864c66398ae0b7988fdf0d80e75c0c3d7880
app/modules/wifi/migrations/2017_02_09_235003_wifi.php
app/modules/wifi/migrations/2017_02_09_235003_wifi.php
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Wifi extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('wifi', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number')->unique()->nullable(); $table->integer('agrctlrssi')->nullable(); $table->integer('agrextrssi')->nullable(); $table->integer('agrctlnoise')->nullable(); $table->integer('agrextnoise')->nullable(); $table->string('state')->nullable(); $table->string('op_mode')->nullable(); $table->integer('lasttxrate')->nullable(); $table->string('lastassocstatus')->nullable(); $table->integer('maxrate')->nullable(); $table->string('x802_11_auth')->nullable(); $table->string('link_auth')->nullable(); $table->string('bssid')->nullable(); $table->string('ssid')->nullable(); $table->integer('mcs')->nullable(); $table->string('channel')->nullable(); // $table->timestamps(); $table->index('bssid'); $table->index('ssid'); $table->index('state'); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('wifi'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Wifi extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('wifi', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number')->unique(); $table->integer('agrctlrssi'); $table->integer('agrextrssi'); $table->integer('agrctlnoise'); $table->integer('agrextnoise'); $table->string('state'); $table->string('op_mode'); $table->integer('lasttxrate'); $table->string('lastassocstatus'); $table->integer('maxrate'); $table->string('x802_11_auth'); $table->string('link_auth'); $table->string('bssid'); $table->string('ssid'); $table->integer('mcs'); $table->string('channel'); $table->index('bssid'); $table->index('ssid'); $table->index('state'); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('wifi'); } }
Remove nullable() from wifi migration
Remove nullable() from wifi migration
PHP
mit
munkireport/munkireport-php,gmarnin/munkireport-php,n8felton/munkireport-php,munkireport/munkireport-php,n8felton/munkireport-php,poundbangbash/munkireport-php,gmarnin/munkireport-php,n8felton/munkireport-php,gmarnin/munkireport-php,poundbangbash/munkireport-php,poundbangbash/munkireport-php,munkireport/munkireport-php,n8felton/munkireport-php,munkireport/munkireport-php,n8felton/munkireport-php,munkireport/munkireport-php,poundbangbash/munkireport-php,n8felton/munkireport-php,gmarnin/munkireport-php,poundbangbash/munkireport-php,gmarnin/munkireport-php
php
## Code Before: <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Wifi extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('wifi', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number')->unique()->nullable(); $table->integer('agrctlrssi')->nullable(); $table->integer('agrextrssi')->nullable(); $table->integer('agrctlnoise')->nullable(); $table->integer('agrextnoise')->nullable(); $table->string('state')->nullable(); $table->string('op_mode')->nullable(); $table->integer('lasttxrate')->nullable(); $table->string('lastassocstatus')->nullable(); $table->integer('maxrate')->nullable(); $table->string('x802_11_auth')->nullable(); $table->string('link_auth')->nullable(); $table->string('bssid')->nullable(); $table->string('ssid')->nullable(); $table->integer('mcs')->nullable(); $table->string('channel')->nullable(); // $table->timestamps(); $table->index('bssid'); $table->index('ssid'); $table->index('state'); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('wifi'); } } ## Instruction: Remove nullable() from wifi migration ## Code After: <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Wifi extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('wifi', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number')->unique(); $table->integer('agrctlrssi'); $table->integer('agrextrssi'); $table->integer('agrctlnoise'); $table->integer('agrextnoise'); $table->string('state'); $table->string('op_mode'); $table->integer('lasttxrate'); $table->string('lastassocstatus'); $table->integer('maxrate'); $table->string('x802_11_auth'); $table->string('link_auth'); $table->string('bssid'); $table->string('ssid'); $table->integer('mcs'); $table->string('channel'); $table->index('bssid'); $table->index('ssid'); $table->index('state'); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('wifi'); } }
56391c7fb2739b833b0e9319275dc0b75655b20c
src/main/java/com/secdec/codedx/util/HashUtil.java
src/main/java/com/secdec/codedx/util/HashUtil.java
package com.secdec.codedx.util; /************************************************************************** * Copyright (c) 2014 Applied Visions, Inc. All Rights Reserved. * Author: Applied Visions, Inc. - Chris Ellsworth * Project: Code Dx * SubSystem: com.secdec.codedx.util * FileName: HashUtil.java *************************************************************************/ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; /** * @author Chris Ellsworth * */ public class HashUtil { // public static String toMd5(String input) { // String toReturn = null; // try { // byte[] digest = MessageDigest.getInstance("MD5").digest(input.getBytes()); // StringBuilder hashBuilder = new StringBuilder(); // for (byte b : digest) { // hashBuilder.append(String.format("%x", b)); // } // toReturn = hashBuilder.toString(); // } catch (NoSuchAlgorithmException exc) { // throw new CodeDxException(exc); // } // return toReturn; // } public static byte[] getSHA1(byte[] input) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); return md.digest(input); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String toHexString(byte[] bytes) { return toHexString(bytes, ""); } public static String toHexString(byte[] bytes, String sep) { Formatter f = new Formatter(); for (int i = 0; i < bytes.length; i++) { f.format("%02x", bytes[i]); if (i < bytes.length - 1) { f.format(sep); } } String result = f.toString(); f.close(); return result; } }
package com.secdec.codedx.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; /** * Contains utilities for dealing with Hashes * * @author Samuel Johnson * */ public class HashUtil { public static byte[] getSHA1(byte[] input) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); return md.digest(input); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String toHexString(byte[] bytes) { return toHexString(bytes, ""); } public static String toHexString(byte[] bytes, String sep) { Formatter f = new Formatter(); for (int i = 0; i < bytes.length; i++) { f.format("%02x", bytes[i]); if (i < bytes.length - 1) { f.format(sep); } } String result = f.toString(); f.close(); return result; } }
Clean up code and documentation
Clean up code and documentation This file contained JavaDoc and unused code that wasn't cleaned up when I borrowed it from elsewhere in our codebase.
Java
apache-2.0
jenkinsci/codedx-plugin,jenkinsci/codedx-plugin
java
## Code Before: package com.secdec.codedx.util; /************************************************************************** * Copyright (c) 2014 Applied Visions, Inc. All Rights Reserved. * Author: Applied Visions, Inc. - Chris Ellsworth * Project: Code Dx * SubSystem: com.secdec.codedx.util * FileName: HashUtil.java *************************************************************************/ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; /** * @author Chris Ellsworth * */ public class HashUtil { // public static String toMd5(String input) { // String toReturn = null; // try { // byte[] digest = MessageDigest.getInstance("MD5").digest(input.getBytes()); // StringBuilder hashBuilder = new StringBuilder(); // for (byte b : digest) { // hashBuilder.append(String.format("%x", b)); // } // toReturn = hashBuilder.toString(); // } catch (NoSuchAlgorithmException exc) { // throw new CodeDxException(exc); // } // return toReturn; // } public static byte[] getSHA1(byte[] input) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); return md.digest(input); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String toHexString(byte[] bytes) { return toHexString(bytes, ""); } public static String toHexString(byte[] bytes, String sep) { Formatter f = new Formatter(); for (int i = 0; i < bytes.length; i++) { f.format("%02x", bytes[i]); if (i < bytes.length - 1) { f.format(sep); } } String result = f.toString(); f.close(); return result; } } ## Instruction: Clean up code and documentation This file contained JavaDoc and unused code that wasn't cleaned up when I borrowed it from elsewhere in our codebase. ## Code After: package com.secdec.codedx.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; /** * Contains utilities for dealing with Hashes * * @author Samuel Johnson * */ public class HashUtil { public static byte[] getSHA1(byte[] input) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); return md.digest(input); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String toHexString(byte[] bytes) { return toHexString(bytes, ""); } public static String toHexString(byte[] bytes, String sep) { Formatter f = new Formatter(); for (int i = 0; i < bytes.length; i++) { f.format("%02x", bytes[i]); if (i < bytes.length - 1) { f.format(sep); } } String result = f.toString(); f.close(); return result; } }
83a1d7964b104754020c18d93fa0b339e33d8ef6
lib/Algorithm/AlgorithmConnectedComponents.php
lib/Algorithm/AlgorithmConnectedComponents.php
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchDepthFirst::getVertices() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vertex){ //for each vertices if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchDepthFirst($vertex); $newVertices = $alg->getVertices(); //get all vertices of this component $components++; foreach ($newVertices as $v){ //mark the vertices of this component as visited $visitedVertices[$v->getId()] = true; } } } return $components; //return number of components } }
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchBreadthFirst::getVerticesIds() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vid=>$vertex){ //for each vertices if ( ! isset( $visitedVertices[$vid] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchBreadthFirst($vertex); $newVertices = $alg->getVerticesIds(); //get all vertices of this component ++$components; foreach ($newVertices as $vid){ //mark the vertices of this component as visited $visitedVertices[$vid] = true; } } } return $components; //return number of components } }
Improve by using breadth search instead of depth search
Improve by using breadth search instead of depth search
PHP
mit
clue-labs/graph,clue/graph
php
## Code Before: <?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchDepthFirst::getVertices() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vertex){ //for each vertices if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchDepthFirst($vertex); $newVertices = $alg->getVertices(); //get all vertices of this component $components++; foreach ($newVertices as $v){ //mark the vertices of this component as visited $visitedVertices[$v->getId()] = true; } } } return $components; //return number of components } } ## Instruction: Improve by using breadth search instead of depth search ## Code After: <?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchBreadthFirst::getVerticesIds() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vid=>$vertex){ //for each vertices if ( ! isset( $visitedVertices[$vid] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchBreadthFirst($vertex); $newVertices = $alg->getVerticesIds(); //get all vertices of this component ++$components; foreach ($newVertices as $vid){ //mark the vertices of this component as visited $visitedVertices[$vid] = true; } } } return $components; //return number of components } }
fc7831aaa86cf4cf7fb7af253d61ff95a8de339e
static/deleteAccountPage.js
static/deleteAccountPage.js
$(document).ready(function(){ $('#deleteAccountSubmitLabel').on('click',function(){ var userID = $('#userIDValue').val(); var verifyCode = $('#verifyCodeValue').val(); var password = $('#passwordValue').val(); var updateField = '#deleteAccountSubmitMessage'; confirmDelete(userID,verifyCode,password,updateField); }); }); function confirmDelete(userID,verifyCode,password,updateField){ confirmDeleteAjax(userID,verifyCode,password,function(data){ switch (data){ case 'success': $(updateField).html('Account has been deleted. You now have a chance at a new life.'); logout(); break; case 'badVerifyCode': $(updateField).html('Unable to verify. Make sure that you followed the link from the delete request email that was sent to you.'); break; case 'badPassword': $(updateField).html('Incorrect password.'); break; case 'expired': $(updateField).html('Request has expired. Please create a new request if you still need to delete this account.'); break; } }); } function confirmDeleteAjax(userID,verifyCode,password,callback){ $.ajax({ 'url' : '/deleteAccountAction', 'type' : 'POST', 'data' : {'userID':userID,'verifyCode':verifyCode,'password':password}, 'success' : function(data){ callback(data); }, }); }
$(document).ready(function(){ $('#deleteAccountSubmitLabel').on('click',function(){ var userID = $('#userIDValue').val(); var verifyCode = $('#verifyCodeValue').val(); var password = $('#passwordValue').val(); var updateField = '#deleteAccountSubmitMessage'; confirmDelete(userID,verifyCode,password,updateField); }); }); function confirmDelete(userID,verifyCode,password,updateField){ $(updateField).html('Sending delete request...'); confirmDeleteAjax(userID,verifyCode,password,function(data){ switch (data){ case 'success': $(updateField).html('Account has been deleted. You now have a chance at a new life.'); logout(); break; case 'badVerifyCode': $(updateField).html('Unable to verify. Make sure that you followed the link from the delete request email that was sent to you.'); break; case 'badPassword': $(updateField).html('Incorrect password.'); break; case 'expired': $(updateField).html('Request has expired. Please create a new request if you still need to delete this account.'); break; } }); } function confirmDeleteAjax(userID,verifyCode,password,callback){ $.ajax({ 'url' : '/deleteAccountAction', 'type' : 'POST', 'data' : {'userID':userID,'verifyCode':verifyCode,'password':password}, 'success' : function(data){ callback(data); }, }); }
Update sending request status message
Update sending request status message
JavaScript
mit
anorman728/threadstr,anorman728/threadstr
javascript
## Code Before: $(document).ready(function(){ $('#deleteAccountSubmitLabel').on('click',function(){ var userID = $('#userIDValue').val(); var verifyCode = $('#verifyCodeValue').val(); var password = $('#passwordValue').val(); var updateField = '#deleteAccountSubmitMessage'; confirmDelete(userID,verifyCode,password,updateField); }); }); function confirmDelete(userID,verifyCode,password,updateField){ confirmDeleteAjax(userID,verifyCode,password,function(data){ switch (data){ case 'success': $(updateField).html('Account has been deleted. You now have a chance at a new life.'); logout(); break; case 'badVerifyCode': $(updateField).html('Unable to verify. Make sure that you followed the link from the delete request email that was sent to you.'); break; case 'badPassword': $(updateField).html('Incorrect password.'); break; case 'expired': $(updateField).html('Request has expired. Please create a new request if you still need to delete this account.'); break; } }); } function confirmDeleteAjax(userID,verifyCode,password,callback){ $.ajax({ 'url' : '/deleteAccountAction', 'type' : 'POST', 'data' : {'userID':userID,'verifyCode':verifyCode,'password':password}, 'success' : function(data){ callback(data); }, }); } ## Instruction: Update sending request status message ## Code After: $(document).ready(function(){ $('#deleteAccountSubmitLabel').on('click',function(){ var userID = $('#userIDValue').val(); var verifyCode = $('#verifyCodeValue').val(); var password = $('#passwordValue').val(); var updateField = '#deleteAccountSubmitMessage'; confirmDelete(userID,verifyCode,password,updateField); }); }); function confirmDelete(userID,verifyCode,password,updateField){ $(updateField).html('Sending delete request...'); confirmDeleteAjax(userID,verifyCode,password,function(data){ switch (data){ case 'success': $(updateField).html('Account has been deleted. You now have a chance at a new life.'); logout(); break; case 'badVerifyCode': $(updateField).html('Unable to verify. Make sure that you followed the link from the delete request email that was sent to you.'); break; case 'badPassword': $(updateField).html('Incorrect password.'); break; case 'expired': $(updateField).html('Request has expired. Please create a new request if you still need to delete this account.'); break; } }); } function confirmDeleteAjax(userID,verifyCode,password,callback){ $.ajax({ 'url' : '/deleteAccountAction', 'type' : 'POST', 'data' : {'userID':userID,'verifyCode':verifyCode,'password':password}, 'success' : function(data){ callback(data); }, }); }
2cc759f4757dbd50b73c264d47fe08efa0d47f3a
app/src/main/java/com/veyndan/redditclient/ui/recyclerview/itemdecoration/TreeInsetItemDecoration.java
app/src/main/java/com/veyndan/redditclient/ui/recyclerview/itemdecoration/TreeInsetItemDecoration.java
package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.content.Context; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; import com.veyndan.redditclient.post.DepthCalculatorDelegate; public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration { @Px private final int childInsetMultiplier; public TreeInsetItemDecoration(@NonNull final Context context, @DimenRes final int childInsetMultiplierRes) { childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes); } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { if (parent.getAdapter() instanceof DepthCalculatorDelegate) { final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter(); final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams(); final int position = layoutParams.getViewLayoutPosition(); final int inset = depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier; outRect.set(inset, 0, 0, 0); } else { throw new IllegalStateException("RecyclerView's Adapter must implement " + "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " + "a decoration"); } } }
package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.content.Context; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; import com.veyndan.redditclient.post.DepthCalculatorDelegate; public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration { @Px private final int childInsetMultiplier; public TreeInsetItemDecoration(@NonNull final Context context, @DimenRes final int childInsetMultiplierRes) { childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes); } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { if (parent.getAdapter() instanceof DepthCalculatorDelegate) { final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter(); final int position = parent.getChildAdapterPosition(view); final int inset = position == RecyclerView.NO_POSITION ? 0 : depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier; outRect.set(inset, 0, 0, 0); } else { throw new IllegalStateException("RecyclerView's Adapter must implement " + "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " + "a decoration"); } } }
Use adapter position instead of layout params position as causing IndexOutOfBoundsException otherwise
Use adapter position instead of layout params position as causing IndexOutOfBoundsException otherwise
Java
mit
veyndan/reddit-client,veyndan/paper-for-reddit,veyndan/paper-for-reddit
java
## Code Before: package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.content.Context; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; import com.veyndan.redditclient.post.DepthCalculatorDelegate; public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration { @Px private final int childInsetMultiplier; public TreeInsetItemDecoration(@NonNull final Context context, @DimenRes final int childInsetMultiplierRes) { childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes); } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { if (parent.getAdapter() instanceof DepthCalculatorDelegate) { final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter(); final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams(); final int position = layoutParams.getViewLayoutPosition(); final int inset = depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier; outRect.set(inset, 0, 0, 0); } else { throw new IllegalStateException("RecyclerView's Adapter must implement " + "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " + "a decoration"); } } } ## Instruction: Use adapter position instead of layout params position as causing IndexOutOfBoundsException otherwise ## Code After: package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.content.Context; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; import com.veyndan.redditclient.post.DepthCalculatorDelegate; public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration { @Px private final int childInsetMultiplier; public TreeInsetItemDecoration(@NonNull final Context context, @DimenRes final int childInsetMultiplierRes) { childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes); } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { if (parent.getAdapter() instanceof DepthCalculatorDelegate) { final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter(); final int position = parent.getChildAdapterPosition(view); final int inset = position == RecyclerView.NO_POSITION ? 0 : depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier; outRect.set(inset, 0, 0, 0); } else { throw new IllegalStateException("RecyclerView's Adapter must implement " + "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " + "a decoration"); } } }
b1c5f75c266f5f5b9976ce2ca7c2b9065ef41bb1
groupmestats/generatestats.py
groupmestats/generatestats.py
import argparse import webbrowser from .groupserializer import GroupSerializer from .statistic import all_statistics from .statistics import * def gstat_stats(): parser = argparse.ArgumentParser(description="Generates stats for a group") parser.add_argument("-g", "--group", dest="group_name", required=True, help="Group to generate stats for.") parser.add_argument("-s", "--stat", dest="stats", default=[], action="append", help=("Name of stat to generate. This may be specified" " more than once. Choices: %s " % ", ".join(all_statistics.keys()))) parser.add_argument("--all-stats", action="store_true", default=False, help="Generate all possible stats.") parser.add_argument("--ignore-user", dest="ignore_users", default=[], action="append", help="User to ignore. May be specified more than once.") args = parser.parse_args() stats = [stat_class() for name, stat_class in all_statistics.items() if args.all_stats or name in args.stats] if not stats: parser.print_help() raise RuntimeError("Must specify a valid --stat or use --all-stats") (group, messages) = GroupSerializer.load(args.group_name) for stat in stats: stat.calculate(group, messages, ignore_users=args.ignore_users) for stat in stats: output_html_filename = stat.show() try: # webbrowser.open_new_tab(output_html_filename) pass except: pass
import argparse import webbrowser from .groupserializer import GroupSerializer from .statistic import all_statistics from .statistics import * def gstat_stats(): parser = argparse.ArgumentParser(description="Generates stats for a group") parser.add_argument("-g", "--group", dest="group_name", required=True, help="Group to generate stats for.") parser.add_argument("-s", "--stat", dest="stats", default=[], action="append", help=("Name of stat to generate. This may be specified" " more than once. Choices: %s " % ", ".join(all_statistics.keys()))) parser.add_argument("--all-stats", action="store_true", default=False, help="Generate all possible stats.") parser.add_argument("--ignore-user", dest="ignore_users", default=[], action="append", help="User to ignore. May be specified more than once.") args = parser.parse_args() stats = [stat_class() for name, stat_class in all_statistics.items() if args.all_stats or name in args.stats] print("args: %s" % str(args)) if not stats: parser.print_help() raise RuntimeError("Must specify a valid --stat or use --all-stats") (group, messages) = GroupSerializer.load(args.group_name) for stat in stats: stat.calculate(group, messages, ignore_users=args.ignore_users) for stat in stats: output_html_filename = stat.show() try: # webbrowser.open_new_tab(output_html_filename) pass except: pass
Print args when generating stats
Print args when generating stats
Python
mit
kjteske/groupmestats,kjteske/groupmestats
python
## Code Before: import argparse import webbrowser from .groupserializer import GroupSerializer from .statistic import all_statistics from .statistics import * def gstat_stats(): parser = argparse.ArgumentParser(description="Generates stats for a group") parser.add_argument("-g", "--group", dest="group_name", required=True, help="Group to generate stats for.") parser.add_argument("-s", "--stat", dest="stats", default=[], action="append", help=("Name of stat to generate. This may be specified" " more than once. Choices: %s " % ", ".join(all_statistics.keys()))) parser.add_argument("--all-stats", action="store_true", default=False, help="Generate all possible stats.") parser.add_argument("--ignore-user", dest="ignore_users", default=[], action="append", help="User to ignore. May be specified more than once.") args = parser.parse_args() stats = [stat_class() for name, stat_class in all_statistics.items() if args.all_stats or name in args.stats] if not stats: parser.print_help() raise RuntimeError("Must specify a valid --stat or use --all-stats") (group, messages) = GroupSerializer.load(args.group_name) for stat in stats: stat.calculate(group, messages, ignore_users=args.ignore_users) for stat in stats: output_html_filename = stat.show() try: # webbrowser.open_new_tab(output_html_filename) pass except: pass ## Instruction: Print args when generating stats ## Code After: import argparse import webbrowser from .groupserializer import GroupSerializer from .statistic import all_statistics from .statistics import * def gstat_stats(): parser = argparse.ArgumentParser(description="Generates stats for a group") parser.add_argument("-g", "--group", dest="group_name", required=True, help="Group to generate stats for.") parser.add_argument("-s", "--stat", dest="stats", default=[], action="append", help=("Name of stat to generate. This may be specified" " more than once. Choices: %s " % ", ".join(all_statistics.keys()))) parser.add_argument("--all-stats", action="store_true", default=False, help="Generate all possible stats.") parser.add_argument("--ignore-user", dest="ignore_users", default=[], action="append", help="User to ignore. May be specified more than once.") args = parser.parse_args() stats = [stat_class() for name, stat_class in all_statistics.items() if args.all_stats or name in args.stats] print("args: %s" % str(args)) if not stats: parser.print_help() raise RuntimeError("Must specify a valid --stat or use --all-stats") (group, messages) = GroupSerializer.load(args.group_name) for stat in stats: stat.calculate(group, messages, ignore_users=args.ignore_users) for stat in stats: output_html_filename = stat.show() try: # webbrowser.open_new_tab(output_html_filename) pass except: pass
1989e588f7685da9cdcc306abf9966f53d97e712
kitchen/templates/main.html
kitchen/templates/main.html
{% extends "base.html" %} {% block extrahead %} <script type="text/javascript" src="/static/js/jquery.dataTables.min.js"></script> {% endblock %} {% load filters %} {% block bodycontent %} {% if nodes %} <table id="nodes" class="table"> <thead> <tr> <th class="node_name">Name</th> <th class="node_ip">IP Address</th> <th class="node_env">Environment</th> <th class="node_role">Role</th> </tr> </thead> {% for node in nodes %} <tr> <td class="node_name"> {{ node.name }} </td> <td class="node_ip"> {{ node.ipaddress }} </td> <td class="node_env"> {{ node.chef_environment }} </td> <td class="node_role"> {% for entry in node.role %}{% if not entry|is_environment_role %}{{ entry }}{% if not forloop.last %}, {% endif %}{% endif %}{% endfor %} </td> </tr> {% endfor %} </table> {% endif %} {% endblock %} {% block bodytail %} <script type="text/javascript"> $(document).ready(function() { setupClickHandlers(); }); $('#nodes').dataTable({ "bPaginate": false }); $('#nodes_filter input:text').focus(); </script> {% endblock %}
{% extends "base.html" %} {% block extrahead %} <script type="text/javascript" src="/static/js/jquery.dataTables.min.js"></script> {% endblock %} {% load filters %} {% block bodycontent %} {% if nodes %} <table id="nodes" class="table"> <thead> <tr> <th class="node_name">Name</th> <th class="node_ip">IP Address</th> <th class="node_env">Environment</th> <th class="node_role">Role</th> </tr> </thead> {% for node in nodes %} <tr> <td class="node_name"> {{ node.name }} </td> <td class="node_ip"> {{ node.ipaddress }} </td> <td class="node_env"> {{ node.chef_environment }} </td> <td class="node_role"> {% for entry in node.role %}{% if not entry|is_environment_role %}{{ entry }}{% if not forloop.last %}, {% endif %}{% endif %}{% endfor %} </td> </tr> {% endfor %} </table> {% endif %} {% endblock %} {% block bodytail %} <script type="text/javascript"> $(document).ready(function() { setupClickHandlers(); $('#nodes').dataTable({ "bPaginate": false }); $('#nodes_filter input:text').focus(); }); </script> {% endblock %}
Initialize datatable on document load
Initialize datatable on document load
HTML
apache-2.0
edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen
html
## Code Before: {% extends "base.html" %} {% block extrahead %} <script type="text/javascript" src="/static/js/jquery.dataTables.min.js"></script> {% endblock %} {% load filters %} {% block bodycontent %} {% if nodes %} <table id="nodes" class="table"> <thead> <tr> <th class="node_name">Name</th> <th class="node_ip">IP Address</th> <th class="node_env">Environment</th> <th class="node_role">Role</th> </tr> </thead> {% for node in nodes %} <tr> <td class="node_name"> {{ node.name }} </td> <td class="node_ip"> {{ node.ipaddress }} </td> <td class="node_env"> {{ node.chef_environment }} </td> <td class="node_role"> {% for entry in node.role %}{% if not entry|is_environment_role %}{{ entry }}{% if not forloop.last %}, {% endif %}{% endif %}{% endfor %} </td> </tr> {% endfor %} </table> {% endif %} {% endblock %} {% block bodytail %} <script type="text/javascript"> $(document).ready(function() { setupClickHandlers(); }); $('#nodes').dataTable({ "bPaginate": false }); $('#nodes_filter input:text').focus(); </script> {% endblock %} ## Instruction: Initialize datatable on document load ## Code After: {% extends "base.html" %} {% block extrahead %} <script type="text/javascript" src="/static/js/jquery.dataTables.min.js"></script> {% endblock %} {% load filters %} {% block bodycontent %} {% if nodes %} <table id="nodes" class="table"> <thead> <tr> <th class="node_name">Name</th> <th class="node_ip">IP Address</th> <th class="node_env">Environment</th> <th class="node_role">Role</th> </tr> </thead> {% for node in nodes %} <tr> <td class="node_name"> {{ node.name }} </td> <td class="node_ip"> {{ node.ipaddress }} </td> <td class="node_env"> {{ node.chef_environment }} </td> <td class="node_role"> {% for entry in node.role %}{% if not entry|is_environment_role %}{{ entry }}{% if not forloop.last %}, {% endif %}{% endif %}{% endfor %} </td> </tr> {% endfor %} </table> {% endif %} {% endblock %} {% block bodytail %} <script type="text/javascript"> $(document).ready(function() { setupClickHandlers(); $('#nodes').dataTable({ "bPaginate": false }); $('#nodes_filter input:text').focus(); }); </script> {% endblock %}
e1514fa5bcc35df74295c254df65e8e99dc289a1
speeches/util.py
speeches/util.py
from speeches.tasks import transcribe_speech from django.forms.widgets import SplitDateTimeWidget """Common utility functions/classes Things that are needed by multiple bits of code but are specific enough to this project not to be in a separate python package""" def start_transcribing_speech(speech): """Kick off a celery task to transcribe a speech""" # We only do anything if there's no text already if not speech.text: # If someone is adding a new audio file and there's already a task # We need to clear it if speech.celery_task_id: celery.task.control.revoke(speech.celery_task_id) # Now we can start a new one result = transcribe_speech.delay(speech.id) # Finally, we can remember the new task in the model speech.celery_task_id = result.task_id speech.save() class BootstrapSplitDateTimeWidget(SplitDateTimeWidget): """ A Widget that splits datetime input into two <input type="text"> boxes and styles with Bootstrap """ def __init__(self, attrs=None, date_format=None, time_format=None): super(BootstrapSplitDateTimeWidget, self).__init__(attrs, date_format, time_format) def format_output(self, rendered_widgets): """Override the output formatting to return widgets with some Bootstrap niceness""" output = '' for i, widget in enumerate(rendered_widgets): output += '<div class="input-append">' output += widget if i == 0: output += '<span class="add-on"><i class="icon-calendar"></i></span>' else: output += '<span class="add-on"><i class="icon-time"></i></span>' output += '</div>' return output
from speeches.tasks import transcribe_speech """Common utility functions/classes Things that are needed by multiple bits of code but are specific enough to this project not to be in a separate python package""" def start_transcribing_speech(speech): """Kick off a celery task to transcribe a speech""" # We only do anything if there's no text already if not speech.text: # If someone is adding a new audio file and there's already a task # We need to clear it if speech.celery_task_id: celery.task.control.revoke(speech.celery_task_id) # Now we can start a new one result = transcribe_speech.delay(speech.id) # Finally, we can remember the new task in the model speech.celery_task_id = result.task_id speech.save()
Remove BootstrapSplitDateTimeWidget as it's no longer needed
Remove BootstrapSplitDateTimeWidget as it's no longer needed
Python
agpl-3.0
opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit
python
## Code Before: from speeches.tasks import transcribe_speech from django.forms.widgets import SplitDateTimeWidget """Common utility functions/classes Things that are needed by multiple bits of code but are specific enough to this project not to be in a separate python package""" def start_transcribing_speech(speech): """Kick off a celery task to transcribe a speech""" # We only do anything if there's no text already if not speech.text: # If someone is adding a new audio file and there's already a task # We need to clear it if speech.celery_task_id: celery.task.control.revoke(speech.celery_task_id) # Now we can start a new one result = transcribe_speech.delay(speech.id) # Finally, we can remember the new task in the model speech.celery_task_id = result.task_id speech.save() class BootstrapSplitDateTimeWidget(SplitDateTimeWidget): """ A Widget that splits datetime input into two <input type="text"> boxes and styles with Bootstrap """ def __init__(self, attrs=None, date_format=None, time_format=None): super(BootstrapSplitDateTimeWidget, self).__init__(attrs, date_format, time_format) def format_output(self, rendered_widgets): """Override the output formatting to return widgets with some Bootstrap niceness""" output = '' for i, widget in enumerate(rendered_widgets): output += '<div class="input-append">' output += widget if i == 0: output += '<span class="add-on"><i class="icon-calendar"></i></span>' else: output += '<span class="add-on"><i class="icon-time"></i></span>' output += '</div>' return output ## Instruction: Remove BootstrapSplitDateTimeWidget as it's no longer needed ## Code After: from speeches.tasks import transcribe_speech """Common utility functions/classes Things that are needed by multiple bits of code but are specific enough to this project not to be in a separate python package""" def start_transcribing_speech(speech): """Kick off a celery task to transcribe a speech""" # We only do anything if there's no text already if not speech.text: # If someone is adding a new audio file and there's already a task # We need to clear it if speech.celery_task_id: celery.task.control.revoke(speech.celery_task_id) # Now we can start a new one result = transcribe_speech.delay(speech.id) # Finally, we can remember the new task in the model speech.celery_task_id = result.task_id speech.save()
c866ab859edf11563382f673e943e849f92a48f9
src/DependencyInjection/Compiler/AddVotersPass.php
src/DependencyInjection/Compiler/AddVotersPass.php
<?php namespace Knp\Bundle\MenuBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Reference; /** * This compiler pass registers the voters in the Matcher. * * @author Christophe Coevoet <[email protected]> * * @internal * @final */ final class AddVotersPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { if (!$container->hasDefinition('knp_menu.matcher')) { return; } $definition = $container->getDefinition('knp_menu.matcher'); $voters = []; foreach ($container->findTaggedServiceIds('knp_menu.voter') as $id => $tags) { // Process only the first tag. Registering the same voter multiple time // does not make any sense, and this allows user to overwrite the tag added // by the autoconfiguration to change the priority (autoconfigured tags are // always added at the end of the list). $tag = $tags[0]; $priority = isset($tag['priority']) ? (int) $tag['priority'] : 0; $voters[$priority][] = new Reference($id); } if (empty($voters)) { return; } krsort($voters); $sortedVoters = \call_user_func_array('array_merge', $voters); $definition->replaceArgument(0, new IteratorArgument($sortedVoters)); } }
<?php namespace Knp\Bundle\MenuBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * This compiler pass registers the voters in the Matcher. * * @author Christophe Coevoet <[email protected]> * * @internal * @final */ final class AddVotersPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { if (!$container->hasDefinition('knp_menu.matcher')) { return; } $definition = $container->getDefinition('knp_menu.matcher'); $voters = []; foreach ($container->findTaggedServiceIds('knp_menu.voter') as $id => $tags) { // Process only the first tag. Registering the same voter multiple time // does not make any sense, and this allows user to overwrite the tag added // by the autoconfiguration to change the priority (autoconfigured tags are // always added at the end of the list). $tag = $tags[0]; $priority = isset($tag['priority']) ? (int) $tag['priority'] : 0; $voters[$priority][] = new Reference($id); } if (empty($voters)) { return; } krsort($voters); $sortedVoters = array_merge(...$voters); $definition->replaceArgument(0, new IteratorArgument($sortedVoters)); } }
Use a variadic call instead of call_user_func_array().
Use a variadic call instead of call_user_func_array().
PHP
mit
KnpLabs/KnpMenuBundle
php
## Code Before: <?php namespace Knp\Bundle\MenuBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Reference; /** * This compiler pass registers the voters in the Matcher. * * @author Christophe Coevoet <[email protected]> * * @internal * @final */ final class AddVotersPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { if (!$container->hasDefinition('knp_menu.matcher')) { return; } $definition = $container->getDefinition('knp_menu.matcher'); $voters = []; foreach ($container->findTaggedServiceIds('knp_menu.voter') as $id => $tags) { // Process only the first tag. Registering the same voter multiple time // does not make any sense, and this allows user to overwrite the tag added // by the autoconfiguration to change the priority (autoconfigured tags are // always added at the end of the list). $tag = $tags[0]; $priority = isset($tag['priority']) ? (int) $tag['priority'] : 0; $voters[$priority][] = new Reference($id); } if (empty($voters)) { return; } krsort($voters); $sortedVoters = \call_user_func_array('array_merge', $voters); $definition->replaceArgument(0, new IteratorArgument($sortedVoters)); } } ## Instruction: Use a variadic call instead of call_user_func_array(). ## Code After: <?php namespace Knp\Bundle\MenuBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * This compiler pass registers the voters in the Matcher. * * @author Christophe Coevoet <[email protected]> * * @internal * @final */ final class AddVotersPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { if (!$container->hasDefinition('knp_menu.matcher')) { return; } $definition = $container->getDefinition('knp_menu.matcher'); $voters = []; foreach ($container->findTaggedServiceIds('knp_menu.voter') as $id => $tags) { // Process only the first tag. Registering the same voter multiple time // does not make any sense, and this allows user to overwrite the tag added // by the autoconfiguration to change the priority (autoconfigured tags are // always added at the end of the list). $tag = $tags[0]; $priority = isset($tag['priority']) ? (int) $tag['priority'] : 0; $voters[$priority][] = new Reference($id); } if (empty($voters)) { return; } krsort($voters); $sortedVoters = array_merge(...$voters); $definition->replaceArgument(0, new IteratorArgument($sortedVoters)); } }
923096e2ad0cd7c616b3f9aa02eb261042952cfa
database/migrations/2015_02_01_000003_create_blog_posts_table.php
database/migrations/2015_02_01_000003_create_blog_posts_table.php
<?php use Arcanesoft\Blog\Bases\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateBlogPostsTable * * @author ARCANEDEV <[email protected]> * * @see \Arcanesoft\Blog\Models\Post */ class CreateBlogPostsTable extends Migration { /* ----------------------------------------------------------------- | Constructor | ----------------------------------------------------------------- */ /** * CreateBlogPostsTable constructor. */ public function __construct() { parent::__construct(); $this->setTable('posts'); } /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * {@inheritdoc} */ public function up() { $this->createSchema(function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('author_id')->default(0); $table->unsignedInteger('category_id'); $table->string('locale', 5)->default(config('app.locale')); $table->string('title'); $table->string('slug'); $table->text('excerpt'); $table->string('thumbnail')->nullable(); $table->longtext('content_raw'); $table->longtext('content_html'); $table->boolean('is_draft')->default(false); $table->timestamps(); $table->timestamp('published_at'); $table->softDeletes(); $table->unique(['locale', 'slug']); }); } }
<?php use Arcanesoft\Blog\Bases\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateBlogPostsTable * * @author ARCANEDEV <[email protected]> * * @see \Arcanesoft\Blog\Models\Post */ class CreateBlogPostsTable extends Migration { /* ----------------------------------------------------------------- | Constructor | ----------------------------------------------------------------- */ /** * CreateBlogPostsTable constructor. */ public function __construct() { parent::__construct(); $this->setTable('posts'); } /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * {@inheritdoc} */ public function up() { $this->createSchema(function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('author_id')->default(0); $table->unsignedInteger('category_id'); $table->string('locale', 5)->default(config('app.locale')); $table->string('title'); $table->string('slug'); $table->text('excerpt'); $table->string('thumbnail')->nullable(); $table->longtext('content_raw'); $table->longtext('content_html'); $table->boolean('is_draft')->default(false); $table->timestamps(); $table->timestamp('published_at')->nullable(); $table->softDeletes(); $table->unique(['locale', 'slug']); }); } }
Fix the MySQL issue with not nullable timestamp
Fix the MySQL issue with not nullable timestamp
PHP
mit
ARCANESOFT/Blog,ARCANESOFT/Blog
php
## Code Before: <?php use Arcanesoft\Blog\Bases\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateBlogPostsTable * * @author ARCANEDEV <[email protected]> * * @see \Arcanesoft\Blog\Models\Post */ class CreateBlogPostsTable extends Migration { /* ----------------------------------------------------------------- | Constructor | ----------------------------------------------------------------- */ /** * CreateBlogPostsTable constructor. */ public function __construct() { parent::__construct(); $this->setTable('posts'); } /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * {@inheritdoc} */ public function up() { $this->createSchema(function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('author_id')->default(0); $table->unsignedInteger('category_id'); $table->string('locale', 5)->default(config('app.locale')); $table->string('title'); $table->string('slug'); $table->text('excerpt'); $table->string('thumbnail')->nullable(); $table->longtext('content_raw'); $table->longtext('content_html'); $table->boolean('is_draft')->default(false); $table->timestamps(); $table->timestamp('published_at'); $table->softDeletes(); $table->unique(['locale', 'slug']); }); } } ## Instruction: Fix the MySQL issue with not nullable timestamp ## Code After: <?php use Arcanesoft\Blog\Bases\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateBlogPostsTable * * @author ARCANEDEV <[email protected]> * * @see \Arcanesoft\Blog\Models\Post */ class CreateBlogPostsTable extends Migration { /* ----------------------------------------------------------------- | Constructor | ----------------------------------------------------------------- */ /** * CreateBlogPostsTable constructor. */ public function __construct() { parent::__construct(); $this->setTable('posts'); } /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * {@inheritdoc} */ public function up() { $this->createSchema(function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('author_id')->default(0); $table->unsignedInteger('category_id'); $table->string('locale', 5)->default(config('app.locale')); $table->string('title'); $table->string('slug'); $table->text('excerpt'); $table->string('thumbnail')->nullable(); $table->longtext('content_raw'); $table->longtext('content_html'); $table->boolean('is_draft')->default(false); $table->timestamps(); $table->timestamp('published_at')->nullable(); $table->softDeletes(); $table->unique(['locale', 'slug']); }); } }
3a0cf1f6114d6c80909f90fe122b026908200b0a
IPython/nbconvert/exporters/markdown.py
IPython/nbconvert/exporters/markdown.py
"""Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({ 'NbConvertBase': { 'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'] }, 'ExtractOutputPreprocessor': { 'enabled':True} }) c.merge(super(MarkdownExporter,self).default_config) return c
"""Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({'ExtractOutputPreprocessor':{'enabled':True}}) c.merge(super(MarkdownExporter,self).default_config) return c
Revert "Removed Javascript from Markdown by adding display priority to def config."
Revert "Removed Javascript from Markdown by adding display priority to def config." This reverts commit 58e05f9625c60f8deba9ddf1c74dba73e8ea7dd1.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
python
## Code Before: """Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({ 'NbConvertBase': { 'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'] }, 'ExtractOutputPreprocessor': { 'enabled':True} }) c.merge(super(MarkdownExporter,self).default_config) return c ## Instruction: Revert "Removed Javascript from Markdown by adding display priority to def config." This reverts commit 58e05f9625c60f8deba9ddf1c74dba73e8ea7dd1. ## Code After: """Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({'ExtractOutputPreprocessor':{'enabled':True}}) c.merge(super(MarkdownExporter,self).default_config) return c
89e6ce73a259f2bb050700e77b3059c6a327fe61
src/components/forms/UsernameControl.js
src/components/forms/UsernameControl.js
import React, { Component, PropTypes } from 'react' import FormControl from './FormControl' class UsernameControl extends Component { static propTypes = { suggestions: PropTypes.array, } static defaultProps = { className: 'UsernameControl', id: 'username', label: 'Username', name: 'user[username]', placeholder: 'Enter your username', suggestions: null, } onClickUsernameSuggestion = (e) => { const val = e.target.title this.formControl.onChangeControl({ target: { value: val } }) } renderSuggestions = () => { const { suggestions } = this.props if (suggestions && suggestions.length) { return ( <ul className="FormControlSuggestionList hasSuggestions"> <p>Here are some available usernames &mdash;</p> {suggestions.map((suggestion, i) => <li key={`suggestion_${i}`}> <button className="FormControlSuggestionButton" title={suggestion} onClick={this.onClickUsernameSuggestion} > {suggestion} </button> </li> )} </ul> ) } return ( <p className="FormControlSuggestionList"> <span /> </p> ) } render() { return ( <FormControl {...this.props} autoCapitalize="off" autoCorrect="off" ref={(comp) => { this.formControl = comp }} maxLength="50" renderFeedback={this.renderSuggestions} trimWhitespace type="text" /> ) } } export default UsernameControl
import React, { Component, PropTypes } from 'react' import FormControl from './FormControl' class UsernameControl extends Component { static propTypes = { suggestions: PropTypes.array, } static defaultProps = { className: 'UsernameControl', id: 'username', label: 'Username', name: 'user[username]', placeholder: 'Enter your username', suggestions: null, } onClickUsernameSuggestion = (e) => { const val = e.target.title const element = document.getElementById('username') if (element) { element.value = val } } renderSuggestions = () => { const { suggestions } = this.props if (suggestions && suggestions.length) { return ( <ul className="FormControlSuggestionList hasSuggestions"> <p>Here are some available usernames &mdash;</p> {suggestions.map((suggestion, i) => <li key={`suggestion_${i}`}> <button className="FormControlSuggestionButton" title={suggestion} onClick={this.onClickUsernameSuggestion} > {suggestion} </button> </li> )} </ul> ) } return ( <p className="FormControlSuggestionList"> <span /> </p> ) } render() { return ( <FormControl {...this.props} autoCapitalize="off" autoCorrect="off" maxLength="50" renderFeedback={this.renderSuggestions} trimWhitespace type="text" /> ) } } export default UsernameControl
Fix clicking on suggestion to set the username
Fix clicking on suggestion to set the username [Fixes: #128912639](https://www.pivotaltracker.com/story/show/128912639)
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
javascript
## Code Before: import React, { Component, PropTypes } from 'react' import FormControl from './FormControl' class UsernameControl extends Component { static propTypes = { suggestions: PropTypes.array, } static defaultProps = { className: 'UsernameControl', id: 'username', label: 'Username', name: 'user[username]', placeholder: 'Enter your username', suggestions: null, } onClickUsernameSuggestion = (e) => { const val = e.target.title this.formControl.onChangeControl({ target: { value: val } }) } renderSuggestions = () => { const { suggestions } = this.props if (suggestions && suggestions.length) { return ( <ul className="FormControlSuggestionList hasSuggestions"> <p>Here are some available usernames &mdash;</p> {suggestions.map((suggestion, i) => <li key={`suggestion_${i}`}> <button className="FormControlSuggestionButton" title={suggestion} onClick={this.onClickUsernameSuggestion} > {suggestion} </button> </li> )} </ul> ) } return ( <p className="FormControlSuggestionList"> <span /> </p> ) } render() { return ( <FormControl {...this.props} autoCapitalize="off" autoCorrect="off" ref={(comp) => { this.formControl = comp }} maxLength="50" renderFeedback={this.renderSuggestions} trimWhitespace type="text" /> ) } } export default UsernameControl ## Instruction: Fix clicking on suggestion to set the username [Fixes: #128912639](https://www.pivotaltracker.com/story/show/128912639) ## Code After: import React, { Component, PropTypes } from 'react' import FormControl from './FormControl' class UsernameControl extends Component { static propTypes = { suggestions: PropTypes.array, } static defaultProps = { className: 'UsernameControl', id: 'username', label: 'Username', name: 'user[username]', placeholder: 'Enter your username', suggestions: null, } onClickUsernameSuggestion = (e) => { const val = e.target.title const element = document.getElementById('username') if (element) { element.value = val } } renderSuggestions = () => { const { suggestions } = this.props if (suggestions && suggestions.length) { return ( <ul className="FormControlSuggestionList hasSuggestions"> <p>Here are some available usernames &mdash;</p> {suggestions.map((suggestion, i) => <li key={`suggestion_${i}`}> <button className="FormControlSuggestionButton" title={suggestion} onClick={this.onClickUsernameSuggestion} > {suggestion} </button> </li> )} </ul> ) } return ( <p className="FormControlSuggestionList"> <span /> </p> ) } render() { return ( <FormControl {...this.props} autoCapitalize="off" autoCorrect="off" maxLength="50" renderFeedback={this.renderSuggestions} trimWhitespace type="text" /> ) } } export default UsernameControl
497ebdbb95474e1f912654463ee16e2e2cf25466
analytics_dashboard/static/js/enrollment-geography-main.js
analytics_dashboard/static/js/enrollment-geography-main.js
/** * This is the first script called by the enrollment geography page. It loads * the libraries and kicks off the application. */ require(['vendor/domReady!', 'load/init-page'], function(doc, page) { 'use strict'; // this is your page specific code require(['views/data-table-view', 'views/world-map-view'], function(DataTableView, WorldMapView) { // Enrollment by country map var enrollmentGeographyMap = new WorldMapView({ el: '[data-view=world-map]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', // eslint-disable-next-line max-len tooltip: gettext('Learner location is determined from IP address. This map shows where learners ' + 'most recently connected.') }), // Enrollment by country table enrollmentGeographyTable = new DataTableView({ el: '[data-role=enrollment-location-table]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', columns: [ {key: 'countryName', title: gettext('Country')}, {key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'}, // Translators: The noun count (e.g. number of learners) {key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'} ], sorting: ['-count'] }); enrollmentGeographyTable.renderIfDataAvailable(); enrollmentGeographyMap.renderIfDataAvailable(); } ); });
/** * This is the first script called by the enrollment geography page. It loads * the libraries and kicks off the application. */ require(['vendor/domReady!', 'load/init-page'], function(doc, page) { 'use strict'; // this is your page specific code require(['views/data-table-view', 'views/world-map-view'], function(DataTableView, WorldMapView) { // Enrollment by country map var enrollmentGeographyMap = new WorldMapView({ el: '[data-view=world-map]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', // eslint-disable-next-line max-len tooltip: gettext('Learner location is determined from IP address. This map shows where learners most recently connected.') }), // Enrollment by country table enrollmentGeographyTable = new DataTableView({ el: '[data-role=enrollment-location-table]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', columns: [ {key: 'countryName', title: gettext('Country')}, {key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'}, // Translators: The noun count (e.g. number of learners) {key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'} ], sorting: ['-count'] }); enrollmentGeographyTable.renderIfDataAvailable(); enrollmentGeographyMap.renderIfDataAvailable(); } ); });
Address review: Put translated line on one line.
Address review: Put translated line on one line.
JavaScript
agpl-3.0
Stanford-Online/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,edx/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,edx/edx-analytics-dashboard
javascript
## Code Before: /** * This is the first script called by the enrollment geography page. It loads * the libraries and kicks off the application. */ require(['vendor/domReady!', 'load/init-page'], function(doc, page) { 'use strict'; // this is your page specific code require(['views/data-table-view', 'views/world-map-view'], function(DataTableView, WorldMapView) { // Enrollment by country map var enrollmentGeographyMap = new WorldMapView({ el: '[data-view=world-map]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', // eslint-disable-next-line max-len tooltip: gettext('Learner location is determined from IP address. This map shows where learners ' + 'most recently connected.') }), // Enrollment by country table enrollmentGeographyTable = new DataTableView({ el: '[data-role=enrollment-location-table]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', columns: [ {key: 'countryName', title: gettext('Country')}, {key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'}, // Translators: The noun count (e.g. number of learners) {key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'} ], sorting: ['-count'] }); enrollmentGeographyTable.renderIfDataAvailable(); enrollmentGeographyMap.renderIfDataAvailable(); } ); }); ## Instruction: Address review: Put translated line on one line. ## Code After: /** * This is the first script called by the enrollment geography page. It loads * the libraries and kicks off the application. */ require(['vendor/domReady!', 'load/init-page'], function(doc, page) { 'use strict'; // this is your page specific code require(['views/data-table-view', 'views/world-map-view'], function(DataTableView, WorldMapView) { // Enrollment by country map var enrollmentGeographyMap = new WorldMapView({ el: '[data-view=world-map]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', // eslint-disable-next-line max-len tooltip: gettext('Learner location is determined from IP address. This map shows where learners most recently connected.') }), // Enrollment by country table enrollmentGeographyTable = new DataTableView({ el: '[data-role=enrollment-location-table]', model: page.models.courseModel, modelAttribute: 'enrollmentByCountry', columns: [ {key: 'countryName', title: gettext('Country')}, {key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'}, // Translators: The noun count (e.g. number of learners) {key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'} ], sorting: ['-count'] }); enrollmentGeographyTable.renderIfDataAvailable(); enrollmentGeographyMap.renderIfDataAvailable(); } ); });
bcdd65f8c220249204df1e21b9d8c19fdbd94890
src/rules/property-no-unknown/index.js
src/rules/property-no-unknown/index.js
import { isString, isArray, isBoolean, } from "lodash" import { isStandardSyntaxProperty, isCustomProperty, report, ruleMessages, validateOptions, } from "../../utils" import { all as properties } from "known-css-properties" export const ruleName = "property-no-unknown" export const messages = ruleMessages(ruleName, { rejected: (property) => `Unexpected unknown property "${property}"`, }) const isPropertyIgnored = (prop, ignore) => { if (isArray(ignore)) { return ignore.indexOf(prop) > -1 } if (isString(ignore)) { return prop === ignore } return false } const isPropertyValid = (prop) => { return properties.indexOf(prop) > -1 } const validate = (result, options) => { return function (node) { const prop = node.prop if (!isStandardSyntaxProperty(prop)) { return } if (isCustomProperty(prop)) { return } if (isPropertyIgnored(prop, options.ignoreProperties)) { return } if (isPropertyValid(prop)) { return } report({ message: messages.rejected(node.prop), node, result, ruleName, }) } } export default function (enabled, options) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: enabled, possible: isBoolean, }, { actual: options, possible: { ignoreProperties: [isString], }, optional: true, }) if (!validOptions) { return } if (!enabled) { return } if (!options) { options = {} } root.walkDecls(validate(result, options)) } }
import { isString, isArray, } from "lodash" import { isStandardSyntaxProperty, isCustomProperty, report, ruleMessages, validateOptions, } from "../../utils" import { all as properties } from "known-css-properties" export const ruleName = "property-no-unknown" export const messages = ruleMessages(ruleName, { rejected: (property) => `Unexpected unknown property "${property}"`, }) export default function (actual, options) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual }, { actual: options, possible: { ignoreProperties: [isString], }, optional: true, }) if (!validOptions) { return } root.walkDecls(node => { const { prop } = node if (!isStandardSyntaxProperty(prop)) { return } if (isCustomProperty(prop)) { return } const ignoreProperties = options && options.ignoreProperties || [] if (isArray(ignoreProperties) && ignoreProperties.indexOf(prop) !== -1) { return } if (properties.indexOf(prop) !== -1) { return } report({ message: messages.rejected(node.prop), node, result, ruleName, }) }) } }
Fix rule to match the project standards
Fix rule to match the project standards
JavaScript
mit
stylelint/stylelint,hudochenkov/stylelint,stylelint/stylelint,heatwaveo8/stylelint,hudochenkov/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,heatwaveo8/stylelint,gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,gucong3000/stylelint,stylelint/stylelint,gaidarenko/stylelint,gaidarenko/stylelint,gucong3000/stylelint
javascript
## Code Before: import { isString, isArray, isBoolean, } from "lodash" import { isStandardSyntaxProperty, isCustomProperty, report, ruleMessages, validateOptions, } from "../../utils" import { all as properties } from "known-css-properties" export const ruleName = "property-no-unknown" export const messages = ruleMessages(ruleName, { rejected: (property) => `Unexpected unknown property "${property}"`, }) const isPropertyIgnored = (prop, ignore) => { if (isArray(ignore)) { return ignore.indexOf(prop) > -1 } if (isString(ignore)) { return prop === ignore } return false } const isPropertyValid = (prop) => { return properties.indexOf(prop) > -1 } const validate = (result, options) => { return function (node) { const prop = node.prop if (!isStandardSyntaxProperty(prop)) { return } if (isCustomProperty(prop)) { return } if (isPropertyIgnored(prop, options.ignoreProperties)) { return } if (isPropertyValid(prop)) { return } report({ message: messages.rejected(node.prop), node, result, ruleName, }) } } export default function (enabled, options) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: enabled, possible: isBoolean, }, { actual: options, possible: { ignoreProperties: [isString], }, optional: true, }) if (!validOptions) { return } if (!enabled) { return } if (!options) { options = {} } root.walkDecls(validate(result, options)) } } ## Instruction: Fix rule to match the project standards ## Code After: import { isString, isArray, } from "lodash" import { isStandardSyntaxProperty, isCustomProperty, report, ruleMessages, validateOptions, } from "../../utils" import { all as properties } from "known-css-properties" export const ruleName = "property-no-unknown" export const messages = ruleMessages(ruleName, { rejected: (property) => `Unexpected unknown property "${property}"`, }) export default function (actual, options) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual }, { actual: options, possible: { ignoreProperties: [isString], }, optional: true, }) if (!validOptions) { return } root.walkDecls(node => { const { prop } = node if (!isStandardSyntaxProperty(prop)) { return } if (isCustomProperty(prop)) { return } const ignoreProperties = options && options.ignoreProperties || [] if (isArray(ignoreProperties) && ignoreProperties.indexOf(prop) !== -1) { return } if (properties.indexOf(prop) !== -1) { return } report({ message: messages.rejected(node.prop), node, result, ruleName, }) }) } }
06656ca98f0f0136a8d4fb369129da03a49a03f3
lib/health_graph/api.rb
lib/health_graph/api.rb
module HealthGraph module API attr_accessor :access_token def get(path, accept_header, params = {}) request(:get, accept_header, path, params) end def post(path, accept_header, params = {}) request(:post, accept_header, path, params) end def put(path, accept_header, params = {}) request(:put, accept_header, path, params) end def delete(path, accept_header, params = {}) request(:delete, accept_header, path, params) end private def request(method, accept_header, path, params) response = connection(method).send(method) do |request| request.headers['Authorization'] = "Bearer #{access_token}" case method.to_sym when :get, :delete request.headers['Accept'] = accept_header request.url(path, params) when :put, :post request.headers['Content-Type'] = accept_header request.path = path request.body = params.to_json unless params.empty? end end response end def connection method merged_options = HealthGraph.faraday_options.merge({ :url => HealthGraph.endpoint }) Faraday.new(merged_options) do |builder| builder.use Faraday::Request::UrlEncoded builder.use Faraday::Request::JSON if method == :post builder.use Faraday::Response::Mashify builder.use Faraday::Response::ParseJson builder.adapter(HealthGraph.adapter) end end end end
module HealthGraph module API attr_accessor :access_token def get(path, accept_header, params = {}) request(:get, accept_header, path, params) end def post(path, accept_header, params = {}) request(:post, accept_header, path, params) end def put(path, accept_header, params = {}) request(:put, accept_header, path, params) end def delete(path, accept_header, params = {}) request(:delete, accept_header, path, params) end private def request(method, accept_header, path, params) response = connection(method).send(method) do |request| request.headers['Authorization'] = "Bearer #{access_token}" case method.to_sym when :get, :delete request.headers['Accept'] = accept_header request.url(path, params) when :put, :post request.headers['Content-Type'] = accept_header request.path = path request.body = params.to_json unless params.empty? end end response end def connection method merged_options = HealthGraph.faraday_options.merge({ :url => HealthGraph.endpoint }) Faraday.new(merged_options) do |builder| builder.use Faraday::Request::UrlEncoded builder.use FaradayMiddleware::EncodeJson if method == :post builder.use Faraday::Response::Mashify builder.use Faraday::Response::ParseJson builder.adapter(HealthGraph.adapter) end end end end
Fix removed Faraday JSON middleware.
Fix removed Faraday JSON middleware. The JSON request middleware is no longer included with Faraday. This seems to have already been partially fixed, since FaradayMiddleware was already a dependency. The tests are now passing on Ruby 1.9.
Ruby
mit
alchemyio/health_graph,chatterplug/health_graph,endoze/health_graph,kennyma/health_graph,dsjoerg/health_graph,naveed-ahmad/health_graph,JamesChevalier/health_graph
ruby
## Code Before: module HealthGraph module API attr_accessor :access_token def get(path, accept_header, params = {}) request(:get, accept_header, path, params) end def post(path, accept_header, params = {}) request(:post, accept_header, path, params) end def put(path, accept_header, params = {}) request(:put, accept_header, path, params) end def delete(path, accept_header, params = {}) request(:delete, accept_header, path, params) end private def request(method, accept_header, path, params) response = connection(method).send(method) do |request| request.headers['Authorization'] = "Bearer #{access_token}" case method.to_sym when :get, :delete request.headers['Accept'] = accept_header request.url(path, params) when :put, :post request.headers['Content-Type'] = accept_header request.path = path request.body = params.to_json unless params.empty? end end response end def connection method merged_options = HealthGraph.faraday_options.merge({ :url => HealthGraph.endpoint }) Faraday.new(merged_options) do |builder| builder.use Faraday::Request::UrlEncoded builder.use Faraday::Request::JSON if method == :post builder.use Faraday::Response::Mashify builder.use Faraday::Response::ParseJson builder.adapter(HealthGraph.adapter) end end end end ## Instruction: Fix removed Faraday JSON middleware. The JSON request middleware is no longer included with Faraday. This seems to have already been partially fixed, since FaradayMiddleware was already a dependency. The tests are now passing on Ruby 1.9. ## Code After: module HealthGraph module API attr_accessor :access_token def get(path, accept_header, params = {}) request(:get, accept_header, path, params) end def post(path, accept_header, params = {}) request(:post, accept_header, path, params) end def put(path, accept_header, params = {}) request(:put, accept_header, path, params) end def delete(path, accept_header, params = {}) request(:delete, accept_header, path, params) end private def request(method, accept_header, path, params) response = connection(method).send(method) do |request| request.headers['Authorization'] = "Bearer #{access_token}" case method.to_sym when :get, :delete request.headers['Accept'] = accept_header request.url(path, params) when :put, :post request.headers['Content-Type'] = accept_header request.path = path request.body = params.to_json unless params.empty? end end response end def connection method merged_options = HealthGraph.faraday_options.merge({ :url => HealthGraph.endpoint }) Faraday.new(merged_options) do |builder| builder.use Faraday::Request::UrlEncoded builder.use FaradayMiddleware::EncodeJson if method == :post builder.use Faraday::Response::Mashify builder.use Faraday::Response::ParseJson builder.adapter(HealthGraph.adapter) end end end end
1d5442aa70d2ed2569cc062d476129840d08a610
oscar/apps/shipping/repository.py
oscar/apps/shipping/repository.py
from django.core.exceptions import ImproperlyConfigured from oscar.apps.shipping.methods import Free, NoShippingRequired class Repository(object): """ Repository class responsible for returning ShippingMethod objects for a given user, basket etc """ def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs): """ Return a list of all applicable shipping method objects for a given basket. We default to returning the Method models that have been defined but this behaviour can easily be overridden by subclassing this class and overriding this method. """ methods = [Free()] return self.add_basket_to_methods(basket, methods) def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs): methods = self.get_shipping_methods(user, basket, shipping_addr, **kwargs) if len(methods) == 0: raise ImproperlyConfigured("You need to define some shipping methods") return methods[0] def add_basket_to_methods(self, basket, methods): for method in methods: method.set_basket(basket) return methods def find_by_code(self, code): """ Return the appropriate Method object for the given code """ known_methods = [Free, NoShippingRequired] for klass in known_methods: if code == getattr(klass, 'code'): return klass() return None
from django.core.exceptions import ImproperlyConfigured from oscar.apps.shipping.methods import Free, NoShippingRequired class Repository(object): """ Repository class responsible for returning ShippingMethod objects for a given user, basket etc """ def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs): """ Return a list of all applicable shipping method objects for a given basket. We default to returning the Method models that have been defined but this behaviour can easily be overridden by subclassing this class and overriding this method. """ methods = [Free()] return self.add_basket_to_methods(basket, methods) def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs): methods = self.get_shipping_methods(user, basket, shipping_addr, **kwargs) if len(methods) == 0: raise ImproperlyConfigured("You need to define some shipping methods") return min(methods, key=lambda method: method.basket_charge_incl_tax()) def add_basket_to_methods(self, basket, methods): for method in methods: method.set_basket(basket) return methods def find_by_code(self, code): """ Return the appropriate Method object for the given code """ known_methods = [Free, NoShippingRequired] for klass in known_methods: if code == getattr(klass, 'code'): return klass() return None
Make the cheapest shipping method the default one
Make the cheapest shipping method the default one
Python
bsd-3-clause
mexeniz/django-oscar,kapari/django-oscar,makielab/django-oscar,eddiep1101/django-oscar,Jannes123/django-oscar,thechampanurag/django-oscar,rocopartners/django-oscar,john-parton/django-oscar,elliotthill/django-oscar,itbabu/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj.com,marcoantoniooliveira/labweb,sonofatailor/django-oscar,vovanbo/django-oscar,ka7eh/django-oscar,jlmadurga/django-oscar,saadatqadri/django-oscar,amirrpp/django-oscar,makielab/django-oscar,bnprk/django-oscar,okfish/django-oscar,ahmetdaglarbas/e-commerce,manevant/django-oscar,ka7eh/django-oscar,kapari/django-oscar,MatthewWilkes/django-oscar,lijoantony/django-oscar,jmt4/django-oscar,elliotthill/django-oscar,anentropic/django-oscar,django-oscar/django-oscar,pdonadeo/django-oscar,jlmadurga/django-oscar,pdonadeo/django-oscar,django-oscar/django-oscar,john-parton/django-oscar,pasqualguerrero/django-oscar,okfish/django-oscar,josesanch/django-oscar,nfletton/django-oscar,WadeYuChen/django-oscar,binarydud/django-oscar,faratro/django-oscar,Jannes123/django-oscar,Idematica/django-oscar,dongguangming/django-oscar,WillisXChen/django-oscar,WillisXChen/django-oscar,lijoantony/django-oscar,rocopartners/django-oscar,nickpack/django-oscar,jlmadurga/django-oscar,sasha0/django-oscar,nfletton/django-oscar,WillisXChen/django-oscar,solarissmoke/django-oscar,taedori81/django-oscar,manevant/django-oscar,dongguangming/django-oscar,adamend/django-oscar,kapt/django-oscar,lijoantony/django-oscar,okfish/django-oscar,nfletton/django-oscar,Idematica/django-oscar,adamend/django-oscar,marcoantoniooliveira/labweb,faratro/django-oscar,solarissmoke/django-oscar,nickpack/django-oscar,nickpack/django-oscar,django-oscar/django-oscar,spartonia/django-oscar,spartonia/django-oscar,okfish/django-oscar,sonofatailor/django-oscar,WadeYuChen/django-oscar,pasqualguerrero/django-oscar,DrOctogon/unwash_ecom,kapari/django-oscar,MatthewWilkes/django-oscar,jinnykoo/christmas,makielab/django-oscar,QLGu/django-oscar,adamend/django-oscar,sasha0/django-oscar,michaelkuty/django-oscar,ademuk/django-oscar,john-parton/django-oscar,Bogh/django-oscar,bschuon/django-oscar,jmt4/django-oscar,pasqualguerrero/django-oscar,WillisXChen/django-oscar,makielab/django-oscar,django-oscar/django-oscar,vovanbo/django-oscar,saadatqadri/django-oscar,DrOctogon/unwash_ecom,dongguangming/django-oscar,thechampanurag/django-oscar,QLGu/django-oscar,jlmadurga/django-oscar,thechampanurag/django-oscar,monikasulik/django-oscar,binarydud/django-oscar,anentropic/django-oscar,monikasulik/django-oscar,jinnykoo/wuyisj.com,manevant/django-oscar,jinnykoo/wuyisj,rocopartners/django-oscar,MatthewWilkes/django-oscar,Jannes123/django-oscar,lijoantony/django-oscar,john-parton/django-oscar,kapari/django-oscar,anentropic/django-oscar,WadeYuChen/django-oscar,ahmetdaglarbas/e-commerce,monikasulik/django-oscar,marcoantoniooliveira/labweb,bschuon/django-oscar,monikasulik/django-oscar,michaelkuty/django-oscar,michaelkuty/django-oscar,Idematica/django-oscar,adamend/django-oscar,bschuon/django-oscar,taedori81/django-oscar,WillisXChen/django-oscar,pdonadeo/django-oscar,nfletton/django-oscar,thechampanurag/django-oscar,sasha0/django-oscar,ahmetdaglarbas/e-commerce,spartonia/django-oscar,eddiep1101/django-oscar,jinnykoo/wuyisj.com,taedori81/django-oscar,manevant/django-oscar,pdonadeo/django-oscar,kapt/django-oscar,MatthewWilkes/django-oscar,josesanch/django-oscar,jmt4/django-oscar,WadeYuChen/django-oscar,mexeniz/django-oscar,mexeniz/django-oscar,sonofatailor/django-oscar,binarydud/django-oscar,eddiep1101/django-oscar,vovanbo/django-oscar,ahmetdaglarbas/e-commerce,machtfit/django-oscar,itbabu/django-oscar,sonofatailor/django-oscar,Jannes123/django-oscar,faratro/django-oscar,saadatqadri/django-oscar,bnprk/django-oscar,elliotthill/django-oscar,taedori81/django-oscar,rocopartners/django-oscar,vovanbo/django-oscar,bnprk/django-oscar,michaelkuty/django-oscar,anentropic/django-oscar,machtfit/django-oscar,ka7eh/django-oscar,binarydud/django-oscar,itbabu/django-oscar,marcoantoniooliveira/labweb,eddiep1101/django-oscar,dongguangming/django-oscar,itbabu/django-oscar,jinnykoo/christmas,Bogh/django-oscar,jmt4/django-oscar,ademuk/django-oscar,amirrpp/django-oscar,sasha0/django-oscar,amirrpp/django-oscar,ademuk/django-oscar,pasqualguerrero/django-oscar,faratro/django-oscar,machtfit/django-oscar,jinnykoo/wuyisj,solarissmoke/django-oscar,solarissmoke/django-oscar,amirrpp/django-oscar,QLGu/django-oscar,josesanch/django-oscar,ka7eh/django-oscar,nickpack/django-oscar,jinnykoo/wuyisj,jinnykoo/wuyisj,jinnykoo/wuyisj.com,bschuon/django-oscar,kapt/django-oscar,WillisXChen/django-oscar,Bogh/django-oscar,saadatqadri/django-oscar,ademuk/django-oscar,bnprk/django-oscar,spartonia/django-oscar,QLGu/django-oscar,DrOctogon/unwash_ecom,jinnykoo/christmas,Bogh/django-oscar
python
## Code Before: from django.core.exceptions import ImproperlyConfigured from oscar.apps.shipping.methods import Free, NoShippingRequired class Repository(object): """ Repository class responsible for returning ShippingMethod objects for a given user, basket etc """ def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs): """ Return a list of all applicable shipping method objects for a given basket. We default to returning the Method models that have been defined but this behaviour can easily be overridden by subclassing this class and overriding this method. """ methods = [Free()] return self.add_basket_to_methods(basket, methods) def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs): methods = self.get_shipping_methods(user, basket, shipping_addr, **kwargs) if len(methods) == 0: raise ImproperlyConfigured("You need to define some shipping methods") return methods[0] def add_basket_to_methods(self, basket, methods): for method in methods: method.set_basket(basket) return methods def find_by_code(self, code): """ Return the appropriate Method object for the given code """ known_methods = [Free, NoShippingRequired] for klass in known_methods: if code == getattr(klass, 'code'): return klass() return None ## Instruction: Make the cheapest shipping method the default one ## Code After: from django.core.exceptions import ImproperlyConfigured from oscar.apps.shipping.methods import Free, NoShippingRequired class Repository(object): """ Repository class responsible for returning ShippingMethod objects for a given user, basket etc """ def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs): """ Return a list of all applicable shipping method objects for a given basket. We default to returning the Method models that have been defined but this behaviour can easily be overridden by subclassing this class and overriding this method. """ methods = [Free()] return self.add_basket_to_methods(basket, methods) def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs): methods = self.get_shipping_methods(user, basket, shipping_addr, **kwargs) if len(methods) == 0: raise ImproperlyConfigured("You need to define some shipping methods") return min(methods, key=lambda method: method.basket_charge_incl_tax()) def add_basket_to_methods(self, basket, methods): for method in methods: method.set_basket(basket) return methods def find_by_code(self, code): """ Return the appropriate Method object for the given code """ known_methods = [Free, NoShippingRequired] for klass in known_methods: if code == getattr(klass, 'code'): return klass() return None
3b2a81465ec55b25bea787804de27d548d8b0920
Shuttle/config/recaptcha.php
Shuttle/config/recaptcha.php
<?php return [ /* |-------------------------------------------------------------------------- | API Keys |-------------------------------------------------------------------------- | | Set the public and private API keys as provided by reCAPTCHA. | | In version 2 of reCAPTCHA, public_key is the Site key, | and private_key is the Secret key. | */ 'public_key' => env('RECAPTCHA_PUBLIC_KEY', '6LftQBITAAAAAMBrnzW4PRHaFo50LIUrG-yqyLA2'), 'private_key' => env('RECAPTCHA_PRIVATE_KEY', '6LftQBITAAAAAKQAUGBzy4hxbEKXmRGVA9mULDlV'), /* |-------------------------------------------------------------------------- | Template |-------------------------------------------------------------------------- | | Set a template to use if you don't want to use the standard one. | */ 'template' => '', /* |-------------------------------------------------------------------------- | Driver |-------------------------------------------------------------------------- | | Determine how to call out to get response; values are 'curl' or 'native'. | Only applies to v2. | */ 'driver' => 'curl', /* |-------------------------------------------------------------------------- | Options |-------------------------------------------------------------------------- | | Various options for the driver | */ 'options' => [ 'curl_timeout' => 1, ], /* |-------------------------------------------------------------------------- | Version |-------------------------------------------------------------------------- | | Set which version of ReCaptcha to use. | */ 'version' => 2, ];
<?php return [ /* |-------------------------------------------------------------------------- | API Keys |-------------------------------------------------------------------------- | | Set the public and private API keys as provided by reCAPTCHA. | | In version 2 of reCAPTCHA, public_key is the Site key, | and private_key is the Secret key. | */ 'public_key' => env('RECAPTCHA_PUBLIC_KEY', ''), 'private_key' => env('RECAPTCHA_PRIVATE_KEY', ''), /* |-------------------------------------------------------------------------- | Template |-------------------------------------------------------------------------- | | Set a template to use if you don't want to use the standard one. | */ 'template' => '', /* |-------------------------------------------------------------------------- | Driver |-------------------------------------------------------------------------- | | Determine how to call out to get response; values are 'curl' or 'native'. | Only applies to v2. | */ 'driver' => 'curl', /* |-------------------------------------------------------------------------- | Options |-------------------------------------------------------------------------- | | Various options for the driver | */ 'options' => [ 'curl_timeout' => 1, ], /* |-------------------------------------------------------------------------- | Version |-------------------------------------------------------------------------- | | Set which version of ReCaptcha to use. | */ 'version' => 2, ];
Remove keys. Keys were deleted, so don't mind trying to use them.
Remove keys. Keys were deleted, so don't mind trying to use them.
PHP
mit
pasadinhas/sirs-project,pasadinhas/sirs-project
php
## Code Before: <?php return [ /* |-------------------------------------------------------------------------- | API Keys |-------------------------------------------------------------------------- | | Set the public and private API keys as provided by reCAPTCHA. | | In version 2 of reCAPTCHA, public_key is the Site key, | and private_key is the Secret key. | */ 'public_key' => env('RECAPTCHA_PUBLIC_KEY', '6LftQBITAAAAAMBrnzW4PRHaFo50LIUrG-yqyLA2'), 'private_key' => env('RECAPTCHA_PRIVATE_KEY', '6LftQBITAAAAAKQAUGBzy4hxbEKXmRGVA9mULDlV'), /* |-------------------------------------------------------------------------- | Template |-------------------------------------------------------------------------- | | Set a template to use if you don't want to use the standard one. | */ 'template' => '', /* |-------------------------------------------------------------------------- | Driver |-------------------------------------------------------------------------- | | Determine how to call out to get response; values are 'curl' or 'native'. | Only applies to v2. | */ 'driver' => 'curl', /* |-------------------------------------------------------------------------- | Options |-------------------------------------------------------------------------- | | Various options for the driver | */ 'options' => [ 'curl_timeout' => 1, ], /* |-------------------------------------------------------------------------- | Version |-------------------------------------------------------------------------- | | Set which version of ReCaptcha to use. | */ 'version' => 2, ]; ## Instruction: Remove keys. Keys were deleted, so don't mind trying to use them. ## Code After: <?php return [ /* |-------------------------------------------------------------------------- | API Keys |-------------------------------------------------------------------------- | | Set the public and private API keys as provided by reCAPTCHA. | | In version 2 of reCAPTCHA, public_key is the Site key, | and private_key is the Secret key. | */ 'public_key' => env('RECAPTCHA_PUBLIC_KEY', ''), 'private_key' => env('RECAPTCHA_PRIVATE_KEY', ''), /* |-------------------------------------------------------------------------- | Template |-------------------------------------------------------------------------- | | Set a template to use if you don't want to use the standard one. | */ 'template' => '', /* |-------------------------------------------------------------------------- | Driver |-------------------------------------------------------------------------- | | Determine how to call out to get response; values are 'curl' or 'native'. | Only applies to v2. | */ 'driver' => 'curl', /* |-------------------------------------------------------------------------- | Options |-------------------------------------------------------------------------- | | Various options for the driver | */ 'options' => [ 'curl_timeout' => 1, ], /* |-------------------------------------------------------------------------- | Version |-------------------------------------------------------------------------- | | Set which version of ReCaptcha to use. | */ 'version' => 2, ];
da5b673ac234d3209da876a128d00b795a363572
kotpref/src/main/kotlin/com/chibatching/kotpref/KotprefPreferences.kt
kotpref/src/main/kotlin/com/chibatching/kotpref/KotprefPreferences.kt
package com.chibatching.kotpref import android.annotation.TargetApi import android.content.SharedPreferences import android.os.Build import com.chibatching.kotpref.pref.StringSetPref internal class KotprefPreferences(val preferences: SharedPreferences) : SharedPreferences by preferences { override fun edit(): SharedPreferences.Editor { return KotprefEditor(preferences.edit()) } internal inner class KotprefEditor(val editor: SharedPreferences.Editor) : SharedPreferences.Editor by editor { private val prefStringSet: HashMap<String, StringSetPref.PrefMutableSet> by lazy { HashMap<String, StringSetPref.PrefMutableSet>() } override fun apply() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.forEach { key, set -> editor.putStringSet(key, set) set.syncTransaction() } prefStringSet.clear() } editor.apply() } override fun commit(): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.forEach { key, set -> editor.putStringSet(key, set) set.syncTransaction() } prefStringSet.clear() } return editor.commit() } @TargetApi(Build.VERSION_CODES.HONEYCOMB) internal fun putStringSet(key: String, prefSet: StringSetPref.PrefMutableSet): SharedPreferences.Editor { prefStringSet.put(key, prefSet) return this } } }
package com.chibatching.kotpref import android.annotation.TargetApi import android.content.SharedPreferences import android.os.Build import com.chibatching.kotpref.pref.StringSetPref import java.util.* internal class KotprefPreferences(val preferences: SharedPreferences) : SharedPreferences by preferences { override fun edit(): SharedPreferences.Editor { return KotprefEditor(preferences.edit()) } internal inner class KotprefEditor(val editor: SharedPreferences.Editor) : SharedPreferences.Editor by editor { private val prefStringSet: MutableMap<String, StringSetPref.PrefMutableSet> by lazy { HashMap<String, StringSetPref.PrefMutableSet>() } override fun apply() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.keys.forEach { key -> prefStringSet[key]?.let { editor.putStringSet(key, it) it.syncTransaction() } } prefStringSet.clear() } editor.apply() } override fun commit(): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.forEach { key, set -> editor.putStringSet(key, set) set.syncTransaction() } prefStringSet.clear() } return editor.commit() } @TargetApi(Build.VERSION_CODES.HONEYCOMB) internal fun putStringSet(key: String, prefSet: StringSetPref.PrefMutableSet): SharedPreferences.Editor { prefStringSet.put(key, prefSet) return this } } }
Remove java 8 api call to avoid crash on Android
Remove java 8 api call to avoid crash on Android
Kotlin
apache-2.0
chibatching/Kotpref
kotlin
## Code Before: package com.chibatching.kotpref import android.annotation.TargetApi import android.content.SharedPreferences import android.os.Build import com.chibatching.kotpref.pref.StringSetPref internal class KotprefPreferences(val preferences: SharedPreferences) : SharedPreferences by preferences { override fun edit(): SharedPreferences.Editor { return KotprefEditor(preferences.edit()) } internal inner class KotprefEditor(val editor: SharedPreferences.Editor) : SharedPreferences.Editor by editor { private val prefStringSet: HashMap<String, StringSetPref.PrefMutableSet> by lazy { HashMap<String, StringSetPref.PrefMutableSet>() } override fun apply() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.forEach { key, set -> editor.putStringSet(key, set) set.syncTransaction() } prefStringSet.clear() } editor.apply() } override fun commit(): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.forEach { key, set -> editor.putStringSet(key, set) set.syncTransaction() } prefStringSet.clear() } return editor.commit() } @TargetApi(Build.VERSION_CODES.HONEYCOMB) internal fun putStringSet(key: String, prefSet: StringSetPref.PrefMutableSet): SharedPreferences.Editor { prefStringSet.put(key, prefSet) return this } } } ## Instruction: Remove java 8 api call to avoid crash on Android ## Code After: package com.chibatching.kotpref import android.annotation.TargetApi import android.content.SharedPreferences import android.os.Build import com.chibatching.kotpref.pref.StringSetPref import java.util.* internal class KotprefPreferences(val preferences: SharedPreferences) : SharedPreferences by preferences { override fun edit(): SharedPreferences.Editor { return KotprefEditor(preferences.edit()) } internal inner class KotprefEditor(val editor: SharedPreferences.Editor) : SharedPreferences.Editor by editor { private val prefStringSet: MutableMap<String, StringSetPref.PrefMutableSet> by lazy { HashMap<String, StringSetPref.PrefMutableSet>() } override fun apply() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.keys.forEach { key -> prefStringSet[key]?.let { editor.putStringSet(key, it) it.syncTransaction() } } prefStringSet.clear() } editor.apply() } override fun commit(): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { prefStringSet.forEach { key, set -> editor.putStringSet(key, set) set.syncTransaction() } prefStringSet.clear() } return editor.commit() } @TargetApi(Build.VERSION_CODES.HONEYCOMB) internal fun putStringSet(key: String, prefSet: StringSetPref.PrefMutableSet): SharedPreferences.Editor { prefStringSet.put(key, prefSet) return this } } }
6243d3ceb43bbdd0ca778bf02b19f895499a0c52
src/js/breadcrumbs/breadcrumbs-view.js
src/js/breadcrumbs/breadcrumbs-view.js
/** * A Backbone view that renders breadcrumbs-type tiered navigation. * * Initialize the view by passing in the following attributes: * *~~~ javascript * var view = new DropdownMenuView({ * el: $('selector for element that will contain breadcrumbs'), * model: new BreadcrumbsModel({ * breadcrumbs: [{url: '/', title: 'Overview'}] * }), * events: { * 'click nav.breadcrumbs a.nav-item': function (event) { * event.preventDefault(); * window.location = $(event.currentTarget).attr('href'); * } * } * }); *~~~ * @module BreadcrumbsView */ ;(function (define) { 'use strict'; define(['backbone', 'edx-ui-toolkit/js/utils/html-utils', 'text!./breadcrumbs.underscore'], function (Backbone, HtmlUtils, breadcrumbsTemplate) { var BreadcrumbsView = Backbone.View.extend({ initialize: function (options) { this.template = HtmlUtils.template(breadcrumbsTemplate); this.listenTo(this.model, 'change', this.render); this.render(); }, render: function () { var json = this.model.attributes; HtmlUtils.setHtml(this.$el, this.template(json)); return this; } }); return BreadcrumbsView; }); }).call( this, // Use the default 'define' function if available, else use 'RequireJS.define' typeof define === 'function' && define.amd ? define : RequireJS.define );
/** * A Backbone view that renders breadcrumbs-type tiered navigation. * * Initialize the view by passing in the following attributes: * *~~~ javascript * var view = new BreadcrumbsView({ * el: $('selector for element that will contain breadcrumbs'), * model: new BreadcrumbsModel({ * breadcrumbs: [{url: '/', title: 'Overview'}] * }), * events: { * 'click nav.breadcrumbs a.nav-item': function (event) { * event.preventDefault(); * window.location = $(event.currentTarget).attr('href'); * } * } * }); *~~~ * @module BreadcrumbsView */ ;(function (define) { 'use strict'; define(['backbone', 'edx-ui-toolkit/js/utils/html-utils', 'text!./breadcrumbs.underscore'], function (Backbone, HtmlUtils, breadcrumbsTemplate) { var BreadcrumbsView = Backbone.View.extend({ initialize: function (options) { this.template = HtmlUtils.template(breadcrumbsTemplate); this.listenTo(this.model, 'change', this.render); this.render(); }, render: function () { var json = this.model.attributes; HtmlUtils.setHtml(this.$el, this.template(json)); return this; } }); return BreadcrumbsView; }); }).call( this, // Use the default 'define' function if available, else use 'RequireJS.define' typeof define === 'function' && define.amd ? define : RequireJS.define );
Fix BreadcrumbsView docs that still said DropdownMenuView
Fix BreadcrumbsView docs that still said DropdownMenuView
JavaScript
apache-2.0
edx/edx-ui-toolkit,edx/edx-ui-toolkit
javascript
## Code Before: /** * A Backbone view that renders breadcrumbs-type tiered navigation. * * Initialize the view by passing in the following attributes: * *~~~ javascript * var view = new DropdownMenuView({ * el: $('selector for element that will contain breadcrumbs'), * model: new BreadcrumbsModel({ * breadcrumbs: [{url: '/', title: 'Overview'}] * }), * events: { * 'click nav.breadcrumbs a.nav-item': function (event) { * event.preventDefault(); * window.location = $(event.currentTarget).attr('href'); * } * } * }); *~~~ * @module BreadcrumbsView */ ;(function (define) { 'use strict'; define(['backbone', 'edx-ui-toolkit/js/utils/html-utils', 'text!./breadcrumbs.underscore'], function (Backbone, HtmlUtils, breadcrumbsTemplate) { var BreadcrumbsView = Backbone.View.extend({ initialize: function (options) { this.template = HtmlUtils.template(breadcrumbsTemplate); this.listenTo(this.model, 'change', this.render); this.render(); }, render: function () { var json = this.model.attributes; HtmlUtils.setHtml(this.$el, this.template(json)); return this; } }); return BreadcrumbsView; }); }).call( this, // Use the default 'define' function if available, else use 'RequireJS.define' typeof define === 'function' && define.amd ? define : RequireJS.define ); ## Instruction: Fix BreadcrumbsView docs that still said DropdownMenuView ## Code After: /** * A Backbone view that renders breadcrumbs-type tiered navigation. * * Initialize the view by passing in the following attributes: * *~~~ javascript * var view = new BreadcrumbsView({ * el: $('selector for element that will contain breadcrumbs'), * model: new BreadcrumbsModel({ * breadcrumbs: [{url: '/', title: 'Overview'}] * }), * events: { * 'click nav.breadcrumbs a.nav-item': function (event) { * event.preventDefault(); * window.location = $(event.currentTarget).attr('href'); * } * } * }); *~~~ * @module BreadcrumbsView */ ;(function (define) { 'use strict'; define(['backbone', 'edx-ui-toolkit/js/utils/html-utils', 'text!./breadcrumbs.underscore'], function (Backbone, HtmlUtils, breadcrumbsTemplate) { var BreadcrumbsView = Backbone.View.extend({ initialize: function (options) { this.template = HtmlUtils.template(breadcrumbsTemplate); this.listenTo(this.model, 'change', this.render); this.render(); }, render: function () { var json = this.model.attributes; HtmlUtils.setHtml(this.$el, this.template(json)); return this; } }); return BreadcrumbsView; }); }).call( this, // Use the default 'define' function if available, else use 'RequireJS.define' typeof define === 'function' && define.amd ? define : RequireJS.define );
156d6f7dd56a5f2554a425fb5a001c99656e320b
semanticize/_semanticizer.py
semanticize/_semanticizer.py
import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(sentence + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__()
import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(json.dumps(sentence) + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__()
Send json to semanticizer stdin
Send json to semanticizer stdin
Python
apache-2.0
semanticize/st,semanticize/st
python
## Code Before: import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(sentence + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__() ## Instruction: Send json to semanticizer stdin ## Code After: import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(json.dumps(sentence) + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__()
99abd852d689b419bc130f8d995d8e73bdfe51b5
spec/shared/common/views/visualisations/bar-chart/spec.user-satisfaction.js
spec/shared/common/views/visualisations/bar-chart/spec.user-satisfaction.js
define([ 'common/views/visualisations/bar-chart/user-satisfaction', 'common/views/visualisations/bar-chart/bar-chart', 'common/collections/journey', 'extensions/collections/collection', 'backbone' ], function (UserSatisfaction, BarChart, JourneyCollection, Collection, Backbone) { describe('UserSatisfaction Bar Chart', function () { var graph; beforeEach(function () { spyOn(UserSatisfaction.prototype, 'render'); graph = new UserSatisfaction({ collection: new Collection([ { values: new Collection([]) } ], { format: 'integer' }) }); }); describe('initialize()', function () { it('calls render() on a reset of the collection data', function () { expect(UserSatisfaction.prototype.render).not.toHaveBeenCalled(); graph.collection.at(0).get('values').reset(); expect(UserSatisfaction.prototype.render).toHaveBeenCalled(); }); }); describe('components()', function () { beforeEach(function () { spyOn(BarChart.prototype, 'components').andReturn({ hover: { view: {} }, xaxis: { view: Backbone.View } }); }); it('removes the hover component from the BarChart', function () { expect(graph.components().hover).toBeUndefined(); }); it('removes the yaxis component from the BarChart', function () { expect(graph.components().yaxis).toBeUndefined(); }); it('sets the xasis to not useEllipses', function () { expect(graph.components().xaxis.view.prototype.useEllipses).toEqual(false); }); }); }); });
define([ 'common/views/visualisations/bar-chart/user-satisfaction', 'common/views/visualisations/bar-chart/bar-chart', 'extensions/collections/collection', 'backbone' ], function (UserSatisfaction, BarChart, Collection, Backbone) { describe('UserSatisfaction Bar Chart', function () { var graph; beforeEach(function () { spyOn(UserSatisfaction.prototype, 'render'); graph = new UserSatisfaction({ collection: new Collection([], { format: 'integer' }) }); }); describe('initialize()', function () { it('calls render() on a reset of the collection data', function () { expect(UserSatisfaction.prototype.render).not.toHaveBeenCalled(); graph.collection.reset(); expect(UserSatisfaction.prototype.render).toHaveBeenCalled(); }); }); describe('components()', function () { beforeEach(function () { spyOn(BarChart.prototype, 'components').andReturn({ hover: { view: {} }, xaxis: { view: Backbone.View } }); }); it('removes the hover component from the BarChart', function () { expect(graph.components().hover).toBeUndefined(); }); it('removes the yaxis component from the BarChart', function () { expect(graph.components().yaxis).toBeUndefined(); }); it('sets the xasis to not useEllipses', function () { expect(graph.components().xaxis.view.prototype.useEllipses).toEqual(false); }); }); }); });
Fix user satisfaction bar charts tests following removal of the matrix
Fix user satisfaction bar charts tests following removal of the matrix
JavaScript
mit
tijmenb/spotlight,keithiopia/spotlight,alphagov/spotlight,tijmenb/spotlight,alphagov/spotlight,alphagov/spotlight,keithiopia/spotlight,keithiopia/spotlight,tijmenb/spotlight
javascript
## Code Before: define([ 'common/views/visualisations/bar-chart/user-satisfaction', 'common/views/visualisations/bar-chart/bar-chart', 'common/collections/journey', 'extensions/collections/collection', 'backbone' ], function (UserSatisfaction, BarChart, JourneyCollection, Collection, Backbone) { describe('UserSatisfaction Bar Chart', function () { var graph; beforeEach(function () { spyOn(UserSatisfaction.prototype, 'render'); graph = new UserSatisfaction({ collection: new Collection([ { values: new Collection([]) } ], { format: 'integer' }) }); }); describe('initialize()', function () { it('calls render() on a reset of the collection data', function () { expect(UserSatisfaction.prototype.render).not.toHaveBeenCalled(); graph.collection.at(0).get('values').reset(); expect(UserSatisfaction.prototype.render).toHaveBeenCalled(); }); }); describe('components()', function () { beforeEach(function () { spyOn(BarChart.prototype, 'components').andReturn({ hover: { view: {} }, xaxis: { view: Backbone.View } }); }); it('removes the hover component from the BarChart', function () { expect(graph.components().hover).toBeUndefined(); }); it('removes the yaxis component from the BarChart', function () { expect(graph.components().yaxis).toBeUndefined(); }); it('sets the xasis to not useEllipses', function () { expect(graph.components().xaxis.view.prototype.useEllipses).toEqual(false); }); }); }); }); ## Instruction: Fix user satisfaction bar charts tests following removal of the matrix ## Code After: define([ 'common/views/visualisations/bar-chart/user-satisfaction', 'common/views/visualisations/bar-chart/bar-chart', 'extensions/collections/collection', 'backbone' ], function (UserSatisfaction, BarChart, Collection, Backbone) { describe('UserSatisfaction Bar Chart', function () { var graph; beforeEach(function () { spyOn(UserSatisfaction.prototype, 'render'); graph = new UserSatisfaction({ collection: new Collection([], { format: 'integer' }) }); }); describe('initialize()', function () { it('calls render() on a reset of the collection data', function () { expect(UserSatisfaction.prototype.render).not.toHaveBeenCalled(); graph.collection.reset(); expect(UserSatisfaction.prototype.render).toHaveBeenCalled(); }); }); describe('components()', function () { beforeEach(function () { spyOn(BarChart.prototype, 'components').andReturn({ hover: { view: {} }, xaxis: { view: Backbone.View } }); }); it('removes the hover component from the BarChart', function () { expect(graph.components().hover).toBeUndefined(); }); it('removes the yaxis component from the BarChart', function () { expect(graph.components().yaxis).toBeUndefined(); }); it('sets the xasis to not useEllipses', function () { expect(graph.components().xaxis.view.prototype.useEllipses).toEqual(false); }); }); }); });