text
stringlengths
27
775k
using Foundation; using System; using System.Collections.Generic; using System.CodeDom.Compiler; using UIKit; namespace BookStore { public class Book { public String Name { get; set; } public String Author { get; set; } public String Editor { get; set; } public int Year { get; set; } } partial class BooksTableViewController : UITableViewController { List<Book> bookList; public BooksTableViewController(IntPtr handle) : base(handle) { this.bookList = new List<Book>(); this.bookList.Add(new Book() { Author = "Author 1", Name = "Book 1", Editor = "Editor 1", Year = 2001 }); this.bookList.Add(new Book() { Author = "Author 1", Name = "Book 2", Editor = "Editor 1", Year = 2001 }); this.bookList.Add(new Book() { Author = "Author 1", Name = "Book 3", Editor = "Editor 1", Year = 2001 }); } public override nint NumberOfSections(UITableView tableView) { //return base.NumberOfSections(tableView); return 1; } public override nint RowsInSection(UITableView tableView, nint section) { //return base.RowsInSection(tableView, section); return bookList.Count; } // Returns a reusable cell, change it values and returns it to be added to the table view public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell("Book") as BookTableViewCell; var dataInTheCell = this.bookList[indexPath.Row]; cell.BookData = dataInTheCell; return cell; //return base.GetCell(tableView, indexPath); } } }
#!/bin/bash rs_taskstart="" rs_taskname="" rs_task_start() { rs_log_info $(printf "\033[1mstarting task:\033[0m %s\n" "$1") rs_taskname=$1 rs_taskstart=$(date +%s.%N) } rs_task_done() { cd $RS_PATH local timer=$(date +%s.%N) local dt=$(echo "$timer - $rs_taskstart" | bc) local dd=$(echo "$dt/86400" | bc) local dt2=$(echo "$dt-86400*$dd" | bc) local dh=$(echo "$dt2/3600" | bc) local dt3=$(echo "$dt2-3600*$dh" | bc) local dm=$(echo "$dt3/60" | bc) local ds=$(echo "$dt3-60*$dm" | bc) local msg="${1-""}" if [ ! -z "$msg" ]; then rs_log_info $msg; fi rs_log_info $(printf "\033[1m$rs_taskname finished\033[0m") rs_log_ok $(printf "task done \033[1mexecution time: \033[0m %dd %02dh %02dm %02.4fs" $dd $dh $dm $ds ) exit 0 } rs_task_failed() { local timer=$(date +%s.%N) local dt=$(echo "$timer - $rs_taskstart" | bc) local dd=$(echo "$dt/86400" | bc) local dt2=$(echo "$dt-86400*$dd" | bc) local dh=$(echo "$dt2/3600" | bc) local dt3=$(echo "$dt2-3600*$dh" | bc) local dm=$(echo "$dt3/60" | bc) local ds=$(echo "$dt3-60*$dm" | bc) rs_log_err $(printf "\033[1mtask %s failed:\033[0m %s" "$rs_taskname" "$1") rs_log_err $(printf "\033[1mexecution time: \033[0m %dd %02dh %02dm %02.4fs" $dd $dh $dm $ds ) exit 1 }
#include <renderable.h> #include <geometry/cleaner.h> namespace Model { Renderable::Renderable(const std::string &name) :m_name(name), m_selected(false), m_visible(true) { } const std::string &Renderable::name() const { return m_name; } bool Renderable::visible() const { return m_visible; } void Renderable::setVisible(bool visible) { if (m_visible != visible) { m_visible = visible; emit visibilityChanged(m_visible); } } void Renderable::toggleVisible() { setVisible(!m_visible); } void Renderable::setSelected(bool selected) { if (m_selected != selected) { m_selected = selected; emit selectedChanged(m_selected); } } void Renderable::toggleSelect() { setSelected(!m_selected); } }
require 'ffi' require 'java' module Process class Foreign SC_CLK_TCK = com.kenai.constantine.platform.Sysconf::_SC_CLK_TCK.value extend FFI::Library ffi_lib FFI::Library::LIBC class Times < FFI::Struct layout \ :utime => :long, :stime => :long, :cutime => :long, :cstime => :long end attach_function :times, [ :buffer_out ], :long attach_function :sysconf, [ :int ], :long Tms = Struct.new("Foreign::Tms", :utime, :stime, :cutime, :cstime) end def self.times hz = Foreign.sysconf(Foreign::SC_CLK_TCK).to_f t = Foreign::Times.alloc_out(false) Foreign.times(t.pointer) Foreign::Tms.new(t[:utime] / hz, t[:stime] / hz, t[:cutime] / hz, t[:cstime] / hz) end end if $0 == __FILE__ while true 10.times { system("ls -l / > /dev/null") } t = Process.times puts "utime=#{t.utime} stime=#{t.stime} cutime=#{t.cutime} cstime=#{t.cstime}" sleep 1 end end
package opengis.process.model /** * Created by Chris on 28/01/2018. */ open class TileData( val rawImageData: ByteArray )
package com.github.cuzfrog import java.awt.Color object GenericPolymor { trait Pet[A] { def name(a: A): String def renamed(a: A, newName: String): A } implicit class PetOps[A](a: A)(implicit ev: Pet[A]) { def name = ev.name(a) def renamed(newName: String): A = ev.renamed(a, newName) } case class Fish(name: String, age: Int) object Fish { implicit object FishPet extends Pet[Fish] { def name(a: Fish) = a.name def renamed(a: Fish, newName: String) = a.copy(name = newName) } } case class Kitty(name: String, color: Color) object Kitty { implicit object KittyPet extends Pet[Kitty] { def name(a: Kitty) = a.name def renamed(a: Kitty, newName: String) = a.copy(name = newName) } } def esquire[A: Pet](a: A): A = a.renamed(a.name + ", Esq.") val bob = Fish("Bob", 12) val thor = Kitty("Thor", Color.ORANGE) val l1 = List[(A, Pet[A]) forSome {type A}]((bob, implicitly[Pet[Fish]]), (thor, implicitly[Pet[Kitty]])) l1.map { case (a, ev) => esquire(a)(ev) }.foreach(println) }
#!/bin/bash while true do echo "Attempting to poke" sh ./smart_poke.sh sleep 3 done
<?php /** * Author: imsamurai <[email protected]> * Date: 08.07.2013 * Time: 18:09:32 * Format: http://book.cakephp.org/2.0/en/development/testing.html */ App::uses('Monitoring', 'Monitoring.Model'); App::uses('MonitoringChecker', 'Monitoring.Lib/Monitoring'); /** * MonitoringTest * * @property Monitoring $Monitoring Monitoring model * * @package MonitoringTest * @subpackage Model */ class MonitoringTest extends CakeTestCase { /** * Fixtures * * @var array */ public $fixtures = array( 'plugin.Monitoring.Monitoring', 'plugin.Monitoring.MonitoringLog' ); /** * setUp method * * @return void */ public function setUp() { parent::setUp(); $this->Monitoring = ClassRegistry::init('Monitoring.Monitoring'); $config = array( 'dateFormat' => 'H:i:s d.m.Y', 'dbDateFormat' => 'Y-m-d H:i:s', 'checkersPath' => 'Lib/Monitoring', 'defaults' => array( 'cron' => '0 15 * * *', 'timeout' => 600, 'active' => false, 'priority' => 0 ), 'email' => array( 'enabled' => array( 'fail' => true, 'stillFail' => true, 'success' => false, 'backToNormal' => true, ), 'config' => 'default', 'subject' => array( 'fail' => 'Monitoring: %s is fail!', 'stillFail' => 'Monitoring: %s still failing!', 'success' => 'Monitoring: %s is ok!', 'backToNormal' => 'Monitoring: %s back to normal!', ) ), 'views' => array( 'pluginFirst' => false ), 'checkers' => array( 'MonitoringSelfFailCheck' => array( 'defaults' => array( 'errorText' => 'MonitoringSelfFailCheck error text' ) ) ) ); Configure::write('Monitoring', $config); } /** * Test get active checkers * * @param array $checkers * @param bool $checkNext * @param array $ids * * @dataProvider getActiveCheckersProvider */ public function testGetActiveCheckers(array $checkers, $checkNext, array $ids) { $this->Monitoring->saveMany($checkers); $checkers = $this->Monitoring->getActiveCheckers($checkNext); $this->assertSame($ids, array_map('intval', Hash::extract($checkers, '{n}.id'))); } /** * Data provider for testGetActiveCheckers * * @return array */ public function getActiveCheckersProvider() { return array( //set #0 array( //checkers array( array( 'id' => 2, 'name' => 'Test2', 'active' => 0, 'cron' => '*/5 * * * *', 'priority' => 0, 'last_check' => date(Configure::read('Monitoring.dbDateFormat')) ), array( 'id' => 3, 'name' => 'Test3', 'active' => 1, 'cron' => '* * * * *', 'last_check' => date(Configure::read('Monitoring.dbDateFormat')) ), array( 'id' => 4, 'name' => 'Test4', 'active' => 1, 'cron' => '* * * * *', 'priority' => 1, 'last_check' => '0000-00-00 00:00:00' ) ), //checkNext false, //ids array( 4, 3 ) ), //set #1 array( //checkers array( array( 'id' => 2, 'name' => 'Test2', 'active' => 0, 'cron' => '*/5 * * * *', 'priority' => 0, 'last_check' => date(Configure::read('Monitoring.dbDateFormat')) ), array( 'id' => 3, 'name' => 'Test3', 'active' => 1, 'cron' => '*/3 */4 * * *', 'last_check' => date(Configure::read('Monitoring.dbDateFormat')) ), array( 'id' => 4, 'name' => 'Test4', 'active' => 1, 'cron' => '1 12 * * *', 'priority' => 1, 'last_check' => '0000-00-00 00:00:00' ) ), //checkNext true, //ids array() ), ); } /** * Test BeforeSave * * @param array $checkerIn * @param array $checkerOut * * @dataProvider beforeSaveProvider */ public function testBeforeSave(array $checkerIn, array $checkerOut) { $this->Monitoring->set($checkerIn); $this->Monitoring->beforeSave(); $this->assertSame($checkerOut, $this->Monitoring->data[$this->Monitoring->alias]); } /** * Data provider for testBeforeSave * * @return array */ public function beforeSaveProvider() { return array( //set #0 array( //checkerIn array( 'id' => 4, 'name' => 'Test4', 'active' => 1, 'cron' => '0 0 * * *', 'priority' => 1, 'last_check' => '0000-00-00 00:00:00' ), //checkerOut array( 'id' => 4, 'name' => 'Test4', 'active' => 1, 'cron' => '0 0 * * *', 'priority' => 1, 'last_check' => '0000-00-00 00:00:00', 'next_check' => (new DateTime('tomorrow'))->format(Configure::read('Monitoring.dbDateFormat')) ) ), //set #1 array( //checkerIn array( 'id' => 4, 'name' => 'Test4', 'active' => 1, 'priority' => 1, 'last_check' => '0000-00-00 00:00:00' ), //checkerOut array( 'id' => 4, 'name' => 'Test4', 'active' => 1, 'priority' => 1, 'last_check' => '0000-00-00 00:00:00', 'cron' => '0 15 * * *', 'next_check' => Cron\CronExpression::factory('0 15 * * *') ->getNextRunDate('now') ->format(Configure::read('Monitoring.dbDateFormat')) ) ), ); } /** * Test find all checker classes */ public function testFindAllCheckerClasses() { $classes = $this->Monitoring->findAllCheckerClasses(); $this->assertNotEmpty($classes); $this->assertTrue(count(array_intersect($classes, array( 'Monitoring.MonitoringSelfCheck', 'Monitoring.MonitoringSelfFailCheck' ))) === 2); } /** * Test find new checkers */ public function testFindNewCheckers() { $this->Monitoring->add('Monitoring.MonitoringSelfCheck'); $classes = $this->Monitoring->findNewCheckers(); $this->assertNotEmpty($classes); $this->assertTrue(count(array_intersect($classes, array( 'Monitoring.MonitoringSelfCheck', 'Monitoring.MonitoringSelfFailCheck' ))) === 1); } /** * Test save check results * * @param int $id * @param string $status * @param string $error * * @dataProvider saveCheckResultsProvider */ public function testSaveCheckResults($id, $status, $error) { $this->Monitoring->add('Monitoring.MonitoringSelfCheck', array('id' => $id)); $this->Monitoring->saveCheckResults($id, $status, $error); $this->Monitoring->contain(array( 'MonitoringLog' )); $checker = $this->Monitoring->findById($id); //debug($checker); $this->assertEqual($checker['Monitoring']['last_code_string'], $status); $this->assertEqual($checker['MonitoringLog'][0]['code_string'], $status); $this->assertEqual($checker['MonitoringLog'][0]['error'], $error); } /** * Data provider for testSaveCheckResults * * @return array */ public function saveCheckResultsProvider() { return array( //set #0 array( //checkerId 1, //codeString MonitoringChecker::STATUS_OK, //error '' ), //set #1 array( //checkerId 2, //codeString MonitoringChecker::STATUS_FAIL, //error 'someerror' ), ); } }
package com.findwise; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsInRelativeOrder; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class DocumentControllerIntegrationTests { @Autowired private TestRestTemplate restTemplate; private static String payloadMultipleDocuments = "[\n" + " \"the brown fox jumped over the brown dog\",\n" + " \"the lazy brown dog sat in the corner\",\n" + " \"the red fox bit the lazy dog\"\n" + "]"; @Test void addDocumentsTest() throws Exception { given().contentType(ContentType.JSON) .body(payloadMultipleDocuments) .post(restTemplate.getRootUri()+"/api/documents") .prettyPeek() .then() .statusCode(HttpStatus.OK.value()); } @Test void searchTest() throws Exception { given().contentType(ContentType.JSON) .body(payloadMultipleDocuments) .post(restTemplate.getRootUri()+"/api/documents") .prettyPeek() .then() .statusCode(HttpStatus.OK.value()); given().contentType(ContentType.JSON) .param("searchTerm", "brown") .get(restTemplate.getRootUri()+"/api/search") .prettyPeek() .then() .statusCode(HttpStatus.OK.value()) .body("id",containsInRelativeOrder("document1","document2")); given().contentType(ContentType.JSON) .param("searchTerm", "fox") .get(restTemplate.getRootUri()+"/api/search") .prettyPeek() .then() .statusCode(HttpStatus.OK.value()) .body("id",containsInRelativeOrder("document3","document1")); } @Test void getAllDocumentsTest() throws Exception { given().contentType(ContentType.JSON) .body(payloadMultipleDocuments) .post(restTemplate.getRootUri()+"/api/documents") .prettyPeek() .then() .statusCode(HttpStatus.OK.value()); given().contentType(ContentType.JSON) .get(restTemplate.getRootUri()+"/api/documents") .prettyPeek() .then() .statusCode(HttpStatus.OK.value()); } }
CREATE TABLE "PLSQL_PROFILER_RUNS" ( "RUNID" NUMBER, "RELATED_RUN" NUMBER, "RUN_OWNER" VARCHAR2(32 CHAR), "RUN_PROC" VARCHAR2(256 CHAR), "RUN_DATE" DATE, "RUN_COMMENT" VARCHAR2(2047 CHAR), "RUN_TOTAL_TIME" NUMBER, "RUN_SYSTEM_INFO" VARCHAR2(2047 CHAR), "RUN_COMMENT1" VARCHAR2(256 CHAR), "SPARE1" VARCHAR2(256 CHAR), PRIMARY KEY ("RUNID") USING INDEX ENABLE )
#!/bin/bash # @ref http://www.cnblogs.com/tianyapiaozi/archive/2011/06/11/2513899.html # @ref http://www.voidcn.com/article/p-gkrqyher-bhv.html # @ref http://smilejustforfan.blogspot.com/2012/03/bashsnippet.html # INTERVAL=1 #sleep time # TCOUNT=0 #for each TCOUNT the line twirls one increment # # while : # do # TCOUNT=$(($TCOUNT+1)) # # case $TCOUNT in # 1) echo -e '-'"\b\c" # sleep $INTERVAL # ;; # 2) echo -e '\\'"\b\c" # sleep $INTERVAL # ;; # 3) echo -e "|\b\c" # sleep $INTERVAL # ;; # 4) echo -e "/\b\c" # sleep $INTERVAL # ;; # *) TCOUNT=0 #reset the TCOUNT to 0 # ;; # esac # done #----中断计数器----# incr= #----旋转的斜杠----# spin="/-\|" echo -en "Please wait ... \n" #这里就是实现旋转效果的代码# while true do echo -e "\b\b${spin:incr++%${#spin}:1} \c" sleep 0.2 done
# Girakkagraph ### Let Akka actors figure out your model ### You just give 'em the rules
package com.ua.plamber_android.activitys; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.ua.plamber_android.R; import com.ua.plamber_android.fragments.DetailBookFragmentOffline; import com.ua.plamber_android.fragments.UploadFileFragment; import com.ua.plamber_android.fragments.UploadFileOfflineFragment; import com.ua.plamber_android.utils.PreferenceUtils; import butterknife.BindView; public class UploadActivity extends SingleFragmentActivity { public static final int REQUEST_SELECT_FILE = 205; public static final int REQUEST_SELECT_CATEGORY = 105; public static final int REQUEST_SELECT_LANGUAGE = 123; @BindView(R.id.toolbar) Toolbar mToolbar; @Override protected Fragment createFragment() { PreferenceUtils preferenceUtils = new PreferenceUtils(this); String bookId = getIntent().getStringExtra(DetailBookFragmentOffline.BOOK_OFFLINE_KEY); boolean isOfflineBook = getIntent().getBooleanExtra(DetailBookFragmentOffline.IS_OFFLINE_BOOK, false); if (!preferenceUtils.readLogic(PreferenceUtils.OFFLINE_MODE)) { UploadFileFragment uploadFileFragment = new UploadFileFragment(); Bundle args = new Bundle(); args.putString(DetailBookFragmentOffline.BOOK_OFFLINE_KEY, bookId); args.putBoolean(DetailBookFragmentOffline.IS_OFFLINE_BOOK, isOfflineBook); uploadFileFragment.setArguments(args); return uploadFileFragment; } else return new UploadFileOfflineFragment(); } @Override protected int setToolbarTitle() { return R.string.upload_book_activity; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; } return true; } public static Intent startUploadActivity(Context context) { return new Intent(context, UploadActivity.class); } }
SELECT * FROM film AS movie WHERE movie.rental_rate > 3 # SELECT title AS movie_title FROM film WHERE title LIKE "A%"
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Data.Common; using System.Linq; using System.Threading.Tasks; using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.EditData; using Microsoft.SqlTools.ServiceLayer.EditData.Contracts; using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement; using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Moq; using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { public class ServiceIntegrationTests { #region EditSession Operation Helper Tests [Test] public async Task NullOrMissingSessionId([Values(null, "", " \t\n\r", "Does not exist")] string sessionId) { // Setup: // ... Create a edit data service var eds = new EditDataService(null, null, null); // ... Create a session params that returns the provided session ID var mockParams = new EditCreateRowParams {OwnerUri = sessionId}; // If: I ask to perform an action that requires a session // Then: I should get an error from it var efv = new EventFlowValidator<EditDisposeResult>() .AddStandardErrorValidation() .Complete(); await eds.HandleSessionRequest(mockParams, efv.Object, session => null); efv.Validate(); } [Test] public async Task OperationThrows() { // Setup: // ... Create an edit data service with a session var eds = new EditDataService(null, null, null); eds.ActiveSessions[Common.OwnerUri] = await GetDefaultSession(); // ... Create a session param that returns the common owner uri var mockParams = new EditCreateRowParams { OwnerUri = Common.OwnerUri }; // If: I ask to perform an action that requires a session // Then: I should get an error from it var efv = new EventFlowValidator<EditDisposeResult>() .AddStandardErrorValidation() .Complete(); await eds.HandleSessionRequest(mockParams, efv.Object, s => { throw new Exception(); }); efv.Validate(); } #endregion #region Dispose Tests [Test] public async Task DisposeNullOrMissingSessionId([Values(null, "", " \t\n\r", "Does not exist")] string sessionId) { // Setup: Create a edit data service var eds = new EditDataService(null, null, null); // If: I ask to perform an action that requires a session // Then: I should get an error from it var efv = new EventFlowValidator<EditDisposeResult>() .AddStandardErrorValidation() .Complete(); await eds.HandleDisposeRequest(new EditDisposeParams {OwnerUri = sessionId}, efv.Object); efv.Validate(); } [Test] public async Task DisposeSuccess() { // Setup: Create an edit data service with a session var eds = new EditDataService(null, null, null); eds.ActiveSessions[Common.OwnerUri] = await GetDefaultSession(); // If: I ask to dispose of an existing session var efv = new EventFlowValidator<EditDisposeResult>() .AddResultValidation(Assert.NotNull) .Complete(); await eds.HandleDisposeRequest(new EditDisposeParams {OwnerUri = Common.OwnerUri}, efv.Object); // Then: // ... It should have completed successfully efv.Validate(); Assert.That(eds.ActiveSessions, Is.Empty, "And the session should have been removed from the active session list"); } #endregion [Test] public async Task DeleteSuccess() { // Setup: Create an edit data service with a session var eds = new EditDataService(null, null, null); eds.ActiveSessions[Constants.OwnerUri] = await GetDefaultSession(); // If: I validly ask to delete a row var efv = new EventFlowValidator<EditDeleteRowResult>() .AddResultValidation(Assert.NotNull) .Complete(); await eds.HandleDeleteRowRequest(new EditDeleteRowParams {OwnerUri = Constants.OwnerUri, RowId = 0}, efv.Object); // Then: // ... It should be successful efv.Validate(); // ... There should be a delete in the session EditSession s = eds.ActiveSessions[Constants.OwnerUri]; Assert.True(s.EditCache.Any(e => e.Value is RowDelete)); } [Test] public async Task CreateSucceeds() { // Setup: Create an edit data service with a session var eds = new EditDataService(null, null, null); eds.ActiveSessions[Constants.OwnerUri] = await GetDefaultSession(); // If: I ask to create a row from a non existant session var efv = new EventFlowValidator<EditCreateRowResult>() .AddResultValidation(ecrr => { Assert.True(ecrr.NewRowId > 0); }) .Complete(); await eds.HandleCreateRowRequest(new EditCreateRowParams { OwnerUri = Constants.OwnerUri }, efv.Object); // Then: // ... It should have been successful efv.Validate(); // ... There should be a create in the session EditSession s = eds.ActiveSessions[Constants.OwnerUri]; Assert.True(s.EditCache.Any(e => e.Value is RowCreate)); } [Test] public async Task RevertCellSucceeds() { // Setup: // ... Create an edit data service with a session that has a pending cell edit var eds = new EditDataService(null, null, null); var session = await GetDefaultSession(); eds.ActiveSessions[Constants.OwnerUri] = session; // ... Make sure that the edit has revert capabilities var mockEdit = new Mock<RowEditBase>(); mockEdit.Setup(edit => edit.RevertCell(It.IsAny<int>())) .Returns(new EditRevertCellResult()); session.EditCache[0] = mockEdit.Object; // If: I ask to revert a cell that has a pending edit var efv = new EventFlowValidator<EditRevertCellResult>() .AddResultValidation(Assert.NotNull) .Complete(); var param = new EditRevertCellParams { OwnerUri = Constants.OwnerUri, RowId = 0 }; await eds.HandleRevertCellRequest(param, efv.Object); // Then: // ... It should have succeeded efv.Validate(); // ... The edit cache should be empty again EditSession s = eds.ActiveSessions[Constants.OwnerUri]; Assert.That(s.EditCache, Is.Empty); } [Test] public async Task RevertRowSucceeds() { // Setup: Create an edit data service with a session that has an pending edit var eds = new EditDataService(null, null, null); var session = await GetDefaultSession(); session.EditCache[0] = new Mock<RowEditBase>().Object; eds.ActiveSessions[Constants.OwnerUri] = session; // If: I ask to revert a row that has a pending edit var efv = new EventFlowValidator<EditRevertRowResult>() .AddResultValidation(Assert.NotNull) .Complete(); await eds.HandleRevertRowRequest(new EditRevertRowParams { OwnerUri = Constants.OwnerUri, RowId = 0}, efv.Object); // Then: // ... It should have succeeded efv.Validate(); // ... The edit cache should be empty again EditSession s = eds.ActiveSessions[Constants.OwnerUri]; Assert.That(s.EditCache, Is.Empty); } [Test] public async Task UpdateSuccess() { // Setup: Create an edit data service with a session var eds = new EditDataService(null, null, null); var session = await GetDefaultSession(); eds.ActiveSessions[Constants.OwnerUri] = session; var edit = new Mock<RowEditBase>(); edit.Setup(e => e.SetCell(It.IsAny<int>(), It.IsAny<string>())).Returns(new EditUpdateCellResult { IsRowDirty = true, Cell = new EditCell(new DbCellValue(), true) }); session.EditCache[0] = edit.Object; // If: I validly ask to update a cell var efv = new EventFlowValidator<EditUpdateCellResult>() .AddResultValidation(eucr => { Assert.NotNull(eucr); Assert.NotNull(eucr.Cell); Assert.True(eucr.IsRowDirty); }) .Complete(); await eds.HandleUpdateCellRequest(new EditUpdateCellParams { OwnerUri = Constants.OwnerUri, RowId = 0}, efv.Object); // Then: // ... It should be successful efv.Validate(); // ... Set cell should have been called once edit.Verify(e => e.SetCell(It.IsAny<int>(), It.IsAny<string>()), Times.Once); } [Test] public async Task GetRowsSuccess() { // Setup: Create an edit data service with a session // Setup: Create an edit data service with a session var eds = new EditDataService(null, null, null); var session = await GetDefaultSession(); eds.ActiveSessions[Constants.OwnerUri] = session; // If: I validly ask for rows var efv = new EventFlowValidator<EditSubsetResult>() .AddResultValidation(esr => { Assert.NotNull(esr); Assert.That(esr.Subset, Is.Not.Empty); Assert.That(esr.RowCount, Is.Not.EqualTo(0)); }) .Complete(); await eds.HandleSubsetRequest(new EditSubsetParams { OwnerUri = Constants.OwnerUri, RowCount = 10, RowStartIndex = 0 }, efv.Object); // Then: // ... It should be successful efv.Validate(); } #region Initialize Tests [Test] [Sequential] public async Task InitializeNullParams([Values(null, Common.OwnerUri, Common.OwnerUri)] string ownerUri, [Values("table", null, "table")] string objName, [Values("table", "table", null)] string objType) { // Setup: Create an edit data service without a session var eds = new EditDataService(null, null, null); // If: // ... I have init params with a null parameter var initParams = new EditInitializeParams { ObjectName = objName, OwnerUri = ownerUri, ObjectType = objType }; // ... And I initialize an edit session with that var efv = new EventFlowValidator<EditInitializeResult>() .AddStandardErrorValidation() .Complete(); await eds.HandleInitializeRequest(initParams, efv.Object); // Then: // ... An error event should have been raised efv.Validate(); // ... There should not be a session Assert.That(eds.ActiveSessions, Is.Empty); } [Test] public async Task InitializeSessionExists() { // Setup: Create an edit data service with a session already defined var eds = new EditDataService(null, null, null); var session = await GetDefaultSession(); eds.ActiveSessions[Constants.OwnerUri] = session; // If: I request to init a session for an owner URI that already exists var initParams = new EditInitializeParams { ObjectName = "testTable", OwnerUri = Constants.OwnerUri, ObjectType = "Table", Filters = new EditInitializeFiltering() }; var efv = new EventFlowValidator<EditInitializeResult>() .AddStandardErrorValidation() .Complete(); await eds.HandleInitializeRequest(initParams, efv.Object); // Then: // ... An error event should have been sent efv.Validate(); // ... The original session should still be there Assert.AreEqual(1, eds.ActiveSessions.Count); Assert.AreEqual(session, eds.ActiveSessions[Constants.OwnerUri]); } // Disable flaky test for investigation (karlb - 3/13/2018) //[Test] public async Task InitializeSessionSuccess() { // Setup: // .. Create a mock query var mockQueryResults = QueryExecution.Common.StandardTestDataSet; var cols = mockQueryResults[0].Columns; // ... Create a metadata factory that will return some generic column information var etm = Common.GetCustomEditTableMetadata(cols.ToArray()); Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>(); emf.Setup(f => f.GetObjectMetadata(It.IsAny<DbConnection>(), It.IsAny<string[]>(), It.IsAny<string>())) .Returns(etm); // ... Create a query execution service that will return a successful query var qes = QueryExecution.Common.GetPrimedExecutionService(mockQueryResults, true, false, false, null); // ... Create a connection service that doesn't throw when asked for a connection var cs = new Mock<ConnectionService>(); cs.Setup(s => s.GetOrOpenConnection(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())) .Returns(Task.FromResult<DbConnection>(null)); // ... Create an edit data service that has mock providers var eds = new EditDataService(qes, cs.Object, emf.Object); // If: I request to initialize an edit data session var initParams = new EditInitializeParams { ObjectName = "testTable", OwnerUri = Constants.OwnerUri, ObjectType = "Table", Filters = new EditInitializeFiltering() }; var efv = new EventFlowValidator<EditInitializeResult>() .AddResultValidation(Assert.NotNull) .AddEventValidation(BatchStartEvent.Type, Assert.NotNull) .AddEventValidation(ResultSetCompleteEvent.Type, Assert.NotNull) .AddEventValidation(MessageEvent.Type, Assert.NotNull) .AddEventValidation(BatchCompleteEvent.Type, Assert.NotNull) .AddEventValidation(QueryCompleteEvent.Type, Assert.NotNull) .AddEventValidation(EditSessionReadyEvent.Type, esrp => { Assert.NotNull(esrp); Assert.AreEqual(Constants.OwnerUri, esrp.OwnerUri); Assert.True(esrp.Success); Assert.Null(esrp.Message); }) .Complete(); await eds.HandleInitializeRequest(initParams, efv.Object); await eds.ActiveSessions[Constants.OwnerUri].InitializeTask; // Then: // ... The event should have been received successfully efv.Validate(); // ... The session should have been created Assert.AreEqual(1, eds.ActiveSessions.Count); Assert.True(eds.ActiveSessions.Keys.Contains(Constants.OwnerUri)); } #endregion private static readonly object[] schemaNameParameters = { new object[] {"table", "myschema", new[] { "myschema", "table" } }, // Use schema new object[] {"table", null, new[] { "table" } }, // skip schema new object[] {"schema.table", "myschema", new[] { "myschema", "schema.table" } }, // Use schema new object[] {"schema.table", null, new[] { "schema", "table" } }, // Split object name into schema }; [Test, TestCaseSource(nameof(schemaNameParameters))] public void ShouldUseSchemaNameIfDefined(string objName, string schemaName, string[] expectedNameParts) { // Setup: Create an edit data service without a session var eds = new EditDataService(null, null, null); // If: // ... I have init params with an object and schema parameter var initParams = new EditInitializeParams { ObjectName = objName, SchemaName = schemaName, OwnerUri = Common.OwnerUri, ObjectType = "table" }; // ... And I get named parts for that string[] nameParts = EditSession.GetEditTargetName(initParams); // Then: Assert.AreEqual(expectedNameParts, nameParts); } private static async Task<EditSession> GetDefaultSession() { // ... Create a session with a proper query and metadata Query q = QueryExecution.Common.GetBasicExecutedQuery(); ResultSet rs = q.Batches[0].ResultSets[0]; EditTableMetadata etm = Common.GetCustomEditTableMetadata(rs.Columns.Cast<DbColumn>().ToArray()); EditSession s = await Common.GetCustomSession(q, etm); return s; } } }
/****************************************************************************\ * * toffdlg.h * * Created: William Taylor (wtaylor) 01/22/01 * * MS Ratings Turn Off Ratings Dialog * \****************************************************************************/ #ifndef TURN_OFF_DIALOG_H #define TURN_OFF_DIALOG_H #include "basedlg.h" // CBaseDialog class CTurnOffDialog: public CBaseDialog<CTurnOffDialog> { public: enum { IDD = IDD_TURNOFF }; public: CTurnOffDialog(); public: typedef CTurnOffDialog thisClass; typedef CBaseDialog<thisClass> baseClass; BEGIN_MSG_MAP(thisClass) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOK) CHAIN_MSG_MAP(baseClass) END_MSG_MAP() protected: LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); }; #endif
import { makeStyles } from '@material-ui/core/styles'; export const useStyles = makeStyles({ container: { // minWidth: 400, minHeight: 400, background: 'black', borderRadius: 10, color: 'white', marginTop: '2rem', paddingLeft: 10, paddingRight: 10, paddingTop: '1rem', paddingBottom: '1rem', }, resultContainer: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', }, result: { fontSize: 45, lineHeight: 1.2, }, subRow: { fontSize: 15, lineHeight: 1.2, }, });
/** * @description Apply a case insensitive regex pattern to a string * @param x The string to apply the regex to * @returns a RegExp object which does case insensitive matching with all text containing the passed string */ export const makeCaseInsensitiveRegex = (x: string): RegExp => new RegExp(`.*${x}.*`, 'i'); /** * @description Apply a formation to an object, applying the case insensitive regex pattern on each its string entries * @param query The object to format * @returns An object with case insensitive regex pattern in all of its string entries */ export const formatQueryToRegex = (query: Record<string, any>): Record<string, unknown> => Object.keys(query).reduce((acc: Record<string, unknown>, queryKey: string) => { const value = query[queryKey]; return typeof value !== 'string' ? { ...acc, [queryKey]: value } : { ...acc, [queryKey]: makeCaseInsensitiveRegex(value) }; }, {}); /** * @description Convert a string to an object understandable by sort option in mongoose * @param str The string to be converted ex: `-name,+dob,+status` */ export const makeSortQuery = (str: string) => str.split(',').reduce((result: Record<string, unknown>, curr) => { const sign = curr[0] === '-' ? -1 : 1; const key = curr.replace(/^(\+| |-){1}/, ''); return { ...result, [key]: sign }; }, {});
from django.urls import path from autobuyfast.career.views import career_detail_view, career_view app_name = "careers" urlpatterns = [ path('', career_view, name='list'), path('<slug>/', career_detail_view, name='detail'), ]
module Statuses extend ActiveSupport::Concern def force_delete? statuses.include?(DomainStatus::FORCE_DELETE) end end
package com.github.collection.demo2; /** * @author 许大仙 * @version 1.0 * @since 2021-09-01 21:37 */ public class Person { private String name; public void say(String word) { boolean flag = true; if (flag) { int age = 5; System.out.println("我的名字是:" + this.name + ",我的年龄是:" + age); } } }
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Coworkers_admin extends MX_Controller { /* Gallery constructor * */ function __construct() { parent::__construct(); $this->load->model('Coworkers_model'); $this->OwnHelpers->is_logged_in(); } function index(){ $this->OwnHelpers->is_logged_in(); $crud = new grocery_CRUD(); $crud->set_table('coworkers'); $crud->set_theme('bootstrap'); $crud->unset_columns('main_img'); $crud->display_as(array( 'name' => 'Név', 'job' => 'Munkakör', 'twitter' => 'Twitter', 'facebook' => 'Facebook', 'skype' => 'Skype', 'phone' => 'Telefon', 'job_desc' => 'Munkakör leírása', 'main_img' => 'Főkép', ) ); $this->config->set_item('grocery_crud_file_upload_allow_file_types', 'gif|jpeg|jpg|png'); $crud->set_field_upload('main_img', 'assets/uploads/coworkers'); $language = Modules::run('helper/helper/get_languages'); $crud->field_type('language', 'dropdown',$language); $output = $crud->render(); return $output; } }
export * from './service.interface' export * from './service'
#!/bin/bash syntax="sas.syntax" comma_color=brightcyan keywords1_color=brightmagenta keywords2_color=brightblue keywords3_color=cyan keywords4_color=brightgreen comments_color=green strings_color=magenta digits_color=brightgreen echo "context default" > $syntax echo "keyword ; $comma_color" >> $syntax echo "">> "$syntax" for word in $(<keywords1) do echo "keyword whole $word $keywords1_color" >> $syntax done echo "" >> $syntax for word in $(<keywords2) do echo "keyword whole $word $keywords2_color" >> $syntax done echo "" >> $syntax for word in $(<keywords3) do echo "keyword whole $word $keywords3_color" >> $syntax done echo "" >> $syntax for word in $(<keywords4) do echo "keyword whole $word $keywords4_color" >> $syntax done echo "" >> $syntax cat "digits" | sed -e "s/_color_/$digits_color/" >> $syntax echo "" >> $syntax echo "" >> $syntax echo "wholechars abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._" >> $syntax echo "" >> $syntax cat "comments" | sed -e "s/_color_/$comments_color/" >> $syntax echo "" >> $syntax echo "" >> $syntax cat "strings" | sed -e "s/_color_/$strings_color/" >> $syntax
package microloggertest import ( "io/ioutil" "github.com/giantswarm/micrologger" ) // New returns a Logger intance configured to discard its output. func New() micrologger.Logger { c := micrologger.Config{ IOWriter: ioutil.Discard, } logger, err := micrologger.New(c) if err != nil { panic(err) } return logger }
#!/bin/bash CMDGET="echo '$1' | openssl aes-256-cbc -a -d -salt" OUTPUT2=$( expect << EOD log_user 0 spawn sh -c "$CMDGET" expect "*password:*" send "$2\r" sleep 1 set result $expect_out(buffer) interact puts -nonewline "$result" expect eof EOD ) echo "$OUTPUT2" | sed "s/ //g" | tr -d "\n\r"
#include "Address.h" using Network::Address; Address::Address(Host hostName, Port portNumber) : endpoint{ std::make_pair(hostName, portNumber) } { } auto Address::host() const -> Host { return endpoint.first; } auto Address::port() const noexcept -> Port { return endpoint.second; }
require File.dirname(__FILE__) + '/../../shared/complex/multiply' ruby_version_is ""..."1.9" do require 'complex' describe "Complex#* with Complex" do it_behaves_like(:complex_multiply_complex, :*) end describe "Complex#* with Integer" do it_behaves_like(:complex_multiply_integer, :*) end describe "Complex#* with Object" do it_behaves_like(:complex_multiply_object, :*) end end
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; public class ContactCreationTests extends TestBase2 { @Test public void testContactCreation() { initContactCreation(); fillContactForm(new ContactData("olga", "shahova", "krasnoyarsk", "[email protected]")); submitContactCreation(); returnToHomePage(); } }
package org.gradoop.spark.functions import org.apache.spark.sql.functions._ import org.apache.spark.sql.{Column, DataFrame, SparkSession} import org.gradoop.common.util.ColumnNames class LabelKeyFunction extends KeyFunction { /* Used to improve performance with tfl layout */ var labelOpt: Option[Array[String]] = None override def name: String = ":label" override def extractKey: Column = col(ColumnNames.LABEL) override def addKey(dataFrame: DataFrame, column: Column): DataFrame = { dataFrame.withColumn(ColumnNames.LABEL, column) } override def addKey(dataMap: Map[String, DataFrame], column: Column) (implicit sparkSession: SparkSession): Map[String, DataFrame] = { import sparkSession.implicits._ dataMap.flatMap(e => { val df = e._2.toDF.cache val labels = labelOpt.getOrElse(df.select(column).distinct.as[String].collect) labels.map(l => (l, df.filter(column === lit(l)).withColumn(ColumnNames.LABEL, lit(l)).toDF)) }) } } object LabelKeyFunction { def apply(): LabelKeyFunction = new LabelKeyFunction() }
# Checkout Integration This is an example Checkout integration using Deno. This is based on https://stripe.com/docs/payments/accept-a-payment?integration=checkout. **Note that this requires Deno v1.16 or greater.** ## Setup 1. Follow instructions for installing [Deno](https://deno.land/#installation). ## Running You can run your application using: ``` STRIPE_API_KEY="<YOUR API KEY HERE>"\ deno run\ --allow-net\ --allow-env\ main.js ``` Note that this makes use of a number of Deno flags: 1. `--allow-net`: Required permission for network access (to issue API calls). 1. `--allow-env`: Required permission for environment variable access (`STRIPE_API_KEY`).
-module(squaresparrow). -behavior(gen_server). %% GenServer exports -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% API exports -export([ start_link/1, start_link/2, add_workers/2, add_workers/3, call/2, call/3, call_rr/2, call_rr/3, call_shard/3, call_shard/4, cast/2, cast_rr/2, cast_shard/3, cast_all/2, send/2, send_rr/2, send_shard/3, send_all/2 ]). -record(squaresparrow, { supervisor :: pid(), workers = #{} :: #{}, delayed = #{} :: #{}, count = 0 :: integer(), next = 0 :: integer() }). %%==================================================================== %% API functions %%==================================================================== -spec start_link(Spec :: {atom(),atom()} | {atom(), atom(), list()} | #{}) -> term(). %% @doc Starts the roundrobin engine. %% @end start_link(Spec) -> start_workers(Spec, gen_server:start_link(?MODULE, Spec, [])). -spec start_link(Name :: term(), Spec :: {atom(),atom()} | {atom(), atom(), list()} | #{}) -> term(). %% @doc Starts a named roundrobin engine. %% Same as roundrobin/3 M,F,[] %% @end start_link(Name, Spec) -> start_workers(Spec, gen_server:start_link(Name, ?MODULE, Spec, [])). -spec add_workers(pid() | atom(), Count :: integer()) -> ok | {error, term()}. %% @doc Adds a worker to the roundrobin pool with the default arguments. %% Same as add_worker(default). %% @end add_workers(Proc, Count) -> add_workers(Proc, Count, []). -spec add_workers(pid() | atom(), Count :: integer(), Args :: list()) -> ok | {error, term()}. %% @doc Adds a worker to the roundrobin pool with specialized arguments. %% @end add_workers(Proc, Count, Args) -> gen_server:call(Proc, {add_workers, Count, Args}). %%==================================================================== %% Call functions %%==================================================================== call(Proc, Message) -> call(Proc, Message, 5000). call(Proc, Message, Timeout) -> call_rr(Proc, Message, Timeout). call_rr(Proc, Message) -> call_rr(Proc, Message, 5000). call_rr(Proc, Message, Timeout) -> gen_call(get_worker(Proc), Message, Timeout). call_shard(Proc, Target, Message) -> call_shard(Proc, Target, Message, 5000). call_shard(Proc, Target, Message, Timeout) -> gen_call(get_worker(Proc, Target), Message, Timeout). gen_call(Proc, Message, Timeout) -> case Proc of {ok, Worker} -> gen_server:call(Worker, Message, Timeout); {caution, _} -> {error, "Process would call itself"} end. %%==================================================================== %% Cast message functions %%==================================================================== cast(Proc, Message) -> cast_rr(Proc, Message). cast_rr(Proc, Message) -> gen_cast(get_worker(Proc), Message). cast_shard(Proc, Target, Message) -> gen_cast(get_worker(Proc, Target), Message). gen_cast(Proc, Message) -> case Proc of {Atom, Worker} when Atom =:= ok orelse Atom =:= caution -> gen_server:cast(Worker, Message) end. cast_all(Proc, Message) -> gen_server:cast(Proc, {'$cast_all', Message}). %%==================================================================== %% Send info functions %%==================================================================== send(Proc, Message) -> send_rr(Proc, Message). send_rr(Proc, Message) -> gen_send(get_worker(Proc), Message). send_shard(Proc, Target, Message) -> gen_send(get_worker(Proc, Target), Message). gen_send(Proc, Message) -> case Proc of {Atom, Worker} when Atom =:= ok orelse Atom =:= caution -> erlang:send(Worker, Message) end. send_all(Proc, Message) -> gen_server:cast(Proc, {'$send_all', Message}). %%==================================================================== %% gen_server functions %%==================================================================== -spec init(term()) -> gen_spec:gs_init_res(#squaresparrow{}). %% @doc Initialize a squaresparrow. %% @end init(Spec) -> case squaresparrow_sup:start_link(Spec) of {ok, Supervisor} -> {ok, #squaresparrow{supervisor = Supervisor}}; _ -> ignore end. -spec handle_call(term(), gen_spec:from(), #squaresparrow{}) -> term(). %% @doc Handle requests. %% @end handle_call( {add_workers, New, Args}, _, S = #squaresparrow{ supervisor = Supervisor, workers = Workers, count = Count } ) -> {Workers2, Count2} = lists:foldl( fun(_, {Workers1, Count1}) -> {ok, Pid} = supervisor:start_child(Supervisor, Args), erlang:monitor(process, Pid), {Workers1#{Pid => Count1, Count1 => Pid}, Count1+1} end, {Workers, Count}, lists:seq(1, New) ), {reply, ok, S#squaresparrow{workers=Workers2, count=Count2}}; handle_call( {get_worker, any, _Caller}, _, S = #squaresparrow{count=0} ) -> {reply, {error, "No worker available"}, S}; handle_call({get_worker, any, Caller}, _, S = #squaresparrow{}) -> {Result, S2} = get_next_worker(Caller, S), {reply, Result, S2}; handle_call( {get_worker, Target, Caller}, From, S = #squaresparrow{ workers = Workers, delayed = Delayed, count = Count } ) -> Target2 = case Target of _ when is_integer(Target) -> Target; _ -> erlang:phash2(Target, Count) end, case maps:get(Target2, Workers, undefined) of undefined -> {reply, {error, {"Invalid target", Target, Target2}}, S}; restarting -> Queue = maps:get(Target2, Delayed, []), {noreply, S#squaresparrow{delayed=maps:put(Target2, [From|Queue], Delayed)}}; Caller -> {reply, {caution, Caller}, S}; Worker -> {reply, {ok, Worker}, S} end; handle_call(_, _, S) -> {reply, {error, unhandled}, S}. -spec handle_cast(term(), #squaresparrow{}) -> gen_spec:gs_cast_res(#squaresparrow{}). %% @doc Handle cast notifications. %% @end handle_cast({'$cast_all', Message}, S = #squaresparrow{workers = Workers}) -> do_for_all(fun gen_server:cast/2, Message, Workers), {noreply, S}; handle_cast({'$send_all', Message}, S = #squaresparrow{workers = Workers}) -> do_for_all(fun erlang:send/2, Message, Workers), {noreply, S}; handle_cast(_, S) -> {noreply, S}. -spec handle_info(term(), #squaresparrow{}) -> gen_spec:gs_info_res(#squaresparrow{}). %% @doc Handle info notifications. %% @end handle_info({'DOWN', _, process, Pid, _}, S = #squaresparrow{workers = Workers}) -> erlang:send(self(), '$refresh'), {noreply, S#squaresparrow{workers = maps:remove(Pid, maps:put(maps:get(Pid, Workers), restarting, Workers))}}; handle_info( '$refresh', S = #squaresparrow{ supervisor = Supervisor, workers = Workers, delayed = Delayed } ) -> %% Get children that we don't know about Children2 = lists:filtermap( fun({_, Child, _, _}) -> case maps:get(Child, Workers, undefined) of undefined -> erlang:monitor(process, Child), {true, Child}; _ -> false end end, supervisor:which_children(Supervisor) ), %% Get the keys that need a child Keys = lists:filter( fun (K) when is_integer(K) -> case maps:get(K, Workers) of restarting -> true; _ -> false end; (_) -> false end, maps:keys(Workers) ), %% Stich new to keys Updates = lists:zip(Keys, Children2), %% Update workers map Workers2 = lists:foldl( fun({Key, Child}, Acc) -> Acc2 = maps:put(Key, Child, Acc), maps:put(Child, Key, Acc2) end, Workers, Updates ), %% Notify those waiting for a specific instance Delayed2 = lists:foldl( fun({Key, Child}, Acc) -> lists:foreach(fun(X) -> gen_server:reply(X, {ok, Child}) end, maps:get(Key, Acc, [])), maps:put(Key, [], Acc) end, Delayed, Updates ), %% If we had more keys then children we need to refresh again Refresh = length(Keys) > length(Children2), case Refresh of false -> ok; true -> erlang:send_after(500, self(), '$refresh') end, {noreply, S#squaresparrow{workers = Workers2, delayed = Delayed2}}; handle_info(_, S) -> {noreply, S}. -spec terminate(normal | shutdown | {shutdown, term()} | term(), #squaresparrow{}) -> no_return(). %% @doc Perform any last second cleanup. %% @end terminate(_, _S) -> ok. -spec code_change({down, term()} | term(), #squaresparrow{}, term()) -> {ok, #squaresparrow{}} | {error, term()}. %% @doc Handle state changes across revisions. %% @end code_change(_, S, _) -> {ok, S}. %%==================================================================== %% Internal functions %%==================================================================== start_workers(Spec, {ok, Pid}) when is_map(Spec) -> add_workers(Pid, maps:get(workers, Spec, 0)), {ok, Pid}; start_workers(_, Else) -> Else. -spec get_worker(pid() | atom()) -> {ok, pid() | atom()} | {error, term()}. %% @doc Gets a worker. %% @end get_worker(Proc) -> get_worker(Proc, any). get_worker(Proc, Target) -> gen_server:call(Proc, {get_worker, Target, self()}). get_next_worker(Caller, State) -> get_next_worker(Caller, State, 0). get_next_worker( _, State = #squaresparrow{ count = Count }, Count ) -> {{error, "No worker available"}, State}; get_next_worker( Caller, State = #squaresparrow{ workers = Workers, count = Count, next = Next }, Checked ) -> case maps:get(Next, Workers) of restarting -> get_next_worker(Caller, State#squaresparrow{next=(Next+1) rem Count}, Checked+1); Worker when Worker =:= Caller -> {{caution, Worker}, State#squaresparrow{next=(Next+1) rem Count}}; Worker -> {{ok, Worker}, State#squaresparrow{next=(Next+1) rem Count}} end. do_for_all(Fun, Message, Workers) -> lists:foreach( fun (Worker) when not is_integer(Worker) -> case maps:get(Worker, Workers) of restarting -> ok; Worker2 -> Fun(Worker2, Message) end; (_) -> ok end, maps:keys(Workers) ).
#!/bin/sh # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. echo "###############################################" echo " BASHSRG - Bash STIG NULL Configuration Script" echo " Skipping STIG" echo "###############################################"
namespace VRTK.Core.Prefabs.CameraRig.SimulatedCameraRig { using UnityEngine; using UnityEngine.UI; using VRTK.Core.Prefabs.CameraRig.UnityXRCameraRig.Input; /// <summary> /// Sets up the key binding display. /// </summary> public class KeyBindingDisplay : MonoBehaviour { public Text keyBindingText; public UnityButtonAction forward; public UnityButtonAction backward; public UnityButtonAction strafeLeft; public UnityButtonAction strafeRight; public UnityButtonAction button1; public UnityButtonAction button2; public UnityButtonAction button3; public UnityButtonAction switchToPlayer; public UnityButtonAction switchToLeftController; public UnityButtonAction switchToRightController; public UnityButtonAction resetPlayer; public UnityButtonAction resetControllers; public UnityButtonAction toggleInstructions; public UnityButtonAction lockCursorToggle; protected string instructions = @"<b>Simulator Key Bindings</b> <b>Movement:</b> Forward: {0} Backward: {1} Strafe Left: {2} Strafe Right: {3} <b>Buttons</b> Button 1: {4} Button 2: {5} Button 3: {6} <b>Object Control</b> Move PlayArea: {7} Move Left Controller: {8} Move Right Controller: {9} Reset Player: Position {10} Reset Controller Position: {11} <b>Misc</b> Toggle Help Window: {12} Lock Mouse Cursor: {13}"; protected virtual void OnEnable() { keyBindingText.text = string.Format( instructions, forward.keyCode, backward.keyCode, strafeLeft.keyCode, strafeRight.keyCode, button1.keyCode, button2.keyCode, button3.keyCode, switchToPlayer.keyCode, switchToLeftController.keyCode, switchToRightController.keyCode, resetPlayer.keyCode, resetControllers.keyCode, toggleInstructions.keyCode, lockCursorToggle.keyCode ); } } }
self.addEventListener('fetch', event => { const url = new URL(event.request.url) , isShell = url.origin === location.origin && event.request.method === 'GET' if (!isShell) { event.respondWith(fetch(event.request)) return } event.respondWith( caches .match(event.request) .then(response => response || caches.match('/index.html')) .then(response => response || Promise.reject()) ) })
package com.dci.dev.appinfobadge.utils import android.content.Context import android.content.Intent import android.content.res.Resources import android.net.Uri import android.provider.Settings import android.webkit.WebView import androidx.core.content.res.ResourcesCompat /** * Extension method to find a device height in pixels */ inline val Context.displayHeight: Int get() = resources.displayMetrics.heightPixels fun Context.goToSettings() { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri = Uri.fromParts("package", packageName, null) intent.data = uri intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } /** * Converts dp unit to equivalent pixels, depending on device density. **/ val Int.dp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt() /** * Converts device specific pixels to density independent pixels. **/ val Int.px: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt() // Assets are hosted under http(s)://appassets.androidplatform.net/assets/... . // If the application's assets are in the "main/assets" folder this will read the file // from "main/assets/www/index.html" and load it as if it were hosted on: // https://appassets.androidplatform.net/assets/www/index.html fun WebView.loadAsset(file: String, context: Context, darkMode: Boolean) { this.webViewClient = AssetsWebViewClient(context, darkMode) loadUrl("https://appassets.androidplatform.net/assets/$file") } fun Context.resolveColor(colorRes: Int) = ResourcesCompat.getColor(resources, colorRes, null) fun Context.resolveDrawable(drawableRes: Int) = ResourcesCompat.getDrawable(resources, drawableRes, null)
#!/bin/bash curdir=`pwd` echo $curdir #paste $curdir user.list > trans.list #sed -n 's/KsponSpeech/$curdir'KsponSpeech'/ user.list > trans.list cd $curdir numfile=$(ls -l | grep .txt$ | wc -l) rm trans.list rm trans1.list rm trans.txt echo $numfile (ls -l | grep .txt$) | awk '{print $9}' | sed '/decoded/d' | sed '/trans/d' > trans.list #SET=$(seq 0, $numfile-1) #for i in $SET for line in `cat trans.list` do # echo $line line=$curdir'/'$line # line=$line'curdir' echo $line done > trans1.list for line in `cat trans.list` do echo $line' '`cat $line` # echo " " # echo `cat $line` done > trans.txt cat trans.txt | sed s/.txt// > trans1.txt cp trans1.txt trans.txt rm trans1.txt #for line in `cat trans1.list` #do # echo $line ## line=`cat line` #done > trans.txt
package ch.epfl.bluebrain.nexus.delta.sdk.testkit import akka.persistence.query.{Offset, Sequence} import ch.epfl.bluebrain.nexus.delta.sdk.model.{Envelope, Event} import fs2.Stream import monix.bio.{Task, UIO} object DummyHelpers { /** * Constructs a stream of events from a sequence of envelopes */ def currentEventsFromJournal[E <: Event]( envelopes: UIO[Seq[Envelope[E]]], offset: Offset ): Stream[Task, Envelope[E]] = Stream .evalSeq(envelopes) .filter { envelope => (envelope.offset, offset) match { case (Sequence(envelopeOffset), Sequence(requestedOffset)) => envelopeOffset > requestedOffset case _ => true } } /** * Constructs a stream of events from a sequence of envelopes */ def eventsFromJournal[E <: Event]( envelopes: Seq[Envelope[E]], offset: Offset ): Stream[Task, Envelope[E]] = eventsFromJournal(UIO.pure(envelopes), offset) /** * Constructs a stream of events from a sequence of envelopes */ def eventsFromJournal[E <: Event]( envelopes: UIO[Seq[Envelope[E]]], offset: Offset ): Stream[Task, Envelope[E]] = currentEventsFromJournal(envelopes, offset) }
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; extern crate rocket_contrib; use rocket::State; use rocket_contrib::json::Json; use serde::Serialize; use std::sync::Mutex; mod cors; struct AppState { count: usize, } #[derive(Serialize, Copy, Clone)] enum Status { Ok, Error, } #[derive(Serialize)] struct ApiResponse<T: Serialize> { status: Status, data: T, } impl<T: Serialize> ApiResponse<T> { fn ok(data: T) -> Self { ApiResponse { status: Status::Ok, data, } } } #[get("/count")] fn count(state: State<Mutex<AppState>>) -> Option<Json<ApiResponse<usize>>> { let lock = state.lock().ok()?; Some(Json(ApiResponse::ok(lock.count))) } #[get("/increment")] fn increment(state: State<Mutex<AppState>>) -> Option<Json<ApiResponse<usize>>> { let mut lock = state.lock().ok()?; lock.count = lock.count.saturating_add(1); Some(Json(ApiResponse::ok(lock.count))) } #[catch(404)] fn not_found() -> Json<ApiResponse<&'static str>> { Json(ApiResponse { status: Status::Error, data: "Resource not found", }) } fn rocket(state: Mutex<AppState>) -> rocket::Rocket { rocket::ignite() .mount("/", routes![count, increment]) .register(catchers![not_found]) .manage(state) .attach(cors::AllowOrigin()) } fn main() { let state = Mutex::new(AppState { count: 0 }); rocket(state).launch(); }
import execa from 'execa'; import fetch from 'node-fetch'; import { getNodeSecurityChecker } from '../src/security'; import { logMessages } from '../src/log-messages'; /// <reference types="@types/jest" /> jest.mock('execa'); jest.mock('node-fetch'); jest.mock('fs-extra'); const { Response } = jest.requireActual('node-fetch'); const exampleNodeList = [ { version: 'v13.0.0', date: '2020-07-29', npm: '6.14.7', security: true, lts: false }, { version: 'v13.1.0', date: '2020-07-29', npm: '6.14.7', security: false, lts: false }, { version: 'v13.2.0', date: '2020-07-29', npm: '6.14.7', security: false, lts: false }, { version: 'v14.1.0', date: '2020-07-29', npm: '6.14.7', security: false, lts: false }, { version: 'v14.2.0', date: '2020-07-29', npm: '6.14.7', security: false, lts: false }, { version: 'v14.3.0', date: '2020-07-29', npm: '6.14.7', security: true, lts: false }, { version: 'v15.1.0', date: '2020-07-29', npm: '6.14.7', security: false, lts: false }, { version: 'v15.3.0', date: '2020-07-29', npm: '6.14.7', security: true, lts: false }, ]; const nodeVersionListURL = 'https://nodejs.org/dist/index.json'; describe('getNodeSecurityChecker', () => { it('should return success-text if there is no security version above inside this major version', async () => { (execa as any).mockReturnValue(Promise.resolve({ stdout: '13.1.0' })); (fetch as any).mockReturnValue(Promise.resolve(new Response(JSON.stringify(exampleNodeList)))); expect(await getNodeSecurityChecker()).toMatchObject({ error: false, text: logMessages.success.nodeVersionSecurity('13.1.0'), }); }); it('should return error-text if there is a security version above inside this major version', async () => { (execa as any).mockReturnValue(Promise.resolve({ stdout: 'v14.1.0' })); (fetch as any).mockReturnValue(Promise.resolve(new Response(JSON.stringify(exampleNodeList)))); expect(await getNodeSecurityChecker()).toMatchObject({ error: true, text: logMessages.error.nodeVersionNotSecureError('14.1.0'), }); }); it('should return warning-text if we can not receive node-list', async () => { (fetch as any).mockReturnValue(Promise.reject()); expect(await getNodeSecurityChecker()).toMatchObject({ error: false, text: logMessages.warning.fetchNodeListErrorNodeSecurity(nodeVersionListURL), }); }); it('should return error-text if we can not receive installed node version', async () => { (execa as any).mockReturnValue(Promise.reject()); expect(await getNodeSecurityChecker()).toMatchObject({ error: true, text: logMessages.error.readProgramVersionError('node'), }); }); });
<?php /** * @author @fabfuel <[email protected]> * @created 13.11.14, 08:13 */ namespace Fabfuel\Prophiler\Benchmark; /** * Interface BenchmarkInterface * @package Fabfuel\Prophiler\Benchmark */ interface BenchmarkInterface { /** * Unique identifier like e.g. Class::Method (\Foobar\MyClass::doSomething) * * @return string */ public function getName(); /** * Name of the component which triggered the benchmark, e.g. "App", "Database" * * @return string */ public function getComponent(); /** * Start the benchmark * * @return void */ public function start(); /** * Stop the benchmark * * @return void */ public function stop(); /** * Add interesting metadata to the benchmark * * @param array $metadata Additional metadata * @return void */ public function addMetadata(array $metadata); /** * @return array Custom metadata regarding this benchmark */ public function getMetadata(); /** * @param string $key Metadata key to receive * @return mixed Custom metadata value */ public function getMetadataValue($key = null); /** * @return double Total elapsed milliseconds */ public function getDuration(); /** * @return double Timestamp in microtime */ public function getStartTime(); /** * @return double Timestamp in microtime */ public function getEndTime(); /** * @return double Total memory usage */ public function getMemoryUsage(); /** * @return double Memory usage at benchmark start */ public function getMemoryUsageStart(); /** * @return double Memory usage at benchmark end */ public function getMemoryUsageEnd(); }
--- title: "新能源汽车电池使用分析" collection: projects type: "工业智能算法" permalink: /projects/2018-10-project-16 venue: "某大型汽车制造国企,联想" date: 2018-10-08 location: "重庆" --- 基于对海量电池数据的分析,结合行业专家知识,构建机器学习模型,完成电池健康度预测、健康度影响因子分析、电池使用行为模式、里程焦虑计算等。 该项目成果对用户电池使用行为做有效的指导,也给长安汽车进行电池相关的设计提供重要参考。 应用单位 ----- 重庆某大型汽车制造国企 实施周期 ----- 2018.10 – 2018.12 承担工作 ----- 项目首席科学家,核心算法设计。 核心技术 ----- 深度神经网络、GBDT、用户行为特征建模 结合用户行为进行user embedding,构建多任务深度神经网络 项目效果 ----- * 项目顺利交付 * 客户高度认可,与联想成立联合创新研发实验室 文献成果 ----- * [专利] [一种处理方法及电子设备](http://www2.soopat.com/Patent/201910174531) * [专利] [信息处理方法和具有电驱动功能的车辆](http://www2.soopat.com/Patent/201811367012) * [专利] [一种信息处理方法及信息处理装置](http://www2.soopat.com/Patent/201910156064) * [专利] [数据处理方法及其装置](http://www2.soopat.com/Patent/201811402639)
#!/usr/bin/env Rscript #sink(file("/dev/null", "w"), type = "message"); library(affy) library(GEOquery); library(pathprint); # Figure out the relative path to the galaxy-pathprint.r library. script.args <- commandArgs(trailingOnly = FALSE); script.name <- sub("--file=", "", script.args[grep("--file=", script.args)]) script.base <- dirname(script.name) library.path <- file.path(script.base, "galaxy-pathprint.r"); source(library.path) data(GEO.metadata.matrix); usage <- function() { sink(stderr(), type = "message"); stop("Usage: fingerprint.r [ARGS]", call. = FALSE) } ## Get the command line arguments. args <- commandArgs(trailingOnly = TRUE) type <- ifelse(! is.na(args[1]), args[1], usage()) if (type == "geo") { geoID <- ifelse(! is.na(args[2]), args[2], usage()); output <- ifelse(! is.na(args[3]), args[3], usage()); fingerprint <- generateFingerprint(geoID); } else if (type == "cel") { input <- ifelse(! is.na(args[2]), args[2], usage()); output <- ifelse(! is.na(args[3]), args[3], usage()); fingerprint <- loadFingerprintFromCELFile(input); } else if (type == "expr") { input <- ifelse(! is.na(args[2]), args[2], usage()); platform <- ifelse(! is.na(args[3]), args[3], usage()); output <- ifelse(! is.na(args[4]), args[4], usage()); fingerprint <- loadFingerprintFromExprsFile(input, platform); } else { usage(); }; saveFingerprint(fingerprint, output); quit("no", 0)
module ReportsHelper def net_suite_export_select_options [ ["NetSuite Donations Export", :donations], ["NetSuite Donors Export", :donors], ["NetSuite Orders Export", :orders], ["NetSuite Organizations Export", :organizations] ] end end
package com.task.noteapp.util import androidx.appcompat.widget.AppCompatImageView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade import com.bumptech.glide.request.transition.DrawableCrossFadeFactory fun AppCompatImageView.load(url: String) { val factory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build() Glide.with(this) .load(url) .transition(withCrossFade(factory)) .centerCrop() .into(this) }
<?php namespace GDO\Util; use GDO\Core\GDOError; final class HTAccess { public static function protectFolder($path) { $content = <<<EOF <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Deny from all </IfModule> EOF; # Create if not exist. if (!is_dir($path)) { @mkdir($path, GDO_CHMOD, true); } if ( (!is_dir($path)) || (!is_readable($path)) ) { throw new GDOError('err_no_dir'); } else { file_put_contents("$path/.htaccess", $content); } } }
// const Tuya = require('tuyapi'); const debug = require('debug')('TuyaSmartDevice'); const TuyaResolver = require('./lib/TuyaResolver'); const TuyaOutlet = require('./lib/TuyaOutlet'); const TuyaPowerStrip = require('./lib/TuyaPowerStrip'); const TuyaLightBulb = require('./lib/TuyaLightBulb'); // const TuyaAccessoryOld = require('./lib/TuyaAccessoryOld'); let homebridge; let Service; let Characteristic; const resolver = new TuyaResolver(); // const tuyaAccessory = new TuyaAccessoryOld(); // eslint-disable-next-line no-unused-vars const callbackify = (promise, callback) => { promise .then(result => callback(null, result)) .catch(error => callback(error)); }; class TuyaSmartDevice { constructor(log, config) { debug('constructor'); this.log = log; this.name = config.name; this.manufacturer = config.manufacturer || 'SLaweck - Tuya'; this.model = config.model || 'Smart device'; this.devId = config.devId; this.isLightbulb = config.type.includes('lightbulb'); this.isOutlet = config.type.includes('outlet'); this.isPowerstrip = config.type.includes('powerstrip'); this.isTimer = config.type.includes('timersensor'); this.interval = (config.interval || 30) * 1000; // this.isDimmable = config.type.includes('dimmable'); // this.isTunable = config.type.includes('tunable'); // this.brightMin = config.brightMin || 25; // this.brightMax = config.brightMax || 255; // this.brightDelta = this.brightMax - this.brightMin; // this.tempMin = config.tempMin || 0; // this.tempMax = config.tempMax || 255; // this.tempDelta = this.tempMax - this.tempMin; // this.informationService = null; // this.tuyaDeviceService = null; if (this.isOutlet) { this.tuyaDevice = new TuyaOutlet(config, resolver, log, homebridge); } else if (this.isPowerstrip) { this.tuyaDevice = new TuyaPowerStrip(config, resolver, log, homebridge); } else if (this.isLightbulb) { this.tuyaDevice = new TuyaLightBulb(config, resolver, log, homebridge); } } getServices() { let services; // if (this.isLightbulb) { // debug('getServices lightbulb'); // services = [this.tuyaDevice.getInformationService(), ...this.tuyaDevice.getDeviceService()]; // } else if (this.isOutlet) { // debug('getServices outlet'); // services = [this.tuyaDevice.getInformationService(), ...this.tuyaDevice.getDeviceService()]; // } else if (this.isPowerstrip) { // debug('getServices powerstrip'); // services = [this.tuyaDevice.getInformationService(), ...this.tuyaDevice.getDeviceService()]; // } else if (this.isTimer) { if (this.isTimer) { debug('getServices timer'); services = [this.getTimerInfoService(), this.getTimerDeviceService()]; } else { debug('getServices from Tuya device'); services = [this.tuyaDevice.getInformationService(), ...this.tuyaDevice.getDeviceService()]; } return services; } getTimerInfoService() { const timerInfoService = new Service.AccessoryInformation(); timerInfoService .setCharacteristic(Characteristic.Manufacturer, this.manufacturer) .setCharacteristic(Characteristic.Model, this.model) .setCharacteristic(Characteristic.SerialNumber, this.devId.slice(0)); return timerInfoService; } getTimerDeviceService() { const timerDeviceService = new Service.MotionSensor(this.name); let motion = false; const motionDetected = timerDeviceService.getCharacteristic(Characteristic.MotionDetected) .on('get', callback => callback(null, motion)); setInterval(() => { motion = !motion; debug('Update motion detect', motion); motionDetected.updateValue(motion); }, this.interval); return timerDeviceService; } } module.exports = (hb) => { homebridge = hb; ({ Service } = homebridge.hap); ({ Characteristic } = homebridge.hap); homebridge.registerAccessory('homebridge-tuya-smartdevice', 'TuyaSmartDevice', TuyaSmartDevice); // eslint-disable-next-line global-require // const TuyaPlatform = require('./lib/TuyaPlatform')(homebridge); // homebridge.registerPlatform('homebridge-tuya-platform', 'TuyaPlatform', TuyaPlatform, true); };
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:my_quotes/commons/resources/dimens.dart'; import 'package:my_quotes/commons/resources/my_quotes_icons.dart'; import 'package:my_quotes/commons/resources/strings.dart'; import 'package:my_quotes/commons/resources/styles.dart'; import 'package:my_quotes/commons/utils/presentation_formatter.dart'; import 'package:my_quotes/model/author.dart'; import 'package:my_quotes/commons/architecture/resource.dart'; import 'package:my_quotes/screens/author/author_screen.dart'; import 'package:my_quotes/tabs/authors/authors_tab_bloc.dart'; import 'package:provider/provider.dart'; class AuthorsTab extends StatelessWidget { final Function onDataChanged; AuthorsTab({@required this.onDataChanged}); @override Widget build(BuildContext context) { final bloc = Provider.of<AuthorsTabBloc>(context); return StreamBuilder<Resource<List<Author>>>( initialData: Resource.loading(), stream: bloc.authorsStream, builder: (_, AsyncSnapshot<Resource<List<Author>>> snapshot) { final resource = snapshot.data; switch (resource.status) { case Status.LOADING: return _buildProgressIndicator(); case Status.SUCCESS: return _buildSuccessBody(resource.data); case Status.ERROR: return Text(resource.message); } return Text(Strings.unknown_error); }); } Widget _buildProgressIndicator() { return Center( child: CircularProgressIndicator(), ); } Widget _buildSuccessBody(List<Author> authors) { if (authors.isEmpty) { return _buildEmptyView(); } else { return _buildAuthorsList(authors); } } Widget _buildEmptyView() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( MyQuotesIcons.authors, size: 120.0, color: Styles.lightGrey, ), SizedBox(height: Dimens.halfDefaultSpacing), Text( Strings.no_authors, style: TextStyle( color: Styles.lightGrey, fontSize: 16.0, ), ), ], ); } Widget _buildAuthorsList(List<Author> authors) { return Scrollbar( child: ListView.separated( itemCount: authors.length, separatorBuilder: (context, index) => Divider( height: 0.0, color: Styles.darkGrey, ), itemBuilder: (BuildContext context, int index) { final author = authors[index]; return _buildAuthorTile(context, author); }, ), ); } Widget _buildAuthorTile(BuildContext context, Author author) { return Material( child: InkWell( child: Padding( padding: const EdgeInsets.all(Dimens.defaultSpacing), child: Text( PresentationFormatter.formatAuthor(author), style: TextStyle( color: Colors.black, fontSize: 16.0, ), ), ), onTap: () => _openAuthorScreen(context, author), ), ); } Future<void> _openAuthorScreen(BuildContext context, Author author) async { print(author); await Navigator.push( context, MaterialPageRoute<void>(builder: (context) => AuthorScreen(author: author)), ); onDataChanged(); } }
package org.elm.ide.inspections import com.intellij.codeInspection.LocalInspectionTool import org.elm.lang.ElmTestBase import org.intellij.lang.annotations.Language abstract class ElmAnnotationTestBase : ElmTestBase() { protected fun doTest(vararg additionalFilenames: String) { myFixture.testHighlighting(fileName, *additionalFilenames) } protected fun checkByText( @Language("Elm") text: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) = check(text, checkWarn = checkWarn, checkInfo = checkInfo, checkWeakWarn = checkWeakWarn, configure = this::configureByText) protected fun checkByFileTree( @Language("Elm") text: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) = check(text, checkWarn = checkWarn, checkInfo = checkInfo, checkWeakWarn = checkWeakWarn, configure = this::configureByFileTree) private fun checkByText(text: String) { myFixture.checkResult(replaceCaretMarker(text.trimIndent())) } protected fun checkFixByText( fixName: String, @Language("Elm") before: String, @Language("Elm") after: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) = checkFix(fixName, before, after, configure = this::configureByText, checkBefore = { myFixture.checkHighlighting(checkWarn, checkInfo, checkWeakWarn) }, checkAfter = this::checkByText) protected fun checkFixByTextWithoutHighlighting( fixName: String, @Language("Elm") before: String, @Language("Elm") after: String ) = checkFix(fixName, before, after, configure = this::configureByText, checkBefore = {}, checkAfter = this::checkByText) private fun checkFix( fixName: String, @Language("Elm") before: String, @Language("Elm") after: String, configure: (String) -> Unit, checkBefore: () -> Unit, checkAfter: (String) -> Unit ) { configure(before) checkBefore() applyQuickFix(fixName) checkAfter(after) } protected fun checkFixByFileTree( fixName: String, @Language("Elm") treeText: String, @Language("Elm") after: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) = checkFix(fixName, treeText, after, configure = this::configureByFileTree, checkBefore = { myFixture.checkHighlighting(checkWarn, checkInfo, checkWeakWarn) }, checkAfter = this::checkByText) protected fun checkFixIsUnavailable( fixName: String, @Language("Elm") text: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) = checkFixIsUnavailable(fixName, text, checkWarn = checkWarn, checkInfo = checkInfo, checkWeakWarn = checkWeakWarn, configure = this::configureByText) protected fun checkFixIsUnavailableByFileTree( fixName: String, @Language("Elm") text: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) = checkFixIsUnavailable(fixName, text, checkWarn = checkWarn, checkInfo = checkInfo, checkWeakWarn = checkWeakWarn, configure = this::configureByFileTree) private fun checkFixIsUnavailable( fixName: String, @Language("Elm") text: String, checkWarn: Boolean, checkInfo: Boolean, checkWeakWarn: Boolean, configure: (String) -> Unit ) { check(text, checkWarn, checkInfo, checkWeakWarn, configure) check(myFixture.filterAvailableIntentions(fixName).isEmpty()) { "Fix $fixName should not be possible to apply." } } private fun check( @Language("Elm") text: String, checkWarn: Boolean, checkInfo: Boolean, checkWeakWarn: Boolean, configure: (String) -> Unit ) { configure(text) myFixture.checkHighlighting(checkWarn, checkInfo, checkWeakWarn) } } abstract class ElmInspectionsTestBase( val inspection: LocalInspectionTool ) : ElmAnnotationTestBase() { private fun enableInspection() = myFixture.enableInspections(inspection) override fun configureByText(text: String) { super.configureByText(text) enableInspection() } override fun configureByFileTree(text: String) { super.configureByFileTree(text) enableInspection() } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using VirtoCommerce.Domain.Common; using VirtoCommerce.Domain.Marketing.Model; namespace VirtoCommerce.MarketingModule.Expressions { public interface IConditionExpression { System.Linq.Expressions.Expression<Func<IEvaluationContext, bool>> GetConditionExpression(); } }
// @flow import React, { Component } from 'react'; import { Spinner } from '../../icons/Spinner'; import { FormInput } from '../../fields/FormInput'; import { Morfi, type FormData } from '../../../../dist/cjs/'; const validation = { password: { onChange: (v?: string) => { if (!v) return { id: 'PasswordRepeatForm.validation.password.required' }; if (RegExp('[^0-9a-zA-Z]').test(v)) return { id: 'PasswordRepeatForm.validation.password.validChars' }; }, onBlur: (v?: string) => { if (!v || v.length < 8) return { id: 'PasswordRepeatForm.validation.password.length' }; if (!RegExp('[^0-9]').test(v) || !RegExp('[^a-zA-Z]').test(v)) return { id: 'PasswordRepeatForm.validation.password.mixed' }; }, }, }; type MyFormValues = {| password: string, repeat: string |}; const initialValues: MyFormValues = { password: '', repeat: '' }; const { Form, Fields } = Morfi.create(initialValues); type PasswordRepeatFormState = {| data: FormData<MyFormValues> |}; const initialState: PasswordRepeatFormState = { data: { values: initialValues, errors: {} } }; export class PasswordRepeatForm extends Component<{}, PasswordRepeatFormState> { state = initialState; validation = { ...validation, repeat: { onChange: (v?: string) => { if (!v || v !== this.state.data.values.password) return { id: 'PasswordRepeatForm.validation.repeat.wrong' }; }, }, }; onChange = (data: FormData<MyFormValues>) => { if (this.state.data.values.password !== data.values.password) { this.setState({ data: { ...data, errors: { ...data.errors, repeat: undefined } } }); } else { this.setState({ data }); } }; onSubmit = (): void => window.sleep(1000); onSubmitFinished = () => this.setState(initialState); render(): React$Node { const data = this.state.data; const { submitting } = data; return ( <div className="col-12"> <Form validation={this.validation} onChange={this.onChange} data={data} onSubmit={this.onSubmit} onSubmitFinished={this.onSubmitFinished}> <div className="row"> <FormInput Field={Fields.password} label="Password" type="password" className="form-group col-sm-6" /> <FormInput Field={Fields.repeat} label="Password repetition" type="password" className="form-group col-sm-6" /> </div> <div className="btn-toolbar"> <button className="btn btn-success" disabled={submitting || Morfi.hasErrors(data)}> {submitting && <Spinner />} Submit </button> </div> </Form> </div> ); } }
package org.kin.sdk.design.view.widget.internal import android.app.Dialog import android.content.Context import android.graphics.Typeface import android.os.Bundle import android.view.Gravity import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.FrameLayout import android.widget.LinearLayout import org.kin.sdk.design.R import org.kin.sdk.design.view.tools.addTo import org.kin.sdk.design.view.tools.dip import org.kin.sdk.design.view.tools.setupViewExtensions class StandardDialog(context: Context) : Dialog(context) { private val rootLayout: LinearLayout private val titleText: PrimaryTextView private val descriptionText: SecondaryTextView private val errorText: CodeStyleTextView private val buttonLayout: LinearLayout companion object { fun confirm(context: Context, title: String = "", description: String = "", confirmed: (Boolean) -> Unit) { val standardDialog = StandardDialog(context) standardDialog.title = title standardDialog.description = description with(DialogButton(context)) { setText(context.getString(R.string.kin_sdk_button_ok)) setOnClickListener { standardDialog.dismiss() confirmed(true) } addTo(standardDialog.buttonLayout) } with(DialogButton(context)) { setText(context.getString(R.string.kin_sdk_button_cancel)) setOnClickListener { standardDialog.dismiss() confirmed(false) } addTo(standardDialog.buttonLayout) } standardDialog.setOnCancelListener { confirmed(false) } standardDialog.show() } fun error(context: Context, title: String = "", description: String = "", error: String = "") { val standardDialog = StandardDialog(context) standardDialog.title = title standardDialog.description = description standardDialog.error = error with(DialogButton(context)) { setText(context.getString(R.string.kin_sdk_button_ok)) setOnClickListener { standardDialog.dismiss() } addTo(standardDialog.buttonLayout) } standardDialog.show() } } init { context.setupViewExtensions() rootLayout = LinearLayout(context).also { rootLayout -> rootLayout.orientation = LinearLayout.VERTICAL titleText = with( PrimaryTextView( context ) ) { setText(title) textSize = 22f typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) visibility = GONE addTo(rootLayout, FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { leftMargin = 16.dip rightMargin = 16.dip topMargin = 16.dip bottomMargin = 8.dip gravity = Gravity.LEFT }) } descriptionText = with( SecondaryTextView( context ) ) { setText(description) visibility = GONE addTo(rootLayout, FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { leftMargin = 16.dip rightMargin = 16.dip topMargin = 8.dip bottomMargin = 8.dip gravity = Gravity.LEFT }) } errorText = with( CodeStyleTextView( context ) ) { setText(error) visibility = GONE val scrollWrapper = with( MaxHeightScrollView( context ) ) { maxHeight = 120.dip addTo(rootLayout, FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { leftMargin = 16.dip rightMargin = 16.dip topMargin = 8.dip bottomMargin = 8.dip gravity = Gravity.LEFT }) } addTo(scrollWrapper, WRAP_CONTENT, WRAP_CONTENT) } buttonLayout = with(LinearLayout(context)) { addTo(rootLayout, LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { leftMargin = 8.dip rightMargin = 8.dip topMargin = 8.dip bottomMargin = 8.dip gravity = Gravity.RIGHT }) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(rootLayout) } var title: String = "" set(value) { field = value titleText.visibility = if (value.isEmpty()) GONE else VISIBLE titleText.setText(value) } var description: String = "" set(value) { field = value descriptionText.visibility = if (value.isEmpty()) GONE else VISIBLE descriptionText.setText(value) } var error: String = "" set(value) { field = value errorText.visibility = if (value.isEmpty()) GONE else VISIBLE errorText.setText(value) } }
# -*- coding: utf-8 -*- # # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more information about nexB OSS projects. # import click import csv from commoncode.cliutils import PluggableCommandLineOption from licensedcode.models import load_licenses from licensedcode.models import load_rules LICENSES_FIELDNAMES = [ 'key', 'short_name', 'name', 'category', 'owner', 'text', 'words_count', 'notes', 'minimum_coverage', 'homepage_url', 'is_exception', 'language', 'is_unknown', 'spdx_license_key', 'reference_url', 'text_urls', 'other_urls', 'standard_notice', 'license_filename', 'faq_url', 'ignorable_authors', 'ignorable_copyrights', 'ignorable_holders', 'ignorable_urls', 'ignorable_emails', 'osi_license_key', 'osi_url', 'other_spdx_license_keys', ] RULES_FIELDNAMES = [ 'identifier', 'license_expression', 'relevance', 'text', 'words_count', 'category', 'is_false_positive', 'is_license_text', 'is_license_notice', 'is_license_tag', 'is_license_reference', 'is_license_intro', 'has_unknown', 'only_known_words', 'notes', 'referenced_filenames', 'minimum_coverage', 'ignorable_copyrights', 'ignorable_holders', 'ignorable_authors', 'ignorable_urls', 'ignorable_emails', ] SCANCODE_LICENSEDB_URL = 'https://scancode-licensedb.aboutcode.org/{}' def write_data_to_csv(data, output_csv, fieldnames): with open(output_csv, 'w') as f: w = csv.DictWriter(f, fieldnames=fieldnames) w.writeheader() for entry in data: w.writerow(entry) def filter_by_attribute(data, attribute, required_key): """ Filters by attribute, if value is required_key. Example `attribute`: `category`. Example `required_key`: `Permissive`. """ return [entry for entry in data if entry.get(attribute, 'None') == required_key] def flatten_output(data): assert isinstance(data, list) output = [] for entry in data: assert isinstance(entry, dict) output_entry = {} for key, value in entry.items(): if value is None: continue if isinstance(value, list): value = ' '.join(value) elif not isinstance(value, str): value = repr(value) output_entry[key] = value output.append(output_entry) return output @click.command() @click.option('-l', '--licenses', type=click.Path(dir_okay=False, writable=True, readable=False), default=None, metavar='FILE', help='Write all Licenses data to the csv FILE.', cls=PluggableCommandLineOption ) @click.option('-r', '--rules', type=click.Path(dir_okay=False, writable=True, readable=False), default=None, metavar='FILE', help='Write all Rules data to the csv FILE.', cls=PluggableCommandLineOption, ) @click.option('-c', '--category', type=str, default=None, metavar='STRING', help='An optional filter to only output licenses/rules of this category. ' 'Example STRING: `permissive`.', cls=PluggableCommandLineOption, ) @click.option('-k', '--lic-key', type=str, default=None, metavar='STRING', help='An optional filter to only output licenses/rules which has this lic key. ' 'Example STRING: `mit`.', cls=PluggableCommandLineOption, ) @click.option('-t', '--with-text', is_flag=True, default=False, help='Also include the lic/rules texts (First 200 characters). ' 'Note that this increases the file size significantly.', cls=PluggableCommandLineOption, ) @click.help_option('-h', '--help') def cli(licenses, rules, category, license_key, with_text): """ Write Licenses/Rules from scancode into a CSV file with all details. Output can be optionally filtered by category/lic-key. """ licenses_output = [] rules_output = [] licenses_data = load_licenses() if licenses: for lic in licenses_data.values(): license_data = lic.to_dict() if with_text: license_data['text'] = lic.text[:200] license_data['is_unknown'] = lic.is_unknown license_data['words_count'] = len(lic.text) license_data['reference_url'] = SCANCODE_LICENSEDB_URL.format(lic.key) licenses_output.append(license_data) if category: licenses_output = filter_by_attribute( data=licenses_output, attribute='category', required_key=category ) if license_key: licenses_output = filter_by_attribute( data=licenses_output, attribute='key', required_key=license_key, ) licenses_output = flatten_output(data=licenses_output) write_data_to_csv(data=licenses_output, output_csv=licenses, fieldnames=LICENSES_FIELDNAMES) if rules: rules_data = list(load_rules()) for rule in rules_data: rule_data = rule.to_dict() rule_data['identifier'] = rule.identifier rule_data['referenced_filenames'] = rule.referenced_filenames if with_text: rule_data['text'] = rule.text()[:200] rule_data['has_unknown'] = rule.has_unknown rule_data['words_count'] = len(rule.text()) try: rule_data['category'] = licenses_data[rule_data['license_expression']].category except KeyError: pass rules_output.append(rule_data) if category: rules_output = filter_by_attribute( data=rules_output, attribute='category', required_key=category, ) if license_key: rules_output = filter_by_attribute( data=rules_output, attribute='license_expression', required_key=license_key, ) rules_output = flatten_output(rules_output) write_data_to_csv(data=rules_output, output_csv=rules, fieldnames=RULES_FIELDNAMES) if __name__ == '__main__': cli()
package com.kasem.flutter_absolute_path import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import io.flutter.plugin.common.PluginRegistry.Registrar import android.content.Context import android.app.Activity import android.net.Uri import io.flutter.plugin.common.BinaryMessenger class FlutterAbsolutePathPlugin : FlutterPlugin, ActivityAware, MethodCallHandler{ private lateinit var channel : MethodChannel private lateinit var context: Context private lateinit var activity: Activity private var pluginBinding: FlutterPlugin.FlutterPluginBinding? = null private var activityBinding: ActivityPluginBinding? = null private var methodChannel: MethodChannel? = null override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutter_absolute_path") channel.setMethodCallHandler(this); context = flutterPluginBinding.applicationContext // From flutter file picker pluginBinding = flutterPluginBinding val messenger = pluginBinding?.binaryMessenger doOnAttachedToEngine(messenger!!) } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { // TODO: your plugin is no longer attached to a Flutter experience. } override fun onAttachedToActivity(binding: ActivityPluginBinding) { activity = binding.activity; // From flutter file picker doOnAttachedToActivity(binding) } override fun onDetachedFromActivity() { } override fun onDetachedFromActivityForConfigChanges() { } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { } override fun onMethodCall(call: MethodCall, result: Result) { when { call.method == "getAbsolutePath" -> { val uriString = call.argument<Any>("uri") as String val uri = Uri.parse(uriString) result.success(FileDirectory.getAbsolutePath(this.context, uri)) } else -> result.notImplemented() } } // V1 only private var registrar: Registrar? = null companion object { @JvmStatic fun registerWith(registrar: Registrar) { if (registrar.activity() != null) { val plugin = FlutterAbsolutePathPlugin() plugin.doOnAttachedToEngine(registrar.messenger()) plugin.doOnAttachedToActivity(null, registrar) } } } private fun doOnAttachedToActivity(activityBinding: ActivityPluginBinding?, registrar: Registrar? = null) { this.activityBinding = activityBinding this.registrar = registrar } private fun doOnAttachedToEngine(messenger: BinaryMessenger) { methodChannel = MethodChannel(messenger, "flutter_absolute_path") methodChannel?.setMethodCallHandler(this) context = pluginBinding!!.applicationContext } }
using P03.Detail_Printer; using System; using System.Collections.Generic; namespace P03.DetailPrinter { class Program { static void Main() { Employee employee = new Employee("GoshoEmploito"); List<string> peshosDocs = new List<string>() { "doc1", "doc2" }; Employee manager = new Manager("PeshoManagera", peshosDocs); Employee justWorker = new JustWorker("Manol4o", 40); List<Employee> employeeList = new List<Employee>(); employeeList.Add(employee); employeeList.Add(manager); employeeList.Add(justWorker); DetailsPrinter detail = new DetailsPrinter(employeeList); detail.PrintDetails(); } } }
require_dependency "larvata_gantt/application_controller" module LarvataGantt class LinkController < ApplicationController before_action :set_link, only: [:update, :destroy] def create link = Link.new(source_id: link_params[:source], target_id: link_params[:target], typing: link_params[:type].to_i) if link.save render json: { action: "inserted", tid: link.id }, status: 201 else render json: { action: "error", message: link.errors.full_messages }, status: 400 end end def update if @link.update(source_id: link_params[:source], target_id: link_params[:target], typing: link_params[:type].to_i) render json: { action: "updated" } else render json: { action: "error", message: @link.errors.full_messages }, status: 400 end end def destroy @link.destroy render json: { action: "deleted" } end private def link_params params.permit(:source, :target, :type) end def set_link @link = Link.find(params[:id]) end end end
# Architecture Decision Records - [1. add-openapi](0001-add-openapi.md) - [2. add-typedoc](0002-add-typedoc.md)
package com.wlangiewicz.workouttracker.domain case class SuccessfulUserSignUpResponse(apiKey: ApiKey) case class UnsuccessfulUserSignUpResponse() case class SuccessfulUserLoginResponse(apiKey: ApiKey) case class UnsuccessfulUserLoginResponse() case class SuccessfulRecordWorkoutResponse(workoutId: WorkoutId) case class UnsuccessfulRecordWorkoutResponse()
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { User } from 'src/app/modules/SignUpMessge.module'; import { JasperService } from 'src/app/services/fileGiver.service'; import { LocalStorageService } from 'src/app/services/LocalStorage/local-storage.service'; import { APIs } from 'src/app/vars/enums/API'; import { Routes } from 'src/app/vars/enums/ROUTES'; @Component({ selector: 'app-request-report', templateUrl: './request-report.component.html', styleUrls: ['./request-report.component.css'], }) export class RequestReportComponent implements OnInit { public _dateStart: string = ''; public _dateEnd: string = ''; public _action: string = ''; public _errorMessage: string = ''; public _showError: boolean = false; public _user: User; constructor( private _localStorage: LocalStorageService, private _router: Router ) { this._user = JSON.parse(`${this._localStorage.getData('user')}`); } ngOnInit(): void {} public requestReport() { if (this.isValid()) { this._router.navigate([ Routes.READ_REPORT, this._action, this._dateEnd, this._dateStart, ]); } } public requestReportAdmin() { if (this.isValid()) { this._router.navigate([ Routes.READ_REPORT, this._action, this._dateEnd, this._dateStart, ]); } } public isValid(): boolean { if (this._action == '') { this._showError = true; this._errorMessage = 'no has seleccionado una categoria valida'; return false; } return true; } }
import java.util.regex.Pattern /** * Created by tony on 2018/5/30. */ fun String.checkEmail(): Boolean { val emailPattern = "[a-zA-Z0-9][a-zA-Z0-9._-]{2,16}[a-zA-Z0-9]@[a-zA-Z0-9]+.[a-zA-Z0-9]+" return Pattern.matches(emailPattern, this) } fun main(args: Array<String>) { println("[email protected]".checkEmail()) }
export { AbsintheLink } from './absinthe/apollo-link'; export { AbsintheOperation } from './absinthe/absinthe'; export { PhoenixChannel } from './phoenix/channel'; export { PhoenixSerializer } from './phoenix/serializer'; export { PhoenixSocket } from './socket/socket';
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; using Xamarin.Forms; namespace CoffeeCups.iOS { [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { public override bool FinishedLaunching(UIApplication app, NSDictionary options) { var tint = UIColor.FromRGB(30,142,128); UINavigationBar.Appearance.BarTintColor = UIColor.FromRGB(242,197,0); //bar background UINavigationBar.Appearance.TintColor = tint; //Tint color of button items UINavigationBar.Appearance.SetTitleTextAttributes(new UITextAttributes { Font = UIFont.FromName("Avenir-Medium", 17f), TextColor = UIColor.Black }); UINavigationBar.Appearance.TitleTextAttributes = new UIStringAttributes { Font = UIFont.FromName("Avenir-Medium", 17f), ForegroundColor = UIColor.Black }; UIBarButtonItem.Appearance.TintColor = tint; //Tint color of button items //NavigationBar Buttons UIBarButtonItem.Appearance.SetTitleTextAttributes(new UITextAttributes { Font = UIFont.FromName("Avenir-Medium", 17f), TextColor = tint }, UIControlState.Normal); //TabBar UITabBarItem.Appearance.SetTitleTextAttributes(new UITextAttributes { Font = UIFont.FromName("Avenir-Book", 10f) }, UIControlState.Normal); UITabBar.Appearance.TintColor = tint; UISwitch.Appearance.OnTintColor = tint; global::Xamarin.Forms.Forms.Init(); Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init(); #if ENABLE_TEST_CLOUD Xamarin.Calabash.Start(); //Mapping StyleId to iOS Labels Forms.ViewInitialized += (object sender, ViewInitializedEventArgs e) => { if (null != e.View.StyleId) { e.NativeView.AccessibilityIdentifier = e.View.StyleId; } }; #endif LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
# Author:: radiospiel (mailto:[email protected]) # Copyright:: Copyright (c) 2011, 2012 radiospiel # License:: Distributes under the terms of the Modified BSD License, see LICENSE.BSD for details. require_relative 'test_helper' class MatchingTest < Test::Unit::TestCase def assert_match(value, expectation) assert_equal true, Expectation::Matcher.match?(value, expectation) end def assert_mismatch(value, expectation) assert_equal false, Expectation::Matcher.match?(value, expectation) end def test_mismatches_raise_exceptions assert_match 1, 1 assert_mismatch 1, 2 end def test_array_matches assert_match [1], [Integer] assert_mismatch [1], [String] assert_match [1, "2"], [[Integer, String]] assert_mismatch [1, "2", /abc/], [[Integer, String]] end def test_int_expectations assert_match 1, 1 assert_match 1, Integer assert_match 1, Integer assert_match 1, 0..2 assert_match 1, 0..1 assert_match 1, 1..10 assert_match 1, [0,1,2] assert_mismatch 1, 2 assert_mismatch 1, Float assert_mismatch 1, 0...1 assert_mismatch 1, 3..5 assert_mismatch 1, [3,4,5] end def test_lambda_expectations # passes in value? assert_match 1, lambda { |i| i.odd? } assert_mismatch 1, lambda { |i| i.even? } # does not pass in a value r = false assert_mismatch 1, lambda { r } r = true assert_match 1, lambda { r } end def test_regexp_expectations assert_match " foo", /foo/ assert_mismatch " foo", /^foo/ assert_match "1", /1/ assert_mismatch "1", /2/ assert_mismatch 1, /1/ assert_mismatch 1, /2/ end def test_hash_expectations assert_mismatch({}, { :key => "Foo" }) assert_match({ :key => "Foo" }, { :key => "Foo" }) assert_mismatch({ :other_key => "Foo" }, { :key => "Foo" }) assert_mismatch({ :key => "Bar" }, { :key => "Foo" }) assert_match({ :key => "Foo" }, { :key => String }) assert_match({ :key => "Foo" }, { :key => [Integer,String] }) assert_mismatch({ :key => "Foo" }, { :key => [Integer,"Bar"] }) assert_match({ :other_key => "Foo" }, { :key => [nil, "Foo"] }) end def test_uri_expectations assert_match "http://foo/bar", URI assert_match "/foo/bar", URI assert_mismatch " foo", URI assert_mismatch nil, URI assert_mismatch 1, URI end end
REAL B(11) CHARACTER*190 A C OPEN NEW FILES OPEN(1,FILE='KIM.DAT',STATUS='OLD') OPEN(2,FILE='DKIM.DAT',STATUS='NEW') C READ IN THE NUMBER OF LINES TO SKIP AND READ DO 600 LKK=1,32 READ(1,*)NS,NR WRITE(2,*)NS,NR DO 30 I=1,NS READ(1,22)A 30 CONTINUE DO 31 I=1,NR READ(1,*)NN,(B(IJ),IJ=1,6) WRITE(2,23)NN,(B(IJ),IJ=1,6) 31 CONTINUE 600 CONTINUE C TERMINATE PROGRAM 22 FORMAT(A) 90 FORMAT(2I3) 23 FORMAT(1X,I4,1X,6(E12.6,1X)) 100 CONTINUE STOP END
package sbt package client /** * An interface which clients that support interaction with tasks implement. */ trait Interaction { /** Prompts the user for input, optionally with a mask for characters. */ def readLine(prompt: String, mask: Boolean): Option[String] /** Ask the user to confirm something (yes or no) before continuing. */ def confirm(msg: String): Boolean }
<?php namespace Sendcloud\Shipping\Core\Infrastructure\TaskExecution\TaskEvents; use Sendcloud\Shipping\Core\Infrastructure\Utility\Events\Event; /** * Class TickEvent. * * @package Logeecom\Infrastructure\Scheduler */ class TickEvent extends Event { /** * Fully qualified name of this class. */ const CLASS_NAME = __CLASS__; }
from tests.base_test_case import BaseTestCase from app.utils.auth import Auth class TestAuth(BaseTestCase): def setUp(self): self.BaseSetUp() def test_get_user_method_return_dict_of_user_data_if_valid_header_present(self): with self.app.test_request_context(path='/api/v1/vendors', method='GET', headers=self.headers()) as request: user_data = Auth._get_user() self.assertIsInstance(user_data, dict) self.assertIsNotNone(user_data) self.assertJSONKeysPresent(user_data, 'id', 'first_name', 'last_name', 'email') def test_user_method_return_list_of_user_data_based_on_supplied_keys(self): with self.app.test_request_context(path='/api/v1/vendors', method='GET', headers=self.headers()) as request: decoded = Auth.decode_token(self.get_valid_token()) values = Auth.user('id', 'first_name', 'last_name', 'email') id, first_name, last_name, email = values self.assertIsInstance(values, list) self.assertEquals(decoded['UserInfo']['id'], id) self.assertEquals(decoded['UserInfo']['first_name'], first_name) self.assertEquals(decoded['UserInfo']['last_name'], last_name) self.assertEquals(decoded['UserInfo']['email'], email) def test_get_token_throws_exception_when_auth_header_missing(self): try: Auth.get_token() assert False except Exception as e: assert True def test_get_token_return_token_if_valid_header_present(self): with self.app.test_request_context(path='/api/v1/vendors', method='GET', headers=self.headers()) as request: token = Auth.get_token() self.assertIsInstance(token, str) self.assertIsNotNone(token) def test_decode_token_throws_exception_on_invalid_token(self): try: Auth.decode_token(self.get_invalid_token()) assert False except Exception as e: assert True def test_decode_token_returns_dict_on_valid_token(self): token = Auth.decode_token(self.get_valid_token()) if type(token) is dict: assert True else: assert False def test_get_location_throws_exception_when_location_header_missing(self): try: Auth.get_location() assert False except Exception as e: assert True def test_get_location_header_returns_int_value_when_location_header_present(self): with self.app.test_request_context(path='/api/v1/vendors', method='GET', headers=self.headers()) as request: location = Auth.get_location() self.assertIsInstance(location, int) self.assertIsNotNone(location)
import settings from '../config/settings'; import StorageService from './storage.service'; import PlatformService from './platform.service'; // Methods var Service = { getToken: getToken, refreshToken: refreshToken, forgotPassword: forgotPassword, getOauth: getOauth, createUser: createUser, getUser: getUser } /** * Get the authorization host * * @returns {String} */ function getHost() { return settings.authHost; } /** * Get the headers used for API calls * * @returns {*} */ function getHeaders() { return { 'Accept': 'application/json', 'Content-Type': 'application/json' } } function handleAuthResponse(data){ return Promise.all([ StorageService.set('access_token', data.access_token), StorageService.set('refresh_token', data.refresh_token) ]).then(() => { return data; }) } /** * Requests an oauth token using email/password * * @param {String} email * @param {String} password */ function getToken(email, password) { return fetch(getHost() + 'oauth/token', { method: 'POST', headers: getHeaders(), body: JSON.stringify({ email: email, password: password, client_id: settings.appKey, client_secret: settings.appSecret, grant_type: 'password' }) }) .then((response) => { return response.json().then(handleAuthResponse); }); } function refreshToken(){ return StorageService.get('refresh_token').then((refresh_token) => { if(!refresh_token) { return Promise.reject('no refresh token'); } return fetch(getHost() + 'oauth/token', { method: 'POST', headers: getHeaders(), body: JSON.stringify({ grant_type: 'refresh_token', refresh_token: refresh_token }) }) .then((response) => { if(response.status !== 200) throw new Error("refresh failed"); return response.json().then(handleAuthResponse); }); }); } /** * Gets oauth token using auth code, app id, app secret * * @param {String} authCode */ function getOauth(authCode) { return fetch(getHost() + 'oauth/token', { method: 'POST', headers: getHeaders(), body: JSON.stringify({ client_id: settings.appKey, client_secret: settings.appSecret, code: authCode, grant_type: "authorization_code", redirect_uri: settings.explicitUrl }) }) .then((response) => { return response.json().then(handleAuthResponse); }); } /** * Sends a forgot password request to authorization host * * @param {String} email */ function forgotPassword(email) { return fetch(getHost() + 'password/forgot', { method: 'POST', headers: getHeaders(), body: JSON.stringify({ email: email }) }) .then((response) => { return response.json(); }); } /** * Create a user * * @param {string} email * @param {string} password * @param {string} firstName * @param {string} lastName */ function createUser(email, password, firstName, lastName) { return fetch(getHost() + 'users', { method: 'POST', headers: getHeaders(), body: JSON.stringify({ email, first_name: firstName, last_name: lastName, password, application_id: settings.appKey }) }) .then((response) => { return response.json(); }); } /** * get the current user */ async function getUser() { let headers = getHeaders(); headers.Authorization = `Bearer ${await StorageService.get('access_token')}`; return fetch(getHost() + 'users/me', { method: 'get', headers: headers }) .then((response) => { return response.json(); }); } export default Service;
import Request from './request'; import { getQueryString } from './function'; import EventHandler from './event'; export { Request, getQueryString, EventHandler }
using System; namespace Karl.Graphics { public struct SpriteAnimationFrame { public TimeSpan Time; public Sprite Sprite; public SpriteAnimationFrame(TimeSpan time, Sprite sprite) { Time = time; Sprite = sprite; } } }
require 'spec_helper' describe Rulers do context 'has a version number' do Given(:version) { Rulers::VERSION } Then { version != nil} end end
# nodes-each > Loop through a NodeList (e.g. the result of querySelectorAll). ## Install `npm i --save nodes-each` ## nodesEach (NodeList, callback[, scope]) ``` var nodesEach = require('nodes-each'); nodesEach( document.querySelectorAll('.someSelector'), function (idx, el) { console.log('index: ' + idx, 'element: ' + el); }, this); ``` ## License MIT, see [LICENSE.md](http://github.com/stbaer/nodes-each/blob/master/LICENSE.md) for details.
<?php namespace App\Http\Controllers; use App\Models\User; use App\Models\Product; use App\Models\Store; use App\Models\Categury; use App\Http\Requests\StoreProductRequest; use App\Http\Requests\UpdateProductRequest; class ProductController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Product $product , store $store ) { if($store->user_id != auth()->user()->id) return back(); return view('backend.customer.creat product',compact('product','store')); } /** * Store a newly created resource in storage. * * @param \App\Http\Requests\StoreProductRequest $request * @return \Illuminate\Http\Response */ public function store(store $store) { $datavalidation= request()-> validate([ 'name'=>'required|min:4', 'price'=>'required', 'image'=>'required|mimes:jpeg,png,jpg|max:10000', 'gallery.*'=>'mimes:jpeg,png,jpg,jft,pdf|max:10000', 'discription'=>'required', ]); if(request()->hasFile('image')) $path='/storage/'.request()->file('image')->store('image_cat',['disk'=>'public']); $path2=array(); $galleries = request()->gallery; if(count($galleries) > 0){ for($i=0 , $imax = count($galleries) ; $i < $imax ; $i++){ $path2[$i]='/storage/'.$galleries[$i]->store('image_cat',['disk'=>'public']); } } $newproduct= new Product(); $newproduct->name = request()->name; $newproduct->price = request()->price; $newproduct->discount = request()->discount; $newproduct->image = $path; $newproduct->gallery = $path2; $newproduct->discription = request()->discription; $newproduct->ship = request()->ship; $newproduct->Inventory = request()->Inventory; $newproduct->discription_long = request()->discription_long; $newproduct->feature = request()->feature; $newproduct->unity = request()->unity; $newproduct->qyt = request()->qyt; $newproduct->cat_id = request()->cat_id; if(empty(request(['feature']))){ $newproduct->feature = '0'; }else{ $newproduct->feature = '1'; } $store->product()->save($newproduct); return redirect('/product/'.$store->id.'/All-Products'); } /** * Display the specified resource. * * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function show(Store $store , Product $product) { $products = Product:: where('store_id','=',$store->id)->inRandomOrder()->limit(4)->get(); return view('front customer.customer store.single-product',compact('product','store','products')); } /** * Show the form for editing the specified resource. * * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function edit(Product $product) { if($product->store->user_id != auth()->user()->id) return back(); $categury = Categury:: where('store_id', $product->store_id)->get(); return view('backend.customer.edite product',compact('product','categury')); } /** * Update the specified resource in storage. * * @param \App\Http\Requests\UpdateProductRequest $request * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function update(Product $product , store $store) { $datavalidation= request()-> validate([ 'name'=>'required|min:4', 'price'=>'required', 'image'=>'required|mimes:jpeg,png,jpg|max:10000', 'gallery.*'=>'mimes:jpeg,png,jpg|max:10000', 'discription'=>'required', ]); if(request()->hasFile('image')) $path='/storage/'.request()->file('image')->store('image_cat',['disk'=>'public']); $path2=array(); $galleries = request()->gallery; if(count($galleries) > 0){ for($i=0 , $imax = count($galleries) ; $i < $imax ; $i++){ $path2[$i]='/storage/'.$galleries[$i]->store('image_cat',['disk'=>'public']); } } $product->name = request()->name; $product->price = request()->price; $product->discount = request()->discount; $product->image = $path; $product->gallery = $path2; $product->discription = request()->discription; $product->ship = request()->ship; $product->Inventory = request()->Inventory; $product->discription_long = request()->discription_long; $product->feature = request()->feature; $product->unity = request()->unity; $product->qyt = request()->qyt; $product->cat_id = request()->cat_id; if(empty(request(['feature']))){ $product->feature='0'; }else{ $product->feature='1'; } $product->save(); return redirect('/product/'.$product->store->id.'/All-Products'); } /** * Remove the specified resource from storage. * * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function destroy(Product $product , Store $store) { $product->delete(); return back(); return redirect(route('allproduct',$store->id)); } }
package help import ( "bufio" "io" "os" "strconv" "strings" ) func ReadInput(path string) []string { fh, err := os.Open(path) if err != nil { panic(err) } lines := []string{} sc := bufio.NewScanner(io.Reader(fh)) for sc.Scan() { lines = append(lines, strings.Trim(sc.Text(), "\n")) } return lines } func Sinter(s string) int { i, _ := strconv.Atoi(s) return i } func Sinters(ss []string) []int { ints := []int{} for _, s := range ss { ints = append(ints, Sinter(s)) } return ints } func Min(ns ...int) int { t := ns[0] for _, v := range ns[1:] { if v < t { t = v } } return t } func Max(ns ...int) int { t := ns[0] for _, v := range ns[1:] { if v > t { t = v } } return t } func PosiMod(n int, modulus int) int { m := n % modulus if m < 0 { m += modulus } return m } func MinMax(ns []int) (int, int) { if len(ns) == 0 { return 0, 0 } min := ns[0] max := ns[0] for _, n := range ns[1:] { if n < min { min = n } if n > max { max = n } } return min, max } func Abs(i int) int { if i < 0 { return -i } return i }
this is hello world <script type="text/javascript"> // NOTE:// aJAX BEGINS $(function() { $(".lib_switch").click(function(){ // $(".ski_loader").css("display", "block"); $(".lib_point").load("{{route('vidlib.vidload')}}"); $.ajax({ success:function(re){ SnackBar.show({text:'Showing Video Section'}); $(".lib_icon").css("display", "block"); $(".vid_icon").css("display", "none"); } }); }); }); </script>
@extends('layouts.app') @section('title') Descrizione Category @endsection @section('main_content') <div class="container" class="d-flex"> <div>{{$category->genre}}</div> <div>{{$category->over18 ? 'si' : 'no'}}</div> </div> @endsection
module Aequitas class Matcher class Unary # Matcher that matches on attribute of value class Attribute < self # Return operand result for length of value # # @return [true] # if operand returns false # # @return [false] # otherwise # # @api private # def matches?(value) operand_matches?(value.public_send(attribute_name)) end # Return attribute name # # @return [Symbol] # # @api private # attr_reader :attribute_name private # Initialize object # # @param [Matcher] operand # @param [Symbol] attribute_name # # @return [undefined] # # @api private # def initialize(attribute_name, operand) @attribute_name = attribute_name super(operand) end end end end end
using Microsoft.VisualStudio.TestTools.UnitTesting; using Bakery.Models; namespace Bakery.Tests { [TestClass] public class BreadTests { [TestMethod] public void Constructor_InitializesObject_IsBread() { Bread newBread = new Bread(1); Assert.AreEqual(typeof(Bread), newBread.GetType()); } [TestMethod] public void Constructor_RunsPricingLogic_OrderTotal() { Bread bread1 = new Bread(1); Assert.AreEqual(bread1.Total, 5); Bread bread2 = new Bread(2); Assert.AreEqual(bread2.Total, 10); Bread bread3 = new Bread(3); Assert.AreEqual(bread3.Total, 10); Bread bread4 = new Bread(7); Assert.AreEqual(bread4.Total, 25); } [TestMethod] public void UpdateTotal_UpdatesPriceAfterInitialization_NewOrderTotal() { Bread newBread = new Bread(1); Assert.AreEqual(newBread.Total, 5); newBread.Quantity = 7; newBread.UpdateTotal(); Assert.AreEqual(newBread.Total, 25); } } }
package io.gitlab.arturbosch.detekt.formatting import io.gitlab.arturbosch.detekt.formatting.wrappers.MaximumLineLength import io.gitlab.arturbosch.detekt.test.TestConfig import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.nio.file.Paths class MaximumLineLengthSpec { private lateinit var subject: MaximumLineLength @BeforeEach fun createSubject() { subject = MaximumLineLength(TestConfig(MAX_LINE_LENGTH to "30")) } @Nested inner class `a single function` { val code = """ package home.test fun f() { /* 123456789012345678901234567890 */ } """.trimIndent() @Test fun `reports line which exceeds the threshold`() { assertThat(subject.lint(code)).hasSize(1) } @Test fun `reports issues with the filename and package as signature`() { val finding = subject.lint( code, Paths.get("home", "test", "Test.kt").toString() ).first() assertThat(finding.entity.signature).isEqualTo("home.test.Test.kt:2") } @Test fun `does not report line which does not exceed the threshold`() { val config = TestConfig(MAX_LINE_LENGTH to code.length) assertThat(MaximumLineLength(config).lint(code)).isEmpty() } } @Test fun `does not report line which does not exceed the threshold`() { val code = "val a = 1" assertThat(subject.lint(code)).isEmpty() } @Test fun `reports correct line numbers`() { val findings = subject.lint(longLines) // Note that KtLint's MaximumLineLength rule, in contrast to detekt's MaxLineLength rule, does not report // exceeded lines in block comments. assertThat(findings).hasSize(2) assertThat(findings[0].entity.location.source.line).isEqualTo(8) assertThat(findings[1].entity.location.source.line).isEqualTo(14) } @Test fun `does not report back ticked line which exceeds the threshold`() { val code = """ package home.test fun `this is a test method that has more than 30 characters inside the back ticks`() { } """.trimIndent() val findings = MaximumLineLength( TestConfig( MAX_LINE_LENGTH to "30", "ignoreBackTickedIdentifier" to "true" ) ).lint(code) assertThat(findings).isEmpty() } } const val MAX_LINE_LENGTH = "maxLineLength"
import { print, info, warn, error, data, debug, getDate } from './lib/utils'; export { print, info, warn, error, data, debug, getDate };
# WARNING: THIS SCRIPT DELETES DATA, RUN IT AT YOUR OWN RISK # MAKE SURE THAT YOUR QUERY RETURNS CHANGESETS YOU WANT TO DELETE # THE SCRIPT IS FOR DEMO PURPOSES ONLY AND IS NOT SUPPORTED BY RALLY require 'rally_api' #Setup custom app information headers = RallyAPI::CustomHttpHeader.new() headers.name = "Create image attachment, add inline to the description" headers.vendor = "Nick M RallyLab" headers.version = "1.0" # Connection to Rally config = {:base_url => "https://rally1.rallydev.com/slm"} config[:api_key] = "_abc123" config[:workspace] = "W" config[:project] = "P1" config[:headers] = headers #from RallyAPI::CustomHttpHeader.new() config[:version] = "v2.0" @rally = RallyAPI::RallyRestJson.new(config) #find changesets that meet criteria query = RallyAPI::RallyQuery.new() query.type = "changeset" query.fetch = "ObjectID,Message" query.query_string = "(Message contains \"DE4\")" results = @rally.find(query) changesets_to_delete = []; results.each do |c| puts "ObjectID: #{c["ObjectID"]}, Message: #{c["Message"]}" c.read changesets_to_delete << c end #delete changesets changesets_to_delete.each do |c| puts "deleting... #{c["_ref"]}" c.delete end
# 任务二 分别实现如下的 document: - dish ``` { "name": "Uthapizza", "image": "images/uthapizza.png", "category": "mains", "label": "Hot", "price": "4.99", "description": "A unique . . .", "comments": [ { "rating": 5, "comment": "Imagine all the eatables, living in conFusion!", "author": "John Lemon" }, { "rating": 4, "comment": "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!", "author": "Paul McVites" } ] } ``` - promotion ``` { "name": "Weekend Grand Buffet", "image": "images/buffet.png", "label": "New", "price": "19.99", "description": "Featuring . . ." } ``` - leadership ``` { "name": "Peter Pan", "image": "images/alberto.png", "designation": "Chief Epicurious Officer", "abbr": "CEO", "description": "Our CEO, Peter, . . ." } ```
#!/bin/sh : ${SRCROOT:?"generate-rlmplatform.sh must be invoked as part of an Xcode script phase"} SOURCE_FILE="${SRCROOT}/Realm/RLMPlatform.h.in" DESTINATION_FILE="${TARGET_BUILD_DIR}/${PUBLIC_HEADERS_FOLDER_PATH}/RLMPlatform.h" TEMPORARY_FILE="${TARGET_TEMP_DIR}/RLMPlatform.h" PLATFORM_SUFFIX="$SWIFT_PLATFORM_TARGET_PREFIX" if [ "$IS_MACCATALYST" = "YES" ]; then PLATFORM_SUFFIX=maccatalyst fi unifdef -B -DREALM_BUILDING_FOR_$(echo ${PLATFORM_SUFFIX} | tr "[:lower:]" "[:upper:]") < "${SOURCE_FILE}" | sed -e "s/''/'/" > "${TEMPORARY_FILE}" if ! cmp -s "${TEMPORARY_FILE}" "${DESTINATION_FILE}"; then echo "Updating ${DESTINATION_FILE}" cp "${TEMPORARY_FILE}" "${DESTINATION_FILE}" fi
# This should reverse a string def reverseString(str) str.reverse! end def reverseStringManual(str) arr = str.split("") revArr = [] arr.each do |i| revArr.unshift( i ) end revArr.join("") end def translatePigLatin(str) return "#{str}way" if str[0] =~ /[aeoui]/i arr = str.split("") until arr[0] =~ /[aeoui]/i char = arr.shift arr << char end arr.join("") + "ay" end
#!/bin/sh set -e if [ $(uname) = "Linux" ]; then apk add --no-cache --no-progress py2-pip imagemagick pip install b2 fi scene=$1 output=$2 commit_hash=$3 fullname=$(basename $scene) filename=${fullname%.*} # Render images mkdir -p "$output" build/raycaster $scene \ | convert - $output/${commit_hash}-${filename}-raycast.png build/raytracer $scene \ | convert - $output/${commit_hash}-${filename}-raytrace.png build/pathtracer -p1 -m1 $scene \ | convert - $output/${commit_hash}-${filename}-pathtrace.png build/radiosity exact -e10 $scene \ | convert - $output/${commit_hash}-${filename}-rad-exact.png build/radiosity hierarchical --gouraud --max-subdivisions=1 -e10 $scene \ | convert - $output/${commit_hash}-${filename}-rad-hierarchical.png # Upload images and comment on PR if [ -n "$B2_APP_KEY" ] && [ -n "$B2_ACCOUNT_ID" ]; then if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then scripts/upload-and-comment.py -c $commit_hash -pr $TRAVIS_PULL_REQUEST $output else scripts/upload-and-comment.py -c $commit_hash $output fi fi
--- title: "Plt. Ka. Sub. Bid. IE" description: "Penata Tingkat I / IIId" image: "https://i.pinimg.com/originals/b2/6a/28/b26a28fb468f65885740ff8ef273e76f.jpg" date: 2020-07-07T11:36:05+07:00 draft: false author: "Hetty Novianti, S.Si." ---
module Elasticemail module Account FIELDS_PRESENCE_REQUIRED = %w[ first_name last_name address_2 delivery_reason ] ACCOUNT_UPDATE_PROFILE_ATTRIBUTES_MAPPING = { :address_1 => "address1", :address_2 => "address2", :api_key => "apikey", :city => "city", :company => "company", :country_id => "countryID", :delivery_reason => "deliveryReason", :first_name => "firstName", :last_name => "lastName", :logo_url => "logoUrl", :marketing_consent => "marketingConsent", :phone => "phone", :state => "state", :tax_code => "taxCode", :website => "website", :zip => "zip", :post_code => "zip", :postal_code => "zip", :zip_code => "zip", }.freeze # http://api.elasticemail.com/public/help#Account_UpdateProfile class UpdateProfileAccount < Struct.new(*ACCOUNT_UPDATE_PROFILE_ATTRIBUTES_MAPPING.keys) include Elasticemail::Base def initialize(*args) super(*args) initialize_required_fileds self.marketing_consent = 'false' end def path :"/account/updateprofile" end def mapping ACCOUNT_UPDATE_PROFILE_ATTRIBUTES_MAPPING end private def initialize_required_fileds FIELDS_PRESENCE_REQUIRED.each { |field| public_send("#{field}=", "") } end end end end
# A few examples illustrating polisher's core extensions require 'polisher/core' puts "rails.gem".gem? # => true puts "rails".gem? # => false puts "rake.gemspec".gemspec? # => true puts "rake".gemspec? # => false puts "/foo/Gemfile".gemfile? # => true puts "/foo/Gemfile.in".gemfile? # => false puts "%doc lib/foo.rb".unrpmize # => lib/foo.rb puts "%{_bindir}/rake".unrpmize # => /bin/rake puts "/bin/rake".rpmize # => "%{_bindir}/rake"
#!/bin/bash sudo gdb --args ./dpdk_picoquicdemo -l 0-4 -a 0000:51:00.0 -- -p 4443
angular-scratch =============== Scratch space for messing with AngularJS. Nothing to see here. Move along.
{-# LANGUAGE MultiWayIf #-} module Lib ( parseStdIn ) where import Scri.GhcWrap import Scri.Ast import qualified Scri.Token as T import Scri.Lexer import Scri.Parser import Control.Monad.IO.Class import System.Environment import qualified Data.List as List parseStdIn :: IO () parseStdIn = do putStrLn "hey" args <- getArgs let isArg optStr = optStr `elem` args s <- getContents print s {-let useThisParser (optList, _) = any isArg optList let maybeSelectedChoice = List.find useThisParser [ (["--lexTokens", "-t"], onlyLexTokens) , (["--parse", "-p"], printParse) ] case maybeSelectedChoice of Just (_, choice) -> choice s _ -> return ()-} --putStrLn $ either id id $ onlyLexTokens s if | isArg "--lexTokens" -> case runAlex s loop of (Right tokens) -> mapM_ (print) tokens (Left errorMsg) -> putStrLn $ "Error: " ++ errorMsg | otherwise -> let result = parse s :: Either String Script in print result where printParse s = let result = parse s :: Either String Script in print result onlyLexTokens s = do let res = runAlex s loop putStrLn $ case res of Left errStr -> errStr Right tokens -> unlines $ map show tokens loop = do token <- alexMonadScan if token == T.EOFToken then return [token] else do rest <- loop return (token:rest)
#include "config.h" #ifdef LIB_USE_UART #include <cassert> #include <cstdarg> #include "uart_device.h" #include "util.h" std::array<std::function<void(const uint8_t)>, 5> UartDevice::listeners_ = {nullptr}; /** * @brief USART1 Handler */ extern "C" void USART1_IRQHandler(); /** * @brief USART2 Handler */ extern "C" void USART2_IRQHandler(); /** * @brief USART3 Handler */ extern "C" void USART3_IRQHandler(); /** * @brief UART4 Handler */ extern "C" void USART4_IRQHandler(); /** * @brief UART5 Handler */ extern "C" void USART5_IRQHandler(); namespace { /** * @param id ID of UART we are using * @return @c Uart::Config object of our UART object */ inline UART::Config GetUartConfig(const uint8_t id) { assert_param(id < LIB_USE_UART); assert(id < 7); UART::Config uart_config; switch (id) { default: assert(false); [[fallthrough]]; case 0: #if LIB_USE_UART > 0 uart_config.usart = USART1; uart_config.rcc = RCC_APB2Periph_USART1; uart_config.tx = {GPIOA, GPIO_Pin_9}; uart_config.rx = {GPIOA, GPIO_Pin_10}; uart_config.tx_periph = RCC_APB2Periph_GPIOA; uart_config.rx_periph = RCC_APB2Periph_GPIOA; uart_config.irq = USART1_IRQn; break; #endif // LIB_USE_UART > 0 } return uart_config; } } // namespace extern "C" void USART1_IRQHandler() { if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) { auto data = static_cast<char>(USART_ReceiveData(USART1)); UartDeviceTriggerListener(UartDevice::kUart1, data); USART_ClearITPendingBit(USART1, USART_IT_RXNE); } } extern "C" void USART2_IRQHandler() { if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) { auto data = static_cast<char>(USART_ReceiveData(USART2)); UartDeviceTriggerListener(UartDevice::kUart2, data); USART_ClearITPendingBit(USART2, USART_IT_RXNE); } } extern "C" void USART3_IRQHandler() { if (USART_GetITStatus(USART3, USART_IT_RXNE) != RESET) { auto data = static_cast<char>(USART_ReceiveData(USART3)); UartDeviceTriggerListener(UartDevice::kUart3, data); USART_ClearITPendingBit(USART3, USART_IT_RXNE); } } extern "C" void USART4_IRQHandler() { if (USART_GetITStatus(UART4, USART_IT_RXNE) != RESET) { auto data = static_cast<char>(USART_ReceiveData(UART4)); UartDeviceTriggerListener(UartDevice::kUart4, data); USART_ClearITPendingBit(UART4, USART_IT_RXNE); } } extern "C" void USART5_IRQHandler() { if (USART_GetITStatus(UART5, USART_IT_RXNE) != RESET) { auto data = static_cast<char>(USART_ReceiveData(UART5)); UartDeviceTriggerListener(UartDevice::kUart5, data); USART_ClearITPendingBit(UART5, USART_IT_RXNE); } } void UartDeviceTriggerListener(const uint8_t uart_port, const char data) { auto listener = UartDevice::InvokeListener(uart_port); if (listener) { listener(data); } } UartDevice::UartDevice(const Config& config) : device_id_(config.id) { auto uart_config = GetUartConfig(device_id_); uart_config.baud_rate = config.baud_rate; uart_ = std::make_unique<UART>(uart_config); } void UartDevice::SetListener(Listener&& listener) { listeners_[device_id_] = listener; uart_->EnableInterrupt(); } void UartDevice::Tx(const std::string& s) { uart_->Tx(s); } void UartDevice::Tx(const char* data, ...) { va_list args; va_start(args, data); uart_->Tx(data, args); va_end(args); } void UartDevice::TxByte(const uint8_t byte) { uart_->TxByte(byte); } #endif // LIB_USE_UART
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next class DoubleConnectedNode: def __init__(self, value, next=None, prev=None): self.value = value self.next = next self.prev = prev def print_linked_list(vertex): while vertex: print(vertex.value, end=" -> ") vertex = vertex.next print("None") def get_node_by_index(node, index): while index: node = node.next index -= 1 return node def insert_node(head, index, value): new_node = Node(value) if index == 0: new_node.next = head return new_node previous_node = get_node_by_index(head, index-1) new_node.next = previous_node.next previous_node.next = new_node return head def delete_node(head, index): if index == 0: head = head.next return head previous_node = get_node_by_index(head, index-1) del_node = previous_node.next previous_node.next = del_node.next return head def found_index(node, elem): idx = 0 while node: if node.value == elem: return idx node = node.next idx += 1 return -1 def reverse_list(node): while node.next: node.next, node.prev = node.prev, node.next node = node.prev node.next, node.prev = node.prev, node.next return node # n3 = Node('third') # n2 = Node('second', n3) # n1 = Node('first', n2) # n0 = Node('zero', n1) # node, index, value = n0, 1, 'new_node' # head = insert_node(node, index, value) # head, index = n0, 2 # head = delete_node(head, index) # print_linked_list(head) # print(found_index(n0, 'second')) n3 = DoubleConnectedNode('third') n2 = DoubleConnectedNode('second') n1 = DoubleConnectedNode('first') n0 = DoubleConnectedNode('zero') n0.next = n1 n1.next = n2 n1.prev = n0 n2.next = n3 n2.prev = n1 n3.prev = n2 head = n0 rev_head = reverse_list(head) print_linked_list(rev_head)
/* Author: Cristian E. Nuno Date: November 9, 2019 Purpose: Identify the schools that are located in community areas that have the highest number of jobs in 2017. Note: This question is vague. After looking at the distribution of jobs per community area, I'll leave say "highest number" means more than 100K jobs per community area. */ DROP TABLE IF EXISTS school_cca_jobs; CREATE TABLE school_cca_jobs AS ( SELECT * FROM ( SELECT cps.school_id, cps.long_name, cps.primary_category, cps.overall_rating, cps.classification_description, CASE WHEN jobs.num_jobs_2017 >= 100000 THEN 1 ELSE 0 END AS high_employment_cca, jobs.num_jobs_2017 FROM cps_sy1819_cca AS cps LEFT JOIN jobs_by_cca AS jobs ON cps.community = jobs.cca_name ) AS schools WHERE high_employment_cca = 1 ); -- Check the overall_rating count for these CPS schools in high employment areas /* For more on window functions (i.e. OVER()), see these posts: https://stackoverflow.com/questions/6489848/percent-to-total-in-postgresql-without-subquery https://www.postgresql.org/docs/current/tutorial-window.html */ SELECT *, SUM(count) OVER() AS total, ROUND((count / SUM(count) OVER()) * 100, 2) AS pct FROM ( SELECT overall_rating, COUNT(overall_rating) AS count FROM school_cca_jobs GROUP BY overall_rating ORDER BY overall_rating ) AS temp; -- Compare it to the distribution against all CPS schools SELECT *, SUM(count) OVER() AS total, ROUND((count / SUM(count) OVER()) * 100, 2) AS pct FROM ( SELECT overall_rating, COUNT(overall_rating) AS count FROM cps_sy1819_cca GROUP BY overall_rating ORDER BY overall_rating ) AS temp; /* Conclusion: those schools in higher employment areas have a larger proportion of Level 1+ schools (40%) when compared to the proportion of Level 1+ schools across all of CPS (28%) */
using System.Collections.Generic; using VkBotFramework.Models; using VkNet.Model; namespace VkBotFramework.Abstractions { public interface IRegexToActionTemplateManager { IEnumerable<RegexToActionTemplate> SearchTemplatesMatchingMessage(Message message); //void Register(string incomingMessageRegexPattern, string responseMessage, // MessageKeyboard messageKeyboard = null, // RegexOptions incomingMessageRegexPatternOptions = RegexOptions.IgnoreCase); //void Register(string incomingMessageRegexPattern, List<string> responseMessages, // MessageKeyboard messageKeyboard = null, // RegexOptions incomingMessageRegexPatternOptions = RegexOptions.IgnoreCase); //void Register(string incomingMessageRegexPattern, Action<VkBot, Message> callback, // RegexOptions incomingMessageRegexPatternOptions = RegexOptions.IgnoreCase); void Unregister(RegexToActionTemplate template); void Unregister(string incomingMessageRegexPattern, long peerId = 0); void Register(RegexToActionTemplate template); } }
# frozen_string_literal: true require 'bundler/setup' require 'polyphony' module GenServer module_function def start(receiver, *args) fiber = spin do state = receiver.initial_state(*args) loop do msg = receive reply, state = receiver.send(msg[:method], state, *msg[:args]) msg[:from] << reply unless reply == :noreply end end build_api(fiber, receiver) fiber end def build_api(fiber, receiver) receiver.methods(false).each do |m| if m =~ /!$/ fiber.define_singleton_method(m) do |*args| GenServer.cast(fiber, m, *args) end else fiber.define_singleton_method(m) do |*args| GenServer.call(fiber, m, *args) end end end end def cast(process, method, *args) process << { from: Fiber.current, method: method, args: args } end def call(process, method, *args) process << { from: Fiber.current, method: method, args: args } receive end end # In a generic server the state is not held in an instance variable but rather # passed as the first parameter to method calls. The return value of each method # is an array consisting of the result and the potentially mutated state. module Map module_function def initial_state(hash = {}) hash end def get(state, key) [state[key], state] end def put!(state, key, value) state[key] = value [:noreply, state] end end # start server with initial state map_server = GenServer.start(Map, {foo: :bar}) puts 'getting value from map server' v = map_server.get(:foo) puts "value: #{v.inspect}" puts 'putting value in map server' map_server.put!(:foo, :baz) puts 'getting value from map server' v = map_server.get(:foo) puts "value: #{v.inspect}" map_server.stop
<?php namespace App\Controllers; use App\Models\KomikModel; class Komik extends BaseController{ protected $komikModel; public function __construct() { $this->komikModel=new KomikModel(); } public function index(){ // $komik=$this->komikModel->findAll(); $data=[ 'title'=>'daftar komik', 'title2'=>'Daftar Komik', 'komik'=>$this->komikModel->getKomik() ]; // contoh manual konek DB // $db=\Config\Database::connect(); // $komik=$db->query("SELECT * FROM komik"); // d($komik); return view('komik/v_index',$data); } public function detail($slug){ $data=[ 'komik'=>$this->komikModel->getKomik($slug), 'title'=>'Detail Komik', 'title2'=>'Detail Komik' ]; return view('komik/v_detail',$data); } public function create(){ $data=[ 'title'=>'Form Tambah Data', 'title2'=>'Form Tambah Data Komik', 'validation'=>\Config\Services::validation(), ]; return view('komik/v_create',$data); } public function save(){ if(!$this->validate([ 'judul'=>[ 'rules'=>'required|is_unique[komik.judul]', 'errors'=>[ 'required'=>'{field} Komik Harus di Isi', 'is_unique'=>'{field} Komik Sudah ada' ] ] ])){ $validation=\Config\Services::validation(); return redirect()->to('/komik/create')->withInput()->with('validation',$validation); } $slug=url_title($this->request->getVar('judul'),'-',true); $this->komikModel->save([ 'judul'=>$this->request->getVar('judul'), 'sampul'=>$this->request->getVar('sampul'), 'slug'=>$slug ]); session()->setFlashdata('pesan','data berhasil di tambah'); return redirect()->to('/komik'); } } ?>
//! PWM implementation use super::pads::{ad_b0::*, b0::*, b1::*, emc::*, sd_b0::*}; use crate::{ consts::*, pwm::{Pin, A, B}, }; impl Pin for SD_B0_00 { const ALT: u32 = 1; type Output = A; type Module = U1; // FlexPWM1 type Submodule = U0; // FlexPWM1 } impl Pin for SD_B0_01 { const ALT: u32 = 1; type Output = B; type Module = U1; // FlexPWM1 type Submodule = U0; // FlexPWM1 } impl Pin for AD_B0_10 { const ALT: u32 = 1; type Output = A; type Module = U1; // FlexPWM1 type Submodule = U3; // PWM3 } impl Pin for AD_B0_11 { const ALT: u32 = 1; type Output = B; type Module = U1; // FlexPWM1 type Submodule = U3; // PWM3 } impl Pin for B0_10 { const ALT: u32 = 2; type Output = A; type Module = U2; // FlexPWM2 type Submodule = U2; // FlexPWM2 } impl Pin for B0_11 { const ALT: u32 = 2; type Output = B; type Module = U2; // FlexPWM2 type Submodule = U2; // FlexPWM2 } impl Pin for B1_01 { const ALT: u32 = 6; type Output = B; type Module = U1; type Submodule = U3; } impl Pin for B1_00 { const ALT: u32 = 6; type Output = A; type Module = U1; type Submodule = U3; } impl Pin for EMC_04 { const ALT: u32 = 1; type Output = A; type Module = U4; type Submodule = U2; } impl Pin for EMC_05 { const ALT: u32 = 1; type Output = B; type Module = U4; type Submodule = U2; } impl Pin for EMC_06 { const ALT: u32 = 1; type Output = A; type Module = U2; type Submodule = U0; } impl Pin for EMC_08 { const ALT: u32 = 1; type Output = A; type Module = U2; type Submodule = U1; }
[CmdletBinding()] param( ) $script:Aliases = @{ 'ac' = 'Add-Content'; 'cat' = 'Get-Content'; 'cd' = 'Set-Location'; 'clear' = 'Clear-Host'; 'cp' = 'Copy-Item'; 'cpp' = 'Copy-ItemProperty'; 'diff' = 'Compare-Object'; 'echo' = 'Write-Output'; 'kill' = 'Stop-Process'; 'ls' = 'Get-ChildItem'; 'man' = 'Get-Help'; 'mount' = 'New-PSDrive'; 'mv' = 'Move-Item'; 'ps' = 'Get-Process'; 'pwd' = 'Get-Location'; 'rm' = 'Remove-Item'; 'rmdir' = 'Remove-Item'; 'sleep' = 'Start-Sleep'; 'sort' = 'Sort-Object'; 'tee' = 'Tee-Object'; 'type' = 'Get-Content'; 'write' = 'Write-Output'; }; $script:Aliases.Keys | ForEach-Object { Write-Verbose -Message "Adding $_"; Set-Alias -Name $_ -Value $script:Aliases[$_] -Option AllScope -Scope Global; }
package com.danavalerie.util.ref; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class RefTest { @Test public void testRef() { final Ref<String> ref = new Ref<>(); assertThat(ref.get()).isNull(); ref.set("foo"); assertThat(ref.get()).isEqualTo("foo"); ref.set("bar"); assertThat(ref.get()).isEqualTo("bar"); ref.set(null); assertThat(ref.get()).isNull(); ref.set("baz"); assertThat(ref.get()).isEqualTo("baz"); } }