text
stringlengths
27
775k
module TopologicalInventory::Amazon class Parser module Reservation def parse_reservations(reservation, scope) uid = reservation.reserved_instances_id flavor = lazy_find(:flavors, :source_ref => reservation.instance_type) collections[:reservations].data << TopologicalInventoryIngressApiClient::Reservation.new( :source_ref => uid, :extra => { :availability_zone => reservation.availability_zone, :instance_count => reservation.instance_count, :instance_type => reservation.instance_type, :product_description => reservation.product_description, :state => reservation.state, :usage_price => reservation.usage_price, :currency_code => reservation.currency_code, :instance_tenancy => reservation.instance_tenancy, :offering_class => reservation.offering_class, :offering_type => reservation.offering_type, :recurring_charges => reservation.recurring_charges.map(&:to_h), :scope => reservation.scope, }, :state => reservation.state, :start => reservation.start, :end => reservation.end, :flavor => flavor, :source_region => lazy_find(:source_regions, :source_ref => scope[:region]), :subscription => lazy_find_subscription(scope), ) parse_tags(:reservations, uid, reservation.tags) end end end end
/** * @file `await` instrumentation analysis */ var p = (_dbux.traceExpr(30, (_sleep = sleep)), _dbux.t(31), _dbux.traceExpr(33, _sleep(_dbux.traceArg(32, 800)))); // var p = f(); /** * Order: * f() > preAwait > wrapAwait ---> postAwait */ var arg; var awaitContextId; _dbux.postAwait( arg = f(), await _dbux.wrapAwait( arg, // argument (awaitContextId = _dbux.preAwait(staticId, preTraceId)) ), _contextId5, 29 ); /** * low priority TODOs: * * * fix postAwait's `resumeInProgramStaticTraceId` to be higher than all previous (especially `CallResult`) trace ids */ // ########################################################################### // raw // ########################################################################### _dbux.postAwait( await _dbux.wrapAwait( (_dbux.traceExpr(30, (_sleep = sleep)), _dbux.t(31), _dbux.traceExpr(33, _sleep(_dbux.traceArg(32, 800)))), (_contextId5 = _dbux.preAwait(8, 28)) ), _contextId5, 29 );
# azvm-automate-hack This is a template repository for a Hackathon focusing on serverless-based IT process automation.
#include <cpp11/sexp.hpp> #include <vector> #include "Rcpp.h" [[cpp11::register]] void protect_one_(SEXP x, int n) { for (R_xlen_t i = 0; i < n; ++i) { PROTECT(x); UNPROTECT(1); } } [[cpp11::register]] void protect_one_sexp_(SEXP x, int n) { for (R_xlen_t i = 0; i < n; ++i) { cpp11::sexp y(x); } } [[cpp11::register]] void protect_one_cpp11_(SEXP x, int n) { for (R_xlen_t i = 0; i < n; ++i) { SEXP p = cpp11::preserved.insert(x); cpp11::preserved.release(p); } } [[cpp11::register]] void protect_one_preserve_(SEXP x, int n) { for (R_xlen_t i = 0; i < n; ++i) { R_PreserveObject(x); R_ReleaseObject(x); } } // The internal protections here are actually uneeded, but it is a useful way to benchmark // them // // clang-format off #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-variable" #endif // clang-format on [[cpp11::register]] void protect_many_(int n) { #ifdef CPP11_BENCH std::vector<SEXP> res; for (R_xlen_t i = 0; i < n; ++i) { res.push_back(PROTECT(Rf_ScalarInteger(n))); } for (R_xlen_t i = n - 1; i >= 0; --i) { SEXP x = res[i]; UNPROTECT(1); res.pop_back(); } #endif } [[cpp11::register]] void protect_many_cpp11_(int n) { std::vector<SEXP> res; for (R_xlen_t i = 0; i < n; ++i) { res.push_back(cpp11::preserved.insert(Rf_ScalarInteger(n))); } for (R_xlen_t i = n - 1; i >= 0; --i) { SEXP x = res[i]; cpp11::preserved.release(x); res.pop_back(); } } [[cpp11::register]] void protect_many_sexp_(int n) { std::vector<cpp11::sexp> res; for (R_xlen_t i = 0; i < n; ++i) { res.push_back(Rf_ScalarInteger(n)); } for (R_xlen_t i = n - 1; i >= 0; --i) { SEXP x = res[i]; res.pop_back(); } } [[cpp11::register]] void protect_many_preserve_(int n) { std::vector<cpp11::sexp> res; for (R_xlen_t i = 0; i < n; ++i) { SEXP x = Rf_ScalarInteger(n); R_PreserveObject(x); res.push_back(x); } for (R_xlen_t i = n - 1; i >= 0; --i) { SEXP x = res[i]; R_ReleaseObject(x); res.pop_back(); } } [[cpp11::register]] void protect_many_rcpp_(int n) { #ifdef CPP11_BENCH std::vector<Rcpp::RObject> res; for (R_xlen_t i = 0; i < n; ++i) { res.push_back(Rcpp::RObject(Rf_ScalarInteger(n))); } for (R_xlen_t i = n - 1; i >= 0; --i) { SEXP x = res[i]; res.pop_back(); } #endif }
--- title: App-V 5.1 技術參考資訊 description: App-V 5.1 技術參考資訊 author: dansimp ms.assetid: 2b9e8b2b-4cd1-46f3-ba08-e3bc8d5c6127 ms.reviewer: '' manager: dansimp ms.author: dansimp ms.pagetype: mdop, appcompat, virtualization ms.mktglfcycl: deploy ms.sitesec: library ms.prod: w10 ms.date: 06/16/2016 ms.openlocfilehash: 1ddf5c70a97d23b767b13c8598f53dadc4d4b50a ms.sourcegitcommit: 354664bc527d93f80687cd2eba70d1eea024c7c3 ms.translationtype: MT ms.contentlocale: zh-TW ms.lasthandoff: 06/26/2020 ms.locfileid: "10800310" --- # App-V 5.1 技術參考資訊 本節提供與管理 App-v 5.1 相關的參考資訊。 ## 本節內容 - [Application Virtualization 5.1 的效能指引](performance-guidance-for-application-virtualization-51.md) 提供各種效能優化做法的戰略與內容。 並非所有的做法都適用,雖然它們受到支援且已經過測試。 使用適用于貴組織的所有建議做法,將提供最佳的使用者體驗。 - [應用程式發佈與用戶端互動](application-publishing-and-client-interaction51.md) 描述下列 App-v 用戶端作業如何影響本機作業系統: App-v、套件儲存區行為、漫遊登錄與資料、用戶端應用程式週期管理、應用程式 V 套件的整合、動態設定、並行元件,以及用戶端記錄。 ## 相關主題 [使用 SQL 指令碼建立 APP-V 4.5 資料庫](../solutions/creating-app-v-45-databases-using-sql-scripting.md)    
/* Replace with your SQL commands */ CREATE TABLE IF NOT EXISTS team_mates ( id SERIAL, name VARCHAR(200) ); INSERT INTO team_mates (name) VALUES ('Moshood'), ('Mekky'), ('Marusoft'), ('Isah'), ('Kelechi');
#!/usr/bin/env bats load test_helper upload_file() { name=$(new_id) echo "Hello world" | govc datastore.upload - "$name" assert_success echo "$name" } @test "datastore.ls" { name=$(upload_file) # Single argument run govc datastore.ls "${name}" assert_success [ ${#lines[@]} -eq 1 ] # Multiple arguments run govc datastore.ls "${name}" "${name}" assert_success [ ${#lines[@]} -eq 2 ] # Pattern argument run govc datastore.ls "./govc-test-*" assert_success [ ${#lines[@]} -ge 1 ] # Long listing run govc datastore.ls -l "./govc-test-*" assert_success assert_equal "12B" $(awk '{ print $1 }' <<<${output}) } @test "datastore.ls-R" { dir=$(new_id) run govc datastore.mkdir "$dir" assert_success for name in one two three ; do echo "$name world" | govc datastore.upload - "$dir/file-$name" run govc datastore.mkdir -p "$dir/dir-$name/subdir-$name" run govc datastore.mkdir -p "$dir/dir-$name/.hidden" assert_success echo "$name world" | govc datastore.upload - "$dir/dir-$name/.hidden/other-$name" echo "$name world" | govc datastore.upload - "$dir/dir-$name/other-$name" echo "$name world" | govc datastore.upload - "$dir/dir-$name/subdir-$name/last-$name" done # without -R json=$(govc datastore.ls -json -l -p "$dir") result=$(jq -r .[].File[].Path <<<"$json" | wc -l) [ "$result" -eq 6 ] result=$(jq -r .[].FolderPath <<<"$json" | wc -l) [ "$result" -eq 1 ] # with -R json=$(govc datastore.ls -json -l -p -R "$dir") result=$(jq -r .[].File[].Path <<<"$json" | wc -l) [ "$result" -eq 15 ] result=$(jq -r .[].FolderPath <<<"$json" | wc -l) [ "$result" -eq 7 ] # with -R -a json=$(govc datastore.ls -json -l -p -R -a "$dir") result=$(jq -r .[].File[].Path <<<"$json" | wc -l) [ "$result" -eq 21 ] result=$(jq -r .[].FolderPath <<<"$json" | wc -l) [ "$result" -eq 10 ] } @test "datastore.rm" { name=$(upload_file) # Not found is a failure run govc datastore.rm "${name}.notfound" assert_failure assert_matches "govc: File .* was not found" "${output}" # Not found is NOT a failure with the force flag run govc datastore.rm -f "${name}.notfound" assert_success assert_empty "${output}" # Verify the file is present run govc datastore.ls "${name}" assert_success # Delete the file run govc datastore.rm "${name}" assert_success assert_empty "${output}" # Verify the file is gone run govc datastore.ls "${name}" assert_failure } @test "datastore.info" { run govc datastore.info enoent assert_failure run govc datastore.info assert_success [ ${#lines[@]} -gt 1 ] } @test "datastore.mkdir" { name=$(new_id) # Not supported datastore type is a failure run govc datastore.mkdir -namespace "notfound" assert_failure assert_matches "govc: ServerFaultCode: .*" "${output}" run govc datastore.mkdir "${name}" assert_success assert_empty "${output}" # Verify the dir is present run govc datastore.ls "${name}" assert_success # Delete the dir on an unsupported datastore type is a failure run govc datastore.rm -namespace "${name}" assert_failure assert_matches "govc: ServerFaultCode: .*" "${output}" # Delete the dir run govc datastore.rm "${name}" assert_success assert_empty "${output}" # Verify the dir is gone run govc datastore.ls "${name}" assert_failure } @test "datastore.download" { name=$(upload_file) run govc datastore.download "$name" - assert_success assert_output "Hello world" run govc datastore.download "$name" "$TMPDIR/$name" assert_success run cat "$TMPDIR/$name" assert_output "Hello world" rm "$TMPDIR/$name" } @test "datastore.upload" { name=$(new_id) echo -n "Hello world" | govc datastore.upload - "$name" run govc datastore.download "$name" - assert_success assert_output "Hello world" } @test "datastore.tail" { run govc datastore.tail "enoent/enoent.log" assert_failure id=$(new_id) govc vm.create "$id" govc vm.power -off "$id" # test with .log (> bufSize) and .vmx (< bufSize) for file in "$id/vmware.log" "$id/$id.vmx" ; do log=$(govc datastore.download "$file" -) for n in 0 1 5 10 123 456 7890 ; do expect=$(tail -n $n <<<"$log") run govc datastore.tail -n $n "$file" assert_output "$expect" expect=$(tail -c $n <<<"$log") run govc datastore.tail -c $n "$file" assert_output "$expect" done done } @test "datastore.disk" { id=$(new_id) vmdk="$id/$id.vmdk" run govc datastore.mkdir "$id" assert_success run govc datastore.disk.create "$vmdk" assert_success run govc datastore.disk.info "$vmdk" assert_success run govc datastore.rm "$vmdk" assert_success run govc datastore.mkdir -p "$id" assert_success run govc datastore.disk.create "$vmdk" assert_success id=$(new_id) run govc vm.create -on=false -link -disk "$vmdk" "$id" assert_success run govc datastore.disk.info -d "$vmdk" assert_success run govc datastore.disk.info -p=false "$vmdk" assert_success run govc datastore.disk.info -c "$vmdk" assert_success run govc datastore.disk.info -json "$vmdk" assert_success # should fail due to: ddb.deletable=false run govc datastore.rm "$vmdk" assert_failure run govc datastore.rm -f "$vmdk" assert_success # one more time, but rm the directory w/o -f run govc datastore.mkdir -p "$id" assert_success run govc datastore.disk.create "$vmdk" assert_success id=$(new_id) run govc vm.create -on=false -link -disk "$vmdk" "$id" assert_success run govc datastore.rm "$(dirname "$vmdk")" assert_success } @test "datastore.disk.info" { import_ttylinux_vmdk run govc datastore.disk.info assert_failure run govc datastore.disk.info enoent assert_failure run govc datastore.disk.info "$GOVC_TEST_VMDK" assert_success run govc datastore.disk.info -d "$GOVC_TEST_VMDK" assert_success run govc datastore.disk.info -c "$GOVC_TEST_VMDK" assert_success }
# Animotion.css Animotion.css is a minimalistic CSS library to animate objects using transitions. # Website https://abjt14.github.io/animotion-css/ ## Usage ```html <link rel="stylesheet" href="animotion.css"> ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. ## License [MIT](https://choosealicense.com/licenses/mit/)
package RDF::Trine::Store::LDF; use strict; use warnings; no warnings 'redefine'; use feature qw(state); use utf8; use base qw(RDF::Trine::Store); use RDF::Trine::Store; use RDF::Trine::Iterator; use RDF::LDF; use RDF::Trine::Error qw(:try); sub new { my ($class,%opts) = @_; my $ref = \%opts; $ref->{ldf} = RDF::LDF->new( url => $ref->{url}); return undef unless $ref->{ldf}->is_fragment_server; bless $ref , $class; } sub _new_with_string { my ($class, $cfg) = @_; $class->new(url => $cfg); } sub _new_with_config { my ($class,$cfg) = @_; $class->new(url => $cfg->{url}); } sub get_statements { my ($self,$subject,$predicate,$object,$context) = @_; my $sub = $self->{ldf}->get_statements($subject,$predicate,$object); RDF::Trine::Iterator::Graph->new($sub); } sub get_pattern { my ($self,$bgp,$context) = @_; $self->{ldf}->get_pattern($bgp,$context); } sub get_contexts { undef; } sub add_statement { throw RDF::Trine::Error::UnimplementedError -text => "LDF add_statement support not implemented"; } sub remove_statement { throw RDF::Trine::Error::UnimplementedError -text => "LDF remove_statement support not implemented"; } sub remove_statements { throw RDF::Trine::Error::UnimplementedError -text => "LDF remove_statements support not implemented"; } sub count_statements { my ($self,$subject,$predicate,$object,$context) = @_; my $it = $self->{ldf}->get_statements($subject,$predicate,$object); my ($triples,$info) = $it->(); $info->{hydra_totalItems}; } sub size { shift->count_statements; } sub supports { undef; } 1; =head1 NAME RDF::Trine::Store::LDF - RDF Store proxy for a Linked Data Fragment endpoint =head1 SYNOPSIS use RDF::Trine::Store::LDF; use RDF::Trine::Store; my $store = RDF::Trine::Store->new_with_config({ storetype => 'LDF', url => $url }); my $it = $store->get_statements(); while (my $st = $it->next) { # $st is a RDF::Trine::Statement print "$st\n"; } # Or query the store with SPAQRL use RDF::Query; my $model = RDF::Trine::Model->new($store); my $rdf_query = RDF::Query->new(<<EOF); . . SPARQL . . EOF my $iter = $rdf_query->execute($model); while (my $s = $iter->next) { # $s is a RDF::Trine::VariableBinding print $s->value . "\n"; } =head1 DESCRIPTION RDF::Trine::Store::LDF provides a RDF::Trine::Store API to interact with a remote Linked Data Fragment endpoint. For details see: <http://linkeddatafragments.org/>. =head1 METHODS Beyond the methods documented below, this class inherits methods from the L<RDF::Trine::Store> class. =over =item new({ url => url }) Returns a new RDF::Trine::Store object that will act as a proxy for the Linked Data Fragment endpoint accessible via the supplied $url. Expertimental: more than one url as an ARRAY reference can be provided for an federated query over many LDF endpoints. =item new_with_config( $hashref ) Returns a new RDF::Trine::Store object configured by a hashref with the url as required key. =item get_statements( $subject, $predicate, $object ) Returns a stream object of all statements matching the specified subject, predicate and objects. Any of the arguments may be undef to match any value. =item get_pattern( $bgp ) Returns an iterator object of all bindings matching the specified graph pattern. =item get_contexts Not supported. =item add_statement ( $statement [, $context] ) Not supported. =item remove_statement ( $statement [, $context]) Not supported. =item remove_statements ( $subject, $predicate, $object [, $context]) Not supported. =item count_statements ( $subject, $predicate, $object ) Returns a count of all the statements matching the specified subject, predicate and object. Any of the arguments may be undef to match any value. =item size Returns the number of statements in the store. =item supports ( [ $feature ] ) Not supported. =back =head1 AUTHOR Patrick Hochstenbach, C<< patrick.hochstenbach at ugent.be >> =head1 CONTRIBUTORS Gregory Todd Williams, C<< greg@evilfunhouse.com >> =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See L<http://dev.perl.org/licenses/> for more information. =encoding utf8 =cut
import * as Encryption from "./encryption"; import * as Errors from "./errors"; import * as KeyDerivation from "./key-derivation"; export * from "./encryption-adapter"; export { KeyDerivation, Encryption, Errors, };
package com.luck.picture.lib.widget.longimage /** * Interface for decoder (and region decoder) factories. * @param <T> the class of decoder that will be produced. </T> */ interface DecoderFactory<T> { /** * Produce a new instance of a decoder with type [T]. * @return a new instance of your decoder. */ @Throws(IllegalAccessException::class, InstantiationException::class) fun make(): T }
/** * Created by sargis on 7/4/17. */ import "pixi"; import "phaser-ce"; import { Facade, PureMVC } from "../src/index"; import config from "./config"; import GameFacade from "./GameFacade"; import GameState from "./state/GameState"; export default class Game extends Phaser.Game { // STATES private static STATE_GAME = "Game"; constructor() { super(config.gameWidth, config.gameHeight, Phaser.CANVAS, "", null); this.state.add(Game.STATE_GAME, new GameState()); PureMVC.debug = true; Facade.getInstance = GameFacade.getInstance; } public init() { this.state.start(Game.STATE_GAME); } } (<any>window).game = new Game(); (<any>window).game.init();
function dropdown(checkbox) { if(checkbox.checked) { document.getElementById("toggle-image").src = "img/up.svg"; } else document.getElementById("toggle-image").src = "img/down.svg"; }
package org.zalando.jsonapi package object json { private[json] def collectSome[A](opts: Option[A]*): List[A] = (opts collect { case Some(field) ⇒ field }).toList }
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'moor_database.dart'; // ************************************************************************** // MoorGenerator // ************************************************************************** // ignore_for_file: unnecessary_brace_in_string_interps, unnecessary_this class Expense extends DataClass implements Insertable<Expense> { final int id; final double amount; final DateTime time; final String description; Expense( {@required this.id, @required this.amount, @required this.time, @required this.description}); factory Expense.fromData(Map<String, dynamic> data, GeneratedDatabase db, {String prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType<int>(); final doubleType = db.typeSystem.forDartType<double>(); final dateTimeType = db.typeSystem.forDartType<DateTime>(); final stringType = db.typeSystem.forDartType<String>(); return Expense( id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), amount: doubleType.mapFromDatabaseResponse(data['${effectivePrefix}amount']), time: dateTimeType.mapFromDatabaseResponse(data['${effectivePrefix}time']), description: stringType .mapFromDatabaseResponse(data['${effectivePrefix}description']), ); } @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; if (!nullToAbsent || id != null) { map['id'] = Variable<int>(id); } if (!nullToAbsent || amount != null) { map['amount'] = Variable<double>(amount); } if (!nullToAbsent || time != null) { map['time'] = Variable<DateTime>(time); } if (!nullToAbsent || description != null) { map['description'] = Variable<String>(description); } return map; } ExpensesCompanion toCompanion(bool nullToAbsent) { return ExpensesCompanion( id: id == null && nullToAbsent ? const Value.absent() : Value(id), amount: amount == null && nullToAbsent ? const Value.absent() : Value(amount), time: time == null && nullToAbsent ? const Value.absent() : Value(time), description: description == null && nullToAbsent ? const Value.absent() : Value(description), ); } factory Expense.fromJson(Map<String, dynamic> json, {ValueSerializer serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return Expense( id: serializer.fromJson<int>(json['id']), amount: serializer.fromJson<double>(json['amount']), time: serializer.fromJson<DateTime>(json['time']), description: serializer.fromJson<String>(json['description']), ); } @override Map<String, dynamic> toJson({ValueSerializer serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return <String, dynamic>{ 'id': serializer.toJson<int>(id), 'amount': serializer.toJson<double>(amount), 'time': serializer.toJson<DateTime>(time), 'description': serializer.toJson<String>(description), }; } Expense copyWith( {int id, double amount, DateTime time, String description}) => Expense( id: id ?? this.id, amount: amount ?? this.amount, time: time ?? this.time, description: description ?? this.description, ); @override String toString() { return (StringBuffer('Expense(') ..write('id: $id, ') ..write('amount: $amount, ') ..write('time: $time, ') ..write('description: $description') ..write(')')) .toString(); } @override int get hashCode => $mrjf($mrjc(id.hashCode, $mrjc(amount.hashCode, $mrjc(time.hashCode, description.hashCode)))); @override bool operator ==(dynamic other) => identical(this, other) || (other is Expense && other.id == this.id && other.amount == this.amount && other.time == this.time && other.description == this.description); } class ExpensesCompanion extends UpdateCompanion<Expense> { final Value<int> id; final Value<double> amount; final Value<DateTime> time; final Value<String> description; const ExpensesCompanion({ this.id = const Value.absent(), this.amount = const Value.absent(), this.time = const Value.absent(), this.description = const Value.absent(), }); ExpensesCompanion.insert({ this.id = const Value.absent(), @required double amount, @required DateTime time, @required String description, }) : amount = Value(amount), time = Value(time), description = Value(description); static Insertable<Expense> custom({ Expression<int> id, Expression<double> amount, Expression<DateTime> time, Expression<String> description, }) { return RawValuesInsertable({ if (id != null) 'id': id, if (amount != null) 'amount': amount, if (time != null) 'time': time, if (description != null) 'description': description, }); } ExpensesCompanion copyWith( {Value<int> id, Value<double> amount, Value<DateTime> time, Value<String> description}) { return ExpensesCompanion( id: id ?? this.id, amount: amount ?? this.amount, time: time ?? this.time, description: description ?? this.description, ); } @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; if (id.present) { map['id'] = Variable<int>(id.value); } if (amount.present) { map['amount'] = Variable<double>(amount.value); } if (time.present) { map['time'] = Variable<DateTime>(time.value); } if (description.present) { map['description'] = Variable<String>(description.value); } return map; } @override String toString() { return (StringBuffer('ExpensesCompanion(') ..write('id: $id, ') ..write('amount: $amount, ') ..write('time: $time, ') ..write('description: $description') ..write(')')) .toString(); } } class $ExpensesTable extends Expenses with TableInfo<$ExpensesTable, Expense> { final GeneratedDatabase _db; final String _alias; $ExpensesTable(this._db, [this._alias]); final VerificationMeta _idMeta = const VerificationMeta('id'); GeneratedIntColumn _id; @override GeneratedIntColumn get id => _id ??= _constructId(); GeneratedIntColumn _constructId() { return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true, declaredAsPrimaryKey: true); } final VerificationMeta _amountMeta = const VerificationMeta('amount'); GeneratedRealColumn _amount; @override GeneratedRealColumn get amount => _amount ??= _constructAmount(); GeneratedRealColumn _constructAmount() { return GeneratedRealColumn( 'amount', $tableName, false, ); } final VerificationMeta _timeMeta = const VerificationMeta('time'); GeneratedDateTimeColumn _time; @override GeneratedDateTimeColumn get time => _time ??= _constructTime(); GeneratedDateTimeColumn _constructTime() { return GeneratedDateTimeColumn( 'time', $tableName, false, ); } final VerificationMeta _descriptionMeta = const VerificationMeta('description'); GeneratedTextColumn _description; @override GeneratedTextColumn get description => _description ??= _constructDescription(); GeneratedTextColumn _constructDescription() { return GeneratedTextColumn( 'description', $tableName, false, ); } @override List<GeneratedColumn> get $columns => [id, amount, time, description]; @override $ExpensesTable get asDslTable => this; @override String get $tableName => _alias ?? 'expenses'; @override final String actualTableName = 'expenses'; @override VerificationContext validateIntegrity(Insertable<Expense> instance, {bool isInserting = false}) { final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { context.handle(_idMeta, id.isAcceptableOrUnknown(data['id'], _idMeta)); } if (data.containsKey('amount')) { context.handle(_amountMeta, amount.isAcceptableOrUnknown(data['amount'], _amountMeta)); } else if (isInserting) { context.missing(_amountMeta); } if (data.containsKey('time')) { context.handle( _timeMeta, time.isAcceptableOrUnknown(data['time'], _timeMeta)); } else if (isInserting) { context.missing(_timeMeta); } if (data.containsKey('description')) { context.handle( _descriptionMeta, description.isAcceptableOrUnknown( data['description'], _descriptionMeta)); } else if (isInserting) { context.missing(_descriptionMeta); } return context; } @override Set<GeneratedColumn> get $primaryKey => {id}; @override Expense map(Map<String, dynamic> data, {String tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return Expense.fromData(data, _db, prefix: effectivePrefix); } @override $ExpensesTable createAlias(String alias) { return $ExpensesTable(_db, alias); } } abstract class _$AppDatabase extends GeneratedDatabase { _$AppDatabase(QueryExecutor e) : super(SqlTypeSystem.defaultInstance, e); $ExpensesTable _expenses; $ExpensesTable get expenses => _expenses ??= $ExpensesTable(this); @override Iterable<TableInfo> get allTables => allSchemaEntities.whereType<TableInfo>(); @override List<DatabaseSchemaEntity> get allSchemaEntities => [expenses]; }
import { createSelector } from 'reselect'; import { TokenSetStatus } from '@/constants/TokenSetStatus'; import { usedTokenSetSelector } from './usedTokenSetSelector'; import type { RootState } from '@/app/store'; export const tokenSetStatusSelector = createSelector( usedTokenSetSelector, (state: RootState, tokenSet: string) => tokenSet, (usedTokenSets, tokenSet) => ( usedTokenSets?.[tokenSet] ?? TokenSetStatus.DISABLED ), );
<?php declare(strict_types=1); namespace App\Enums; enum AppPermission: string { case LIST_USERS = 'list users'; case VIEW_USER = 'view user'; case CREATE_USER = 'create user'; case UPDATE_USER = 'update user'; case DELETE_USER = 'delete user'; case USER_TICKETS = 'user tickets'; case CURRENT_PROFILE = 'current profile'; case LOGOUT = 'logout'; case BOOKING_HISTORY = 'booking history'; CASE CREATE_MOVIE = 'create movie'; CASE UPDATE_MOVIE = 'update movie'; CASE DELETE_MOVIE = 'delete movie'; CASE CREATE_HALL = 'create hall'; CASE UPDATE_HALL = 'update hall'; CASE DELETE_HALL = 'delete hall'; case LIST_OPTIONS = 'list options'; CASE CREATE_OPTION = 'create option'; CASE UPDATE_OPTION = 'update option'; CASE DELETE_OPTION = 'delete option'; CASE CREATE_SHOW = 'create show'; CASE UPDATE_SHOW = 'update show'; CASE DELETE_SHOW = 'delete show'; case LIST_TICKETS = 'list tickets'; case VIEW_TICKET = 'view ticket'; CASE CREATE_TICKET = 'create ticket'; CASE UPDATE_TICKET = 'update ticket'; CASE DELETE_TICKET = 'delete ticket'; case BOOK_TICKET = 'book ticket'; }
// build.js // builds our RethinkDB database, tables, and documents. // dependencies: products.json // NOTE: Make sure RethinkDB is running before using this script... var r = require('rethinkdb'); var fs = require('fs'); // Connect to RethinkDB r.connect({host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; var connection = conn; // Create the db that we use. r.dbCreate('shoraq_products').run(connection, function(err, result) { if (err) throw err; console.log('Build DB:', result); // Create the table to store our products. r.db('shoraq_products').tableCreate('products').run(connection, function(err, result) { if (err) throw err; console.log('Build Table:', result); // Pull our products from products.json, and insert them our table. fs.readFile('products.json', 'utf8', function(err, result) { if (err) throw err; var products = JSON.parse(result); r.db('shoraq_products').table('products').insert(products).run(connection, function(err, result) { if (err) throw err; console.log('Build Documents:', result); r.db('shoraq_products').table('products').indexCreate('videoID').run(connection, function(err) { if (err) throw err; console.log('Creating index...'); r.db('shoraq_products').table('products').indexWait('videoID').run(connection, function(err) { if (err) throw err; console.log('Index created on videoID.'); connection.close(function(err) { if (err) throw err; }); }); }) }); }); }); }); });
# CSViewer > simple and lightweight *.csv file viewer written in Python ![](screenshot_1.png) ![](screenshot_2.png) ## Installation Windows: ```cmd cd /d d: git clone https://github.com/ma1ex/CSViewer.git cd CSViewer python -m venv venv && venv\scripts\activate pip install -r requirements.txt ``` ## Run application Windows: ```cmd cd /d d:\CSViewer venv\scripts\activate python main.py ``` ## Features > _Eng_: > - Fast loading of large files; > - Zebra shading of odd lines; > - Display the total number of rows and columns; > - Autodetection* and manual selection of encoding (utf-8, cp1251, cp866, koi8-r); > - Separator selection - comma, semicolon, tabulation; > - Auto column width selection with double click on header; > - Copying the value of the selected cell to the clipboard; > > _Rus_: > - Быстрая загрузка больших файлов; > - Закрашивание нечетных строк "зеброй"; > - Отображение общего количества строк и столбцов; > - Автоопределение* и ручной выбор кодировки (utf-8, cp1251, cp866, koi8-r); > - Выбор разделителя значений - запятая, точка с запятой, табуляция; > - Автоподбор ширины столбцов при двойном клике на заголовке; > - Копирование в буфер обмена значения выбранной ячейки; ## Dependencies > wxPython ### Requirements > - Python >= 3.6 ## Compiling to binaries Windows: ```cmd cd /d d\CSViewer: venv\scripts\activate pip install -r requirements_dev.txt python setup_wx.py build ``` After compilation in the project directory will appear `Build\CSViewer_vX.X.X_win_x64` ## Run compiled application Windows: ```cmd Build\CSViewer_vX.X.X_win_x64\CSViewer.exe ``` ## Release History * 1.0.0 * Release v1.0.0 ## Contributing 1. Fork it (<https://github.com/ma1ex/CSViewer/fork>) 2. Create your feature branch (`git checkout -b feature/fooBar`) 3. Commit your changes (`git commit -am 'Add some fooBar'`) 4. Push to the branch (`git push main feature/fooBar`) 5. Create a new Pull Request ## License Distributed under the MIT license. See ``LICENSE.md`` for more information.
//----------------------------------------------------------------------------- // The MIT License // // Copyright (c) 2012 Rick Beton <rick@bigbeeconsultants.co.uk> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //----------------------------------------------------------------------------- package uk.co.bigbeeconsultants.http.servlet import javax.servlet.http.HttpServletRequest import uk.co.bigbeeconsultants.http._ import header._ import request.{StringRequestBody, RequestBody} import url.{Endpoint, Path, Href} /** * Adapts HTTP Servlet request objects to the Light Http Client API. This allows a variety of solutions such as * reverse proxying to be implemented easily. * @param textualBodyFilter an optional mutation that may be applied to every line of the body content. */ @deprecated("This will be removed from future versions.", "0.25.1") class HttpServletRequestAdapter(req: HttpServletRequest, textualBodyFilter: Option[TextualBodyFilter] = None) { def url: Href = { val port = if (req.getServerPort < 0) None else Some(req.getServerPort) new Href(Endpoint(Option(req.getScheme), Option(req.getServerName), port), Path(req.getRequestURI), None, Option(req.getQueryString)) } def headers: Headers = { import scala.collection.JavaConversions.enumerationAsScalaIterator new Headers(enumerationAsScalaIterator(req.getHeaderNames).map { headerName: Any => new Header(headerName.toString, req.getHeader(headerName.toString)) }.toList) } /** * Gets the request body. * @return the request body which will be a low-footprint streaming implementation by default. However, it * is possible to access the body by first caching it, e.g. * {{{ * val adapter = new HttpServletRequestAdapter(req) * val body = adapter.requestBody.cachedBody * println(body.asString) * val request = Request.post(url, Some(body)) * ... * }}} */ def requestBody: RequestBody = { val rawContentType = req.getContentType val contentType = if (rawContentType != null) MediaType(rawContentType) else MediaType.TEXT_PLAIN val streamRequestBody = RequestBody(req.getInputStream, contentType) if (textualBodyFilter.isDefined && textualBodyFilter.get.processAsText(contentType)) { val body = streamRequestBody.cachedBody.asString new StringRequestBody(body, contentType, textualBodyFilter.map(_.lineProcessor)) } else { streamRequestBody } } }
--- layout: default title: CTF Walkthroughs permalink: /ctf.html --- ---- ## CyberSecLabs **[Debug - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/debug.html)** **[Deployable - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/deployable.html)** **[Engine - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/engine.html)** **[Fuel - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/fuel.html)** **[Leakage - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/leakage.html)** **[Monitor - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/monitor.html)** **[Outdated - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/outdated.html)** **[Secret - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/secret.html)** **[Shares - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/shares.html)** **[Shock - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/shock.html)** **[Simple - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/simple.html)** **[Unattended - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/unattended.html)** **[Weak - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/cyberseclabs/weak.html)** ---- ## HackTheBox **[Arctic - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/arctic.html)** **[Bashed - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/bashed.html)** **[Bastard - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/bastard.html)** **[Bounty - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/bounty.html)** **[Devel - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/devel.html)** **[Grandpa - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/grandpa.html)** **[Lame - Linux](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/lame.html)** **[Silo - Windows](https://cyb3rr3ap3r.github.io/posts/ctf/hackthebox/silo.html)**
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.vault.config.consul; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.vault.util.IntegrationTestSupport; import org.springframework.cloud.vault.util.Settings; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.event.EventListener; import org.springframework.util.Base64Utils; import org.springframework.vault.core.VaultOperations; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; /** * Tests for {@link VaultConfigConsulConfigDataTests}. * * @author Mark Paluch */ public class VaultConfigConsulConfigDataTests extends IntegrationTestSupport { private static final String POLICY = "key \"\" { policy = \"read\" }"; private ConfigurableApplicationContext context; @Before public void before() { assumeTrue(SetupConsul.isConsulAvailable()); VaultOperations vaultOperations = this.vaultRule.prepare().getVaultOperations(); if (!prepare().hasSecretBackend("consul")) { prepare().mountSecret("consul"); } SetupConsul.setupConsul(vaultOperations, "consul"); Map<String, Object> role = new LinkedHashMap<>(); role.put("policy", Base64Utils.encodeToString(POLICY.getBytes())); role.put("ttl", "3s"); role.put("max_ttl", "3s"); vaultOperations.write(String.format("%s/roles/%s", "consul", "short-readonly"), role); this.vaultRule.prepare().getVaultOperations().write("secret/VaultConfigConsulConfigDataTests", Collections.singletonMap("default-key", "default")); SpringApplication application = new SpringApplication(VaultConfigConsulConfigDataTests.Config.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.application.name=VaultConfigConsulConfigDataTests", "--spring.config.import=vault:", "--spring.cloud.vault.kv.enabled=false", "--spring.cloud.vault.config.lifecycle.min-renewal=2s", "--spring.cloud.vault.consul.enabled=true", "--spring.cloud.vault.consul.role=short-readonly", "--spring.cloud.vault.token=" + Settings.token().getToken()); } @Test public void shouldApplyConfigurer() throws InterruptedException { Config config = this.context.getBean(Config.class); assertThat(config.events).isEmpty(); assertThat(this.context.getEnvironment().getProperty("spring.cloud.consul.config.acl-token")).isNotNull(); Thread.sleep(5_000); assertThat(config.events).isNotEmpty(); } @After public void after() { if (this.context != null) { this.context.close(); } } @SpringBootConfiguration(proxyBeanMethods = false) @EnableAutoConfiguration static class Config { final BlockingQueue<ConsulBackendMetadata.RebindConsulEvent> events = new LinkedBlockingQueue<>(); @EventListener public void onRebind(ConsulBackendMetadata.RebindConsulEvent rebindConsulEvent) { this.events.add(rebindConsulEvent); } } }
package com.example.dreamless.tools import android.widget.Toast class ToastUtils { companion object { fun long(message: String) { Toast.makeText(AndroidApplication.getContext(), message, Toast.LENGTH_LONG).show() } fun short(message: String) { Toast.makeText(AndroidApplication.getContext(), message, Toast.LENGTH_SHORT).show() } } }
package coil import android.app.Application import android.content.Context import androidx.test.core.app.ApplicationProvider import coil.request.ImageRequest import coil.util.createTestMainDispatcher import coil.util.runBlockingTest import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.util.concurrent.atomic.AtomicBoolean import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertSame import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) @OptIn(ExperimentalCoroutinesApi::class) class ImageLoaderFactoryTest { private lateinit var context: Context private lateinit var mainDispatcher: TestCoroutineDispatcher @Before fun before() { context = ApplicationProvider.getApplicationContext() mainDispatcher = createTestMainDispatcher() } @After fun after() { Dispatchers.resetMain() Coil.reset() } @Test @Config(application = TestApplication::class) fun `application factory is invoked exactly once`() { assertFalse((context.applicationContext as TestApplication).isInitialized.get()) val imageLoader1 = Coil.imageLoader(context) assertTrue((context.applicationContext as TestApplication).isInitialized.get()) val imageLoader2 = Coil.imageLoader(context) assertSame(imageLoader1, imageLoader2) } @Test fun `setImageLoader factory is invoked exactly once`() { val imageLoader1 = ImageLoader(context) val isInitialized = AtomicBoolean(false) Coil.setImageLoader(object : ImageLoaderFactory { override fun newImageLoader(): ImageLoader { check(!isInitialized.getAndSet(true)) { "newImageLoader was invoked more than once." } return imageLoader1 } }) assertFalse(isInitialized.get()) val imageLoader2 = Coil.imageLoader(context) assertSame(imageLoader1, imageLoader2) assertTrue(isInitialized.get()) val imageLoader3 = Coil.imageLoader(context) assertSame(imageLoader1, imageLoader3) } @Test @Config(application = TestApplication::class) fun `setImageLoader preempts application factory`() { val isInitialized = AtomicBoolean(false) assertFalse(isInitialized.get()) assertFalse((context.applicationContext as TestApplication).isInitialized.get()) Coil.setImageLoader(object : ImageLoaderFactory { override fun newImageLoader(): ImageLoader { check(!isInitialized.getAndSet(true)) { "newImageLoader was invoked more than once." } return ImageLoader(context) } }) Coil.imageLoader(context) assertTrue(isInitialized.get()) assertFalse((context.applicationContext as TestApplication).isInitialized.get()) } @Test fun `setImageLoader shuts down previous instance`() = runBlockingTest { val imageLoader1 = ImageLoader(context) Coil.setImageLoader(imageLoader1) val imageLoader2 = ImageLoader(context) Coil.setImageLoader(imageLoader2) // The request should fail instantly since imageLoader1 is shut down. assertFailsWith<IllegalStateException> { imageLoader1.execute(ImageRequest.Builder(context).data(Unit).build()) } } class TestApplication : Application(), ImageLoaderFactory { val isInitialized = AtomicBoolean(false) override fun newImageLoader(): ImageLoader { check(!isInitialized.getAndSet(true)) { "newImageLoader was invoked more than once." } return ImageLoader(this) } } }
package com.test.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Mapper; import com.test.domain.Employee; @Mapper public interface EmployeeDao { List<Employee> list(Map<String,Object> map); List<Employee> queryByName(Map<String,Object> map); int count(Map<String,Object> map); int save(Employee employee); int update(Employee employee); int remove(Integer id); int batchRemove(List<Integer> ids); }
package com.github.nikitavbv.servicemonitor.metric const val API_KEY_PREFIX = "API_TOKEN " const val API_KEY_HEADER = "Authorization"
namespace GangOfFour.Behavioral.Bridge.Implementer { public interface IWeapon { public int GetAttackForce(); } }
/** * Human Cell Atlas * https://www.humancellatlas.org/ * * Model of a term contained in the JSON response returned from files API. Contains term name and the total count, and * in the case of the "project" facet, an array of project IDs that share the same term name. */ export interface ResponseTerm { count: number; projectId?: string[]; term: string; }
URL_ZH = r'https://www.hkex.com.hk/chi/services/trading/securities/securitieslists/ListOfSecurities_c.xlsx' URL_EN = r'https://www.hkex.com.hk/eng/services/trading/securities/securitieslists/ListOfSecurities.xlsx'
/* * autor: cristobal liendo i * fecha: 9/1/11 vim * descripcion: calcula la temperatura maxima, minima y el promedio de * 10 datos usando arreglos. */ #include <stdio.h> int main() { float avg, min, max; float vals[10]; avg = 0; for (int i = 0; i < 10; i++) { printf("Ingresa la temperatura numero %d: ", i + 1); scanf("%f", &vals[i]); if (i == 0){ max = vals[i]; min = vals[i]; } else if (vals[i] > max) max = vals[i]; else if (vals[i] < min) min = vals[i]; avg += vals[i] / 10; } printf("\nEl promedio de las temperaturas fue: %.2f\n", avg); printf("La temperatura mayor fue: %.2f\n", max); printf("La temperatura menor fue: %.2f\n", min); return 0; }
const URL = 'ws://localhost:8080/ws-chat'; let client = null; function showMessage(value) { const responseContainer = document.getElementById('response'); const responseFragment = document.createDocumentFragment(); const newMessage = createElementFromHTML('<div class="message-container">\n' + ' <div class="row">' + ' <img class="col-sm-2" src="img/user.svg" width="50px" height="50px" alt="Avatar">\n' + ' <p class="col-sm-8">' + value + '</p>\n' + ' </div>' + ' <span class="time-right">11:00</span>\n' + '</div>'); responseFragment.appendChild(newMessage); responseContainer.appendChild(responseFragment); // scroll down let chatContainer = document.getElementById('response'); chatContainer.scrollTop = chatContainer.scrollHeight; } function connect() { client = Stomp.client(URL); client.connect({}, function (frame) { client.subscribe('/topic/messages', function (message) { showMessage(JSON.parse(message.body).value); }); }); } function sendMessage() { let messageInput = USERNAME + ': ' + document.getElementById('message-input').value; client.send('/app/ws-chat', {}, JSON.stringify({'value':messageInput})); }
using Mono.Cecil.Cil; namespace Cauldron.Interception.Cecilator.Coders { public sealed class FinallyCoder : TryCatchFinallyCoderBase { internal FinallyCoder(TryCatchFinallyCoderBase tryCatchFinallyCoderBase) : base(tryCatchFinallyCoderBase, new InstructionMarker { instruction = tryCatchFinallyCoderBase.instructions.Last, markerType = MarkerType.Finally }) { } public Coder EndTry() => base.EndTryInternal(); } }
<!-- YAML added: v9.7.0 --> * `err` {number} * Returns: {string} Returns the string name for a numeric error code that comes from a Node.js API. The mapping between error codes and error names is platform-dependent. See [Common System Errors][] for the names of common errors. ```js fs.access('file/that/does/not/exist', (err) => { const name = util.getSystemErrorName(err.errno); console.error(name); // ENOENT }); ```
package com.caowj.fastdev.model.net import retrofit2.Call import retrofit2.http.GET interface HttpServiceApi { /** * 新闻列表 * @return Call<HttpBaseResult<NewsBean>> */ @GET("http://news-at.zhihu.com/api/4/news/latest") fun getNews(): Call<Any> // /** // * 新闻列表 // * @return Call<HttpBaseResult<NewsBean>> // */ // @GET("https://news-at.zhihu.com/api/4/news/latest") // fun getNews(): Call<HttpBaseResult<NewsBean>> }
package kfile import ( "fmt" "strings" "time" ) // 从路径中获取文件名 // param: filepath 文件路径或者文件名 // notice: 如果不是路径 则认为是文件 func GetFileName(path string) string { if strings.Count(path, "/") == 0 && strings.Count(path, `\`) == 0 { return path } if strings.Count(path, "/") > strings.Count(path, `\`) { return path[strings.LastIndex(path, "/")+1:] } if strings.Count(path, "/") < strings.Count(path, `\`) { return path[strings.LastIndex(path, `\`)+1:] } return path } // 按年月日生成路径 // notice: 这个只有阿里云上传的时候创建路径用 其他地方尽量不要使用 // 最终类似: 2019/January/10 func GetDirectoryPathByDate() string { year := time.Now().Year() month := time.Now().Month() day := time.Now().Day() return fmt.Sprintf("%d/%s/%d", year, month, day) }
package com.example.ulesson.ui.subject import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import com.example.ulesson.data.helper.Event import com.example.ulesson.data.helper.Resource import com.example.ulesson.data.model.Lesson import com.example.ulesson.data.model.RecentView import com.example.ulesson.data.model.Subject import com.example.ulesson.data.source.repo.Repository class SubjectViewModel @ViewModelInject constructor( private val repository: Repository ) : ViewModel() { private var subject: Subject? = null private val _navigateToVideo = MutableLiveData<Event<RecentView>>() val navigateToVideo: LiveData<Event<RecentView>> = _navigateToVideo fun getSubject(id: Long): LiveData<Resource<Subject>> = liveData { emit(repository.getSubject(id)) } fun setSubject(subject: Subject) { this.subject = subject } fun openVideo(lesson: Lesson) { subject?.let { subject -> val topicName = subject.chapters.find { it.id == lesson.chapterId }!!.name _navigateToVideo.value = Event( RecentView(subject.id, subject.name, topicName, lesson.mediaUrl) ) } } }
<?php class BankAccountModel extends BaseModel { public $table = "bank_accounts"; public $soft_delete = true; public $order_by_priority = true; public function addBalance($accounts) { $new_accounts = []; foreach ($accounts as $account) { $account_transactions = $this->db->get_where("transactions", [ 'tran_date >' => $account['last_reconciled'], 'account_id' => $account['id'] ] )->result(); $running_balance = $account['last_reconciled_balance']; foreach ($account_transactions as $tran) { if ($tran->in_out == 0) $running_balance += $tran->amount; else $running_balance -= $tran->amount; } $running_balance = number_format($running_balance,2,'.',''); $account['balance'] = $running_balance; $new_accounts[] = $account; } return $new_accounts; } }
ruby_version_is "1.9" do require File.expand_path('../../../shared/rational/exponent', __FILE__) describe "Rational#**" do it_behaves_like(:rational_exponent, :**) end describe "Rational#** when passed Rational" do it_behaves_like(:rational_exponent_rat, :**) end describe "Rational#** when passed Float" do it_behaves_like(:rational_exponent_float, :**) end describe "Rational#** when passed Integer" do it_behaves_like(:rational_exponent_int, :**) end end
#pragma once #include "aggreget_generated.hpp" namespace aggreget { /* ** To tuple */ template <Aggregate T> constexpr auto to_tuple(const T& t) { return details::to_tuple_impl_cref(t); } template <Aggregate T> constexpr auto to_tuple(T&& t) { return details::to_tuple_impl_fref(std::forward<T>(t)); } template <Aggregate T> constexpr auto to_tuple(T& t) { return details::to_tuple_impl_ref(t); } /* ** Get */ template <std::size_t Index, Aggregate T> constexpr const auto& get(const T& t) { return std::get<Index>(to_tuple(t)); } template <std::size_t Index, Aggregate T> constexpr auto& get(T& t) { return std::get<Index>(to_tuple(t)); } /* ** Foreach */ template <Aggregate T, typename Cb> constexpr auto foreach(const T& t, Cb&& cb) { return std::apply([&](auto&&... args) {(cb(args), ...);}, to_tuple(t)); } template <Aggregate T, typename Cb> constexpr auto foreach(T&& t, Cb&& cb) { return std::apply([&](auto&&... args) {(cb(std::forward<decltype(args)>(args)), ...);}, to_tuple(std::forward<T>(t))); } template <Aggregate T, typename Cb> constexpr auto foreach(T& t, Cb&& cb) { return std::apply([&](auto&&... args) {(cb(args), ...);}, to_tuple(t)); } /* ** Convert */ // Still early stage and expirimental template <Aggregate Output, Aggregate Input> constexpr auto convert(Input&& i) { // Later add a static assert so that Output and Input have the same number of attributes return std::apply( [&](auto&&... args) { return Output { std::forward<decltype(args)>(args)... }; }, to_tuple(std::forward<Input>(i))); } template <Aggregate Output, Aggregate Input> constexpr auto convert(const Input& i) { // Later add a static assert so that Output and Input have the same number of attributes return std::apply( [&](const auto&... args) { return Output { args... }; }, to_tuple(i)); } template <Aggregate Input> constexpr std::size_t get_tuple_size(const Input&) { return details::get_tuple_size_impl<Input>(); } template <Aggregate Input> constexpr std::size_t get_tuple_size() { return details::get_tuple_size_impl<Input>(); } }
/*! * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ import * as vscode from 'vscode' import { localize } from '../../shared/utilities/vsCodeUtils' import { IotClient } from '../../shared/clients/iotClient' import { AWSTreeNodeBase } from '../../shared/treeview/nodes/awsTreeNodeBase' import { ErrorNode } from '../../shared/treeview/nodes/errorNode' import { PlaceholderNode } from '../../shared/treeview/nodes/placeholderNode' import { makeChildrenNodes } from '../../shared/treeview/treeNodeUtilities' import { inspect } from 'util' import { IotThingFolderNode } from './iotThingFolderNode' import { IotCertsFolderNode } from './iotCertFolderNode' import { IotPolicyFolderNode } from './iotPolicyFolderNode' /** * An AWS Explorer node representing IoT. * * Contains folders for Things, Certificates, and Policies as child nodes. */ export class IotNode extends AWSTreeNodeBase { /* These nodes are declared here to be used when refreshing resources that * occur multiple times in the tree (e.g. certificates that are under both * Things and the Certificates folder). However, they cannot be assinged in * the constructor due to a circular dependency with this node, so they are * initially undefined. */ public thingFolderNode: IotThingFolderNode | undefined public certFolderNode: IotCertsFolderNode | undefined public policyFolderNode: IotPolicyFolderNode | undefined public constructor(private readonly iot: IotClient) { super('IoT', vscode.TreeItemCollapsibleState.Collapsed) this.contextValue = 'awsIotNode' } public async getChildren(): Promise<AWSTreeNodeBase[]> { return await makeChildrenNodes({ getChildNodes: async () => { const thingFolderNode = new IotThingFolderNode(this.iot, this) this.thingFolderNode = thingFolderNode const certFolderNode = new IotCertsFolderNode(this.iot, this) this.certFolderNode = certFolderNode const policyFolderNode = new IotPolicyFolderNode(this.iot, this) this.policyFolderNode = policyFolderNode const categories: AWSTreeNodeBase[] = [thingFolderNode, certFolderNode, policyFolderNode] return categories }, getErrorNode: async (error: Error, logID: number) => new ErrorNode(this, error, logID), getNoChildrenPlaceholderNode: async () => new PlaceholderNode(this, localize('AWS.explorerNode.iot.noThings', '[No Things found]')), }) } public async getEndpoint(): Promise<string> { return await this.iot.getEndpoint() } public [inspect.custom](): string { return 'IotNode' } }
<?php namespace CpPress\Application\BackEnd; use \Commonhelp\WP\WPController; use \Commonhelp\App\Http\RequestInterface; use CpPress\Application\WP\Admin\Settings; use CpPress\Application\WP\Admin\PostMeta; class AttachmentController extends WPController{ public function featured($files, $validMime){ if($files == ''){ $files = array(); } $this->assign('validMime', htmlspecialchars($validMime)); $this->assign('json_files', htmlspecialchars(json_encode($files, JSON_HEX_TAG))); } }
describe("multiple destinations", function() { var $multiselect, $multiselect_to, $multiselect_to_2; beforeEach(function() { var html = '<div class="row">'+ ' <div class="col-xs-5">'+ ' <select name="from[]" id="multi_d" class="form-control" size="26" multiple="multiple">'+ ' <option value="1">C++</option>'+ ' <option value="2">C#</option>'+ ' <option value="3">Haskell</option>'+ ' <option value="4">Java</option>'+ ' <option value="5">JavaScript</option>'+ ' <option value="6">Lisp</option>'+ ' <option value="7">Lua</option>'+ ' <option value="8">MATLAB</option>'+ ' <option value="9">NewLISP</option>'+ ' <option value="10">PHP</option>'+ ' <option value="11">Perl</option>'+ ' <option value="12">SQL</option>'+ ' <option value="13">Unix shell</option>'+ ' </select>'+ ' </div>'+ ' '+ ' <div class="col-xs-2">'+ ' <button type="button" id="multi_d_rightAll" class="btn btn-default btn-block" style="margin-top: 20px;"><i class="glyphicon glyphicon-forward"></i></button>'+ ' <button type="button" id="multi_d_rightSelected" class="btn btn-default btn-block"><i class="glyphicon glyphicon-chevron-right"></i></button>'+ ' <button type="button" id="multi_d_leftSelected" class="btn btn-default btn-block"><i class="glyphicon glyphicon-chevron-left"></i></button>'+ ' <button type="button" id="multi_d_leftAll" class="btn btn-default btn-block"><i class="glyphicon glyphicon-backward"></i></button>'+ ' '+ ' <hr style="margin: 40px 0 60px;" />'+ ' '+ ' <button type="button" id="multi_d_rightAll_2" class="btn btn-default btn-block"><i class="glyphicon glyphicon-forward"></i></button>'+ ' <button type="button" id="multi_d_rightSelected_2" class="btn btn-default btn-block"><i class="glyphicon glyphicon-chevron-right"></i></button>'+ ' <button type="button" id="multi_d_leftSelected_2" class="btn btn-default btn-block"><i class="glyphicon glyphicon-chevron-left"></i></button>'+ ' <button type="button" id="multi_d_leftAll_2" class="btn btn-default btn-block"><i class="glyphicon glyphicon-backward"></i></button>'+ ' </div>'+ ' '+ ' <div class="col-xs-5">'+ ' <b>Known languages</b>'+ ' <select name="to[]" id="multi_d_to" class="form-control" size="8" multiple="multiple"></select>'+ ' '+ ' <br/><hr/><br/>'+ ' '+ ' <b>I want to learn</b>'+ ' <select name="to_2[]" id="multi_d_to_2" class="form-control" size="8" multiple="multiple"></select>'+ ' </div>'+ '</div>'; jasmine.getFixtures().set(html); $multiselect = $('#multi_d').multiselect({ right: '#multi_d_to, #multi_d_to_2', rightSelected: '#multi_d_rightSelected, #multi_d_rightSelected_2', leftSelected: '#multi_d_leftSelected, #multi_d_leftSelected_2', rightAll: '#multi_d_rightAll, #multi_d_rightAll_2', leftAll: '#multi_d_leftAll, #multi_d_leftAll_2', search: { left: '<input type="text" name="q" class="form-control" placeholder="Search..." />' }, moveToRight: function(Multiselect, $options, event, silent, skipStack) { var button = $(event.currentTarget).attr('id'); if (button == 'multi_d_rightSelected') { var $left_options = Multiselect.$left.find('> option:selected'); Multiselect.$right.eq(0).append($left_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$right.eq(0).find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$right.eq(0)); } } else if (button == 'multi_d_rightAll') { var $left_options = Multiselect.$left.children(':visible'); Multiselect.$right.eq(0).append($left_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$right.eq(0).find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$right.eq(0)); } } else if (button == 'multi_d_rightSelected_2') { var $left_options = Multiselect.$left.find('> option:selected'); Multiselect.$right.eq(1).append($left_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$right.eq(1).find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$right.eq(1)); } } else if (button == 'multi_d_rightAll_2') { var $left_options = Multiselect.$left.children(':visible'); Multiselect.$right.eq(1).append($left_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$right.eq(1).eq(1).find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$right.eq(1)); } } }, moveToLeft: function(Multiselect, $options, event, silent, skipStack) { var button = $(event.currentTarget).attr('id'); if (button == 'multi_d_leftSelected') { var $right_options = Multiselect.$right.eq(0).find('> option:selected'); Multiselect.$left.append($right_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$left.find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$left); } } else if (button == 'multi_d_leftAll') { var $right_options = Multiselect.$right.eq(0).children(':visible'); Multiselect.$left.append($right_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$left.find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$left); } } else if (button == 'multi_d_leftSelected_2') { var $right_options = Multiselect.$right.eq(1).find('> option:selected'); Multiselect.$left.append($right_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$left.find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$left); } } else if (button == 'multi_d_leftAll_2') { var $right_options = Multiselect.$right.eq(1).children(':visible'); Multiselect.$left.append($right_options); if ( typeof Multiselect.callbacks.sort == 'function' && !silent ) { Multiselect.$left.find('> option').sort(Multiselect.callbacks.sort).appendTo(Multiselect.$left); } } } }); $multiselect_to = $('#multi_d_to'); $multiselect_to_2 = $('#multi_d_to_2'); }); it("multiselect is instantiated and contains options", function() { expect($multiselect.attr('id')).toBe('multi_d'); expect($multiselect.find('option').length).toBe(13); expect($multiselect_to.attr('id')).toBe('multi_d_to'); expect($multiselect_to.find('option').length).toBe(0); expect($multiselect_to_2.attr('id')).toBe('multi_d_to_2'); expect($multiselect_to_2.find('option').length).toBe(0); }); it("move all to right 1", function() { // Click move all to right $('#multi_d_rightAll').trigger('click'); expect($multiselect.find('option').length).toBe(0); expect($multiselect_to.find('option').length).toBe(13); }); it("move one to right 1", function() { $multiselect.find('option:eq(0)').attr('selected', true); // Click move selected to right $('#multi_d_rightSelected').trigger('click'); expect($multiselect.find('option').length).toBe(12); expect($multiselect_to.find('option').length).toBe(1); }); it("move all selected to right 1", function() { $multiselect.find('option:nth-child(2n)').attr('selected', true); // Click move selected to right $('#multi_d_rightSelected').trigger('click'); expect($multiselect.find('option').length).toBe(7); expect($multiselect_to.find('option').length).toBe(6); }); it("move all to left 1", function() { // Click move all to right $('#multi_d_rightAll').trigger('click'); // Click move all to left $('#multi_d_leftAll').trigger('click'); expect($multiselect.find('option').length).toBe(13); expect($multiselect_to.find('option').length).toBe(0); }); it("move one to left 1", function() { // Click move all to right $('#multi_d_rightAll').trigger('click'); $multiselect_to.find('option:eq(0)').attr('selected', true); // Click move selected to right $('#multi_d_leftSelected').trigger('click'); expect($multiselect.find('option').length).toBe(1); expect($multiselect_to.find('option').length).toBe(12); }); it("move all selected to left 1", function() { // Click move all to right $('#multi_d_rightAll').trigger('click'); $multiselect_to.find('option:nth-child(2n)').attr('selected', true); // Click move selected to right $('#multi_d_leftSelected').trigger('click'); expect($multiselect.find('option').length).toBe(6); expect($multiselect_to.find('option').length).toBe(7); }); it("move all to right 2", function() { // Click move all to right $('#multi_d_rightAll_2').trigger('click'); expect($multiselect.find('option').length).toBe(0); expect($multiselect_to_2.find('option').length).toBe(13); }); it("move one to right 2", function() { $multiselect.find('option:eq(0)').attr('selected', true); // Click move selected to right $('#multi_d_rightSelected_2').trigger('click'); expect($multiselect.find('option').length).toBe(12); expect($multiselect_to_2.find('option').length).toBe(1); }); it("move all selected to right 2", function() { $multiselect.find('option:nth-child(2n)').attr('selected', true); // Click move selected to right $('#multi_d_rightSelected_2').trigger('click'); expect($multiselect.find('option').length).toBe(7); expect($multiselect_to_2.find('option').length).toBe(6); }); it("move all to left 2", function() { // Click move all to right $('#multi_d_rightAll_2').trigger('click'); // Click move all to left $('#multi_d_leftAll_2').trigger('click'); expect($multiselect.find('option').length).toBe(13); expect($multiselect_to_2.find('option').length).toBe(0); }); it("move one to left 2", function() { // Click move all to right $('#multi_d_rightAll_2').trigger('click'); $multiselect_to_2.find('option:eq(0)').attr('selected', true); // Click move selected to right $('#multi_d_leftSelected_2').trigger('click'); expect($multiselect.find('option').length).toBe(1); expect($multiselect_to_2.find('option').length).toBe(12); }); it("move all selected to left 2", function() { // Click move all to right $('#multi_d_rightAll_2').trigger('click'); $multiselect_to_2.find('option:nth-child(2n)').attr('selected', true); // Click move selected to right $('#multi_d_leftSelected_2').trigger('click'); expect($multiselect.find('option').length).toBe(6); expect($multiselect_to_2.find('option').length).toBe(7); }); it("move one to right 1 and one to right 2", function() { $multiselect.find('option:eq(0)').attr('selected', true); // Click move selected to right $('#multi_d_rightSelected').trigger('click'); expect($multiselect.find('option').length).toBe(12); expect($multiselect_to.find('option').length).toBe(1); expect($multiselect_to_2.find('option').length).toBe(0); $multiselect.find('option:eq(0)').attr('selected', true); // Click move selected to right $('#multi_d_rightSelected_2').trigger('click'); expect($multiselect.find('option').length).toBe(11); expect($multiselect_to.find('option').length).toBe(1); expect($multiselect_to_2.find('option').length).toBe(1); }); });
<?php /** * Created by PhpStorm. * User: davidquaglieri * Date: 14/5/17 * Time: 1:39 PM */ namespace AppBundle\Services; use AppBundle\Entity\Article; use Doctrine\Bundle\DoctrineBundle\Registry; use Doctrine\Common\Collections\Collection; class ArticleManager { private $doctrine; /** * ArticleManager constructor. * @param Registry $doctrine */ public function __construct(Registry $doctrine) { $this->doctrine = $doctrine; } /** * Get all Articles * * @return null|array */ public function findAll() { return $this->doctrine->getRepository('AppBundle:Article')->findAll(); } /** * Get an Article by the given id * * @param $id * @return null|object|\AppBundle\Entity\Article */ public function findOne($id) { return $this->doctrine->getRepository('AppBundle:Article')->find($id); } /** * @param Article $article * @return Article */ public function save(Article $article) { $em = $this->doctrine->getManager(); $em->persist($article); $em->flush(); return $article; } /** * @param Article $article */ public function delete(Article $article) { $em = $this->doctrine->getManager(); $em->remove($article); $em->flush(); } }
--- layout: post title: Cumbia Japonesa date: 2011-04-13 19:35 author: coherentnoise comments: true categories: [funny, japanese, music, Reposts, video] --- Hahahaha, omigosh [youtube=http://www.youtube.com/watch?v=BNZ0aYSHncY]
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Routing\Middleware; class OnceAuth implements Middleware { protected $auth; public function __construct(Guard $auth) { $this->auth = $auth; } public function handle($request, Closure $next) { $fallo = $this->auth->onceBasic(); if($fallo) { return response()->json(['mensaje' => 'Se debe estar autenticado para esta petición', 'codigo' => 401],401); } return $next($request); } }
using ArdanisDockerizedServiceTests.WebApi.DataAccess; using ArdanisDockerizedServiceTests.WebApi.Entities; using ArdanisDockerizedServiceTests.WebApi.Requests; using ArdanisDockerizedServiceTests.WebApi.Responses; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ArdanisDockerizedServiceTests.WebApi.Controllers { [ApiController] [Route("/api/expenses")] public class ExpensesController : ControllerBase { private readonly ExpensesContext _dbContext; private readonly BlobServiceClient _blobServiceClient; public ExpensesController(ExpensesContext dbContext, BlobServiceClient blobServiceClient) { _dbContext = dbContext; _blobServiceClient = blobServiceClient; } [HttpPost] public async Task<IActionResult> PostExpense([FromBody] PostExpenseRequest request) { _dbContext.Add(new Expense() { Amount = request.Amount, Description = request.Description, ExternalId = request.ExpenseId }); await _dbContext.SaveChangesAsync(); return Ok(); } [HttpPost] [Route("{expenseId}/receipts")] public async Task<IActionResult> PostExpenseFile(Guid expenseId, List<IFormFile> receipts) { var expense = await _dbContext.Expenses.FirstOrDefaultAsync(x => x.ExternalId == expenseId); if (expense == null) return NotFound(); foreach (var receipt in receipts) { expense.ReceiptFilename = receipt.FileName; await StoreFileAsync(expense, receipt); } await _dbContext.SaveChangesAsync(); return Ok(); } private async Task StoreFileAsync(Expense expense, IFormFile receipt) { var containerClient = await GetBlobClientAsync(expense); using (var s = receipt.OpenReadStream()) { await containerClient.UploadBlobAsync(receipt.FileName, s); } } private async Task<BlobContainerClient> GetBlobClientAsync(Expense expense) { var containerClient = _blobServiceClient.GetBlobContainerClient(expense.ExternalId.ToString()); await containerClient.CreateIfNotExistsAsync(PublicAccessType.BlobContainer); return containerClient; } [HttpGet] [Route("{expenseId}")] public async Task<IActionResult> GetExpense(Guid expenseId) { var expense = await _dbContext.Expenses.SingleOrDefaultAsync(x => x.ExternalId == expenseId); if (expense == null) { return NotFound(); } var response = new GetExpenseResponse() { Amount = expense.Amount, Description = expense.Description, ExpenseId = expense.ExternalId, ReceiptFilename = expense.ReceiptFilename }; return Ok(response); } [HttpGet] [Route("{expenseId}/receipts")] public async Task<IActionResult> DownloadExpenseReceipt(Guid expenseId) { var expense = await _dbContext.Expenses.SingleOrDefaultAsync(x => x.ExternalId == expenseId); if (expense == null || string.IsNullOrEmpty(expense.ReceiptFilename)) { return NotFound(); } var client = await GetBlobClientAsync(expense); var file = await client.GetBlobClient(expense.ReceiptFilename).DownloadAsync(); return File(file.Value.Content, "application/octet-stream"); } } }
#!/bin/bash # # Copyright 2018 The Bazel Authors. All rights reserved. # # 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. # # modify_execution_info_test.sh: tests of the --modify_execution_info flag. # --- begin runfiles.bash initialization --- # Copy-pasted from Bazel's Bash runfiles library (tools/bash/runfiles/runfiles.bash). set -euo pipefail if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then if [[ -f "$0.runfiles_manifest" ]]; then export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest" elif [[ -f "$0.runfiles/MANIFEST" ]]; then export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST" elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then export RUNFILES_DIR="$0.runfiles" fi fi if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash" elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \ "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)" else echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash" exit 1 fi # --- end runfiles.bash initialization --- source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \ || { echo "integration_test_setup.sh not found!" >&2; exit 1; } case "$(uname -s | tr [:upper:] [:lower:])" in msys*|mingw*|cygwin*) declare -r is_windows=true ;; *) declare -r is_windows=false ;; esac if "$is_windows"; then export MSYS_NO_PATHCONV=1 export MSYS2_ARG_CONV_EXCL="*" fi #### HELPER FUNCTIONS ################################################## if ! type try_with_timeout >&/dev/null; then # Bazel's testenv.sh defines try_with_timeout but the Google-internal version # uses a different testenv.sh. function try_with_timeout() { $* ; } fi function set_up() { cd ${WORKSPACE_DIR} } function tear_down() { try_with_timeout bazel shutdown } #### TESTS ############################################################# function test_aquery_respects_modify_execution_info_changes { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" cat > "$pkg/BUILD" <<'EOF' genrule(name = "bar", outs = ["bar_out.txt"], cmd = "touch $(OUTS)") EOF bazel aquery --output=text "//$pkg:bar" \ --modify_execution_info=Genrule=+requires-x \ > output1 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-x: ''}" output1 bazel aquery --output=text "//$pkg:bar" \ --modify_execution_info=Genrule=+requires-y \ > output2 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-y: ''}" output2 } function test_modify_execution_info_multiple { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" cat > "$pkg/BUILD" <<'EOF' genrule( name = "bar", outs = ["bar_out.txt"], cmd = "touch $(OUTS)", tags = ["requires-x"], ) cc_binary(name="zero", srcs=["zero.cc"]) EOF echo "int main(void) {}" > "$pkg/zero.cc" # multiple elements in the value list that match the same mnemonic. bazel aquery --output=text "//$pkg:bar" \ --modify_execution_info=Genrule=+requires-y,Genrule=+requires-z \ > output 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-x: '', requires-y: '', "\ "requires-z: ''}" output # multiple elements in the value list, the first of which adds an # ExecutionInfo and the second of which removes it. bazel aquery --output=text "//$pkg:bar" \ --modify_execution_info=Genrule=+requires-z,.*=-requires-z \ > output 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-x: ''}" output # multiple elements in the value list, the first of which removes an # ExecutionInfo (previously absent) and the second of which adds it. bazel aquery --output=text "//$pkg:bar" \ --modify_execution_info=Genrule=-requires-z,.*=+requires-z \ > output 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-x: '', requires-z: ''}" output # multiple elements in the value list, the first of which removes an # ExecutionInfo (previously present) and the second of which adds it back. bazel aquery --output=text "//$pkg:bar" \ --modify_execution_info=Genrule=-requires-x,.*=+requires-x \ > output 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-x: ''}" output # multiple elements with multiple values bazel aquery --output=text "//$pkg:all" \ --modify_execution_info=Genrule=-requires-x,Genrule=+requires-z,\ Genrule=+requires-a,CppCompile=+requires-b,CppCompile=+requires-c \ > output 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-a: '', requires-z: ''}" output assert_contains "ExecutionInfo: {requires-b: '', requires-c: ''" output # negative lookahead bazel aquery --output=text "//$pkg:all" \ --modify_execution_info='(?!Genrule).*=+requires-a,(?!CppCompile).*=+requires-z' \ > output 2> "$TEST_log" || fail "Expected success" assert_contains "ExecutionInfo: {requires-x: '', requires-z: ''}" output assert_contains "ExecutionInfo: {requires-a: ''" output } function test_modify_execution_info_various_types() { if [[ "$PRODUCT_NAME" = "bazel" ]]; then # proto_library requires this external workspace. cat >> WORKSPACE << EOF # TODO(#9029): May require some adjustment if/when we depend on the real # @rules_python in the real source tree, since this third_party/ package won't # be available. new_local_repository( name = "rules_python", path = "$(dirname $(rlocation io_bazel/third_party/rules_python/rules_python.WORKSPACE))", build_file = "$(rlocation io_bazel/third_party/rules_python/BUILD)", workspace_file = "$(rlocation io_bazel/third_party/rules_python/rules_python.WORKSPACE)", ) EOF cat "$(rlocation "io_bazel/src/test/shell/integration/rules_proto_stanza.txt")" >>WORKSPACE cat >> WORKSPACE << EOF load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains") rules_proto_dependencies() rules_proto_toolchains() # @com_google_protobuf//:protoc depends on @io_bazel//third_party/zlib. new_local_repository( name = "io_bazel", path = "$(dirname $(rlocation io_bazel/third_party/rules_python/rules_python.WORKSPACE))/../..", build_file_content = "# Intentionally left empty.", workspace_file_content = "workspace(name = 'io_bazel')", ) EOF fi local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" echo "load('//$pkg:shell.bzl', 'starlark_shell')" > "$pkg/BUILD" cat >> "$pkg/BUILD" <<'EOF' starlark_shell( name = "shelly", output = "ok.txt", ) cc_binary(name="zero", srcs=["zero.cc"]) sh_test(name="test_a", srcs=["a.sh"]) java_library(name = "javalib", srcs = ["HelloWorld.java"]) action_listener( name = "al", extra_actions = [":echo-filename"], mnemonics = ["Javac"], visibility = ["//visibility:public"], ) extra_action(name = "echo-filename", cmd = "echo Hi \\$(EXTRA_ACTION_FILE)") py_binary(name = "pybar", srcs=["pybar.py"],) proto_library(name = "proto", srcs=["foo.proto"]) EOF cat > "$pkg/shell.bzl" <<'EOF' def _impl(ctx): ctx.actions.run_shell( outputs = [ ctx.outputs.output ], command = "touch %s" % ctx.outputs.output.path, ) starlark_shell = rule( _impl, attrs = { "output": attr.output(mandatory=True), } ) EOF cat > "$pkg/a.sh" <<'EOF' #!/bin/sh exit 0 EOF chmod 755 "$pkg/a.sh" echo "int main(void) {}" > "$pkg/zero.cc" echo "public class HelloWorld {}" > "$pkg/HelloWorld.java" echo 'print("Hi")' > "$pkg/pybar.py" echo 'syntax="proto2"; package foo;' > "$pkg/foo.proto" bazel aquery --output=text "//$pkg:all" \ --experimental_action_listener=$pkg:al \ --modify_execution_info=\ echo.*=+requires-extra-action,\ .*Proto.*=+requires-proto,\ CppCompile=+requires-cpp-compile,\ CppLink=+requires-cpp-link,\ TestRunner=+requires-test-runner,\ Turbine=+requires-turbine,\ JavaSourceJar=+requires-java-source-jar,\ Javac=+requires-javac,\ Py.*=+requires-py,\ Action=+requires-action \ > output 2> "$TEST_log" || fail "Expected success" # There are sometimes other elements in ExecutionInfo, e.g. requires-darwin # for obj-c, supports-workers for java. Since testing for these combinations # would be brittle, irrelevant to the operation of the flag, and in some # cases platform-dependent, we just search for the key itself, not the whole # ExecutionInfo: {...} line. assert_contains "requires-action: ''" output assert_contains "requires-cpp-compile: ''" output assert_contains "requires-cpp-link: ''" output assert_contains "requires-extra-action: ''" output assert_contains "requires-test-runner: ''" output assert_contains "requires-javac: ''" output assert_contains "requires-turbine: ''" output assert_contains "requires-java-source-jar: ''" output assert_contains "requires-proto: ''" output # GenProtoDescriptorSet should match if [[ "$PRODUCT_NAME" != "bazel" ]]; then assert_contains "requires-py: ''" output fi } # Regression test for b/127874955. We use --output=textproto since --output=text # sorts the execution info. function test_modify_execution_info_deterministic_order() { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg/x" "$pkg/y" || fail "mkdir failed" touch "$pkg/BUILD" cat > "$pkg/build_defs.bzl" <<'EOF' || fail "Couldn't cat" def _rule_x_impl(ctx): output = ctx.outputs.out ctx.actions.run_shell( outputs = [output], command = "touch %s" % output.path, mnemonic = "RuleX", execution_requirements = {"requires-x": ""}, ) rule_x = rule(outputs = {"out": "%{name}.out"}, implementation = _rule_x_impl) def _rule_y_impl(ctx): output = ctx.outputs.out ctx.actions.run_shell( outputs = [output], command = "touch %s" % output.path, mnemonic = "RuleY", execution_requirements = {"requires-y": ""}, ) rule_y = rule(outputs = {"out": "%{name}.out"}, implementation = _rule_y_impl) EOF echo "load('//$pkg:build_defs.bzl', 'rule_x')" > "$pkg/x/BUILD" echo 'rule_x(name = "x")' >> "$pkg/x/BUILD" echo "load('//$pkg:build_defs.bzl', 'rule_y')" > "$pkg/y/BUILD" echo 'rule_y(name = "y")' >> "$pkg/y/BUILD" mod='Rule(X|Y)=+requires-x,Rule(X|Y)=+requires-y' bazel aquery "//$pkg/x" --output=textproto --modify_execution_info="$mod" \ > output1 2> "$TEST_log" || fail "Expected success" bazel shutdown >& "$TEST_log" || fail "Couldn't shutdown" bazel aquery "//$pkg/y" --modify_execution_info="$mod" \ >& "$TEST_log" || fail "Expected success" bazel aquery "//$pkg/x" --output=textproto --modify_execution_info="$mod" \ > output2 2> "$TEST_log" || fail "Expected success" assert_equals "$(cat output1)" "$(cat output2)" } # Regression test for b/130762259. function test_modify_execution_info_changes_test_runner_cache_key() { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" echo "sh_test(name = 'test', srcs = ['test.sh'])" > "$pkg/BUILD" touch "$pkg/test.sh" bazel aquery "mnemonic(TestRunner,//$pkg:test)" --output=text \ --modify_execution_info= \ 2> "$TEST_log" | grep ActionKey > key1 || fail "Expected success" bazel aquery "mnemonic(TestRunner,//$pkg:test)" --output=text \ --modify_execution_info=TestRunner=+requires-x \ 2> "$TEST_log" | grep ActionKey > key2 || fail "Expected success" assert_not_equals "$(cat key1)" "$(cat key2)" } run_suite "Integration tests of the --modify_execution_info option."
import cookieManager from './LocalForageCookieManager' import requestManager from './RequestManager2' import Logger from './SimpleLogger' import * as version from './Version' export default class AnalyticsManager { private logger: Logger private newPageLoad: boolean private initialized: boolean constructor (logger: Logger) { this.logger = logger this.initialized = false // Report analytics counts as a page hit this.newPageLoad = true } public async initialize () { if (this.initialized) { return } await cookieManager.initialize() let uuid = cookieManager.get('id') if (!uuid) { uuid = (await requestManager.get('/api/uuid')).id await cookieManager.set('id', uuid) } this.initialized = true } public async reportAnalytics () { await this.initialize() let send try { send = await requestManager.post('/api/stats/hit', { id: cookieManager.get('id'), newPageLoad: this.newPageLoad, source: cookieManager.get('source'), theme: cookieManager.get('theme', 'Default - Light'), userAgent: window.navigator.userAgent, version }) } catch (e) { this.logger.warn('Analytics sending failed') return send } this.newPageLoad = false if (send.success) { this.logger.success('Analytics data sent successfully') } else { this.logger.warn('Analytics are disabled') } return send } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.scala.examples.join import org.apache.flink.streaming.api.scala._ import org.apache.flink.api.java.utils.ParameterTool import org.apache.flink.streaming.api.TimeCharacteristic import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows import org.apache.flink.streaming.api.windowing.time.Time /** * Example illustrating a windowed stream join between two data streams. * * The example works on two input streams with pairs (name, grade) and (name, salary) * respectively. It joins the steams based on "name" within a configurable window. * * The example uses a built-in sample data generator that generates * the steams of pairs at a configurable rate. */ object WindowJoin { // ************************************************************************* // Program Data Types // ************************************************************************* case class Grade(name: String, grade: Int) case class Salary(name: String, salary: Int) case class Person(name: String, grade: Int, salary: Int) // ************************************************************************* // Program // ************************************************************************* def main(args: Array[String]) { // parse the parameters val params = ParameterTool.fromArgs(args) val windowSize = params.getLong("windowSize", 2000) val rate = params.getLong("rate", 3) println("Using windowSize=" + windowSize + ", data rate=" + rate) println("To customize example, use: WindowJoin " + "[--windowSize <window-size-in-millis>] [--rate <elements-per-second>]") // obtain execution environment, run this example in "ingestion time" val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime) // make parameters available in the web interface env.getConfig.setGlobalJobParameters(params) // // create the data sources for both grades and salaries val grades = WindowJoinSampleData.getGradeSource(env, rate) val salaries = WindowJoinSampleData.getSalarySource(env, rate) // join the two input streams by name on a window. // for testability, this functionality is in a separate method. val joined = joinStreams(grades, salaries, windowSize) // print the results with a single thread, rather than in parallel joined.print().setParallelism(1) // execute program env.execute("WindowJoin") } def joinStreams( grades: DataStream[Grade], salaries: DataStream[Salary], windowSize: Long) : DataStream[Person] = { grades.join(salaries) .where(_.name) .equalTo(_.name) .window(TumblingEventTimeWindows.of(Time.milliseconds(windowSize))) .apply { (g, s) => Person(g.name, g.grade, s.salary) } } }
# encoding: utf-8 describe 'et_nginx::default' do before do stub_command('which nginx').and_return(nil) end let(:chef_run) do ChefSpec::SoloRunner.new.converge(described_recipe) end shared_examples_for 'default recipe' do end context 'unmodified attributes' do it 'includes the package recipe' do expect(chef_run).to include_recipe('et_nginx::package') end it 'does not include a module recipe' do expect(chef_run).to_not include_recipe('module_http_stub_status') end it_behaves_like 'default recipe' end context 'installs modules based on attributes' do it 'includes a module recipe when specified' do chef_run.node.set['nginx']['modules'] = ['module_http_geoip'] chef_run.converge(described_recipe) expect(chef_run).to include_recipe('et_nginx::module_http_geoip') end end end
module OrgansHelper def manager [@organ.manager_name, @organ.manager_email].reject(&:blank?).join(', ') end def status_class_for(application) if show_recommendations?(application.call) application.admissible? && application.eligible? ? 'valid' : 'invalid' else '' end end end
#!/bin/bash # --- # Ask and save to variable in input 2 of argument 2. # --- source ./f.sh process_argument "${command[1]}" echo read -p "${argument[0]}" readtemp set_var "${argument[1]}" "$readtemp"
@extends('layouts.app') @section('content') <h1>{{$shelf->shelf_name}}</h1> @foreach($books as $Book) <div class="well"> <h3><a href="/books/{{$Book->id}}">{{$Book->book_name}}</a></h3> </div> @endforeach @endsection
USE [C:\USERS\DADDY\SOURCE\REPOS\BUDGETEXECUTION\NINJA\DATABASE\SQLSERVER\R6.MDF] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[ORC] AS SELECT PrcId, BudgetLevel, RPIO, BFY, FundCode, FundName, BocCode, BocName, AhCode, OrgCode, RcCode, DivisionName, AccountCode, Amount, ActivityCode, NpmName, NpmCode, ProgramProjectCode, ProgramProjectName, ProgramAreaCode, ProgramAreaName, GoalCode, GoalName, ObjectiveCode, ObjectiveName FROM dbo.PRC WHERE (Amount <> '0') AND (RcCode = '06D') GO
use crate::fonts::{Font, FontError, GlyphId}; use crate::pdf::object::{Dictionary, Object}; use crate::pdf::syntax::{BasicObjects, PdfFile, PAGE_TREE_ID}; use crate::primitives::*; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash; use std::io::{self, Write}; use std::ops::Deref; use std::sync::Arc; const PT_PER_INCH: f32 = 72.; const PX_PER_INCH: f32 = 96.; const PT_PER_PX: f32 = PT_PER_INCH / PX_PER_INCH; const CSS_TO_PDF_SCALE_X: f32 = PT_PER_PX; const CSS_TO_PDF_SCALE_Y: f32 = -PT_PER_PX; // Flip the Y axis direction, it defaults to upwards in PDF. pub(crate) struct InProgressDoc { pdf: PdfFile, page_ids: Vec<Object<'static>>, extended_graphics_states: Vec<(Vec<u8>, Object<'static>)>, font_resources: Vec<(Vec<u8>, Object<'static>)>, alpha_states: HashMap<u16, String>, fonts: HashMap<ByAddress<Arc<Font>>, String>, } impl InProgressDoc { pub(crate) fn new() -> Self { InProgressDoc { pdf: PdfFile::new(), page_ids: Vec::new(), extended_graphics_states: Vec::new(), font_resources: Vec::new(), alpha_states: HashMap::new(), fonts: HashMap::new(), } } pub(crate) fn write<W: Write>(&self, w: &mut W) -> io::Result<()> { self.pdf.write(w, &BasicObjects { page_tree: dictionary! { "Type" => "Pages", "Count" => self.page_ids.len(), "Kids" => &*self.page_ids, "Resources" => dictionary! { "Font" => Object::DictionaryWithOwnedKeys(&self.font_resources), "ExtGState" => Object::DictionaryWithOwnedKeys(&self.extended_graphics_states), }, }, catalog: dictionary! { "Type" => "Catalog", "Pages" => PAGE_TREE_ID, }, info: dictionary! { "Producer" => Object::LiteralString(b"Victor <https://github.com/SimonSapin/victor>"), }, }) } } struct ByAddress<T>(T); impl<T> hash::Hash for ByAddress<T> where T: Deref, T::Target: Sized, { fn hash<H>(&self, state: &mut H) where H: hash::Hasher, { (self.0.deref() as *const T::Target as usize).hash(state) } } impl<T> PartialEq for ByAddress<T> where T: Deref, T::Target: Sized, { fn eq(&self, other: &Self) -> bool { (self.0.deref() as *const T::Target as usize) == (other.0.deref() as *const T::Target as usize) } } impl<T> Eq for ByAddress<T> where T: Deref, T::Target: Sized, { } pub(crate) struct InProgressPage<'a> { doc: &'a mut InProgressDoc, size: Size<CssPx>, operations: Vec<u8>, graphics_state: GraphicsState, } impl<'a> Drop for InProgressPage<'a> { fn drop(&mut self) { let content_id = self .doc .pdf .add_stream(dictionary! {}, self.operations.as_slice().into()); let page_id = self.doc.pdf.add_dictionary(dictionary! { "Type" => "Page", "Parent" => PAGE_TREE_ID, "Contents" => content_id, "MediaBox" => array![ 0, 0, self.size.width * CSS_TO_PDF_SCALE_X, self.size.height * CSS_TO_PDF_SCALE_Y, ], }); self.doc.page_ids.push(page_id.into()); } } struct GraphicsState { non_stroking_color_rgb: (f32, f32, f32), alpha: f32, } macro_rules! op { ( $self_: expr, $operator: expr ) => { op!($self_, $operator,) }; ( $self_: expr, $operator: expr, $( $operands: expr ),*) => { { $( Object::from($operands).write(&mut $self_.operations).unwrap(); $self_.operations.push(b' '); )* $self_.operations.extend(str::as_bytes($operator)); $self_.operations.push(b'\n'); } } } impl<'a> InProgressPage<'a> { pub fn new(doc: &'a mut InProgressDoc, size: Size<CssPx>) -> Self { let mut page = InProgressPage { doc, size, operations: Vec::new(), // Initial state: graphics_state: GraphicsState { non_stroking_color_rgb: (0., 0., 0.), // Black alpha: 1., // Fully opaque }, }; op!( page, CURRENT_TRANSFORMATION_MATRIX, CSS_TO_PDF_SCALE_X, 0, 0, CSS_TO_PDF_SCALE_Y, 0, 0 ); page } pub(crate) fn set_color(&mut self, &RGBA(r, g, b, a): &RGBA) { if self.graphics_state.non_stroking_color_rgb != (r, g, b) { self.graphics_state.non_stroking_color_rgb = (r, g, b); op!(self, NON_STROKING_RGB_COLOR, r, g, b); } self.set_alpha(a) } pub(crate) fn paint_rectangle(&mut self, rect: &Rect<CssPx>) { op!( self, RECTANGLE, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height ); op!(self, FILL); } pub(crate) fn show_text(&mut self, text: &TextRun) -> Result<(), FontError> { let TextRun { ref segment, ref font_size, ref origin, } = *text; let font_key = self.add_font(&segment.font)?; // flip the Y axis in to compensate the same flip at the page level. let x_scale = font_size.0; let y_scale = -font_size.0; let mut glyph_codes = Vec::with_capacity(segment.glyphs.len() * 2); for &GlyphId(id) in &segment.glyphs { // Big-endian glyph_codes.push((id >> 8) as u8); glyph_codes.push(id as u8); } op!(self, BEGIN_TEXT); op!(self, TEXT_FONT_AND_SIZE, &*font_key, 1); op!( self, TEXT_MATRIX, x_scale, 0, 0, y_scale, origin.x, origin.y ); op!(self, SHOW_TEXT, Object::HexString(&glyph_codes)); op!(self, END_TEXT); // https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf#G8.1910927 // In the Font resource dictionary: // subtype (TrueType), PS name, font program (stream), advance width of each glyph // glyph space: 1/1000 of text space // text space: controlled by text maxtrix (Tm op) and text size (Tf op) based on user space // Td op: place current text position (origin of text space) in user space // glyph displacement vector translates text space when showing a glyph, based on font metrics // writing mode: 0 is horizontal, 1 is vertical // vertical: no “vhea” and “vmtx” tables, DW2 and W2 entries in a CIDFont dict // more than 1 byte per glyph ID: composite fonts // Embedded font stream dictionary: /Length1 decoded TrueType size // TrueType tables required: // “head”, “hhea”, “loca”, “maxp”, “cvt”, “prep”, “glyf”, “hmtx”, and “fpgm” // Subset: prefix /BaseFont name with 6 upper case letters // (identifying this subset) and "+" // Probably won’t use: // Word spacing = character spacing for ASCII space 0x20 single-byte code // Leading = height between consecutive baselines Ok(()) } fn set_alpha(&mut self, alpha: f32) { let alpha = alpha.max(0.).min(1.); if alpha != self.graphics_state.alpha { self.graphics_state.alpha = alpha; // Use u16 instead of f32 as a hash key because f32 does not implement Eq, // and to do some rounding in case float computation // produces very close but different values. // // Map 0.0 to 0, 1.0 to max let hash_key = (alpha * (u16::max_value() as f32)) as u16; let next_id = self.doc.alpha_states.len(); let states = &mut self.doc.extended_graphics_states; let pdf_key = self.doc.alpha_states.entry(hash_key).or_insert_with(|| { let pdf_key = format!("a{}", next_id); states.push(( pdf_key.clone().into_bytes(), Object::GraphicsStateDictionaryAlpha(alpha), )); pdf_key }); op!(self, EXTENDED_GRAPHICS_STATE, &*pdf_key); } } fn add_font(&mut self, font: &Arc<Font>) -> Result<String, FontError> { let next_id = self.doc.fonts.len(); let vacant_entry = match self.doc.fonts.entry(ByAddress(font.clone())) { Entry::Occupied(entry) => return Ok(entry.get().clone()), Entry::Vacant(entry) => entry, }; let font_bytes = font.bytes(); let truetype_id = self.doc.pdf.add_stream( dictionary! { "Length1" => font_bytes.len(), }, font_bytes.into(), ); let font_descriptor_id = self.doc.pdf.add_dictionary(dictionary! { "Type" => "FontDescriptor", "FontName" => font.postscript_name(), "FontBBox" => array![ font.min_x(), font.min_y(), font.max_x(), font.max_y(), ], "Ascent" => font.ascender(), "Descent" => font.descender(), "FontFile2" => truetype_id, // These seem somewhat arbitrary, they’re copied from cairo: "ItalicAngle" => 0, "Flags" => 4, "CapHeight" => font.max_y(), "StemV" => 80, "StemH" => 80, }); // Boilerplate based on a PDF generated by cairo let mut to_unicode_cmap = b"\ /CIDInit /ProcSet findresource begin\n\ 12 dict begin\n\ begincmap\n\ /CIDSystemInfo\n\ << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n\ /CMapName /Adobe-Identity-UCS def\n\ /CMapType 2 def\n\ 1 begincodespacerange\n\ <0000> <ffff>\n\ endcodespacerange\n\ " .to_vec(); { let mut write_bfchar = |chars: &[char], glyph_ids: &[u16]| { write!(to_unicode_cmap, "{} beginbfchar\n", chars.len()).unwrap(); for (ch, glyph_id) in chars.iter().zip(glyph_ids) { write!(to_unicode_cmap, "<{:04x}> <", glyph_id).unwrap(); for code_unit in ch.encode_utf16(&mut [0, 0]) { write!(to_unicode_cmap, "{:04x}", code_unit).unwrap() } to_unicode_cmap.extend(b">\n"); } to_unicode_cmap.extend(b"endbfchar\n"); }; // Max 100 entries per beginbfchar operator let mut chars = ['\0'; 100]; let mut glyph_ids = [0_u16; 100]; let mut i = 0; font.each_code_point(|ch, GlyphId(glyph_id)| { if i >= 100 { write_bfchar(&chars, &glyph_ids); i = 0 } chars[i] = ch; glyph_ids[i] = glyph_id; i += 1; })?; if i > 0 { write_bfchar(&chars[..i], &glyph_ids[..i]) } } to_unicode_cmap.extend( b"\ endcmap\n\ CMapName currentdict /CMap defineresource pop\n\ end\n\ end\ " .as_ref(), ); let to_unicode_id = self .doc .pdf .add_stream(dictionary! {}, to_unicode_cmap.into()); // Type 0 Font Dictionaries // https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf#G8.1859105 // FIXME: revert to direct object let mut glyph_widths = Vec::with_capacity(font.glyph_count() as usize); for i in 0..font.glyph_count() { glyph_widths.push(Object::from(font.glyph_width(GlyphId(i))?)); } let font_dict_id = self.doc.pdf.add_dictionary(dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => font.postscript_name(), "ToUnicode" => to_unicode_id, // 2-bytes big-endian char codes, horizontal writing mode: "Encoding" => "Identity-H", "DescendantFonts" => array![dictionary! { "Type" => "Font", "Subtype" => "CIDFontType2", "BaseFont" => font.postscript_name(), "CIDSystemInfo" => dictionary! { "Registry" => Object::LiteralString(b"Adobe"), "Ordering" => Object::LiteralString(b"Identity"), "Supplement" => 0, }, "FontDescriptor" => font_descriptor_id, "W" => array![ 0, // start CID &*glyph_widths, ], }], }); let pdf_key = format!("f{}", next_id); self.doc .font_resources .push((pdf_key.clone().into_bytes(), font_dict_id.into())); vacant_entry.insert(pdf_key.clone()); Ok(pdf_key) } } macro_rules! operators { ($( $name: ident = $value: expr, )+) => { $( const $name: &'static str = $value; )+ } } // PDF Content Stream Operators // https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf#G14.1032355 operators! { // Graphics State Operators // https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf#G7.3793795 CURRENT_TRANSFORMATION_MATRIX = "cm", EXTENDED_GRAPHICS_STATE = "gs", // Path Construction and Painting // https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf#G7.1849957 RECTANGLE = "re", FILL = "f", // Colour Spaces // https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf#G7.1850197 NON_STROKING_RGB_COLOR = "rg", // Text // https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf#G8.1910927 BEGIN_TEXT = "BT", END_TEXT = "ET", TEXT_FONT_AND_SIZE = "Tf", TEXT_MATRIX = "Tm", SHOW_TEXT = "Tj", }
#!/usr/bin/perl -w use strict; use Getopt::Std; # - - - - - H E A D E R - - - - - - - - - - - - - - - - - #Goals of script: #Use idxstats and bins from DASTool to generate a total number of reads recruiting to each bin. # - - - - - U S E R V A R I A B L E S - - - - - - - - # - - - - - G L O B A L V A R I A B L E S - - - - - - my %options=(); getopts("b:i:x:o:h", \%options); if ($options{h}) { print "\n\nHelp called:\nOptions:\n"; print "-b = path to bin folder\n"; print "-x = bin file suffix (i.e. fasta, fa, fna, etc)\n"; print "-i = idxstats file from samtools\n"; print "-o = output prefix\n"; print "-h = This help message\n\n"; die; } my %Sequences; my %Bin_names; # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # - - - - - M A I N - - - - - - - - - - - - - - - - - - - - # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - opendir(DIR, "$options{b}") or die "\n\nNada $options{b} you fool!!\n\n"; my $fastaread = 1; while (my $file = readdir(DIR)) { my $binsuffix = qr/$options{x}/; if ($file =~ m/$binsuffix$/) { $Bin_names{$file}{'Name'} = $file; $Bin_names{$file}{'FileNum'} = $fastaread; $Bin_names{$file}{'total_reads'} = 0; &FASTAread($file, $fastaread); $fastaread += 1; } } open(IN2, "<$options{i}") or die "\n\nNADA $options{i} you FOOL!!!\n\n"; my @idx_data = <IN2>; close(IN2); foreach my $line (@idx_data) { chomp($line); my @data = split('\t', $line); my $seq_header = $data[0]; chomp($seq_header); if (exists $Sequences{$seq_header}) { $Sequences{$seq_header}{'READ_COUNT'} = $data[2];} else {print "This contig seems to be erroneous: $seq_header\n";} } foreach my $i (sort keys %Bin_names) { foreach my $j (sort keys %Sequences) { my $test1 = $Sequences{$j}{'filename'}; #print "Sequence file name: $test1\n"; my $test2 = $Bin_names{$i}{'Name'}; #print "Bin file name: $test2\n"; if ($test1 eq $test2) { $Bin_names{$i}{'total_reads'} += $Sequences{$j}{'READ_COUNT'}; } } } open(OUT, ">".$options{o}."_readrecruitment.txt"); foreach my $m (sort keys %Bin_names) { my $total_reads = $Bin_names{$m}{'total_reads'}; print OUT "$Bin_names{$m}{'Name'}\t$total_reads\n"; } close(OUT); # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # - - - - - S U B R O U T I N E S - - - - - - - - - - - # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub FASTAread { #print " Reading file . . . \n"; # 1. Load FIlE . . . . . . . . . . $/=">"; # set input break string my $infile = $_[0]; my $filenumber = $_[1]; my $path = $options{b}; open(IN, "<".$path."/".$infile) or die "\n\nNADA $path/$infile you FOOL!!!\n\n"; my @DATA = <IN>; close(IN); shift(@DATA); # 2. Parse sequence data . . . . . . . . . . . . . #my $unid = $filenumber.100000001; string to generate unique ids foreach my $entry (@DATA) { my @data = split('\n', $entry); #my $seq = ''; #foreach my $i (1..$#data) #{ $seq .= $data[$i]; } #$seq =~ s/>//; $Sequences{$data[0]}{'HEAD'} = $data[0]; # store header my @shorthead = split(' ', $data[0]); $Sequences{$data[0]}{'SHORT_HEAD'} = $shorthead[0]; $Sequences{$data[0]}{'READ_COUNT'} = 0; #$Sequences{$unid}{'gappy-ntseq'} = uc($seq); # store aligned sequence #$Sequences{$unid}{'SIZE'} = length($seq); # store length #$seq =~ s/\.//; #$seq =~ s/\-//; #$Sequences{$unid}{'degapped-ntseq'} = uc($seq); # store degapped sequence $Sequences{$data[0]}{'filenumber'} = $filenumber; $Sequences{$data[0]}{'filename'} = $infile; #$unid += 1; } $/="\n"; } # - - - - - EOF - - - - - - - - - - - - - - - - - - - - - -
package ast func convertSliceMap(i interface{}) []m { var m []m for _, mm := range i.([]interface{}) { m = append(m, convertMap(mm)) } return m } func convertMap(i interface{}) m { return m(i.(map[string]interface{})) } func convertString(i interface{}) string { return i.(string) } func convertInt(i interface{}) int { return int(i.(float64)) } func convertFloat(i interface{}) float64 { return i.(float64) } func convertBool(i interface{}) bool { return i.(bool) }
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ // https://leetcode.com/problems/add-one-row-to-tree/description/ func addOneRow(root *TreeNode, v int, d int) *TreeNode { if root == nil { return nil } if d == 1 { t := &TreeNode{Val: v, Left: root} return t } else if d == 2 { left := &TreeNode{Val: v, Left: root.Left} root.Left = left right := &TreeNode{Val: v, Right: root.Right} root.Right = right } else if d > 2 { root.Left = addOneRow(root.Left, v, d-1) root.Right = addOneRow(root.Right, v, d-1) } return root }
module PlayerRequestHelper def make_valid_player_param_hash(player) param = player.attributes param.delete 'id' param end def make_invalid_player_param_hash(player) param = make_valid_player_param_hash(player) param['name'] = '' param end end RSpec.configure do |config| config.include PlayerRequestHelper, type: :controller end
trait A trait B trait C trait D object Test { type AB = A with B val list: List[AB with C] = Nil list.collect { case d: D => d } }
using System; namespace SpoolerWatcher { public interface ISpoolWatcher : IDisposable { event EventHandler<SpoolNotificationEventArgs> SpoolerNotificationReached; PrinterNotifyFilters PrinterNotifyFilter { get; set; } JobNotifyFilters JobNotifyFilter { get; set; } PrinterChange PrinterChange { get; set; } void Start(); void Stop(); } }
--- layout: post title: A More Subtle Wordpress Security Hole permalink: /2009/09/subtle-wordpress-security-hole --- This has come up twice in one day over here at the Haystack group, so I thought I'd post it here. Using Emacs and Vi to configure Wordpress can expose your database login and password to the world. Here is why: Wordpress stores this configuration information in a file called wp-config.php that lives in the root of your install. This files contents aren't visible to web visitors because its .php extension causes to be interpreted by PHP instead of returned to the web user. Emacs, by default, will save a backup file of anything you edit in the same directory. This file will end with a tilde character (~). This means that if you use a non-customized version of Emacs to edit your wp-config.php file, you'll get a second file called wp-config.php~. The .php~ extension is not registered to any particular MIME type, and so it will be returned, in full, to the remote user as text, revealing your database server, login, and password with it. So please, if you use Emacs and have Wordpress, check your WP install directory for any Emacs backup files and delete them! There's enough Wordpress hackery going around already this week :)
class Task5 { public static void main(String[] args) { Student student1 = new Student(); Student student2 = new Student(); Student student3 = new Student(); Student student4 = new Student(); Student student5 = new Student(); Student student6 = new Student(); Student student7 = new Student(); Student student8 = new Student(); Student student9 = new Student(); Student student10 = new Student(); student1.setInfo("Yasir",20,"Room no 212"); student2.setInfo("Usama",18,"Room no 212"); student3.setInfo("Meesum",25,"Room no 213"); student4.setInfo("Mehtab",17,"Room no 213"); student5.setInfo("Toseef",18,"Room no 226"); student6.setInfo("Hakim",18,"Room no 226"); student7.setInfo("Hassnain",18,"Room no 226"); student8.setInfo("Moiz",17,"Room no 126"); student9.setInfo("Altamash",18,"Room no 125"); student10.setInfo("Zain",20,"Room no 123"); Student[] students = {student1,student2,student3,student4,student5,student6,student7,student8,student9,student10}; for(int i=0;i<students.length;i++) { System.out.println(students[i].toString()); } } } class Student{ private String name; private int age; private String address; public Student() { this.name="Unknown"; this.age=0; this.address="Not available"; } public void setInfo(String name,int age) { this.name=name; this.age=age; } public void setInfo(String name,int age,String address) { this.name=name; this.age=age; this.address=address; } public String toString() { return ("Name = "+name+", Age = "+age+", Adress = "+address); } }
""" The `Format` module provides a public interface that can be used to define custom formatters aside from the predefined HTML and LaTeX outputs supported by `Highlights`. The [Formatting](@ref) section of the manual provides a example of how to go about extending `Highlights` to support additional output formats. The following functions and types are exported from the module for public use: $(EXPORTS) """ module Format using DocStringExtensions import ..Highlights import ..Highlights.Compiler: Context import ..Highlights.Themes: RGB, Style, Theme import ..Highlights.Tokens export TokenIterator, render """ The `render` function is used to define custom output formats for tokenised source code. Methods with signatures of the form ```julia function Format.render(io::IO, mime::MIME, tokens::Format.TokenIterator) # ... for (str, id, style) in tokens # ... end # ... end ``` can be defined for any `mime` type to allow the [`highlight`](@ref Highlights.highlight) function to support new output formats. """ function render end # RGB colours. render(io::IO, ::MIME"text/css", c::RGB) = (print(io, "rgb("); _tup(io, c); print(io, ")")) render(io::IO, ::MIME"text/latex", c::RGB) = (print(io, "[RGB]{"); _tup(io, c); print(io, "}")) _tup(io::IO, c::RGB) = print(io, Int(c.r), ",", Int(c.g), ",", Int(c.b)) # Styles. function render(io::IO, mime::MIME"text/css", style::Style) if style.fg.active print(io, "color: ") render(io, mime, style.fg) print(io, "; ") end if style.bg.active print(io, "background-color: ") render(io, mime, style.bg) print(io, "; ") end style.bold && print(io, "font-weight: bold; ") style.italic && print(io, "font-style: italic; ") style.underline && print(io, "text-decoration: underline; ") return nothing end function render(io::IO, mime::MIME"text/latex", style::Style) print(io, "[1]{") if style.fg.active print(io, "\\textcolor") render(io, mime, style.fg) print(io, "{") end if style.bg.active print(io, "\\colorbox") render(io, mime, style.bg) print(io, "{") end style.bold && print(io, "\\textbf{") style.italic && print(io, "\\textit{") style.underline && print(io, "\\underline{") print(io, "#1") style.underline && print(io, "}") style.italic && print(io, "}") style.bold && print(io, "}") style.bg.active && print(io, "}") style.fg.active && print(io, "}") print(io, "}") end # Stylesheets. function render(io::IO, mime::MIME"text/css", theme::Theme) print(io, """ pre.hljl { border: 1px solid #ccc; margin: 5px; padding: 5px; overflow-x: auto; """ ) render(io, mime, theme.base) println(io, "}") for (nth, style) in enumerate(theme.styles) print(io, "pre.hljl > span.hljl-", Tokens.__SHORTNAMES__[nth], " { ") render(io, mime, style) println(io, "}") end end function render(io::IO, ::MIME"text/html", theme::Theme) println(io, "\n<style>") render(io, MIME"text/css"(), theme) println(io, "</style>\n") end function render(io::IO, mime::MIME"text/latex", theme::Theme) println(io, "\\usepackage{upquote}") println(io, "\\usepackage{listings}") println(io, "\\usepackage{xcolor}") print(io, """ \\lstset{ basicstyle=\\ttfamily\\footnotesize, upquote=true, breaklines=true, breakindent=0pt, keepspaces=true, showspaces=false, columns=fullflexible, showtabs=false, showstringspaces=false, escapeinside={(*@}{@*)}, extendedchars=true, } """ ) for (nth, style) in enumerate(theme.styles) print(io, "\\newcommand{\\HLJL", Tokens.__SHORTNAMES__[nth], "}") render(io, mime, style) println(io) end end # Token Iterator. """ $(TYPEDEF) An iterator type used in user-defined [`render`](@ref) methods to provide custom output formats. This type supports the basic Julia iterator protocol: namely `iterate` which enables `for`-loop interation over tokenised text. The iterator returns a 3-tuple of `str`, `id`, and `style` where * `str` is the `SubString` covered by the token; * `id` is the shorthand name of the token type as a `Symbol`; * `style` is the `Style` applied to the token. """ struct TokenIterator ctx::Context theme::Theme end Base.iterate(t::TokenIterator) = isempty(t.ctx.tokens) ? nothing : iterate(t::TokenIterator, 1) Base.length(t::TokenIterator) = length(t.ctx.tokens) function Base.iterate(t::TokenIterator, state) (state > length(t)) && return nothing token = t.ctx.tokens[state] result = ( SubString(t.ctx.source, token.first, token.last), Tokens.__SHORTNAMES__[token.value.value], t.theme.styles[token.value.value], ) return result, state + 1 end # Code blocks. render(io::IO, mime::MIME, ctx::Context, theme::Theme) = render(io, mime, TokenIterator(ctx, theme)) function render(io::IO, mime::MIME"text/html", tokens::TokenIterator) println(io, "<pre class='hljl'>") for (str, id, style) in tokens print(io, "<span class='hljl-") print(io, id, "'>") escape(io, mime, str) print(io, "</span>") end println(io, "\n</pre>") end const CONSECUTIVE_WHITESPACE = r"\s+" function print_formatted(io::IO,mime::MIME"text/latex",str,id,style) id === :t || print(io, "(*@\\HLJL", id, "{") escape(io, mime, str; charescape=(id === :t)) id === :t || print(io, "}@*)") end function render_nonwhitespace(io::IO,mime::MIME"text/latex",str,id,style) # Whitespace chars within an escapeinside are not correctly printed in a # lstlisting env. So in order to have the correct highlighting # and correct characters, that are recognized by listings, they need to be # added outside of the escapeinside. offset = 1 for m in eachmatch(CONSECUTIVE_WHITESPACE,str) whitespace = m.match nonwhitespace = str[offset:prevind(str,m.offset)] offset = nextind(str,m.offset,length(whitespace)) length(nonwhitespace) > 0 && print_formatted(io,mime,nonwhitespace,id,style) print(io,whitespace) end nonwhitespace = str[offset:end] length(nonwhitespace) > 0 && print_formatted(io,mime,str[offset:end],id,style) end function render(io::IO, mime::MIME"text/latex", tokens::TokenIterator) println(io, "\\begin{lstlisting}") for (str, id, style) in tokens render_nonwhitespace(io,mime,str,id,style) end println(io, "\n\\end{lstlisting}") end # Character escapes. function escape(io::IO, ::MIME"text/html", str::AbstractString) for char in str char === '&' ? print(io, "&amp;") : char === '<' ? print(io, "&lt;") : char === '>' ? print(io, "&gt;") : char === '"' ? print(io, "&quot;") : char === '\'' ? print(io, "&#39;") : print(io, char) end end function escape(io::IO, ::MIME"text/latex", str::AbstractString; charescape=false) for char in str char === '`' ? printe(io, charescape, "{\\textasciigrave}") : char === '\'' ? printe(io, charescape, "{\\textquotesingle}") : char === '$' ? printe(io, charescape, "{\\\$}") : char === '%' ? printe(io, charescape, "{\\%}") : char === '#' ? printe(io, charescape, "{\\#}") : char === '&' ? printe(io, charescape, "{\\&}") : char === '\\' ? printe(io, charescape, "{\\textbackslash}") : char === '^' ? printe(io, charescape, "{\\textasciicircum}") : char === '_' ? printe(io, charescape, "{\\_}") : char === '{' ? printe(io, charescape, "{\\{}") : char === '}' ? printe(io, charescape, "{\\}}") : char === '~' ? printe(io, charescape, "{\\textasciitilde}") : char === '"' ? printe(io, charescape, "\"{}") : print(io, char) end end function printe(io::IO, charescape::Bool, s) charescape && print(io, "(*@{") print(io, s) charescape && print(io, "}@*)") end end # module
<?php namespace Teacher\Controller; use Think\Controller; class CommonController extends Controller{ public function __initialize() { $this->checkUser(); //检查登陆 $this->checkSelected(); //检查是否选择了年份 } //检查登陆 public function checkUser() { if (!session('?Tnum')){ $this->error('请登录',U('teacher/Login/index')); exit; } //分配模板变量 $role=$_SESSION['role']; $this->assign('role',$role); } //检查是否选择了年份 public function checkSelected() { $config = M('config'); $count = $config->where('status=1')->count(); $role = $_SESSION['role']; if (!session('?selected_year')){ if($count == 0 && $role ==3){ $this->error('请先开发系统',U('teacher/config/index')); }else{ $this->error('请选择年份',U('teacher/index/select_year')); exit; } } } public function mypage($count,$pagenumber) { $Page = new \Think\Page($count,$pagenumber);//实例化分页类记录数和每页显示的记录数 // 修改分页样式 $Page->setConfig('header', '共%TOTAL_ROW%条数据,当前第%NOW_PAGE%/%TOTAL_PAGE%页'); $Page->setConfig('prev', '上一页'); $Page->setConfig('first', '首页'); $Page->setConfig('last', '尾页'); $Page->setConfig('next', '下一页'); $Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%'); // 返回分页对象 return $Page; } /** * 公共数据创建方法 * @param string $tablename 表名 * @param string $func 操作方法 * @param int $type 验证时机(1=添加 2=修改) * @param string/array $where 查询条件 * @return mixed 操作结果 */ protected function create($tablename,$func,$type=1,$where=array()) { $Model = D($tablename); if(!$Model->create(I('post.'),$type)){ $this->error($Model->getError()); } if(empty($where)){ return $Model->$func(); } return $Model->where($where)->$func(); } }
// SPDX-License-Identifier: MIT OR Apache-2.0 use std::{ collections::HashSet, env, io::{self, BufRead}, path::{Path, PathBuf}, }; use clap::{crate_authors, crate_name, crate_version, App, AppSettings, Arg, ArgMatches}; use taxonate::config::{Color, Config, LogLevel}; pub fn build() -> App<'static, 'static> { let color = env::var("TAXONATE_COLOR").unwrap_or_else(|_| "auto".to_owned()); let color_app_setting = match color.as_str() { "always" => AppSettings::ColorAlways, "never" => AppSettings::ColorNever, _ => AppSettings::ColorAuto, }; App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .setting(AppSettings::AllowInvalidUtf8) .setting(AppSettings::ColoredHelp) .setting(color_app_setting) .about( "Identify and filter files based on their programming language.\n\n\ Use '--help' instead of '-h' to see a more detailed version of the \ help text.", ) .long_about("Identify and filter files based on their programming language.") .arg( Arg::with_name("filename_only") .help("Suppresses display of the identified language") .long_help( "Suppresses normal output; only displays the file name and \ not the identified programming language", ) .short("f") .long("filename-only"), ) .arg( Arg::with_name("list_languages") .help("Lists supported programming languages") .long_help( "Displays a list of supported programming languages for \ filtering output", ) .short("L") .long("list-languages"), ) .arg( Arg::with_name("color") .help("Specifies when to use colored output") .short("c") .long("color") .takes_value(true) .value_name("WHEN") .possible_values(&["auto", "always", "never"]) .env("TAXONATE_COLOR") .default_value("auto"), ) .arg( Arg::with_name("debug") .help("Adjusts the log level for debugging") .short("d") .long("debug") .takes_value(true) .value_name("LEVEL") .possible_values(&["error", "warning", "info", "debug", "trace"]) .env("TAXONATE_DEBUG") .default_value("error"), ) .arg( Arg::with_name("language") .help("Filters output by programming language") .long_help( "Filters output to only show files identified as the given \ programming language", ) .short("l") .long("language") .takes_value(true) .value_name("LANGUAGE") .env("TAXONATE_LANGUAGE"), ) .arg( Arg::with_name("PATH") .help("File or directory to identify. Use '-' for standard input.") .long_help( "A file or directory to identify. Directories will have \ all files identified recursively. Use a dash ('-') to \ read from standard input.", ) .multiple(true), ) } pub fn config_from(matches: &ArgMatches) -> Config { // unwrap is safe since we specify a default let color = match matches.value_of("color").unwrap() { "auto" => Color::Auto, "always" => Color::Always, "never" => Color::Never, _ => unreachable!(), }; let filename_only = matches.is_present("filename_only"); // unwrap is safe since we specify a default let log_level = match matches.value_of("debug").unwrap() { "error" => LogLevel::Error, "warning" => LogLevel::Warning, "info" => LogLevel::Info, "debug" => LogLevel::Debug, "trace" => LogLevel::Trace, _ => unreachable!(), }; let language = matches.value_of("language").map(String::from); let mut paths: HashSet<PathBuf> = matches .values_of_os("PATH") .unwrap_or_default() .map(PathBuf::from) .collect(); // include paths from STDIN, if explicitly requested if paths.remove(Path::new("-")) { let stdin = io::stdin(); for line in stdin.lock().lines() { paths.insert(PathBuf::from(line.unwrap())); } } if paths.is_empty() { // default to the current working directory paths.insert(PathBuf::from(".")); } Config::new() .set_color(color) .set_filename_only(filename_only) .set_log_level(log_level) .set_language(language) .set_paths(paths) }
# frozen_string_literal: true require_relative "../spec/fixtures/cranky_process.rb" supervisor = RubyEx::Supervisor.start( [ RubyEx::Supervisor::ChildSpec.new("cranky", CrankyProcess, :start, [5]) ] ) child = RubyEx::Supervisor.children(supervisor).first CrankyProcess.double(child) CrankyProcess.double(child) p "Getting state" p CrankyProcess.get_state(child) p "Crashing Process" CrankyProcess.crash(child) sleep(0.5) child = RubyEx::Supervisor.children(supervisor).first p "Getting new state" p CrankyProcess.get_state(child)
class Course { String name; double completedPercentage; String author; String thumbnail; Course({ required this.author, required this.completedPercentage, required this.name, required this.thumbnail, }); } List<Course> courses = [ Course( author: "Кубаныч Асанов", completedPercentage: 1, name: "SQL кыргыз тилинде", thumbnail: "assets/icons/SQL-icon.jpg", ), Course( author: "Кубаныч Асанов", completedPercentage: .75, name: "Flutter курсу", thumbnail: "assets/icons/flutter.jpg", ), Course( author: "Кубаныч Асанов", completedPercentage: .60, name: "React курсу", thumbnail: "assets/icons/react.jpg", ), Course( author: "Кубаныч Асанов", completedPercentage: .75, name: "Node - толук курс", thumbnail: "assets/icons/node.png", ), Course( author: "Кубаныч Асанов", completedPercentage: 1, name: "SQL кыргыз тилинде", thumbnail: "assets/icons/SQL-icon.jpg", ), ];
# Implements weighted randomization for a group of weighted items. # This class expects a hash of key -> value pairs where the value is # the weight for the item. # # @example Usage # wr = WeightedRandomizer.new('queue1' => 25, 'queue2' => 100, 'queue3' => 2) # puts "Using queue #{wr.sample}" # # @note Mostly adapted from recipe 5.11 from the Ruby Cookbook. class WeightedRandomizer VERSION = '0.1.2' # Creates a new instance. # # @param [Hash] items the weighted items (key item, value weight) # @return [WeightedRandomizer] def initialize(items) @items = normalize(items) end # Returns one or more weighted random values. # # @param [Integer] num the number of samples to return # @return [Object, Array<Object>] one or more sampled items def sample(num = nil) return _sample unless num Array.new(num) { _sample } end private # Returns a single weighted random value. # # @return [Object] the weighted item def _sample pick = rand @items.each do |key, weight| return key if pick <= weight pick -= weight end nil end # Normalizes the weights to float values so that # arbitrary integer/float weights can be specified. # # @param [Hash] items the weighted items (key item, value weight) # @return [Hash] the items with their weights normalized def normalize(items) normalized = {} sum = items.values.inject(0.0, :+) items.each do |key, weight| normalized[key] = weight / sum end normalized end end
module Roby module Tasks # This task class can be used to monitor the execution of an external # process. Among the useful features, it can redirect standard output and # error output to files. # # The events will act as follows: # * the start command starts the process per se. The event is emitted once # exec() has been called with success # * the signaled event is emitted when the process dies because of a signal # * the failed event is emitted whenever the process exits with a nonzero # status # * the success event is emitted when the process exits with a zero status # * the stop event is emitted when the process exits class ExternalProcess < Roby::Task ## # :attr_reader: # This task argument is an array whose first element is the executable # to start and the rest the arguments that need to be passed to it. # # It can also be set to a simple string, which is interpreted as the # executable name with no arguments. argument :command_line ## # :attr_reader: # The working directory. If not set, the current directory is used. argument :working_directory # Redirection specification. See #redirect_output attr_reader :redirection def initialize(arguments) arguments[:working_directory] ||= nil arguments[:command_line] = [arguments[:command_line]] unless arguments[:command_line].kind_of?(Array) super(arguments) end class << self # The set of running ExternalProcess instances. It is a mapping # from the PID value to the instances. attr_reader :processes end @processes = Hash.new # Called by the SIGCHLD handler to announce that a particular process # has finished. It calls #dead!(result) in the context of the execution # thread, on the corresponding task def self.dead!(pid, result) # :nodoc: task = processes[pid] return if !task if engine = task.plan.engine engine.once { task.dead!(result) } end end # Called to announce that this task has been killed. +result+ is the # corresponding Process::Status object. def dead!(result) if !result emit :failed elsif result.success? emit :success elsif result.signaled? emit :signaled, result else emit :failed, result end end # This event gets emitted if the process died because of a signal event :signaled forward :signaled => :failed ## # If set to a string, the process' standard output will be redirected to # the given file. The following replacement is done: # * '%p' is replaced by the process PID # # The last form (with nil argument) removes any redirection. A specific # redirection can also be disabled using the hash form: # redirect_output :stdout => nil # # :call-seq: # redirect_output "file" # redirect_output :stdout => "file-out", :stderr => "another-file" # redirect_output nil # def redirect_output(args) if !args @redirection = nil elsif args.respond_to? :to_str @redirection = args.to_str else args = validate_options args, :stdout => nil, :stderr => nil if args[:stdout] == args[:stderr] @redirection = args[:stdout].to_str else @redirection = Hash.new @redirection[:stdout] = args[:stdout].to_str if args[:stdout] @redirection[:stderr] = args[:stderr].to_str if args[:stderr] end end end # The PID of the child process, or nil if the child process is not # running attr_reader :pid # Error codes between the child and the parent. Note that the error # codes must not be greater than 9 # :stopdoc: KO_REDIRECTION = 1 KO_NO_SUCH_FILE = 2 KO_EXEC = 3 # :startdoc: # Returns the file name based on the redirection pattern and the current # PID values. This is called in the child process before exec(). def redirection_path(pattern) # :nodoc: pattern.gsub '%p', Process.pid.to_s end # Starts the child process def start_process # :nodoc: # Open a pipe to monitor the child startup r, w = IO.pipe @pid = fork do # Open the redirection outputs stdout, stderr = nil begin if redirection.respond_to?(:to_str) stdout = stderr = File.open(redirection_path(redirection), "w") elsif redirection if stdout_file = redirection[:stdout] stdout = File.open(redirection_path(stdout_file), "w") end if stderr_file = redirection[:stderr] stderr = File.open(redirection_path(stderr_file), "w") end end rescue Exception => e Roby.log_exception_with_backtrace(e, Roby, :error) w.write("#{KO_REDIRECTION}") return end STDOUT.reopen(stdout) if stdout STDERR.reopen(stderr) if stderr r.close w.fcntl(Fcntl::F_SETFD, 1) # set close on exit ::Process.setpgrp begin exec(*command_line) rescue Errno::ENOENT w.write("#{KO_NO_SUCH_FILE}") rescue Exception => e Roby.log_exception_with_backtrace(e, Roby, :error) w.write("#{KO_EXEC}") end end ExternalProcess.processes[pid] = self w.close begin read, _ = select([r], nil, nil, 5) rescue IOError Process.kill("SIGKILL", pid) retry end if read && (control = r.read(1)) case Integer(control) when KO_REDIRECTION raise "could not start #{command_line.first}: cannot establish output redirections" when KO_NO_SUCH_FILE raise "could not start #{command_line.first}: provided command does not exist" when KO_EXEC raise "could not start #{command_line.first}: exec() call failed" end end # This block is needed as there is a race condition between the fork # and the assignation to ExternalProcess.processes (which is # required for the SIGCHLD handler to work). begin if Process.waitpid(pid, ::Process::WNOHANG) if exit_status = $? exit_status = exit_status.dup end engine.once { dead!(pid, exit_status) } return end rescue Errno::ECHILD end rescue Exception => e ExternalProcess.processes.delete(pid) raise e end ## # :method: start! # # Starts the child process. Emits +start+ when the process is actually # started. event :start do |context| if working_directory Dir.chdir(working_directory) do start_process end else start_process end emit :start end # Kills the child process def kill(signo) Process.kill(signo, pid) end on :stop do |event| ExternalProcess.processes.delete(pid) end end def ExternalProcess.handle_terminated_children(plan) begin while pid = ::Process.wait(-1, ::Process::WNOHANG) if exit_status = $? exit_status = exit_status.dup end Roby.debug { "external process #{pid} terminated" } Tasks::ExternalProcess.dead! pid, exit_status end rescue Errno::ECHILD end end Roby::ExecutionEngine.add_propagation_handler(&ExternalProcess.method(:handle_terminated_children)) end end
static const auto fastIO = []() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); return 0; }(); class Solution { public: string capitalizeTitle(string title) { } };
package com.fexo.wordcloud.controller; import com.fexo.wordcloud.service.WordCloudService; import io.swagger.annotations.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author wangfeixiong */ @Api(description = "生成词语的接口类") @RestController public class WordCloudController { @Autowired private WordCloudService service; @ApiOperation(value = "获取词云图片的方法") @PostMapping("getWordCouldImage") public void getWordCloudImg(@ApiParam(value = "生成词云图片的文字") @RequestBody String text, HttpServletResponse response) throws IOException { response.setContentType("image/png"); service.getImg(text, response.getOutputStream()); } }
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.1 (2013/07/14) #include "Lights.h" WM5_WINDOW_APPLICATION(Lights); //---------------------------------------------------------------------------- Lights::Lights () : WindowApplication3("SampleGraphics/Lights", 0, 0, 800, 600, Float4(0.0f, 0.25f, 0.75f, 1.0f)), mTextColor(1.0f, 1.0f, 1.0f, 1.0f) { } //---------------------------------------------------------------------------- bool Lights::OnInitialize () { if (!WindowApplication3::OnInitialize()) { return false; } // Set up the camera. mCamera->SetFrustum(60.0f, GetAspectRatio(), 0.1f, 100.0f); APoint camPosition(16.0f, 0.0f, 8.0f); AVector camDVector = APoint::ORIGIN - camPosition; // look at origin camDVector.Normalize(); AVector camUVector(camDVector[2], 0.0f, -camDVector[0]); AVector camRVector(0.0f, 1.0f, 0.0f); mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector); CreateScene(); // Initial update of objects. mScene->Update(); // Initial culling of scene. mCuller.SetCamera(mCamera); mCuller.ComputeVisibleSet(mScene); InitializeCameraMotion(0.01f, 0.001f); InitializeObjectMotion(mScene); return true; } //---------------------------------------------------------------------------- void Lights::OnTerminate () { mScene = 0; mWireState = 0; mPlane0 = 0; mSphere0 = 0; mPlane1 = 0; mSphere1 = 0; for (int i = 0; i < 3; ++i) { mLight[i][0] = 0; mLight[i][1] = 0; mInstance[i][0][0] = 0; mInstance[i][0][1] = 0; mInstance[i][1][0] = 0; mInstance[i][1][1] = 0; } WindowApplication3::OnTerminate(); } //---------------------------------------------------------------------------- void Lights::OnIdle () { MeasureTime(); if (MoveCamera()) { mCuller.ComputeVisibleSet(mScene); } if (MoveObject()) { mScene->Update(); mCuller.ComputeVisibleSet(mScene); } if (mRenderer->PreDraw()) { mRenderer->ClearBuffers(); mRenderer->Draw(mCuller.GetVisibleSet()); mRenderer->Draw(8, 16, mTextColor, mCurrentCaption); DrawFrameRate(8, GetHeight()-8, mTextColor); mRenderer->PostDraw(); mRenderer->DisplayColorBuffer(); } UpdateFrameCount(); } //---------------------------------------------------------------------------- bool Lights::OnKeyDown (unsigned char key, int x, int y) { if (WindowApplication3::OnKeyDown(key, x, y)) { return true; } switch (key) { case 'w': case 'W': mWireState->Enabled = !mWireState->Enabled; return true; case 'd': case 'D': // Switch to directional lights. mPlane0->SetEffectInstance(mInstance[0][0][0]); mSphere0->SetEffectInstance(mInstance[0][0][1]); mPlane1->SetEffectInstance(mInstance[0][1][0]); mSphere1->SetEffectInstance(mInstance[0][1][1]); mCurrentCaption = mCaption[0]; mActiveType = 0; return true; case 'p': case 'P': // Switch to point lights. mPlane0->SetEffectInstance(mInstance[1][0][0]); mSphere0->SetEffectInstance(mInstance[1][0][1]); mPlane1->SetEffectInstance(mInstance[1][1][0]); mSphere1->SetEffectInstance(mInstance[1][1][1]); mCurrentCaption = mCaption[1]; mActiveType = 1; return true; case 's': case 'S': // Switch to spot lights. mPlane0->SetEffectInstance(mInstance[2][0][0]); mSphere0->SetEffectInstance(mInstance[2][0][1]); mPlane1->SetEffectInstance(mInstance[2][1][0]); mSphere1->SetEffectInstance(mInstance[2][1][1]); mCurrentCaption = mCaption[2]; mActiveType = 2; return true; case 'i': mLight[mActiveType][0]->Intensity -= 0.125f; mLight[mActiveType][1]->Intensity -= 0.125f; if (mLight[mActiveType][0]->Intensity < 0.0f) { mLight[mActiveType][0]->Intensity = 0.0f; mLight[mActiveType][1]->Intensity = 0.0f; } return true; case 'I': mLight[mActiveType][0]->Intensity += 0.125f; mLight[mActiveType][1]->Intensity += 0.125f; return true; case 'a': mLight[mActiveType][0]->Angle -= 0.1f; mLight[mActiveType][1]->Angle -= 0.1f; if (mLight[mActiveType][0]->Angle < 0.0f) { mLight[mActiveType][0]->Angle = 0.0f; mLight[mActiveType][1]->Angle = 0.0f; } mLight[mActiveType][0]->SetAngle(mLight[mActiveType][0]->Angle); mLight[mActiveType][1]->SetAngle(mLight[mActiveType][1]->Angle); return true; case 'A': mLight[mActiveType][0]->Angle += 0.1f; mLight[mActiveType][1]->Angle += 0.1f; if (mLight[mActiveType][0]->Angle > Mathf::HALF_PI) { mLight[mActiveType][0]->Angle = Mathf::HALF_PI; mLight[mActiveType][1]->Angle = Mathf::HALF_PI; } mLight[mActiveType][0]->SetAngle(mLight[mActiveType][0]->Angle); mLight[mActiveType][1]->SetAngle(mLight[mActiveType][1]->Angle); return true; case 'e': mLight[mActiveType][0]->Exponent *= 0.5f; mLight[mActiveType][1]->Exponent *= 0.5f; return true; case 'E': mLight[mActiveType][0]->Exponent *= 2.0f; mLight[mActiveType][1]->Exponent *= 2.0f; return true; } return false; } //---------------------------------------------------------------------------- void Lights::CreateScene () { // Create the root of the scene. mScene = new0 Node(); mWireState = new0 WireState(); mRenderer->SetOverrideWireState(mWireState); // Create the lights. mLight[0][0] = new0 Light(Light::LT_DIRECTIONAL); mLight[0][0]->Ambient = Float4(0.75f, 0.75f, 0.75f, 1.0f); mLight[0][0]->Diffuse = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[0][0]->Specular = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[0][0]->SetDirection(AVector(-1.0f, -1.0f, -1.0f)); mLight[0][1] = new0 Light(Light::LT_DIRECTIONAL); mLight[0][1]->Ambient = Float4(0.75f, 0.75f, 0.75f, 1.0f); mLight[0][1]->Diffuse = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[0][1]->Specular = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[0][1]->SetDirection(AVector(-1.0f, -1.0f, -1.0f)); mLight[1][0] = new0 Light(Light::LT_POINT); mLight[1][0]->Ambient = Float4(0.1f, 0.1f, 0.1f, 1.0f); mLight[1][0]->Diffuse = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[1][0]->Specular = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[1][0]->Position = APoint(4.0f, 4.0f - 8.0f, 8.0f); mLight[1][1] = new0 Light(Light::LT_POINT); mLight[1][1]->Ambient = Float4(0.1f, 0.1f, 0.1f, 1.0f); mLight[1][1]->Diffuse = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[1][1]->Specular = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[1][1]->Position = APoint(4.0f, 4.0f + 8.0f, 8.0f); mLight[2][0] = new0 Light(Light::LT_SPOT); mLight[2][0]->Ambient = Float4(0.1f, 0.1f, 0.1f, 1.0f); mLight[2][0]->Diffuse = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[2][0]->Specular = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[2][0]->Position = APoint(4.0f, 4.0f - 8.0f, 8.0f); mLight[2][0]->SetDirection(AVector(-1.0f, -1.0f, -1.0f)); mLight[2][0]->Exponent = 1.0f; mLight[2][0]->SetAngle(0.125f*Mathf::PI); mLight[2][1] = new0 Light(Light::LT_SPOT); mLight[2][1]->Ambient = Float4(0.1f, 0.1f, 0.1f, 1.0f); mLight[2][1]->Diffuse = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[2][1]->Specular = Float4(1.0f, 1.0f, 1.0f, 1.0f); mLight[2][1]->Position = APoint(4.0f, 4.0f + 8.0f, 8.0f); mLight[2][1]->SetDirection(AVector(-1.0f, -1.0f, -1.0f)); mLight[2][1]->Exponent = 1.0f; mLight[2][1]->SetAngle(0.125f*Mathf::PI); // The material shared by the planes (polished copper). Material* copper = new0 Material(); copper->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); copper->Ambient = Float4(0.2295f, 0.08825f, 0.0275f, 1.0f); copper->Diffuse = Float4(0.5508f, 0.2118f, 0.066f, 1.0f); copper->Specular = Float4(0.580594f, 0.223257f, 0.0695701f, 51.2f); // The material shared by the spheres (polished gold). Material* gold = new0 Material(); gold->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); gold->Ambient = Float4(0.24725f, 0.2245f, 0.0645f, 1.0f); gold->Diffuse = Float4(0.34615f, 0.3143f, 0.0903f, 1.0f); gold->Specular = Float4(0.797357f, 0.723991f, 0.208006f, 83.2f); // Create the effects. LightDirPerVerEffect* effectDV = new0 LightDirPerVerEffect(); LightDirPerPixEffect* effectDP = new0 LightDirPerPixEffect(); LightPntPerVerEffect* effectPV = new0 LightPntPerVerEffect(); LightPntPerPixEffect* effectPP = new0 LightPntPerPixEffect(); LightSptPerVerEffect* effectSV = new0 LightSptPerVerEffect(); LightSptPerPixEffect* effectSP = new0 LightSptPerPixEffect(); mInstance[0][0][0] = effectDV->CreateInstance(mLight[0][0], copper); mInstance[0][1][0] = effectDP->CreateInstance(mLight[0][1], copper); mInstance[1][0][0] = effectPV->CreateInstance(mLight[1][0], copper); mInstance[1][1][0] = effectPP->CreateInstance(mLight[1][1], copper); mInstance[2][0][0] = effectSV->CreateInstance(mLight[2][0], copper); mInstance[2][1][0] = effectSP->CreateInstance(mLight[2][1], copper); mInstance[0][0][1] = effectDV->CreateInstance(mLight[0][0], gold); mInstance[0][1][1] = effectDP->CreateInstance(mLight[0][1], gold); mInstance[1][0][1] = effectPV->CreateInstance(mLight[1][0], gold); mInstance[1][1][1] = effectPP->CreateInstance(mLight[1][1], gold); mInstance[2][0][1] = effectSV->CreateInstance(mLight[2][0], gold); mInstance[2][1][1] = effectSP->CreateInstance(mLight[2][1], gold); // Create the objects. The normals are duplicated to texture // coordinates to avoid the AMD lighting problems due to use of // pre-OpenGL2.x extensions. VertexFormat* vformat = VertexFormat::Create(3, VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0, VertexFormat::AU_NORMAL, VertexFormat::AT_FLOAT3, 0, VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT3, 1); StandardMesh sm(vformat); VertexBufferAccessor vba; mPlane0 = sm.Rectangle(128, 128, 8.0f, 8.0f); vba.ApplyTo(mPlane0); for (int i = 0; i < vba.GetNumVertices(); ++i) { vba.TCoord<Float3>(1, i) = vba.Normal<Float3>(i); } mPlane0->LocalTransform.SetTranslate(APoint(0.0f, -8.0f, 0.0f)); mPlane0->SetEffectInstance(mInstance[0][0][0]); mScene->AttachChild(mPlane0); mSphere0 = sm.Sphere(64, 64, 2.0f); vba.ApplyTo(mSphere0); for (int i = 0; i < vba.GetNumVertices(); ++i) { vba.TCoord<Float3>(1, i) = vba.Normal<Float3>(i); } mSphere0->LocalTransform.SetTranslate(APoint(0.0f, -8.0f, 2.0f)); mSphere0->SetEffectInstance(mInstance[0][0][1]); mScene->AttachChild(mSphere0); mPlane1 = sm.Rectangle(128, 128, 8.0f, 8.0f); vba.ApplyTo(mPlane1); for (int i = 0; i < vba.GetNumVertices(); ++i) { vba.TCoord<Float3>(1, i) = vba.Normal<Float3>(i); } mPlane1->LocalTransform.SetTranslate(APoint(0.0f, +8.0f, 0.0f)); mPlane1->SetEffectInstance(mInstance[0][1][0]); mScene->AttachChild(mPlane1); mSphere1 = sm.Sphere(64, 64, 2.0f); vba.ApplyTo(mSphere1); for (int i = 0; i < vba.GetNumVertices(); ++i) { vba.TCoord<Float3>(1, i) = vba.Normal<Float3>(i); } mSphere1->LocalTransform.SetTranslate(APoint(0.0f, +8.0f, 2.0f)); mSphere1->SetEffectInstance(mInstance[0][1][1]); mScene->AttachChild(mSphere1); mCaption[0] = "Directional Light (left per vertex, right per pixel)"; mCaption[1] = "Point Light (left per vertex, right per pixel)"; mCaption[2] = "Spot Light (left per vertex, right per pixel)"; mCurrentCaption = mCaption[0]; mActiveType = 0; } //----------------------------------------------------------------------------
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.openstack.marconi.v1.domain; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Optional; import org.jclouds.javax.annotation.Nullable; import java.beans.ConstructorProperties; /** * Statistics on messages in this queue. */ public class MessagesStats { private final int claimed; private final int free; private final int total; private final Aged oldest; private final Aged newest; @ConstructorProperties({ "claimed", "free", "total", "oldest", "newest" }) protected MessagesStats(int claimed, int free, int total, @Nullable Aged oldest, @Nullable Aged newest) { this.claimed = claimed; this.free = free; this.total = total; this.oldest = oldest; this.newest = newest; } /** * @return The number of claimed messages in this queue. */ public int getClaimed() { return claimed; } /** * @return The number of free messages in this queue. */ public int getFree() { return free; } /** * @return The total number of messages in this queue. */ public int getTotal() { return total; } /** * @return Statistics on the oldest messages in this queue. If the value of total is 0, then oldest is not present. */ public Optional<Aged> getOldest() { return Optional.fromNullable(oldest); } /** * @return Statistics on the newest messages in this queue. If the value of total is 0, then newest is not present. */ public Optional<Aged> getNewest() { return Optional.fromNullable(newest); } @Override public int hashCode() { return Objects.hashCode(claimed, free, total, oldest, newest); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; MessagesStats that = MessagesStats.class.cast(obj); return Objects.equal(this.claimed, that.claimed) && Objects.equal(this.free, that.free) && Objects.equal(this.total, that.total) && Objects.equal(this.oldest, that.oldest) && Objects.equal(this.newest, that.newest); } protected MoreObjects.ToStringHelper string() { return MoreObjects.toStringHelper(this).omitNullValues() .add("claimed", claimed).add("free", free).add("total", total).add("oldest", oldest).add("newest", newest); } @Override public String toString() { return string().toString(); } public static Builder builder() { return new ConcreteBuilder(); } public Builder toBuilder() { return new ConcreteBuilder().fromMessagesStats(this); } public abstract static class Builder { protected abstract Builder self(); protected int claimed; protected int free; protected int total; protected Aged oldest; protected Aged newest; /** * @see MessagesStats#getClaimed() */ public Builder claimed(int claimed) { this.claimed = claimed; return self(); } /** * @see MessagesStats#getFree() */ public Builder free(int free) { this.free = free; return self(); } /** * @see MessagesStats#getTotal() */ public Builder total(int total) { this.total = total; return self(); } /** * @see MessagesStats#getOldest() */ public Builder oldest(Aged oldest) { this.oldest = oldest; return self(); } /** * @see MessagesStats#getNewest() */ public Builder newest(Aged newest) { this.newest = newest; return self(); } public MessagesStats build() { return new MessagesStats(claimed, free, total, oldest, newest); } public Builder fromMessagesStats(MessagesStats in) { return this.claimed(in.getClaimed()).free(in.getFree()).total(in.getTotal()).oldest(in.getOldest().orNull()) .newest(in.getNewest().orNull()); } } private static class ConcreteBuilder extends Builder { @Override protected ConcreteBuilder self() { return this; } } }
package dybarsky.agecounter import android.appwidget.AppWidgetManager import android.content.Context import android.util.Log import android.widget.RemoteViews class Remote(context: Context) { private val drawer = Drawer(context) private val views = RemoteViews(context.packageName, R.layout.widget_layout) private val widgetManager = AppWidgetManager.getInstance(context) fun update(widgetId: Int, ageWhole: Int, ageFraction: Int) { Log.d("###", "$ageWhole.$ageFraction") val image = drawer.draw(ageWhole, ageFraction) views.setImageViewBitmap(R.id.image, image) widgetManager.updateAppWidget(widgetId, views) } }
''' Steven Kyritsis CS100 2021F Section 031 HW 10, November 12, 2021 ''' #1 def initialletterCount(wordlist): my_d={} for word in wordlist: if len(word)>0: w=word[0] if w not in my_d: my_d[w]=0 my_d[w]+=1 return my_d print(initialletterCount(['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']))
using UncommonSense.CBreeze.Core.Property.Implementation; using UncommonSense.CBreeze.Core.Report.Classic.Section.Contracts; namespace UncommonSense.CBreeze.Core.Report.Classic.Section.Properties { public class FooterSectionProperties : SectionPropertiesBase { private readonly NullableBooleanProperty _placeInBottom = new NullableBooleanProperty("PlaceInBottom"); private readonly NullableBooleanProperty _printOnEveryPage = new NullableBooleanProperty("PrintOnEveryPage"); public FooterSectionProperties(SectionBase section) : base(section) { innerList.Add(_printOnEveryPage); innerList.Add(_placeInBottom); } public bool? PlaceInBottom { get => _placeInBottom.Value; set => _placeInBottom.Value = value; } public bool? PrintOnEveryPage { get => _printOnEveryPage.Value; set => _printOnEveryPage.Value = value; } } }
import { ModuleWithProviders, NgZone, InjectionToken } from '@angular/core'; import { DevtoolsOptions } from '@datorama/akita'; import * as i0 from "@angular/core"; export declare const DEVTOOLS_OPTIONS: InjectionToken<DevtoolsOptions>; export declare class AkitaDevtools { private ngZone; private options; constructor(ngZone: NgZone, options: DevtoolsOptions); static ɵfac: i0.ɵɵFactoryDef<AkitaDevtools, never>; static ɵprov: i0.ɵɵInjectableDef<AkitaDevtools>; } export declare function d(): void; export declare function init(akitaDevtools: AkitaDevtools): typeof d; export declare class AkitaNgDevtools { static forRoot(options?: Partial<DevtoolsOptions>): ModuleWithProviders<AkitaNgDevtools>; static ɵmod: i0.ɵɵNgModuleDefWithMeta<AkitaNgDevtools, never, never, never>; static ɵinj: i0.ɵɵInjectorDef<AkitaNgDevtools>; }
/* Plugin-SDK (Grand Theft Auto 3) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CCredits.h" PLUGIN_SOURCE_FILE PLUGIN_VARIABLE unsigned int &CCredits::CreditsStartTime = *reinterpret_cast<unsigned int *>(GLOBAL_ADDRESS_BY_VERSION(0x8F2528, 0x8F25DC, 0x90271C)); PLUGIN_VARIABLE bool &CCredits::bCreditsGoing = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0x95CDD3, 0x95CF8B, 0x96D0CB)); int addrof(CCredits::AreCreditsDone) = ADDRESS_BY_VERSION(0x4FE790, 0x4FE870, 0x4FE800); int gaddrof(CCredits::AreCreditsDone) = GLOBAL_ADDRESS_BY_VERSION(0x4FE790, 0x4FE870, 0x4FE800); bool CCredits::AreCreditsDone() { return plugin::CallAndReturnDynGlobal<bool>(gaddrof(CCredits::AreCreditsDone)); } int addrof(CCredits::Init) = ADDRESS_BY_VERSION(0x4FE7A0, 0x4FE880, 0x4FE810); int gaddrof(CCredits::Init) = GLOBAL_ADDRESS_BY_VERSION(0x4FE7A0, 0x4FE880, 0x4FE810); void CCredits::Init() { plugin::CallDynGlobal(gaddrof(CCredits::Init)); } int addrof(CCredits::PrintCreditSpace) = ADDRESS_BY_VERSION(0x4FE710, 0x4FE7F0, 0x4FE780); int gaddrof(CCredits::PrintCreditSpace) = GLOBAL_ADDRESS_BY_VERSION(0x4FE710, 0x4FE7F0, 0x4FE780); void CCredits::PrintCreditSpace(float space, unsigned int *line) { plugin::CallDynGlobal<float, unsigned int *>(gaddrof(CCredits::PrintCreditSpace), space, line); } int addrof(CCredits::PrintCreditText) = ADDRESS_BY_VERSION(0x4FE620, 0x4FE700, 0x4FE690); int gaddrof(CCredits::PrintCreditText) = GLOBAL_ADDRESS_BY_VERSION(0x4FE620, 0x4FE700, 0x4FE690); void CCredits::PrintCreditText(float scaleX, float scaleY, wchar_t *text, unsigned int *lineOffset, float scrollOffset) { plugin::CallDynGlobal<float, float, wchar_t *, unsigned int *, float>(gaddrof(CCredits::PrintCreditText), scaleX, scaleY, text, lineOffset, scrollOffset); } int addrof(CCredits::Render) = ADDRESS_BY_VERSION(0x4FADF0, 0x4FAED0, 0x4FAE60); int gaddrof(CCredits::Render) = GLOBAL_ADDRESS_BY_VERSION(0x4FADF0, 0x4FAED0, 0x4FAE60); void CCredits::Render() { plugin::CallDynGlobal(gaddrof(CCredits::Render)); } int addrof(CCredits::Start) = ADDRESS_BY_VERSION(0x4FE760, 0x4FE840, 0x4FE7D0); int gaddrof(CCredits::Start) = GLOBAL_ADDRESS_BY_VERSION(0x4FE760, 0x4FE840, 0x4FE7D0); void CCredits::Start() { plugin::CallDynGlobal(gaddrof(CCredits::Start)); } int addrof(CCredits::Stop) = ADDRESS_BY_VERSION(0x4FE780, 0x4FE860, 0x4FE7F0); int gaddrof(CCredits::Stop) = GLOBAL_ADDRESS_BY_VERSION(0x4FE780, 0x4FE860, 0x4FE7F0); void CCredits::Stop() { plugin::CallDynGlobal(gaddrof(CCredits::Stop)); }
@extends('layouts.app') @section('scripts') <script> tinymce.init({ selector: 'textarea', height: "500" }); </script> @endsection @section('content') <div class="container"> <div class="row"> <div class="col-12"> <h1>Edit Home Page</h1> </div> </div> <!-- Content Wrapper --> <div class="row"> <div class="col"> <form action="{{route('pages.edithome', $home->id)}}" method="post"> @csrf <input type="hidden" name="id" value="{{ $home->id }}"> <div class="form-group"> <label for="title_nl">title_nl</label> <textarea name="title_nl" id="title_nl">{{$home->title_nl}}</textarea> </div> <div class="form-group"> <label for="title_en">title_en</label> <textarea name="title_en" id="title_en">{{$home->title_en}}</textarea> </div> <div class="form-group"> <label for="maininfo_nl">maininfo_nl</label> <textarea name="maininfo_nl" id="maininfo_nl">{{$home->maininfo_nl}}</textarea> </div> <div class="form-group"> <label for="maininfo_en">maininfo_en</label> <textarea name="maininfo_en" id="maininfo_en">{{$home->maininfo_en}}</textarea> </div> <button class="btn btn-danger" type="submit"> {{__('home.button')}} </button> </form> </div> </div> </div> @endsection
// ---------------------------------------------------------------- // xml_csharp_delete.aspx.cs // // // May/24/2013 // // ---------------------------------------------------------------- using System; using System.IO; using System.Collections.Generic; using Newtonsoft.Json; // ---------------------------------------------------------------- public class xml_csharp_delete : System.Web.UI.Page { // ---------------------------------------------------------------- void Page_Load (Object sender, EventArgs e) { Response.ContentType = "text/plain"; Response.Write ("xml_csharp_delete.aspx.cs"); string xml_file = "/var/tmp/xml_file/cities.xml"; string str_xml = file_io.file_to_str_proc (xml_file); Dictionary <string,Object> dict_aa = xml_manipulate.xml_to_dict_proc (str_xml); String[] array_aa = request_delete_parser_proc (); for (int it=0; it< array_aa.Length; it++) { String key_in = array_aa[it]; Response.Write (key_in + "<br />"); if (dict_aa.ContainsKey (key_in)) { dict_aa.Remove (key_in); } } Response.Write ("May/23/2013"); string xml_str = xml_manipulate.dict_to_xml_proc (dict_aa); file_io.file_write_proc (xml_file,xml_str); Response.Write ("OK"); } // ---------------------------------------------------------------- String[] request_delete_parser_proc () { Response.Write ("request_parser_proc *** AM 08:12<br />"); foreach (string ss in Request.Form) { Response.Write ("Form : " + ss + " "); string pp = Request.Form.Get (ss).ToString (); Response.Write ("Form.Get : " + pp + " "); } string str_json = Request.Form.Get ("my_data").ToString (); Response.Write ("str_json : " + str_json + "<br />"); String []array_aa = JsonConvert.DeserializeObject <String []> (str_json); Response.Write ("Length : " + array_aa.Length + "<br />"); return array_aa; } // ---------------------------------------------------------------- } // ----------------------------------------------------------------
import { GraphQLNonNull, GraphQLInt, GraphQLList } from 'graphql'; import { MatchType } from '../../types/match'; import { LeagueTeam } from '../../../db/models/leagueteam.model'; import { Match } from '../../../db/models/match.model'; /** * Get all match data for league. */ export const getMatches = { type: new GraphQLList(MatchType), args: { leagueId: { type: new GraphQLNonNull(GraphQLInt) } }, async resolve(parent: object, args: any): Promise<Match[]> { const Matches = await Match.findAll({ include: [ { model: LeagueTeam, as: 'homeTeam' }, { model: LeagueTeam, as: 'awayTeam' }, ], where: { leagueId: args.leagueId }, }); if (!Matches) { throw Error('Matches could not be found'); } return Matches; }, };
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'package:score_keeper_2/models/game.dart'; import 'package:score_keeper_2/models/player.dart'; import 'package:score_keeper_2/models/theme.dart'; import 'package:score_keeper_2/screens/options_screen.dart'; void main() { List<Player> players = new List<Player>(); Game game; setUp() { players = <Player>[ Player(name: 'p1'), ]; game = new Game(players: players); } tearDown() { players = new List<Player>(); game = null; } testWidgets('Options page renders', (WidgetTester tester) async { await tester.pumpWidget(ChangeNotifierProvider( create: (context) => GameTheme(), child: MaterialApp( home: OptionsScreen( game: Game(players: new List<Player>()), ), ), )); expect(find.byType(OptionsScreen), findsOneWidget); expect(find.text('spoon'), findsNothing); }); testWidgets('Options page shows initial increment and decrement values', (WidgetTester tester) async { setUp(); await tester.pumpWidget(ChangeNotifierProvider( create: (context) => GameTheme(), // have to add a material app to this for a "context" with media query child: MaterialApp( home: OptionsScreen( game: game, ), ), )); expect(find.text('1'), findsNWidgets(2)); tearDown(); }); testWidgets('Options page shows change dialog', (WidgetTester tester) async { setUp(); await tester.pumpWidget(ChangeNotifierProvider( create: (context) => GameTheme(), child: MaterialApp( // have to add a material app to this for a "context" with media query home: OptionsScreen( game: game, ), ), )); // incrementing score await tester.tap(find.byKey(Key('change-increment-score'))); await tester.pump(); expect(find.text('Change Value'), findsOneWidget); await tester.tap(find.byKey(Key('cancel-edit-inc-dec-value'))); await tester.pump(); expect(find.text('Change Value'), findsNothing); // decrementing score await tester.tap(find.byKey(Key('change-decrement-score'))); await tester.pump(); expect(find.text('Change Value'), findsOneWidget); await tester.tap(find.byKey(Key('cancel-edit-inc-dec-value'))); await tester.pump(); expect(find.text('Change Value'), findsNothing); expect(game.incrementValue, 1); expect(game.decrementValue, 1); tearDown(); }); testWidgets('Options page changes game increment and decrement values', (WidgetTester tester) async { setUp(); await tester.pumpWidget(ChangeNotifierProvider( create: (context) => GameTheme(), child: MaterialApp( home: OptionsScreen( game: game, ), ), )); // incrementing score await tester.tap(find.byKey(Key('change-increment-score'))); await tester.pump(); await tester.enterText(find.byKey(Key('text-inc-dec-value')), '10'); await tester.tap(find.byKey(Key('edit-inc-dec-value'))); await tester.pump(); // decrementing score await tester.tap(find.byKey(Key('change-decrement-score'))); await tester.pump(); await tester.enterText(find.byKey(Key('text-inc-dec-value')), '10'); await tester.tap(find.byKey(Key('edit-inc-dec-value'))); await tester.pump(); expect(game.incrementValue, 10); expect(game.decrementValue, 10); tearDown(); }); }
#if DEBUG using JetBrains.Annotations; using DuckGame; using TMGmod.Core.WClasses; namespace TMGmod.Buddies { [PublicAPI] [EditorGroup("TMG|DEBUG")] public class StingerLauncher:BaseGun { public StingerLauncher(float xval, float yval) : base(xval, yval) { var sprite = new SpriteMap(GetPath("deleteco/Future/Stinger.png"), 42, 10); _graphic = sprite; sprite.frame = 0; _center = new Vec2(21f, 5f); _collisionOffset = new Vec2(-21f, -5f); _collisionSize = new Vec2(42f, 10f); depth = -0.5f; thickness = 0.0f; _weight = 3f; ammo = 1; } public override void Fire() { var b = Offset(new Vec2(16, 0)); var stg = new StingerMissile(b.x, b.y) { velocity = OffsetLocal(new Vec2(10, 0)) + velocity - 2 * new Vec2(0f, gravity), owner = this, offDir = offDir, angle = angle }; Level.Add(stg); } } } #endif
/* * ForumPage Messages * * This contains all the text for the ForumPage component. */ import { defineMessages } from 'react-intl' export default defineMessages({ CreatorAccountNamePlaceholder: { id: 'ProposalPage CreatorAccountNamePlaceholder', defaultMessage: '签名账号' }, ProposalFirstOne: { id: 'ProposalPage ProposalFirstOne', defaultMessage: '步骤1/3:填写提案表单' }, ProposalPermission: { id: 'ProposalPage ProposalPermission', defaultMessage: '签名权限' }, Proposaler: { id: 'ProposalPage Proposaler', defaultMessage: '投票人' }, VoterLabel: { id: 'ProxyPage VoterLabel', defaultMessage: '投票账户' }, ProxyLabel: { id: 'ProxyPage ProxyLabel', defaultMessage: '代理账户' }, ProxyScatterHelp: { id: 'ProxyPage ProxyScatterHelp', defaultMessage: '注:使用Scatter将使用已登录的账号签名' }, ProposalName: { id: 'ProposalPage ProposalName', defaultMessage: '提案名称' } })
import { Injectable } from '@angular/core'; import { ApplicationData } from './application-data'; @Injectable() export class MockApplicationDataService { // The local state of application data. This is a single, global instance that // is shared across the whole app. Once it is pulled from the server, only the // local state will be pulled by getApplicationData(). updateApplicationData() // will always send the current local state back to the server. application_data = new ApplicationData(); getApplicationData(): Promise<ApplicationData> { return Promise.resolve(this.application_data); } updateApplicationData(): Promise<any> { return Promise.resolve({ success: true }); } }
import sbt._ import sbt.Keys._ import org.scalajs.sbtplugin.ScalaJSPlugin import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._ object ScalaJSReact extends Build { val SCALA_VERSION = "2.11.5" val uTestVersion = "0.3.0" val scalajsDomVersion = "0.7.0" val scalaXml = "org.scala-lang.modules" %% "scala-xml" % "1.0.2" val scalaReflect = "org.scala-lang" % "scala-reflect" % SCALA_VERSION val macroParadisePlugin = compilerPlugin("org.scalamacros" % "paradise" % "2.0.1" cross CrossVersion.full) val jasmine = "org.scala-js" %% "scalajs-jasmine-test-framework" % scalaJSVersion % "test" val reactjs = "org.webjars" % "react" % "0.11.0" / "react.js" commonJSName "React" val commonSettings = Seq( version := "0.3.4-SNAPSHOT", organization := "com.xored.scalajs", scalaVersion := SCALA_VERSION, licenses := Seq("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0.html")), homepage := Some(url("http://github.com/xored/scala-js-react/")), scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8", "-feature", "-Yinline-warnings", "-language:implicitConversions", "-language:higherKinds") ) lazy val react = Project("scalajs-react", file("scalajs-react")) .enablePlugins(ScalaJSPlugin) .settings(commonSettings: _*) .settings( libraryDependencies ++= Seq( "org.scala-js" %%% "scalajs-dom" % scalajsDomVersion, scalaXml, scalaReflect, macroParadisePlugin ), jsDependencies += reactjs, test in Test := {} ) lazy val reactTests = Project("scalajs-react-tests", file("scalajs-react-tests")) .enablePlugins(ScalaJSPlugin) .settings(commonSettings: _*) .settings( libraryDependencies ++= Seq( "org.scala-js" %%% "scalajs-dom" % scalajsDomVersion, scalaXml, macroParadisePlugin, "com.lihaoyi" %%% "utest" % uTestVersion % "test" ), scalaJSStage := FastOptStage, testFrameworks += new TestFramework("utest.runner.Framework"), publishArtifact := false ) .dependsOn(react) lazy val examples = Project("scalajs-react-examples", file("scalajs-react-examples")) .enablePlugins(ScalaJSPlugin) .settings(commonSettings: _*) .settings( libraryDependencies ++= Seq( macroParadisePlugin ), skip in packageJSDependencies := false, // creates scalajs-react-examples-jsdeps.js test in Test := {} ) .dependsOn(react) val root = Project("root", file(".")) .settings(publishArtifact := false) .aggregate(react, reactTests, examples) resolvers += Resolver.sonatypeRepo("releases") }
package avatar.game.user; public enum Title { TEST("Test"); private String display; Title(String display){this.display = display;} public String getDisplay(){ return "[" + display + "] "; } }
# Ark-Lock Lock service in parallel environment > This library is based on [php-lock/lock](https://github.com/php-lock/lock), > which is licensed under the `Do What The F*ck You Want To Public License`. This project aims to provide lock service for PHP 5.5+. Multi Mutex Lock is supported since Version 0.3.
import { __decorate } from "tslib"; import { customElement, bindable, useView } from 'aurelia-templating'; import { inject } from 'aurelia-dependency-injection'; import { PLATFORM } from 'aurelia-pal'; var UxField = /** @class */ (function () { function UxField(element) { this.element = element; } UxField.prototype.attached = function () { if (this.label && !this.element.querySelector('label')) { this.labelElement = document.createElement('label'); this.labelElement.classList.add('ux-field__label'); this.labelElement.textContent = this.label; this.element.insertBefore(this.labelElement, this.element.firstChild); } }; UxField.prototype.labelChanged = function (newValue) { if (this.labelElement != null) { this.labelElement.textContent = newValue; } }; __decorate([ bindable ], UxField.prototype, "label", void 0); UxField = __decorate([ inject(Element), customElement('ux-field'), useView(PLATFORM.moduleName('./ux-field.html')) ], UxField); return UxField; }()); export { UxField }; //# sourceMappingURL=ux-field.js.map
module Api class PhysicalServerProfilesController < BaseController include Subcollections::EventStreams def assign_server_resource(type, id, data) # Make sure the requested server exists resource_search(data["server_id"], :physical_servers) enqueue_ems_action(type, id, :method_name => :assign_server, :args => [data["server_id"]]) end def deploy_server_resource(type, id, _data) enqueue_ems_action(type, id, :method_name => :deploy_server) end def unassign_server_resource(type, id, _data) enqueue_ems_action(type, id, :method_name => :unassign_server) end end end
package flavor.pie.sunkcost.permissions import flavor.pie.kludge.* import flavor.pie.sunkcost.textByCode import org.bukkit.permissions.PermissionDefault import org.spongepowered.api.service.permission.PermissionDescription import org.spongepowered.api.service.permission.PermissionService import org.bukkit.permissions.Permission as Permission object Permissions { const val OP = "sunkcost.op" } fun Permission.toPermissionBuilder(): PermissionDescription.Builder { val svc: PermissionService by UncheckedService val builder = svc.newDescriptionBuilder(plugin) when (default) { PermissionDefault.FALSE -> builder.assign(PermissionDescription.ROLE_ADMIN, false) .assign(PermissionDescription.ROLE_STAFF, false) .assign(PermissionDescription.ROLE_USER, false) PermissionDefault.NOT_OP -> builder.assign(PermissionDescription.ROLE_ADMIN, false) .assign(PermissionDescription.ROLE_STAFF, false) .assign(PermissionDescription.ROLE_USER, true) PermissionDefault.OP -> builder.assign(PermissionDescription.ROLE_ADMIN, true) .assign(PermissionDescription.ROLE_STAFF, true) .assign(PermissionDescription.ROLE_USER, false) PermissionDefault.TRUE -> builder.assign(PermissionDescription.ROLE_ADMIN, true) .assign(PermissionDescription.ROLE_STAFF, true) .assign(PermissionDescription.ROLE_USER, true) null -> {} } return builder.description(this.description.textByCode()) .id(this.name) }
# Linux ## Install packages ### Ubuntu ``` sudo apt-get install python3-dev libdbus-glib-1-dev ``` ### Fedora ``` sudo dnf install redhat-lsb-core python3-devel gcc dbus-devel dbus-glib-devel ``` ## Checkout xv\_leak\_tools\_internal Simply `git clone` this repo to a location of your choice. We'll refer to the `python` subfolder in that location as `$LEAK_TOOLS_ROOT`. ## Setup Python Run `./setup_python.sh $VIRTUALENV_LOCATION` where `$VIRTUALENV_LOCATION` is the directory where you want the virtualenv to be created, e.g. ``` ./setup_python.sh ~/xv_leak_testing_python ``` You can now source the `activate` script as a shortcut to activating `virtualenv` with this version of python. ## Install VPN Applications Install ExpressVPN and any other applications you want to test. No specific steps related to leak testing are required. ## Install Browsers and Webdrivers First ensure that Chrome, Firefox and Opera are installed (where supported). > Note that some drives can be installed with package managers, e.g. apt. In order for selenium to control various browsers some install steps are required. Install Edge driver: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/#downloads Install Chrome driver: https://chromedriver.storage.googleapis.com/index.html?path=2.30/ Firefox gecko driver: https://github.com/mozilla/geckodriver/releases Opera driver: https://github.com/operasoftware/operachromiumdriver/releases ## Install Torrent Clients You can choose which torrent clients you want to test. We have tested * Transmission * uTorrent
type ChatService = TeaDispenserService | DmvService; export type TeaDispenserService = 'discordTeaDispenser' | 'kaiheilaTeaDispenser'; export type DmvService = 'kaiheilaDmv'; export default ChatService;
function checkOLKind(element) { var addressKind = $(element).val(); var row = $(element).closest(".row").next(".row").next(".row"); if (addressKind == "primary") { row.find('#inputCounty').attr('required', true); row.find('#inputCounty').attr('disabled', true); row.find('#inputCounty').attr('data-target','zip-check.countySelect'); row.find('#inputZip').attr('required', true); row.find('#inputZip').attr('data-action', 'change->zip-check#zipChange'); } else { row.find('#inputCounty').removeAttr('required'); row.find('#inputCounty').removeProp('required'); row.find('#inputZip').removeAttr('data-action'); row.find('#inputZip').removeProp('data-action'); row.find('#inputZip').removeAttr('required'); row.find('#inputZip').removeProp('required'); row.find('#inputZip').removeAttr('data-options'); row.find('#inputZip').removeProp('data-options'); // removes blank option from select options //setTimeout(function() { // element.options[0].remove() // },300) } } module.exports = { checkOLKind: checkOLKind };
--- title: "bcc-profile-exercise" weight: 412 --- # BCC Profile exercise (Part 2) .exercise[ - Download the Flamegrapsh scripts: ``` git clone https://github.com/brendangregg/FlameGraph ``` - Generate a flamegraph for your profiled data: ``` sudo tools/profile -p PID -f > /tmp/profile.out flamegraph.pl /tmp/profile.out > /tmp/profile-graph.svg \ && firefox /tmp/profile-graph.svg ``` ]
<?php namespace ShahBurhan\OWA\Concerns; /** * Example map * Case 1. * protected $actionMap = [ * 0 => "methodNameForNoArgAction", * 1 => "methodNameForActionWithOneArg", * ] * Case 2. * protected $actionMap = [ * 0 => [ * "methodNameForNoArgAction" => [ * 1 => 'segmentOne' * ], * "AnotherMethodNameForNoArgAction" => [ * 1 => 'segmentOneAnother' * ] * ], * 1 => "methodNameForActionWithOneArg", * ] * */ trait HasSubAction { /** * Call a sub action based on the argument map * * @param array $args * @return void */ public function subAction(array $args) { $args = array_shift($args); return call_user_func_array([$this, $this->getMethodName(count($args))], $args); } /** * Get the name of the action method based based on the argument map * * @param integer $count * @return string */ protected function getMethodName(int $count) { $map = $method = $this->actionMap[$count]; if (is_array($map)) { foreach ($map as $method => $segmentKeyValue) { $position = array_key_first($segmentKeyValue); $segment = array_pop($segmentKeyValue); if ($this->hasSegment($segment, $position)) { break; } } } return $method; } /** * Check if a mapped segment matches the first url segment * * @param string $segment * @return boolean */ public function hasSegment(string $segment, int $position) { return request()->segment($position) == $segment; } /** * Automatically take action on class using HasSubAction * * @param array ...$args * @return void */ public function take(...$args) { return $this->subAction($args); } }
package me.shedaniel.architect.plugin.transformers import me.shedaniel.architect.plugin.Transformer import me.shedaniel.architect.plugin.TransformerStepSkipped import net.fabricmc.loom.LoomGradleExtension import org.gradle.api.Project import java.nio.file.Files import java.nio.file.Path object AddRefmapName : Transformer { override fun invoke(project: Project, input: Path, output: Path) { Files.copy(input, output) val loomExtension = project.extensions.getByType(LoomGradleExtension::class.java) var refmapHelperClass: Class<*>? = null runCatching { refmapHelperClass = Class.forName("net.fabricmc.loom.util.MixinRefmapHelper") }.onFailure { runCatching { refmapHelperClass = Class.forName("net.fabricmc.loom.build.MixinRefmapHelper") }.onFailure { throw ClassNotFoundException("Failed to find MixinRefmapHelper!") } } val method = refmapHelperClass!!.getDeclaredMethod( "addRefmapName", String::class.java, String::class.java, Path::class.java ) if ( method.invoke( null, loomExtension.getRefmapName(), loomExtension.mixinJsonVersion, output ) as Boolean ) { project.logger.debug("Transformed mixin reference maps in output JAR!") } else { throw TransformerStepSkipped } } }
<?php declare(strict_types=1); namespace EonX\EasyWebhook\Tests; use DateTime; use EonX\EasyWebhook\Webhook; final class WebhookTest extends AbstractTestCase { public function testSettersGetters(): void { $body = [ 'key' => 'value', ]; $event = 'my-event'; $extra = [ 'key' => 'value', ]; $httpOptions = [ 'key' => 'value', 'query' => [ 'query' => 'value', ], 'headers' => [ 'header' => 'value', ], ]; $maxAttempt = 5; $secret = 'my-secret'; $sendAfter = new DateTime(); $url = 'https://eonx.com'; $webhook = Webhook::create($url, $body); $webhook ->allowRerun() ->body($body) ->event($event) ->extra($extra) ->header('header', 'value') ->headers([ 'header' => 'value', ]) ->httpClientOptions($httpOptions) ->maxAttempt($maxAttempt) ->mergeExtra([ 'key1' => 'value1', ]) ->query('query', 'value') ->queries([ 'query' => 'value', ]) ->secret($secret) ->sendAfter($sendAfter) ->sendNow() ->url($url); self::assertEquals($body, $webhook->getBody()); self::assertEquals($event, $webhook->getEvent()); self::assertEquals($extra + [ 'key1' => 'value1', ], $webhook->getExtra()); self::assertEquals($httpOptions, $webhook->getHttpClientOptions()); self::assertEquals($maxAttempt, $webhook->getMaxAttempt()); self::assertEquals($secret, $webhook->getSecret()); self::assertEquals($sendAfter, $webhook->getSendAfter()); self::assertTrue($webhook->isSendNow()); self::assertEquals($url, $webhook->getUrl()); self::assertIsArray($webhook->toArray()); } }
; RUN: opt < %s -aa-pipeline=basic-aa,globals-aa -passes='require<globals-aa>,gvn' -S | FileCheck %s ; ; This tests the safe no-alias conclusions of GMR -- when there is ; a non-escaping global as one indentified underlying object and some pointer ; that would inherently have escaped any other function as the other underlying ; pointer of an alias query. @g1 = internal global i32 0 define i32 @test1(i32* %param) { ; Ensure that we can fold a store to a load of a global across a store to ; a parameter when the global is non-escaping. ; ; CHECK-LABEL: @test1( ; CHECK: store i32 42, i32* @g1 ; CHECK-NOT: load i32 ; CHECK: ret i32 42 entry: store i32 42, i32* @g1 store i32 7, i32* %param %v = load i32, i32* @g1 ret i32 %v } declare i32* @f() define i32 @test2() { ; Ensure that we can fold a store to a load of a global across a store to ; the pointer returned by a function call. Since the global could not escape, ; this function cannot be returning its address. ; ; CHECK-LABEL: @test2( ; CHECK: store i32 42, i32* @g1 ; CHECK-NOT: load i32 ; CHECK: ret i32 42 entry: %ptr = call i32* @f() readnone store i32 42, i32* @g1 store i32 7, i32* %ptr %v = load i32, i32* @g1 ret i32 %v } @g2 = external global i32* define i32 @test3() { ; Ensure that we can fold a store to a load of a global across a store to ; the pointer loaded from that global. Because the global does not escape, it ; cannot alias a pointer loaded out of a global. ; ; CHECK-LABEL: @test3( ; CHECK: store i32 42, i32* @g1 ; CHECK: store i32 7, i32* ; CHECK-NOT: load i32 ; CHECK: ret i32 42 entry: store i32 42, i32* @g1 %ptr1 = load i32*, i32** @g2 store i32 7, i32* %ptr1 %v = load i32, i32* @g1 ret i32 %v } @g3 = internal global i32 1 @g4 = internal global [10 x i32*] zeroinitializer define i32 @test4(i32* %param, i32 %n, i1 %c1, i1 %c2, i1 %c3) { ; Ensure that we can fold a store to a load of a global across a store to ; the pointer loaded from that global even when the load is behind PHIs and ; selects, and there is a mixture of a load and another global or argument. ; Note that we can't eliminate the load here because it is used in a PHI and ; GVN doesn't try to do real DCE. The store is still forwarded by GVN though. ; ; CHECK-LABEL: @test4( ; CHECK: store i32 42, i32* @g1 ; CHECK: store i32 7, i32* ; CHECK: ret i32 42 entry: %call = call i32* @f() store i32 42, i32* @g1 %ptr1 = load i32*, i32** @g2 %ptr2 = select i1 %c1, i32* %ptr1, i32* %param %ptr3 = select i1 %c3, i32* %ptr2, i32* @g3 br label %loop loop: %iv = phi i32 [ 0, %entry ], [ %inc, %loop ] %ptr = phi i32* [ %ptr3, %entry ], [ %ptr5, %loop ] store i32 7, i32* %ptr %ptr4 = load i32*, i32** getelementptr ([10 x i32*], [10 x i32*]* @g4, i32 0, i32 1) %ptr5 = select i1 %c2, i32* %ptr4, i32* %call %inc = add i32 %iv, 1 %test = icmp slt i32 %inc, %n br i1 %test, label %loop, label %exit exit: %v = load i32, i32* @g1 ret i32 %v } define i32 @test5(i32** %param) { ; Ensure that we can fold a store to a load of a global across a store to ; a parameter that has been dereferenced when the global is non-escaping. ; ; CHECK-LABEL: @test5( ; CHECK: %p = load i32* ; CHECK: store i32 42, i32* @g1 ; CHECK-NOT: load i32 ; CHECK: ret i32 42 entry: %p = load i32*, i32** %param store i32 42, i32* @g1 store i32 7, i32* %p %v = load i32, i32* @g1 ret i32 %v }