text
stringlengths
27
775k
#!/bin/sh set -e # Format with Black black errantbot/*.py if [[ -n $(git diff) ]]; then echo "Formatted with Black" fi DBNAME=$(python - <<EOF from errantbot import helper print(helper.get_secrets()["database"]["name"]) EOF ) # Export schema ./export_schema.sh $DBNAME if [[ -n $(git diff schema.sql) ]]; then echo "Changed database schema file" fi if [[ -n $(git diff) ]]; then echo "Changed files; add the changes and re-commit" exit 1 fi
test_that("Integer check fails when character or factor is added", { expect_error(phyloseq2ML:::is.wholenumber(c("blabla"))) }) test_that("Integer check returns TRUE for decimals without rest", { expect_true(phyloseq2ML:::is.wholenumber(c(7.0))) }) test_that("Integer check works for vectors", { expect_true(phyloseq2ML:::is.wholenumber(c(7, 7.0, 9, 500, 0, -1))) }) test_that("Integer check returns FALSE if one value is not wholenumber", { expect_false(phyloseq2ML:::is.wholenumber(c(7, 7.0, 3.1))) }) test_that("Integer check returns TRUE for decimals without rest", { expect_true(phyloseq2ML:::is.wholenumber(c(7, 7.0))) }) test_that("Integer check returns TRUE for number", { expect_false(phyloseq2ML:::is.wholenumber(c(7.1))) }) ## is.dummy test_that("Dummy check works for vectors", { expect_true(phyloseq2ML:::is.dummy(c(1, 0, 0, 1))) expect_true(phyloseq2ML:::is.dummy(c(0, 0))) expect_true(phyloseq2ML:::is.dummy(c(1, 1))) }) test_that("Dummy check returns FALSE for numerical vectors unlike 0 or 1", { expect_false(phyloseq2ML:::is.dummy(c(7, 7.0, 9, 500, 0, -1))) }) test_that("Dummy check returns FALSE for decimal with rest", { expect_false(phyloseq2ML:::is.dummy(c(1, 0, 1.1))) expect_true(phyloseq2ML:::is.dummy(c(1, 0, 1.0))) }) test_that("Dummy check returns FALSE for negative value", { expect_false(phyloseq2ML:::is.dummy(c(-1))) }) test_that("Dummy check returns FALSE for text or factor", { expect_false(phyloseq2ML:::is.dummy(c("word", "word2"))) expect_false(phyloseq2ML:::is.dummy(as.factor(c("word", "word2")))) })
/** * LiveData に関する拡張関数群 */ package com.github.fhenm.himataway.extensions import android.arch.lifecycle.LiveData /** null でない値を取得する。null の場合例外。 */ fun <T> LiveData<T>.get() : T = this.value!!
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using PackIT.Application.Commands; using PackIT.Application.DTO; using PackIT.Application.Queries; using PackIT.Shared.Abstractions.Commands; using PackIT.Shared.Abstractions.Queries; namespace PackIT.Api.Controllers { public class PackingListsController : BaseController { private readonly ICommandDispatcher _commandDispatcher; private readonly IQueryDispatcher _queryDispatcher; public PackingListsController(ICommandDispatcher commandDispatcher, IQueryDispatcher queryDispatcher) { _commandDispatcher = commandDispatcher; _queryDispatcher = queryDispatcher; } [HttpGet("{id:guid}")] public async Task<ActionResult<PackingListDto>> Get([FromRoute] GetPackingList query) { var result = await _queryDispatcher.QueryAsync(query); return OkOrNotFound(result); } [HttpGet] public async Task<ActionResult<IEnumerable<PackingListDto>>> Get([FromQuery] SearchPackingLists query) { var result = await _queryDispatcher.QueryAsync(query); return OkOrNotFound(result); } [HttpPost] public async Task<IActionResult> Post([FromBody] CreatePackingListWithItems command) { await _commandDispatcher.DispatchAsync(command); return CreatedAtAction(nameof(Get), new {id = command.Id}, null); } [HttpPut("{packingListId}/items")] public async Task<IActionResult> Put([FromBody] AddPackingItem command) { await _commandDispatcher.DispatchAsync(command); return Ok(); } [HttpPut("{packingListId:guid}/items/{name}/pack")] public async Task<IActionResult> Put([FromBody] PackItem command) { await _commandDispatcher.DispatchAsync(command); return Ok(); } [HttpDelete("{packingListId:guid}/items/{name}")] public async Task<IActionResult> Delete([FromBody] RemovePackingItem command) { await _commandDispatcher.DispatchAsync(command); return Ok(); } [HttpDelete("{id:guid}")] public async Task<IActionResult> Delete([FromBody] RemovePackingList command) { await _commandDispatcher.DispatchAsync(command); return Ok(); } } }
TICA TAC TOE V2 =============== Tic Tac Toe game designed for three players with a minimum playfield of 3x3 to a maximum playfield of 10x10. Design decisions ---------------- - I took the decision to create a Maven Java project. - I created a "Player" Business Object (bo) to define the properties that the player contains. - I defined a Business Services (bs) layer to define all the logic of the game. ``` 1. There are "Services" that implement the rules of the game and the decisions that CPU should consider. 2. These services have "Helper" objects to provide idiomatic and clean code. 3. Unfortunately for me, I did not have time to finish the CPU logic. ``` - I defined a resource file to retrieve the configuration for the game. ``` 1. This file has the format key-value, so the application expects something like this: e.g. playfield=5 2. The App expects that the file does not contain blank spaces between the "=" symbol. ``` - I defined a CLI layer which is in charge to display the board status to the console. - The CPUService tries to simulate the status for the CPU movements to provide what is the best movement to do. - This App uses JUnit to do tests over the code. Building and Runing Tests ------------------------- - Apache Maven is required - Go to the root of this project - Clean, Compile and Run Tests with the following command ```java mvn install ``` How to run it ------------- - Go to the root of this project. - Compile the project with the following command ``` mvn compile ``` - Then to start the app, run the following command ``` mvn exec:java -Dexec.mainClass="com.metronom.tictactoe.Application" ```
# Sample go server that uses the Grafeas go client library To run this server against the Grafeas reference implementation run the following: ``` go get github.com/Grafeas/Greafeas/samples/server/go-server/api/ go get github.com/Grafeas/client-go go run grafeas/samples/server/go-server/api/server/main/main.go go run client-go/example/v1alpha1/main.go
package com.platform.service; import com.platform.dao.ApiKeywordsMapper; import com.platform.entity.KeywordsVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class ApiKeywordsService { @Autowired private ApiKeywordsMapper keywordsDao; public KeywordsVo queryObject(Integer id) { return keywordsDao.queryObject(id); } public List<KeywordsVo> queryList(Map<String, Object> map) { return keywordsDao.queryList(map); } public int queryTotal(Map<String, Object> map) { return keywordsDao.queryTotal(map); } public void save(KeywordsVo goods) { keywordsDao.save(goods); } public void update(KeywordsVo goods) { keywordsDao.update(goods); } public void delete(Integer id) { keywordsDao.delete(id); } public void deleteBatch(Integer[] ids) { keywordsDao.deleteBatch(ids); } public List<Map> hotKeywordList(Map<String, Object> map) { return keywordsDao.hotKeywordList(map); } }
package analysis /** * Panther is a scalable, powerful, cloud-native SIEM written in Golang/React. * Copyright (C) 2020 Panther Labs Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ // PolicyEngineInput is the request format for invoking the panther-policy-engine Lambda function. type PolicyEngineInput struct { Policies []Policy `json:"policies"` Resources []Resource `json:"resources"` } // Policy is a subset of the policy fields needed for analysis, returns True if compliant. type Policy struct { Body string `json:"body"` ID string `json:"id"` ResourceTypes []string `json:"resourceTypes"` } // Resource is a subset of the resource fields needed for analysis. type Resource struct { Attributes interface{} `json:"attributes"` ID string `json:"id"` Type string `json:"type"` } // PolicyEngineOutput is the response format returned by the panther-policy-engine Lambda function. type PolicyEngineOutput struct { Resources []Result `json:"resources"` } // Result is the analysis result for a single resource. type Result struct { ID string `json:"id"` // resourceID Errored []PolicyError `json:"errored"` Failed []string `json:"failed"` // set of non-compliant policy IDs Passed []string `json:"passed"` // set of compliant policy IDs } // PolicyError indicates an error when evaluating a policy. type PolicyError struct { ID string `json:"id"` // policy ID which caused runtime error Message string `json:"message"` // error message } // ##### Log Analysis ##### // RulesEngineInput is the request format when doing event-driven log analysis. type RulesEngineInput struct { Rules []Rule `json:"rules"` Events []Event `json:"events"` } // Rule evaluates streaming logs, returning True if an alert should be triggered. type Rule struct { Body string `json:"body"` ID string `json:"id"` LogTypes []string `json:"logTypes"` } // Event is a security log to be analyzed, e.g. a CloudTrail event. type Event struct { Data interface{} `json:"data"` ID string `json:"id"` Type string `json:"type"` } // RulesEngineOutput is the response returned when invoking in log analysis mode. type RulesEngineOutput struct { Events []EventAnalysis `json:"events"` } // EventAnalysis is the python evaluation for a single event in the input. type EventAnalysis struct { ID string `json:"id"` Errored []PolicyError `json:"errored"` Matched []string `json:"matched"` // set of rule IDs which returned True NotMatched []string `json:"notMatched"` // set of rule IDs which returned False }
export * from '@drizzle-http/core' export * from '@drizzle-http/undici' export * from '@drizzle-http/logging-interceptor' export * from '@drizzle-http/rxjs-adapter' export * from '@drizzle-http/response-mapper-adapter' export * from '@drizzle-http/opossum-circuit-breaker'
require 'net/http' require 'json' module Oculus module Helpers class GraphiteHelper def initialize(hostname) @host=hostname end def get_graphite_json(namespace,time_from,time_to) begin params = URI.escape("target=#{namespace}&from=#{time_from}&until=#{time_to}") uri = URI.parse("#{@host}/render/?#{params}&rawData=1&format=json") http = Net::HTTP.new(uri.host, uri.port) http.read_timeout = 180 JSON.parse(http.request(Net::HTTP::Get.new(uri.request_uri)).body) rescue SocketError => msg puts "SocketError: #{msg}" exit 3 end end def get_graphite_namespace_tree(namespace) begin params = URI.escape("query=#{namespace}") uri = URI.parse("#{@host}/metrics/find/?#{params}&format=treejson") http = Net::HTTP.new(uri.host, uri.port) http.read_timeout = 180 JSON.parse(http.request(Net::HTTP::Get.new(uri.request_uri)).body) rescue SocketError => msg puts "SocketError: #{msg}" exit 3 end end end end end
import EventEmitter from 'events'; require('whatwg-fetch'); const SERVER_ERROR_STRING = 'Server unavailable'; function apiError (status, message) { var err = new Error(message); err.status = status; return err; } function onAPIResponse (res) { if (res.status >= 500) { return Promise.reject(apiError(res.status, SERVER_ERROR_STRING)); } return res.json().then((json) => { if (res.status >= 400) { return Promise.reject(apiError(res.status, json.message)); } return json; }); } export const client = ({ apiUrl }) => { const em = new EventEmitter(); function request (method, url) { em.emit('request', { method, url }); return window.fetch(url) .then(onAPIResponse); } const methods = { codenames: { fetch ({ lists, filters }) { return request('get', `${apiUrl}/codenames?lists=${lists.join(',')}&filters=${filters.join(',')}`); } } }; return Object.assign(em, methods); }; export default client;
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Console\BoilerplateInputParser; use App\Console\BoilerplateGenerator; use Illuminate\Filesystem\Filesystem; class BoilerplateGenerate extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'boilerplate:generate {name} {--properties=} {--base=App}'; /** * The console command description. * * @var string */ protected $description = 'Boilerplate command'; protected $parser; protected $generator; protected $file; /** * Create a new command instance. * * @return void */ public function __construct(BoilerplateInputParser $parser, BoilerplateGenerator $generator, Filesystem $file) { parent::__construct(); $this->parser = $parser; $this->generator = $generator; $this->file = $file; } /** * Execute the console command. * * @return mixed */ public function handle() { // Parse input from Artisan into usable form $input = $this->parser->parse( $this->argument('name'), $this->option('base'), $this->option('properties') ); if($this->file->isDirectory($input->base)) { $this->file->makeDirectory($input->base.'/Repo'); $this->file->makeDirectory($input->base.'/Entities'); } // Create a file with the correct boilerplate $this->generator->make( $input, app_path('Console/Commands/templates/eloquent.template'), $this->getClassPath($input,'Eloquent') ); $this->generator->make( $input, app_path('Console/Commands/templates/interface.template'), $this->getClassPath($input,'Interface') ); $this->generator->make( $input, app_path('Console/Commands/templates/model.template'), $input->base.'/Entities/'.$input->class.'.php' ); $this->info("All done!"); } private function getClassPath($input,$type) { return sprintf("%s/%s%s.php", $input->base.'/Repo', $input->class, $type); } }
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module River.Core.Primitive ( Prim(..) ) where import Control.DeepSeq (NFData) import Data.Data (Data) import Data.Set (Set) import qualified Data.Set as Set import Data.Typeable (Typeable) import GHC.Generics (Generic) import River.Effect data Prim = Neg | Not | Add | Sub | Mul | Div | Mod | Eq | Ne | Lt | Le | Gt | Ge | And | Xor | Or | Shl | Shr deriving (Eq, Ord, Read, Show, Data, Typeable, Generic, NFData) instance HasEffect Prim where hasEffect p = Set.member p effectfulPrims effectfulPrims :: Set Prim effectfulPrims = Set.fromList [Mul, Div, Mod]
package com.example.android.guesstheword import com.example.android.guesstheword.screens.game.GameViewModel const val GameViewModelTag: String = "GameViewModel"
package com.theslipper.chargebackspecialist.chargebackspecialist.controllers; import com.theslipper.chargebackspecialist.chargebackspecialist.models.SystemUserRole; import com.theslipper.chargebackspecialist.chargebackspecialist.services.HelpEntryService; import com.theslipper.chargebackspecialist.chargebackspecialist.services.SystemUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Handles the incoming traffic for the home subsection of the website. */ @Controller public class HomeViewController { private final String homeViewSectionLayoutName = "standard_layout"; private final String[] homeSectionTitles = {"Home", "Updates", "Help"}; private final String[] homeSectionLinks = {"/home/home", "/home/updates", "/home/help"}; private final HelpEntryService helpEntryService; @Autowired public HomeViewController(HelpEntryService helpEntryService) { this.helpEntryService = helpEntryService; } @RequestMapping(value = {"/", "/home", "/home/home", "/home/Home"}) public String homeHome(Model model) { model.addAttribute("metadata", new WebsiteMetadata("Home", "Home", homeSectionTitles, homeSectionLinks)); return homeViewSectionLayoutName; } @RequestMapping(value = {"/home/updates", "/home/Updates"}) public String homeUpdates(Model model) { model.addAttribute("metadata", new WebsiteMetadata("Home", "Updates", homeSectionTitles, homeSectionLinks)); return homeViewSectionLayoutName; } @RequestMapping(value = {"/home/help", "/home/Help"}) public String homeHelp(Model model) { model.addAttribute("metadata", new WebsiteMetadata("Home", "Help", homeSectionTitles, homeSectionLinks)); model.addAttribute("helpEntries", helpEntryService.getAllHelpEntries()); return homeViewSectionLayoutName; } }
<?php $I = new AcceptanceTester($scenario); $I->wantTo('Contacts'); $I->amOnPage('/contacts'); $I->see('Тел. (044) 221-65-78'); $I->see('Email: [email protected]');
--- title: "Differential Equation: Test 2-4" categories: - Differential Equation tags: - Differential Equation toc: true toc_sticky: true --- # 질문 ## 내용 $$(e^{y}-ye^{x})dx + (xe^{y}-e^{x})dy = 0$$이 완전미분방정식임을 보이고 해를 구하시오. # 답변 ## 내용 ![Answer](/assets/images/differential_equation/test_2/test_4.png)
# frozen_string_literal: true require 'spec_helper' RSpec.describe GitlabSchema.types['NugetMetadata'] do it 'includes nuget metadatum fields' do expected_fields = %w[ id license_url project_url icon_url ] expect(described_class).to include_graphql_fields(*expected_fields) end %w[projectUrl licenseUrl iconUrl].each do |optional_field| it "#{optional_field} can be null" do expect(described_class.fields[optional_field].type).to be_nullable end end end
#!perl -w # vim: ft=perl use strict; use Test::More; use DBI; use lib 't', '.'; require 'lib.pl'; use vars qw($table $test_dsn $test_user $test_passwd); $|= 1; my $dbh; eval {$dbh= DBI->connect($test_dsn, $test_user, $test_passwd, { RaiseError => 1, PrintError => 1, AutoCommit => 0 });}; if ($@) { plan skip_all => "ERROR: $@. Can't continue test"; } plan tests => 21; ok(defined $dbh, "connecting"); ok($dbh->do(qq{DROP TABLE IF EXISTS t1}), "making slate clean"); # # Bug #20559: Program crashes when using server-side prepare # ok($dbh->do(qq{CREATE TABLE t1 (id INT, num DOUBLE)}), "creating table"); my $sth; ok($sth= $dbh->prepare(qq{INSERT INTO t1 VALUES (?,?),(?,?)}), "loading data"); ok($sth->execute(1, 3.0, 2, -4.5)); #ok ($sth= $dbh->prepare("SELECT num FROM t1 WHERE id = ? FOR UPDATE")); ok ($sth= $dbh->prepare("SELECT num FROM t1 WHERE id = ?")); ok ($sth->bind_param(1, 1), "binding parameter"); ok ($sth->execute(), "fetching data"); is_deeply($sth->fetchall_arrayref({}), [ { 'num' => '3' } ]); ok ($sth->finish); ok ($dbh->do(qq{DROP TABLE t1}), "cleaning up"); # # Bug #42723: Binding server side integer parameters results in corrupt data # ok($dbh->do(qq{DROP TABLE IF EXISTS t2}), "making slate clean"); ok($dbh->do(q{CREATE TABLE `t2` (`i` int,`si` smallint,`ti` tinyint,`bi` bigint)}), "creating test table"); my $sth2; ok($sth2 = $dbh->prepare('INSERT INTO t2 VALUES (?,?,?,?)')); #bind test values ok($sth2->bind_param(1, 101), "binding the first param"); ok($sth2->bind_param(2, 102), "binding the second param"); ok($sth2->bind_param(3, 103), "binding the third param"); ok($sth2->bind_param(4, 104), "binding the fourth param"); ok($sth2->execute(), "inserting data"); is_deeply($dbh->selectall_arrayref('SELECT * FROM t2'), [[101, 102, 103, 104]]); ok ($dbh->do(qq{DROP TABLE t2}), "cleaning up"); $dbh->disconnect();
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System.Collections.Generic; using System.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.Unity; using Microsoft.Practices.EnterpriseLibrary.Logging.Filters; using Microsoft.Practices.ObjectBuilder2; namespace Microsoft.Practices.EnterpriseLibrary.Logging.Configuration { [Assembler(typeof(CategoryFilterAssembler))] [ContainerPolicyCreator(typeof(CategoryFilterPolicyCreator))] public class CategoryFilterData : LogFilterData { private const string categoryFilterModeProperty = "categoryFilterMode"; private const string categoryFiltersProperty = "categoryFilters"; public CategoryFilterData() { } public CategoryFilterData(NamedElementCollection<CategoryFilterEntry> categoryFilters, CategoryFilterMode categoryFilterMode) : this("category", categoryFilters, categoryFilterMode) { } public CategoryFilterData(string name, NamedElementCollection<CategoryFilterEntry> categoryFilters, CategoryFilterMode categoryFilterMode) : base(name, typeof(CategoryFilter)) { this.CategoryFilters = categoryFilters; this.CategoryFilterMode = categoryFilterMode; } [ConfigurationProperty(categoryFilterModeProperty)] public CategoryFilterMode CategoryFilterMode { get { return (CategoryFilterMode)this[categoryFilterModeProperty]; } set { this[categoryFilterModeProperty] = value; } } [ConfigurationProperty(categoryFiltersProperty)] public NamedElementCollection<CategoryFilterEntry> CategoryFilters { get { return (NamedElementCollection<CategoryFilterEntry>)base[categoryFiltersProperty]; } private set { base[categoryFiltersProperty] = value; } } } public class CategoryFilterAssembler : IAssembler<ILogFilter, LogFilterData> { public ILogFilter Assemble(IBuilderContext context, LogFilterData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache) { CategoryFilterData castedObjectConfiguration = (CategoryFilterData)objectConfiguration; ICollection<string> categoryFilters = new List<string>(); foreach (CategoryFilterEntry entry in castedObjectConfiguration.CategoryFilters) { categoryFilters.Add(entry.Name); } ILogFilter createdObject = new CategoryFilter( castedObjectConfiguration.Name, categoryFilters, castedObjectConfiguration.CategoryFilterMode); return createdObject; } } }
use jni::JNIEnv; use jni::objects::{JClass, JString}; use jni::sys::jlong; use crate::common::context::Context; #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn Java_org_nativescript_canvas_TNSSVG_nativeDrawSVG( env: JNIEnv, _: JClass, context: jlong, svg: JString, ) { unsafe { let context: *mut Context = context as _; let context = &mut *context; if let Ok(svg) = env.get_string(svg) { let svg = svg.to_string_lossy(); crate::common::svg::draw_svg(context, svg.as_ref()); } } } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn Java_org_nativescript_canvas_TNSSVG_nativeDrawSVGFromPath( env: JNIEnv, _: JClass, context: jlong, path: JString, ) { unsafe { let context: *mut Context = context as _; let context = &mut *context; if let Ok(path) = env.get_string(path) { let path = path.to_string_lossy(); crate::common::svg::draw_svg_from_path(context, path.as_ref()); } } }
/* SecurityPermission.java -- Class for named security permissions Copyright (C) 1998, 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.security; /** * This class provides a mechanism for specified named permissions * related to the Java security framework. These permissions have no * associated actions list. They are either granted or not granted. * * <p>The list of valid permission names is:<br> * <table border=1> * <tr><th>Permission Name</th><th>Permission Allows</th><th>Risks</th</tr> * <tr> * <td><code>createAccessControlContext</code></td> * <td>Allows creation of an AccessControlContext</td> * <td>The new control context can have a rogue DomainCombiner, leading * to a privacy leak</td></tr> * <tr> * <td><code>getDomainCombiner</code></td> * <td>Get a DomainCombiner from an AccessControlContext</td> * <td>Access to a DomainCombiner can lead to a privacy leak</td></tr> * <tr> * <td><code>getPolicy</code></td> * <td>Allows retrieval of the system security policy</td> * <td>Malicious code can use information from the policy to better plan * an attack</td></tr> * <tr> * <td><code>setPolicy</code></td> * <td>Allows the security policy to be changed</td> * <td>Malicious code can give itself any permission it wants</td></tr> * <tr> * <td><code>getProperty.</code><em>key</em></td> * <td>Retrieve the property specified by the key</td> * <td>Malicious code can use information from the property to better plan * an attack</td></tr> * <tr> * <td><code>setProperty.</code><em>key</em></td> * <td>Allows changing of the value of all properties implied by key</td> * <td>Malicious code can insert rogue classes to steal keys or recreate * the security policy with whatever permissions it desires</td></tr> * <tr> * <td><code>insertProvider.</code><em>key</em></td> * <td>Allows the named provider to be added</td> * <td>Malicious code can insert rogue providers that steal data</td></tr> * <tr> * <td><code>removeProvider.</code><em>key</em></td> * <td>Allows the named provider to be removed</td> * <td>A missing provider can cripple code that relies on it</td></tr> * <tr> * <td><code>setSystemScope</code></td> * <td>Allows the system identity scope to be set</td> * <td>Malicious code can add certificates not available in the original * identity scope, to gain more permissions</td></tr> * <tr> * <td><code>setIdentityPublicKey</code></td> * <td>Allows the public key of an Identity to be set</td> * <td>Malicious code can install its own key to gain permissions not * allowed by the original identity scope</td></tr> * <tr> * <td><code>SetIdentityInfo</code></td> * <td>Allows the description of an Identity to be set</td> * <td>Malicious code can spoof users into trusting a fake identity</td></tr> * <tr> * <td><code>addIdentityCertificate</code></td> * <td>Allows a certificate to be set for the public key of an identity</td> * <td>The public key can become trusted to a wider audience than originally * intended</td></tr> * <tr> * <td><code>removeIdentityCertificate</code></td> * <td>Allows removal of a certificate from an identity's public key</td> * <td>The public key can become less trusted than it should be</td></tr> * <tr> * <td><code>printIdentity</code></td> * <td>View the name of the identity and scope, and whether they are * trusted</td> * <td>The scope may include a filename, which provides an entry point for * further security breaches</td></tr> * <tr> * <td><code>clearProviderProperties.</code><em>key</em></td> * <td>Allows the properties of the named provider to be cleared</td> * <td>This can disable parts of the program which depend on finding the * provider</td></tr> * <tr> * <td><code>putProviderProperty.</code><em>key</em></td> * <td>Allows the properties of the named provider to be changed</td> * <td>Malicious code can replace the implementation of a provider</td></tr> * <tr> * <td><code>removeProviderProperty.</code><em>key</em></td> * <td>Allows the properties of the named provider to be deleted</td> * <td>This can disable parts of the program which depend on finding the * provider</td></tr> * <tr> * <td><code>getSignerPrivateKey</code></td> * <td>Allows the retrieval of the private key for a signer</td> * <td>Anyone that can access the private key can claim to be the * Signer</td></tr> * <tr> * <td><code>setSignerKeyPair</code></td> * <td>Allows the public and private key of a Signer to be changed</td> * <td>The replacement might be a weaker encryption, or the attacker * can use knowledge of the replaced key to decrypt an entire * communication session</td></tr> * </table> * * <p>There is some degree of security risk in granting any of these * permissions. Some of them can completely compromise system security. * Please exercise extreme caution in granting these permissions. * * @author Aaron M. Renn ([email protected]) * @see Permission * @see SecurityManager * @since 1.1 * @status updated to 1.4 */ public final class SecurityPermission extends BasicPermission { /** * Compatible with JDK 1.1+. */ private static final long serialVersionUID = 5236109936224050470L; /** * Create a new instance with the specified name. * * @param name the name to assign to this permission */ public SecurityPermission(String name) { super(name); } /** * Create a new instance with the specified name. As SecurityPermission * carries no actions, the second parameter is ignored. * * @param name the name to assign to this permission * @param actions ignored */ public SecurityPermission(String name, String actions) { super(name); } } // class SecurityPermission
MODULES.moduleClasses["casterlabs_donation"] = class { constructor(id) { this.namespace = "casterlabs_donation"; this.displayname = "caffeinated.donation_alert.title"; this.type = "overlay settings"; this.id = id; this.supportedPlatforms = ["TWITCH", "CAFFEINE", "TROVO"]; } widgetDisplay = [ { name: "Test", icon: "dice", onclick(instance) { koi.test("donation"); } }, { name: "Copy", icon: "copy", onclick(instance) { putInClipboard("https://caffeinated.casterlabs.co/donation.html?id=" + instance.id); } } ] getDataToStore() { FileStore.setFile(this, "audio_file", this.audio_file); FileStore.setFile(this, "image_file", this.image_file); return nullFields(this.settings, ["audio_file", "image_file"]); } onConnection(socket) { MODULES.emitIO(this, "config", this.settings, socket); MODULES.emitIO(this, "audio_file", this.audio_file, socket); MODULES.emitIO(this, "image_file", this.image_file, socket); } init() { koi.addEventListener("donation", (event) => { for (const donation of event.donations) { const converted = Object.assign({ image: donation.image, animated_image: donation.animated_image }, event); MODULES.emitIO(this, "event", converted); // Only alert once for Caffeine props if (event.sender.platform == "CAFFEINE") { return; } } }); if (this.settings.audio_file) { this.audio_file = this.settings.audio_file; delete this.settings.audio_file; MODULES.saveToStore(this); } else { this.audio_file = FileStore.getFile(this, "audio_file", this.audio_file); } if (this.settings.image_file) { this.image_file = this.settings.image_file; delete this.settings.image_file; MODULES.saveToStore(this); } else { this.image_file = FileStore.getFile(this, "image_file", this.image_file); } } async onSettingsUpdate() { MODULES.emitIO(this, "config", nullFields(this.settings, ["audio_file", "image_file"])); if (this.settings.audio_file.files.length > 0) { this.audio_file = await fileToBase64(this.settings.audio_file, "audio"); MODULES.emitIO(this, "audio_file", this.audio_file); } if (this.settings.image_file.files.length > 0) { this.image_file = await fileToBase64(this.settings.image_file); MODULES.emitIO(this, "image_file", this.image_file); } } settingsDisplay = { font: { display: "generic.font", type: "font", isLang: true }, font_size: { display: "generic.font.size", type: "number", isLang: true }, text_color: { display: "generic.text.color", type: "color", isLang: true }, volume: { display: "generic.volume", type: "range", isLang: true }, text_to_speech_voice: { display: "caffeinated.donation_alert.text_to_speech_voice", type: "select", isLang: true }, audio: { display: "generic.alert.audio", type: "select", isLang: true }, image: { display: "generic.alert.image", type: "select", isLang: true }, audio_file: { display: "generic.audio.file", type: "file", isLang: true }, image_file: { display: "generic.image.file", type: "file", isLang: true } }; defaultSettings = { font: "Poppins", font_size: "16", text_color: "#FFFFFF", volume: 1, text_to_speech_voice: ["Brian", "Russell", "Nicole", "Amy", "Salli", "Joanna", "Matthew", "Ivy", "Joey"], audio: ["Custom Audio", "Text To Speech", "Custom Audio & Text To Speech", "None"], image: ["Custom Image", "Animated Donation Image", "Donation Image", "None"], audio_file: "", image_file: "" }; };
#!/bin/sh pacman -Qen > "sync_packages" pacman -Qem > "aur_packages"
/* Copyright 2014 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef BASE_LOG_SEVERITY_H_ #define BASE_LOG_SEVERITY_H_ #include "base/port.h" #include "base/commandlineflags_declare.h" // Variables of type LogSeverity are widely taken to lie in the range // [0, NUM_SEVERITIES-1]. Be careful to preserve this assumption if // you ever need to change their values or add a new severity. typedef int LogSeverity; namespace base_logging { // Severity-level definitions. These are C++ constants representing // the four severity levels INFO through FATAL. // // These severity constants can be used outside of a LOG statement, or // in a variable-severity statement such as: // // LOG(LEVEL(is_error ? base_logging::ERROR : base_logging::WARNING)) << ...; // // Another common use of these symbols is: // // using base_logging::INFO; // testing::ScopedMockLog log; // EXPECT_CALL(log, Log(INFO, testing::_, "...")); const LogSeverity INFO = 0; const LogSeverity WARNING = 1; const LogSeverity ERROR = 2; const LogSeverity FATAL = 3; const int NUM_SEVERITIES = 4; } // namespace base_logging // TODO(jmacd): Replace uses of ::INFO, ::WARNING, ::ERROR, and // ::FATAL with the base_logging members. (A benefit of this change // is that it avoids namespace collisions with ~1000 existing enums // named "INFO", "WARNING", "ERROR", and "FATAL" in google3 .proto // files alone.) const int INFO = base_logging::INFO; const int WARNING = base_logging::WARNING; const int ERROR = base_logging::ERROR; const int FATAL = base_logging::FATAL; const int NUM_SEVERITIES = base_logging::NUM_SEVERITIES; // An array containing "INFO", "WARNING", "ERROR", "FATAL". extern const char* const LogSeverityNames[NUM_SEVERITIES]; // Some flags needed for VLOG and RAW_VLOG DECLARE_int32(v); DECLARE_bool(silent_init); // NDEBUG usage helpers related to (RAW_)DCHECK: // // DEBUG_MODE is for small !NDEBUG uses like // if (DEBUG_MODE) foo.CheckThatFoo(); // instead of substantially more verbose // #ifndef NDEBUG // foo.CheckThatFoo(); // #endif // #ifdef NDEBUG const bool DEBUG_MODE = false; #else const bool DEBUG_MODE = true; #endif namespace base_logging { // Use base_logging::DFATAL to refer to the LogSeverity level // "DFATAL" outside of a log statement. const LogSeverity DFATAL = DEBUG_MODE ? FATAL : ERROR; // If "s" is less than base_logging::INFO, returns base_logging::INFO. // If "s" is greater than base_logging::FATAL, returns // base_logging::ERROR. Otherwise, returns "s". LogSeverity NormalizeSeverity(LogSeverity s); } // namespace base_logging namespace base { namespace internal { // TODO(jmacd): Remove this (one use in webserver/...) inline LogSeverity NormalizeSeverity(LogSeverity s) { return base_logging::NormalizeSeverity(s); } } // namespace internal } // namespace base // Special-purpose macros for use OUTSIDE //base/logging.h. These are // to support hygienic forms of other logging macros (e.g., // raw_logging.h). #define BASE_LOG_SEVERITY_INFO (::base_logging::INFO) #define BASE_LOG_SEVERITY_WARNING (::base_logging::WARNING) #define BASE_LOG_SEVERITY_ERROR (::base_logging::ERROR) #define BASE_LOG_SEVERITY_FATAL (::base_logging::FATAL) #define BASE_LOG_SEVERITY_DFATAL (::base_logging::DFATAL) #define BASE_LOG_SEVERITY_QFATAL (::base_logging::QFATAL) #define BASE_LOG_SEVERITY_LEVEL(severity) \ (::base_logging::NormalizeSeverity(severity)) // TODO(jmacd): Remove this once DFATAL_LEVEL is eliminated. #define BASE_LOG_SEVERITY_DFATAL_LEVEL (::base_logging::DFATAL) #endif // BASE_LOG_SEVERITY_H_
# frozen_string_literal: true require 'json' module RubyCandy class Client module FirmwareConfigAPI API_METHODS = %i[ auto_status dithering= interpolation= status= ].freeze VAR_NAME = '@firmware_config' def reset_firmware_config(send: true) instance_variable_set(VAR_NAME, FirmwareConfig.new) send_firmware_config if send end def send_firmware_config if defined?(:socket_send) socket_send(firmware_config_packet) else puts firmware_config_packet.inspect end end API_METHODS.each do |delegated_method| define_method(delegated_method) do |*args| instance_variable_get(VAR_NAME).public_send(delegated_method, *args) send_firmware_config end end private def firmware_config_byte instance_variable_get(VAR_NAME).config_byte end def firmware_config_packet [ 0x00, # Channel (reserved) 0xFF, # Command (System Exclusive) 0x00, # Length high byte 0x05, # Length low byte 0x00, # System ID high byte 0x01, # System ID low byte 0x00, # Command ID high byte 0x02, # Command ID low byte firmware_config_byte ].pack('C*') end class FirmwareConfig DEFAULT_FIRMWARE_CONFIG = 0x00 DISABLE_DITHERING_BIT = 0x01 DISABLE_INTERPOLATION_BIT = 0x02 MANUAL_STATUS_BIT = 0x04 STATUS_LED_BIT = 0x08 attr_reader :config_byte def initialize(config_byte: DEFAULT_FIRMWARE_CONFIG) @config_byte = config_byte end def set_firmware_bits(bitmask) @config_byte |= bitmask end def unset_firmware_bits(bitmask) @config_byte &= ~bitmask end def dithering=(val) case val when nil || 0 || false then disable_dithering else enable_dithering end end def disable_dithering set_firmware_bits(DISABLE_DITHERING_BIT) end def enable_dithering unset_firmware_bits(DISABLE_DITHERING_BIT) end def interpolation=(val) case val when nil || 0 || false then disable_interpolation else enable_interpolation end end def disable_interpolation set_firmware_bits(DISABLE_INTERPOLATION_BIT) end def enable_interpolation unset_firmware_bits(DISABLE_INTERPOLATION_BIT) end def status=(val) case val when nil then auto_status when 0 || false then status_off else status_on end end def auto_status unset_firmware_bits(MANUAL_STATUS_BIT | STATUS_LED_BIT) end def status_on set_firmware_bits(MANUAL_STATUS_BIT | STATUS_LED_BIT) end def status_off set_firmware_bits(MANUAL_STATUS_BIT) unset_firmware_bits(STATUS_LED_BIT) end end end end end
// getopt_book.c // Chapter 20 // Learn C Programming, 2nd Edition // // Demonstrate how to // * retrieve arguments entered on the command line with the C Standard // Library routine getopts(). // // compile with: // cc getopt_book.c -o getopt_book -Wall -Werror -std=c17 // // sample inputs; // // ./getopt_book -t "There and Back" -a "Bilbo Baggins" -p -y 1955 -r // ./getopt_book -a "Jeff Szuhay" -t "Learn C Programming" -y 2020 -p // ./getopt_book -x #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> static char* options_string = "pra:t:y:"; typedef struct _book { bool bPublished; bool bReprint; char* title; char* author; char* year; } Book; void Usage( char* exec ) { printf( "\nUsage: %s -r -p -t 'title' -a 'name' -y year\n\n" , exec ); exit(1); } void PrintArgs( int argc , char** argv ) { printf( "argument count = [%d]\n" , argc ); printf( "%s " , argv[0] ); for( int i = 1 ; i < argc ; i++ ) { printf( "%s " , argv[i] ); } putchar( '\n' ); putchar( '\n' ); } int main(int argc, char *argv[]) { char ch; Book book = { false , false , 0 , 0, 0 }; PrintArgs( argc , argv ); while( (ch = getopt( argc , argv , options_string ) ) != -1 ) { switch (ch) { case 'p': book.bPublished = true; break; case 'r': book.bReprint = true; break; case 't': book.title = optarg; break; case 'a': book.author = optarg; break; case 'y': book.year = optarg; break; default: Usage( argv[0] ); break; } } printf( " Title is [%s]\n" , book.title ); printf( "Author is [%s]\n" , book.author ); printf( "Published [%s]\n" , book.bPublished ? "yes" : "no" ); if( book.year ) printf( " Year is [%s]\n" , book.year ); printf( "Reprinted [%s]\n" , book.bReprint? "yes" : "no" ); if( optind < argc ) { printf( "non-option ARGV-elements: " ); while( optind < argc ) { printf( "%s ", argv[ optind++ ] ); } putchar( '\n' ); } putchar( '\n' ); return 0; } /* eof */
import { StorageService } from './providers/storage.service'; import { CartService } from './providers/cart.service'; import { ProductsService } from './providers/products.service'; import { MenuService } from './providers/menu.service'; import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; // modulos import { RoutingModule } from './app.routes'; import { AppComponent } from './app.component'; import { HeaderComponent } from './components/header/header.component'; import { MenuComponent } from './components/menu/menu.component'; import { LogoComponent } from './components/logo/logo.component'; import { SearchbarComponent } from './components/searchbar/searchbar.component'; import { CartbarComponent } from './components/cartbar/cartbar.component'; import { BannerComponent } from './components/banner/banner.component'; import { ProductListComponent } from './components/product-list/product-list.component'; import { ProductCardComponent } from './components/product-card/product-card.component'; import { FooterComponent } from './components/footer/footer.component'; import { HomePageComponent } from './pages/home-page/home-page.component'; import { ProductsPageComponent } from './pages/products-page/products-page.component'; import { ProductPageComponent } from './pages/product-page/product-page.component'; import { Error404PageComponent } from './pages/error-404-page/error-404-page.component' @NgModule({ declarations: [ AppComponent, HeaderComponent, MenuComponent, LogoComponent, SearchbarComponent, CartbarComponent, BannerComponent, ProductListComponent, ProductCardComponent, FooterComponent, HomePageComponent, ProductsPageComponent, ProductPageComponent, Error404PageComponent ], imports: [ RoutingModule, BrowserModule, FormsModule ], providers: [ MenuService, ProductsService, CartService, StorageService ], bootstrap: [AppComponent] }) export class AppModule { }
/* global createCanvas, mouseIsPressed, fill, mouseX, mouseY, ellipse, windowHeight, windowWidth, cos, sin, random, vec, rndInCirc */ let state; function makeBristles(bnum, blen, rad){ const bristles = []; for (let i=0; i < bnum; i++){ const r = sqrt(random()); const a = random(-PI, PI); bristles.push({ xy: vec(cos(a)*r*rad, sin(a)*r*rad), l: blen * (1.0 - r)}); } return bristles; } function makeBrush(bnum, blen, rad){ return { blen, bnum, rad, bristles: makeBristles(bnum, blen, rad) }; } function setup(){ //win = vec(windowHeight, windowWidth); win = vec(1000, 1000); angleMode(RADIANS); createCanvas(win.x, win.y); //strokeWeight(2); fill('rgba(0,0,0,0.03)'); noStroke(); state = { mouse: [], speed: 0, brush: makeBrush(200, 50.0, 20.0), win, }; console.log(state); } //function mouseClicked(){ //} function getDot(xy, df, h, blen){ return xy.copy().add(df.copy().mult(sqrt(pow(blen, 2.0) - pow(h, 2.0)))); } function midPos(a){ const l = a.length; const v = vec(0, 0); let s = 0; for (let i=0; i < l-1; i++){ v.add(a[i].copy().mult(i)); s += i; } return v.div(s); } function mouseDiff(){ const i = state.mouse.length; if (i > 1){ const mp = midPos(state.mouse); //const df = state.mouse[i-2].copy().sub(state.mouse[i-1]); const df = mp.copy().sub(state.mouse[i-1]); const l = df.mag(); if (l <= 0.001){ state.speed = 0; return null; } state.speed = l; return df.div(l); } return null; } function drawStroke(a, b, n){ for (let i=0; i < n; i++){ const xy = p5.Vector.lerp(a, b, random()); square(xy.x, xy.y, 1); } } function brushDraw(df, w=0.5){ if (df && w){ const i = state.mouse.length; const xy = state.mouse[i-1]; const blen = state.brush.blen; const h = (1.0 - w)*blen; for (let i=0; i < state.brush.bnum; i++){ const bristle = state.brush.bristles[i]; if (bristle.l > h){ const xya = xy.copy().add(bristle.xy); drawStroke(xya, getDot(xya, df, h, blen), 20); } } } } function draw(){ state.mouse.push(vec(mouseX, mouseY)); if (state.mouse.length>10){ state.mouse = state.mouse.slice(1, 11); } const df = mouseDiff(); const maxSpeed = 100; brushDraw(df, pow(1.0 - min(max(0, state.speed), maxSpeed)/maxSpeed, 2.0)); }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/debug/shared/message_loop_poll.h" #include <fcntl.h> #include <lib/syslog/cpp/macros.h> #include <poll.h> #include <string.h> #include <time.h> #include <unistd.h> #include "src/lib/files/eintr_wrapper.h" #include "src/lib/fxl/build_config.h" namespace debug_ipc { namespace { #if !defined(OS_LINUX) bool SetCloseOnExec(int fd) { const int flags = fcntl(fd, F_GETFD); if (flags == -1) return false; if (flags & FD_CLOEXEC) return true; if (HANDLE_EINTR(fcntl(fd, F_SETFD, flags | FD_CLOEXEC)) == -1) return false; return true; } bool SetNonBlocking(int fd) { const int flags = fcntl(fd, F_GETFL); if (flags == -1) return false; if (flags & O_NONBLOCK) return true; if (HANDLE_EINTR(fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1) return false; return true; } #endif // Creates a nonblocking temporary pipe pipe and assigns the two ends of it to // the two out parameters. Returns true on success. bool CreateLocalNonBlockingPipe(fbl::unique_fd* out_end, fbl::unique_fd* in_end) { #if defined(OS_LINUX) int fds[2]; if (pipe2(fds, O_CLOEXEC | O_NONBLOCK) != 0) return false; out_end->reset(fds[0]); in_end->reset(fds[1]); return true; #else int fds[2]; if (pipe(fds) != 0) return false; fbl::unique_fd fd_out(fds[0]); fbl::unique_fd fd_in(fds[1]); if (!SetCloseOnExec(fd_out.get())) return false; if (!SetCloseOnExec(fd_in.get())) return false; if (!SetNonBlocking(fd_out.get())) return false; if (!SetNonBlocking(fd_in.get())) return false; *out_end = std::move(fd_out); *in_end = std::move(fd_in); return true; #endif } } // namespace struct MessageLoopPoll::WatchInfo { int fd = 0; WatchMode mode = WatchMode::kReadWrite; FDWatcher* watcher = nullptr; }; MessageLoopPoll::MessageLoopPoll() { if (!CreateLocalNonBlockingPipe(&wakeup_pipe_out_, &wakeup_pipe_in_)) fprintf(stderr, "Can't create pipe.\n"); } MessageLoopPoll::~MessageLoopPoll() = default; bool MessageLoopPoll::Init(std::string* error_message) { if (!MessageLoop::Init(error_message)) return false; wakeup_pipe_watch_ = WatchFD(WatchMode::kRead, wakeup_pipe_out_.get(), this); return true; } void MessageLoopPoll::Cleanup() { // Force unregister out watch before cleaning up current MessageLoop. wakeup_pipe_watch_ = WatchHandle(); MessageLoop::Cleanup(); } MessageLoop::WatchHandle MessageLoopPoll::WatchFD(WatchMode mode, int fd, FDWatcher* watcher) { // The dispatch code for watch callbacks requires this be called on the // same thread as the message loop is. FX_DCHECK(Current() == static_cast<MessageLoop*>(this)); WatchInfo info; info.fd = fd; info.mode = mode; info.watcher = watcher; // The reason this function must be called on the message loop thread is that // otherwise adding a new watch would require synchronously breaking out of // the existing poll() call to add the new handle and then resuming it. int watch_id = next_watch_id_; next_watch_id_++; watches_[watch_id] = info; return WatchHandle(this, watch_id); } uint64_t MessageLoopPoll::GetMonotonicNowNS() const { struct timespec ts; int ret = clock_gettime(CLOCK_MONOTONIC, &ts); FX_DCHECK(!ret); return static_cast<uint64_t>(ts.tv_sec) * 1000000000 + ts.tv_nsec; } void MessageLoopPoll::RunImpl() { std::vector<pollfd> poll_vect; std::vector<int> map_indices; while (!should_quit()) { // This could be optimized to avoid recomputing every time. ConstructFDMapping(&poll_vect, &map_indices); FX_DCHECK(!poll_vect.empty()); FX_DCHECK(poll_vect.size() == map_indices.size()); int poll_timeout; uint64_t delay = DelayNS(); if (delay == MessageLoop::kMaxDelay) { poll_timeout = -1; } else { delay += 999999; delay /= 1000000; poll_timeout = static_cast<int>(delay); } int res = poll(&poll_vect[0], static_cast<nfds_t>(poll_vect.size()), poll_timeout); FX_DCHECK(res >= 0 || errno == EINTR) << "poll() failed: " << strerror(errno); for (size_t i = 0; i < poll_vect.size(); i++) { if (poll_vect[i].revents) OnHandleSignaled(poll_vect[i].fd, poll_vect[i].revents, map_indices[i]); } // Process one pending task. If there are more set us to wake up again. // ProcessPendingTask must be called with the lock held. std::lock_guard<std::mutex> guard(mutex_); if (ProcessPendingTask()) SetHasTasks(); } } void MessageLoopPoll::StopWatching(int id) { // The dispatch code for watch callbacks requires this be called on the // same thread as the message loop is. FX_DCHECK(Current() == this); std::lock_guard<std::mutex> guard(mutex_); auto found = watches_.find(id); if (found == watches_.end()) { FX_NOTREACHED(); return; } watches_.erase(found); } void MessageLoopPoll::OnFDReady(int fd, bool readable, bool, bool) { if (!readable) { return; } FX_DCHECK(fd == wakeup_pipe_out_.get()); // Remove and discard the wakeup byte. char buf; auto nread = HANDLE_EINTR(read(wakeup_pipe_out_.get(), &buf, 1)); FX_DCHECK(nread == 1); // This is just here to wake us up and run the loop again. We don't need to // actually respond to the data. } void MessageLoopPoll::SetHasTasks() { // Wake up the poll() by writing to the pipe. char buf = 0; auto written = HANDLE_EINTR(write(wakeup_pipe_in_.get(), &buf, 1)); FX_DCHECK(written == 1 || errno == EAGAIN); } void MessageLoopPoll::ConstructFDMapping(std::vector<pollfd>* poll_vect, std::vector<int>* map_indices) const { // The watches_ vector is not threadsafe. FX_DCHECK(Current() == this); poll_vect->resize(watches_.size()); map_indices->resize(watches_.size()); size_t i = 0; for (const auto& pair : watches_) { pollfd& pfd = (*poll_vect)[i]; pfd.fd = pair.second.fd; pfd.events = 0; if (pair.second.mode == WatchMode::kRead || pair.second.mode == WatchMode::kReadWrite) pfd.events |= POLLIN; if (pair.second.mode == WatchMode::kWrite || pair.second.mode == WatchMode::kReadWrite) pfd.events |= POLLOUT; pfd.revents = 0; (*map_indices)[i] = pair.first; i++; } } bool MessageLoopPoll::HasWatch(int watch_id) { auto it = watches_.find(watch_id); if (it == watches_.end()) return false; return true; } void MessageLoopPoll::OnHandleSignaled(int fd, short events, int watch_id) { // The watches_ vector is not threadsafe. FX_DCHECK(Current() == this); // Handle could have been just closed. Since all signaled handles are // notified for one call to poll(), a previous callback could have removed // a watch. if (!HasWatch(watch_id)) return; // We obtain the watch info and see what kind of signal we received. auto it = watches_.find(watch_id); const auto& watch_info = it->second; FX_DCHECK(fd == watch_info.fd); bool error = (events & POLLERR) || (events & POLLHUP) || (events & POLLNVAL); #if defined(POLLRDHUP) // Mac doesn't have this. error = error || (events & POLLRDHUP); #endif bool readable = !!(events & POLLIN); bool writable = !!(events & POLLOUT); if (HasWatch(watch_id)) watch_info.watcher->OnFDReady(fd, readable, writable, error); } } // namespace debug_ipc
#require "spreadsheet/excel" # writing excel #include Spreadsheet # writing excel #require 'parseexcel' # reading excel module Crud class << self # Crud tools provide Crud class methods that can perform operations across # multiple tables. These methods inlcude: # # - tables_list # - generate # - download ######################################################################################### # # tables_list # # Returns an array of names of the substantive tables used by the app. # ######################################################################################### def tables_list ActiveRecord::Base.active_connections.values.map {|connection| connection.tables}.flatten - %w(schema_migrations schema_info sessions) end def app_tables_list # collect list of app-defined models Dir.chdir("#{RAILS_ROOT}/app/models") app_tables = Dir['*.rb'].map {|fn| fn.gsub(/\.rb/, "").tableize} # intersect above list with list of database tables (app_tables & tables_list).sort end # returns list of app controllers located at the top level of # app/controllers def app_controllers_list controllers = Dir.new("#{RAILS_ROOT}/app/controllers").entries controllers.map {|c| c.camelize.gsub(".rb","") if c =~ /_controller.rb/}.compact.sort end ######################################################################################### # # generate(table, number, options = {}) # # Generates 'number' records for table 'table'. # ######################################################################################### def generate(tables, numbers, options = {}) # Prelimnary error checking return "tables must be an array" unless tables.is_a? Array return "numbers must be an array" unless numbers.is_a? Array return "tables and numbers are mismatched" unless tables.size == numbers.size all_tables = tables_list tables.each_with_index do |table,i| return "#{table.tableize} is not a valid table" unless all_tables.include?(table.tableize) return "all numbers must be > 0" unless numbers[i].to_i > 0 end # Generate records for each of the tables tables.each_with_index do |table,i| # extract columns to populate table = table.classify columns_hash = get_columns_hash(table, 'generate', 'default') return ":has_many columns not permitted (#{table.tableize})" unless columns_hash['_hm_attributes'].blank? # setup possible values columns_hash.delete('_attributes') columns_hash.delete('_hm_attributes') instance_variable_set("@#{table.underscore}", table.constantize.new) columns_hash.each do |k,v| case v[:type] when "belongs_to" r = {:array => get_association(table.classify, k).table_name.classify.constantize.find( :all).map(&:id).compact} when "simple_list" list_name = table.constantize.send("#{k}_selection_list") r = {:array => SimpleListList.find_or_create(list_name).simple_list_items.map(&:id)} when "multi_simple_list" list_name = /_id\z/ =~ k ? k[0..-4] : k r = {:array => SimpleListList.find_or_create(list_name).simple_list_items.map(&:id), :multi => (v['multi'] || 3)} when "multi_simple_list_list" list_name = /_list\z/ =~ k ? k[0..-6] : k r = {:array => SimpleListList.find_or_create(list_name).simple_list_items.map(&:name), :multi => (v['multi'] || 3), :list => true} when "price" r = {:start => (v['start'] || 10), :end => (v['end'] || 20000000)} when "percentage" r = {:start => (v['start'] || 0), :end => (v['end'] || 20)} when "boolean" r = {:start => 0, :end => 1} when "date" r = {:start => (v['start'] || '1/1/1990').to_date, :end => (v['end'] || '1/1/2008').to_date} when "integer" r = {:start => (v['start'] || 0), :end => (v['end'] || 100)} else # string or text (default) end r.merge!(:nil => v['nil']) if r && v['nil'] columns[k] = r ? r : v[:type] end # generate the records #return columns.to_a.flatten.join(' ') errors = 0 numbers[i].to_i.times do attributes = Hash.new.merge(columns) attributes.each do |k, v| if v.is_a? Hash if v[:nil] && rand(v[:nil]) == 0 r = nil elsif v[:start] && v[:end] r = v[:start] + rand(v[:end]-v[:start]) elsif v[:array] if v[:multi] choices = v[:array].map {|e| e.to_s} size = choices.size r = [] rand(v[:multi]+1).times do # get random subset (at least one) r << choices[rand(choices.size)] choices -= r end r = r.join(' ') if v[:list] else r = v[:array][rand(v[:array].size)] end end elsif v.is_a? String r = "test data" end attributes[k] = r ? r : nil end (object = table.constantize.new).attributes = attributes errors += 1 unless object.save end numbers[i] -= errors end return numbers # array of number of records that were generated per table end ######################################################################################### # # export(tables, options = {}) # # Writes records from 'tables' into a file and return the path to that file # to enable downloading (i.e. via send_file). Default file format is Excel. # ######################################################################################### def export(tables, options = {}) # Prelimnary error checking all_tables = tables_list if tables.first == "*" tables = all_tables else return "tables must be an array" unless tables.is_a? Array tables.each do |table| return "#{table.tableize} is not a valid table" unless all_tables.include?(table.tableize) end end format = options[:format] || 'xls' # Assuming we're downloading into excel for now # generate a new xls file file_path = "#{RAILS_ROOT}/tmp/hip_data_#{rand(100).to_s + Time.now.to_i.to_s}.#{format}" workbook = Excel.new(file_path) # populate the file tables.each do |table| # generate a new worksheet worksheet = workbook.add_worksheet(table) objects = table.classify.constantize.find(:all) columns, has_many_columns = Crud.columns_array(table.classify, 'download', format) # populate the column headings columns.each_with_index do |column, i| worksheet.write(0, i, column.first) end # populate the worksheet rows objects.each_with_index do |object, j| columns.each_with_index do |column, i| cell = object.send(column.first) worksheet.write(j+1, i, cell.respond_to?('name') ? cell.name : cell.to_s) end end end workbook.close file_path end ######################################################################################### # # import(tables, options = {}) # # ######################################################################################### def import(xls_file, options = {}) return "Error: '#{xls_file.original_filename}' is not an Excel file" unless /.+?\.xls$/ =~ xls_file.original_filename # TBD end end end
mod stats; mod stats_by_team; use stats_by_team::StatsByTeam; use std::convert::TryFrom; pub fn tally(log: &str) -> String { let stats_by_team = StatsByTeam::try_from(log).expect("failed to parse log"); format!("{}", stats_by_team) }
import pickle import gc import pandas as pd from keras_preprocessing.sequence import pad_sequences from tensorflow_core.python.keras.models import load_model from src.neuralnetwork import lstm_utils from src.pipelineapplication import utils lstm_model = "../../output/official/neuralnetwork.h5" tokenizer_model = "../../output/official/tokenizer.pickle" testset_path = "../../output/lstmdataset/testdataset_multilabel.csv" validationset_path = "../../output/lstmdataset/trainingdataset_multilabel.csv" trainingset_path = "../../output/lstmdataset/valdataset_multilabel.csv" padding = ",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1" T = 0.4 N = 3 print("*** TEST SET ***") print("INFO: Extracting Test dataset", end="... ") abstracts_test = pd.read_csv(testset_path) print("Done ✓") print("INFO: Preprocessing Test dataset", end="... ") X_test = [] sentences = list(abstracts_test["text"]) with open(testset_path, "r", encoding="utf-8") as fp: lines = fp.readlines() lines = lines[1:] lines = list(map(lambda x: x[-len(padding):-1], lines)) lines = list(map(lambda x: x.split(","), lines)) lines = list(map(lambda x: list(map(lambda y: int(y), x)), lines)) labels = lines for sen in sentences: X_test.append(lstm_utils.preprocess_text(sen)) print("Done ✓", end="\n\n") model = load_model(lstm_model) # load model from single file with open(tokenizer_model, 'rb') as handle: # get the tokenizer tokenizer = pickle.load(handle) labels = list(map(lambda x: x.index(1), labels)) print("INFO: Tokenizing sequences", end="... ") seq = tokenizer.texts_to_sequences(X_test) seq = pad_sequences(seq, padding='post', maxlen=200) print("Done ✓") print("INFO: Predicting", end="... ") yhat = model.predict(seq) # make predictions print("Done ✓") predictions = [] for y in yhat: pr = list(enumerate(y)) pr.sort(key=lambda x: x[1], reverse=True) predictions.append(pr[:N]) cont = 0 for i in range(len(predictions)): p = predictions[i] predicted_class = [x[0] for x in p] if labels[i] in predicted_class: cont += 1 acc_1 = cont / len(predictions) predictions = list(map(lambda x: utils.get_valid_predictions(x, T), yhat)) cont = 0 for i in range(len(predictions)): p = predictions[i] predicted_class = [x[0] for x in p] if labels[i] in predicted_class: cont += 1 acc_2 = cont / len(predictions) print("Accuracy with first " + str(N) + " elements: " + str(acc_1)) print("Accuracy with threshold " + str(acc_2)) print() abstracts_test = X_test = None gc.collect() print("*** TRAINING SET ***") print("INFO: Extracting Training dataset", end="... ") abstracts_training = pd.read_csv(trainingset_path) print("Done ✓") print("INFO: Preprocessing Training dataset", end="... ") X_training = [] sentences = list(abstracts_training["text"]) with open(trainingset_path, "r", encoding="utf-8") as fp: lines = fp.readlines() lines = lines[1:] lines = list(map(lambda x: x[-len(padding):-1], lines)) lines = list(map(lambda x: x.split(","), lines)) lines = list(map(lambda x: list(map(lambda y: int(y), x)), lines)) labels = lines for sen in sentences: X_training.append(lstm_utils.preprocess_text(sen)) print("Done ✓", end="\n\n") model = load_model(lstm_model) # load model from single file with open(tokenizer_model, 'rb') as handle: # get the tokenizer tokenizer = pickle.load(handle) labels = list(map(lambda x: x.index(1), labels)) print("INFO: Tokenizing sequences", end="... ") seq = tokenizer.texts_to_sequences(X_training) seq = pad_sequences(seq, padding='post', maxlen=200) print("Done ✓") print("INFO: Predicting", end="... ") yhat = model.predict(seq) # make predictions print("Done ✓") predictions = [] for y in yhat: pr = list(enumerate(y)) pr.sort(key=lambda x: x[1], reverse=True) predictions.append(pr[:N]) cont = 0 for i in range(len(predictions)): p = predictions[i] predicted_class = [x[0] for x in p] if labels[i] in predicted_class: cont += 1 acc_1 = cont / len(predictions) predictions = list(map(lambda x: utils.get_valid_predictions(x, T), yhat)) cont = 0 for i in range(len(predictions)): p = predictions[i] predicted_class = [x[0] for x in p] if labels[i] in predicted_class: cont += 1 acc_2 = cont / len(predictions) print("Accuracy with first " + str(N) + " elements: " + str(acc_1)) print("Accuracy with threshold " + str(acc_2)) print() abstracts_training = X_training = None gc.collect() print("*** VALIDATION SET ***") print("INFO: Extracting Validation dataset", end="... ") abstracts_validation = pd.read_csv(validationset_path) print("Done ✓") print("INFO: Preprocessing Validation dataset", end="... ") X_validation = [] sentences = list(abstracts_validation["text"]) with open(validationset_path, "r", encoding="utf-8") as fp: lines = fp.readlines() lines = lines[1:] lines = list(map(lambda x: x[-len(padding):-1], lines)) lines = list(map(lambda x: x.split(","), lines)) lines = list(map(lambda x: list(map(lambda y: int(y), x)), lines)) labels = lines for sen in sentences: X_validation.append(lstm_utils.preprocess_text(sen)) print("Done ✓", end="\n\n") model = load_model(lstm_model) # load model from single file with open(tokenizer_model, 'rb') as handle: # get the tokenizer tokenizer = pickle.load(handle) labels = list(map(lambda x: x.index(1), labels)) print("INFO: Tokenizing sequences", end="... ") seq = tokenizer.texts_to_sequences(X_validation) seq = pad_sequences(seq, padding='post', maxlen=200) print("Done ✓") print("INFO: Predicting", end="... ") yhat = model.predict(seq) # make predictions print("Done ✓") predictions = [] for y in yhat: pr = list(enumerate(y)) pr.sort(key=lambda x: x[1], reverse=True) predictions.append(pr[:N]) cont = 0 for i in range(len(predictions)): p = predictions[i] predicted_class = [x[0] for x in p] if labels[i] in predicted_class: cont += 1 acc_1 = cont / len(predictions) predictions = list(map(lambda x: utils.get_valid_predictions(x, T), yhat)) cont = 0 for i in range(len(predictions)): p = predictions[i] predicted_class = [x[0] for x in p] if labels[i] in predicted_class: cont += 1 acc_2 = cont / len(predictions) print("Accuracy with first " + str(N) + " elements: " + str(acc_1)) print("Accuracy with threshold " + str(acc_2))
package at.roteskreuz.stopcorona.screens.base.epoxy import android.widget.CheckBox import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import at.roteskreuz.stopcorona.R import at.roteskreuz.stopcorona.skeleton.core.screens.base.view.BaseEpoxyHolder import at.roteskreuz.stopcorona.skeleton.core.screens.base.view.BaseEpoxyModel import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass /** * Epoxy model for a checkbox element. */ @EpoxyModelClass(layout = R.layout.base_checkbox_epoxy_model) abstract class CheckboxModel( private val onCheckedChangedListener: (Boolean) -> Unit ) : BaseEpoxyModel<CheckboxModel.Holder>() { @EpoxyAttribute var label: String? = null @EpoxyAttribute var checked: Boolean = false /** * Text size of the label in sp. */ @EpoxyAttribute var textSize: Int = 20 @EpoxyAttribute var textStyle: Int = R.style.AppTheme_Copy override fun Holder.onBind() { checkbox.isChecked = checked checkboxLabel.text = label checkboxLabel.textSize = textSize.toFloat() checkboxLabel.setTextAppearance(textStyle) constraintLayoutCheckbox.setOnClickListener { checkbox.toggle() } checkbox.setOnCheckedChangeListener { _, checked -> onCheckedChangedListener(checked) } } override fun Holder.onUnbind() { checkbox.setOnCheckedChangeListener(null) constraintLayoutCheckbox.setOnClickListener(null) } class Holder : BaseEpoxyHolder() { val constraintLayoutCheckbox: ConstraintLayout by bind(R.id.constraintLayoutCheckbox) val checkbox: CheckBox by bind(R.id.checkbox) val checkboxLabel: TextView by bind(R.id.checkboxLabel) } }
<footer> <span class='sitefooter'><?=$footer?></span> </footer>
package com.nurbk.ps.countryweather.ui.activity import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import com.nurbk.ps.countryweather.R import com.nurbk.ps.countryweather.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var mBinding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) setSupportActionBar(mBinding.toolbar) val navHostFragment = supportFragmentManager .findFragmentById(R.id.fragment_nav_host_home) as NavHostFragment? val navController = navHostFragment!!.navController val appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build() NavigationUI.setupWithNavController( mBinding.toolbar, navController, appBarConfiguration ) navController.addOnDestinationChangedListener { controller, destination, arguments -> when (destination.id) { R.id.mainFragment, R.id.sliderFragment, R.id.seeAllFragment -> { mBinding.toolbar.visibility = View.GONE } else -> { mBinding.toolbar.visibility = View.VISIBLE } } } } }
package com.cognifide.gradle.lighthouse.config import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) class Suite { lateinit var name: String var default: Boolean = false var baseUrl: String? = null var paths: List<String> = listOf() var args: List<String> = listOf() }
<?php namespace App\Repositories\EmployeeRepositories; use App\Repositories\EmployeeRepositories\EmployeeRepositoryInterface; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Auth; class EmployeeRepository implements EmployeeRepositoryInterface{ public function index() { $user=User::all(); return $user; } public function create() { // } public function store(array $data,$image) { $employee=User::create( [ 'name'=>$data['name'], 'email'=>$data['email'], 'password'=>Hash::make($data['password']), 'image'=> $image ] ); return $employee; } public function show($id) { // } public function edit($id) { $employee=User::find($id); return $employee; } public function update(array $data,$name) { $employee=User::find($data['id']); $employee->name=$data['name']; $employee->email=$data['email']; $employee->password=Hash::make($data['password']); $employee->image=$name; $employee->save(); return $employee; } public function destroy($id) { User::destroy($id); return 'delete'; } }
namespace IQMStarterKit.Migrations { using System.Data.Entity.Migrations; public partial class ChangeFilePathFields : DbMigration { public override void Up() { AddColumn("dbo.FilePaths", "ContentType", c => c.String(maxLength: 100)); AddColumn("dbo.FilePaths", "Content", c => c.Binary()); } public override void Down() { DropColumn("dbo.FilePaths", "Content"); DropColumn("dbo.FilePaths", "ContentType"); } } }
<?php require(__DIR__ . "/this-file-does-not-exist.php");
function solve(a) { let p = JSON.parse(a); for(let key of Object.keys(p)) { console.log(`${key}: ${p[key]}`); } }
Pod::Spec.new do |spec| spec.name = "TVMeetingSDK" spec.version = "2.0.4" spec.summary = "TVMeetingSDK for IOS" spec.description = "TVMeetingSDK.framework一款用于开启即时视频会议的sdk" spec.homepage = "https://github.com/loneKiss/TVMeetingSDK" spec.license = { :type => "MIT", :file => "LICENSE" } spec.author = { "loneKiss" => "[email protected]" } spec.platform = :ios, "9.0" spec.source = { :git => "https://github.com/loneKiss/TVMeetingSDK.git", :tag => spec.version } spec.resources = ['TVMeetingSDKReadme.md'] spec.vendored_frameworks = "TVMeetingSDK/Frameworks/*.framework" spec.source_files = 'TVMeetingSDK/Headers/*.h' # 图片,其他资源文件存放的路径,需要注意的是,xib,nib也属于资源文件 spec.resource_bundles = { # 这是个数组,可以添加其他bundle 'TVMeetingSDK' => ['TVMeetingSDK/Resources/*'], } spec.requires_arc = true spec.pod_target_xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) $(PODS_ROOT)/**', 'HEADER_SEARCH_PATHS' => '$(inherited) $(PODS_ROOT)/**', 'VALID_ARCHS' => 'armv7 arm64 x86_64', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } end
package io.particle.android.sdk.cloud.models enum class ParticleSimStatus { READY_TO_ACTIVATE, // ok == "ready" ACTIVATED_FREE, // already activated on a free plan ACTIVATED, // already activated NOT_FOUND, NOT_OWNED_BY_USER, ERROR } internal fun statusCodeToSimStatus(statusCode: Int): Pair<ParticleSimStatus, String> { when (statusCode) { 204 -> return Pair(ParticleSimStatus.ACTIVATED_FREE, "SIM card is activated and on a free plan") 205 -> return Pair(ParticleSimStatus.ACTIVATED, "SIM card is already activated") 403 -> return Pair(ParticleSimStatus.NOT_OWNED_BY_USER, "SIM card is owned by another user") 404 -> return Pair(ParticleSimStatus.NOT_FOUND, "SIM card not found") } return if (statusCode in 200..299) { Pair(ParticleSimStatus.READY_TO_ACTIVATE, "SIM card is ready") } else { Pair(ParticleSimStatus.ERROR, "SIM card check error") } }
import 'package:flutter/material.dart'; import 'package:flutter_holo_date_picker/flutter_holo_date_picker.dart'; import 'package:intl/intl.dart'; class DateTesting extends StatefulWidget { DateTesting({Key? key}) : super(key: key); @override _DateTestingState createState() => _DateTestingState(); } class _DateTestingState extends State { static DateTime startDate = DateTime.now(); String quoteStartDate = DateFormat.yMMMd().format(startDate.add(Duration(days: 1))).toString(); String endPeriod = DateFormat.yMMMd() .format(DateTime.now().add(Duration(days: 30))) .toString(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( "Date Testing", ), ), body: ListView( children: [ ElevatedButton( child: Text("$quoteStartDate"), onPressed: () async { var selectedFirstDate = await DatePicker.showSimpleDatePicker( context, initialDate: DateFormat.yMMMd().parse(quoteStartDate), // firstDate: DateFormat.yMMMd().parse(quoteStartDate), firstDate: // startDate, // DateTime(2020), DateTime.now(), lastDate: DateTime(2030), dateFormat: "yyyy-MMMM-dd", locale: DateTimePickerLocale.en_us, looping: true, ); print("My date is picked $selectedFirstDate"); setState(() { setState(() { quoteStartDate = DateFormat.yMMMd().format(selectedFirstDate!); print("My quoteStartDate is picked $quoteStartDate"); endPeriod = DateFormat.yMMMd() .format(selectedFirstDate.add(Duration(days: 30))) .toString(); // oneYear = selectedFirstDate.add(Duration(days: 29)); }); }); }, ), ElevatedButton( child: Text("$endPeriod"), onPressed: () async { var selectedEndDate = await DatePicker.showSimpleDatePicker( context, initialDate: DateFormat.yMMMd().parse(endPeriod), firstDate: DateFormat.yMMMd() .parse(endPeriod) .subtract(Duration(days: 30)), lastDate: DateFormat.yMMMd() .parse(quoteStartDate) .add(Duration(days: 30)), dateFormat: "yyyy-MMMM-dd", locale: DateTimePickerLocale.en_us, looping: true, ); setState(() { endPeriod = DateFormat.yMMMd().format(selectedEndDate!).toString(); }); print("My date is picked $selectedEndDate"); }, ), ], )); } }
import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import 'package:rxdart/rxdart.dart'; import 'bloc_provider.dart'; import 'auth_bloc.dart'; class ConfigBloc extends BlocBase { final FirebaseDatabase db = FirebaseDatabase.instance; final BehaviorSubject<String> _userId = BehaviorSubject.seeded(null); static ConfigBloc of(BuildContext context) => BlocProvider.of(context); @override void initState(BuildContext context) { db.setPersistenceEnabled(true); AuthBloc.of(context).loginState.listen((user) { _userId.sink.add(user?.uid); }); } @override void dispose() { _userId.close(); } DatabaseReference userDB(String uid) { return db.reference().child('users').child(uid).child('configs'); } Future<void> setConfig(String key, String value) async { String uid = _userId.stream.value; await userDB(uid).child(key).set(value); } Observable getConfig(String key) { return Observable.switchLatest( _userId.map(userDB).map((node) { return node.child(key).onValue.map((e) => e.snapshot.value); }), ); } }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <MMCommon/MMService.h> #import "IRemoteControlMusicPlayerExt-Protocol.h" #import "ISysCallCheckExt-Protocol.h" #import "MMImageLoaderObserver-Protocol.h" #import "MMMusicAlbumRtnExt-Protocol.h" #import "MMMusicListExt-Protocol.h" #import "MMMusicLyricsRtnExt-Protocol.h" #import "MMMusicPlayerExt-Protocol.h" #import "MMMusicPlayerNotifyExt-Protocol.h" #import "MMService-Protocol.h" #import "PBMessageObserverDelegate-Protocol.h" @class MMMusicInfo, MMMusicListMgr, MMMusicLyricResolver, MusicLogInfo, NSMutableArray, NSString; @interface MMMusicPlayerMgr : MMService <MMImageLoaderObserver, IRemoteControlMusicPlayerExt, PBMessageObserverDelegate, MMMusicPlayerNotifyExt, MMService, MMMusicPlayerExt, MMMusicLyricsRtnExt, MMMusicAlbumRtnExt, MMMusicListExt, ISysCallCheckExt> { NSMutableArray *m_arrMusicItems; MMMusicInfo *m_prevMusicInfo; MMMusicInfo *m_curMusicInfo; MMMusicInfo *m_nextMusicInfo; int m_playMode; int m_playDirection; MMMusicListMgr *m_musicListMgr; MMMusicLyricResolver *m_musicLyricResolver; unsigned int m_uiCurMusicIndex; _Bool m_bforceStop; _Bool m_shouldTurnRepeatNoneMode; MusicLogInfo *m_musicLogInfo; _Bool m_shouldDelayResetCurMusicInfo; _Bool m_isManualPaused; int m_state; NSString *m_shouldForceStopMusicID; } @property(nonatomic) _Bool m_isManualPaused; // @synthesize m_isManualPaused; @property(nonatomic) int m_state; // @synthesize m_state; @property(retain, nonatomic) NSString *m_shouldForceStopMusicID; // @synthesize m_shouldForceStopMusicID; @property(nonatomic) _Bool m_shouldDelayResetCurMusicInfo; // @synthesize m_shouldDelayResetCurMusicInfo; @property(nonatomic) _Bool m_shouldTurnRepeatNoneMode; // @synthesize m_shouldTurnRepeatNoneMode; @property(retain, nonatomic) MusicLogInfo *m_musicLogInfo; // @synthesize m_musicLogInfo; @property(retain, nonatomic) MMMusicInfo *m_nextMusicInfo; // @synthesize m_nextMusicInfo; @property(retain, nonatomic) MMMusicInfo *m_prevMusicInfo; // @synthesize m_prevMusicInfo; @property(retain, nonatomic) MMMusicListMgr *m_musicListMgr; // @synthesize m_musicListMgr; @property(retain) MMMusicInfo *m_curMusicInfo; // @synthesize m_curMusicInfo; - (void).cxx_destruct; - (_Bool)isMusicIdPlayingOrWaiting:(id)arg1; - (void)updateMusicWebUrl:(id)arg1; - (void)updateMusicCover:(id)arg1; - (void)updateMusicEPName:(id)arg1; - (void)updateMusicSinger:(id)arg1; - (void)updateMusicTitle:(id)arg1; - (void)statNativePlayerAction:(id)arg1 scene:(unsigned int)arg2 actionType:(unsigned int)arg3; - (void)resetMusicPlayerEntranceType; - (void)updateMusicLogInfo; - (void)logMusicStatAndReset; - (void)logMusicStat; - (void)notifyMusicPlayerRestartMusic; - (void)notifyMusicPlayerPauseMusic; - (void)onRemoteControlMusicShouldPlayPrevTrack; - (void)onRemoteControlMusicShouldPlayNextTrack; - (void)onRemoteControlMusicShouldStop; - (void)onRemoteControlMusicShouldPlayOrPause; - (void)onRemoteControlMusicShouldPauseByMannual:(_Bool)arg1; - (void)onRemoteControlMusicShouldPlay; - (id)getCurTimeList; - (id)getCurLyricsList; - (void)onMusicListArrayChange; - (void)OnGetSongAlbumUrl:(id)arg1 AlbumUrl:(id)arg2; - (void)OnGetLyrics:(id)arg1 Lyrics:(id)arg2; - (void)onDataBuffering:(double)arg1; - (void)onForceStopMusic; - (void)onLevelMeterPeak:(float)arg1; - (void)delayResetCurMusicInfo; - (void)handlePlayerStopOrErrorEvent; - (void)onMusicPlayStatusChanged:(unsigned long long)arg1 error:(id)arg2; - (id)getNextMusicInfo; - (id)getPreviousMusicInfo; - (unsigned long long)indexOfMusic:(id)arg1; - (_Bool)isLyricValid; - (void)updateMPNowPlayingInfo:(id)arg1; - (void)ImageDidLoad:(id)arg1 Url:(id)arg2; - (void)safeForceStopMusic; - (void)MessageReturn:(id)arg1 Event:(unsigned int)arg2; - (void)safeCheckMusicInfo:(id)arg1; - (void)playWithMusicInfo:(id)arg1; - (_Bool)isValidLowBandUrl:(id)arg1; - (id)getMusicUrlWithMusicInfo:(id)arg1; - (void)setMusicPlayDirection:(int)arg1; - (id)getMusicInfoByMusicKey:(id)arg1; - (_Bool)isMusicItemsContainsMusicKey:(id)arg1; - (id)getArrMusicItems; - (double)getCurMusicBufferTime; - (double)getCurMusicBufferProgress; - (double)getCurMusicOffset; - (double)getCurMusicDuration; - (int)getMusicPlayState; - (id)getCurMusicTitle; - (id)getCurMusicInfo; - (_Bool)isPaused; - (_Bool)isWaiting; - (_Bool)isPlaying; - (_Bool)isIdle; - (_Bool)stopWithMusicKey:(id)arg1; - (void)stopPlay; - (void)seekToTime:(double)arg1 playAuto:(_Bool)arg2; - (void)resumePlay; - (_Bool)isManualPaused; - (_Bool)pausePlayManual:(_Bool)arg1 pauseDownload:(_Bool)arg2; - (void)playNextMusic; - (void)playPreviousMusic; - (void)playWithMusicKey:(id)arg1; - (void)setMusicItemList:(id)arg1; - (void)setAndPlayMusicItem:(id)arg1; - (void)updateMusicListBySource:(int)arg1; - (int)getMusicListSource; - (void)setPlayMode:(int)arg1; - (int)getMusicPlayMode; - (void)dealloc; - (void)updateArrMusicItems; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
package com.fasterxml.jackson.dataformat.protobuf.schema; import java.util.List; import com.fasterxml.jackson.dataformat.protobuf.ProtobufTestBase; public class ReadCyclicSchema140Test extends ProtobufTestBase { final protected static String PROTOC_CYCLIC = "message Front {\n" +" optional string id = 1;\n" +" optional Back next = 2;\n" +"}\n" +"message Back {\n" +" optional string id = 1;\n" +" optional string extra = 2;\n" +" optional Front next = 3;\n" +"}\n" ; public void testCyclicDefinition() throws Exception { ProtobufSchema schema = ProtobufSchemaLoader.std.parse(PROTOC_CYCLIC); assertNotNull(schema); List<String> all = schema.getMessageTypes(); assertEquals(2, all.size()); assertEquals("Front", all.get(0)); assertEquals("Back", all.get(1)); ProtobufMessage msg = schema.getRootType(); assertEquals("Front", msg.getName()); assertEquals(2, msg.getFieldCount()); ProtobufField f = msg.field("id"); assertNotNull(f); assertEquals("id", f.name); _verifyMessageFieldLinking(schema.getRootType()); } }
@extends('layouts.admin.master') @section('title')Apex Chart {{ $title }} @endsection @push('css') @endpush @section('content') @component('components.breadcrumb') @slot('breadcrumb_title') <h3>Apex Chart</h3> @endslot <li class="breadcrumb-item">Charts</li> <li class="breadcrumb-item active">Apex Chart</li> @endcomponent <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Basic Area Chart</h5> </div> <div class="card-body"> <div id="basic-apex"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Area Spaline Chart</h5> </div> <div class="card-body"> <div id="area-spaline"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Bar chart</h5> </div> <div class="card-body"> <div id="basic-bar"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Column Chart</h5> </div> <div class="card-body"> <div id="column-chart"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-12"> <div class="card"> <div class="card-header pb-0"> <h5> 3d Bubble Chart </h5> </div> <div class="card-body"> <div id="chart-bubble"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-12"> <div class="card"> <div class="card-header pb-0"> <h5>Candlestick Chart</h5> </div> <div class="card-body"> <div id="candlestick"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Stepline Chart</h5> </div> <div class="card-body"> <div id="stepline"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Column Chart</h5> </div> <div class="card-body"> <div id="annotationchart"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Pie Chart</h5> </div> <div class="card-body apex-chart"> <div id="piechart"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Donut Chart</h5> </div> <div class="card-body apex-chart"> <div id="donutchart"></div> </div> </div> </div> <div class="col-sm-12 col-xl-12 box-col-12"> <div class="card"> <div class="card-header pb-0"> <h5>Mixed Chart</h5> </div> <div class="card-body"> <div id="mixedchart"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Radar Chart</h5> </div> <div class="card-body"> <div id="radarchart"></div> </div> </div> </div> <div class="col-sm-12 col-xl-6 box-col-6"> <div class="card"> <div class="card-header pb-0"> <h5>Radial Bar Chart</h5> </div> <div class="card-body"> <div id="circlechart"></div> </div> </div> </div> </div> </div> @push('scripts') <script src="{{ asset('assets/js/chart/apex-chart/apex-chart.js') }}"></script> <script src="{{ asset('assets/js/chart/apex-chart/stock-prices.js') }}"></script> <script src="{{ asset('assets/js/chart/apex-chart/chart-custom.js') }}"></script> @endpush @endsection
package com.elementary.tasks.core.calendar import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager class InfiniteViewPager : ViewPager { private var enabled = true override fun isEnabled(): Boolean { return enabled } override fun setEnabled(enabled: Boolean) { this.enabled = enabled } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context) : super(context) override fun setAdapter(adapter: PagerAdapter?) { super.setAdapter(adapter) currentItem = OFFSET } override fun onTouchEvent(event: MotionEvent): Boolean { try { return enabled && super.onTouchEvent(event) } catch (ex: IllegalArgumentException) { ex.printStackTrace() } return false } override fun onInterceptTouchEvent(event: MotionEvent): Boolean { try { return super.onInterceptTouchEvent(event) } catch (ex: IllegalArgumentException) { ex.printStackTrace() } return false } companion object { const val OFFSET = 1000 } }
--- title: werf config render sidebar: documentation permalink: documentation/cli/management/config/render.html --- {% include /cli/werf_config_render.md %}
#include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "sea_dsa/CallSite.hh" using namespace llvm; namespace sea_dsa { bool DsaCallSite::isPointerTy::operator()(const Value *v) { return v->getType()->isPointerTy(); } bool DsaCallSite::isPointerTy::operator()(const Argument &a) { return a.getType()->isPointerTy(); } static const Function* getCalledFunctionThroughAliasesAndCasts(ImmutableCallSite &CS) { const Value* CalledV = CS.getCalledValue(); CalledV = CalledV->stripPointerCasts(); if (const Function* F = dyn_cast<const Function>(CalledV)) { return F; } if (const GlobalAlias *GA = dyn_cast<const GlobalAlias>(CalledV)) { if (const Function* F = dyn_cast<const Function>(GA->getAliasee()->stripPointerCasts())) { return F; } } return nullptr; } DsaCallSite::DsaCallSite(const ImmutableCallSite &cs) : m_cs(cs) , m_cell(None) , m_cloned(false) , m_callee(getCalledFunctionThroughAliasesAndCasts(m_cs)) {} DsaCallSite::DsaCallSite(const Instruction &cs) : m_cs(&cs) , m_cell(None) , m_cloned(false) , m_callee(getCalledFunctionThroughAliasesAndCasts(m_cs)) {} DsaCallSite::DsaCallSite(const Instruction &cs, Cell c) : m_cs(&cs) , m_cell(c) , m_cloned(false) , m_callee(getCalledFunctionThroughAliasesAndCasts(m_cs)) { m_cell.getValue().getNode(); } DsaCallSite::DsaCallSite(const Instruction &cs, const Function &callee) : m_cs(&cs) , m_cell(None) , m_cloned(false) , m_callee(&callee) { assert(isIndirectCall() || getCalledFunctionThroughAliasesAndCasts(m_cs) == &callee); } bool DsaCallSite::hasCell() const { return m_cell.hasValue(); } const Cell &DsaCallSite::getCell() const { assert(hasCell()); return m_cell.getValue(); } Cell &DsaCallSite::getCell() { assert(hasCell()); return m_cell.getValue(); } const llvm::Value &DsaCallSite::getCalledValue() const { return *(m_cs.getCalledValue()); } bool DsaCallSite::isIndirectCall() const { // XXX: this does not compile // return m_cs.isIndirectCall(); const Value *V = m_cs.getCalledValue(); if (!V) return false; if (isa<const Function>(V) || isa<const Constant>(V)) return false; if (const CallInst *CI = dyn_cast<const CallInst>(getInstruction())) { if (CI->isInlineAsm()) return false; } return true; } bool DsaCallSite::isInlineAsm() const { return m_cs.isInlineAsm(); } bool DsaCallSite::isCloned() const { return m_cloned; } void DsaCallSite::markCloned(bool v) { m_cloned = v; } const Value *DsaCallSite::getRetVal() const { if (const Function *F = getCallee()) { const FunctionType *FTy = F->getFunctionType(); if (!(FTy->getReturnType()->isVoidTy())) return getInstruction(); } return nullptr; } const Function *DsaCallSite::getCallee() const { return m_callee; } const Function *DsaCallSite::getCaller() const { return m_cs.getCaller(); } const Instruction *DsaCallSite::getInstruction() const { return m_cs.getInstruction(); } DsaCallSite::const_formal_iterator DsaCallSite::formal_begin() const { isPointerTy p; assert(getCallee()); return boost::make_filter_iterator(p, getCallee()->arg_begin(), getCallee()->arg_end()); } DsaCallSite::const_formal_iterator DsaCallSite::formal_end() const { isPointerTy p; assert(getCallee()); return boost::make_filter_iterator(p, getCallee()->arg_end(), getCallee()->arg_end()); } DsaCallSite::const_actual_iterator DsaCallSite::actual_begin() const { isPointerTy p; return boost::make_filter_iterator(p, m_cs.arg_begin(), m_cs.arg_end()); } DsaCallSite::const_actual_iterator DsaCallSite::actual_end() const { isPointerTy p; return boost::make_filter_iterator(p, m_cs.arg_end(), m_cs.arg_end()); } void DsaCallSite::write(raw_ostream &o) const { o << *m_cs.getInstruction(); if (isIndirectCall() && hasCell()) { o << "\nCallee cell " << m_cell.getValue(); } } } // namespace sea_dsa
import { bridgeSql } from '../database/postgre'; import { sql } from '../utils/sql'; export const up = async (knex, db = bridgeSql(knex)) => { // Create documents structure await db.execute(sql` CREATE TABLE "products" ( id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), description text, logo_url text, association_id VARCHAR(255) NOT NULL, created_at timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE (name, association_id), CONSTRAINT fk_association_id FOREIGN KEY (association_id) REFERENCES associations (id) ); CREATE TABLE "applications" ( id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), description text, url text, logo_url text, product_id VARCHAR(255) NOT NULL, created_at timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE (name, product_id), CONSTRAINT fk_product_id FOREIGN KEY (product_id) REFERENCES products (id) ); CREATE TABLE "applications_memberships" ( membership VARCHAR(255), application VARCHAR(255), UNIQUE (membership, application), CONSTRAINT fk_membership FOREIGN KEY (membership) REFERENCES memberships (id), CONSTRAINT fk_application FOREIGN KEY (application) REFERENCES applications (id) ); `); }; // eslint-disable-next-line no-unused-vars export const down = async (knex, db = bridgeSql(knex)) => { // Nothing to do };
package io.petros.movies.network.rest import io.mockk.coEvery import io.mockk.mockk import io.petros.movies.network.raw.movie.MovieRaw import io.petros.movies.network.raw.movie.MoviesPageRaw import io.petros.movies.test.domain.movie import io.petros.movies.test.domain.moviesPage import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Test import strikt.api.expect import strikt.assertions.isEqualTo import java.util.* @ExperimentalCoroutinesApi class RestClientTest { private val restApiMock = mockk<RestApi>() private val testedClass = RestClient(restApiMock) @Test fun `when load movies is triggered, then the movies page is the expected one`() = runTest { val moviesPageRaw = MoviesPageRaw(emptyList()) val moviesPage = moviesPage(emptyList()) coEvery { restApiMock.loadMovies(RELEASE_DATE_GTE, RELEASE_DATE_LTE, SECOND_PAGE) } returns moviesPageRaw val result = testedClass.loadMovies(MOVIE_YEAR, MOVIE_MONTH, SECOND_PAGE) expect { that(result).isEqualTo(moviesPage) } } @Test fun `when load movie is triggered, then the movie is the expected one`() = runTest { val title = "Ad Astra" val releaseDate = "2019-09-17" val voteAverage = 6.0 val voteCount = 2958 val overview = "The near future, a time when both hope and hardships drive humanity to look to the stars " + "and beyond. While a mysterious phenomenon menaces to destroy life on planet Earth, astronaut " + "Roy McBride undertakes a mission across the immensity of space and its many perils to " + "uncover the truth about a lost expedition that decades before boldly faced emptiness and " + "silence in search of the unknown." val backdrop = "http://image.tmdb.org/t/p/w500/5BwqwxMEjeFtdknRV792Svo0K1v.jpg" val movieRaw = MovieRaw( voteCount, MOVIE_ID, voteAverage, title, backdrop, overview, releaseDate, ) val movie = movie( MOVIE_ID, title, GregorianCalendar(2019, Calendar.SEPTEMBER, 17).time, voteAverage, voteCount, overview, MovieRaw.IMAGE_URL_PREFIX + backdrop, ) coEvery { restApiMock.loadMovie(MOVIE_ID) } returns movieRaw val result = testedClass.loadMovie(MOVIE_ID) expect { that(result).isEqualTo(movie) } } companion object { private const val SECOND_PAGE = 2 private const val MOVIE_ID = 419_704 private const val MOVIE_YEAR = 2018 private const val MOVIE_MONTH = 7 private const val RELEASE_DATE_GTE = "2018-08-01" private const val RELEASE_DATE_LTE = "2018-08-31" } }
<?php namespace App\Http\Controllers; use App\Models\Mascota; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class MascotaController extends Controller { // function test(Request $request){ return response()->json(["error"=>false,"message"=>"Consulta Exitosa"],200); } function crearMascota(Request $request){ DB::beginTransaction(); $objetoMascota = new Mascota(); try{ if(!empty($request->id)){ $objetoMascota=Mascota::find($request->id); $objetoMascota->raza = $request->raza; $objetoMascota->tamanio = $request->tamanio; $objetoMascota->save(); DB::commit(); return response()->json([ "error"=>false, "message"=>"Registro actualizado", "Detalles"=>$objetoMascota] , 200); }else{ $objetoMascota->raza = $request->raza; $objetoMascota->tamanio = $request->tamanio; $objetoMascota->save(); DB::commit(); return response()->json([ "error"=>false, "message"=>"Registro Creado", "Detalles"=>$objetoMascota] , 201); } }catch(QueryException $queryException){ DB::rollback(); return response()->json($queryException->errorInfo,500); } } /*function crearMascota(Request $request){ DB::beginTransaction(); try{ $objetoMascota = new Mascota(); $objetoMascota->raza = $request->raza; $objetoMascota->tamanio= $request->tamanio; $objetoMascota->save(); DB::commit(); return response()->json(["error"=>false,"message"=>"Registro Creado","Detalles"=>$objetoMascota],201); }catch(QueryException $queryException){ DB::rollback(); return response()->json($queryException->errorInfo,500); } }*/ }
package com.afdhal_fa.treasure.core.utils interface IBaseView { fun onShowProgressBar() fun onHideProgressBar() }
-- Revert seattleflu/id3c-customizations:shipping/views from pg -- requires: seattleflu/schema:shipping/schema -- Hello! All shipping views are defined here. Rework this change with Sqitch -- to change a view definition or add new views. This workflow helps keep -- inter-view dependencies manageable. begin; -- This view is versioned as a hedge against future changes. Changing this -- view in place is fine as long as changes are backwards compatible. Think of -- the version number as the major part of a semantic versioning scheme. If -- there needs to be a lag between view development and consumers being -- updated, copy the view definition into v2 and make changes there. drop view shipping.reportable_condition_v1; commit;
# CreateUser {#reference_lmj_ftk_xdb .reference} ## Interface description {#section_whn_4tk_xdb .section} Creates an RAM user. ## Request parameters {#section_k2y_ptk_xdb .section} **Action** - Type: String - Required: Yes - Description: Operation interface, required. The parameter value is "CreateUser". **UserName** - Type: String - Required: Yes - Description: User name. It consists of a maximum of 64 characters. - Format: ``` ^[a-zA-Z0-9\. @\\-_]+$ ``` **DisplayName** - Type: String - Required: No - Description: Display name. It consists of a maximum of 128 characters. - Format: ``` ^[a-zA-Z0-9\.@\-\u4e00-\u9fa5]+$ ``` **MobilePhone** - Type: String - Required: No - Description: An RAM user's mobile number. - Format: International area code-number such as 86-18600008888 **E-mail** - Type: String - Required: No - Description: An RAM user's email address. **Comments** - Type: String - Required: No - Description: Remark information. It consists of a maximum of 128 characters. ## Required permissions {#section_g22_rtk_xdb .section} **Action** ``` ram:CreateUser ``` **Resource** ``` ACS: Ram: *: $ {accountant}: User /* ``` ## Return parameters {#section_svf_5tk_xdb .section} **User** - Type:[User](reseller.en-US/API reference/API Reference (RAM)/Data types/User.md) - Description: user information ## Error messages {#section_zjv_5tk_xdb .section} **InvalidParameter.UserName.InvalidChars** - HTTP Status:400 - Error Message:The parameter - "UserName" contains invalid chars. **InvalidParameter.UserName.Length** - HTTP status: 400 - Error Message:The parameter - "UserName" beyond the length limit. **InvalidParameter.DisplayName.InvalidChars** - HTTP Status: 400 - Error Message: The parameter - "DisplayName" contains invalid chars. **InvalidParameter.DisplayName.Length** - HTTP Status: 400 - Error Message: The parameter - "DisplayName" beyond the length limit. **InvalidParameter.Comments.Length** - HTTP Status: 400 - Error Message: The parameter - "Comments" beyond the length limit. **InvalidParameter.MobilePhone.Format** - HTTP Status: 400 - Error Message: The format of the parameter - "MobilePhone" is incorrect. **InvalidParameter.Email.Format** - HTTP Status: 400 - Error Message: The format of the parameter - "Email" is incorrect. **EntityAlreadyExists.User** - HTTP Status: 409 - Error Message: The user does already EXIST. **LimitExceeded.User** - HTTP Status: 409 - Error Message: The count of users beyond the current limits. ## Operation examples {#section_pwp_vtk_xdb .section} **Request example** **Note:** To facilitate reading, parameters are not encoded in the following request examples. ``` https://ram.aliyuncs.com/?Action=CreateUser &UserName=zhangqiang &DisplayName=zhangqiang &MobilePhone=86-18688888888 &[email protected] &Comments=This is a cloud computing engineer. &<Public request parameters> ``` **Response example** - XML format ``` <CreateUserResponse>  <RequestId>04F0F334-1335-436C-A1D7-6C044FE73368</RequestId>  <User> <UserId>1227489245380721</UserId> <UserName>zhangqiang</UserName> <DisplayName>zhangqiang</DisplayName> <MobilePhone>86-18600008888</MobilePhone> <Email>[email protected]</Email>  <Comments>This is a cloud computing engineer.</Comments>  <CreateDate>2015-01-23T12:33:18Z</CreateDate>  </User> </CreateUserResponse> ``` - JSON format ``` { "RequestId": "04F0F334-1335-436C-A1D7-6C044FE73368", "User": { "UserId": "1227489245380721", "UserName": "zhangqiang", "DisplayName": "zhangqiang", "MobilePhone": "86-18600008888", "Email": "maid ", "Comments": "This is a cloud computing engineer". "CreateDate": "2015-01-23T12:33:18Z" } } ```
require_relative '../exercise2/file_sorter.rb' require 'timeout' module Exercise2 describe FileSorter do describe '::by_size_biggest_first' do it 'Sorts files by their length attribute' do File = Struct.new(:length) file1 = File.new 1 file2 = File.new 5 file3 = File.new 7 file4 = File.new 3 file5 = File.new 2 expect(FileSorter.by_size_biggest_first( [file1, file2, file3, file4, file5] )).to eq [file3, file2, file4, file5, file1] end context 'with files where #length is slow' do SlowFile = Struct.new(:fast_length) do def length sleep 0.1 fast_length end end xit 'is fast' do Timeout.timeout(3) do files = [ SlowFile.new(1), SlowFile.new(2), SlowFile.new(3), SlowFile.new(4), SlowFile.new(5), SlowFile.new(6), SlowFile.new(7), SlowFile.new(8), SlowFile.new(9), SlowFile.new(10), SlowFile.new(11), SlowFile.new(12), SlowFile.new(13), SlowFile.new(14), SlowFile.new(15), SlowFile.new(16), SlowFile.new(17), SlowFile.new(18), SlowFile.new(19), SlowFile.new(20) ] files_shuffled = files.shuffle expect(FileSorter.by_size_biggest_first( files_shuffled )).to eq files.reverse end end end end end end
#!/bin/bash source ~/.dotfiles.env if [[ "$DOTFILES_CONFIG_I3_DISABLE_VOLUME_WIDGET" == 'true' ]]; then echo >&2 'Widget is disabled by variable DOTFILES_CONFIG_I3_DISABLE_VOLUME_WIDGET' exit 0 fi I3_HOME="$DOTFILES_HOME/config/i3" SOUND_ICON='' NO_SOUND_ICON='' dir="$(dirname "${BASH_SOURCE[@]}")" VOLUMECTL="$I3_HOME/bin/volumectl" [[ -n "$BLOCK_BUTTON" ]] && ( exec > /dev/null 2>&1 case $BLOCK_BUTTON in 1) "$VOLUMECTL" mute-toggle ;; # click, mute/unmute 4) "$VOLUMECTL" up ;; # scroll up 5) "$VOLUMECTL" down ;; # scroll down esac ) percentage="$(BLOCK_BUTTON='' "$dir/volume.sh" "${1:-5}" "${2:-pulse}")" if [[ "$percentage" != 'MUTE' ]]; then echo "$SOUND_ICON $percentage" else echo "$NO_SOUND_ICON" echo "$NO_SOUND_ICON" echo '#FF0000' fi
package unikv // Key is the type of unikv key type Key interface { // Convert to string String() string } // KeyString is string key type KeyString string // String converts KeyString to string func (ks KeyString) String() string { return string(ks) } // KeyNil is blanck key var KeyNil = KeyString("(unikv_nil)") // NewKey creates a new key func NewKey(key interface{}) Key { switch key.(type) { case string: return KeyString(key.(string)) case Key: return key.(Key) } return KeyNil }
using RumahScarlett.Domain.Models.Pembelian; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RumahScarlett.Services.Services.Pembelian { public class PembelianReturnServices : IPembelianReturnServices { private IPembelianReturnRepository _repo; private IModelDataAnnotationCheck _modelDAC; public PembelianReturnServices(IPembelianReturnRepository repo, IModelDataAnnotationCheck modelDAC) { _repo = repo; _modelDAC = modelDAC; } public void Insert(IPembelianReturnModel model) { ValidateModel(model); _repo.Insert(model); } public void Update(IPembelianReturnModel model) { throw new NotImplementedException(); } public void Delete(IPembelianReturnModel model) { _repo.Delete(model); } public IEnumerable<IPembelianReturnModel> GetAll() { throw new NotImplementedException(); } public IEnumerable<IPembelianReturnModel> GetByDate(object date) { return _repo.GetByDate(date); } public IEnumerable<IPembelianReturnModel> GetByDate(object startDate, object endDate) { return _repo.GetByDate(startDate, endDate); } public IPembelianReturnModel GetById(object id) { throw new NotImplementedException(); } public IEnumerable<IPembelianReturnReportModel> GetReportByDate(object date) { return _repo.GetReportByDate(date); } public IEnumerable<IPembelianReturnReportModel> GetReportByDate(object startDate, object endDate) { return _repo.GetReportByDate(startDate, endDate); } public void ValidateModel(IPembelianReturnModel model) { _modelDAC.ValidateModel(model); _modelDAC.ValidateModels(model.PembelianReturnDetails); } } }
Python Style Guidelines ======================= For Python programming, we use a slightly modified version of the standard [PEP-8 Style Guide for Python Code](http://legacy.python.org/dev/peps/pep-0008 "PEP-8 Style Guide for Python Code"). Read below for our modifications. - - - ## Code lay-out ## ### Indentation ### The closing brace/bracket/parenthesis on multi-line constructs may either be directly at the end, as in: my_list = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f') or it may be by itself on the next line: my_list = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f' ) ### Tabs or Spaces? ### **_Always_** use spaces. ### Maximum Line Length ### **Docstrings and comments** should be restricted to _72 characters_. Anything else should be limited to _100 characters_. **_Never_** use backslashes _(\\)_ to wrap lines. ## Naming Conventions ## ### Variables ### Intentionally **unused** variables should be named "**_**". This will make common IDEs and editors ignore it. ## Strings ## ### Quotations ### Use single quotations _(')_ unless there is one inside the string, in which case use double quotations _(")_.
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley.mock; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; // TODO: the name of this class sucks @SuppressWarnings({ "serial", "rawtypes" }) public class WaitableQueue extends PriorityBlockingQueue<Request> { private final Request<?> mStopRequest = new MagicStopRequest(); private final Semaphore mStopEvent = new Semaphore(0); // TODO: this isn't really "until empty" it's "until next call to take() after empty" public void waitUntilEmpty(long timeoutMillis) throws TimeoutException, InterruptedException { add(mStopRequest); if (!mStopEvent.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) { throw new TimeoutException(); } } @Override public Request<?> take() throws InterruptedException { Request<?> item = super.take(); if (item == mStopRequest) { mStopEvent.release(); return take(); } return item; } private static class MagicStopRequest extends Request<Object> { public MagicStopRequest() { super("", null); } @Override public Priority getPriority() { return Priority.LOW; } @Override protected Response<Object> parseNetworkResponse(NetworkResponse response) { return null; } @Override protected void deliverResponse(Object response) { } } }
# Dashboard This folder contains the components necessary to build and deploy a dashboard to visualize gRPC OSS benchmarking results. gRPC OSS benchmarks save results to [BigQuery][bigquery]. The dashboard consists of two components: 1. A [Postgres replicator][replicator], to transfer the results to a Postgres database. 1. A Grafana dashboard, to display the results from the Postgres database. These components can be built and deployed manually using the [Makefile](Makefile) (see [manual build](#manual-build)). Notice that the dashboard build is independent from the top-level build. ## Configuration The configuration of the Postgres replicator is defined in a YAML file. The default configuration is defined here, in template form: - [config/postgres_replicator/default/config.yaml][replicatorconfig] For more information, see [Postgres replicator][replicator]. The configuration of the Grafana dashboard is defined in a set of dashboards specified in JSON files. The default configuration is defined here: - [config/grafana/dashboards/default/][grafanaconfig] The continuous integration dashboard linked from the [gRPC performance benchmarking][benchmarking] page uses the default configuration. The variables `REPLICATOR_CONFIG_TEMPLATE` and `DASHBOARDS_CONFIG_DIR` can be set to build dashboards with different configurations. [benchmarking]: https://grpc.io/docs/guides/benchmarking/ [bigquery]: https://cloud.google.com/bigquery [grafanaconfig]: config/grafana/dashboards/default/ [replicator]: cmd/postgres_replicator/README.md [replicatorconfig]: config/postgres_replicator/default/config.yaml ## Manual build Several environment variables must be set before building and deploying. The table below shows the names and values of the variables in our main dashboard: | Variable | Value | | --------------------------- | --------------------------------------------- | | `BQ_PROJECT_ID` | `grpc-testing` | | `CLOUD_SQL_INSTANCE` | `grpc-testing:us-central1:grafana-datasource` | | `GCP_DATA_TRANSFER_SERVICE` | `postgres-replicator` | | `GCP_GRAFANA_SERVICE` | `grafana` | | `GCP_PROJECT_ID` | `grpc-testing` | | `GRAFANA_ADMIN_PASS` | ... | | `PG_DATABASE` | `datasource` | | `PG_PASS` | ... | | `PG_USER` | `grafana-user` | Docker files that can be used to build and deploy the Postgres replicator and Grafana dashboard are then created with the following commands: ```shell make configure-replicator make configure-dashboard ``` ## Cloud build The continuous integration dashboard is built and deployed with [Cloud Build][cloudbuild], using the configuration specified in [cloudbuild.yaml](cloudbuild.yaml). The use of Cloud Build allows the dashboard to be redeployed automatically on configuration changes. In addition, it allows passwords such as `PG_PASS` and `GRAFANA_ADMIN_PASS` to be stored as secrets in the cloud project. [cloudbuild]: https://cloud.google.com/build
package net.codecision.startask.http.code.sample.network import net.codecision.startask.http.code.HttpStatusCode import retrofit2.Response fun <T> Response<T>.toHttpStatusCode(): HttpStatusCode { return HttpStatusCode.fromValue(code()) }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Employee extends Model { //whitelist protected $fillable=['name','alamat','phone','email','position_id','picture']; //blacklist protected $guarded=['id']; public function position(){ return $this->belongsTo('App\Position'); } public function inventory(){ return $this->belongsToMany('App\Inventory') ->withPivot('description', 'created_at'); } }
require 'app/controllers/html_controller' require 'app/helpers/manage_helper' require 'app/models/pod' require 'app/controllers/slack_controller' require 'active_support/core_ext/hash/except' require 'peiji_san/view_helper' require 'sinatra/twitter-bootstrap' require 'sinatra/url_for' module Pod module TrunkApp class ManageController < HTMLController def self.hash_password(password) Digest::SHA2.hexdigest(password) end use Rack::Auth::Basic, 'Protected Area' do |username, password| username == 'admin' && hash_password(password) == ENV['TRUNK_APP_ADMIN_PASSWORD'] end configure do enable :method_override # Enable PUT from forms. set :views, settings.root + '/app/views/manage' end configure :development do register Sinatra::Reloader end helpers ManageHelper, Sinatra::UrlForHelper, PeijiSan::ViewHelper register Sinatra::Twitter::Bootstrap::Assets get '/' do redirect to('/disputes?scope=unsettled') end get '/commits' do @collection = Commit.page(params[:page]).order(Sequel.desc(:created_at)) erb :'commits/index' end get '/commits/:id' do @commit = Commit.find(:id => params[:id]) erb :'commits/show' end get '/pods' do pods = Pod.page(params[:page]) pods = pods.where(Sequel.like(:name, /#{params[:name]}/i)) if params[:name] @collection = pods.order(Sequel.asc(:name)) erb :'pods/index' end post '/pods/:name/owners' do pod = Pod.find(:name => params[:name]) owner = Owner.find(:email => params[:email]) if pod && owner unclaimed_owner = Owner.unclaimed DB.test_safe_transaction do if pod.owners == [unclaimed_owner] pod.remove_owner(unclaimed_owner) end pod.add_owner(owner) end redirect to('/pods/' + pod.name) else halt 404 end end get '/pods/:name' do @pod = Pod.find(:name => params[:name]) if @pod erb :'pods/detail' else halt 404 end end post '/owners/delete' do owner = Owner.find(:id => params[:owner]) pod = Pod.find(:id => params[:pod]) pod.remove_owner owner pod.add_owner(Owner.unclaimed) if pod.owners.empty? body owner.to_json end get '/versions' do @collection = PodVersion.page(params[:page]).order(Sequel.desc(:id)) erb :'pod_versions/index' end get '/log_messages' do reference_filter = params[:reference] messages = LogMessage.page(params[:page]) messages = messages.where('reference = ?', reference_filter) if reference_filter @collection = messages.order(Sequel.desc(:id)) erb :'log_messages/index' end get '/disputes' do disputes = Dispute.page(params[:page]) if params[:scope] == 'unsettled' @collection = disputes.where(:settled => false).order(Sequel.asc(:id)) else @collection = disputes.order(Sequel.desc(:id)) end erb :'disputes/index' end get '/disputes/:id' do @dispute = Dispute.find(:id => params[:id]) erb :'disputes/show' end put '/disputes/:id' do @dispute = Dispute.find(:id => params[:id]) @dispute.update(params[:dispute]) SlackController.notify_slack_of_resolved_dispute(@dispute) if params[:dispute][:settled] redirect to("/disputes/#{@dispute.id}") end end end end
use crate::*; #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[repr(C)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Circle<T> { pub center: Point<T>, pub radius: T, } impl<T> Circle<T> { #[inline] pub fn new(center: impl Into<Point<T>>, radius: T) -> Self { Self { center: center.into(), radius, } } } impl<T: ToPrimitive> Circle<T> { #[inline] pub fn cast<U: NumCast>(self) -> Option<Circle<U>> { Some(Circle::new(self.center.cast::<U>()?, U::from(self.radius)?)) } } impl<T> Circle<T> where T: std::ops::Add<T, Output = T> + Copy, { #[inline] pub fn translate(&self, v: impl Into<Vector<T>>) -> Self { let v = v.into(); Self::new(self.center + v, self.radius) } } impl<T> Circle<T> where T: std::ops::Mul<T, Output = T> + Copy, { #[inline] pub fn scale(&self, s: T) -> Self { Self::new(self.center, self.radius * s) } } #[inline] pub fn circle<T>(center: impl Into<Point<T>>, radius: T) -> Circle<T> { Circle::new(center, radius) } #[cfg(test)] mod tests { use super::*; #[test] fn eq_test() { assert!(circle((10, 20), 3) == circle((10, 20), 3)); } #[test] fn translate_test() { assert!(circle((10, 20), 3).translate((1, 2)) == circle((11, 22), 3)); } #[test] fn scale_test() { assert!(circle((10, 20), 3).scale(2) == circle((10, 20), 6)); } }
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.packaging // ATTENTION - keep this in sync with com.android.build.gradle.internal.dsl.PackagingOptions JavaDoc val defaultExcludes: Set<String> = setOf( "/META-INF/LICENSE", "/META-INF/LICENSE.txt", "/META-INF/MANIFEST.MF", "/META-INF/NOTICE", "/META-INF/NOTICE.txt", "/META-INF/*.DSA", "/META-INF/*.EC", "/META-INF/*.SF", "/META-INF/*.RSA", "/META-INF/maven/**", "/META-INF/proguard/*", "/META-INF/com.android.tools/**", "/NOTICE", "/NOTICE.txt", "/LICENSE.txt", "/LICENSE", // Exclude version control folders. "**/.svn/**", "**/CVS/**", "**/SCCS/**", // Exclude hidden and backup files. "**/.*/**", "**/.*", "**/*~", // Exclude index files "**/thumbs.db", "**/picasa.ini", // Exclude javadoc files "**/about.html", "**/package.html", "**/overview.html", // Exclude protobuf metadata files "**/protobuf.meta", // Exclude stuff for unknown reasons "**/_*", "**/_*/**", // Exclude kotlin metadata files "**/*.kotlin_metadata" ) // ATTENTION - keep this in sync with com.android.build.gradle.internal.dsl.PackagingOptions JavaDoc val defaultMerges: Set<String> = setOf("/META-INF/services/**", "jacoco-agent.properties")
expect fun functionNoParameters() expect fun functionSingleParameter(i: Int) expect fun functionTwoParameters(i: Int, s: String) expect fun functionThreeParameters(i: Int, s: String, l: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames1(arg0: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames2(arg0: Int, arg1: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames3(arg0: Int, arg1: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames4(arg0: Int, arg1: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames5(arg0: Int, arg1: String, arg2: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames6(arg0: Int, arg1: String, arg2: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames7(arg0: Int, arg1: String, arg2: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames8(arg0: Int, arg1: String, arg2: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames9(arg0: Int, arg1: String, arg2: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames10(arg0: Int, arg1: String, arg2: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames11(arg0: Int, arg1: String, arg2: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames12(vararg variadicArguments: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames13(arg0: Int, vararg variadicArguments: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames14(arg0: Int, vararg variadicArguments: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames15(arg0: Int, vararg variadicArguments: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames16(i: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames17(i: Int, s: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames18(i: Int, s: String, l: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames19(vararg v: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames20(i: Int, vararg v: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames21(i: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames22(i: Int, s: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames23(i: Int, s: String, l: List<Double>) // hasStableParameterNames=false expect fun functionMismatchedParameterNames24(vararg v: Int) // hasStableParameterNames=false expect fun functionMismatchedParameterNames25(i: Int, vararg v: Int) expect fun functionMismatchedParameterNames26(arg0: Int) expect fun functionMismatchedParameterNames27(arg0: Int, arg1: String) expect fun functionMismatchedParameterNames28(arg0: Int, arg1: String, arg2: List<Double>) expect fun functionMismatchedParameterNames29(vararg variadicArguments: Int) expect fun functionMismatchedParameterNames30(arg0: Int, vararg variadicArguments: Int) expect fun functionMismatchedParameterNames31(i: Int, s: String) expect fun functionMismatchedParameterNames34(i: Int, s: String) expect fun functionMismatchedParameterNames37(arg0: Int, arg1: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames38(i: Int, s: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames39(i: Int, s: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames40(i: Int, s: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames41(arg0: Int, arg1: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames42(arg0: Int, arg1: String) // hasStableParameterNames=false expect fun functionMismatchedParameterNames43(arg0: Int, arg1: String) expect fun overloadedFunctionByParameterNames(i: Int, s: String) expect fun overloadedFunctionByParameterNames(xi: Int, xs: String) expect inline fun inlineFunction1(lazyMessage: () -> String) expect inline fun inlineFunction2(lazyMessage: () -> String) expect inline fun inlineFunction3(crossinline lazyMessage: () -> String) expect inline fun inlineFunction4(lazyMessage: () -> String) expect inline fun inlineFunction5(noinline lazyMessage: () -> String) expect fun functionWithVararg1(vararg numbers: Int) expect fun functionWithVararg5(numbers: Array<out Int>) expect fun functionWithVararg6(vararg names: String) expect fun functionWithVararg10(names: Array<out String>) expect fun <T> functionWithTypeParameters1(p1: T, p2: String) expect fun <Q, R> functionWithTypeParameters4(p1: Q, p2: R)
#include <bits/stdc++.h> using namespace std; int dis[6000][6000], n, a, b, w, q; vector<pair<int,int> > adj[6000]; int main(){ scanf("%d",&n); for(int i=1; i<n;i++){ scanf("%d%d%d", &a,&b,&w); adj[a].push_back(make_pair(b,w)); adj[b].push_back(make_pair(a,w)); } for(int i = 0; i < n; i++){ bool vis[6000]={0}; queue<int> que; que.push(i); vis[i]=1; while(!que.empty()){ int cur=que.front(); que.pop(); for(pair<int,int> p:adj[cur]){ if(!vis[p.first]){ dis[i][p.first]=dis[i][cur]+p.second; vis[p.first]=1; que.push(p.first); } } } } scanf("%d", &q); while(q--){ scanf("%d%d",&a,&b); printf("%lld\n", dis[a][b]); } return 0; }
import { GridColumnTypesRecord } from './gridColTypeDef'; import { GRID_STRING_COL_DEF } from './gridStringColDef'; import { GRID_NUMERIC_COL_DEF } from './gridNumericColDef'; import { GRID_DATE_COL_DEF, GRID_DATETIME_COL_DEF } from './gridDateColDef'; export const DEFAULT_GRID_COL_TYPE_KEY = '__default__'; export const getGridDefaultColumnTypes: () => GridColumnTypesRecord = () => { const nativeColumnTypes = { string: { ...GRID_STRING_COL_DEF }, number: { ...GRID_NUMERIC_COL_DEF }, date: { ...GRID_DATE_COL_DEF }, dateTime: { ...GRID_DATETIME_COL_DEF }, }; nativeColumnTypes[DEFAULT_GRID_COL_TYPE_KEY] = { ...GRID_STRING_COL_DEF }; return nativeColumnTypes; };
'use strict'; import * as angular from "angular"; import "angular-ui-router"; import "angular-material"; import "app/components/sampleOne/index"; import "app/partials/stateControllers/index"; import "app/components/sampleOne/index"; var AppTest = angular.module("appTest", ["ui.router", "stateControllers", "sampleOneComponenet"]); AppTest.config(($stateProvider: angular.ui.IStateProvider, $urlRouterProvider: angular.ui.IUrlRouterProvider) => { $urlRouterProvider.otherwise("/state1"); $stateProvider .state('state1', { url: "/state1", templateUrl: "src/partials/state1.html", controller: 'state1Controller as vm' }) .state('state2', { url: "/state2", templateUrl: "src/partials/state2.html", controller: 'state2Controller as vm' }); }); export {AppTest}
# --- LRR Windows build script --- echo "🎌 Building up LRR Windows Package 🎌" echo "Inferring version from package.json..." $json = (Get-Content "package.json" -Raw) | ConvertFrom-Json $version = $json.version echo "Version is $version" $env:LRR_VERSION_NUM=$version # Use Docker image mv .\package\package.tar .\tools\build\windows\Karen\External\package.tar # Use Karen master cd .\tools\build\windows\Karen echo (Resolve-Path .\).Path nuget restore # Build Karen and Setup msbuild /p:Configuration=Release /p:Platform=x64 Get-FileHash .\Setup\bin\LANraragi.msi | Format-List
<?php class NeverEver extends Game { private $type = Games::NEVEREVER; private $answer; private $question; public function __construct($value) { parent::__construct($value); $this->answer = $value->answer; $this->question = $value->question; } public function getUsername() { return $this->username; } public function getAnswer() { return $this->answer; } public function getMessage() { return $this->message; } public function getFinished() { return $this->finished; } public function getQuestion() { return $this->question; } }
if RUBY_PLATFORM == 'opal' require 'volt/extra_core/logger' else require 'logger' end # Simple global access to the logger. # You can also include Log into a class to get the logger # inside of it. module Log def self.logger @logger = Logger.new(STDOUT) end # Module methods, Log.info... def self.fatal(*args, &block) logger.fatal(*args, &block) end def self.info(*args, &block) logger.info(*args, &block) end def self.warn(*args, &block) logger.warn(*args, &block) end def self.debug(*args, &block) logger.debug(*args, &block) end def self.error(*args, &block) logger.error(*args, &block) end # Included methods, info "something" def fatal(*args, &block) Log.fatal(*args, &block) end def info(*args, &block) Log.info(*args, &block) end def warn(*args, &block) Log.warn(*args, &block) end def debug(*args, &block) Log.debug(*args, &block) end def error(*args, &block) Log.error(*args, &block) end end
import { RGBToRGBArray } from './rgb-to-rgb' import { hexToRGBArray } from './hex-to-rgb' import { HSLtoRGBArray } from './hsl-to-rgb' import { ColorInput, ColorArray } from '../index.types' import { RGBRegex, HSLRegex } from '../constants' export const getColorArray = (color: ColorInput): ColorArray => { const getArrayBasedOnInput = (color: ColorInput): ColorArray => { if (Array.isArray(color)) return color if (typeof color === 'number') return [color, color, color] if (color[0] === '#') return hexToRGBArray(color) if (color.match(RGBRegex)) return RGBToRGBArray(color) if (color.match(HSLRegex)) return HSLtoRGBArray(color) return [0, 0, 0] } const verifyOutput = ([r, g, b, a]: ColorArray): ColorArray => [ Math.min(Math.max(r, 0), 255), Math.min(Math.max(g, 0), 255), Math.min(Math.max(b, 0), 255), Math.min(Math.max(a || 1, 0), 1), ] return verifyOutput(getArrayBasedOnInput(color)) }
#!/bin/bash HOSTNAME=$1 if [ -z "$HOSTNAME" ]; then echo "Usage: docker exec nginx-vhost-proxy /add-ssl-vhost.sh <domain.example.com> [container-port-or-80]" exit 1 fi PORT=$2 if [ -z "$PORT" ]; then PORT=80 fi function sep { echo -e "\n\n####################" } function ifexit { [ "$?" -eq "0" ] || exit 1 } echo "Creating fake virtual-host for certbot webroot checks" WWWDIR=/tmp/www_${HOSTNAME} mkdir -vp ${WWWDIR} ifexit echo "server { \ server_name $HOSTNAME; \ access_log /var/log/nginx/$HOSTNAME.log main; \ root $WWWDIR; \ }" >"/etc/nginx/conf.d/$HOSTNAME.conf" ifexit nginx -t ifexit /etc/init.d/nginx reload ifexit echo "Certbot running in webroot mode for host $HOSTNAME" certbot certonly --webroot --register-unsafely-without-email --agree-tos -w $WWWDIR -d $HOSTNAME -d $HOSTNAME ifexit echo "Adding SSL virtual-host configuration for host $HOSTNAME port $PORT" echo "server { \ server_name $HOSTNAME www.$HOSTNAME; \ access_log /var/log/nginx/$HOSTNAME.log main; \ ssl_certificate /etc/letsencrypt/live/$HOSTNAME/fullchain.pem; \ ssl_certificate_key /etc/letsencrypt/live/$HOSTNAME/privkey.pem; \ include snippets/ssl-params.conf; \ location / { \ proxy_pass http://$HOSTNAME:$PORT; \ } \ } \ " >"/etc/nginx/conf.d/$HOSTNAME.conf" /etc/init.d/nginx restart
json.set! "@type", "SearchResult" json.hits do json.found @search.total json.start @search.start json.hit @search.hits do |hit| json.partial! "v1/search/hit", hit: hit end end json.facets @search.facets do |facet| json.partial! "v1/search/facet", facet: facet end json.sorts @search.sorts do |sort_field| json.partial! "v1/search/sort_field", sort_field: sort_field end
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Entidades; using System; using System.Collections.Generic; using System.Text; namespace Persistencia { public class DB_OverseasContext : IdentityDbContext<AppUser, AppRole, int> { public DB_OverseasContext(DbContextOptions<DB_OverseasContext> options) : base(options) { } public DbSet<Apoderado> Apoderado { get; set; } public DbSet<Asistencia> Asistencia { get; set; } public DbSet<Ambiente> Ambiente { get; set; } public DbSet<Curso> Curso { get; set; } public DbSet<TipoCurso> TipoCurso { get; set; } public DbSet<DetalleApoderadoEstudiante> DetalleApoderadoEstudiante { get; set; } public DbSet<DetalleDocenteEspecialidad> DetalleDocenteEspecialidad { get; set; } public DbSet<Docente> Docente { get; set; } public DbSet<Especialidad> Especialidad { get; set; } public DbSet<Estudiante> Estudiante { get; set; } public DbSet<Evaluacion> Evaluacion { get; set; } public DbSet<TipoEvaluacion> TipoEvaluacion { get; set; } public DbSet<TipoCursoTipoEvaluacion> TipoCursoTipoEvaluacion { get; set; } public DbSet<HistorialEvaluacion> HistorialEvaluacion { get; set; } public DbSet<Horario> Horario { get; set; } public DbSet<Inscripcion> Inscripcion { get; set; } public DbSet<Persona> Persona { get; set; } public DbSet<Sesion> Sesion { get; set; } public DbSet<AppRole> TipoUsuario { get; set; } public virtual DbSet<Traduccion> Traduccion { get; set; } public DbSet<AppUser> Usuario { get; set; } //public DbSet<AppUser> UserRole { get; set; } } }
/* Package table contains functions that use the github.com/Azure/azure-sdk-for-go/sdk/tables/aztable package (see: https://github.com/Azure/azure-sdk-for-go/tree/track2-tables ). While in preview, this must be installed via: go get github.com/Azure/azure-sdk-for-go/sdk/internal@track2-tables go get github.com/Azure/azure-sdk-for-go/sdk/tables/aztable@track2-tables In our sample app, we call these via commands in cmd/table.go. These include: Available Commands: delete ... get ... insert ... insert-kv ... insert-stdin ... query ... query-delete ... table-create ... table-delete ... table-list ... upsert-kv ... In many cases these functions accept JSON, or print JSON to the standard output, which causes them to be optimized for the simple CLI use-case. They are purposely designed to be simple, and able to be borrowed from and tweaked for more complex use-cases. The main convention we have is the use of TableClientFromEnv to create a TableClient from the AZGO_TABLE_ACCOUNT and AZGO_TABLE_KEY environment variables, and optionally the AZGO_TABLE_TYPE variable which can be set to "storage" to connect to a Storage Account rather than Cosmos DB (default). */ package table
#!/usr/bin/bash set -e ################################################################################ ## CMake setup export PYTHONPATH=$PYTHONPATH:@CMAKE_BINARY_DIR@/python export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:@CMAKE_BINARY_DIR@/lib export SCRATCHDIR=@CMAKE_BINARY_DIR@/scratch export GEOMH1=@CMAKE_SOURCE_DIR@/UnitTests/Data/F1.mtx export GEOMO1=@CMAKE_SOURCE_DIR@/UnitTests/Data/S1.mtx export GEOMO2=@CMAKE_SOURCE_DIR@/UnitTests/Data/S2.mtx export GEOMD2=@CMAKE_SOURCE_DIR@/UnitTests/Data/D2.mtx export REALIO=@CMAKE_SOURCE_DIR@/UnitTests/Data/realio.mtx export CholTest=@CMAKE_SOURCE_DIR@/UnitTests/Data/CholTest.mtx cd @CMAKE_BINARY_DIR@/UnitTests # Get Parameters if [ "$#" -ne 4 ] then echo "Illegal number of parameters" exit fi export PROCESS_COLUMNS="$1" export PROCESS_ROWS="$2" export PROCESS_SLICES="$3" export PROCESSES="$4" ## Local Tests if [ $PROCESSES == "1" ] then @PYTHON_EXECUTABLE@ -m unittest -v test_matrix fi ## Matrix Tests @MPIEXEC@ @MPIEXEC_NUMPROC_FLAG@ $PROCESSES @oversubscribe@ \ @PYTHON_EXECUTABLE@ -m unittest -v test_solvers @MPIEXEC@ @MPIEXEC_NUMPROC_FLAG@ $PROCESSES @oversubscribe@ \ @PYTHON_EXECUTABLE@ -m unittest -v test_chemistry @MPIEXEC@ @MPIEXEC_NUMPROC_FLAG@ $PROCESSES @oversubscribe@ \ @PYTHON_EXECUTABLE@ -m unittest -v test_psmatrix @MPIEXEC@ @MPIEXEC_NUMPROC_FLAG@ $PROCESSES @oversubscribe@ \ @PYTHON_EXECUTABLE@ -m unittest -v test_psmatrixalgebra
// Copyright 2015-2016 Sevki <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package builder parses build graphs and coordinates builds package postprocessor import ( "fmt" "log" "os" "path" "path/filepath" "reflect" "strings" "bldy.build/build" "bldy.build/build/label" "bldy.build/build/project" "bldy.build/build/workspace" ) type PostProcessor struct { packagePath string ws workspace.Workspace } // New returns a new PostProcessor func New(ws workspace.Workspace, l label.Label) PostProcessor { pkg := ws.AbsPath() if err := l.Valid(); err != nil { panic(err) } if pkg != "" { pkg = path.Join(pkg, l.Package()) } return PostProcessor{ packagePath: pkg, ws: ws, } } // ProcessDependencies takes relative dependency paths and turns then in to // absolute paths. func (pp *PostProcessor) ProcessDependencies(t build.Rule) error { deps := t.Dependencies() seen := make(map[string]bool) for _, d := range deps { if _, ok := seen[d.String()]; ok { return fmt.Errorf("post process dependencies: %s is duplicated", d) } seen[d.String()] = true } return nil } // ProcessPaths takes paths relative to the target and absolutes them, // unless they are going to be exported in to the target folder from a dependency. func (pp *PostProcessor) ProcessPaths(t build.Rule, deps []build.Rule) error { v := reflect.ValueOf(t) r := reflect.TypeOf(t).Elem() for i := 0; i < r.NumField(); i++ { f := r.Field(i) tag := f.Tag.Get("build") if !(tag == "path" || tag == "expand") { continue } n := v.Elem().FieldByName(f.Name) isExported := func(s string) bool { for _, d := range deps { for _, output := range d.Outputs() { if output == s { return true } } } return false } exp := func(s string) string { if tag == "path" { return pp.absPath(s) } if tag == "expand" { return os.Expand(s, project.Getenv) } return s } switch n.Kind() { case reflect.String: s := n.Interface().(string) if isExported(s) { continue } if s == "" { continue } n.SetString(exp(s)) case reflect.Slice: switch n.Type().Elem().Kind() { case reflect.String: strs := n.Convert(reflect.TypeOf([]string{})).Interface().([]string) for i, s := range strs { if isExported(s) { continue } strs[i] = exp(s) } n.Set(reflect.ValueOf(strs)) } case reflect.Map: switch n.Type().Elem().Kind() { case reflect.String: strs := n.Convert(reflect.TypeOf(map[string]string{})).Interface().(map[string]string) for k, v := range strs { if isExported(k) { continue } delete(strs, k) k, v = exp(k), exp(v) strs[k] = v } n.Set(reflect.ValueOf(strs)) } } } return nil } func (pp *PostProcessor) absPath(s string) string { if len(s) < 2 { log.Fatalf("%s is invalid", s) } var r string switch { case s[:2] == "//": r = filepath.Join(pp.ws.AbsPath(), strings.Trim(s, "//")) default: r = os.Expand(s, project.Getenv) if filepath.IsAbs(r) { return r } r = filepath.Join(pp.ws.AbsPath(), pp.packagePath, s) } r = os.Expand(r, project.Getenv) return r }
package com.ymy.im.module import com.tencent.qcloud.tim.uikit.modules.conversation.base.ConversationInfo import com.ymy.core.bean.FunctionInfo import java.io.Serializable /** * Created on 1/16/21 09:15. * @author:hanxueqiang * @version: 1.0.0 * @desc: */ data class CompanyFunctionData( val companyId: String = "", val companyName: String = "", val functionList: MutableList<FunctionInfo> = mutableListOf(), var functionItemList: MutableList<FunctionItemInfo> = mutableListOf() ) : Serializable data class FunctionItemInfo( val imId: String, val functionInfo: FunctionInfo = FunctionInfo(), var conversationInfo: ConversationInfo? = null, var avater: String = "", var name: String = "", ) { fun initShowData() { var icon = "" var title = "" conversationInfo?.run { if (iconUrlList.isNotEmpty()) { icon = iconUrlList[0].toString() } if (this.title.isNotEmpty()) { title = this.title } } avater = when { functionInfo.avatarUrl.isNotEmpty() -> { functionInfo.avatarUrl } icon.isNotEmpty() -> { icon } else -> { // getAvatarByChannel(functionInfo.channel) "" } } name = when { functionInfo.title.isNotEmpty() -> { functionInfo.title } title.isNotEmpty() -> { title } else -> { "" } } } // private fun getAvatarByChannel(channel: String): String { // // } }
import React, { useCallback } from 'react'; import { withRouter, RouteComponentProps } from 'react-router'; import VelogSearchInput from '../../components/velog/VelogSearchInput'; export interface VelogSearchInputContainerProps extends RouteComponentProps { initial: string; username: string; } function VelogSearchInputContainer({ history, initial, username, }: VelogSearchInputContainerProps) { const onSearch = useCallback( (keyword: string) => { let nextUrl = `/@${username}`; if (keyword) { nextUrl += `/?q=${keyword}`; } history.replace(nextUrl); }, [history, username], ); return <VelogSearchInput initial={initial} onSearch={onSearch} />; } export default withRouter(VelogSearchInputContainer);
## 类型转换 对于`byte`/`short`/`char`三种类型来说,如果右侧赋值的数值没有超过范围,会自动强制类型转换 `byte`/`short`涉及到运算会自动提升为`int`类型 ## 变量赋值 赋值时,若右侧表达式中都是常量,编译时就会直接计算出结果 ## 文件层次 项目 -> 模块 -> 包 -> 文件 ## 函数定义 1. 定义顺序无关 2. 方法定义不能嵌套 3. 定义在类中 4. return的返回值必须与定义的方法类型一致 5. 对于一个void么有返回值的方法,不写return后面的返回值 ## 函数重载 ### 方法重载与下列因素相关 1. 参数不同 2. 参数类型不同 3. 参数的多类型顺序不同 ### 方法重载与下列因素无关 1. 与参数名无关 2. 与返回值类型无关 ## 数组 ### 概念 一个容器,可以存放多个数据值 ### 特点 1. 引用类型 2. 数组元素的类型必须统一 3. 数组长度在程序运行期间不可改变 ### 两种常见的初始化方式 1. 动态初始化(指定长度) 2. 静态初始化(指定内容) #### 动态初始化基本格式 `数据类型[] 数组名称 = new 数据类型[数组长度]` #### 默认值 动态初始化数组时,其中元素会自动拥有一个默认值,默认规则如下: 1. 整数类型,默认为0 2. 浮点类型,默认为0.0 3. 字符类型,默认为'\u0000' 4. 布尔类型,默认为`false` 5. 引用类型,默认为`null` #### 静态初始化基本格式 `数据类型[] 数组名称 = new 数据类型[] { 元素1, 元素2 }` ### 注意事项 1. 静态初始化没有给长度,但会自动推算长度 2. 静态初始化标准格式可以拆分成两个步骤 3. 动态初始化也可以分为两个步骤 4. 静态初始化一旦使用省略模式,就不能拆分成两个步骤了 ## `Java`内存 分为五个部分: 1. 栈(stack):存放的都是方法中的局部变量,方法运行一定要在栈中 局部变量:方法的参数,或者是方法{}内部的变量 作用域:一旦超出作用域,立刻从栈内存中消失 2. 堆(Heap):凡是`new`出来的东西,都在堆中 堆内存里面的东西都有一个地址值:16进制 堆内存里面的数据,都有默认值,规则: 整数 默认为0 浮点数 默认为0.0 字符 默认为'\u0000' 3. 方法区(Method Area):存储class相关信息,包含方法的信息。 4. 本地方法栈(Native Method Stack);与操作系统相关 5. 寄存器(pc Register):与CPU相关 ## 类 ### 成员变量 ```java String name; // 姓名 int age; // 年龄 ``` ### 成员方法 ```java public void eat() { } ``` ### 使用类的步骤 1. 导包,也就是指出需要使用的类在哪儿(在同一个包下的类可以省略导包语句) 2. 通过`new`创建类 3. 用,`.`运算符使用 成员变量没有赋值,将会有一个默认值,规则和数组一样 ### 局部变量和成员变量 1. 定义的位置不一样 局部变量:方法内部 成员变量:方法外部,直接写在类中 2. 作用范围不一样 局部变量:只有方法中可以使用,出了方法不再使用 成员变量:整个类都可以通用 3. 默认值不一样 局部变量:没有默认值,如果想使用,必须进行手动赋值 成员变量:如果没有赋值,会有默认值,规则与数组一样 4. 内存的位置不同 局部变量:跟着方法走,位于栈内存 成员变量:在创建对象时创建成员变量,位于堆内存 5. 生命周期 局部变量:跟着方法走,随着对象出栈而消失 成员变量:随着对象创建而诞生,随着对象被垃圾回收而消失 ## 面向对象 ### 三大特性 封装、继承、多态 ### 访问`private`变量 定义一对`Getter/Setter`方法 必须叫`setXXX`或者`getXXX`命名规则 `boolean`类型的`get`应该用`isXXX` ### `this` 通过谁调用的方法,谁就是`this` ### 构造方法 1. 方法名称与类名一致(包括大小写) 2. 构造方法没有返回值类型 3. 构造方法不能return值 4. 没有构造方法,默认会添加 5. 有自编写构造函数,不会再使用默认的构造方法 ### 标准类的四个组成部分 1. 所有成员变量都使用`private`修饰 2. 每个变量都编写一对`Setter/Getter`方法 3. 编写一个无参数的构造方法 4. 编写一个全参数的构造方法 ## api ### `Scanner` `Scanner`类的功能,可实现键盘输入数据到程序 ### 引用类型的一般步骤: 1. 导包(`java.lang`包下面的内容不需要导包,可以直接使用) 2. 创建 类名称 对象名 = new 类名称 3. 使用 对象名.成员方法名 ### `ArrayList` `ArrayList`使用时,跟着一个尖括号表示泛型,如一个`String`类型的`ArrayList`,可以通过`ArrayList<String>`来表示 对于`ArrayList`来说,直接打印得到的不是地址值,而是内容 ### 包装类与基本类型的对照 | 基本类型 | 包装类 | | -------- | --------- | | byte | Byte | | short | short | | int | Integer | | long | Long | | float | Float | | double | Double | | char | Character | | boolean | Boolean | ## 字符串 ### 字符串常量池 `new`的不在常量池中 直接赋值的字符串在常量池中 ### 字符串中的常用方法 `equals`: 内容是否相等,推荐使用一个字面量字符串.equals(字符串变量) `concat`: 不改变原字符串,返回一个全新的结果 `toCharArray`: 将当前字符转换为一个`char`类型数组 `getBytes`: 获取字符串对应的`char`类型数组的`bytes`类型数组 ### 静态代码块 + 静态代码总是优先于动态代码块执行,静态代码块比构造代码先执行 + 静态代码执行唯一的一次 ### Arrays + `toString` + `sort` 1. 如果是数值,从小到大 2. 如果字符串,默认按字母升序 3. 如果是自定义类型,需要有`Comparable`接口 ### Math + `ceil` (取整的结果是一个`double`类型值,但`double`类型可以++) + `floor` + `round` ## 继承 ### 继承关系的特点 1. 子类可以拥有父类的“内容”; 2. 子类还可以拥有自己专有的 ### 父类、当前类、成员变量重名 + 直接访问(成员变量) + `this.成员变量` (当前类) + `super.成员变量` (父类) ### 重写 & 重载 + 重写 —— 方法名称,参数列表均相同 + 重载 —— 方法名称相同,参数列表不同 #### 方法覆写的注意事项 1. 必须保证父子类之间的方法名称相同,参数列表也相同; 2. 子类方法的返回值必须小于等于父类方法的返回值范围; 3. 子类方法的权限必须大于等于父类方法的权限修饰符。 `public` > `protected` > (`default`) > `private` `default`指关键字什么都不写 #### 重写检测 `@Override`: 写在方法前面,检测是否为有效重载 ### 继承关系中父子构造函数 1. 子类构造函数中,会默认调用一个`super()`方法,以调用父类的构造函数; 2. 父类构造函数中,不再有默认,需要手动`super(args)`传入参数; 3. 只有子类构造方法才能调用父类构造方法,其他方法中不能调用`super()`; 4. 父类调用必须在构造函数的第一个语句 ### 关键字`this` 1. 访问成员变量 2. 访问成员函数 3. 访问本类的另一个构造方法 注意:`this(...)`调用的构造方法必须是第一个;`super`和`this`两种构造方法,只能用一个。 ### Java特点 1. Java语言是单继承的 2. Java语言可以多级继承 3. 一个子类只能有一个父类,一个父类可以有多个子类 ### 抽象方法 1. 在方法前加上`abstract`关键字就行修饰; 2. 抽象方法所在类必须为抽象类; ## 接口 接口就是一种多个类的公共规范 ### 接口的编译 接口编译后生成的字节码文件仍然是:.java -> .class ### 接口中可以包含的内容 1. 常量 (Java7) 2. 抽象方法 (Java7) 3. 默认方法 (Java8) 默认方法可以有方法体,接口中的默认方法,可以解决接口升级的问题,升级接口添加的默认值可以直接在创建的子类中使用 ```java public default 返回值类型 方法名称(参数列表) { 方法体 } ``` 4. 静态方法 (Java8) 5. 私有方法 (Java9) 1. 普通私有方法:解决多个默认方法之间重复代码问题 2. 静态私有方法:解决多个静态方法之间重复代码问题 ### 接口的使用 1. 必须要有`实现类`实现`接口` ```java public class ClassName implements InterfaceName { } ``` 2. 接口的实现必须覆盖重写(实现)接口中的所有抽象方法 3. 创建实现类的对象进行使用 ### 接口中常量的定义 一旦赋值,不能修改 ```java public static final int contantInt = 10; ``` #### `final` 一旦使用`final`关键字进行修饰,说明不可改变 ### 注意事项 1. 接口是没有静态代码块或构造方法的; 2. 一个类可以实现多个接口 3. 如果实现类的所实现的接口中存在重复方法,只需要覆盖一次即可 4. 如果实现类的所实现接口中存在重复默认方法,必须进行覆盖处理 5. 一个类如果是直接父类中的方法,和接口当中默认方法产生了冲突,优先使用父类当中的方法 ### 接口继承 1. 多个父接口当中的抽象方法如果重复,没有关系 2. 多个接口中的默认方法如果重复,必须进行重写。【重写带着default关键字】 ## 多态 父类引用指向子类对象 格式: 父类对象 对象名 = new 子类名称(); 或者: 接口名称 对象名 = new 实现类名称(); ### 通过父类定义的对象名访问方法和成员变量 + 访问方法看`new`, `new`谁调用的就是谁 + 访问变量看等号左边,左边是谁,优先是谁,没有则向上找 ### 对象转型 + 向上转型(多态写法)—— 向上转型一定安全,因为是从小范围 -> 大范围 + 向下转型 (还原) ```java 子类名称 对象名 = (子类名称) 父类对象名; ``` ## `final` 1. 修饰类 —— 修饰后类不会有任何子类 2. 修饰方法 —— 子类不能再覆盖重写 3. 修饰局部变量 —— 局部变量为常量 4. 修饰成员变量 —— 与局部变量相比,有默认值,所以使用`final`即需要手动赋值,构造函数中也可以进行赋值 对于子类、方法来说,`abstract`关键字和`final`关键字不能同时使用,因为矛盾 ## 四种权限修饰符 | | public | protected | (default) | private | | ------------ | ------ | --------- | --------- | ------- | | 同一个类 | YES | YES | YES | YES | | 同一个包 | YES | YES | YES | NO | | 不同包子类 | YES | YES | NO | NO | | 不同包非子类 | YES | NO | NO | NO | ## 内部类 1. 成员内部类 2. 局部内部类 内用外,随意访问,外用内,需要借助内部对象 ### 内部类的使用 1. 间接方式:在外部类的方法中使用内部类,然后通过调用外部类的方式使用 2. 直接访问,格式: ```java 外部类名称.内部类名称 对象名 = new 外部类名称().new 内部类名称(); ``` ### 命名冲突 内部类访问外部类的重名变量: `外部类.this.变量名` ### 局部内部类 只有当前所属的方法才能使用 ### 类的权限修饰符 public > protected > (default) > private 定义一个类时,权限修饰符规则: 1. 外部类:public / (default) 2. 成员内部类:public / protected / (default) / private 3. 局部内部类:什么都不能写,因为只能所属方法才能访问 ### 匿名内部类 1. 适用场景 —— 接口或抽象类只需要实现一次 ### 注意事项 1. 匿名内部类只会在创建对象时调用一次; ## DateFormate 抽象类,常用实现的类`SimpleDateFormate` ## StringBuilder 字符串缓冲区,可以提高字符串的操作效率 底层也是一个数组,但没有被`final`修饰,但字符串是被`final`修饰的,因此字符串加法中,会存在多个字符串,影响效率 ## `Collection`架构 ![整体架构](./assets/java/Collection.png) ### `Collection`常用功能 + `add` + `clear` + `remove` + `contains` + `isEmpty` + `size` + `toArray` ### `Iterator`迭代器 取出元素的一种通用方法,是一个接口,无法直接使用,需要使用`Iterator`接口的实现类对象 + `boolean hasNext()` —— 如果仍有元素可以迭代,则返回`true` + `next` —— 取出元素中的下一个元素 ### 使用步骤 1. 使用集合中的方法`iterator()`获取迭代器的实现类对象,使用`iterator`接口接受; 2. 使用`iterator`接口中的方法`hasNext()`判断是否可以继续迭代; 3. 使用`iterator`接口中的`next`方法获取集合中下一个元素 ## 泛型 + `E` —— element元素 + `T` —— type 类型 ### 含有泛型的类 ```java public class Test<E> {} ``` ### 含有泛型的函数 ```java public <E> void print(E e1, E e2) {} ``` ### 通配符 一般不知道接收的类型应该是哪个,选`?`作为通配符接收,一般泛型是没有继承概念的 ### 上限及下限 + `泛型的上限限定`: ? extends E —— 代表使用的泛型只能是E类型的子类/自身 + `泛型的下限限定`: ? super E —— 代表使用的泛型只能是E类型的父类/自身 ## 数据结构 ### 红黑树 特点:趋近于平衡树,查询的速度非常快,查询叶子节点最大次数和最小次数不能超过二倍 #### 约束 1. 节点可以是红色或者黑色的; 2. 根节点是黑色的; 3. 叶子节点(空节点)是黑色的; 4. 每个红色的节点的子节点都是黑色的; 5. 任何一个节点到其每个叶子节点的路径上黑色节点相同。 ## `Collection` ### `List`特点 1. 有序的集合; 2. 索引:包含一些索引的方法; 3. 允许存储重复元素. ### `ArrayList`与`LinkedList`对比 `ArrayList`底层为数组实现,查询快,增删慢 `LinkedList`底层为链表实现,增删快,查询慢 ### `Set`特点 1. 无序集合; 2. 没有索引; 3. 不允许重复元素. #### `HashSet`的特点 1. 不允许存储重复元素; 2. 没有索引,没有带索引的方法,无法使用普通for循环进行遍历; 3. 无序,存取顺序可能不一致; 4. 底层通过哈希表实现. ### `HashSet`底层实现原理 `Set`集合在调用`add`方法时,`add`方法会调用元素的`hashCode`方法和`equals`方法,判断元素是否重复 ### `LinkedHashMap`与`HashMap`的区别 `LinkedHashMap`存储的数据是有序的 ## 可变参数 当方法的参数列表已经确定,参数的个数不确定,就可以使用可变参数
import _ from 'lodash/fp' export let isTraversable = x => _.isArray(x) || _.isPlainObject(x) export let traverse = x => isTraversable(x) && !_.isEmpty(x) && x
module PlanSpec where import Control.Lens import Control.Monad import Data.Either import Data.Maybe import Data.Time import Instances () import Plan.Env import Plan.Functions import Plan.Plan import Plan.Task import Test.Hspec import Test.QuickCheck import TestData spec :: SpecWith () spec = describe "Planning" $ do it "removes overdue tasks and tasks with no time needed, unless they are recurring" $ property $ \(c, s) -> do (e, c') <- runMonads' printPlan c $ Env c s when (isRight e) $ length (c' ^. tasks) & shouldBe $ length $ filter (\x -> localDay (s ^. time) <= x ^. deadline && x ^. timeNeeded > 0 || isJust (x ^. recur)) $ c ^. tasks it "only fails for empty task lists, unless there isn't enough time" $ property $ \(c, s) -> do (e, c') <- runMonads' printPlan c $ Env c s when (isLeft e) $ shouldBe 0 $ length $ flip filter (c' ^. tasks) $ \x -> timeOfDayToTime (localTimeOfDay (s ^. time)) + picosecondsToDiffTime (timeNeededToday (s ^. time) x) <= timeOfDayToTime (TimeOfDay 23 59 59) it "prints simple tasks consecutively" $ do (Right r, _) <- runMonads' printPlan con1 $ Env con1 baseSit r `shouldBe` "3) 15:00-16:00: C\n\ \2) 16:00-17:00: B\n\ \1) 17:00-18:00: A" it "prints simple tasks in importance order" $ do (Right r, _) <- runMonads' printPlan con2 $ Env con2 baseSit r `shouldBe` "1) 15:00-16:00: A\n\ \2) 16:00-17:00: B\n\ \3) 17:00-18:00: C" it "gives 20 minutes for a 6 day, 2 hour task" $ do (Right r, _) <- runMonads' printPlan con3 $ Env con3 baseSit r `shouldBe` "1) 15:00-15:20: A" it "gives starting time as current time if currently working on task" $ do (Right r, _) <- runMonads' printPlan con4 $ Env con4 $ Situation ".plan.yaml" middleTime r `shouldBe` "1) 13:30-14:00: A" it "prints that tasks are done" $ do (Right r, _) <- runMonads' printPlan con4 $ Env con4 baseSit r `shouldBe` "Some tasks are finished for today:\n\ \1) A" it "prints both tasks that are done and not done" $ do (Right r, _) <- runMonads' printPlan con5 $ Env con5 baseSit r `shouldBe` "2) 15:00-16:00: B\n\ \Some tasks are finished for today:\n\ \1) A" it "correctly updates for new days" $ do (Right r, _) <- runMonads' printPlan con6 $ Env con6 $ Situation ".plan.yaml" daysLater r `shouldBe` "1) 15:00-15:30: A"
using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.Metadata; namespace WalletWasabi.Fluent; public class DataTemplateSelector : IDataTemplate { public IControl Build(object param) { return Templates.FirstOrDefault()?.Build(param) ?? new TextBlock {Text = "Not found "}; } public bool Match(object data) { return true; } [Content] public IEnumerable<IDataTemplate> Templates { get; set; } = new List<IDataTemplate>(); }
; Yul Library ; ; Copyright (C) 2022 Kestrel Institute (http://www.kestrel.edu) ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: Alessandro Coglio ([email protected]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "YUL") (include-book "renaming-variables") (include-book "renaming-functions") (include-book "unique-variables") (include-book "unique-functions") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defxdoc+ disambiguator :parents (transformations) :short "The @('Disambiguator') transformation." :long (xdoc::topstring (xdoc::p "The @('Disambiguator') transformation described in [Solidity: Internals: The Optimizer: Yul-Based Optimizer Module: Preprocessing: Disambiguator], makes all the variable and function names globally unique by renaming them.") (xdoc::p "Conceptually, this transformation could be split into two: one that disambiguates variables, and one that disambiguates functions; the two are independent, and can be applied in any order. We follow this approach, by formalizing the disambiguation of variables and functions separately, and by defining @('Disambiguator') as their combination.") (xdoc::p "There are many possible ways to rename variables or functions so that they are globally unique. To avoid committing to a specific renaming approach, we characterize these transformations relationally instead of functionally: instead of defining a function that turns the original code into the transformed code, we define a predicate over original and transformed code that holds when the two have the same structure except for possibly the variable or function names.") (xdoc::p "This relational formulation of the disambiguation of variables and functions opens the door to defining each as the combination of a renaming relation that may or may not yield globally unique names, and an additional uniqueness requirement on the transformed code. Thus, the @('Disambiguator') transformation is characterized relationally as the combination of " (xdoc::seetopic "renaming-variables" "variable renaming") ", " (xdoc::seetopic "renaming-functions" "function renaming") ", " (xdoc::seetopic "unique-variables" "variable uniqueness") ", and " (xdoc::seetopic "unique-functions" "function uniqueness") ".")) :order-subtopics t :default-parent t) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; TODO: define the relation
/* * (c) Copyright 2012 EVRYTHNG Ltd London / Zurich * www.evrythng.com */ #if !defined(_MQTT_MARVELL_) #define _MQTT_MARVELL_ #include <stddef.h> #include <wm_os.h> #include <wm_mbedtls_helper_api.h> #include "FreeRTOS.h" #include "task.h" typedef struct Timer { portTickType xTicksToWait; xTimeOutType xTimeOut; } Timer; typedef struct Network { int socket; int tls_enabled; const char* ca_buf; size_t ca_size; wm_mbedtls_cert_t tls_cert; mbedtls_ssl_config* tls_config; mbedtls_ssl_context* tls_context; } Network; typedef struct Mutex { os_mutex_t mutex; } Mutex; typedef struct Semaphore { os_semaphore_t sem; } Semaphore; typedef struct Thread { os_thread_t tid; void* arg; void (*func)(void*); Semaphore join_sem; } Thread; #endif //_MQTT_MARVELL_
php-casperjs ============ [![Travis branch](https://img.shields.io/travis/alwex/php-casperjs/stable.svg)]() [![Packagist](https://img.shields.io/packagist/dt/phpcasperjs/phpcasperjs.svg?maxAge=2592000)]() [![Version](http://img.shields.io/packagist/v/phpcasperjs/phpcasperjs.svg?style=flat)](https://packagist.org/packages/phpcasperjs/phpcasperjs) [![License](http://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/64289c40-f11c-49ef-b295-2e7ec784d64a/big.png)](https://insight.sensiolabs.com/projects/64289c40-f11c-49ef-b295-2e7ec784d64a) php-casperjs is a simple PHP wrapper for the fine library CasperJS designed to automate user testing against web pages. It is easy to integrate into PHPUnit test case. Making webcrawler has never been so easy! Installation ------------ Before using php-casperjs, you need to install both library: 1 - **PhantomJS** http://phantomjs.org/download.html 2 - **CasperJS** http://docs.casperjs.org/en/latest/installation.html ```shell npm install phantomjs npm install casperjs ``` then ```shell composer require phpcasperjs/phpcasperjs ``` Usage ----- ```php <?php use Browser\Casper; $casper = new Casper(); // forward options to phantomJS // for example to ignore ssl errors $casper->setOptions([ 'ignore-ssl-errors' => 'yes' ]); // navigate to google web page $casper->start('http://www.google.com'); // fill the search form and submit it with input's name $casper->fillForm( 'form[action="/search"]', array( 'q' => 'search' ), true); // or with javascript selectors: $casper->fillFormSelectors( 'form.form-class', array( 'input#email-id' => 'user-email', 'input#password-id' => 'user-password' ),true); // wait for 5 seconds (have a coffee) $casper->wait(5000); // wait for text if needed for 3 seconds $casper->waitForText('Yahoo', 3000); // or wait for selector $casper->waitForSelector('.gbqfb', 3000); // make a screenshot of the google logo $casper->captureSelector('#hplogo', '/tmp/logo.png'); // or take a screenshot of a custom area $casper->capture( array( 'top' => 0, 'left' => 0, 'width' => 800, 'height' => 600 ), '/tmp/custom-capture.png' ); // click the first result $casper->click('h3.r a'); // switch to the first iframe $casper->switchToChildFrame(0); // make some stuff inside the iframe $casper->fillForm('#myForm', array( 'search' => 'my search', )); // go back to parent $casper->switchToParentFrame(); // run the casper script $casper->run(); // check the urls casper get through var_dump($casper->getRequestedUrls()); // need to debug? just check the casper output var_dump($casper->getOutput()); ``` If you want to see your crawler in action, set the engine to slimerjs ```php $casper = new Casper(); $casper->setOptions(['engine' => 'slimerjs']); ```
#pragma once #include <vector> #include "items/item.hpp" #include "../types.hpp" #include "../non_copyable.hpp" #include "../definitions/grass_effect_definition.hpp" namespace space { class Area; class GameSession; class AreaInstances : private NonCopyable { public: // Fields // Constructor // Methods void addPostLoadObject(const ObjectId &id) { _onPostLoadObjects.emplace_back(id); } void applyToArea(Area &area, GameSession &session) const; private: // Fields std::vector<ObjectId> _onPostLoadObjects; // Methods }; } // space
// DomApi // --------- import _ from 'underscore'; import Backbone from 'backbone'; // Performant method for returning the jQuery instance function getEl(el) { return el instanceof Backbone.$ ? el : Backbone.$(el); } // Static setter export function setDomApi(mixin) { this.prototype.Dom = _.extend({}, this.prototype.Dom, mixin); return this; } export default { // Returns a new HTML DOM node instance createBuffer() { return document.createDocumentFragment(); }, // Lookup the `selector` string // Selector may also be a DOM element // Returns an array-like object of nodes getEl(selector) { return getEl(selector); }, // Finds the `selector` string with the el // Returns an array-like object of nodes findEl(el, selector, _$el = getEl(el)) { return _$el.find(selector); }, // Returns true if the el contains the node childEl hasEl(el, childEl) { return el.contains(childEl && childEl.parentNode); }, // Detach `el` from the DOM without removing listeners detachEl(el, _$el = getEl(el)) { _$el.detach(); }, // Remove `oldEl` from the DOM and put `newEl` in its place replaceEl(newEl, oldEl) { if (newEl === oldEl) { return; } const parent = oldEl.parentNode; if (!parent) { return; } parent.replaceChild(newEl, oldEl); }, // Swaps the location of `el1` and `el2` in the DOM swapEl(el1, el2) { if (el1 === el2) { return; } const parent1 = el1.parentNode; const parent2 = el2.parentNode; if (!parent1 || !parent2) { return; } const next1 = el1.nextSibling; const next2 = el2.nextSibling; parent1.insertBefore(el2, next1); parent2.insertBefore(el1, next2); }, // Replace the contents of `el` with the HTML string of `html` setContents(el, html, _$el = getEl(el)) { _$el.html(html); }, // Takes the DOM node `el` and appends the DOM node `contents` // to the end of the element's contents. appendContents(el, contents, {_$el = getEl(el), _$contents = getEl(contents)} = {}) { _$el.append(_$contents); }, // Does the el have child nodes hasContents(el) { return !!el && el.hasChildNodes(); }, // Remove the inner contents of `el` from the DOM while leaving // `el` itself in the DOM. detachContents(el, _$el = getEl(el)) { _$el.contents().detach(); } };
package org.springframework.beans.support; /** * @since 29.07.2004 */ public class DerivedFromProtectedBaseBean extends ProtectedBaseBean { }
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # mount RailsAdmin::Engine => '/teacher', as: 'rails_admin' resources :subjects resources :staffs resources :students resources :faculties resources :users resources :courses resources :sections resources :subscriptions, only: [:create, :destroy] # get 'sections/:id/courses/:id' => 'courses#show', as: 'section_course' # resources :subjects, shallow: true do # resources :courses # end # # resources :courses, shallow: true do # resources :sections # end # # resources :sections, shallow: true do # resources :students # end # ----------------------Routes for course subscription -------------------------- put 'courses/:id/enroll' => 'courses#enroll', as: 'enroll' get 'courses/:id/exit' => 'subscriptions#destroy', as: 'leave_course' # -------------------------------------------------------------------------------- # --------------------------- Routes for the static pages ------------------------- root 'static_pages#index' # --------------------------------------------------------------------------------- # ------------------------------Dashboard Routes----------------------------------- resources :dashboard, only: [:index] get 'dashboard/home' => 'dashboard#home' get 'dashboard/courses' => 'dashboard#courses' # --------------------------------------------------------------------------------- #Single Sign On Routes match 'login', to: 'sessions#new', as: 'login', via: [:get, :post] match '/create_session', to: 'sessions#create', as: 'create_session', via: [:get, :post] match 'signout', to: 'sessions#destroy', as: 'signout', via: [:get, :post] #--------------------------------Survey Plugin & System-------------------------------- # scope module: 'contests' do # resources :surveys # resources :attempts # end # # match '/surveys/new', to: 'contests/surveys#new', as: 'new_question', via: [:get, :post] # get '/surveys/', to: 'contests/surveys#show', as: 'contests_surveys', via: [:get, :post] # get '/surveys/:id', to: 'contests/surveys#show', as: 'show_survey', via: [:get, :post] # ------------------------------------------------------------------------------------------ end
using MpcCore.Contracts.Mpd; using System; namespace MpcCore.Mpd { public class Status : IStatus { /// <summary> /// Status has error /// </summary> public bool HasError => Error != null; /// <summary> /// Mpd playback is running /// </summary> public bool IsPlaying => State == "play"; /// <summary> /// Mpd playback is paused /// </summary> public bool IsPaused => State == "pause"; /// <summary> /// Mpd playback is stopped /// </summary> public bool IsStopped => State == "stop"; /// <summary> /// The current partition /// </summary> public string Partition { get; internal set; } /// <summary> /// Current volume. /// 0 if it can not be determined. /// </summary> public int Volume { get; internal set; } /// <summary> /// Repeat mode /// </summary> public bool Repeat { get; internal set; } /// <summary> /// Random mode /// </summary> public bool Random { get; internal set; } /// <summary> /// Single /// </summary> public bool Single { get; internal set; } /// <summary> /// Consume mode (tracks are removed from the queue after playing) /// </summary> public bool Consume { get; internal set; } /// <summary> /// Playlist version number /// </summary> public int Playlist { get; internal set; } /// <summary> /// Playlist length /// </summary> public int PlaylistLength { get; internal set; } /// <summary> /// play, pause or stop /// </summary> public string State { get; internal set; } = string.Empty; /// <summary> /// Playlist/queue number of the item currently playing or stopped /// </summary> public int Song { get; internal set; } /// <summary> /// Playlist/queue item id of the item currently playing or stopped /// </summary> public int SongId { get; internal set; } /// <summary> /// Playlist/queue item number of the item after the one currently playing or stopped /// </summary> public int NextSong { get; internal set; } /// <summary> /// Playlist/queue item id of the item after the one currently playing or stopped /// </summary> public int NextSongId { get; internal set; } /// <summary> /// Total time elapsed within the current item in seconds, with higher resolution than "time" used to have. /// </summary> public double Elapsed { get; internal set; } /// <summary> /// Duration of the current item in seconds /// </summary> public double Duration { get; internal set; } /// <summary> /// Instantaneous bitrate in kbps /// </summary> public int Bitrate { get; internal set; } /// <summary> /// Crossfade setting in seconds /// </summary> public int Crossfade { get; internal set; } /// <summary> /// Threshold in dB /// </summary> public double MixRampDb { get; internal set; } /// <summary> /// Mixrampdelay in dB /// </summary> public int MixRampDelay { get; internal set; } /// <summary> /// Jobid if an update is running /// </summary> public int UpdateJobId { get; internal set; } /// <summary> /// Error in case there is one /// </summary> public IMpdError Error { get; internal set; } /// <summary> /// The format emitted by the decoder plugin during playback /// </summary> public IAudio AudioSetting { get; internal set; } } }
// Copyright 2017 Mikio Hara. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tcpopt_test import ( "log" "net" "time" "github.com/mikioh/tcp" "github.com/mikioh/tcpopt" ) func ExampleOption() { c, err := net.Dial("tcp", "golang.org:80") if err != nil { log.Fatal(err) } defer c.Close() tc, err := tcp.NewConn(c) if err != nil { log.Fatal(err) } if err := tc.SetOption(tcpopt.KeepAlive(true)); err != nil { log.Fatal(err) } if err := tc.SetOption(tcpopt.KeepAliveIdleInterval(3 * time.Minute)); err != nil { log.Fatal(err) } if err := tc.SetOption(tcpopt.KeepAliveProbeInterval(30 * time.Second)); err != nil { log.Fatal(err) } if err := tc.SetOption(tcpopt.KeepAliveProbeCount(3)); err != nil { log.Fatal(err) } }
import type { NextApiRequest, NextApiResponse } from "next"; import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient(); export default async function handler( req: NextApiRequest, res: NextApiResponse ) { let { id } = req.query; if (!id || typeof id !== "string") { res .status(400) .send({ ok: false, error: "Request must contain a `customerId`" }); } else { try { let customer = await prisma.customer.findUnique({ where: { id } }); if (!customer) { res .status(404) .send({ ok: false, error: `"No customer found for id "${id}"` }); return; } let subscription = await prisma.subscription.findFirst({ where: { customer_id: id }, }); let lastInvoice = subscription && (await prisma.invoice.findFirst({ where: { subscription_id: subscription.id }, orderBy: { created: "desc" }, })); let paymentMethodId = customer.invoice_settings_default_payment_method_id; let paymentMethod = paymentMethodId && (await prisma.payment_method.findUnique({ where: { id: paymentMethodId }, })); let charges = await prisma.charge.findMany({ where: { customer_id: id, receipt_url: { not: null } }, orderBy: { created: "desc" }, include: { payment_method: true }, }); res.status(200).send({ ok: true, customer, subscription, lastInvoice, paymentMethod, charges, }); } catch (e) { console.error(e); res.status(400).send({ ok: false, error: "Error querying the database" }); } } } // @ts-ignore BigInt.prototype.toJSON = function () { return this.toString(); };
// Copyright 2014-2015 Matthew Endsley // All rights reserved // // Redistribution and use in source and binary forms, with or without // modification, are permitted providing that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package mnet import ( "bytes" "crypto/hmac" crand "crypto/rand" "crypto/sha1" "encoding/binary" "errors" "fmt" "hash/adler32" "net" "sync" "time" ) var ErrListenerClosed = errors.New("Listener has been closed") type listener struct { sync.Cond err error addr net.Addr pending []net.Conn stopListening func() } // Listen announces on the local network address laddr. // The network net must be a packet-oriented netowrk: // "udp", "udp4", "udp6", "unixgram". func Listen(network, addr string) (net.Listener, error) { conn, err := net.ListenPacket(network, addr) if err != nil { return nil, err } return ListenConn(conn) } // Listen announces on existing packet-based connection func ListenConn(conn net.PacketConn) (net.Listener, error) { l := &listener{ Cond: sync.Cond{ L: new(sync.Mutex), }, addr: conn.LocalAddr(), } rld := &receiveLoopData{ Cond: sync.Cond{ L: new(sync.Mutex), }, buffers: [][]byte{ make([]byte, 65536), make([]byte, 65536), make([]byte, 65536), }, } pld := &processLoopData{ Cond: sync.Cond{ L: new(sync.Mutex), }, } l.stopListening = func() { pld.L.Lock() pld.rejectNewConnections = true pld.L.Unlock() pld.Signal() } go receiveLoop(conn, l, rld, pld) go processLoop(conn, l, rld, pld) return l, nil } // Close the listener. Stops accepting new // connections, but will continue to process // established connections. func (l *listener) Close() error { l.L.Lock() err := l.err if err == nil { l.err = ErrListenerClosed } l.L.Unlock() l.Broadcast() if err == nil { l.stopListening() } return errors.New("Not implemented") } // Accept blocks until a new connection is ready, // then returns that connection to the caller. func (l *listener) Accept() (net.Conn, error) { l.L.Lock() defer l.L.Unlock() for l.err == nil && len(l.pending) == 0 { l.Wait() } if l.err != nil { return nil, l.err } c := l.pending[0] n := copy(l.pending, l.pending[1:]) l.pending = l.pending[:n] return c, nil } // Addr returns the local address for the listener. func (l *listener) Addr() net.Addr { return l.addr } type receiveLoopData struct { sync.Cond buffers [][]byte } // receives datagrams from a connection and enqueues them to // the processing loop func receiveLoop(c net.PacketConn, l *listener, rld *receiveLoopData, pld *processLoopData) { // wait for a buffer to be available for { rld.L.Lock() for len(rld.buffers) == 0 { rld.Wait() } n := len(rld.buffers) buffer := rld.buffers[n-1] rld.buffers = rld.buffers[:n-1] rld.L.Unlock() n, addr, err := c.ReadFrom(buffer[:cap(buffer)]) if err != nil { l.L.Lock() if l.err == nil { l.err = err } l.L.Unlock() l.Broadcast() // notify the processing loop pld.L.Lock() pld.err = err pld.L.Unlock() pld.Signal() return } if n < 4 { continue } // push the packet to the processing loop pld.L.Lock() pld.Q = append(pld.Q, processLoopPacket{D: buffer[:n], A: addr}) pld.L.Unlock() pld.Signal() } } type processLoopPacket struct { D []byte A net.Addr } type processLoopData struct { sync.Cond err error rejectNewConnections bool remainingConnections int Q []processLoopPacket } // receives packets from the receive loop and dispatches them // to their corresponding connections func processLoop(c net.PacketConn, l *listener, rld *receiveLoopData, pld *processLoopData) { var ( quit bool wg = new(sync.WaitGroup) tq = newTimerQueue() connections = struct { sync.RWMutex M map[uint32]*connection }{ M: make(map[uint32]*connection), } ) // keep a refcount to `c` for ourselves wg.Add(1) defer wg.Done() // wait for all pending connections, then close the socket go func() { wg.Wait() c.Close() tq.Close() }() // generate a new key for cookies cookieKey := make([]byte, sha1.Size) if _, err := crand.Read(cookieKey); err != nil { l.L.Lock() l.err = fmt.Errorf("Failed to generate cookie secret: %v", err) l.L.Unlock() l.Broadcast() return } sig := hmac.New(sha1.New, cookieKey) // generate addler32(localaddr) var localAddrSum [4]byte binary.LittleEndian.PutUint32(localAddrSum[:], adler32.Checksum([]byte(c.LocalAddr().String()))) shouldWait := func() bool { waitOnConnections := pld.rejectNewConnections && pld.remainingConnections == 0 return pld.err == nil && len(pld.Q) == 0 && !waitOnConnections } var packets []processLoopPacket for !quit { // wait for a packet to become available pld.L.Lock() for shouldWait() { pld.Wait() } rejectNewConnections := pld.rejectNewConnections pldErr := pld.err quit = pldErr != nil packets, pld.Q = pld.Q, packets[:0] remainingConnections := pld.remainingConnections pld.L.Unlock() if rejectNewConnections && remainingConnections == 0 { quit = true } // process packets for ii := range packets { buffer, addr := packets[ii].D, packets[ii].A switch PacketType(buffer[0]) { case PacketInit: // are we accepting new connections? if rejectNewConnections { continue } // verify length const MinInitPacketLength = 9 if len(buffer) < MinInitPacketLength { continue } // verify protocol magic if !bytes.Equal(buffer[1:5], protocolMagic) { continue } // verify version if buffer[5] != version1 { sendAbort(c, addr, buffer[6:9]) continue } var outgoing [32]byte now := time.Now() outgoing[0] = byte(PacketCookie) if _, err := crand.Read(outgoing[1:4]); err != nil { return } copy(outgoing[4:7], buffer[6:9]) outgoing[7] = version1 binary.LittleEndian.PutUint32(outgoing[8:12], uint32(now.Add(5*time.Second).Unix()+1)) sig.Reset() sig.Write(outgoing[1:12]) sig.Write(localAddrSum[:]) sig.Sum(outgoing[1:12]) c.WriteTo(outgoing[:], addr) case PacketCookieEcho: // are we accepting new connections if rejectNewConnections { continue } // verify length const CookieEchoPacketLength = 32 if len(buffer) != CookieEchoPacketLength { continue } // verify signature sig.Reset() sig.Write(buffer[1:12]) sig.Write(localAddrSum[:]) if !hmac.Equal(sig.Sum(nil), buffer[12:]) { continue } // verify version if buffer[7] != version1 { sendAbort(c, addr, buffer[1:4]) continue } // vetify timeout now := time.Now() if time.Unix(int64(binary.LittleEndian.Uint32(buffer[8:12])), 0).Before(now) { sendAbort(c, addr, buffer[1:4]) continue } // decode connection tag to uin32 tagId := binary.LittleEndian.Uint32(buffer[3:7]) >> 8 connections.RLock() _, ok := connections.M[tagId] connections.RUnlock() // create new connection if !ok { // create connection wg.Add(1) connections.Lock() conn := newConnection(c, addr, tq, buffer[1:4], func() { connections.Lock() delete(connections.M, tagId) connections.Unlock() wg.Done() pld.L.Lock() pld.remainingConnections-- remain := pld.remainingConnections pld.L.Unlock() if remain == 0 { pld.Signal() } }) connections.M[tagId] = conn connections.Unlock() pld.L.Lock() pld.remainingConnections++ pld.L.Unlock() l.L.Lock() l.pending = append(l.pending, conn) l.L.Unlock() l.Signal() } // send COOKIE-ACK var outgoing [4]byte outgoing[0] = byte(PacketCookieAck) copy(outgoing[1:4], buffer[1:4]) c.WriteTo(outgoing[:], addr) default: // parse connection tag tagId := binary.LittleEndian.Uint32(buffer[0:4]) >> 8 connections.RLock() conn, ok := connections.M[tagId] connections.RUnlock() // discard packets addressed to unknown connections if !ok { sendAbort(c, addr, buffer[1:4]) continue } // copy the packet data so we can reuse the buffer p := NewPacket(len(buffer)) copy(p.D, buffer) // queue the packet onto the connection conn.L.Lock() conn.Incoming = append(conn.Incoming, p) conn.L.Unlock() conn.Signal() } } // return the packet to the receive loop rld.L.Lock() for ii := range packets { rld.buffers = append(rld.buffers, packets[ii].D) } rld.L.Unlock() rld.Signal() // if we were signaled to quit, terminate existing connections if pldErr != nil { connections.Lock() m := connections.M connections.M = make(map[uint32]*connection) connections.Unlock() for _, c := range m { c.closeWithError(pldErr) } } } } // sends an ABORT packet to the specified peer func sendAbort(c net.PacketConn, addr net.Addr, tag []byte) { p := NewPacket(4) p.D[0] = byte(PacketAbort) copy(p.D[1:4], tag) c.WriteTo(p.D, addr) p.Free() }