text
stringlengths
27
775k
FactoryGirl.define do factory :profile do name "My first profile" calls_per_second 5 max_calls 100 max_concurrent 10 transport_type "u1" end end
import BaseSeeder from '@ioc:Adonis/Lucid/Seeder' import Region from 'App/Models/Region' import Province from 'App/Models/Province' export default class ProvinceSeeder extends BaseSeeder { public async run() { let northId: number = 0 let centerId: number = 0 let southId: number = 0 const uniqueKey = 'name' const regions = await Region.all() regions.map((region) => { switch (region.name.toUpperCase()) { case 'NORTE': northId = region.id break case 'CENTRO': centerId = region.id break case 'SUL': southId = region.id break } }) await Province.updateOrCreateMany(uniqueKey, [ { name: 'Cabo Delgado', capital: 'Pemba', code: 'MZ-P', regionId: northId, }, { name: 'Niassa', capital: 'Lichinga', code: 'MZ-A', regionId: northId, }, { name: 'Nampula', capital: 'Nampula', code: 'MZ-N', regionId: northId, }, { name: 'Tete', capital: 'Tete', code: 'MZ-T', regionId: centerId, }, { name: 'Sofala', capital: 'Beira', code: 'MZ-S', regionId: centerId, }, { name: 'Zambézia', capital: 'Quelimane', code: 'MZ-Q', regionId: centerId, }, { name: 'Manica', capital: 'Chimoio', code: 'MZ-B', regionId: centerId, }, { name: 'Inhambane', capital: 'Inhambane', code: 'MZ-I', regionId: southId, }, { name: 'Gaza', capital: 'Xai-xai', code: 'MZ-G', regionId: southId, }, { name: 'Maputo', capital: 'Matola', code: 'MZ-L', regionId: southId, }, { name: 'Cidade de Maputo', capital: '---', code: 'MZ-MPM', regionId: southId, }, ]) } }
# -*- coding: utf-8 -*- from django.conf import settings # 自定义上下文管理器 def settings_info(request): return { 'site_end_title':settings.SITE_END_TITLE, 'site_description':settings.SITE_DESCRIPTION, 'site_keywords':settings.SITE_KEYWORDS, 'my_github': settings.MY_GITHUB, 'my_csdn':settings.MY_CSDN, }
import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:args/args.dart'; import 'package:automated_testing_framework_driver_websocket/driver.dart'; import 'package:automated_testing_framework_models/automated_testing_framework_models.dart'; import 'package:convert/convert.dart'; import 'package:crypto/crypto.dart'; import 'package:logging/logging.dart'; Future<void> main(List<String> args) async { Logger.root.level = Level.ALL; Logger.root.onRecord.listen((record) { // ignore: avoid_print print('${record.message}'); if (record.error != null) { // ignore: avoid_print print('${record.error}'); } if (record.stackTrace != null) { // ignore: avoid_print print('${record.stackTrace}'); } }); final logger = Logger('main'); var parser = ArgParser(); parser.addOption( 'app', abbr: 'a', help: 'Application identifier.', ); parser.addOption( 'device', abbr: 'd', help: 'Identifier of the device to be driven.', ); parser.addOption( 'driver', abbr: 'n', help: 'Name of the driver.', ); parser.addOption( 'secret', abbr: 's', help: 'Secret text for communicating with the server.', ); parser.addOption( 'test', abbr: 't', help: 'Path to the test to run', ); parser.addOption( 'url', abbr: 'u', help: 'URL for the server.', ); parser.addFlag('help', abbr: 'h'); var results = parser.parse(args); if (results['help'] == true) { // ignore: avoid_print print(''' Usage: run [<options>] Starts the websocket server for the testing framework. -a, --app=<app-identifier> The application identifier. -d, --device=<device-id> Identifier of the device to be driven. -h, --help Display this help message. -n, --driver=<driver-name> Identifier of the device to be driven. -s, --secret=<port> Secret text for communicating with the server. -t, --test Path to the test to run -u, --url Websocket URL for the server. Optionally, environmental variables can be used to set the following args: ATF_APP_IDENTIFIER The application identifier ATF_DRIVER_NAME The name of the driver. ATF_WEBSOCKET_URL Websocket URL for the server. '''); exit(0); } var device = results['device']; if (device?.isNotEmpty != true) { logger.severe( 'No device set.', ); exit(1); } var secrets = {}; var secretsFile = File('secret/keys.json'); if (secretsFile.existsSync() == true) { try { var data = json.decode(secretsFile.readAsStringSync()); secrets['driver'] = data['driver']; } catch (e) { // no-op } } var appIdentifier = results['app'] ?? secrets['app'] ?? Platform.environment['ATF_APP_IDENTIFIER'] ?? 'default'; var driverName = results['driver'] ?? Platform.environment['ATF_DRIVER_NAME'] ?? Platform.localHostname; var secret = results['secret'] ?? secrets['driver'] ?? Platform.environment['ATF_DRIVER_SECRET']; if (secret?.isNotEmpty != true) { logger.severe( 'Environment variable "ATF_DRIVER_SECRET" not found, and [secret] arg not set.', ); exit(1); } var testPath = results['test']; if (testPath?.isNotEmpty != true) { logger.severe('No test set'); exit(1); } var tests = <Test>[]; if (FileSystemEntity.isDirectorySync(testPath)) { var dir = Directory(testPath); for (var file in dir.listSync()) { if (file is File) { tests.add(Test.fromDynamic(json.decode(file.readAsStringSync()))); } } } else if (FileSystemEntity.isFileSync(testPath)) { var file = File(testPath); tests.add(Test.fromDynamic(json.decode(file.readAsStringSync()))); } else { logger.severe('Unable to locate test file: $testPath'); exit(1); } if (tests.isNotEmpty != true) { logger.severe('Unable to load data for test(s): $testPath'); exit(1); } var url = results['url'] ?? secrets['url'] ?? Platform.environment['ATF_WEBSOCKET_URL']; if (url?.isNotEmpty != true) { logger.severe( 'Environment variable "ATF_WEBSOCKET_URL" not found, and [url] arg not set.', ); exit(1); } var output = Directory('output/$device'); try { output.deleteSync(recursive: true); } catch (e) { // no-op } output.createSync(recursive: true); var comm = WebSocketTestDriverCommunicator( appIdentifier: appIdentifier ?? 'default', driverName: driverName, secret: secret, url: url, ); comm.onConnectionChanged = (connected) async => logger.fine('[CONNECTED]: $connected'); await comm.activate(); logger.info('[ACTIVATED]'); var reserveCmd = ReserveDeviceCommand( deviceId: device, driverName: driverName, ); var logCmd = StartLogStreamCommand(); var ssCmd = StartScreenshotStreamCommand(); var testCmd = RunTestCommand(sendScreenshots: false, test: tests.removeAt(0)); var releaseCmd = ReleaseDeviceCommand(deviceId: device); var completer = Completer(); comm.commandStream.listen((command) { if (command is CommandAck) { if (command.commandId == reserveCmd.id) { if (command.success == true) { comm.sendCommand(logCmd); comm.sendCommand(ssCmd); comm.sendCommand(testCmd); } else { completer.completeError('Unable to reserve device'); } } else if (command.commandId == logCmd.id) { var response = command.response; if (response is LogResponse) { var file = File( 'output/${device}/${hex.encode(utf8.encode(testCmd.test.id))}.log', ); file.createSync(recursive: true); var record = response.record; file.writeAsString( '${record.level.name}: ${record.time}: [${record.loggerName}]: ${record.message}\n', mode: FileMode.append, ); } } else if (command.commandId == testCmd.id) { var response = command.response; if (response is TestStatusResponse) { logger.info('[TEST STATUS]: ${command.message}'); if (response.complete == true) { logger.info('[TEST COMPLETE]: ${command.success}'); if (tests.isNotEmpty == true) { testCmd = RunTestCommand( sendScreenshots: false, test: tests.removeAt(0), ); comm.sendCommand(testCmd); } else { comm.sendCommand(releaseCmd); completer.complete(); } } } else if (response is ScreenshotResponse) { var hash = sha256.convert(response.image).toString(); var file = File( 'output/${device}/${hex.encode(utf8.encode(testCmd.test.id))}/screenshots/$hash.png', ); file.createSync(recursive: true); file.writeAsBytesSync(response.image); } } else if (command.commandId == ssCmd.id) { var response = command.response; if (response is ScreenshotResponse) { var dt = DateTime.now().millisecondsSinceEpoch; var file = File( 'output/${device}/${hex.encode(utf8.encode(testCmd.test.id))}/screens/$dt.png', ); file.createSync(recursive: true); file.writeAsBytesSync(response.image); } } } }); await comm.sendCommand(reserveCmd); var timer = Timer(Duration(minutes: 10), () { completer.completeError('TIMEOUT'); }); try { await completer.future; timer.cancel(); exit(0); } catch (e) { logger.severe(e); exit(1); } }
@using Ateliex @using Ateliex.Extensions @using Ateliex.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
package exifcommand import ( "encoding/csv" "errors" "flag" "fmt" "log" "os" "path/filepath" "sort" "strings" "time" exifutil "github.com/cxcheng/exifutil" ) type OutCmd struct { conf *Config w *os.File csvW *csv.Writer filter string cols []string outType string sortColIdx int sortReverse bool trim bool tz *time.Location value bool } func (cmd *OutCmd) Init(conf *Config) error { cmd.conf = conf // Process command-line arguments var cols, outPath, sortCol string flag.StringVar(&cols, "cols", "Sys/Name,Make,Model,DateTimeOriginal", "Columns to output") flag.StringVar(&cmd.filter, "filter", "", "Expression to filter") flag.StringVar(&sortCol, "sort", "-", "Sort column") flag.BoolVar(&cmd.sortReverse, "reverse", false, "Reverse sort order") flag.StringVar(&outPath, "out", "", "Output path") flag.StringVar(&cmd.outType, "type", "", "Output type: csv, json, keys") flag.BoolVar(&cmd.value, "value", false, "Output value instead of original text") flag.Parse() // Initialize configuration cmd.cols = strings.Split(cols, ",") cmd.trim = conf.Trim if outPath != "" { if f, err := os.OpenFile(outPath, os.O_RDWR|os.O_CREATE, 0666); err == nil { cmd.w = f defer f.Close() } } if cmd.w == nil { cmd.w = os.Stdout } // Set timezone if specified, otherwise, use local time zone if conf.Tz != "" { var err error if cmd.tz, err = time.LoadLocation(conf.Tz); err != nil { log.Fatalf("Unable to load timezone [%s]", conf.Tz) return err } } else { // otherwise use local location cmd.tz = time.Now().Local().Location() } // Check for output type and sort col if len(cmd.cols) > 1 && cmd.outType == "" { cmd.outType = "csv" // set type to csv } if cmd.outType == "csv" { if len(cmd.cols) == 0 { return errors.New("No columns specified for CSV") } cmd.csvW = csv.NewWriter(cmd.w) } if sortCol == "-" { cmd.sortColIdx = -1 // no sorting } else { cmd.sortColIdx = 0 if sortCol != "" { // Check if ordering by specified tag for i, col := range cmd.cols { if sortCol == col { cmd.sortColIdx = i break } } if cmd.sortColIdx == -1 { log.Printf("Missing sort col [%s], ignored", sortCol) } } } return nil } func (cmd *OutCmd) Run() { // Walkthrough arguments var err error ctx := outCtx{cmd: cmd} // Preliminary output of CSV headers if ctx.cmd.csvW != nil { ctx.cmd.csvW.Write(ctx.cmd.cols) } for _, arg := range flag.Args() { err = filepath.Walk(arg, func(path string, f os.FileInfo, err error) error { // Filter out file based on extension matchedExt := false if len(cmd.conf.FileExts) > 0 { for _, ext := range cmd.conf.FileExts { if filepath.Ext(path) == "."+ext { matchedExt = true } } } else { matchedExt = true } // Proceed to create context to process file if matchedExt { if cmd.conf.Verbose { log.Printf("Processing [%s]", path) } err = ctx.process(path, f, err) if err != nil && cmd.conf.ExitOnFirstError { // return on first error if flag set return err } } return nil // ignore errors }) } // If no error, finish the processing by sorting and emptying buffered input if err == nil { ctx.finish() } } type outCtx struct { cmd *OutCmd records []outRecord } type outRecord struct { cols []string colVs []interface{} } func (ctx *outCtx) process(path string, f os.FileInfo, err error) error { exifData, err := exifutil.ReadExifData(path, ctx.cmd.tz, ctx.cmd.conf.Trim, ctx.cmd.conf.Tags) if err != nil { log.Fatalf("[%s]: [%s]\n", path, err) } else { // Apply optional filter if ctx.cmd.filter == "" || exifData.Filter(ctx.cmd.filter) { switch ctx.cmd.outType { case "json": ctx.out(exifData.Json()) case "keys": for _, key := range exifData.Keys() { ctx.out(key) } default: // if cols specified, evaluate; otherwise, print every field if len(ctx.cmd.cols) > 0 { outCols := make([]string, len(ctx.cmd.cols)) outColVs := make([]interface{}, len(ctx.cmd.cols)) for i, col := range ctx.cmd.cols { outCols[i], outColVs[i] = exifData.Expr(col) } ctx.outRecord(outRecord{ cols: outCols, colVs: outColVs, }) } else { ctx.out(exifData.String()) } } } } return err } func (ctx *outCtx) flush() { if ctx.cmd.csvW != nil { ctx.cmd.csvW.Flush() } } func (ctx *outCtx) out(s string) { ctx.outRecord(outRecord{ cols: []string{s}, colVs: []interface{}{s}, }) } func (ctx *outCtx) outRecord(r outRecord) { if ctx.cmd.sortColIdx >= 0 { // buffer ctx.records = append(ctx.records, r) } else if ctx.cmd.csvW != nil { if ctx.cmd.value { cols := make([]string, len(r.cols)) for i, colV := range r.colVs { cols[i] = fmt.Sprintf("%v", colV) } ctx.cmd.csvW.Write(cols) } else { ctx.cmd.csvW.Write(r.cols) } } else { // only 1 column written if not in CSV mode if ctx.cmd.value { fmt.Fprintln(ctx.cmd.w, r.colVs[0]) } else { fmt.Fprintln(ctx.cmd.w, r.cols[0]) } } } func (ctx *outCtx) finish() { // Sort if ctx.cmd.sortColIdx >= 0 && ctx.cmd.sortColIdx < len(ctx.cmd.cols) { sort.Sort(ctx) ctx.cmd.sortColIdx = -1 // mark as done, or this becomes recursive } // Output for _, r := range ctx.records { ctx.outRecord(r) } ctx.flush() } func (ctx *outCtx) Len() int { return len(ctx.records) } func (ctx *outCtx) Less(i, j int) bool { less := false ok := false vi := ctx.records[i].colVs[ctx.cmd.sortColIdx] switch vi.(type) { case string: var vj string if vj, ok = ctx.records[j].colVs[ctx.cmd.sortColIdx].(string); ok { less = vi.(string) < vj } case float64: var vj float64 if vj, ok = ctx.records[j].colVs[ctx.cmd.sortColIdx].(float64); ok { less = vi.(float64) < vj } case int64: var vj int64 if vj, ok = ctx.records[j].colVs[ctx.cmd.sortColIdx].(int64); ok { less = vi.(int64) < vj } } if ctx.cmd.sortReverse { return ok && !less } else { return ok && less } } func (ctx *outCtx) Swap(i, j int) { ctx.records[i], ctx.records[j] = ctx.records[j], ctx.records[i] }
//Problem 6. Sum integers //You are given a sequence of positive integer values written into a string, separated by spaces. //Write a function that reads these values from given string and calculates their sum. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SumIntegers { class Program { static void Main() { Console.WriteLine("Enter a integers separated by a space: "); string input = Console.ReadLine(); SumOfInteger(input); } static void SumOfInteger(string input) { string[] num = input.Split(' ').ToArray(); int[] numbers = new int[num.Length]; for (int i = 0; i < num.Length; i++) { numbers[i] = int.Parse(num[i]); } Console.WriteLine(string.Join(", ", numbers)); Console.WriteLine("Sum = {0}", numbers.Sum()); } } }
import md5 from "md5"; function getUrl(type, uid, data = {}) { // let host = "https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/"; let host = "https://api-takumi.mihoyo.com/game_record/app/genshin/api/"; let server = getServer(uid); let query = ""; let body = ""; switch (type) { //首页宝箱 case "index": query = `role_id=${uid}&server=${server}`; break; //深渊 case "spiralAbyss": query = `role_id=${uid}&schedule_type=${data.schedule_type}&server=${server}`; break; //角色详情 case "character": body = JSON.stringify(data); //树脂每日任务(只能当前id) case "dailyNote": query = `role_id=${uid}&server=${server}`; break; //角色天赋等级接口 case "detail": host = "https://api-takumi.mihoyo.com/event/e20200928calculate/v1/sync/avatar/detail"; query = `uid=${uid}&region=${server}&avatar_id=${data.avatar_id}`; type = ""; break; } let url = host + type + "?" + query; return { url, query, body }; } function getServer(uid) { switch (uid.toString()[0]) { case "1": case "2": return "cn_gf01"; //官服 case "5": return "cn_qd01"; //B服 } return "cn_gf01"; //官服 } //# Github-@lulu666lulu function getDs(q = "", b = "") { let n = "xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs"; let t = Math.round(new Date().getTime() / 1000); let r = Math.floor(Math.random() * 900000 + 100000); let DS = md5(`salt=${n}&t=${t}&r=${r}&b=${b}&q=${q}`); return `${t},${r},${DS}`; } export { getUrl, getDs, getServer };
#!/bin/bash /home/baruque/HoneyMapping/scripts/kill_all_pid.sh /home/baruque/HoneyMapping/var/pid.txt /home/baruque/HoneyMapping/scripts/monitor_files.sh
package com.mercari.data.condition.protobuf import com.google.protobuf.Timestamp object TimestampCondition { // See https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto private val SECONDS_LOWER_LIMIT = -62135596800L private val SECONDS_UPPER_LIMIT = 253402300799L private val NANOS_LOWER_LIMIT = 0 private val NANOS_UPPER_LIMIT = 999999999 /** * Validate the values satisfy expectation in proto * * @param ts * @return */ def isValid(ts: Timestamp): Boolean = ts.getSeconds >= SECONDS_LOWER_LIMIT && ts.getSeconds < SECONDS_UPPER_LIMIT && ts.getNanos >= NANOS_LOWER_LIMIT && ts.getNanos < NANOS_UPPER_LIMIT }
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; class IndexController extends Controller { public function __construct() { //$this->middleware('guest'); } protected function index() { $data['body'] = 'index.index'; return view('common.layout',$data); } }
<?php namespace Padosoft\Support\Test; trait DateTimeDataProvider { /** * @return array */ public function cal_days_in_monthProvider() { return [ 'null, null, null' => [null, null, null, 'PHPUnit_Framework_Error'], '\'\', \'\', \'\'' => ['', '', '', 'PHPUnit_Framework_Error'], '\' \', \' \', \' \' ' => [' ', ' ', ' ', 'PHPUnit_Framework_Error'], '0, 1, 2016' => [0, 1, 2016, 31], 'CAL_GREGORIAN, 1, 2016' => [CAL_GREGORIAN, 1, 2016, 31], 'CAL_GREGORIAN, 2, 2015' => [CAL_GREGORIAN, 2, 2015, 28], 'CAL_GREGORIAN, 2, 2016' => [CAL_GREGORIAN, 2, 2016, 29], 'CAL_GREGORIAN, 4, 2016' => [CAL_GREGORIAN, 4, 2016, 30], 'CAL_GREGORIAN, 4, 1900' => [CAL_GREGORIAN, 4, 1900, 30], 'CAL_GREGORIAN, 4, 2400' => [CAL_GREGORIAN, 4, 2400, 30], 'CAL_JULIAN, 1, 2016' => [CAL_JULIAN, 1, 2016, 31], 'CAL_JULIAN, 2, 2015' => [CAL_JULIAN, 2, 2015, 28], 'CAL_JULIAN, 2, 2016' => [CAL_JULIAN, 2, 2016, 29], 'CAL_JULIAN, 4, 2016' => [CAL_JULIAN, 4, 2016, 30], 'CAL_JULIAN, 4, 1900' => [CAL_JULIAN, 4, 1900, 30], 'CAL_JULIAN, 4, 2400' => [CAL_JULIAN, 4, 2400, 30], ]; } /** * @return array */ public function cal_days_in_current_monthProvider() { return [ 'null, '.cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y')) => [null, 'TypeError'], '\'\', '.cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y')) => ['', 'TypeError'], '\' \', '.cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y')) => [' ', 'TypeError'], '0' => [0, cal_days_in_month(0, date('m'), date('Y'))], 'CAL_GREGORIAN' => [CAL_GREGORIAN, cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'))], 'CAL_JULIAN, 1, 2016' => [CAL_JULIAN, cal_days_in_month(CAL_JULIAN, date('m'), date('Y'))], ]; } /** * @return array */ public function days_in_monthProvider() { return [ 'null, null' => [null, null, 'TypeError'], '\'\', \'\'' => ['', '', 'TypeError'], '\' \', \' \'' => [' ', ' ', 'TypeError'], '1, 2016' => [0, 1, 2016, 31], '1, 2016' => [1, 2016, 31], '2, 2015' => [2, 2015, 28], '2, 2016' => [2, 2016, 29], '4, 2016' => [4, 2016, 30], '4, 1900' => [4, 1900, 30], '4, 2400' => [4, 2400, 30], ]; } /** * @return array */ public function days_in_current_monthProvider() { return [ '' => [cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'))], ]; } }
import {Service} from 'typedi'; import {ConfigService} from './config.service'; import {createClient, RedisClient} from 'redis'; @Service() export class RedisService { private _redisClient: RedisClient; constructor(private configService: ConfigService) {} public get redisClient(): RedisClient { if (this._redisClient) return this._redisClient; this._redisClient = createClient(this.configService.getConfig('redis')); return this._redisClient; } public has(key: string): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { this.redisClient.exists(key, (err, reply) => { if (err) { reject(err); return; } resolve(!!reply); }); }); } public delete(key: string): Promise<void> { return new Promise<void>((resolve, reject) => { this.redisClient.del(key, (err) => { if (err) { reject(err); return; } resolve(); }); }); } public ttl(key: string): Promise<number> { return new Promise<number>((resolve, reject) => { this.redisClient.ttl(key, (err, reply) => { if (err) { reject(err); return; } resolve(reply); }); }); } public setString(key: string, value: string, expire: number): Promise<void> { return new Promise<void>((resolve, reject) => { this.redisClient.setex(key, expire, value, (err) => { if (err) { reject(err); return; } resolve(); }); }); } public getString(key: string): Promise<string> { return new Promise<string>((resolve, reject) => { this.redisClient.get(key, (err, reply) => { if (err) { reject(err); return; } resolve(reply); }); }); } public setObject(key: string, value: { [key: string]: string | number }, expire: number): Promise<void> { return new Promise<void>((resolve, reject) => { this.redisClient.hmset(key, value, (err) => { if (err) { reject(err); return; } this.redisClient.expire(key, expire); resolve(); }); }); } public getObject(key: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.redisClient.hgetall(key, (err, reply) => { if (err) { reject(err); return; } resolve(reply); }); }); } }
package responses import models.Question import responses.UserProtocol._ import responses.AnswerProtocol._ import spray.json._ case class QuestionResponse(id: Int, from: UserResponse, statusId: Int, statusName: String, text: String, createdAt: String, answer: Option[AnswerResponse]) object QuestionProtocol extends DefaultJsonProtocol { implicit def questionFormat: RootJsonFormat[QuestionResponse] = jsonFormat7(QuestionResponse.apply) } object QuestionResponse { def from(question: Question): QuestionResponse = QuestionResponse( question.id, UserResponse.from(question.from), question.status.id, question.status.text, question.text, question.createdAt, question.answer match { case Some(answer) => Some(AnswerResponse.from(answer)) case None => None } ) }
<?php if(!function_exists('dateFormat')) { function dateFormat($format='d-m-Y', $givenDate=null) { return date($format, strtotime($givenDate)); } } if(!function_exists('dateFormatTime')) { function dateFormatTime($format='d-m-Y H:i:s', $givenDate=null) { return date($format, strtotime($givenDate)); } } if(!function_exists('dateEnFrancais')) { function dateEnFrancais($format='%A %e %B %Y', $givenDate=null) { return strftime($format, strtotime($givenDate)); } }
mkdir build g++ glfw_startup.cpp -lglfw -lGL -lm -lX11 -lpthread -lXi -lXrandr -ldl -o build/glfw_startup
fn main() { println!("Hello, world!"); } #[test] fn sample_test() { assert_eq!(digits(5), 1); assert_eq!(digits(12345), 5); assert_eq!(digits(9876543210), 10); } fn digits(n: u64) -> usize { n.to_string().len() }
'use strict'; angular.module('main').service('Points', function (DataStore) { var dataStore = DataStore('points'); this.earn = function (session) { return dataStore.save({ amount: session.subject.topics[session.topic].points, session: session }); }; this.remove = function (session) { return dataStore.all().where({ session: { $id: session.$id } }).remove(); }; this.all = function () { return dataStore.all(); }; });
# Spell Check Shootout These are the results as of 2019-10-24 Command: ```bash $ ./benchsuite.sh . Nightblood ``` Spell checkers: - ripgrep 11.0.1 (rev 973de50c9e) -SIMD -AVX (compiled) +SIMD +AVX (runtime) - Though not a spell checker, present to be a theoretical lower bound - typos-cli 0.1.0 w/ cargo 1.38.0 (23ef9a4ef 2019-08-20) - misspell 0.2.0 w/ cargo 1.38.0 (23ef9a4ef 2019-08-20) - misspell_go 0.3.4 - codespell 1.15.0 w/ Python 3.5.2 - scspell 2.2 w/ Python 3.5.2 ## linux_clean fixture N/A ## linux_built fixture N/A ## subtitles_ru_small fixture subtitles_ru_small: OpenSubtitles2016.raw.ru.small c4549d470463cae24b3dbb1efd138192242c0853 | Command | Mean [ms] | Min…Max [ms] | |:---|---:|---:| | `./rg/rg bin ./subtitles_ru/OpenSubtitles2016.raw.ru.small` | 7.6 ± 1.2 | 5.7…12.0 | | `./typos/bin/typos ./subtitles_ru/OpenSubtitles2016.raw.ru.small` | 61.2 ± 4.1 | 52.4…70.1 | | `./misspell_rs/bin/misspell ./subtitles_ru/OpenSubtitles2016.raw.ru.small` | 33.5 ± 2.3 | 30.2…40.0 | | `./misspell_go/bin/misspell ./subtitles_ru/OpenSubtitles2016.raw.ru.small` | 40.2 ± 2.6 | 34.1…46.1 | | `./scspell/bin/scspell ./subtitles_ru/OpenSubtitles2016.raw.ru.small` | 281.5 ± 3.8 | 276.8…289.3 | | `./codespell/bin/codespell ./subtitles_ru/OpenSubtitles2016.raw.ru.small` | 311.8 ± 5.8 | 299.8…321.8 | ## ripgrep_clean fixture ripgrep_clean: rg 973de50c9ef451da2cfcdfa86f2b2711d8d6ff48 | Command | Mean [ms] | Min…Max [ms] | |:---|---:|---:| | `./rg/rg bin ./ripgrep_clean` | 27.6 ± 5.1 | 20.6…38.1 | | `./typos/bin/typos ./ripgrep_clean` | 168.0 ± 11.4 | 145.4…182.4 | | `./misspell_rs/bin/misspell ./ripgrep_clean` | 145.4 ± 4.1 | 136.1…153.0 | | `./misspell_go/bin/misspell ./ripgrep_clean` | 214.8 ± 7.8 | 193.4…226.5 | | `./codespell/bin/codespell ./ripgrep_clean` | 651.0 ± 15.1 | 628.9…682.0 | ## ripgrep_built fixture ripgrep_built: rg 973de50c9ef451da2cfcdfa86f2b2711d8d6ff48 | Command | Mean [ms] | Min…Max [ms] | |:---|---:|---:| | `./rg/rg bin ./ripgrep_built` | 32.5 ± 4.9 | 26.1…41.5 | | `./typos/bin/typos ./ripgrep_built` | 174.1 ± 5.9 | 163.8…187.5 | | `./misspell_rs/bin/misspell ./ripgrep_built` | 143.8 ± 5.0 | 137.2…161.0 | | `./misspell_go/bin/misspell ./ripgrep_built` | 278.6 ± 8.1 | 266.7…291.6 | | `./codespell/bin/codespell ./ripgrep_built` | 840.5 ± 11.2 | 819.4…853.0 |
/////////////////////////////////////////////////////////////////////// // Copyright (c) 2018 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /////////////////////////////////////////////////////////////////////// package io.dispatchframework.javabaseimage; public interface FunctionExecutor { String execute(String message) throws DispatchException; }
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); Route::resource('personals', 'PersonalController'); Route::get('niveles', 'NivelController@ListarNiveles'); Route::get('listar_notas/{cur_cod}/{gra_cod}/{sec_cod}', 'NotaController@ListarNotasporCurso'); Route::get('grados/{niv_cod}', 'GradoController@ListarGrado'); Route::get('secciones/{gra_cod}', 'SeccionController@ListarSeccion'); Route::get('ubi_deps', 'UbigeoController@ListarUbidep'); Route::get('ubi_provs/{id}', 'UbigeoController@ListarUbiprov'); Route::get('ubi_dists/{id}', 'UbigeoController@ListarUbidist'); Route::get('cursobygrado/{id}', 'CursoController@GetCursoByGrado'); Route::get('login/{usu_login}/{usu_contra}', 'LoginController@UsuLogin'); Route::get('verify/{id}', 'LoginController@verifySession'); Route::get('listar_asigs/{id}', 'AsignacionController@ListarAsignacion'); Route::resource('cursos', 'CursoController'); Route::resource('alumnos', 'AlumnoController'); Route::resource('domicilio', 'DomicilioController'); Route::resource('matriculas', 'MatriculaController'); Route::resource('login','LoginController'); Route::post('act_notas', 'NotaController@InsertarNotas'); Route::post('ins_asigs', 'AsignacionController@InsertarAsignacion'); Route::delete('elim_asigs/{id}', 'AsignacionController@EliminarAsignacion');
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Javascript/jQuery functions to initialize UI on page * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ $(".menu-link").click( function() { show_page(); } ); $(".home").click( function() { hide_page(); } ); $(".resume").click( function() { if (!($(this).hasClass('active'))) { $('*').removeClass('active'); $('#nav-resume').addClass('active'); clear_section(); load_page_to_section('page-content','resume'); load_cards(); } } ); $(".about").click( function() { if (!($(this).hasClass('active'))) { $('*').removeClass('active'); $('#nav-about').addClass('active'); clear_section(); load_page_to_section('page-content','about'); load_cards(); } } ); $(".projects").click( function() { if (!($(this).hasClass('active'))) { $('*').removeClass('active'); $('#nav-projects').addClass('active'); clear_section(); load_page_to_section('page-content','projects'); load_cards(); } } ); $(".contact").click( function() { if (!($(this).hasClass('active'))) { $('*').removeClass('active'); $('#nav-contact').addClass('active'); clear_section(); load_page_to_section('page-content','contact'); load_cards(); } } ); $(window).mousemove(adjustBackground);
; ############################### ; Draws an 8x8 sprite aligned to a grid ; ; Inputs: ; $82 = address of sprite ; $86 = x coord ; $87 = y coord ; Destroys: ; a, x, y ; $80, $81, $84 draw_sprite: jsr get_coords ; Get starting VRAM coordinates into $80 ldy #0 draw_sprite_row: lda ($82), y ; load (address + y) from ($82) into a, $82 holds sprite address eor ($80), y sta ($80), y iny cpy #8 bne draw_sprite_row rts ; ############################### ; Puts the starting address in VRAM into $80 ; ; Inputs: -- ; Outputs: ; $80 = Sprite coordinates (Y * 40 + X * 8 + $2000) ; Destroys: ; a, x ; $81, $84 get_coords: lda #0 sta $84 ; temp variable sta $81 ; ; x lda $86 ; x * 8 asl ; srl a, don't put carry into bit 0 rol $81 ; ROtateLeft, carry goes into bit 1 asl ; x4 rol $81 asl ; x8 rol $81 sta $80 ; $80 = x_pos * 8, $80 $81 act like a 16-bit register ; y: 25*8 rows = 200 rows of 320 pixels lda $87 ; y * 8, won't overflow so no need for 16-bit variable asl asl asl ; now need y*40 asl rol $84 ; y * 2 asl rol $84 ; y * 4 asl rol $84 ; y * 8 tax adc $80 ; add y * 8 now, later we'll add y * 32 to get y * 40 sta $80 ; add to the x value lda $84 adc $81 sta $81 txa asl ; y * 16 rol $84 asl ; y * 32 rol $84 adc $80 ; add y * 32 sta $80 lda $84 adc $81 adc #$20 sta $81 ; MSB rts ; ############################### ; Clears "x" bytes at address stored in $80 ; Inputs: ; a = byte to store at address ; x = number of bytes * 256 to clear ; $80 = address to clear clear: ldy #0 clear_loop: sta ($80), y dey bne clear_loop inc $81 dex bne clear_loop rts
def find_nth_term_for_an_arithmetic_sequence(first_term: int, common_difference: int, requested_term: int) -> int: """ Find the nth term in an arithmetic sequence :param first_term: :param common_difference: :param requested_term :return: the nth term """ return first_term + (requested_term - 1) * common_difference def find_the_nth_term_for_a_geometric_sequence(first_term: int, common_ratio: int, requested_term: int) -> int: """ Find the nth term in a geometric sequence :param first_term: :param common_ratio: :param requested_term: :return: the nth term """ return first_term * common_ratio ** (requested_term - 1) def find_sum_of_arithmetic_sequence(requested_terms: int, first_term: int, common_difference: int) -> int: """ Finds the sum of an arithmetic sequence :param requested_terms: :param first_term: :param common_difference: :return: the sum of an arithmetic sequence """ return int((requested_terms / 2) * (2 * first_term + (requested_terms - 1) * common_difference))
package com.patres.automation.action.keyboard import com.patres.automation.gui.controller.box.AbstractBox import com.patres.automation.gui.controller.model.AutomationController import com.patres.automation.keyboard.KeyboardKey import com.patres.automation.type.ActionBootKeyboard class HoldKeyboardButtonAction( keyboardKeys: List<KeyboardKey>, box: AbstractBox<*>? ) : KeyboardButtonAction(keyboardKeys, ActionBootKeyboard.HOLD_KEYBOARD_BUTTON, box) { override fun runAction() { keyValues.forEach { robot.keyPress(it) } } }
// This file is licensed to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Spines.Utility { /// <summary> /// An array of bits with methods to access single or multiple bits. /// </summary> public class BitField { /// <summary> /// Instantiates a new instance of BitField. /// </summary> /// <param name="bits">The source bits.</param> public BitField(int bits) { _bits = bits; } /// <summary> /// Checks if the meld code has the specified bit, starting from the least significant bit at index 0. /// </summary> public bool HasBit(int bitIndex) { return (_bits & 1 << bitIndex) != 0; } /// <summary> /// Apply a bitmask with all ones in a single block and then treat the selected bits as an integer. /// For example, with letters as arbitrary bits: _code = abcdefgh => ExtractSegment(3, 2) == 00000def. /// </summary> /// <param name="numberOfBits">The number of bits that will be selected.</param> /// <param name="leftShift">How many of the least significant bits to ignore.</param> /// <returns>The selected bits from the original value.</returns> public int ExtractSegment(int numberOfBits, int leftShift) { var mask = (1 << numberOfBits) - 1; return (_bits >> leftShift) & mask; } /// <summary> /// The underlying bits. /// </summary> private readonly int _bits; } }
package com.example.furlencotask.domain.usecases import com.example.furlencotask.domain.Repository import com.example.furlencotask.domain.entities.RequestType import io.reactivex.Single import javax.inject.Inject /** * Created by Sourik on 7/11/20. */ class GetRowCountUseCase @Inject constructor(private val repository: Repository){ fun getRowCount(type: RequestType):Single<Int>{ return repository.getRowCount(type) } }
#!/usr/bin/env python3 r""" Use robot framework API to extract test data from test suites. Refer to https://robot-framework.readthedocs.io/en/3.0.1/autodoc/robot.parsing.html """ import sys import os from robot.parsing.model import TestData sys.path.append(os.path.join(os.path.dirname(__file__), "../lib")) from gen_arg import * from gen_print import * from gen_valid import * # Set exit_on_error for gen_valid functions. set_exit_on_error(True) valid_options = ['name', 'tags', 'doc', 'all'] parser = argparse.ArgumentParser( usage='%(prog)s [OPTIONS]', description=";%(prog)s will print test suite information to stdout. This \ information consists of any and/or all of the following: \ the suite name, test case names, tag names and doc strings. \ Example for generated test case names \ tests/test_basic_poweron.robot \ Verify Front And Rear LED At Standby \ Power On Test \ Check For Application Failures \ Verify Uptime Average Against Threshold \ Test SSH And IPMI Connections", formatter_class=argparse.ArgumentDefaultsHelpFormatter, prefix_chars='-+') parser.add_argument( '--source_path', '-s', help='The robot test file or directory path.') parser.add_argument( '--option', '-o', default="name", help='Test case attribute name. This may be any one of the following:\n' + sprint_var(valid_options)) # Populate stock_list with options we want. stock_list = [("test_mode", 0), ("quiet", 0), ("debug", 0)] def exit_function(signal_number=0, frame=None): r""" Execute whenever the program ends normally or with the signals that we catch (i.e. TERM, INT). """ dprint_executing() dprint_var(signal_number) qprint_pgm_footer() def signal_handler(signal_number, frame): r""" Handle signals. Without a function to catch a SIGTERM or SIGINT, the program would terminate immediately with return code 143 and without calling the exit_function. """ # Our convention is to set up exit_function with atexit.register() so # there is no need to explicitly call exit_function from here. dprint_executing() # Calling exit prevents us from returning to the code that was running # when the signal was received. exit(0) def validate_parms(): r""" Validate program parameters, etc. Return True or False (i.e. pass/fail) accordingly. """ valid_path(source_path) valid_value(option, valid_values=valid_options) gen_post_validation(exit_function, signal_handler) def parse_test_suites(source_path, option): r""" Parse the robot files and extract test data output. Description of argument(s): source_path The path to a robot file or a directory of robot files. option Test case attribute instances such as "name", "tags" or "doc". """ if os.path.isfile(source_path): file_paths = [source_path] else: file_paths = [os.path.join(path, file) for (path, dirs, files) in os.walk(source_path) for file in files] for file_path in file_paths: print(file_path) if "__init__.robot" in file_path: continue test_suite_obj = TestData(parent=None, source=file_path) parse_test_file(test_suite_obj, option) def parse_test_file(test_suite_obj, option): r""" Extract test information from test suite object and print it to stdout in the following format: <Test Case name> <Test Tags name> <Test Documentation> Description of argument(s): test_suite_obj Test data suite object. option Test case attribute instances such as "name", "tags" or "doc". """ for testcase in test_suite_obj.testcase_table: if option == "name": print(testcase.name) elif option == "tags": print(testcase.tags) elif option == "doc": print(testcase.doc) elif option == "all": print(testcase.name) print(testcase.tags) print(testcase.doc) def main(): gen_get_options(parser, stock_list) validate_parms() qprint_pgm_header() parse_test_suites(source_path, option) return True # Main main()
<img src="slides/log.png" style="width:50%"> ## 喫煙ログ機能 タバコを吸った本数を管理する機能
#include "Pickup.h" #include "Physics.h" #include "Renderer.h" #include "Editor.h" #include "Game.h" #include "Destructable.h" using namespace glm; Health::Health() { className = "Health"; Tag("Roomless"); amount = 1; } void Health::Draw() { Render::DrawCircle(vec3(position, 11), vec2(1), vec4(1, 0.3, 0.3, 1)); } void Health::Update() { //Pickup if in range if (distance(Game::player->position,position) < 2) { Destructable* destruct = (Destructable*)Game::player->GetComponent("Destructable"); destruct->damage -= amount; World::DeleteEntity(this); } } nlohmann::json Health::Save() { nlohmann::json data; data["amount"] = amount; return data; } void Health::Load(nlohmann::json data) { if (data.contains("amount")) amount = data["amount"].get<int>(); } void Health::Editor() { Editor::Int("Amount", &amount); }
module Philbot module Providers class Rackspace def dir config = Philbot::Config.instance rackspace = Fog::Storage.new( { provider: config['provider'], rackspace_username: config['username'], rackspace_api_key: config['api_key'], rackspace_region: config['region'].to_sym } ) container = rackspace.directories.get config['container'] container end end end end
package solutions.alterego.androidbound import org.junit.Assert.assertTrue import org.junit.Test class KotlinJunitTest { @Test fun firstTest() { assertTrue(true) } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use PDF; use DB; use App\Tabia; use App\Woreda; class PdfDemoController extends Controller { public function index(){ $Tabias = DB::table('hitsuys') ->join('midebas', 'hitsuys.hitsuyID', '=', 'midebas.hitsuyID')->get(); // DB::table('woredas')->where('Mekelle', $Tabias)->pluck('name'); return view('customer', ['Tabias'=>$Tabias]); } public function samplePDF() { /* $html_content = '<h1>Generate a PDF using TCPDF in laravel </h1> <h4>by<br/>Learn Infinity</h4>'; PDF::SetTitle('Sample PDF'); PDF::AddPage(); PDF::writeHTML($html_content, true, false, true, false, ''); PDF::Output('SamplePDF.pdf'); */ } public function savePDF() { /* $html_content = '<h1>Generate a PDF using TCPDF in laravel </h1> <h4>by<br/>Learn Infinity</h4>'; PDF::SetTitle('Sample PDF'); PDF::AddPage(); PDF::writeHTML($html_content, true, false, true, false, ''); PDF::Output(public_path(uniqid().'_SamplePDF.pdf'), 'F'); */ } public function downloadPDF() { $Tabias = DB::table('hitsuys') ->leftjoin('education_informations', 'hitsuys.hitsuyID', '=', 'education_informations.hitsuyID')->get(); $zobatat = DB::table('zobatats')->get(); // DB::table('woredas')->where('Mekelle', $Tabias)->pluck('name'); return view('report.hilwiabalreport', compact('Tabias','zobatat')); } public function HtmlToPDF() { // $Tabias = Tabia::all(); //$Tabias = DB::table('tabias') // ->join('woredas', 'tabias.woredacode', '=', 'woredas.woredacode')->get(); $Tabias = DB::table('hitsuys') ->join('midebas', 'hitsuys.hitsuyID', '=', 'midebas.hitsuyID')->get(); $zobatat = DB::table('zobatats')->get(); // DB::table('woredas')->where('Mekelle', $Tabias)->pluck('name'); // DB::table('woredas')->where('Mekelle', $Tabias)->pluck('name'); //return view('customer', ['Tabias'=>$Tabias]); $pdf = PDF::loadView('pdf.customer', ['zobatat'=>$zobatat]); //$pdf->setPaper([0, 0, 596.85, 1085.98], 'landscape'); $pdf->setPaper('A4', 'landscape'); //$pdf->loadHTML($cart_body);//body -> html content which needs to be converted as pdf.. //$pdf->render(); //$output = $dompdf->output(); return $pdf->stream('hilwiabalreport.pdf'); //Stream */ //$pdf->setPaper([0, 0, 685.98, 396.85], 'landscape'); //return $pdf->download('review.pdf'); //Download /*$view = \View::make('HtmlToPDF'); $html_content = $view->render(); PDF::SetTitle('Sample PDF'); PDF::AddPage(); PDF::writeHTML($html_content, true, false, true, false, ''); PDF::Output(uniqid().'_SamplePDF.pdf'); */ } public function HtmlToPDF1() { // $Tabias = Tabia::all(); //$Tabias = DB::table('tabias') // ->join('woredas', 'tabias.woredacode', '=', 'woredas.woredacode')->get(); $Tabias = DB::table('hitsuys')->get(); // DB::table('woredas')->where('Mekelle', $Tabias)->pluck('name'); //return view('customer', ['Tabias'=>$Tabias]); $pdf = PDF::loadView('pdf.wesekngudiletnreport', ['Tabias'=>$Tabias]); //$pdf->setPaper([0, 0, 596.85, 1085.98], 'landscape'); $pdf->setPaper('A4', 'landscape'); //$pdf->loadHTML($cart_body);//body -> html content which needs to be converted as pdf.. //$pdf->render(); //$output = $dompdf->output(); return $pdf->stream('customer.pdf'); //Stream */ //$pdf->setPaper([0, 0, 685.98, 396.85], 'landscape'); //return $pdf->download('review.pdf'); //Download /*$view = \View::make('HtmlToPDF'); $html_content = $view->render(); PDF::SetTitle('Sample PDF'); PDF::AddPage(); PDF::writeHTML($html_content, true, false, true, false, ''); PDF::Output(uniqid().'_SamplePDF.pdf'); */ } public function HtmlToPDF2() { $weredatat = DB::table('woredas')->get(); $pdf = PDF::loadView('pdf.variationtopleader', ['weredatat'=>$weredatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('variationtopleader.pdf'); //Stream */ } public function HtmlToPDF3() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totaltopleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totaltopleader.pdf'); //Stream */ } public function HtmlToPDF4() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.nominattopleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('nominattopleader.pdf'); //Stream */ } public function HtmlToPDF5() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.penalitytopleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('penalitytopleader.pdf'); //Stream */ } public function HtmlToPDF6() { $weredatat = DB::table('woredas')->get(); $pdf = PDF::loadView('pdf.variationmiddleleader', ['weredatat'=>$weredatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('variationmiddleleader.pdf'); //Stream */ } public function HtmlToPDF7() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totalmiddleleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totalmiddleleader.pdf'); //Stream */ } public function HtmlToPDF8() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.nominatmiddleleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('nominatmiddleleader.pdf'); //Stream */ } public function HtmlToPDF9() { $weredatat = DB::table('woredas')->get(); $pdf = PDF::loadView('pdf.variationworedaleader', ['weredatat'=>$weredatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('variationworedaleader.pdf'); //Stream */ } public function HtmlToPDF10() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totalworedaleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totalworedaleader.pdf'); //Stream */ } public function HtmlToPDF11() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.penalityworedaleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('penalityworedaleader.pdf'); //Stream */ } public function HtmlToPDF12() { $weredatat = DB::table('woredas')->get(); $pdf = PDF::loadView('pdf.variation1stleader', ['weredatat'=>$weredatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('variation1stleader.pdf'); //Stream */ } public function HtmlToPDF13() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.total1stleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('total1stleader.pdf'); //Stream */ } public function HtmlToPDF14() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.nominat1stleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('nominat1stleader.pdf'); //Stream */ } public function HtmlToPDF15() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totalwtleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totalwtleader.pdf'); //Stream */ } public function HtmlToPDF16() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totalwnleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totalwnleader.pdf'); //Stream */ } public function HtmlToPDF17() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totalmwtleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totalmwtleader.pdf'); //Stream */ } public function HtmlToPDF18() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totalmwnleader', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totalmwnleader.pdf'); //Stream */ } public function HtmlToPDF19() { $zobatat = DB::table('zobatats')->get(); $pdf = PDF::loadView('pdf.totalleaders', ['zobatat'=>$zobatat]); $pdf->setPaper('A4', 'landscape'); return $pdf->stream('totalleaders.pdf'); //Stream */ } }
#!/usr/bin/env python """reducer.py""" from operator import itemgetter import sys import math def median(lst): lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return lst[index] else: return (lst[index] + lst[index + 1])/2.0 batch_current = 0 metric_list = [] # input comes from STDIN (standard input) with open("NDBench-testing-mapped.csv") as file: for line in file:#sys.stdin # remove leading and trailing whitespace line = line.strip() line = line.rstrip() # parse the input we got from mapper.py batch_id_current, metric_value, metric_selected = line.split('\t') # convert count (currently a string) to int try: batch_id_current = int(batch_id_current) metric_value = float(metric_value) except ValueError: # count was not a number, so silently # ignore/discard this line continue if batch_current != batch_id_current: if(batch_current != 0) and (batch_id_current != 1) and (batch_id_current-batch_current == 1): # Number of observations batch_unit=len(metric_list) # Mean of the data metric_mean=sum(metric_list)/batch_unit metric_med=median(metric_list) # Square deviations deviations = [(x - metric_mean) ** 2 for x in metric_list] # Variance variance = sum(deviations) / batch_unit # Standard deviation std_dev = math.sqrt(variance) print('batch_id: {}\t metric: {}\t min: {}\t max: {}\t med: {}\t std_dev: {}'.format( batch_current, metric_selected.lower(), metric_list[0], metric_list[-1], metric_med, std_dev)) del metric_list[:] metric_list.append(metric_value) batch_current = batch_id_current continue else: metric_list.append(metric_value) continue # Number of observations batch_unit=len(metric_list) # Mean of the data metric_mean=sum(metric_list)/batch_unit metric_med=median(metric_list) # Square deviations deviations = [(x - metric_mean) ** 2 for x in metric_list] # Variance variance = sum(deviations) / batch_unit # Standard deviation std_dev = math.sqrt(variance) print('batch_id: {}\t metric: {}\t min: {}\t max: {}\t med: {}\t std_dev: {}'.format( batch_current, metric_selected.lower(), metric_list[0], metric_list[-1], metric_med, std_dev))
use super::BaseEvent; use crate::ExtendedMap; #[cfg(feature = "impl")] use crate::MessageAlt; use serde::{Deserialize, Serialize}; /// ## OneBot 消息事件 Content /// /// 消息事件是聊天机器人收到其他用户发送的消息对应的一类事件,例如私聊消息等。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct MessageContent { #[serde(flatten)] pub ty: MessageEventType, pub message_id: String, pub message: crate::Message, pub alt_message: String, pub user_id: String, /// just for Deserialize pub sub_type: String, #[serde(flatten)] pub extra: ExtendedMap, } /// MessageEvent detail_type ( private or group ) #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "detail_type", rename_all = "snake_case")] pub enum MessageEventType { Private, Group { group_id: String }, } impl MessageEventType { pub fn group_id(&self) -> Option<&str> { match self { MessageEventType::Group { group_id } => Some(group_id), _ => None, } } } #[cfg(feature = "impl")] impl MessageContent { pub fn new_group_message_content( message: crate::Message, message_id: String, user_id: String, group_id: String, extra: ExtendedMap, ) -> Self { Self { ty: MessageEventType::Group { group_id }, message_id, alt_message: message.alt(), message, user_id, sub_type: "".to_owned(), extra, } } pub fn new_private_message_content( message: crate::Message, message_id: String, user_id: String, extra: ExtendedMap, ) -> Self { Self { ty: MessageEventType::Private, message_id, alt_message: message.alt(), message, user_id, sub_type: "".to_owned(), extra, } } } impl BaseEvent<MessageContent> { pub fn group_id(&self) -> Option<&str> { self.content.ty.group_id() } pub fn user_id(&self) -> &str { &self.content.user_id } pub fn ty(&self) -> &MessageEventType { &self.content.ty } pub fn message_id(&self) -> &str { &self.content.message_id } pub fn message(&self) -> &crate::Message { &self.content.message } pub fn alt_message(&self) -> &str { &self.content.alt_message } pub fn sub_type(&self) -> &str { &self.content.sub_type } pub fn extra(&self) -> &ExtendedMap { &self.content.extra } }
COMMENT ON COLLATION testschema."Cl1_$%{}[]()&*^!@""'`\/#" IS 'Description for alter'; ALTER COLLATION testschema."Cl1_$%{}[]()&*^!@""'`\/#" RENAME TO "Cl1_$%{}[]()&*^!@""'`\/#a";
# Performance ## Browser Profiling - It's not automated yet(Integrating with CI) - So must perform it manually from time to time ## What to search for - Memory leak - Increasing memory - Bottleneck functions - Rendering too much ## Tools - Chrome V8 profiler - React Extension (?? Research more)
require 'net/http' require 'uri' require 'json' module Sendable class Client attr_reader :api_key def initialize(api_key) @api_key = api_key end def render(params = {}) uri = URI('https://api.sendable.io/v1/render') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) request.basic_auth(api_key, '') request.body = params.respond_to?(:to_json) ? params.to_json : JSON.dump(params) response = http.request(request) JSON.parse(response.body) end def email(params = {}) uri = URI('https://api.sendable.io/v1/email') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) request.basic_auth(api_key, '') request.body = params.respond_to?(:to_json) ? params.to_json : JSON.dump(params) response = http.request(request) JSON.parse(response.body) end end end
{"score_count": 17634, "score": 8.23, "timestamp": 1582633648.0} {"score_count": 14868, "score": 8.19, "timestamp": 1581420070.0} {"score_count": 13089, "score": 8.22, "timestamp": 1580812013.0} {"score_count": 11977, "score": 8.22, "timestamp": 1580414615.0} {"score_count": 11977, "score": 8.22, "timestamp": 1580414612.0} {"score_count": 11413, "score": 8.21, "timestamp": 1580204127.0} {"score_count": 9249, "score": 8.19, "timestamp": 1579596374.0} {"score_count": 6680, "score": 8.18, "timestamp": 1578986851.0} {"score_count": 3751, "score": 8.15, "timestamp": 1578528754.0} {"score_count": 3036, "score": 8.14, "timestamp": 1578435625.0} {"score_count": 2549, "score": 8.13, "timestamp": 1578376561.0} {"score_count": 1823, "score": 8.11, "timestamp": 1578328911.0}
using Quartz.Impl.Matchers; using Quartz.Spi; using System; using System.Threading; using System.Threading.Tasks; namespace Quartz.Plugins.RecentHistory { public class ExecutionHistoryPlugin : ISchedulerPlugin, IJobListener { IScheduler _scheduler; IExecutionHistoryStore _store; public string Name { get; set; } public Type StoreType { get; set; } public Task Initialize(string pluginName, IScheduler scheduler, CancellationToken cancellationToken = default(CancellationToken)) { Name = pluginName; _scheduler = scheduler; _scheduler.ListenerManager.AddJobListener(this, EverythingMatcher<JobKey>.AllJobs()); return Task.FromResult(0); } public Task Start(CancellationToken cancellationToken = default(CancellationToken)) { _store = _scheduler.Context.GetExecutionHistoryStore(); if (_store == null) { if (StoreType != null) _store = (IExecutionHistoryStore)Activator.CreateInstance(StoreType); if (_store == null) throw new Exception(nameof(StoreType) + " is not set."); _scheduler.Context.SetExecutionHistoryStore(_store); } _store.SchedulerName = _scheduler.SchedulerName; return _store.Purge(); } public Task Shutdown(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(0); } public Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken)) { var entry = new ExecutionHistoryEntry() { FireInstanceId = context.FireInstanceId, SchedulerInstanceId = context.Scheduler.SchedulerInstanceId, SchedulerName = context.Scheduler.SchedulerName, ActualFireTimeUtc = context.FireTimeUtc.UtcDateTime, ScheduledFireTimeUtc = context.ScheduledFireTimeUtc?.UtcDateTime, Recovering = context.Recovering, Job = context.JobDetail.Key.ToString(), Trigger = context.Trigger.Key.ToString(), }; return _store.Save(entry); } public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default(CancellationToken)) { var entry = await _store.Get(context.FireInstanceId); if (entry != null) { entry.FinishedTimeUtc = DateTime.UtcNow; entry.ExceptionMessage = jobException?.GetBaseException()?.Message; await _store.Save(entry); } if (jobException == null) await _store.IncrementTotalJobsExecuted(); else await _store.IncrementTotalJobsFailed(); } public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken)) { var entry = await _store.Get(context.FireInstanceId); if (entry != null) { entry.Vetoed = true; await _store.Save(entry); } } } }
import React, { createContext, useContext } from "react"; import { GltfStore } from "./GltfStore"; import { SettingsStore } from "./SettingsStore"; export class RootStore { public gltfStore = new GltfStore(); public settingsStore = new SettingsStore(); } export const RootStoreContext = createContext<RootStore>({} as RootStore); export const RootStoreProvider: React.FC = ({ children }) => ( <RootStoreContext.Provider value={new RootStore()}> {children} </RootStoreContext.Provider> ); export const useStores = (): RootStore => useContext<RootStore>(RootStoreContext);
<!DOCTYPE html> <html> <head> <title>Supermercado de Nuria Gutierrez Liano</title> </head> <body> <?php require_once 'categoria.php'; require_once 'producto.php'; require_once 'alimentacion.php'; require_once 'electronica.php'; require_once 'DB.php'; $bbdd = new db("localhost", "root", "", "dwes_supermercado"); echo "<h2>Productos Supermercado</h2>"; $listado = $bbdd->getProductos(); foreach ($listado as $lista) { $lista = new producto($lista->codigo, $lista->precio, $lista->nombre, $lista->categoria); print $lista->mostrar() . "<br/>"; echo "<br/>"; } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <h2>Listado de las categorias</h2> <select name="categoria"> <?php $listadoCategoria = $bbdd->getCategorias(); foreach ($listadoCategoria as $lista) { $lista = new categoria($lista->id, $lista->nombre); echo "<option value=".$lista->getNombre()."> ".$lista->getNombre()." </option>"; echo "<br/>"; } ?> </select> <input name="busqueda" type="submit" value="Buscador"></input> <?php if (isset($_POST["busqueda"])) { $c = $_POST["categoria"]; if($bbdd->getCategoriaElectronica($c)!= null){ $listaCat = $bbdd->getCategoriaElectronica($c); foreach ($listaCat as $l) { print $l->nombre. " " . $l->plazoGarantia."<br>"; } } else { $listaCat = $bbdd->getCategoriaAlimentacion($c); foreach ($listaCat as $l) { print $l->nombre . " " . $l->mesCaducidad . "/" . $l->anioCaducidad . "<br>"; } } } ?> </form> </body> </html>
package com.depromeet.bboxx.data.repository import com.depromeet.bboxx.data.mapper.TokenEntityMapper import com.depromeet.bboxx.data.mapper.TokenValidEntityMapper import com.depromeet.bboxx.data.repository.authsign.AuthSignDataSource import com.depromeet.bboxx.domain.model.Token import com.depromeet.bboxx.domain.model.TokenValid import com.depromeet.bboxx.domain.repository.auth.AuthSignRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import io.reactivex.rxjava3.core.Single import javax.inject.Inject import javax.inject.Singleton class AuthSignRepositoryImpl @Inject constructor( private val authSignDataSource: AuthSignDataSource, private val tokenEntityMapper: TokenEntityMapper, private val tokenValidEntityMapper: TokenValidEntityMapper ) : AuthSignRepository { override fun signIn(authData: String, providerType: String): Single<Token> { return authSignDataSource.authSignIn(authData, providerType) .map(tokenEntityMapper::trans) } override fun signUp(authData: String, nickName: String, providerType: String): Single<Token> { return authSignDataSource.authSignUp(authData, nickName, providerType) .map(tokenEntityMapper::trans) } override fun validToken(token: String): Single<TokenValid> { return authSignDataSource.validToken(token) .map(tokenValidEntityMapper::trans) } } @Module @InstallIn(SingletonComponent::class) abstract class AuthSignRepositoryModule { @Binds @Singleton abstract fun bindAuthSignRepository(repositoryImpl: AuthSignRepositoryImpl): AuthSignRepository }
package de.paulweber.routes.profile import de.paulweber.getBaseUrl import de.paulweber.plugins.getPrincipalIdentifier import de.paulweber.profileStore import io.ktor.application.* import io.ktor.auth.* import io.ktor.http.* import io.ktor.request.* import io.ktor.response.* import io.ktor.routing.* fun Application.registerProfileRoutes() { routing { authenticate("registered") { route("/profile") { get { val identifier = call.getPrincipalIdentifier() profileStore[identifier]?.let { call.respond(it) } ?: run { call.respond(HttpStatusCode.NotFound) } } get("/qrcode") { val identifier = call.getPrincipalIdentifier() profileStore[identifier]?.let { val code = QRCodeGenerator.generate(it.recipientCode) call.respondBytes(code) } ?: run { call.respond(HttpStatusCode.NotFound) } } post("/create") { val params = call.receive<CreateProfileParameters>() if (params.username == "") { call.respond(HttpStatusCode.BadRequest, "illegal username") } else { val identifier = call.getPrincipalIdentifier() val profile = Profile.create(params.username, identifier) profileStore[identifier] = profile call.respond(profile) } } } } } }
-- more characters for storing IP addresses (to accommodate IPv6) ALTER TABLE jforum_posts MODIFY poster_ip VARCHAR2(50); ALTER TABLE jforum_privmsgs MODIFY privmsgs_ip VARCHAR2(50); ALTER TABLE jforum_banlist MODIFY banlist_ip VARCHAR2(50); ALTER TABLE jforum_sessions MODIFY session_ip VARCHAR2(50); ALTER TABLE jforum_vote_voters MODIFY vote_user_ip VARCHAR2(50);
import { bindActionCreators, Dispatch, } from 'redux'; import { connect, } from 'react-redux'; import { fetchToken, verifyToken, } from '~/actions'; import { State, } from '~/reducers'; import { AppComponent, } from './AppComponent'; function mapStateToProps(state: State) { return { 'token': state.account.token, }; } function mapDispatchToProps(dispatch: Dispatch) { return bindActionCreators({ 'fetchToken': fetchToken.request, 'verifyToken': verifyToken.request, }, dispatch); } export const AppContainer = connect(mapStateToProps, mapDispatchToProps)(AppComponent);
<?php namespace App\Exports; use App\Models\Marca; use Maatwebsite\Excel\Concerns\FromCollection; class MarcasExport implements FromCollection { /** * @return \Illuminate\Support\Collection */ public function collection() { $marcas = Marca::where('ma_eliminado',false)->get(); $output = []; $output[] = [ "ID", "Marca", "Teléfono", "Correo", "Contacto", ]; foreach($marcas as $marca){ $output[] = [ $marca->id, $marca->ma_nombre, $marca->ma_telefono, $marca->ma_correo, $marca->ma_contacto ]; } return collect($output); } }
/* * Copyright (c) 2020 by Denis Verentsov (decsent@yandex.ru) * All rights reserved. */ package com.dvinc.core.di.component import com.dvinc.core.di.DaggerApplication import com.dvinc.core.di.module.AppToolsModule import com.dvinc.core.di.provider.AppToolsProvider import dagger.BindsInstance import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = [AppToolsModule::class]) interface AppToolsComponent : AppToolsProvider { @Component.Builder interface ComponentBuilder { @BindsInstance fun application(daggerApplication: DaggerApplication): ComponentBuilder fun build(): AppToolsComponent } class Builder private constructor() { companion object { fun build(daggerApplication: DaggerApplication): AppToolsProvider { return DaggerAppToolsComponent.builder() .application(daggerApplication) .build() } } } }
pad(io, n)::Void = print(io, " "^n) # function Base.show(io::IO, q::QueryNode, leftmargin=0)::Void # println(io, name(typeof(q))) # pad(io, leftmargin+2); println(io, "arguments:") # for (i, arg) in enumerate(q.args) # pad(io, leftmargin+6); println(io, "$i) ", arg) # end # pad(io, leftmargin+2); println(io, "inputs:") # pad(io, leftmargin+6); print(io, "1) ") # show(io, q.input, leftmargin+10) # return # end function Base.show(io::IO, q::QueryNode, leftmargin=0)::Void println(io, name(typeof(q))) pad(io, leftmargin+2); println(io, "arguments:") for (i, arg) in enumerate(q.args) pad(io, leftmargin+6); println(io, "$i) ", arg) end pad(io, leftmargin+2); println(io, "inputs:") for (i, input) in enumerate(q.inputs) pad(io, leftmargin+6); print(io, "$i) ") show(io, input, leftmargin+10) end return end function Base.show(io::IO, d::DataNode, leftmargin)::Void # println("Data source: ", d.input) println(io, name(typeof(d))) pad(io, leftmargin+2); print(io, "source: ") if isdefined(d, :input) println(io, "source of type ", name(typeof(d.input))) else println(io, "unset source") end return end
// ignore_for_file: unnecessary_this import '../../curo.dart'; import '../daycount/convention.dart'; import 'cash_flow.dart'; import 'validator.dart'; /// A container for a series of cash in-flows and out-flows. /// class Profile { /// The cash flow series. final List<CashFlow> cashFlows; /// The day count convention applied to cash flows in the series. final Convention dayCount; /// The post date of the *first drawdown*. Analogous to a contract date. late final DateTime firstDrawdownPostDate; /// The value date of the *first drawdown*. This date is expected to /// occur on or after the drawdown post date and is used specifically /// in deferred settlement calculations. late final DateTime firstDrawdownValueDate; /// The number of fractional digits to apply in the rounding of /// cash flow values. final int precision; /// Instantiates a profile instance and performs basic validation. /// /// [cashFlows] the collection of advance, payment and charge cash flow /// objects /// /// [precision] (optional) the number of fractional digits to apply in the /// rounding of cash flow values in the notional currency. Default is 2, /// with valid options being 0, 2, 3 and 4 /// /// [dayCount] (optional) the convention to use in computing time periods. /// Default is [US30360] /// Profile({ required this.cashFlows, this.precision = 2, this.dayCount = const US30360(), }) { validatePrecision(precision); final firstDrawdown = validateAdvances(cashFlows); firstDrawdownPostDate = firstDrawdown.postDate; firstDrawdownValueDate = firstDrawdown.valueDate; validatePayments(cashFlows); validateUnknowns(cashFlows); validateIsInterestCapitalised(cashFlows); } Profile copyWith({ List<CashFlow>? cashFlows, int? precision, Convention? dayCount, }) => Profile( cashFlows: cashFlows ?? this.cashFlows, precision: precision ?? this.precision, dayCount: dayCount ?? this.dayCount, ); // coverage:ignore-start @override String toString() { final sb = StringBuffer(); sb.write('Profile ['); sb.write('cashFlows: $cashFlows, '); sb.write('\ndayCount: $dayCount, '); sb.write('\nfirstDrawdownPostDate: $firstDrawdownPostDate, '); sb.write('\nfirstDrawdownValueDate: $firstDrawdownValueDate, '); sb.write('\nprecision: $precision, '); sb.write(']'); return sb.toString(); } // coverage:ignore-end }
$(document).ready(function() { $('#allDataTable').DataTable({ "info": true, "ordering": false, "seraching": true, "paging": true, }); });
package models import play.api._ import play.api.libs.json._ case class SongInput( id: String, startTime: Long, endTime: Long, titre: String, titreAlbum: String, interpreteMorceau: String, anneeEditionMusique: Option[String], label: Option[String], visuel: Map[String, String], lien: String ) case class Song( id: String, startTime: Long, endTime: Long, title: String, album: String, artist: String, year: Option[String], label: Option[String], icons: Map[String, String], itunes: String ) object Song { import Error._ implicit val songInputFormat = Json.format[SongInput] implicit val songFormat = Json.format[Song] def fromInput(input: SongInput): Song = { Song( input.id, input.startTime, input.endTime, input.titre, input.titreAlbum, input.interpreteMorceau, input.anneeEditionMusique, input.label, input.visuel, input.lien ) } def fromJson(json: JsValue): Either[InvalidSongData, Song] = { val result = (json \ "current" \ "song").validate[SongInput] result.fold(e => Left(InvalidSongData(e)), s => Right(fromInput(s))) } }
package app.flux.react.uielements.media import app.flux.action.AppActions import app.flux.action.AppActions.AddSongsToPlaylist.Placement import app.flux.router.AppPages import app.flux.stores.media.AlbumDetailStoreFactory import app.flux.stores.media.PlayStatusStore import app.models.media.JsAlbum import app.models.media.JsSong import hydro.common.ScalaUtils import hydro.common.ScalaUtils.ifThenOption import hydro.flux.action.Dispatcher import hydro.flux.react.uielements.Bootstrap import hydro.flux.react.HydroReactComponent import hydro.flux.router.RouterContext import japgolly.scalajs.react._ import japgolly.scalajs.react.vdom.html_<^._ import scala.async.Async.async import scala.async.Async.await import scala.collection.immutable.Seq import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue final class AlbumDiv(implicit dispatcher: Dispatcher, albumDetailStoreFactory: AlbumDetailStoreFactory, playStatusStore: PlayStatusStore, ) extends HydroReactComponent { // **************** API ****************// def apply(album: JsAlbum, key: Any)(implicit router: RouterContext): VdomElement = { component.withKey(key.toString).apply(Props(album)) } // **************** Implementation of HydroReactComponent methods ****************// override protected val config = ComponentConfig(backendConstructor = new Backend(_), initialState = State()) .withStateStoresDependencyFromProps { props => StateStoresDependency( albumDetailStoreFactory.get(props.album.id), _ => getNewStateFromStores(props) ) } .withStateStoresDependencyFromProps { props => StateStoresDependency( playStatusStore, _ => getNewStateFromStores(props) ) } private def getNewStateFromStores(props: Props): State = { val albumDetailState = albumDetailStoreFactory.get(props.album.id).state val playStatusState = playStatusStore.state val songs = albumDetailState.map(_.songs) getOrElse Seq() val isCurrentAlbum = { for { state <- playStatusState currentEntry <- state.currentPlaylistEntry } yield songs.exists(_.id == currentEntry.song.id) } getOrElse false val isNowPlaying = isCurrentAlbum && playStatusState.get.hasStarted State( songs = songs, isCurrentAlbum = isCurrentAlbum, isNowPlaying = isNowPlaying, ) } // **************** Implementation of HydroReactComponent types ****************// protected case class Props(album: JsAlbum)(implicit val router: RouterContext) protected case class State(songs: Seq[JsSong] = Seq(), isCurrentAlbum: Boolean = false, isNowPlaying: Boolean = false) protected class Backend($ : BackendScope[Props, State]) extends BackendBase($) { override def render(props: Props, state: State): VdomElement = { implicit val router = props.router val buttons = <.div( Bootstrap.Glyphicon("circle-arrow-right")( ^.onClick --> addSongsToPlaylistCallback( albumId = props.album.id, placement = Placement.AfterCurrentSong) ), " ", Bootstrap.Glyphicon("plus-sign")( ^.onClick --> addSongsToPlaylistCallback(albumId = props.album.id, placement = Placement.AtEnd) ) ) val numberOfSongs: Option[VdomTag] = ifThenOption(state.songs.nonEmpty) { <.span( Bootstrap.Glyphicon("music"), " ", state.songs.size ) } val yearInfo: Option[VdomTag] = props.album.year map { year => <.span( Bootstrap.FontAwesomeIcon("microphone"), " ", year ) } val pathInfo: VdomTag = <.span( Bootstrap.FontAwesomeIcon("thumb-tack"), " ", props.album.relativePath ) GeneralMusicDivs.musicalObjectWithButtons( icon = Bootstrap.Glyphicon("cd"), title = router.anchorWithHrefTo(AppPages.Album(props.album.id))(props.album.title), extraPiecesOfInfo = Seq() ++ numberOfSongs ++ yearInfo :+ pathInfo, buttons = Some(buttons), isCurrentObject = state.isCurrentAlbum, isNowPlaying = state.isNowPlaying, )( ^.className := "album-div", ) } // **************** Private helper methods ****************// private def addSongsToPlaylistCallback(albumId: Long, placement: Placement): Callback = Callback.future(async { // Force wait until the state has been loaded val albumState = await(albumDetailStoreFactory.get(albumId).stateFuture) await( dispatcher.dispatch( AppActions.AddSongsToPlaylist(songIds = albumState.songs.map(_.id), placement = placement))) Callback.empty }) } }
--- layout: static title: Jupyter Notebook template: 3-columns name: Jupyter Notebbok category: Machine Learning --- # jupyter notebook ## インストール アナコンダをインストール ## ローカルサーバーを起動する ``` $ cd <jupyter notebook> $ jupyter notebook ``` ## ローカルサーバーをシャットダウンする ``` $ (crtl + c) ``` ## カーネル操作 セルで、bashを実行するには、コマンドの先頭に`!`を付ける ``` !pip install -q keras ``` からの ``` import keras ``` ## 設定ファイルの作成 ``` $ jupyter notebook --generate-config ``` `~/.jupyter/jupyter_notebook_config.py`が作成される。 ## Pythonの実行環境設定 システム環境、miniconda、仮想環境の交通整理 bashとJupyter Notebookで実行環境が一致することを確認する。 ### 注意 本章の記述では、condaの仮想環境を作成している記述があるが、最終的には、仮想環境を作成しないことにした。 やりたかったこと - Jupyter Notebookを主に使用し、機械学習の学習を行う。 - また、機械学習の機能をAPI化しても良いように、Jupyterとbashの実行環境を一致させる。(参照先を`/opt/conda/bin`にした。) - Dockerでコンテナ化する。 できなかったこと - venv,pyenv,condaを使用して仮想環境を作成する。 つまづく所 - 仮想環境を作成すると、`conda install`だと`/opt/conda/bin`に、`pip install`だと、`/opt/conda/envs/env/bin`にインストールされて、統一されない。 - 上記理由で、Jupyter Notebookは、`/opt/conda/bin`の方にインストールされ、仮想環境(動かしたいバージョンのPython)では動かせない。 - tensorflow-gpuはPython3.4~3.6でサポートされるが、minicondaの最新をインストールしたらPython3.7になり、Jupyter Notebookでは、tensorflow-gpuを使用できない。 解決策 - minicondaを使用するが、仮想環境は使用しない。 (Dockerコンテナ化されているので、環境の再現性はあるとする。) - minicondaの最新をインストールするが、直後に、Pythonの3.6を再インストール(Pythonをダウングレード)する。 ### conda/pipコマンド - bashでのインタラクティブモード起動 ``` $ python ``` - Pythonの実行モジュール確認 ``` $ which python ``` - Pythonの実行モジュールのバージョン確認 ``` $ python --version ``` - pipのライブラリ一覧 ``` $ pip list ``` or ``` $ pip freeze ``` - condaのライブラリ一覧 ``` $ conda list ``` - pathの確認 ``` import sys sys.path ``` - pipでインストールしたライブラリの格納場所 ``` $ pip show hoge ``` 一度、`bin`階層に`.whl`ファイル(zipと同じ)をダウンロードしてから、`lib/python3.6/site-packages`にインストール(展開)している。 自分で`clean`コマンドをしないとダウンロードしたファイルは消えないと思われる。 `no-cache-dir`というオプションがあるのでメモ。 ``` pip install --no-cache-dir -r /usr/src/app/requirements.txt ``` - インストールしたモジュールがimportできるか確認 ``` import hoge ``` ### ライブラリの一括適用 - ライブラリ一覧をExport ``` $ conda myenv export > myenv.yaml ``` - ライブラリーを一括Import ``` $ conda myenv create --file myenv.yaml ``` ### Jupyter NotebookのKernelに仮想環境を追加 - 仮想環境を作成 ``` $ conda create -n myenv python=3.6 ``` - condaの仮想環境一覧 ``` $ conda info -e ``` or ``` $ conda env list ``` - 仮想環境をActiate ``` $ source activate myenv (myenv) $ conda install notebook ipykernel (myenv) $ ipython kernel install --user --name myenv (myenv) $ jupyter kernelspec list ``` notebookの右上のnewのところで、myenvを選択できるようになる。 既存のnotebookのkernelのプルダウンでも、kernelを変更できるようになっている。 ### 自作モジュールの使用 下記の階層の場合の、自作モジュールのimportの方法について - 実行モジュール.py or .ipynb - my_modules(package) - \__init__.py(packageを再帰的に読み込むためのダミーファイル) - my_module.py(module) - my_class(class) - my_def(function) 1.packageはimportできない。パッケージはフォルダだからかな? ``` import my_modules ``` -> error 2.moduleはimportできる。fromを使用してもよい。 ``` import my_modules.my_module ``` -> ok ``` from my_modules import my_module ``` -> ok 3.classはimportできるが、fromを使用しないといけない(.でパスを指定できない) ``` import my_modules.my_module.myclass ``` -> error ``` from my_modules.my_module import myclass ``` -> ok
module Roleman class Router attr_reader :routes def initialize(routes) @routes = routes end #FIXME optimize lookup algorithm def find_route(path, method) method = method.upcase routes.each do |route| next unless route.method == method if route.regex && route.regex.match?(path) return route elsif route.path == path return route end end nil end end end
# @see http://api.myemma.com/api/external/fields.html module Emma module API module Fields # Gets a list of this account’s defined fields. def my_fields(params = {}) get("/fields", params) end # Gets the detailed information about a particular field. def get_field_by_id(id, params = {}) get("/fields/#{id}", params) end # Create a new field def add_field(params = {}) post("/fields", params) end # Delete a field def remove_field(id) delete("/fields/#{id}") end # Clear the member data for the specified field. def remove_member_data_for_field(id) post("/fields/#{id}/clear") end # Updates an existing field. def update_field(id, params = {}) put("/fields/#{id}", params) end end end end
--- layout: post title: "Nice Sky" tags: - albuquerque - farm - clouds hero: ../uploads/IMAG1526_optimized.jpg overlay: orange published: true --- [![Nice Sky](../uploads/IMAG1526_optimized.jpg){:.lead}](../uploads/IMAG1526.jpg)
using FluentValidation; namespace ChallengeBuiltCode.Business.Models.Validations { public class PatientValidation : AbstractValidator<Patient> { public PatientValidation() { RuleFor(f => f.BirthDate) .NotEmpty().WithMessage("The 'BirthDate' is required"); RuleFor(f => f.Cpf) .NotEmpty().WithMessage("The 'Cpf' is required"); RuleFor(f => f.Name) .NotEmpty().WithMessage("The 'Name' is required"); } } }
import 'package:dio/dio.dart'; import 'package:flutter_template/util/interceptor/combining_smart_interceptor.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../di/test_injectable.dart'; void main() { CombiningSmartInterceptor sut; setUp(() async { await initTestInjectable(); sut = CombiningSmartInterceptor(); }); test('CombiningSmartInterceptor test sequence onrequest', () async { final interceptor1 = TestInterceptor(); final interceptor2 = TestInterceptor(); final interceptor3 = TestInterceptor(); sut..addInterceptor(interceptor1)..addInterceptor(interceptor2)..addInterceptor(interceptor3); final requestOptions = RequestOptions(); await sut.onRequest(requestOptions); expect(interceptor1.onRequestCalled.isBefore(interceptor2.onRequestCalled), true); expect(interceptor2.onRequestCalled.isBefore(interceptor3.onRequestCalled), true); }); test('CombiningSmartInterceptor test sequence onresponse', () async { final interceptor1 = TestInterceptor(); final interceptor2 = TestInterceptor(); final interceptor3 = TestInterceptor(); sut..addInterceptor(interceptor1)..addInterceptor(interceptor2)..addInterceptor(interceptor3); final response = Response<void>(); await sut.onResponse(response); expect(interceptor1.onResponseCalled.isAfter(interceptor2.onResponseCalled), true); expect(interceptor2.onResponseCalled.isAfter(interceptor3.onResponseCalled), true); }); test('CombiningSmartInterceptor test sequence onError', () async { final interceptor1 = TestInterceptor(); final interceptor2 = TestInterceptor(); final interceptor3 = TestInterceptor(); sut..addInterceptor(interceptor1)..addInterceptor(interceptor2)..addInterceptor(interceptor3); final error = DioError(); await sut.onError(error); expect(interceptor1.onErrorCalled.isAfter(interceptor2.onErrorCalled), true); expect(interceptor2.onErrorCalled.isAfter(interceptor3.onErrorCalled), true); }); } class TestInterceptor extends Interceptor { DateTime onRequestCalled; DateTime onResponseCalled; DateTime onErrorCalled; @override Future onRequest(RequestOptions options) { onRequestCalled = DateTime.now(); return super.onRequest(options); } @override Future onResponse(Response response) { onResponseCalled = DateTime.now(); return super.onResponse(response); } @override Future onError(DioError err) { onErrorCalled = DateTime.now(); return super.onError(err); } }
export enum AUTH_ROLES { USER, } export const COOKIE_NAME_JWT_TOKEN = "JWT_TOKEN"; export const VISITOR_SIADBARS: { label: string; tab: string }[] = [ { label: "User Info", tab: "", }, { label: "Torrent Status", tab: "torrentsStatus", }, ]; export const PROFILE_SIDEBARS: { label: string; tab: string }[] = [ { label: "User Info", tab: "", }, { label: "Torrents Status", tab: "torrentsStatus", }, { label: "Send Invitation", tab: "invitations", }, { label: "Security", tab: "security", }, ]; export const PROFILE_SIDEBARS_ADMIN: { label: string; tab: string }[] = [ { label: "Manage Torrent", tab: "#torrent", }, { label: "Manage User", tab: "#user", }, { label: "Configure Site", tab: "#site", }, ];
--- layout: tag permalink: /ml-blog/ author_profile: true header: image: "/images/other/intro_3.png" taxonomy: ml entries_layout: list --- Welcome to my blog! I hope you enjoy the posts. Posts will either be Fun/Random <b>[Rand]</b> or Research/Ideas <b>[Idea]</b>. Enjoy!
<?php session_start(); $jAdmin = $_SESSION['sUser']; if( !isset($_SESSION['sUser']) ) { header('Location: index'); } //get database $sData = file_get_contents('../data/subscribers.json'); $jData = json_decode($sData); //handle input $sSubject = $_POST['newsletter-subject']; if(empty($sSubject)){sendResponse(0,__LINE__,'Newsletter subject is missing');} $sContent = $_POST['newsletter-content']; if(empty($sContent)){sendResponse(0,__LINE__,'Newsletter content is missing');} foreach ($jData->subscribers as $sSubscriberId => $jSubscriber){ $to = $jSubscriber->email; $headers = "From: newsletter@swb.dk"; if( mail($to,$sSubject,$sContent,$headers)) { sendResponse(1, __LINE__, 'Mail successfully sent to all subscribers.'); } else { sendResponse(0, __LINE__, 'We have spotted some problem with your request. Try again. '); } } // ************************************************************************************************** function sendResponse($iStatus, $iLineNumber, $sMessage) { echo '{"status":'.$iStatus.', "code":'.$iLineNumber.',"message":"'.$sMessage.'"}'; exit; }
import {Injectable} from '@angular/core'; import {createMnemonic, getSHA3hashSum} from './binance-crypto'; import {StorageService} from './storage.service'; import {StateService} from './state.service'; @Injectable() export class RegistrationService { mnemonic: string = null; private passHash: string; constructor(private storageService: StorageService, private stateService: StateService) { } get hasMnemonic(): boolean { return !!this.mnemonic; } generateMnemonic(): string { this.mnemonic = createMnemonic(); return this.mnemonic; } set password(value: string) { this.passHash = getSHA3hashSum(value); } isPasswordRepeatedCorrectly(passwordRepeat: string): boolean { return this.passHash && this.passHash === getSHA3hashSum(passwordRepeat); } finishRegistration(repeatedPassword: string): boolean { if (!this.isPasswordRepeatedCorrectly(repeatedPassword)) { return false; } const data = this.storageService.registerAccount(this.mnemonic, repeatedPassword); this.stateService.initState(data, repeatedPassword); // cleanup - TODO: move at the component level this.mnemonic = null; this.passHash = null; return true; } // TODO: check how import works now // async finishImport(password: string): Promise<boolean> { // this.addAccount(this.mnemonic, password); // this.cleanup(); // return true; // } }
enum SelectType { start, between, end, none, disabled, selected, empty }
<?php namespace Mchekin\MVCBoiler\Filters; abstract class Filter { protected $message = 'Invalid value'; protected $min = 3; protected $max = 255; /** * @param string $value * @return bool */ abstract public function validate($value); /** * @param string $value * @return string */ abstract public function sanitize($value); /** * @return string */ public function getMessage() { return $this->message; } }
class FiatStripe::Subscription::CancelStripeSubscriptionJob < ApplicationJob queue_as :default def perform(subscription) if subscription sub = Stripe::Subscription.retrieve({ id: subscription.id }, api_key: subscribable.stripe_api_key) sub.delete end end end
package levsha.benchmark import org.openjdk.jmh.annotations.{Benchmark, Param, Scope, State} @State(Scope.Benchmark) class StaticRenderingComparision { import StaticRenderingComparision.engines // TODO "beard" @Param(Array("levsha", "scalatags", "twirl")) var engineName: String = _ @Benchmark def simpleHtml(): Unit = engines(engineName).simpleHtml() @Benchmark def withVariables(): Unit = engines(engineName).withVariables() @Benchmark def withConditionAndLoop(): Unit = engines(engineName).withConditionAndLoop() } object StaticRenderingComparision { trait TemplateEngine { def simpleHtml(): Unit def withVariables(): Unit def withConditionAndLoop(): Unit } val engines = Map( "levsha" -> new TemplateEngine { import sharedContent._ import levsha.text.symbolDsl._ import levsha.text.renderHtml def simpleHtml(): Unit = { renderHtml { 'body( 'div('class /= "title", "Hello, I'm Cow!"), 'ul('class /= "list", 'li("One"), 'li("Two"), 'li("Three"), 'li("..."), 'li("Moooo") ) ) } } def withVariables(): Unit = { renderHtml { 'body( 'div('class /= "title", greeting), 'ul('class /= className, 'li("One"), 'li("Two"), 'li("Three"), 'li("..."), 'li("Moooo") ) ) } } def withConditionAndLoop(): Unit = { renderHtml { 'body( 'div('class /= "title", if (condition) leftBranch else rightBranch ), 'ul('class /= className, items.map(item => 'li(item)) ) ) } } }, "scalatags" -> new TemplateEngine { import sharedContent._ import scalatags.Text.all._ def simpleHtml(): Unit = { val tags = body( div(`class` := "title")("Hello, I'm Cow!"), ul(`class` := "list")( li("One"), li("Two"), li("Three"), li("..."), li("Moooo") ) ) tags.render } def withVariables(): Unit = { val tags = body( div(`class` := "title")(greeting), ul(`class` := className)( li("One"), li("Two"), li("Three"), li("..."), li("Moooo") ) ) tags.render } def withConditionAndLoop(): Unit = { val tags = body( div(`class` := "title")( if (condition) leftBranch else rightBranch ), ul(`class` := className)( items.map(item => li(item)) ) ) tags.render } } , "twirl" -> new TemplateEngine { import sharedContent._ def simpleHtml(): Unit = html.simple() def withVariables(): Unit = html.withVariables(greeting, className) def withConditionAndLoop(): Unit = html.withConditionAndLoop(condition, leftBranch, rightBranch, items) } ) // The content should be rendered by template engine object sharedContent { val greeting = "Hello, I'm Cow!" val className = "list" val condition = true val leftBranch = "Welcome!" val rightBranch = "Get off!" val items = Seq( "One", "Two", "Three", "...", "Moooo" ) } }
# Emerald 面向游戏的轻量级绘图框架 # 支持 Visual Basic 6.0 # 功能 √ 基本图形的绘制 √ 即时控件 √ 安全游戏存档 √ 游戏资源管理器 √ 游戏页面管理器 √ 封装Bass的音乐播放器 √ 动画系统 # 文档 [Emerald Wiki](https://github.com/buger404/Emerald/wiki) # English Version # Emerald A game framework for Visual Basic 6.0. # Support Visual Basic 6.0 # Functions √ Basic Graphics Drawing √ Immediate Controls √ Safe Game Save √ Game Resource Manager √ Game Page Manager √ Music Player based on Bass √ Animation System # Documentation [Emerald Wiki](https://github.com/buger404/Emerald/wiki)
class VideoAuth def initialize video, user = nil @video = video @user = user end def play raise StandardError, "Unauthorized" unless @user == "Authenticated user" @video.play end end
#!/usr/bin/perl # Shared code for glibc conformance tests. # Copyright (C) 2014-2016 Free Software Foundation, Inc. # This file is part of the GNU C Library. # The GNU C Library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # The GNU C Library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with the GNU C Library; if not, see # <http://www.gnu.org/licenses/>. package GlibcConform; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(%CFLAGS list_exported_functions); # Compiler options for each standard. $CFLAGS{"ISO"} = "-ansi"; $CFLAGS{"ISO99"} = "-std=c99"; $CFLAGS{"ISO11"} = "-std=c11"; $CFLAGS{"POSIX"} = "-D_POSIX_C_SOURCE=199506L -ansi"; $CFLAGS{"XPG3"} = "-ansi -D_XOPEN_SOURCE"; $CFLAGS{"XPG4"} = "-ansi -D_XOPEN_SOURCE -D_XOPEN_SOURCE_EXTENDED"; $CFLAGS{"UNIX98"} = "-ansi -D_XOPEN_SOURCE=500"; $CFLAGS{"XOPEN2K"} = "-std=c99 -D_XOPEN_SOURCE=600"; $CFLAGS{"XOPEN2K8"} = "-std=c99 -D_XOPEN_SOURCE=700"; $CFLAGS{"POSIX2008"} = "-std=c99 -D_POSIX_C_SOURCE=200809L"; # Return a list of functions exported by a header, empty if an include # of the header does not compile. sub list_exported_functions { my ($cc, $standard, $header, $tmpdir) = @_; my ($cc_all) = "$cc -D_ISOMAC $CFLAGS{$standard}"; my ($tmpfile) = "$tmpdir/list-$$.c"; my ($auxfile) = "$tmpdir/list-$$.c.aux"; my ($ret); my (%res) = (); open (TMPFILE, ">$tmpfile") || die ("open $tmpfile: $!\n"); print TMPFILE "#include <$header>\n"; close (TMPFILE) || die ("close $tmpfile: $!\n"); $ret = system "$cc_all -c $tmpfile -o /dev/null -aux-info $auxfile > /dev/null"; unlink ($tmpfile) || die ("unlink $tmpfile: $!\n"); if ($ret != 0) { return; } open (AUXFILE, "<$auxfile") || die ("open $auxfile: $!\n"); while (<AUXFILE>) { s|/\*.*?\*/||g; if (/^\s*$/) { next; } # The word before a '(' that isn't '(*' is the function name # before the argument list (not fully general, but sufficient for # -aux-info output on standard headers). if (/(\w+)\s*\([^*]/) { $res{$1} = 1; } else { die ("couldn't parse -aux-info output: $_\n"); } } close (AUXFILE) || die ("close $auxfile: $!\n"); unlink ($auxfile) || die ("unlink $auxfile: $!\n"); return sort keys %res; }
package controllers import io.flow.healthcheck.v0.Client import io.flow.healthcheck.v0.models.Healthcheck import io.flow.test.utils.FlowPlaySpec class HealthchecksSpec extends FlowPlaySpec with db.Helpers { lazy val client = new Client(wsClient, s"http://localhost:$port") "GET /_internal_/healthcheck" in { await(client.healthchecks.getHealthcheck()) must be (Healthcheck("healthy")) } }
const { Router } = require('express') const router = Router() const auth = require('../middleware/auth') const Poems = require('../model/Poema') const rateLimit = require('express-rate-limit') const { v4: uuidv4 } = require('uuid') const User = require('../model/User') const Category = require('../model/Category') const { Types } = require('mongoose') const createRateLimit = rateLimit({ windowMs: 60 * 60 * 1000, max: 3, message: { success: false, message: 'Rate limit' } }) router.get('/list', async (req, res) => { if (req.query.limit) { const getPoemas = await Poems.find().limit(parseInt(req.query.limit)).lean() const poemas = await Promise.all(getPoemas.map(async p => { const likes = await User.find({ liked: p._id }).countDocuments() return { ...p, likes } })) return res.json({ success: true, data: poemas }) } if (req.query.category) { const findCategory = await Category.find() if (!!findCategory.find(r => r.name.toLowerCase() === req.query.category.toLowerCase())) { const getPoemas = await Poems.find({ category: req.query.category.toLowerCase() }).lean() const poemas = await Promise.all(getPoemas.map(async p => { const likes = await User.find({ liked: p._id }).countDocuments() return { ...p, likes } })) return res.json({ success: true, data: poemas }) } res.status(400).json({ success: false, message: 'Категория не найдена' }) } const getPoemas = await Poems.find().lean() const poemas = await Promise.all(getPoemas.map(async p => { const likes = await User.find({ liked: p._id }).countDocuments() return { ...p, likes } })) return res.json({ success: true, data: poemas }) }) router.put('/create', auth, createRateLimit, async (req, res) => { const { title, thumbnail, text, author, category } = req.body if (!title) { return res.status(400).json({ success: false, message: 'Вы не указали заголовок' }) } if (!category) { return res.status(400).json({ success: false, message: 'Вы не указали категорию' }) } if (!text) { return res.status(400).json({ success: false, message: 'Вы не указали текст стиха' }) } if (!author) { return res.status(400).json({ success: false, message: 'Вы не указали автора стиха' }) } const findCategory = await Category.findOne({ name: category.toLowerCase() }) if (!findCategory) { return res.status(400).json({ success: false, message: 'Вы не указали категорию' }) } await Poems.create({ title, thumbnail, text, creator: req.user.userId, author, category: category.toLowerCase() }) res.status(200).json({ success: true, message: 'Вы успешно добавили стих на сайт' }) }) router.get('/get/:id', async (req, res) => { const find = await Poems.findById(req.params.id).lean() if (find) { // we need to cache it, but this project doesn't use redis or memcached const likes = await User.find({ liked: find._id }).countDocuments() res.status(201).json({ success: true, data: { ...find, likes } }) } else { res.status(400).json({ success: false, message: 'Стих не найден' }) } }) router.get('/get/:id/comments', async (req, res) => { const find = await Poems.findById(req.params.id) if (find) { res.status(201).json({ success: true, data: find.comments }) } else { res.status(400).json({ success: false, message: 'Стих не найден' }) } }) router.post('/comment/:id', auth, createRateLimit, async (req, res) => { const { text } = req.body const find = await Poems.findById(req.params.id) if (!find) { return res.status(400).json({ success: false, message: 'Стих не найден' }) } if(!text) { res.status(400).json({ success: false, message: 'Вы не указали текст комментария' }) } const id = uuidv4() const update = await Poems.findByIdAndUpdate(req.params.id, { $push: { comments: { text, id} } }) if(!update) { return res.status(400).json({ success: false, message: 'Что-то пошло не так, повторите попытку позже' }) } res.status(201).json({ success: true, message: 'Вы успешно добавили комменарий' }) }) router.delete('/comment/:id', auth, async (req, res) => { const { id } = req.body if(!id) { res.status(400).json({ success: false, message: 'Вы не указали id комментария' }) } const find = await Poems.findOne({ _id: Types.ObjectId(req.params.id)}, { comments: { $elemMatch: { id } } }) if(!find) { return res.status(400).json({ success: false, message: 'Стих или комментарий не найден' }) } await Poems.findByIdAndUpdate(req.params.id, { $pull: { comments: find.comments[0] } }) res.status(200).json({ success: true, message: 'Комментарий удален' }) }) router.post('/like/:id', auth, async (req, res) => { if (!req.params.id) { return res.status(400).json({ success: false, message: 'Стих не найден' }) } const poema = await Poems.findById(req.params.id) if (!poema) { return res.status(400).json({ success: false, message: 'Стих не найден' }) } const hasLike = await User.find({ _id: req.user.userId, liked: poema._id }) if (hasLike.length > 0) { await User.findByIdAndUpdate(req.user.userId, { $pull: { liked: poema._id } }) return res.status(201).json({ success: true, message: 'Вы убрали этот стих из понравившихся' }) } await User.findByIdAndUpdate(req.user.userId, { $push: { liked: poema._id } }) res.status(201).json({ success: true, message: 'Вы добавили в понравившийся этот стих' }) }) router.delete('/delete/:id', auth, async (req, res) => { const findPoema = await Poems.findById(req.params.id) if (!findPoema) { return res.status(400).json({ success: false, message: 'Стих не найден' }) } if (Types.ObjectId(findPoema.creator).equals(Types.ObjectId(req.user.userId)) || req.user.mod) { await Poems.findByIdAndDelete(req.params.id) await User.updateMany({ $pull: { liked: { _id: Types.ObjectId(req.params.id) } } }) res.json({ success: true, message: 'Стих удален' }) } else { res.status(400).json({ success: false, message: 'Вы не автор текста' }) } }) router.get('/my', auth, async (req, res) => { const find = await User.findById(req.user.userId) if (!find) { return res.status(401).json({ success: false, message: 'Вы не авторизованы' }) } const findPoems = await Poems.find({ creator: Types.ObjectId(req.user.userId) }) res.status(201).json({ success: true, data: { liked: find.liked, you: findPoems, id: req.user.userId, email: req.user.email, mod: req.user.mod } }) }) module.exports = router
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WeiXinManage.Model { /// <summary> /// 图文信息 /// </summary> public class S_ImageText : SendBase { public S_ImageText() { Articles = new List<Article>(); base.MsgType = "news"; } /// <summary> /// 图文消息个数,限制为10条以内,必须 /// </summary> protected int ArticleCount { get { return Articles.Count(); } } public List<Article> Articles { get; set; } } }
#!/bin/bash # LinuxGSM install_factorio_save.sh function # Author: Kristian Polso # Website: https://linuxgsm.com # Description: Creates the initial save file for Factorio functionselfname="$(basename "$(readlink -f "${BASH_SOURCE[0]}")")" echo -e "" echo -e "${lightyellow}Creating initial Factorio savefile${default}" echo -e "=================================" fn_sleep_time check_glibc.sh "${executabledir}"/factorio --create "${serverfiles}/save1"
using System; using System.Collections.Generic; using SmartSql.Configuration.Tags; namespace SmartSql.IdGenerator { public interface ISnowflakeId : IIdGenerator { int MachineIdBits { get; } int SequenceBits { get; } long Epoch { get; } DateTimeOffset EpochTime { get; } long MachineId { get; } long Sequence { get; } int MaxMachineMask { get; } int SequenceMask { get; } int TimestampShift { get; } long LastTimestamp { get; } long TimestampMask { get; } long TilNextMillis(long lastTimestamp); long TimeGen(); SnowflakeIdState FromId(long snowflakeId); SnowflakeIdState FromId(String idString); } }
# encoding: utf-8 require 'rubygems' require 'yaml' class Spore module SpecParser class Yaml attr_reader :specs def self.load_file(f) YAML.load_file(f) end end end end
namespace EntityGraphQL.Schema.FieldExtensions { public class ConnectionArgs { // forward pagination public int? First { get; set; } = null; public string After { get; set; } = null; [GraphQLIgnore] public int? AfterNum { get; set; } = null; // backward pagination public int? Last { get; set; } = null; public string Before { get; set; } = null; [GraphQLIgnore] public int? BeforeNum { get; set; } = null; // On creation of Connection<> we store the total count here to avoid having to execute it multiple times [GraphQLIgnore] public int TotalCount { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Web; using Microsoft.AspNetCore.Http; using RemoteFork.Network; namespace RemoteFork.Requests { public class ProxyM3u8RequestHandler : BaseRequestHandler<byte[]> { public const string UrlPath = "proxym3u8"; public override async Task<byte[]> Handle(HttpRequest request, HttpResponse response) { try { string url = HttpUtility.UrlDecode(request.Path.Value.Replace("/" + UrlPath, "")); if (url.StartsWith("B")) { if (url.Contains("endbase64")) { url = Encoding.UTF8.GetString( Convert.FromBase64String(url.Substring(1, url.IndexOf("endbase64") - 1))) + url.Substring(url.IndexOf("endbase64") + 9); } else { url = Encoding.UTF8.GetString(Convert.FromBase64String(url.Substring(1, url.Length - 2))); } } string ts = string.Empty; bool usertype = false; var header = new Dictionary<string, string>(); Log.LogDebug("Proxy url: " + url); if (url.Contains("OPT:")) { if (url.IndexOf("OPEND:/") == url.Length - 7) { url = url.Replace("OPEND:/", ""); Log.LogDebug("Req root m3u8 " + url); } else { ts = url.Substring(url.IndexOf("OPEND:/") + 7); Log.LogDebug("Req m3u8 ts " + ts); } if (url.Contains("OPEND:/")) { url = url.Substring(0, url.IndexOf("OPEND:/")); } var headers = url.Substring(url.IndexOf("OPT:") + 4).Replace("--", "|").Split('|'); url = url.Remove(url.IndexOf("OPT:")); for (int i = 0; i < headers.Length; i++) { if (headers[i] == "ContentType") { if (request.Headers.ContainsKey("Range")) { header["Range"] = request.Headers["Range"]; } response.Headers.Add("Accept-Ranges", "bytes"); Log.LogDebug("reproxy with ContentType"); usertype = true; response.ContentType = headers[++i]; continue; } header[headers[i]] = headers[++i]; Log.LogDebug($"{headers[i - 1]}={headers[i]}"); } } if (!usertype) { if (!string.IsNullOrEmpty(ts)) { url = url.Remove(url.LastIndexOf("/") + 1) + ts; Log.LogDebug($"Full ts url {url}"); response.ContentType = "video/mp2t"; } else { response.ContentType = "application/vnd.apple.mpegurl"; } } //response.Headers.Remove("Tranfer-Encoding"); //response.Headers.Remove("Keep-Alive"); response.Headers.Add("Connection", "Close"); // response.AddHeader("Accept-Ranges", "bytes"); Log.LogDebug($"Real url:{url}"); Log.LogDebug($"usertype:{usertype}"); var data = await HTTPUtility.GetBytesRequestAsync(url, header, usertype); return data; } catch (Exception exception) { Log.LogError(exception); return Encoding.UTF8.GetBytes(exception.ToString()); } } } }
import {indexCondition} from "../common/indexCondition"; /** * @param array - The array to slice. * @param start - The start position. * @param end - The end position. * Creates a slice of array from start up to, but not including, end. * Note: This method is used instead of Array#slice to ensure dense arrays are returned. * * - Start Index Condition - * smaller than 0: array.length + given index (negative number) * Bigger than array.length: array.length * Not Number: 0 * * - End Index Condition - * Same as Start Index Condition */ export const slice = ( array: any[], start: number = 0, end: number = Array.isArray(array) ? array.length : 0 ) => { if (!Array.isArray(array)) { return []; } const arrLeng = array.length; const sliceStartIdx = indexCondition(start, arrLeng); const sliceEndIdx = indexCondition(end, arrLeng); const arrFinalLeng = sliceEndIdx - sliceStartIdx; const newArr = new Array(arrFinalLeng < 0 ? 0 : arrFinalLeng); let startFromZeroIndex = 0; for (let idx = sliceStartIdx; idx < sliceEndIdx; idx++) { newArr[startFromZeroIndex++] = array[idx]; } return newArr; };
#!/bin/bash -e # Debugging. set -x # Environment. export SHELL=/bin/bash # Fix https://github.com/aiidalab/aiidalab-docker-stack/issues/225 if [ -L /home/${SYSTEM_USER}/${SYSTEM_USER} ]; then rm /home/${SYSTEM_USER}/${SYSTEM_USER} fi # Setup AiiDA jupyter extension. # Don't forget to copy this file to .ipython/profile_default/startup/ # aiida/tools/ipython/aiida_magic_register.py if [ ! -e /home/${SYSTEM_USER}/.ipython/profile_default/startup/aiida_magic_register.py ]; then mkdir -p /home/${SYSTEM_USER}/.ipython/profile_default/startup/ cat << EOF > /home/${SYSTEM_USER}/.ipython/profile_default/startup/aiida_magic_register.py if __name__ == "__main__": try: import aiida del aiida except ImportError: pass else: import IPython # pylint: disable=ungrouped-imports from aiida.tools.ipython.ipython_magics import load_ipython_extension # Get the current Ipython session IPYSESSION = IPython.get_ipython() # Register the line magic load_ipython_extension(IPYSESSION) EOF fi # Create apps folder and make its subfolders importable from Python. if [ ! -e /home/${SYSTEM_USER}/apps ]; then # Create apps folder and make it importable from python. mkdir -p /home/${SYSTEM_USER}/apps INITIAL_SETUP=1 fi # Install the home app. if [ ! -e /home/${SYSTEM_USER}/apps/home ]; then echo "Install home app." # The home app is installed in system space and linked to from user space. # That ensures that users are not inadvertently running the wrong version of # the home app for a given system environment, but still makes it possible to # manually install a specific version of the home app in between upgrades, e.g., # for development work, by simply replacing the link with a clone of the repository. ln -s /opt/aiidalab-home /home/${SYSTEM_USER}/apps/home elif [[ -d /home/${SYSTEM_USER}/apps/home && ! -L /home/${SYSTEM_USER}/apps/home ]]; then # Backup an existing repository of the home app and replace with link to /opt/aiidalab-home. # This mechanism preserves potential development work on a manually installed repository # of the home app and also constitutes a migration path for existing aiidalab accounts, where # the home app was installed directly into user space by default. mv /home/${SYSTEM_USER}/apps/home /home/${SYSTEM_USER}/apps/.home~`date --iso-8601=seconds` \ && ln -s /opt/aiidalab-home /home/${SYSTEM_USER}/apps/home || echo "WARNING: Unable to install home app." fi # Install default apps (see the Dockerfile for an explanation of the # AIIDALAB_DEFAULT_APPS variable). if [[ ${INITIAL_SETUP} == 1 ]]; then # Iterate over lines in AIIDALAB_DEFAULT_APPS variable. for app in ${AIIDALAB_DEFAULT_APPS:-}; do aiidalab install --yes "${app}" done fi # Update reentry. reentry scan # Clear user trash directory. if [ -e /home/${SYSTEM_USER}/.trash ]; then rm -rf /home/${SYSTEM_USER}/.trash/* fi # Remove old apps_meta.sqlite requests cache files. find -L /home/${SYSTEM_USER} -maxdepth 3 -name apps_meta.sqlite -writable -delete # Remove old temporary notebook files. find -L /home/${SYSTEM_USER}/apps -maxdepth 2 -type f -name .*.ipynb -writable -delete # Uninstall aiidalab from user packages (if present). # Would otherwise interfere with the system package. USER_AIIDALAB_PACKAGE="$(/opt/conda/bin/python -c 'import site; print(site.USER_SITE)')/aiidalab" if [ -e ${USER_AIIDALAB_PACKAGE} ]; then echo "Uninstall local installation of aiidalab package." /opt/conda/bin/python -m pip uninstall --yes aiidalab fi
package renetik.kotlin.collections inline val Collection<*>.length get() = size inline val Collection<*>.count get() = size inline val Collection<*>.hasItems get() = isNotEmpty() inline val Collection<*>.isEmpty get() = isEmpty() inline val Collection<*>.lastIndex get() = size - 1 fun <T> Collection<T>.hasAll(vararg elements: T): Boolean { for (element in elements) if (!contains(element)) return false return true } fun <T> Collection<T>.containsNot(element: T) = !contains(element) fun <T> Collection<T>.containsNot(vararg elements: T): Boolean { for (element in elements) if (!containsNot(element)) return false return true }
package org.s3s3l.yggdrasil.redis; import java.time.LocalDateTime; import org.s3s3l.yggdrasil.redis.base.IRedis; /** * <p> * </p> * ClassName:AutoSwithRedis <br> * Date: Mar 10, 2018 2:32:09 PM <br> * * @author kehw_zwei * @version 1.0.0 * @since JDK 1.8 */ public class AutoSwitchRedis { private LocalDateTime switchTime; private IRedis current; private IRedis next; public IRedis getCurrent() { return current; } public void setCurrent(IRedis current) { this.current = current; } public IRedis getNext() { return next; } public void setNext(IRedis next) { this.next = next; } public IRedis getResource() { return LocalDateTime.now() .isAfter(switchTime) ? next : current; } public LocalDateTime getSwitchTime() { return switchTime; } public void setSwitchTime(LocalDateTime switchTime) { this.switchTime = switchTime; } }
--- title: Error occurs when setting Dynamics CRM for Outlook description: This article provides a resolution to an error you may see when configuring the Microsoft Dynamics CRM Client for Microsoft Office Outlook. ms.reviewer: jowells, chanson ms.topic: troubleshooting ms.date: 3/31/2021 --- # Cannot authenticate your credentials error when configuring the Microsoft Dynamics CRM for Outlook client 2011 This article provides a resolution for the issue that you can't configure Microsoft Dynamics CRM for Microsoft Office Outlook using the Configuration Wizard due to the **Cannot connect to Microsoft Dynamics CRM server because we cannot authenticate your credentials** error. _Applies to:_ &nbsp; Microsoft CRM client for Microsoft Office Outlook, Microsoft Dynamics CRM 2011, Microsoft Business Solutions CRM Sales for Outlook _Original KB number:_ &nbsp; 2682528 ## Symptoms When trying to configure Microsoft Dynamics CRM for Outlook using the Configuration Wizard, you receive the following error: > Cannot connect to Microsoft Dynamics CRM server because we cannot authenticate your credentials. Check your connection or contact your administrator for more help. In the Microsoft Dynamics CRM Configuration log, (default location: C:\Users\\*\<username>*\AppData\Local\Microsoft\MSCRM\Logs\Crm50ClientConfig.log), you will see an error similar to the following: > Error| Error connecting to URL: `https://dev.crm.dynamics.com/XRMServices/2011/Discovery.svc` Exception: Microsoft.Crm.Passport.IdCrl.IdCrlException: InitializeEx() at Microsoft.Crm.Passport.IdCrl.FederationLogOnManager.Initialize(String environment) at Microsoft.Crm.Passport.IdCrl.FederationLogOnManager..ctor(String environment) at Microsoft.Crm.Outlook.ClientAuth.PassportAuthProvider\`1.GetLogonManager() at Microsoft.Crm.Outlook.ClientAuth.PassportAuthProvider\`1.SignIn() at Microsoft.Crm.Outlook.ClientAuth.ClientAuthProvidersFactory\`1.SignIn(Uri endPoint, Credential credentials, AuthUIMode uiMode, IClientOrganizationContext context, Form parentWindow, Boolean retryOnError) at Microsoft.Crm.Application.Outlook.Config.DeploymentsInfo.DeploymentInfo.LoadOrganizations(AuthUIMode uiMode, Form parentWindow, Credential credentials) at Microsoft.Crm.Application.Outlook.Config.DeploymentsInfo.InternalLoadOrganizations(OrganizationDetailCollection orgs, AuthUIMode uiMode, Form parentWindow) ## Cause Windows Live ID Sign-in Assistant service is not running. ## Resolution Start or restart the Windows Live ID Sign-In Assistant. 1. Select Windows button and within **Search programs and files** type *Services.msc*. 2. Locate Windows Live ID Sign-in Assistant and verify the Startup Type is set to Automatic. 3. If the Startup Type is not set to Automatic, do the following: 1. Double-click on Windows Live ID Sign-in Assistant. 2. Change Startup type to Automatic. 3. Select **Start**. 4. Select **OK**. 4. If the Startup Type is set to Automatic, verify the status is set to Started. If the status is not set to Started, then do the following: 1. Select the Windows Live ID Sign-in Assistant. 2. Right-click on it and go to **Start**. 5. If the Startup Type is set to Automatic and the status is set to Started, do the following: 1. Select the Windows Live ID Sign-in Assistant. 2. Right-click on it and go to Restart. If you experience any errors when trying to start the Windows Live ID Sign-in Assistant, try uninstalling and reinstalling the service: 1. Point to the **Start** menu, select **Control Panel**, and select **Programs and Features**. 2. Find and right-click Windows Live ID Sign-in Assistant. Select **uninstall**. 3. Reinstall Windows Live ID Sign-in Assistant.
class AddressPresenter < BasePresenter def full_name(format = :formal) if format == :formal [formal_name, first_name].compact.join(', ') elsif format == :pdf [title, first_name, name].compact.join(' ') else [first_name, name].compact.join(' ') end end def detail_line [address, mail_to, phone_numbers(separator: ' | ')].compact.join(' | ').html_safe end def notes_paragraph return if notes.blank? h.content_tag(:p, h.content_tag(:span, Address.human_attribute_name(:notes) + ': ', class: 'text-info' ) + notes ) end def formal_name [title, name].compact.join(' ') end def address [street_number, city_line, country_name].compact.join(', ') end def city_line [zip, city].join(' ') end def country_name return nil unless country_code country = ISO3166::Country[country_code] country.translations[I18n.locale.to_s] || country.name end def phone_numbers(separator: ' | ') return unless phone (phone || '').gsub("\r\n", separator).html_safe end def confirmation_label full_name(:informal) end def human_salutation return unless @model.is_a?(Person) I18n.t(salutation, scope: 'helpers.salutation') end end
+++ fragment = "item" #disabled = false date = "2017-10-04" weight = 330 background = "secondary" align = "center" title = "item" image = "resource_logo.svg" +++
package input_files import ( "fmt" "os" "path/filepath" ) type t struct { myString string } func myPrint() { println(T("isn't that grand")) } func Something() string { myPrint() // a trivial case someString := T("hello") var anotherString string = T("world") println(someString, anotherString) yetAnotherString := []string{T("tricky tests")} var moreStrings []string moreStrings = []string{T("are"), T("tricky")} println(yetAnotherString, moreStrings) mappyMap := map[string]string{T("hello"): T("world")} println(mappyMap) println(mappyMap[T("hello")]) myT := t{myString: T("my string")} println(myT.myString) trickyT := t{T("this is a tricky case")} println(trickyT.myString) concatenatedStrings := T("foo") + T(" ") + T("bar") println(concatenatedStrings) fmt.Printf(T("HAI")) if os.Getenv(T("SOMETHING")) != T("") { fmt.Printf(filepath.Clean(os.Getenv(T("SOMETHING")))) } fmt.Println(T("hello") + T("world")) return T("enqueuedequeueenqueuebananapants") }
export default (baseUrl, configData) => { return fetch(baseUrl + "/api/v1/upsertBotConfig", { method: "POST", body: configData, }).then(resp => { return resp.json(); }); };
--- layout: capture label: 20190606 station: TLP3 date: 2019-06-07 03:55:03 preview: TLP3/2019/201906/20190606/stack.jpg capturas: - imagem: TLP3/2019/201906/20190606/M20190607_035503_TLP_3P.jpg - imagem: TLP3/2019/201906/20190606/M20190607_045909_TLP_3P.jpg - imagem: TLP3/2019/201906/20190606/M20190607_075010_TLP_3P.jpg ---
import 'dart:async'; import 'package:bloc_pattern/bloc_pattern.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class LoginBloc extends BlocBase { CollectionReference colecao = Firestore.instance.collection("usuarios"); String status = ""; final StreamController _streamController = StreamController(); Sink get entrada => _streamController.sink; Stream get saida => _streamController.stream; void verificaUsuario(String usuario) async { if (await verifica(usuario) == true) { status = "Localizado"; } else { status = "Não localizado"; } entrada.add(status); } Future<bool> verifica(String usuario) async { final QuerySnapshot res = await colecao.where("CPF", isEqualTo: usuario).getDocuments(); final List<DocumentSnapshot> docs = res.documents; print(docs); if (docs.length == 0) { return false; } else { return true; } } @override void dispose() { _streamController.close(); super.dispose(); } }
package xyz.luan.audioplayers.source import android.media.MediaPlayer import xyz.luan.audioplayers.player.SoundPoolPlayer import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.net.URI import java.net.URL data class UrlSource( val url: String, val isLocal: Boolean, ): Source { override fun setForMediaPlayer(mediaPlayer: MediaPlayer) { mediaPlayer.setDataSource(url) } override fun setForSoundPool(soundPoolPlayer: SoundPoolPlayer) { soundPoolPlayer.setUrlSource(this) } fun getAudioPathForSoundPool(): String? { if (isLocal) { return url.removePrefix("file://") } return loadTempFileFromNetwork().absolutePath } private fun loadTempFileFromNetwork(): File { val bytes = downloadUrl(URI.create(url).toURL()) val tempFile = File.createTempFile("sound", "") FileOutputStream(tempFile).use { it.write(bytes) tempFile.deleteOnExit() } return tempFile } private fun downloadUrl(url: URL): ByteArray { val outputStream = ByteArrayOutputStream() url.openStream().use { stream -> val chunk = ByteArray(4096) while (true) { val bytesRead = stream.read(chunk).takeIf { it > 0 } ?: break outputStream.write(chunk, 0, bytesRead) } } return outputStream.toByteArray() } }
class MovieCastModel { final int id; final int castId; final String character; final String name; final String profilePath; MovieCastModel({ this.id, this.castId, this.character, this.name, this.profilePath, }); }
import fs = require('fs'); import os = require('os'); import path = require('path'); import ts = require('typescript'); var FILENAME_TS = 'file.ts'; function tss(code: string, options?: ts.CompilerOptions): string { if (options) { return new tss.TypeScriptSimple(options).compile(code); } else { return defaultTss.compile(code); } } namespace tss { export class TypeScriptSimple { private service: ts.LanguageService = null; private outputs: ts.Map<string> = {}; private options: ts.CompilerOptions; private files: ts.Map<{ version: number; text: string; }> = {}; /** * @param {ts.CompilerOptions=} options TypeScript compile options (some options are ignored) * @param {boolean=} doSemanticChecks Throw if TypeScript semantic error found (default: true) * @constructor */ constructor(options: ts.CompilerOptions = {}, private doSemanticChecks = true) { if (options.target == null) { options.target = ts.ScriptTarget.ES5; } if (options.module == null) { options.module = ts.ModuleKind.None; } this.options = options; } /** * @param {string} code TypeScript source code to compile * @param {string=} fileName Only needed if you plan to use sourceMaps. * Provide the complete filePath relevant to you * @return {string} The JavaScript with inline sourceMaps if sourceMaps were enabled * @throw {Error} A syntactic error or a semantic error (if doSemanticChecks is true) */ compile(code: string, fileName = FILENAME_TS): string { if (!this.service) { this.service = this.createService(); } var file = this.files[FILENAME_TS]; file.text = code; file.version++; return this.toJavaScript(this.service, fileName); } private createService(): ts.LanguageService { var defaultLib = this.getDefaultLibFileName(this.options); var defaultLibPath = path.join(this.getTypeScriptBinDir(), defaultLib); this.files[defaultLib] = { version: 0, text: fs.readFileSync(defaultLibPath).toString() }; this.files[FILENAME_TS] = { version: 0, text: '' }; var serviceHost: ts.LanguageServiceHost = { getScriptFileNames: () => [this.getDefaultLibFileName(this.options), FILENAME_TS], getScriptVersion: (fileName) => this.files[fileName] && this.files[fileName].version.toString(), getScriptSnapshot: (fileName) => { var file = this.files[fileName]; if (file) { return { getText: (start, end) => file.text.substring(start, end), getLength: () => file.text.length, getLineStartPositions: (): number[]=> [], getChangeRange: (oldSnapshot) => undefined }; } else { // This is some reference import return { getText: (start, end) => '', getLength: () => 0, getLineStartPositions: (): number[]=> [], getChangeRange: (oldSnapshot) => undefined }; } }, getCurrentDirectory: () => process.cwd(), getCompilationSettings: () => this.options, getDefaultLibFileName: (options: ts.CompilerOptions) => { return this.getDefaultLibFileName(options); }, // TODO: Use options.newLine getNewLine: () => os.EOL, log: (message: string) => console.log(message), trace: (message: string) => console.debug(message), error: (message: string) => console.error(message) }; return ts.createLanguageService(serviceHost, ts.createDocumentRegistry()) } private getTypeScriptBinDir(): string { return path.dirname(require.resolve('typescript')); } private getDefaultLibFileName(options: ts.CompilerOptions): string { if (options.target === ts.ScriptTarget.ES6) { return 'lib.es6.d.ts'; } else { return 'lib.d.ts'; } } /** * converts {"version":3,"file":"file.js","sourceRoot":"","sources":["file.ts"],"names":[], * "mappings":"AAAA,IAAI,CAAC,GAAG,MAAM,CAAC"} * to {"version":3,"sources":["foo/test.ts"],"names":[], * "mappings":"AAAA,IAAI,CAAC,GAAG,MAAM,CAAC","file":"foo/test.ts","sourcesContent":["var x = 'test';"]} * derived from : https://github.com/thlorenz/convert-source-map */ private getInlineSourceMap(mapText: string, fileName: string): string { var sourceMap = JSON.parse(mapText); sourceMap.file = fileName; sourceMap.sources = [fileName]; sourceMap.sourcesContent = [this.files[FILENAME_TS].text]; delete sourceMap.sourceRoot; return JSON.stringify(sourceMap); } private toJavaScript(service: ts.LanguageService, fileName = FILENAME_TS): string { var output = service.getEmitOutput(FILENAME_TS); var allDiagnostics = service.getCompilerOptionsDiagnostics() .concat(service.getSyntacticDiagnostics(FILENAME_TS)); if (this.doSemanticChecks) { allDiagnostics = allDiagnostics.concat(service.getSemanticDiagnostics(FILENAME_TS)); } if (allDiagnostics.length) { throw new Error(this.formatDiagnostics(allDiagnostics)); } var outputFileName = FILENAME_TS.replace(/ts$/, 'js'); var file = output.outputFiles.filter((file) => file.name === outputFileName)[0]; var text = file.text; // If we have sourceMaps convert them to inline sourceMaps if (this.options.sourceMap) { var sourceMapFileName = FILENAME_TS.replace(/ts$/, 'js.map'); var sourceMapFile = output.outputFiles.filter((file) => file.name === sourceMapFileName)[0]; // Transform sourcemap var sourceMapText = sourceMapFile.text; sourceMapText = this.getInlineSourceMap(sourceMapText, fileName); var base64SourceMapText = new Buffer(sourceMapText).toString('base64'); var sourceMapComment = '//# sourceMappingURL=data:application/json;base64,' + base64SourceMapText; text = text.replace('//# sourceMappingURL=' + sourceMapFileName, sourceMapComment); } return text; } private formatDiagnostics(diagnostics: ts.Diagnostic[]): string { return diagnostics.map((d) => { if (d.file) { return 'L' + d.file.getLineAndCharacterOfPosition(d.start).line + ': ' + d.messageText; } else { return d.messageText; } }).join(os.EOL); } } } var defaultTss = new tss.TypeScriptSimple(); export = tss;
#To be inserted at 800238d4 ########################################### ##FPSHack_14_ActorEventMoveApproval_LowHz## ########################################### lis r17, 0x817F lwz r17, 0x0000 (r17) #Load LowHzUpdate ##### cmpwi r17, 0 bne- 0x0008 ##### li r3, 0 ##### cmpwi r3, 2 #Vanilla
<?php /** * @author Thomas Müller <thomas.mueller@tmit.eu> * * @copyright Copyright (c) 2018, ownCloud GmbH * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\DAV\JobStatus; use OCA\DAV\JobStatus\Entity\JobStatus as JobStatusEntity; use OCA\DAV\JobStatus\Entity\JobStatusMapper; use Sabre\DAV\File; class JobStatus extends File { /** @var string */ private $jobId; /** @var string */ private $userId; /** @var string */ private $data; /** @var JobStatusMapper */ private $mapper; /** @var JobStatusEntity */ private $entity; public function __construct($userId, $jobId, JobStatusMapper $mapper, JobStatusEntity $entity) { $this->userId = $userId; $this->jobId = $jobId; $this->mapper = $mapper; $this->entity = $entity; } /** * Returns the name of the node. * * This is used to generate the url. * * @return string */ public function getName() { return $this->jobId; } public function get() { if ($this->entity === null) { $this->entity = $this->mapper ->findByUserIdAndJobId($this->userId, $this->jobId); } return $this->entity->getStatusInfo(); } public function getETag() { return '"' . \sha1($this->get()) . '"'; } public function getSize() { return \strlen($this->get()); } public function refreshStatus() { $this->entity = null; } }
<?php namespace Victorem\Entities; use Illuminate\Database\Eloquent\Model; class Answer extends Model { public $timestamp = true; public $fillable = ['text', 'question_id']; }
TODO: - Extend to fit random effects on turn angle and transistion probability - Extend to fit covariates - Consider estimating mean turn angle...may be useful for quantifying effects of sound on heading
package me.rainstorm.jvm; public final class ClassFileParseTest implements Interface1, Interface2 { @Anno public static final boolean FLAG = true; public static final byte BYTE = 123; public static final char X = 'X'; public static final short SHORT = 12345; public static final int INT = 123456; public static final long LONG = 12345654321L; public static final float FLOAT = 3.14f; public static final double DOUBLE = 2.71828; public static void main(String[] args) throws RuntimeException { System.out.println("Hello world!"); ClassFileParseTest test = new ClassFileParseTest(); ((Interface1)test).sayHi(); ((Interface2)test).saySomething(); } }
import {Filter} from "./filter" import * as p from "core/properties" import {Indices} from "core/types" import {ColumnarDataSource} from "../sources/columnar_data_source" export namespace InversionFilter { export type Attrs = p.AttrsOf<Props> export type Props = Filter.Props & { operand: p.Property<Filter> } } export interface InversionFilter extends InversionFilter.Attrs {} export class InversionFilter extends Filter { override properties: InversionFilter.Props constructor(attrs?: Partial<InversionFilter.Attrs>) { super(attrs) } static { this.define<InversionFilter.Props>(({Ref}) => ({ operand: [ Ref(Filter) ], })) } compute_indices(source: ColumnarDataSource): Indices { const index = this.operand.compute_indices(source) index.invert() return index } }
<?php declare(strict_types=1); namespace Falgun\Application\Tests; use Falgun\Routing\Router; use Falgun\Fountain\Fountain; use Falgun\Application\Config; use PHPUnit\Framework\TestCase; use Falgun\Reporter\ProdReporter; use Falgun\Application\Application; final class ApplicationTest extends TestCase { public function testApplication() { $predefined = ['ROOT_DIR' => __DIR__]; $config = Config::fromFileDir(__DIR__ . '/Stubs/Config', $predefined); $container = new Fountain(); $middlewareGroups = []; $reporter = new ProdReporter(); $request = RequestBuilder::build(); $router = new Router($request->uri()->getFullDocumentRootUrl()); $router->any('/')->closure(function() { echo 'Hello World'; }); $application = new Application($config, $container, $router, $middlewareGroups, $reporter); $this->expectOutputString('Hello World'); $application->run($request); } public function testApplicationWithMiddleware() { $predefined = ['ROOT_DIR' => __DIR__]; $config = Config::fromFileDir(__DIR__ . '/Stubs/Config', $predefined); $container = new Fountain(); $middlewareGroups = []; $reporter = new ProdReporter(); $request = RequestBuilder::build(); $router = new Router($request->uri()->getFullDocumentRootUrl()); $router->any('/') ->closure(function() { echo 'Hello World With Middlewares'; }) ->middleware([Stubs\Middlewares\FakeMiddleware::class]); $application = new Application($config, $container, $router, $middlewareGroups, $reporter); $this->expectOutputString('Hello World With Middlewares'); $application->run($request); $this->assertSame(1, $request->attributes()->get('layers')); $this->assertSame(['FakeMiddleware'], $request->attributes()->get('middlewares')); } }
using System; namespace src.Api.domain.Entity { public class Character : Entity { public String firstname { get; set; } public String lastname { get; set; } public String grade { get; set; } public long experience { get; set; } public Status status { get; set; } public Skill skills { get; set; } public Equipaments equipaments { get; set; } public Potion potions { get; set; } public float defence { get; set; } public float attack { get; set; } public float power { get; set; } public float stamina { get; set; } } }