text
stringlengths
27
775k
#nullable enable using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace DocumentStores { /// <InheritDoc/> public readonly struct DocumentRoute : IEquatable<DocumentRoute> { private readonly ImmutableArray<string> segments; /// <summary> /// The segments of the route. /// </summary> public IEnumerable<string> Segments => segments; private DocumentRoute(IEnumerable<string> segments) => this.segments = (segments ?? throw new ArgumentNullException(nameof(segments))) .ToImmutableArray(); /// <InheritDoc/> public static DocumentRoute Default => Create(Enumerable.Empty<string>()); /// <InheritDoc/> public static DocumentRoute Create(IEnumerable<string> segments) => new DocumentRoute(segments); /// <InheritDoc/> public static DocumentRoute Create(params string[] segments) => new DocumentRoute(segments); /// <InheritDoc/> public DocumentRoute Prepend(DocumentRoute route) => new DocumentRoute(route.segments.Concat(this.segments)); /// <InheritDoc/> public DocumentRoute Append(DocumentRoute route) => new DocumentRoute(this.segments.Concat(route.segments)); /// <InheritDoc/> public DocumentRoute TrimLeft(DocumentRoute route) => StartsWith(route) switch { true => Create(segments.Skip(route.Segments.Count())), false => this }; internal DocumentRoute MapSegments(Func<string, string> mapper) => new DocumentRoute(this.segments.Select(mapper)); /// <InheritDoc/> public bool StartsWith(DocumentRoute route) { var segments = this.segments; var otherSegments = route.Segments; return (otherSegments.Count(), segments.Length) switch { (0, _) => true, (var x, var y) when x > y => false, _ => segments .Zip(otherSegments, (x,y) => (x, y)) .All(z => EqualityComparer<string>.Default.Equals(z.x, z.y)) }; } #region "Override" /// <inheritdoc/> public bool Equals(DocumentRoute other) => Enumerable.SequenceEqual(segments, other.segments); /// <inheritdoc/> public override bool Equals(object? obj) => obj is DocumentRoute name && Enumerable.SequenceEqual(segments, name.segments); private int GetSegmentsHash() { if (!segments.Any()) return 0; return segments .Select(s => s.GetHashCode()) .Aggregate((x, y) => x ^ y); } /// <inheritdoc/> public override int GetHashCode() => -312155673 + GetSegmentsHash(); /// <inheritdoc/> public override string ToString() => $"[{String.Join(", ", segments.ToArray())}]"; #endregion #region Operators /// <inheritdoc /> public static bool operator ==(DocumentRoute left, DocumentRoute right) { return left.Equals(right); } /// <inheritdoc /> public static bool operator !=(DocumentRoute left, DocumentRoute right) { return !(left == right); } #endregion } }
package creational_patterns.singleton class ChiefExecutiveOfficer { companion object { private var name: String = "" private var age: Int = 0 } fun getName(): String { return name } fun setName(name: String) { ChiefExecutiveOfficer.name = name } fun getAge(): Int { return age } fun setAge(age: Int) { ChiefExecutiveOfficer.age = age } override fun toString(): String { return "ChiefExecutiveOfficer(name='$name', age=$age)" } } fun main() { val ceo = ChiefExecutiveOfficer() ceo.setName("Adam Smith") ceo.setAge(55) val ceo2 = ChiefExecutiveOfficer() println(ceo2) }
--- title: Q3-6 マイナンバーカードに旧姓併記がある場合、アプリで接種証明書は発行できますか。 question_no: Q3-6 draft: false weight: 306 categories: 03_このような場合は発行できますか lastmod: 2021-12-20 --- {{< vaccinefaq>}} 近日中に対応予定です。 現時点では、マイナンバーカードに旧姓併記がある場合は接種証明書の発行はできません。「マイナンバーカードに旧姓併記がある」とは、次を指します。 ・氏名欄に「田中[佐藤] 花子」などと括弧書きで旧姓が記載されている。 ・券面右下の追記欄に「旧氏 佐藤」や「旧氏記載 田中[佐藤] 花子」などと記載されている。 (参考)旧姓(旧氏)併記に関するリーフレット:総務省ホームページ (https://www.soumu.go.jp/main_content/000625549.pdf) これらの場合以外は、旧姓併記にあたらないので、アプリで発行可能です。 なお、市区町村窓口等で発行する紙の接種証明書については、マイナンバーカードに旧姓併記がある場合も発行可能です。申請方法は各市区町村へお問い合わせください。 {{</ vaccinefaq>}}
class Rules::ImportsController < ApplicationController before_action :authorize, :not_guest, :not_security before_action :set_title, only: [:new] def new end def create file = params[:file] if file.present? Rule.import file.tempfile.path redirect_to rules_url, notice: t('.imported') else redirect_to rules_imports_new_url, alert: t('.no_file') end rescue => ex logger.error ex redirect_to rules_url, alert: t('.fail') end end
class Stlsplit < Formula homepage "https://github.com/stlsplit/stlsplit" url "https://github.com/hroncok/stlsplit/archive/v1.1.tar.gz" sha256 "0ff8a206845e911302e26b7916fa5fac175cbc752bb29c683ad59ecbd69eae52" depends_on "premake" => :build depends_on "admesh" def install system "premake4", "gmake" system "make" # there is no make install bin.install "build/stlsplit" lib.install "build/libstlsplit.dylib" lib.install "build/libstlsplit.1.dylib" include.install "stlsplit.h" end test do # Test file is a simple cube (testpath/"test.stl").write <<-EOS.undent solid admesh facet normal -0 0 1 outer loop vertex 0 1 1 vertex 1 0 1 vertex 1 1 1 endloop endfacet facet normal 0 0 1 outer loop vertex 1 0 1 vertex 0 1 1 vertex 0 0 1 endloop endfacet facet normal 0 0 -1 outer loop vertex 0 0 0 vertex 1 1 0 vertex 1 0 0 endloop endfacet facet normal -0 0 -1 outer loop vertex 1 1 0 vertex 0 0 0 vertex 0 1 0 endloop endfacet facet normal 0 -1 0 outer loop vertex 0 0 0 vertex 1 0 1 vertex 0 0 1 endloop endfacet facet normal 0 -1 -0 outer loop vertex 1 0 1 vertex 0 0 0 vertex 1 0 0 endloop endfacet facet normal 1 -0 0 outer loop vertex 1 0 1 vertex 1 1 0 vertex 1 1 1 endloop endfacet facet normal 1 0 0 outer loop vertex 1 1 0 vertex 1 0 1 vertex 1 0 0 endloop endfacet facet normal 0 1 -0 outer loop vertex 1 1 0 vertex 0 1 1 vertex 1 1 1 endloop endfacet facet normal 0 1 0 outer loop vertex 0 1 1 vertex 1 1 0 vertex 0 1 0 endloop endfacet facet normal -1 0 0 outer loop vertex 0 0 0 vertex 0 1 1 vertex 0 1 0 endloop endfacet facet normal -1 -0 0 outer loop vertex 0 1 1 vertex 0 0 0 vertex 0 0 1 endloop endfacet endsolid admesh EOS system bin/"stlsplit", "test.stl" end end
Set-StrictMode -Version Latest function Get-VideosFromGame { param( [Parameter(Mandatory = $true)] [string]$GameUrl ) if ($GameUrl -notmatch '^https?:\/\/www\.giantbomb\.com\/([a-z0-9-]+)\/3030-([0-9]+)\/$') { return $false } <# else { Write-Host "Game ID # '$($Matches[2])' ('$($Matches[1])') found." } #> Write-Host "Getting videos from game '$($Matches[1])'..." -NoNewline $GameApiUrl = "$(Convert-UrlForApi $Matches[0])?api_key=$ApiKey&format=json&field_list=videos" $GameResponse = ((Invoke-WebRequest -Uri "$GameApiUrl").Content | ConvertFrom-Json) Start-Sleep -Milliseconds 1000 $Return = @() foreach ($GameVideo in $GameResponse.results.videos) { $Return += $GameVideo.site_detail_url } Write-Host " Found $($Return.Count) video(s) for '$($Matches[1])'." return $Return }
symbol_size_data <- function(a,symsize=0.2,colour=4) { if(dim(a)[1]>0) { a <- aggregate(a$setwt,list(a$centlat,a$centlong),sum) # a <- a[a$x>0,] symbols(a[,2],a[,1],circles=sqrt(a[,3]),add=T,inches=symsize,bg=colour) } } clean_logbook_data <- function(dat) { dat <- dat[,c("trip_id","set_id","flag_id","logdate","lat_long","lon_long","ez_id", "in_arch","spc","sch_id","days_sch","set_start","set_end","skj_c","yft_c","bet_c", "skj_w","yft_w","bet_w","yft_c_adj","bet_c_adj")] return(dat) } prepare_logbook_data <- function(dat) { dat$latd <- as.numeric(substring(dat$lat, 1, 4))/100 dat$latd <- floor(dat$latd) + (dat$latd-floor(dat$latd))/0.6 dat$latd <- ifelse(substring(dat$lat, 5, 5) == "S", -1 * dat$latd, dat$latd) dat <- dat[dat$latd <= 0,] dat$lond <- as.numeric(substring(dat$lon, 1, 5))/100 dat$lond <- floor(dat$lond) + (dat$lond-floor(dat$lond))/0.6 dat$lond <- ifelse(substring(dat$lon, 6, 6) == "W", 360-dat$lond, dat$lond) dat <- dat[dat$lond>=140 & dat$lond<250,] dat$lat5 <- 5*floor((dat$latd+5)/5)-5 dat$lon5 <- 5*floor(dat$lond/5) dat$latlong <- as.factor(paste(dat$lat5,dat$lon5)) dat$centlat <- dat$lat5 + 2.5 dat$centlong <- dat$lon5 + 2.5 dat <- dat[dat$centlat > -50,] dat <- dat[dat$centlat < 50,] dat <- dat[dat$centlong > 100,] dat <- dat[dat$centlong < 310,] dat$reg <- rep(0, length(dat$centlat)) dat$reg <- ifelse(dat$centlat >= -25 & dat$centlat < 0 & dat$centlong >= 140 & dat$centlong < 180, 1, dat$reg) dat$reg <- ifelse(dat$centlat >= -25 & dat$centlat < 0 & dat$centlong >= 180 & dat$centlong < 250, 2, dat$reg) dat$reg <- ifelse(dat$centlat >= -40 & dat$centlat < -25 & dat$centlong >= 140 & dat$centlong < 180, 3, dat$reg) dat$reg <- ifelse(dat$centlat >= -40 & dat$centlat < -25 & dat$centlong >= 180 & dat$centlong < 250, 4, dat$reg) dat$reg <- ifelse(dat$centlat >= -25 & dat$centlat < 0 & dat$centlong >= 250 & dat$centlong < 330, 5, dat$reg) dat$reg <- ifelse(dat$centlat >= -40 & dat$centlat < -25 & dat$centlong >= 250 & dat$centlong < 330, 6, dat$reg) dat <- dat[dat$reg %in% 1:4,] return(dat) } prepare_logbook_data_2 <- function(a) { a$trip_date <- as.Date(a$trip_date,format="%d/%m/%Y") a$trip_yr <- as.numeric(format(a$trip_date,"%Y")) a$trip_mon <- as.numeric(format(a$trip_date,"%m")) a$set_date <- as.Date(a$logdate,format="%d/%m/%Y") a$set_yr <- as.numeric(format(a$set_date,"%Y")) a$set_mon <- as.numeric(format(a$set_date,"%m")) a$set_qtr <- floor((a$set_mon+2)/3) a$set_yrqtr <- a$set_yr + a$set_qtr/4 - 0.125 return(a) } spatial_overlap_index <- function(samp,catch){ latlevs <- seq(-12.5,12.5,5);lonlevs <- seq(127.5,207.5,5); t1 <- with(samp,tapply(setwt,list(factor(centlat,levels=latlevs),factor(centlong,levels=lonlevs)),sum)) t2 <- with(catch,tapply(setwt,list(factor(centlat,levels=latlevs),factor(centlong,levels=lonlevs)),sum)) t1[is.na(t1)] <- 0 t2[is.na(t2)] <- 0 r1 <- t1 / sum(t1) r2 <- t2 / sum(t2) d1 <- sum(abs(r1-r2)) d2 <- sum(log(((r1[r2>0]-r2[r2>0])^2)/r2[r2>0])) d3 <- (sum(t2)/sum(t1))/(sum(t2[t1>0]/(t1[t1>0]))/sum(t1>0)) return(data.frame(absdiff=d1,propLik=d2,Gulland=d3)) } symbol_catch_data <- function(a,symsize=0.2,colour=4) { if(dim(a)[1]>0) { a <- aggregate(a$setwt,list(a$centlat,a$centlong),sum) symbols(a[,2],a[,1],circles=sqrt(a[,3]),add=T,inches=symsize,bg=colour) } }
package io.stud.forest.springsamples.todo_rest_client.data_source import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.functions.Consumer import io.stud.forest.springsamples.todo_rest_client.Printer import io.stud.forest.springsamples.todo_rest_client.model.User import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class UsersService @Autowired constructor( private val api: UsersApi ) { companion object { private val log = LoggerFactory.getLogger(Printer::class.java) } fun users(): Single<List<User>> { return api .users() .flatMapIterable { it } .flatMap { user -> api .tasksByUser(user.id) .flatMap { user.tasks = it; Observable.just(user) } }.toList() } }
package me.hufman.androidautoidrive.phoneui import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.GridView class NestedGridView(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0): GridView(context, attrs, defStyleAttr) { constructor(context: Context): this(context, null, 0) constructor(context: Context, attrs: AttributeSet? = null): this(context, attrs, 0) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(View.MEASURED_SIZE_MASK, MeasureSpec.AT_MOST)) layoutParams.height = measuredHeight } }
// Copied with some modifications from: https://github.com/harc/ohm/blob/master/examples/ecmascript/es5.js /* eslint-env node */ "use strict" // -------------------------------------------------------------------- // Imports // -------------------------------------------------------------------- var fs = require("fs") var path = require("path") var ohm = require("ohm-js") // -------------------------------------------------------------------- // Helpers // -------------------------------------------------------------------- // Take an Array of nodes, and whenever an _iter node is encountered, splice in its // recursively-flattened children instead. function flattenIterNodes(nodes) { var result = [] for (var i = 0; i < nodes.length; ++i) { if (nodes[i]._node.ctorName === "_iter") { result.push.apply(result, flattenIterNodes(nodes[i].children)) } else { result.push(nodes[i]) } } return result } // Comparison function for sorting nodes based on their interval's start index. function compareByInterval(node, otherNode) { return node.source.startIdx - otherNode.source.startIdx } function nodeToES5(node, children) { var flatChildren = flattenIterNodes(children).sort(compareByInterval) // Keeps track of where the previous sibling ended, so that we can re-insert discarded // whitespace into the final output. var prevEndIdx = node.source.startIdx var code = "" for (var i = 0; i < flatChildren.length; ++i) { var child = flatChildren[i] // Restore any discarded whitespace between this node and the previous one. if (child.source.startIdx > prevEndIdx) { code += node.source.sourceString.slice( prevEndIdx, child.source.startIdx ) } code += child.toES5() prevEndIdx = child.source.endIdx } return code } // Instantiate the ES5 grammar. var contents = fs.readFileSync(path.join(__dirname, "es5.ohm")) var g = ohm.grammars(contents).ES5 module.exports = { grammar: g }
package org.odk.collect.android.formmanagement import android.app.Activity import android.content.Intent import org.odk.collect.android.activities.FormEntryActivity import org.odk.collect.android.external.FormsContract import org.odk.collect.android.external.InstancesContract import org.odk.collect.android.utilities.ApplicationConstants.BundleKeys.FORM_MODE import org.odk.collect.android.utilities.ApplicationConstants.FormModes.VIEW_SENT import org.odk.collect.forms.instances.Instance import org.odk.collect.forms.instances.InstancesRepository import org.odk.collect.settings.SettingsProvider import org.odk.collect.settings.keys.ProtectedProjectKeys.KEY_EDIT_SAVED class FormNavigator( private val projectId: String, private val settingsProvider: SettingsProvider, private val instancesRepositoryProvider: () -> InstancesRepository ) { fun editInstance(activity: Activity, instanceId: Long) { val uri = InstancesContract.getUri(projectId, instanceId) activity.startActivity( Intent(activity, FormEntryActivity::class.java).also { it.action = Intent.ACTION_EDIT it.data = uri val editingDisabled = !settingsProvider.getProtectedSettings().getBoolean(KEY_EDIT_SAVED) val status = instancesRepositoryProvider().get(instanceId)?.status if (editingDisabled || status == Instance.STATUS_SUBMITTED || status == Instance.STATUS_SUBMISSION_FAILED ) { it.putExtra(FORM_MODE, VIEW_SENT) } } ) } fun newInstance(activity: Activity, formId: Long) { activity.startActivity( Intent(activity, FormEntryActivity::class.java).also { it.action = Intent.ACTION_EDIT it.data = FormsContract.getUri(projectId, formId) } ) } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Course; use App\Student; class CourseController extends Controller { /** * Retrieve the course for the given ID. * * @param int $id * @return Response */ public function show($id) { $course = Course::find($id); return response($course, ($course!=null) ? 200:404) ->header('Content-Type', 'application/json'); } /** * Display a listing of courses. * * @return Response */ public function index() { return Course::all(); } /** * Display a listing of courses paginated. * * @return Response */ public function indexPaginated(Request $request){ $size = $request->input('size', 10); $page = $request->input('page',1); return Course::paginate($size,['*'],'page',$page); } /** * Store a newly created course in storage. * * @return Response */ public function store(Request $request) { $data = Course::create($request->all()); return response(["msg"=>"created"],201); } /** * Update the specified course in storage. * * @param int $id * @return Response */ public function update(Request $request, $id) { $course = Course::find($id); if($course==null) return response(["msg"=>"not found"],404); else $course->update($request->all()); return response(["msg"=>"successfully updated"],200); } /** * Remove the specified course from storage. * * @param int $id * @return Response */ public function destroy($id) { $course = Course::find($id); if($course==null) return response(["msg"=>"not found"],404); $students = Student::where(["course"=>$id])->get(); if(count($students)>0) return response(["msg"=>"this course has students. Can't delete it"],400); $course->delete(); return response(["msg"=>"successfully deleted"],200); } }
using System; namespace CommonUtils.MathLib.Wavelets.Compress { /// Author: Linzhi Qi /// Converted from C++ by perivar@nerseth.com /// https://github.com/linzhi/wavelet-compress public static class VerificationResult { public static double MeanSquaredError(double[] file_in, double[] file_out, ref int file_size) { int i; double mse = 0; for (i = 0; i < file_size; i++) { mse += Math.Pow((file_in[i] - file_out[i]), 2.0); } mse = mse / file_size; return mse; } public static double PeakSignalToNoiseRatio(double mse) { double psnr = 0; psnr = 10.0 * Math.Log10((255.0 * 255.0) / mse); return psnr; } } }
#ifndef _F13_H #define _F13_H #include "Benchmarks.h" class F13:public Benchmarks{ protected: public: F13(); double compute(double* x) ; ~F13(); }; #endif
--- layout: post title: "采用cdn路径获取资源" description: "使用又拍云资源管理器,采用cdn路径获取资源" date: 2016-02-28 18:00:00 categories: share tags: [前端分享,王兆丹] comments: true --- #分享采用cdn的方式获取资源 >1.项目正式完成之后; >2.生成dist文件,将dist文件中的压缩过的除了html/php文件之外的资源上传到cdn中; 2.1 使用又拍云资源管理器,进入相应的空间,建立目录; 2.2 按照项目的目录格式建立云存储,将js/css等资源以压缩的形式存储; >3.修改gulp文件,将cdn的默认路径修改为在cdn建立的路径,执行cdn的任务,统一将路径修改; #3.1 默认配置中添加cdn(路径修改为资源存储的路径) {% highlight js %} var config = { ...... cdn: '//images.menma.me/website.hydq.menma.me/assets/' }; {% endhighlight %} #3.2 替换静态cdn,替换路径,只更改了php文件,其他的保持不变 {% highlight js %} gulp.task('cdn', function () { return gulp.src(config.distPath + [ '*.php' ]) .pipe(cdn({ domain: "assets/", cdn: config.cdn })) .pipe(gulp.dest(config.distPath + "/")) }); {% endhighlight %}
#!/usr/bin/perl use strict; use warnings; use Test::Most; plan qw/no_plan/; our @did; package My::Command; use Getopt::Chain::Declare; start [qw/ verbose|v /]; # These are "global" # my-command --verbose initialize ... # my-command ? initialize ... --> my-command help initialize ... rewrite qr/^\?(.*)/ => sub { "help ".($1||'') }; # NOTE: Rewriting applies to the command sequence, NOT options # my-command about ... --> my-command help about rewrite [ ['about', 'copying'] ] => sub { "help $1" }; # my-command initialize --dir=... on initialize => [qw/ dir|d=s /], sub { my $context = shift; my $dir = $context->option( 'dir' ); push @did, [ $context->command, dir => $dir ]; # Do initialize stuff with $dir }; # my-command help on help => undef, sub { my $context = shift; # Do help stuff ... # First argument is undef because help # doesn't take any options push @did, [ $context->command, ]; }; under help => sub { # my-command help create # my-command help initialize on [ [ qw/create initialize/ ] ] => undef, sub { my $context = shift; # Do help for create/initialize # Both: "help create" and "help initialize" go here push @did, [ $context->command, ]; }; # my-command help about on 'about' => undef, sub { my $context = shift; # Help for about... push @did, [ $context->command, ]; }; # my-command help copying on 'copying' => undef, sub { my $context = shift; # Help for copying... push @did, [ $context->command, ]; }; # my-command help ... on qr/^(\S+)$/ => undef, sub { my $context = shift; my $topic = $1; # Catch-all for anything not fitting into the above... push @did, [ $context->command, "I don't know about \"$topic\"\n" ] }; }; no Getopt::Chain::Declare; package main; my $options; sub run { undef @did; $options = My::Command->new->run( [ @_ ] ); } run qw/--verbose/; ok( $options->{verbose} ); ok( ! @did ); run qw/--verbose about/; ok( $options->{verbose} ); cmp_deeply( \@did, [ [ "about" ] ] ); run qw/help copying/; ok( ! $options->{verbose} ); cmp_deeply( \@did, [ [ "copying" ] ] ); run qw/initialize/; ok( ! $options->{verbose} ); cmp_deeply( \@did, [ [ "initialize", dir => undef ] ] ); run qw/initialize --dir ./; ok( ! $options->{verbose} ); cmp_deeply( \@did, [ [ "initialize", dir => '.' ] ] ); run qw/-v ? create/; ok( $options->{verbose} ); cmp_deeply( \@did, [ [ "create" ] ] ); run qw/? xyzzy/; cmp_deeply( \@did, [ [ "xyzzy", "I don't know about \"xyzzy\"\n" ] ] );
var currentUser = null; var userEmail = null; var userName = null; var currentUserProf = null; var currentLong = ''; var currentLat = ''; var currentAddress = ''; var config = { apiKey: "AIzaSyAl_ivk9jeCwqIPtiD0bbTBPrgiSQDa0R4", authDomain: "plan-it-project.firebaseapp.com", databaseURL: "https://plan-it-project.firebaseio.com", projectId: "plan-it-project", storageBucket: "plan-it-project.appspot.com", messagingSenderId: "250401634632" }; firebase.initializeApp(config); var database = firebase.database(); var uiConfig = { signInSuccessUrl: 'https://jstevens79.github.io/Project1/', signInOptions: [ firebase.auth.GoogleAuthProvider.PROVIDER_ID, firebase.auth.EmailAuthProvider.PROVIDER_ID, ], }; var ui = new firebaseui.auth.AuthUI(firebase.auth()); ui.start('#firebaseui-auth-container', uiConfig); firebase.auth().onAuthStateChanged(function (user) { if (user) { userName = user.displayName; userEmail = user.email; currentUser = user.uid; $('#login').hide(); $('#profile-name').text('Hello, ' + userName + '!'); $('#profile').show(); var userExists = false database.ref('users').once('value', function (snapshot) { snapshot.forEach(function (childSnaphot) { if (childSnaphot.val().userID === currentUser) { currentUserProf = childSnaphot.key; userExists = true; } }) }).then(function () { if (!userExists) { database.ref('users').push({ userID: currentUser, userName: userName, userEmail: userEmail }) } }).then(function () { init(); }) } else { $('#login').show(); $('#profile').hide(); $('#sign-out').hide(); $('#create-event').hide(); } }) function init() { // add user cards to event add area database.ref('users').on('child_added', function (snapshot) { if (snapshot.key !== currentUserProf) { var friendColumn = $('<div>').addClass('column'); var friend = $('<div>') .addClass('card') .addClass('friend') .attr('data-id', snapshot.key); var friendContent = $('<div>').addClass('card-content'); var friendName = $('<p>').addClass('has-text-weight-bold').text(snapshot.val().userName); friendContent.append(friendName); friend.append(friendContent); friendColumn.append(friend) $('#friends-container').append(friendColumn); } }) database.ref('events').on('child_removed', function (oldChildSnapshot) { $('#' + oldChildSnapshot.key).remove(); }); database.ref('events').on('child_changed', function (snapshot) { if (snapshot.val().eventMembers !== undefined) { var obj = snapshot.val().eventMembers; Object.keys(obj).forEach(function (key) { if (obj[key].member === currentUserProf) { renderEventsListItem(snapshot) }; }); } }); database.ref('events').on('child_added', function (snapshot) { if (snapshot.val().eventMembers !== undefined) { var obj = snapshot.val().eventMembers; Object.keys(obj).forEach(function (key) { if (obj[key].member === currentUserProf) { renderEventsListItem(snapshot) }; }); } }); } function renderEventsListItem(item) { var status = ''; var others = []; item.child('eventMembers').forEach(function (snapshot) { if (snapshot.val().member === currentUserProf) { status = snapshot.val().response; } else { others.push(snapshot.val()) } }) var userTagContainers = []; // get others... others.forEach(function(other){ database.ref('users/' + other.member).once('value', function(snap) { var userTagContainer = $('<div>').addClass('control').css({'margin': '0 10px 10px 0'}); var userTags = $('<div>').addClass('tags has-addons'); var nameTag = $('<span>').addClass('tag is-dark is-capitalized').text(snap.val().userName); var responseTag = $('<span>').addClass('tag is-capitalized').text(other.response); if (other.response === 'pending') { responseTag.addClass('is-warning'); } if (other.response === 'going') { responseTag.addClass('is-success'); } if (other.response === 'not going') { responseTag.addClass('is-danger'); } userTags.append(nameTag, responseTag); userTagContainer.append(userTags); userTagContainers.push(userTagContainer); }) }) function getDate(a) { //03/15/2019 var dateArray = a.split('/'); var month = '' switch (dateArray[0]) { case '01': month = 'January' break; case '02': month = 'February' break; case '03': month = 'March' break; case '04': month = 'April' break; case '05': month = 'May' break; case '06': month = 'June' break; case '07': month = 'July' break; case '08': month = 'August' break; case '09': month = 'September' break; case '10': month = 'October' break; case '11': month = 'Novemeber' break; case '12': month = 'December' break; } return [month, dateArray[1]] } var cardColumn = $('<div>').attr('id', item.key).addClass('column').addClass('is-half'); var card = $('<div>').addClass('message is-dark').addClass('eventsListItem'); var date = getDate(item.val().eventDate); var cardHeader = $('<header>').addClass('message-header'); var cardTitle = $('<p>').text(date[0] + ' ' + date[1]); cardHeader.append(cardTitle); var itemLoc = item.val().eventLocation; var cardContent = $('<div>').addClass('message-body'); var content = $('<div>').addClass('content'); var eventTitle = $('<h2>').addClass('title is-3').text(item.val().eventName); var locationName = $('<h4>').addClass('title is-marginless').text(item.val().eventLocation.name); var categories = item.val().eventLocation.categories.map(function(cat) { return cat.title }) var categoryText = (categories.length > 1) ? categories.join(', ') : categories[0]; var categoryP = $('<p>').text(categoryText); var locationAddress = $('<a>') .addClass('locationLink subtitle is-7') .attr('data-lat', itemLoc.coordinates.latitude) .attr('data-long', itemLoc.coordinates.longitude) .attr('data-address', itemLoc.location.display_address[0] + ', ' + itemLoc.location.display_address[1]) .text(itemLoc.location.display_address[0] + ', ' + itemLoc.location.display_address[1]); var description = $('<blockquote>').text(item.val().eventDescription).css('marginTop', '20px'); var friendsGoing = $('<h5>').addClass('title is-6 is-marginless').text("Friends' Status:"); var friendResponses = $('<div>').css({paddingTop: '10px'}).addClass('buttons').append(userTagContainers); content.append(eventTitle, locationName, categoryP, locationAddress, description, friendsGoing, friendResponses); cardContent.append(content); var responseButtonContainer = $('<div>').addClass('level-item buttons'); var responseGoing = $('<button>') .attr('data-id', item.key) .addClass('going') .addClass('button') .text('Going'); var responseNotGoing = $('<button>') .attr('data-id', item.key) .addClass('not-going') .addClass('button').text('Not Going'); if (status === 'pending') { var pendingTag = $('<span>').addClass('tag is-medium is-warning is-capitalized').text('Please respond'); cardHeader.append(pendingTag) } if (status === 'going') { responseGoing.addClass('is-success'); } if (status === 'not going') { responseNotGoing.addClass('is-danger'); } responseButtonContainer.append(responseGoing, responseNotGoing); var footer = $('<div>').addClass('level'); var footerLeft = $('<div>').addClass('level-left'); var footerRight = $('<div>').addClass('level-right'); var footerItem = $('<div>').addClass('level-item'); footerItem.append(responseButtonContainer); footerRight.append(footerItem); footer.append(footerLeft, footerRight).css({ padding: "10px", borderTop: 'solid 1px rgba(0,0,0,0.1)' }); card.append(cardHeader, cardContent, footer); cardColumn.append(card); if (!$('#' + item.key).length) { $('#user-events').append(cardColumn); } else { $('#' + item.key).empty().append(card); } } $(document).on('click', '.going', function(e) { e.preventDefault(); var dataID = $(this).data('id') database.ref('events/' + dataID + '/eventMembers').once('value', function(snapshot) { var obj = snapshot.val(); Object.keys(obj).forEach(function (myKey) { if (obj[myKey].member === currentUserProf) { database.ref('events/' + dataID + '/eventMembers/' + myKey).update({ response: 'going' }) }; }); }) }) $(document).on('click', '.not-going', function(e) { e.preventDefault(); var dataID = $(this).data('id') database.ref('events/' + dataID + '/eventMembers').once('value', function(snapshot) { var obj = snapshot.val(); Object.keys(obj).forEach(function (myKey) { if (obj[myKey].member === currentUserProf) { database.ref('events/' + dataID + '/eventMembers/' + myKey).update({ response: 'not going' }) }; }); }) }) $(document).on('click', '.friend', function () { $(this).toggleClass('selected'); $(this).toggleClass('has-background-primary has-text-white') }) $(document).on('click', '#start-event', function (e) { e.preventDefault() $('#profile').hide(); $('#create-event').show(); }) $(document).on('click', '#sign-out', function (e) { console.log('click') e.preventDefault(); firebase.auth().signOut(); }) $(document).on('click', '.locationLink', function(e) { e.preventDefault(); currentLat = $(this).data('lat'); currentLong = $(this).data('long'); currentAddress = $(this).data('address') initMap(); $('#map-modal').addClass('is-active') }) var dateSelected = ''; var timeSelected = ''; // create an event & add it to a user... $(document).on('click', '#add-event', function (e) { e.preventDefault(); var eventName = $('#event-name').val().trim(); var eventDate = dateSelected; var eventTime = timeSelected; var friends = []; var eventLocation = yelpResponse.businesses[selectedYelpResponse]; var eventDescription = $('#event-description').val().trim(); $('.friend.selected').each(function () { friends.push($(this).data('id')); }); var newEvent = database.ref('/events').push(); newEvent.set({ eventOwner: currentUserProf, eventName: eventName, eventDate: eventDate, eventTime: eventTime, eventDescription: eventDescription, eventLocation: eventLocation }).then(function () { newEvent.child('eventMembers').push({ member: currentUserProf, response: 'going' }) friends.forEach(function (friend) { newEvent.child('eventMembers').push({ member: friend, response: 'pending' }) }) $('#event-name').val(''); $('#event-description').val('') $('.friend') .removeClass('selected') .removeClass('has-background-primary') .removeClass('has-text-white'); $('#chosen-place').hide(); $('#chose-place').find('title').empty(); $('#event-location').val(''); $('#eventPlace').show(); $('#create-event').hide(); $('#profile').show(); }) }) $(document).on('click', '#cancel-event', function (e) { e.preventDefault(); $('#event-name').val(''); $('#event-description').val('') $('.friend') .removeClass('selected') .removeClass('has-background-primary') .removeClass('has-text-white'); $('#chosen-place').hide(); $('#chose-place').find('title').empty(); $('#event-location').val(''); $('#eventPlace').show(); $('#create-event').hide(); $('#profile').show(); }); $(document).on('click', 'button', function (e) { e.preventDefault(); }) $(document).ready(function() { $(window).keydown(function(event){ if(event.keyCode == 13) { event.preventDefault(); return false; } }); });
package com.book.recipe.config import com.book.recipe.data.* import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.StdOutSqlLogger import org.jetbrains.exposed.sql.addLogger import org.jetbrains.exposed.sql.transactions.transaction fun initDB() { Database.connect( url = "jdbc:h2:file:./database/RECIPE/RECIPE;AUTO_SERVER=TRUE;", driver = "org.h2.Driver", user = "sa" ) createTables() createTestData() } private fun createTables() = transaction { transaction { addLogger(StdOutSqlLogger) SchemaUtils.create( Ingredients, NutritionFacts, Recipes, Labels, RecipeLabels, RecipeIngredients, RecipeRecipeIngredients ) } } fun createTestData() { transaction { if (LabelEntity.all().empty()) { Label.values().forEach { LabelEntity.new { name = it } } } } }
<?php namespace WovoSchool\Modules\Contracts; interface PublisherInterface { /** * Publish something. * * @return mixed */ public function publish(); }
# frozen_string_literal: true require 'rake_helper' describe 'gitlab:uploads:migrate and migrate_to_local rake tasks' do let(:batch_size) { 3 } before do stub_env('MIGRATION_BATCH_SIZE', batch_size.to_s) stub_uploads_object_storage(uploader_class) Rake.application.rake_require 'tasks/gitlab/uploads/migrate' allow(ObjectStorage::MigrateUploadsWorker).to receive(:perform_async) end context "for DesignManagement::DesignV432x230Uploader" do let(:uploader_class) { DesignManagement::DesignV432x230Uploader } let(:model_class) { DesignManagement::Action } let(:mounted_as) { :image_v432x230 } before do create_list(:design_action, 10, :with_image_v432x230) end it_behaves_like 'enqueue upload migration jobs in batch', batch: 4 end end
/* * Copyright © 2021 RongCloud. All rights reserved. */ package com.rongcloud.common.net.bean /** * @author gusd * @Date 2021/06/07 */ data class SimpleRespondBean( val code: Int, val msg: String?, )
// IGNORE_BACKEND_FIR: JVM_IR // TARGET_BACKEND: JVM // WITH_RUNTIME // FULL_JDK // WITH_COROUTINES // IGNORE_BACKEND: package test // NB This test depends on line numbers import helpers.* import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* suspend fun foo() { /* A LOT OF EMPTY LINES */ suspendHere() suspendHere() } val lambda: suspend () -> Unit = { /* A LOT OF EMPTY LINES */ suspendHere() suspendHere() } var continuation: Continuation<Unit>? = null suspend fun suspendHere() = suspendCoroutineUninterceptedOrReturn<Unit> { continuation = it COROUTINE_SUSPENDED } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { builder { foo() } if (!"$continuation".contains("21")) return "$continuation" continuation!!.resumeWith(Result.success(Unit)) if (!"$continuation".contains("22")) return "$continuation" builder { lambda() } if (!"$continuation".contains("33")) return "$continuation" continuation!!.resumeWith(Result.success(Unit)) if (!"$continuation".contains("34")) return "$continuation" return "OK" }
const errorCodes = require('./errorCodes'); module.exports = class JwtExpressError extends Error { constructor(errorCode, extra = {}) { super(); if (errorCodes[errorCode]) { this._errorCode = errorCode; } else { this._errorCode = errorCodes.UNKNOWN_ERROR; } this._extra = (extra instanceof Object) ? extra : {}; } get errorCode() { return this._errorCode; } get extraObject() { return this._extra; } static get ErrorCodes() { return errorCodes; } };
#[cfg(not(feature = "library"))] use crate::error::ContractError; use crate::staking::{ apply_pending_slope_changes_to_state, apply_pending_slope_changes_to_state_and_save_updates, send_tokens, update_user_lock, }; use crate::state::{ Config, State, UserLockedBalance, CONFIG, MAX_SECONDS, MAX_WEEKS, SECONDS_PER_WEEK, STATE, USER_LOCKED_BALANCES, }; use cosmwasm_std::entry_point; use cosmwasm_std::{ from_binary, to_binary, Addr, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, }; use cw20::Cw20ReceiveMsg; use cw900::ve_token::{ ConfigResponse, Cw20HookMsg, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, StakerResponse, StateResponse, }; pub fn is_contract(_addr: &Addr) -> bool { false } #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, env: Env, info: MessageInfo, _msg: InstantiateMsg, ) -> Result<Response, ContractError> { let config = Config { cw20_address: None, owner: deps.api.addr_validate(info.sender.as_str())?, }; CONFIG.save(deps.storage, &config)?; // Save an initial default state let state = State::default(); STATE.save(deps.storage, &state, env.block.time.seconds())?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::Receive(msg) => receive_cw20(deps, env, info, msg), ExecuteMsg::Withdraw {} => execute_withdraw(deps, env, info), ExecuteMsg::IncreaseEndLockTime { end_lock_time } => { execute_increase_end_lock_time(deps, env, info, end_lock_time) } ExecuteMsg::Checkpoint {} => execute_global_checkpoint(deps, env, info), ExecuteMsg::RegisterContracts { cw20_address } => { execute_register_contracts(deps, cw20_address) } } } pub fn receive_cw20( deps: DepsMut, env: Env, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> Result<Response, ContractError> { // only asset contract can execute this message let config: Config = CONFIG.load(deps.storage)?; match config.cw20_address { Some(cw20_address) if cw20_address == deps.api.addr_validate(info.sender.as_str())? => {} _ => { return Err(ContractError::Unauthorized {}); } } match from_binary(&cw20_msg.msg) { Ok(Cw20HookMsg::CreateLock { end_lock_time }) => { let api = deps.api; execute_create_lock( deps, env, api.addr_validate(&cw20_msg.sender)?, cw20_msg.amount, end_lock_time, ) } Ok(Cw20HookMsg::IncreaseLockAmount {}) => { let api = deps.api; execute_increase_lock_amount( deps, env, api.addr_validate(&cw20_msg.sender)?, cw20_msg.amount, ) } _ => Err(ContractError::DataShouldBeGiven {}), } } pub fn execute_global_checkpoint( deps: DepsMut, env: Env, _info: MessageInfo, ) -> Result<Response, ContractError> { let mut state = STATE.load(deps.storage)?; apply_pending_slope_changes_to_state_and_save_updates( deps.storage, &mut state, env.block.time.seconds(), )?; Ok(Response::new()) } pub fn execute_create_lock( deps: DepsMut, env: Env, user: Addr, amount: Uint128, end_lock_time: u64, ) -> Result<Response, ContractError> { let end_lock_time = end_lock_time / SECONDS_PER_WEEK * SECONDS_PER_WEEK; let prev_user_locked_balance = USER_LOCKED_BALANCES .may_load(deps.storage, &user)? .unwrap_or_default(); // Validate that the address is not a contract if is_contract(&user) { return Err(ContractError::ContractsCannotInteractWithLocks {}); } // Validate that the old lock is finished if prev_user_locked_balance.exists() { return Err(ContractError::LockAlreadyExists {}); } // Validate that the new lock is positive if amount == Uint128::zero() { return Err(ContractError::InsufficientLockAmount {}); } // Validate that the new lock is in the future if end_lock_time <= env.block.time.seconds() { return Err(ContractError::EndLockTimeTooEarly {}); } // Validate that the unlock week isn't too far in the future if end_lock_time > env.block.time.seconds() + MAX_SECONDS { return Err(ContractError::EndLockTimeTooLate { max_weeks: MAX_WEEKS, lock_duration_in_weeks: (end_lock_time - env.block.time.seconds()) / MAX_WEEKS, }); } // Create the new user ve token point let new_user_locked_balance = UserLockedBalance { // Locked balance info deposited_amount: amount, end_lock_time, start_lock_time: env.block.time.seconds(), // History tracking info timestamp: env.block.time.seconds(), }; // Propogate the changes update_user_lock( deps.storage, &user, prev_user_locked_balance, new_user_locked_balance, )?; Ok(Response::new().add_attributes(vec![ ("action", "create_lock"), ("user", user.as_str()), ("amount", amount.to_string().as_str()), ])) } pub fn execute_increase_end_lock_time( deps: DepsMut, env: Env, info: MessageInfo, new_end_lock_time: u64, ) -> Result<Response, ContractError> { let user = info.sender; let new_end_lock_time = new_end_lock_time / SECONDS_PER_WEEK * SECONDS_PER_WEEK; let prev_user_locked_balance = USER_LOCKED_BALANCES .may_load(deps.storage, &user)? .unwrap_or_default(); // Validate that the address is not a contract if is_contract(&user) { return Err(ContractError::ContractsCannotInteractWithLocks {}); } // Validate that the lock exists if prev_user_locked_balance.is_void_or_undefined() { return Err(ContractError::LockDoesNotExist {}); } // Validate that the current lock isn't expired. if prev_user_locked_balance.expired_at_timestamp(env.block.time.seconds()) { return Err(ContractError::LockIsExpired {}); } // Validate that the unlock week is further in the future than the current end lock time if prev_user_locked_balance.end_lock_time >= new_end_lock_time { return Err(ContractError::EndLockTimeTooEarly {}); } // Validate that you aren't increasing the lock period too far if new_end_lock_time > env.block.time.seconds() + MAX_SECONDS { return Err(ContractError::EndLockTimeTooLate { max_weeks: MAX_WEEKS, lock_duration_in_weeks: (new_end_lock_time - env.block.time.seconds()) / MAX_WEEKS, }); } // Create the new user ve token point let new_user_locked_balance = UserLockedBalance { // Locked balance info deposited_amount: prev_user_locked_balance.deposited_amount, end_lock_time: new_end_lock_time, start_lock_time: env.block.time.seconds(), // History tracking info timestamp: env.block.time.seconds(), }; // Propogate the changes update_user_lock( deps.storage, &user, prev_user_locked_balance, new_user_locked_balance, )?; Ok(Response::new()) } pub fn execute_increase_lock_amount( deps: DepsMut, env: Env, user: Addr, increase_amount: Uint128, ) -> Result<Response, ContractError> { // Validate that the address is not a contract if is_contract(&user) { return Err(ContractError::ContractsCannotInteractWithLocks {}); } let prev_user_locked_balance = USER_LOCKED_BALANCES .may_load(deps.storage, &user)? .unwrap_or_default(); // Validate that a lock exists if prev_user_locked_balance.is_void_or_undefined() { return Err(ContractError::LockDoesNotExist {}); } // Validate that the current lock isn't expired if prev_user_locked_balance.expired_at_timestamp(env.block.time.seconds()) { return Err(ContractError::LockIsExpired {}); } // Validate that the amount to increase by is positive if increase_amount == Uint128::zero() { return Err(ContractError::InsufficientLockIncreaseAmount {}); } // Create the new user ve token point let new_user_locked_balance = UserLockedBalance { // Locked balance info deposited_amount: prev_user_locked_balance.deposited_amount + increase_amount, end_lock_time: prev_user_locked_balance.end_lock_time, start_lock_time: env.block.time.seconds(), // History tracking info timestamp: env.block.time.seconds(), }; // Propogate the changes update_user_lock( deps.storage, &user, prev_user_locked_balance, new_user_locked_balance, )?; Ok(Response::new()) } pub fn execute_withdraw( deps: DepsMut, env: Env, info: MessageInfo, ) -> Result<Response, ContractError> { let user = info.sender; // Validate that the address is not a contract if is_contract(&user) { return Err(ContractError::ContractsCannotInteractWithLocks {}); } // Get the user locked balance let prev_user_locked_balance = USER_LOCKED_BALANCES .may_load(deps.storage, &user)? .unwrap_or_default(); // Validate that the lock isn't void if prev_user_locked_balance.is_void_or_undefined() { return Err(ContractError::LockDoesNotExist {}); } let new_user_locked_balance: UserLockedBalance; let withdrawn_amount: Uint128; if prev_user_locked_balance.expired_at_timestamp(env.block.time.seconds()) { // If the lock is expired, then withdraw the full amount withdrawn_amount = prev_user_locked_balance.deposited_amount; // Set the new user locked balance to be zeroed out new_user_locked_balance = UserLockedBalance::void_lock_with_timestamp(env.block.time.seconds()); } else { // The lock is not expired, so withdraw everything that is available to be withdrawn // Get the locked_amount at the current timestamp let locked_amount = prev_user_locked_balance.locked_amount_at_timestamp(env.block.time.seconds()); // The amount available to be withdrawn let unlocked_amount = prev_user_locked_balance.deposited_amount - locked_amount; withdrawn_amount = unlocked_amount; if withdrawn_amount == prev_user_locked_balance.deposited_amount { // Set the new user locked balance to be zeroed out // if the withdrawn amount happens to be the entire deposit amount new_user_locked_balance = UserLockedBalance::void_lock_with_timestamp(env.block.time.seconds()); } else { new_user_locked_balance = UserLockedBalance { // Locked balance info deposited_amount: locked_amount, end_lock_time: prev_user_locked_balance.end_lock_time, // Reset the start_lock_time start_lock_time: env.block.time.seconds(), // History tracking info timestamp: env.block.time.seconds(), } } } // Propogate the changes update_user_lock( deps.storage, &user, prev_user_locked_balance, new_user_locked_balance, )?; let config = CONFIG.load(deps.storage)?; let cw20_address = if let Some(cw20_address) = config.cw20_address { cw20_address } else { return Err(ContractError::ConfigContractsNotRegistered {}); }; send_tokens(&cw20_address, &user, withdrawn_amount, "withdraw") } pub fn execute_register_contracts( deps: DepsMut, cw20_address: String, ) -> Result<Response, ContractError> { let mut config: Config = CONFIG.load(deps.storage)?; if config.cw20_address != None { return Err(ContractError::Unauthorized {}); } config.cw20_address = Some(deps.api.addr_validate(&cw20_address)?); CONFIG.save(deps.storage, &config)?; Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> Result<Binary, ContractError> { match msg { QueryMsg::Config {} => Ok(to_binary(&query_config(deps)?)?), QueryMsg::State { timestamp } => Ok(to_binary(&query_state(deps, env, timestamp)?)?), QueryMsg::Staker { address, timestamp } => { Ok(to_binary(&query_staker(deps, env, address, timestamp)?)?) } } } fn query_config(deps: Deps) -> Result<ConfigResponse, ContractError> { let config: Config = CONFIG.load(deps.storage)?; Ok(ConfigResponse { owner: config.owner.to_string(), cw20_address: config .cw20_address .map_or("None".to_string(), |a| a.to_string()), }) } fn query_state( deps: Deps, env: Env, timestamp: Option<u64>, ) -> Result<StateResponse, ContractError> { let timestamp = timestamp.unwrap_or_else(|| env.block.time.seconds()); let mut state: State = STATE .may_load_at_height(deps.storage, timestamp)? .unwrap_or_default(); apply_pending_slope_changes_to_state(deps.storage, &mut state, env.block.time.seconds())?; Ok(StateResponse { total_deposited_amount: state.total_deposit, total_locked_amount: state .voting_power_coefficients .evaluate_locked_balance_at_timestamp(timestamp), total_balance: state .voting_power_coefficients .evaluate_voting_power_at_timestamp(timestamp), }) } pub fn query_staker( deps: Deps, env: Env, address: String, timestamp: Option<u64>, ) -> Result<StakerResponse, ContractError> { let timestamp = timestamp.unwrap_or_else(|| env.block.time.seconds()); let staker_addr = deps.api.addr_validate(address.as_str())?; let user_locked_balance = USER_LOCKED_BALANCES .may_load_at_height(deps.storage, &staker_addr, timestamp)? .unwrap_or_default(); Ok(StakerResponse { deposited_amount: user_locked_balance.deposited_amount, locked_amount: user_locked_balance.locked_amount_at_timestamp(timestamp), balance: user_locked_balance.voting_power_at_timestamp(timestamp), }) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> { Ok(Response::default()) }
<?php class Exam extends CI_Controller { public function index() { $data['title'] = "Your Exams"; $this->load->view('Exam/header'); $this->load->view('Exam/index', $data); $this->load->view('Exam/footer'); } public function free() { $data['title'] = "Your Exams"; $this->load->view('Exam/header'); $this->load->view('Exam/createfree-exam', $data); $this->load->view('Exam/footer'); } public function edit() { $data['title'] = "Your Exams"; $this->load->library('encryption'); $this->load->view('Exam/header'); $this->load->view('Exam/editer', $data); $this->load->view('Exam/footer'); } } ?>
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using OneEchan.Core.Models; using OneEchan.Server.Models.Interfaces; using OneEchan.Core.Common.Extensions; namespace OneEchan.Server.Models.HomeViewModels { public class HomeListModel : ListResult, ICardItemModel { public string Href => $"/Detail?id={ID}"; public string SubText => Updated_At?.DiffForHumans(); public string Text => Name; } }
<?php namespace App\Dao\Dataport; use DB; /** * Description of InterfacesDao * * @author Administrator */ class DataportDao { public function brokers($id,$data){ $datas = array( 'id' => $data['id'], 'realName'=>$data['realName'], 'photo'=>$datas['photo'], 'gender'=>$data['gender'], 'QQ'=>$data['qq'], 'intro'=>$data['intro'], 'cityId'=>$data['cityId'], 'cityAreaId'=>$data['cityAreaId'], 'businessAreaId'=>$data['businessAreaId'], 'company'=>$data['realName'], 'shopName'=>$data['shopName'], 'address'=>$data['address'], 'birthday'=>$data['birthday'], ); return DB::connection("36user$id")->table('brokers')-> insert($datas); } public function customers($id,$data){ $datas = array( 'id' => $data['id'], 'realName'=>$data['realName'], 'QQ'=>$data['qq'], 'birthday'=>$data['birthday'], 'cityId'=>$data['cityId'], 'cityAreaId'=>$data['cityAreaId'], 'intro'=>$data['intro'], 'photo'=>$data['photo'], 'timeRegister'=>$data['timeRegister'], 'timeUpdate'=>$data['timeUpdate'], ); return DB::connection("36user$id")->table('brokers')-> insert($datas); } public function user($user){ $users = array( 'id' => $user['id'], 'userName' => $user['userName'], 'password' =>$user['password'], 'email'=>$user['mobile'], 'mobile'=>$user['mobile'], 'type'=>$user['type'], 'timeUpdate'=>$user['timeUpdate'], ); return DB::connection("36user0")->table('users')-> insert( $users ); } }
<?php namespace Buggl\MainBundle\Service; use Buggl\PhotoBundle\Component\PhotoUploader; /** * BugglPhotoUploaderService * * @author Vincent Farly G. Taboada <farly.taboada@goabroad.com> * * @copyright 2013 (c) Buggl.com */ class BugglPhotoUploaderService { /** * @var Boolean */ private $initiliazed = null; /** * @var Buggl\PhotoBundle\Component\PhotoUploader; */ private $photoUploader = null; /** * @var Array */ private $options = null; /** * @var Array */ private $paths = null; const UPLOAD_PATH = 'uploads'; const TEMP_PATH = 'temp'; /** * constructor * @param PhotoUploader $photoUploader [description] */ public function __construct( PhotoUploader $photoUploader ) { $this->initiliazed = false; $this->photoUploader = $photoUploader; $this->options = array(); $this->paths = array(); $this->setDefaults(); } /** * @param Boolean $isAjax [] * @param Array $options [] * * @return self */ public function setOptions($isAjax,$options) { $this->options['isAjax'] = $isAjax; if ($isAjax) { $this->options['file'] = $this->generateGlobalFilesFormat($options); } else { $this->options['file'] = $this->generateGlobalFilesFormat($options); } $this->photoUploader->setOptions($this->options); return $this; } /** * set the default config * * @return self */ private function setDefaults() { $uploadPath = self::UPLOAD_PATH; $temp = self::TEMP_PATH; $imageUploadPath = $uploadPath.'/images'; $tempPath = $uploadPath.'/'.$temp; if (!file_exists($uploadPath)) { mkdir($uploadPath); } if (!file_exists($tempPath)) { mkdir($tempPath); } $this->paths['temp-path'] = $tempPath; return $this->setPath($imageUploadPath); } /** * set upload path * @param String $imageUploadPath * * @return self */ public function setPath($imageUploadPath) { if (!file_exists($imageUploadPath)) { mkdir($imageUploadPath); } $this->paths['uploaded-image-path'] = $imageUploadPath; $this->initialized = true; return $this; } /** * upload pic to specified upload path * @param String $prefix * * @return PhotoUploader */ public function upload($prefix = null) { if ($this->initialized) { $this->photoUploader->setPaths($this->paths); $this->photoUploader->upload(); return $this->photoUploader; } return null; } /** * @return String upload path */ public function getPath() { return $this->paths['uploaded-image-path']; } /** * @param UploadedFile $uploadedFile * * @return Array */ private function generateGlobalFilesFormat($uploadedFile = null) { if (is_null($uploadedFile)) { return null; } $file = array(); $file['error'] = $uploadedFile->getError(); $file['size'] = $uploadedFile->getClientSize(); $file['type'] = $uploadedFile->getClientMimeType(); $file['name'] = $uploadedFile->getClientOriginalName(); $file['tmp_name'] = $uploadedFile->getPathName(); return $file; } }
package de.metas.invoicecandidate.api.impl; /* * #%L * de.metas.swat.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.adempiere.util.lang.ObjectUtils; import de.metas.invoicecandidate.model.I_C_InvoiceCandidate_InOutLine; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import de.metas.invoicecandidate.api.IInvoiceLineAggregationRequest; import de.metas.invoicecandidate.api.IInvoiceLineAttribute; import de.metas.invoicecandidate.model.I_C_Invoice_Candidate; import de.metas.util.Check; /** * Default immutable implementation of {@link IInvoiceLineAggregationRequest}. * * @author tsa * */ /* package */final class InvoiceLineAggregationRequest implements IInvoiceLineAggregationRequest { public static final Builder builder() { return new Builder(); } private final I_C_Invoice_Candidate invoiceCandidate; private final I_C_InvoiceCandidate_InOutLine iciol; private final ImmutableList<Object> aggregationKeyElements; private final ImmutableSet<IInvoiceLineAttribute> invoiceLineAttributes; private final boolean allocateRemainingQty; private InvoiceLineAggregationRequest(final Builder builder) { super(); Check.assumeNotNull(builder, "builder not null"); this.invoiceCandidate = builder.invoiceCandidate; Check.assumeNotNull(invoiceCandidate, "invoiceCandidate not null"); this.iciol = builder.iciol; if (iciol != null && iciol.getC_Invoice_Candidate_ID() != invoiceCandidate.getC_Invoice_Candidate_ID()) { throw new IllegalArgumentException("Invalid " + iciol + ". C_Invoice_Candidate_ID shall match." + "\n Expected invoice candidate: " + invoiceCandidate); } this.aggregationKeyElements = ImmutableList.copyOf(builder.aggregationKeyElements); this.invoiceLineAttributes = ImmutableSet.copyOf(builder.invoiceLineAttributes); this.allocateRemainingQty = builder.allocateRemainingQty; } @Override public String toString() { return ObjectUtils.toString(this); } @Override public I_C_Invoice_Candidate getC_Invoice_Candidate() { return invoiceCandidate; } @Override public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine() { return iciol; } @Override public List<Object> getLineAggregationKeyElements() { return aggregationKeyElements; } @Override public Set<IInvoiceLineAttribute> getInvoiceLineAttributes() { return invoiceLineAttributes; } @Override public boolean isAllocateRemainingQty() { return this.allocateRemainingQty; } /** * {@link InvoiceLineAggregationRequest} builder. * * @author tsa */ public static class Builder { private I_C_Invoice_Candidate invoiceCandidate; private I_C_InvoiceCandidate_InOutLine iciol; private final List<Object> aggregationKeyElements = new ArrayList<>(); private final Set<IInvoiceLineAttribute> invoiceLineAttributes = new LinkedHashSet<>(); private boolean allocateRemainingQty = false; public InvoiceLineAggregationRequest build() { return new InvoiceLineAggregationRequest(this); } private Builder() { } @Override public String toString() { return ObjectUtils.toString(this); } public Builder setC_Invoice_Candidate(final I_C_Invoice_Candidate invoiceCandidate) { this.invoiceCandidate = invoiceCandidate; return this; } public Builder setC_InvoiceCandidate_InOutLine(final I_C_InvoiceCandidate_InOutLine iciol) { this.iciol = iciol; return this; } /** * Adds an additional element to be considered part of the line aggregation key. * * NOTE: basically this shall be always empty because everything which is related to line aggregation * shall be configured from aggregation definition, * but we are also leaving this door open in case we need to implement some quick/hot fixes. * * @param aggregationKeyElement * @deprecated This method will be removed because we shall go entirely with standard aggregation definition. */ @Deprecated public Builder addLineAggregationKeyElement(final Object aggregationKeyElement) { aggregationKeyElements.add(aggregationKeyElement); return this; } public Builder addInvoiceLineAttributes(final Collection<IInvoiceLineAttribute> invoiceLineAttributes) { this.invoiceLineAttributes.addAll(invoiceLineAttributes); return this; } public Builder setAllocateRemainingQty(boolean allocateRemainingQty) { this.allocateRemainingQty = allocateRemainingQty; return this; } } }
package org.jetbrains.bio.span.statistics.mixture import org.jetbrains.bio.dataframe.DataFrame import org.jetbrains.bio.span.fit.flipStatesIfNecessary import org.jetbrains.bio.span.statistics.regression.PoissonRegressionEmissionScheme import org.jetbrains.bio.statistics.Preprocessed import org.jetbrains.bio.statistics.emission.ConstantIntegerEmissionScheme import org.jetbrains.bio.statistics.emission.EmissionScheme import org.jetbrains.bio.statistics.mixture.MLFreeMixture import org.jetbrains.bio.statistics.model.Fitter import org.jetbrains.bio.viktor.F64Array import org.jetbrains.bio.viktor.asF64Array import kotlin.math.exp /** * Mixture of 3 components: * 0 - zero-inflated component * 1 - LOW (poisson with small parameters) * 2 - HIGH (poisson with high parameters) * * @author Elena Kartysheva * @date 5/25/19 */ class PoissonRegressionMixture( weights: F64Array, covariateLabels: List<String>, regressionCoefficients: Array<DoubleArray> ) : MLFreeMixture(numComponents = 3, numDimensions = 1, weights = weights) { private val zeroEmission = ConstantIntegerEmissionScheme(0) private val regressionEmissionSchemes = arrayOf( PoissonRegressionEmissionScheme( covariateLabels = covariateLabels, regressionCoefficients = regressionCoefficients[0] ), PoissonRegressionEmissionScheme( covariateLabels = covariateLabels, regressionCoefficients = regressionCoefficients[1] ) ) val signalToNoise get() = exp( regressionEmissionSchemes[1].regressionCoefficients[0] - regressionEmissionSchemes[0].regressionCoefficients[0] ) operator fun get(i: Int) = if (i == 0) zeroEmission else regressionEmissionSchemes[i - 1] operator fun set(i: Int, e: PoissonRegressionEmissionScheme) { require(i > 0) regressionEmissionSchemes[i - 1] = e } override fun getEmissionScheme(i: Int, d: Int): EmissionScheme { require(d == 0) { "Invalid dimension $d" } return get(i) } /** * We assume that the response vector is the integer-valued column 0, * and that the remaining columns include all the covariate labels as the double-valued covariates. */ override fun fit(preprocessed: List<Preprocessed<DataFrame>>, title: String, threshold: Double, maxIter: Int) { val data = DataFrame.rowBind(preprocessed.map { it.get() }.toTypedArray()) super.fit(Preprocessed.of(data), title, threshold, maxIter) flipStatesIfNecessary() } companion object { @Suppress("MayBeConstant", "unused") @Transient @JvmField var VERSION = 2 fun fitter() = object : Fitter<PoissonRegressionMixture> { /** * We assume that the response vector is the integer-valued column 0, * and that the remaining columns are the double-valued covariates. */ override fun guess( preprocessed: Preprocessed<DataFrame>, title: String, threshold: Double, maxIter: Int, attempt: Int ) = guess(listOf(preprocessed), title, threshold, maxIter, attempt) /** * We assume that the response vector is the integer-valued column 0, * and that the remaining columns are the double-valued covariates. */ override fun guess( preprocessed: List<Preprocessed<DataFrame>>, title: String, threshold: Double, maxIter: Int, attempt: Int ): PoissonRegressionMixture { // Filter out 0s, since they are covered by dedicated ZERO state val emissions = preprocessed.flatMap { it.get().let { df -> df.sliceAsInt(df.labels.first()).toList() } }.filter { it != 0 }.toIntArray() check(emissions.isNotEmpty()) { "Model can't be trained on empty coverage, exiting." } val df = preprocessed[0].get() return PoissonRegressionMixture( doubleArrayOf(1 / 3.0, 1 / 3.0, 1 / 3.0).asF64Array(), df.labels.drop(1), arrayOf( DoubleArray(df.columnsNumber) { 0.0 }, DoubleArray(df.columnsNumber) { if (it == 0) 1.0 else 0.0 } ) ) } } } }
You can **get** a single value out of an array using **bracket notation**. ```sh $ node > var ingredients = ["Flour", "Water", "Salt"]; undefined > ingredients[0] Flour > ingredients[1] Water > ingredients.length 3 ``` Did you notice how we use `[0]` to get the first value? In programming we count starting at zero. > The number inside of the brackets is called an **index**. Index just means the position of the item within the array. You can also **set** a value using bracket notation and an assignment operator (`=`). ```js var scores = [80, 41, 47]; scores[2] = 29; // Change the last score scores[3] = 51; // Add a new score ```
//! "Dummy" implementations of `ModuleEnvironment` and `FuncEnvironment` for testing //! wasm translation. For complete implementations of `ModuleEnvironment` and //! `FuncEnvironment`, see [wasmtime-environ] in [Wasmtime]. //! //! [wasmtime-environ]: https://crates.io/crates/wasmtime-environ //! [Wasmtime]: https://github.com/CraneStation/wasmtime use crate::environ::{FuncEnvironment, GlobalVariable, ModuleEnvironment, ReturnMode, WasmResult}; use crate::func_translator::FuncTranslator; use crate::translation_utils::{ DefinedFuncIndex, FuncIndex, Global, GlobalIndex, Memory, MemoryIndex, SignatureIndex, Table, TableIndex, }; use core::convert::TryFrom; use cranelift_codegen::cursor::FuncCursor; use cranelift_codegen::ir::immediates::{Offset32, Uimm64}; use cranelift_codegen::ir::types::*; use cranelift_codegen::ir::{self, InstBuilder}; use cranelift_codegen::isa::TargetFrontendConfig; use cranelift_entity::{EntityRef, PrimaryMap}; use std::boxed::Box; use std::string::String; use std::vec::Vec; /// Compute a `ir::ExternalName` for a given wasm function index. fn get_func_name(func_index: FuncIndex) -> ir::ExternalName { ir::ExternalName::user(0, func_index.as_u32()) } /// A collection of names under which a given entity is exported. pub struct Exportable<T> { /// A wasm entity. pub entity: T, /// Names under which the entity is exported. pub export_names: Vec<String>, } impl<T> Exportable<T> { pub fn new(entity: T) -> Self { Self { entity, export_names: Vec::new(), } } } /// The main state belonging to a `DummyEnvironment`. This is split out from /// `DummyEnvironment` to allow it to be borrowed separately from the /// `FuncTranslator` field. pub struct DummyModuleInfo { /// Target description relevant to frontends producing Cranelift IR. config: TargetFrontendConfig, /// Signatures as provided by `declare_signature`. pub signatures: PrimaryMap<SignatureIndex, ir::Signature>, /// Module and field names of imported functions as provided by `declare_func_import`. pub imported_funcs: Vec<(String, String)>, /// Module and field names of imported globals as provided by `declare_global_import`. pub imported_globals: Vec<(String, String)>, /// Module and field names of imported tables as provided by `declare_table_import`. pub imported_tables: Vec<(String, String)>, /// Module and field names of imported memories as provided by `declare_memory_import`. pub imported_memories: Vec<(String, String)>, /// Functions, imported and local. pub functions: PrimaryMap<FuncIndex, Exportable<SignatureIndex>>, /// Function bodies. pub function_bodies: PrimaryMap<DefinedFuncIndex, ir::Function>, /// Tables as provided by `declare_table`. pub tables: PrimaryMap<TableIndex, Exportable<Table>>, /// Memories as provided by `declare_memory`. pub memories: PrimaryMap<MemoryIndex, Exportable<Memory>>, /// Globals as provided by `declare_global`. pub globals: PrimaryMap<GlobalIndex, Exportable<Global>>, /// The start function. pub start_func: Option<FuncIndex>, } impl DummyModuleInfo { /// Creates a new `DummyModuleInfo` instance. pub fn new(config: TargetFrontendConfig) -> Self { Self { config, signatures: PrimaryMap::new(), imported_funcs: Vec::new(), imported_globals: Vec::new(), imported_tables: Vec::new(), imported_memories: Vec::new(), functions: PrimaryMap::new(), function_bodies: PrimaryMap::new(), tables: PrimaryMap::new(), memories: PrimaryMap::new(), globals: PrimaryMap::new(), start_func: None, } } } /// This `ModuleEnvironment` implementation is a "naïve" one, doing essentially nothing and /// emitting placeholders when forced to. Don't try to execute code translated for this /// environment, essentially here for translation debug purposes. pub struct DummyEnvironment { /// Module information. pub info: DummyModuleInfo, /// Function translation. trans: FuncTranslator, /// Vector of wasm bytecode size for each function. pub func_bytecode_sizes: Vec<usize>, /// How to return from functions. return_mode: ReturnMode, /// Instructs to collect debug data during translation. debug_info: bool, } impl DummyEnvironment { /// Creates a new `DummyEnvironment` instance. pub fn new(config: TargetFrontendConfig, return_mode: ReturnMode, debug_info: bool) -> Self { Self { info: DummyModuleInfo::new(config), trans: FuncTranslator::new(), func_bytecode_sizes: Vec::new(), return_mode, debug_info, } } /// Return a `DummyFuncEnvironment` for translating functions within this /// `DummyEnvironment`. pub fn func_env(&self) -> DummyFuncEnvironment { DummyFuncEnvironment::new(&self.info, self.return_mode) } fn get_func_type(&self, func_index: FuncIndex) -> SignatureIndex { self.info.functions[func_index].entity } /// Return the number of imported functions within this `DummyEnvironment`. pub fn get_num_func_imports(&self) -> usize { self.info.imported_funcs.len() } } /// The `FuncEnvironment` implementation for use by the `DummyEnvironment`. pub struct DummyFuncEnvironment<'dummy_environment> { pub mod_info: &'dummy_environment DummyModuleInfo, return_mode: ReturnMode, } impl<'dummy_environment> DummyFuncEnvironment<'dummy_environment> { pub fn new(mod_info: &'dummy_environment DummyModuleInfo, return_mode: ReturnMode) -> Self { Self { mod_info, return_mode, } } // Create a signature for `sigidx` amended with a `vmctx` argument after the standard wasm // arguments. fn vmctx_sig(&self, sigidx: SignatureIndex) -> ir::Signature { let mut sig = self.mod_info.signatures[sigidx].clone(); sig.params.push(ir::AbiParam::special( self.pointer_type(), ir::ArgumentPurpose::VMContext, )); sig } } impl<'dummy_environment> FuncEnvironment for DummyFuncEnvironment<'dummy_environment> { fn target_config(&self) -> TargetFrontendConfig { self.mod_info.config } fn return_mode(&self) -> ReturnMode { self.return_mode } fn make_global( &mut self, func: &mut ir::Function, index: GlobalIndex, ) -> WasmResult<GlobalVariable> { // Just create a dummy `vmctx` global. let offset = i32::try_from((index.index() * 8) + 8).unwrap().into(); let vmctx = func.create_global_value(ir::GlobalValueData::VMContext {}); Ok(GlobalVariable::Memory { gv: vmctx, offset, ty: self.mod_info.globals[index].entity.ty, }) } fn make_heap(&mut self, func: &mut ir::Function, _index: MemoryIndex) -> WasmResult<ir::Heap> { // Create a static heap whose base address is stored at `vmctx+0`. let addr = func.create_global_value(ir::GlobalValueData::VMContext); let gv = func.create_global_value(ir::GlobalValueData::Load { base: addr, offset: Offset32::new(0), global_type: self.pointer_type(), readonly: true, }); Ok(func.create_heap(ir::HeapData { base: gv, min_size: 0.into(), offset_guard_size: 0x8000_0000.into(), style: ir::HeapStyle::Static { bound: 0x1_0000_0000.into(), }, index_type: I32, })) } fn make_table(&mut self, func: &mut ir::Function, _index: TableIndex) -> WasmResult<ir::Table> { // Create a table whose base address is stored at `vmctx+0`. let vmctx = func.create_global_value(ir::GlobalValueData::VMContext); let base_gv = func.create_global_value(ir::GlobalValueData::Load { base: vmctx, offset: Offset32::new(0), global_type: self.pointer_type(), readonly: true, // when tables in wasm become "growable", revisit whether this can be readonly or not. }); let bound_gv = func.create_global_value(ir::GlobalValueData::Load { base: vmctx, offset: Offset32::new(0), global_type: I32, readonly: true, }); Ok(func.create_table(ir::TableData { base_gv, min_size: Uimm64::new(0), bound_gv, element_size: Uimm64::from(u64::from(self.pointer_bytes()) * 2), index_type: I32, })) } fn make_indirect_sig( &mut self, func: &mut ir::Function, index: SignatureIndex, ) -> WasmResult<ir::SigRef> { // A real implementation would probably change the calling convention and add `vmctx` and // signature index arguments. Ok(func.import_signature(self.vmctx_sig(index))) } fn make_direct_func( &mut self, func: &mut ir::Function, index: FuncIndex, ) -> WasmResult<ir::FuncRef> { let sigidx = self.mod_info.functions[index].entity; // A real implementation would probably add a `vmctx` argument. // And maybe attempt some signature de-duplication. let signature = func.import_signature(self.vmctx_sig(sigidx)); let name = get_func_name(index); Ok(func.import_function(ir::ExtFuncData { name, signature, colocated: false, })) } fn translate_call_indirect( &mut self, mut pos: FuncCursor, _table_index: TableIndex, _table: ir::Table, _sig_index: SignatureIndex, sig_ref: ir::SigRef, callee: ir::Value, call_args: &[ir::Value], ) -> WasmResult<ir::Inst> { // Pass the current function's vmctx parameter on to the callee. let vmctx = pos .func .special_param(ir::ArgumentPurpose::VMContext) .expect("Missing vmctx parameter"); // The `callee` value is an index into a table of function pointers. // Apparently, that table is stored at absolute address 0 in this dummy environment. // TODO: Generate bounds checking code. let ptr = self.pointer_type(); let callee_offset = if ptr == I32 { pos.ins().imul_imm(callee, 4) } else { let ext = pos.ins().uextend(I64, callee); pos.ins().imul_imm(ext, 4) }; let mflags = ir::MemFlags::trusted(); let func_ptr = pos.ins().load(ptr, mflags, callee_offset, 0); // Build a value list for the indirect call instruction containing the callee, call_args, // and the vmctx parameter. let mut args = ir::ValueList::default(); args.push(func_ptr, &mut pos.func.dfg.value_lists); args.extend(call_args.iter().cloned(), &mut pos.func.dfg.value_lists); args.push(vmctx, &mut pos.func.dfg.value_lists); Ok(pos .ins() .CallIndirect(ir::Opcode::CallIndirect, INVALID, sig_ref, args) .0) } fn translate_call( &mut self, mut pos: FuncCursor, _callee_index: FuncIndex, callee: ir::FuncRef, call_args: &[ir::Value], ) -> WasmResult<ir::Inst> { // Pass the current function's vmctx parameter on to the callee. let vmctx = pos .func .special_param(ir::ArgumentPurpose::VMContext) .expect("Missing vmctx parameter"); // Build a value list for the call instruction containing the call_args and the vmctx // parameter. let mut args = ir::ValueList::default(); args.extend(call_args.iter().cloned(), &mut pos.func.dfg.value_lists); args.push(vmctx, &mut pos.func.dfg.value_lists); Ok(pos.ins().Call(ir::Opcode::Call, INVALID, callee, args).0) } fn translate_memory_grow( &mut self, mut pos: FuncCursor, _index: MemoryIndex, _heap: ir::Heap, _val: ir::Value, ) -> WasmResult<ir::Value> { Ok(pos.ins().iconst(I32, -1)) } fn translate_memory_size( &mut self, mut pos: FuncCursor, _index: MemoryIndex, _heap: ir::Heap, ) -> WasmResult<ir::Value> { Ok(pos.ins().iconst(I32, -1)) } } impl<'data> ModuleEnvironment<'data> for DummyEnvironment { fn target_config(&self) -> TargetFrontendConfig { self.info.config } fn declare_signature(&mut self, sig: ir::Signature) -> WasmResult<()> { self.info.signatures.push(sig); Ok(()) } fn declare_func_import( &mut self, sig_index: SignatureIndex, module: &'data str, field: &'data str, ) -> WasmResult<()> { assert_eq!( self.info.functions.len(), self.info.imported_funcs.len(), "Imported functions must be declared first" ); self.info.functions.push(Exportable::new(sig_index)); self.info .imported_funcs .push((String::from(module), String::from(field))); Ok(()) } fn declare_func_type(&mut self, sig_index: SignatureIndex) -> WasmResult<()> { self.info.functions.push(Exportable::new(sig_index)); Ok(()) } fn declare_global(&mut self, global: Global) -> WasmResult<()> { self.info.globals.push(Exportable::new(global)); Ok(()) } fn declare_global_import( &mut self, global: Global, module: &'data str, field: &'data str, ) -> WasmResult<()> { self.info.globals.push(Exportable::new(global)); self.info .imported_globals .push((String::from(module), String::from(field))); Ok(()) } fn declare_table(&mut self, table: Table) -> WasmResult<()> { self.info.tables.push(Exportable::new(table)); Ok(()) } fn declare_table_import( &mut self, table: Table, module: &'data str, field: &'data str, ) -> WasmResult<()> { self.info.tables.push(Exportable::new(table)); self.info .imported_tables .push((String::from(module), String::from(field))); Ok(()) } fn declare_table_elements( &mut self, _table_index: TableIndex, _base: Option<GlobalIndex>, _offset: usize, _elements: Box<[FuncIndex]>, ) -> WasmResult<()> { // We do nothing Ok(()) } fn declare_memory(&mut self, memory: Memory) -> WasmResult<()> { self.info.memories.push(Exportable::new(memory)); Ok(()) } fn declare_memory_import( &mut self, memory: Memory, module: &'data str, field: &'data str, ) -> WasmResult<()> { self.info.memories.push(Exportable::new(memory)); self.info .imported_memories .push((String::from(module), String::from(field))); Ok(()) } fn declare_data_initialization( &mut self, _memory_index: MemoryIndex, _base: Option<GlobalIndex>, _offset: usize, _data: &'data [u8], ) -> WasmResult<()> { // We do nothing Ok(()) } fn declare_func_export(&mut self, func_index: FuncIndex, name: &'data str) -> WasmResult<()> { self.info.functions[func_index] .export_names .push(String::from(name)); Ok(()) } fn declare_table_export( &mut self, table_index: TableIndex, name: &'data str, ) -> WasmResult<()> { self.info.tables[table_index] .export_names .push(String::from(name)); Ok(()) } fn declare_memory_export( &mut self, memory_index: MemoryIndex, name: &'data str, ) -> WasmResult<()> { self.info.memories[memory_index] .export_names .push(String::from(name)); Ok(()) } fn declare_global_export( &mut self, global_index: GlobalIndex, name: &'data str, ) -> WasmResult<()> { self.info.globals[global_index] .export_names .push(String::from(name)); Ok(()) } fn declare_start_func(&mut self, func_index: FuncIndex) -> WasmResult<()> { debug_assert!(self.info.start_func.is_none()); self.info.start_func = Some(func_index); Ok(()) } fn define_function_body( &mut self, body_bytes: &'data [u8], body_offset: usize, ) -> WasmResult<()> { let func = { let mut func_environ = DummyFuncEnvironment::new(&self.info, self.return_mode); let func_index = FuncIndex::new(self.get_num_func_imports() + self.info.function_bodies.len()); let name = get_func_name(func_index); let sig = func_environ.vmctx_sig(self.get_func_type(func_index)); let mut func = ir::Function::with_name_signature(name, sig); if self.debug_info { func.collect_debug_info(); } self.trans .translate(body_bytes, body_offset, func, &mut func_environ)? }; self.func_bytecode_sizes.push(body_bytes.len()); self.info.function_bodies.push(func); Ok(()) } }
package com.twitter.concurrent import com.twitter.util.{Future, StdBenchAnnotations} import org.openjdk.jmh.annotations.{Benchmark, Scope, State} @State(Scope.Benchmark) class AsyncQueueBenchmark extends StdBenchAnnotations { private[this] val q = new AsyncQueue[String] @Benchmark def offerThenPoll: Future[String] = { q.offer("hello") q.poll() } @Benchmark def pollThenOffer: Future[String] = { val polled = q.poll() q.offer("hello") polled } }
Basic retro effect for Unity's Post Processing Stack v2 ![Alt Tag](https://user-images.githubusercontent.com/10098032/58493196-12548400-817b-11e9-8e75-a96cd5c105ef.PNG)
// Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in project root for information. package com.microsoft.ml.spark.explainers.split1 import com.microsoft.ml.spark.core.test.base.TestBase import com.microsoft.ml.spark.explainers.LocalExplainer import org.apache.spark.ml.linalg.{Vector, Vectors} class HasExplainTargetSuite extends TestBase { test("getExplainTarget can handle different types of targets") { import spark.implicits._ val df = Seq( (Array(1, 2, 3), Vectors.dense(1, 2, 3), Map(0 -> 1f, 1 -> 2f, 2 -> 3f), Array(0, 2)) ) toDF("label1", "label2", "label3", "targets") // array of Int val target1 = LocalExplainer.LIME.vector .setTargetCol("label1") .extractTarget(df.schema, "targets") val Tuple1(v1) = df.select(target1).as[Tuple1[Vector]].head assert(v1 == Vectors.dense(1d, 3d)) // vector val target2 = LocalExplainer.LIME.vector .setTargetCol("label2") .extractTarget(df.schema, "targets") val Tuple1(v2) = df.select(target2).as[Tuple1[Vector]].head assert(v2 == Vectors.dense(1d, 3d)) // Map of Int -> Float val target3 = LocalExplainer.LIME.vector .setTargetCol("label3") .extractTarget(df.schema, "targets") val Tuple1(v3) = df.select(target3).as[Tuple1[Vector]].head assert(v3 == Vectors.dense(1d, 3d)) } }
# Payment service It consist of three components Order, Payment and Refund A order can have mulitple payments and multiple refunds ##### Order -* Payments ##### Order -* Refunds Right now we only have payments associated with order , refund will come later Payment consist of paypal implementation as of now. It is two step process ##### Initiate payment Initiates a payment for a given order, amount ,callback_url and returns a PaypalURl, ```eg : callback_url :/yourdomain/path/order_id/payment_id``` user logs in to papyaplURL and authorizes payment after authorization paypal returns flow back to a callback_url along with payment and order metadata which was passed during initiate call. ##### Execute payment When paypal gives control back to your callback_url you redirect it to appropiate page on your frontend and call execute payment api to execute the payment on paypal ,and process the order in backend. #### Reference: <a href="https://github.com/paypal/PayPal-Python-SDK"> PayPal Python SDK </a>
class ErrorsController < ApplicationController def not_found error = CloudController::Errors::NotFound.new_from_details('NotFound') presenter = ErrorPresenter.new(error, Rails.env.test?, V3ErrorHasher.new(error)) render status: :not_found, json: presenter end def internal_error error = request.env['action_dispatch.exception'] presenter = ErrorPresenter.new(error, Rails.env.test?, V3ErrorHasher.new(error)) logger.error(presenter.log_message) render status: presenter.response_code, json: presenter end def bad_request error = CloudController::Errors::ApiError.new_from_details('InvalidRequest') if request.env['action_dispatch.exception'].is_a?(ActionDispatch::Http::Parameters::ParseError) error = CloudController::Errors::ApiError.new_from_details('MessageParseError', 'invalid request body') end presenter = ErrorPresenter.new(error, Rails.env.test?, V3ErrorHasher.new(error)) render status: presenter.response_code, json: presenter end end
using UnityEngine; using System.Collections; using UnityEngine.UI; public class VolumeSlider : MonoBehaviour { public Text volumeText; void OnEnable () { float volume = PlayerPrefs.GetFloat("VolumeLevel", 0.8f); gameObject.GetComponent<Slider>().normalizedValue = volume; UpdateVolumeText(volume); } public void UpdateVolumeText (float volume) { volumeText.text = "Volume: " + Mathf.Round(volume * 100) + "%"; } }
#!/bin/bash # # status.sh # Created: 1/02/2016 # Author: jju / VTT Technical Research Centre of Finland Ltd., 2016 # # Description: # Script that returns the current status of the Bro PSA. # # This script is called by the PSA API when the PSA's runtime status is # requested. # # Return value: # 1: alive # 2: not alive # #if [ -z "$PSA_HOME" ]; then # echo "error: 'PSA_HOME' is not set." >&2 # exit 1 #fi #if [ ! -d "$PSA_HOME" ]; then # echo "error: 'PSA_HOME' is not a valid directory." >&2 # exit 1 #fi BROCTL=/opt/bro/bin/broctl LINE=`$BROCTL status 2>&1 | grep "running"` if [ "$?" -eq 0 ] ; then echo 1 exit 1 fi echo 0 exit 0
package blackbox; /** * The mysterious BlackBox */ public class BlackBox { /** * Fizzbuzz returns: * "fizzbuzz" when the number is a multiple of 3 and 5: 15, 30, etc... * "fizz" when the number is a multiple of 3: 3,6,9,12,15, etc... * "buzz" when the number is a multiple of 5: 5,10,15,20, etc... * "" in all other cases. * @param number an integer * @return String value of "" "fizz" "buzz" or "fizzbuzz" */ public String FizzBuzz(int number) { return (number%3==0? "fizz" : "") + (number%5==0? "buzz" : ""); } }
#!/bin/bash ../.port_include.sh port=sqlite version=3310100 files="https://sqlite.org/2020/sqlite-autoconf-${version}.tar.gz sqlite-autoconf-${version}.tar.gz" auth_type="sha1" # sha1: 0c30f5b22152a8166aa3bebb0f4bc1f3e9cc508b workdir="sqlite-autoconf-${version}" export CFLAGS="-Os -DSQLITE_THREADSAFE=0 -DHAVE_UTIME=1" useconfigure=true configopts="--disable-threadsafe" #makeopts="-ltime"
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="assets/css/bootstrap/bootstrap.min.css" rel="stylesheet"> <link href="assets/css/style.css" rel="stylesheet"> <link href="assets/css/font-awesome.min.css" rel="stylesheet"> <link href="assets/css/magnific-popup.css" rel="stylesheet"> <link rel="stylesheet" href="assets/owlcarousel/assets/owl.carousel.min.css"> <link rel="stylesheet" href="assets/owlcarousel/assets/owl.theme.default.min.css"> <title>Литературные апартаменты "На углу у Пушкина" - Псков</title> </head> <body> <div id="logo"> <a href="/"> <img src="assets/img/logo.png" alt="На углу у Пушкина"> </a> <h1>На углу у Пушкина</h1> </div> <section id="top-banner"></section> <section id="main"> <div class="container"> <div class="row" style="height: 100%"> <div class="wrapper"> <div class="col-md-7 col-sm-8 left-block"> <? include 'description.php';?> <? include 'comfort.php';?> <? include 'availability.php';?> <? include 'review.php';?> <? include 'location.php';?> </div> <div class="col-md-offset-1 col-lg-3 col-sm-4 right-block"> <? include 'order.php';?> </div> <div class="clearfix"></div> </div> <div class="col-md-12"> <? include 'gallery.php';?> <? include 'sight.php';?> </div> </div> </div> </section> <footer> <div class="container"> <div class="row"> <div class="col-sm-7"> <hr> <div class="col-sm-6 contact"> <h3>Контакты</h3> <p>+7 (911) 390-06-44 Александр</p> <p>targalife@gmail.com</p> </div> <div class="col-sm-6"> <a class="contract" href="#">Договор</a> </div> </div> </div> </div> </footer> <script src="assets/js/jquery-plugins/jquery-3.3.1.min.js" type="text/javascript"></script> <script src="assets/js/bootstrap.min.js" type="text/javascript"></script> <script src="assets/js/jquery-plugins/jquery.equalheights.min.js"></script> <script src="assets/js/jquery-plugins/jquery.magnific-popup.min.js"></script> <script src="assets/js/jquery-plugins/jquery.sticky-kit.min.js"></script> <script src="assets/owlcarousel/owl.carousel.min.js"></script> <script src="assets/js/common.js"></script> </body> </html>
# Dice Research This is a project for dice game research and simulator. require python3.x and jupyter notebook.
%%% @doc %%% @private %%% Private functions taken from merl.erl and tweaked to return an iolist %%% rather then print to stdout. %%% @end -module(merlin_merl). -export([ format/1, show/1 ]). %% @doc Pretty-print a syntax tree or template to the standard output. This %% is a utility function for development and debugging. format(Ts) when is_list(Ts) -> unicode:characters_to_list(lists:map(fun format/1, Ts)); format(T) -> unicode:characters_to_list([ erl_prettypr:format(merl:tree(T)), $\n ]). %% @doc Print the structure of a syntax tree or template to the standard %% output. This is a utility function for development and debugging. show(Ts) when is_list(Ts) -> unicode:characters_to_list(lists:map(fun show/1, Ts)); show(T) -> unicode:characters_to_list([ pp(merl:tree(T), 0), $\n ]). pp(T, I) -> [ lists:duplicate(I, $\s), limit( lists:flatten([ atom_to_list(type(T)), ": ", erl_prettypr:format(erl_syntax_lib:limit(T, 3)) ]), 79 - I ), $\n, pp_1(lists:filter(fun(X) -> X =/= [] end, subtrees(T)), I + 2) ]. pp_1([G], I) -> pp_2(G, I); pp_1([G | Gs], I) -> [pp_2(G, I), lists:duplicate(I, $\s), "+\n" | pp_1(Gs, I)]; pp_1([], _I) -> []. pp_2(G, I) -> [pp(E, I) || E <- G]. %% limit string to N characters, stay on a single line and compact whitespace limit([$\n | Cs], N) -> limit([$\s | Cs], N); limit([$\r | Cs], N) -> limit([$\s | Cs], N); limit([$\v | Cs], N) -> limit([$\s | Cs], N); limit([$\t | Cs], N) -> limit([$\s | Cs], N); limit([$\s, $\s | Cs], N) -> limit([$\s | Cs], N); limit([C | Cs], N) when C < 32 -> limit(Cs, N); limit([C | Cs], N) when N > 3 -> [C | limit(Cs, N - 1)]; limit([_C1, _C2, _C3, _C4 | _Cs], 3) -> "..."; limit(Cs, 3) -> Cs; limit([_C1, _C2, _C3 | _], 2) -> ".."; limit(Cs, 2) -> Cs; limit([_C1, _C2 | _], 1) -> "."; limit(Cs, 1) -> Cs; limit(_, _) -> []. %% wrappers around erl_syntax functions to provide more uniform shape of %% generic subtrees (maybe this can be fixed in syntax_tools one day) type(T) -> case erl_syntax:type(T) of nil -> list; Type -> Type end. subtrees(T) -> case erl_syntax:type(T) of tuple -> %% don't treat {} as a leaf [erl_syntax:tuple_elements(T)]; nil -> %% don't treat [] as a leaf, but as a list [[], []]; list -> case erl_syntax:list_suffix(T) of none -> [erl_syntax:list_prefix(T), []]; S -> [erl_syntax:list_prefix(T), [S]] end; binary_field -> [ [erl_syntax:binary_field_body(T)], erl_syntax:binary_field_types(T) ]; clause -> case erl_syntax:clause_guard(T) of none -> [ erl_syntax:clause_patterns(T), [], erl_syntax:clause_body(T) ]; G -> [ erl_syntax:clause_patterns(T), [G], erl_syntax:clause_body(T) ] end; receive_expr -> case erl_syntax:receive_expr_timeout(T) of none -> [erl_syntax:receive_expr_clauses(T), [], []]; E -> [ erl_syntax:receive_expr_clauses(T), [E], erl_syntax:receive_expr_action(T) ] end; record_expr -> case erl_syntax:record_expr_argument(T) of none -> [ [], [erl_syntax:record_expr_type(T)], erl_syntax:record_expr_fields(T) ]; V -> [ [V], [erl_syntax:record_expr_type(T)], erl_syntax:record_expr_fields(T) ] end; record_field -> case erl_syntax:record_field_value(T) of none -> [[erl_syntax:record_field_name(T)], []]; V -> [[erl_syntax:record_field_name(T)], [V]] end; _ -> erl_syntax:subtrees(T) end. %% End merl private functions
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..', 'lib')) require 'ruminate' include Ruminate $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..', 'test')) require 'fixture_injector' include FixtureInjector require 'test/unit/assertions' World(Test::Unit::Assertions) require 'mocha'
<?php declare(strict_types=1); namespace Beblife\SpecCurator\Curators; use Beblife\SpecCurator\Spec; interface Curator { public function curate(Spec $spec): Spec; }
/** * Copyright 2020 - Offen Authors <hioffen@posteo.de> * SPDX-License-Identifier: Apache-2.0 */ const { route } = require('preact-router') module.exports = (store) => (next) => (action) => { switch (action.type) { case 'EXPRESS_CONSENT_SUCCESS': route(window.location.pathname) next(action) break default: next(action) } }
# Loyalty engine specific rake tasks class LoyaltyDatabase MIGRATION_FILES_PATH = '../../db/migrate'.freeze SCHEMA_FILE = 'loyalty_schema.rb'.freeze class << self def create config = LOYALTY_DATABASE[Rails.env] # Database is null because it hasn't been created yet. ActiveRecord::Base.establish_connection(config.merge('database' => nil)) ActiveRecord::Base.connection.create_database(config['database'], config) end def drop ActiveRecord::Base.connection .drop_database(LOYALTY_DATABASE[Rails.env]['database']) end def migrate with_engine_connection do ActiveRecord::MigrationContext .new(File.expand_path(MIGRATION_FILES_PATH, __dir__)) .migrate end schema_dump end def rollback with_engine_connection do ActiveRecord::MigrationContext .new(File.expand_path(MIGRATION_FILES_PATH, __dir__)) .rollback end schema_dump end def schema_dump with_engine_connection do File.open(File.join(Rails.root, 'db', SCHEMA_FILE), 'w') do |file| ActiveRecord::SchemaDumper.dump ActiveRecord::Base.connection, file end end end def schema_load with_engine_connection do load File.join(Rails.root, 'db', SCHEMA_FILE) end end private def with_engine_connection original = ActiveRecord::Base.remove_connection ActiveRecord::Base.establish_connection LOYALTY_DATABASE[Rails.env] yield ensure ActiveRecord::Base.establish_connection original end end end desc 'Explaining what the task does' namespace :loyalty do namespace :db do desc 'Create the loyalty database' task create: :environment do LoyaltyDatabase.create end desc 'drop the loyalty database' task drop: :environment do LoyaltyDatabase.drop end desc 'Migrates the loyalty_* database' task migrate: :environment do LoyaltyDatabase.migrate end desc 'Rollback the loyalty_* database' task rollback: :environment do LoyaltyDatabase.rollback end desc 'Loads loyality schema' task :'schema:load' => :environment do LoyaltyDatabase.schema_load end end end
#!/bin/bash set -euo pipefail FILE_ARG=${1:-""} if [ -z ${FILE_ARG} ] then PROJECT_DIR=${PWD} DATABASE_FILE=prod_dump_`date +%Y-%m-%d"_"%H_%M_%S`.sql ssh ${DATABASE_USER}@${DATABASE_HOST} "bash -s" -- \ < ./scripts/dump_prod_db.sh ${DATABASE_NAME} ${DATABASE_FILE} ${DATABASE_PASSWORD} scp ${DATABASE_USER}@${DATABASE_HOST}:${DATABASE_FILE} ${PWD}/db/backups/${DATABASE_FILE} ssh ${DATABASE_USER}@${DATABASE_HOST} rm ${DATABASE_FILE} else DATABASE_FILE=${FILE_ARG} fi docker-compose rm -s -v db docker-compose up -d db # Not ideal, but wait-for-it was listening for the port to be ready, but that # wasn't enough time for the DB to be ready to accept commands, # so we're sleeping instead sleep 7 cat $PWD/db/backups/${DATABASE_FILE} \ | docker exec -i tipresias_db_1 psql -U postgres -d ${DATABASE_NAME}
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Array.Accelerate.Linear.Vector -- Copyright : 2014 Edward Kmett, Charles Durham, -- [2015..2020] Trevor L. McDonell -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Trevor L. McDonell <trevor.mcdonell@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- Operations on free vector spaces ---------------------------------------------------------------------------- module Data.Array.Accelerate.Linear.Vector where import Data.Array.Accelerate as A hiding ( pattern V2 ) import Data.Array.Accelerate.Linear.Type import Control.Lens import Prelude as P import qualified Linear.Vector as L infixl 6 ^+^, ^+, +^, ^-^, ^-, -^ infixl 7 ^*, *^, ^/, /^ -- $setup -- >>> :set -XPatternSynonyms -- >>> import Linear.V2 -- >>> import Data.Array.Accelerate.Linear.V2 ( pattern V2_ ) -- >>> import Data.Array.Accelerate.Interpreter -- >>> :{ -- let test :: Elt e => Exp e -> e -- test e = indexArray (run (unit e)) Z -- :} -- | A vector is an additive group with additional structure. -- -- TODO: Support both 'Exp' and 'Acc' -- class L.Additive f => Additive f where -- | The zero vector -- zero :: (Elt (f a), P.Num a) => Exp (f a) zero = constant (L.zero) -- | Compute the sum of two vectors -- -- >>> test $ (V2_ 1 2 :: Exp (V2 Int)) ^+^ (V2_ 3 4 :: Exp (V2 Int)) -- V2 4 6 -- (^+^) :: forall a. (A.Num a, Box f a) => Exp (f a) -> Exp (f a) -> Exp (f a) (^+^) = lift2 ((L.^+^) :: f (Exp a) -> f (Exp a) -> f (Exp a)) -- | Compute the difference between two vectors -- -- >>> test $ (V2_ 4 5 :: Exp (V2 Int)) ^-^ (V2_ 3 1 :: Exp (V2 Int)) -- V2 1 4 -- (^-^) :: forall a. (A.Num a, Box f a) => Exp (f a) -> Exp (f a) -> Exp (f a) (^-^) = lift2 ((L.^-^) :: f (Exp a) -> f (Exp a) -> f (Exp a)) -- | Linearly interpolate between two vectors -- lerp :: forall a. (A.Num a, Box f a) => Exp a -> Exp (f a) -> Exp (f a) -> Exp (f a) lerp = lift3 (L.lerp :: Exp a -> f (Exp a) -> f (Exp a) -> f (Exp a)) -- type IsAdditive f a = (Additive f, Box f a) -- | Basis element -- newtype E t = E { el :: forall a. (Elt a, Box t a) => Lens' (Exp (t a)) (Exp a) } -- | Compute the negation of a vector -- -- >>> test $ negated (V2_ 2 4 :: Exp (V2 Int)) -- V2 (-2) (-4) -- negated :: forall f a. (Functor f, A.Num a, Box f a) => Exp (f a) -> Exp (f a) negated = lift1 (L.negated :: f (Exp a) -> f (Exp a)) -- | Compute the left scalar product -- -- >>> test $ 2 *^ (V2_ 3 4 :: Exp (V2 Int)) -- V2 6 8 -- (*^) :: forall f a. (Functor f, A.Num a, Box f a) => Exp a -> Exp (f a) -> Exp (f a) (*^) = lift2 ((L.*^) :: Exp a -> f (Exp a) -> f (Exp a)) -- | Compute the right scalar product -- -- >>> test $ (V2_ 3 4 :: Exp (V2 Int)) ^* 2 -- V2 6 8 -- (^*) :: forall f a. (Functor f, A.Num a, Box f a) => Exp (f a) -> Exp a -> Exp (f a) (^*) = lift2 ((L.^*) :: f (Exp a) -> Exp a -> f (Exp a)) -- | Compute division by a scalar on the right -- -- >>> test $ (V2_ 4 6 :: Exp (V2 Double)) ^/ 2 -- V2 2.0 3.0 -- (^/) :: forall f a. (Functor f, A.Fractional a, Box f a) => Exp (f a) -> Exp a -> Exp (f a) (^/) = lift2 ((L.^/) :: f (Exp a) -> Exp a -> f (Exp a)) -- | Compute division of a scalar on the left -- -- >>> test $ 4 /^ (V2_ 2 4 :: Exp (V2 Double)) -- V2 2.0 1.0 -- (/^) :: forall f a. (Functor f, A.Fractional a, Box f a) => Exp a -> Exp (f a) -> Exp (f a) (/^) = lift2 ((\a f -> fmap (a/) f) :: Exp a -> f (Exp a) -> f (Exp a)) -- | Addition with a scalar on the left -- -- >>> test $ 2 +^ (V2_ 3 4 :: Exp (V2 Int)) -- V2 5 6 -- (+^) :: forall f a. (Functor f, A.Num a, Box f a) => Exp a -> Exp (f a) -> Exp (f a) (+^) = lift2 ((\a f -> fmap (a+) f) :: Exp a -> f (Exp a) -> f (Exp a)) -- | Addition with a scalar on the right -- -- >>> test $ (V2_ 1 2 :: Exp (V2 Int)) ^+ 3 -- V2 4 5 -- (^+) :: forall f a. (Functor f, A.Num a, Box f a) => Exp (f a) -> Exp a -> Exp (f a) (^+) = lift2 ((\f a -> fmap (+a) f) :: f (Exp a) -> Exp a -> f (Exp a)) -- | Subtraction with a scalar on the left -- -- >>> test $ 2 -^ (V2_ 3 4 :: Exp (V2 Int)) -- V2 (-1) (-2) -- (-^) :: forall f a. (Functor f, A.Num a, Box f a) => Exp a -> Exp (f a) -> Exp (f a) (-^) = lift2 ((\a f -> fmap (a-) f) :: Exp a -> f (Exp a) -> f (Exp a)) -- | Subtraction with a scalar on the right -- -- >>> test $ (V2_ 1 2 :: Exp (V2 Int)) ^- 3 -- V2 (-2) (-1) -- (^-) :: forall f a. (Functor f, A.Num a, Box f a) => Exp (f a) -> Exp a -> Exp (f a) (^-) = lift2 ((\f a -> fmap (A.subtract a) f) :: f (Exp a) -> Exp a -> f (Exp a))
<?php class SubPatternTest extends PHPUnit_Framework_TestCase { public function testSimpleSubpattern () { $regex = REBuilder\REBuilder::parse("/(a)*/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame(true, $children[0]->getCapture()); $this->assertSame("", $children[0]->getName()); $this->assertSame("", $children[0]->getModifiers()); $children = $children[0]->getChildren(); $this->assertInstanceOf("REBuilder\Pattern\Char", $children[0]); $this->assertSame("a", $children[0]->getChar()); $this->assertSame("/(a)*/", $regex->render()); } public function testNonCapturingSubpattern () { $regex = REBuilder\REBuilder::parse("/(?:a)*/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame(false, $children[0]->getCapture()); $this->assertSame("/(?:a)*/", $regex->render()); } public function testNonCapturingSubpatternWithModifiers () { $regex = REBuilder\REBuilder::parse("/(?i:a)*/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame(false, $children[0]->getCapture()); $this->assertSame("i", $children[0]->getModifiers()); $this->assertSame("/(?i:a)*/", $regex->render()); } public function anchoredSubpatterns () { return array( array("(^a)", true, false), array("(a$)", false, true), array("(^a$)", true, true), array('($a)', false, false), array('(a^)', false, false) ); } /** * @dataProvider anchoredSubpatterns */ public function testSubpatternWithAnchors ($pattern, $start, $end) { $regex = REBuilder\REBuilder::parse("/$pattern/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame($start, $children[0]->getStartAnchored()); $this->assertSame($end, $children[0]->getEndAnchored()); $render = $start || $end ? $pattern : "(a)"; $this->assertSame("/$render/", $regex->render()); } public function validNamedSubpatterns () { return array( array("P<name>"), array("<name>"), array("'name'") ); } /** * @dataProvider validNamedSubpatterns */ public function testNamedSubpattern ($pattern) { $regex = REBuilder\REBuilder::parse("/(?" . $pattern . "a)*/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame(true, $children[0]->getCapture()); $this->assertSame("name", $children[0]->getName()); $this->assertSame("/(?<name>a)*/", $regex->render()); } public function testGroupMatches () { $regex = REBuilder\REBuilder::parse("/(?|a)*/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame(false, $children[0]->getCapture()); $this->assertSame(true, $children[0]->getGroupMatches()); $this->assertSame("/(?|a)*/", $regex->render()); } public function testOnceOnly () { $regex = REBuilder\REBuilder::parse("/(?>a)/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame(false, $children[0]->getCapture()); $this->assertSame(true, $children[0]->getOnceOnly()); $this->assertSame("/(?>a)/", $regex->render()); } public function testSubtractModifiers () { $regex = REBuilder\REBuilder::parse("/(?-i:a)/i"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame("-i", $children[0]->getModifiers()); $this->assertSame("/(?-i:a)/i", $regex->render()); } public function testNestedSubpatterns () { $regex = REBuilder\REBuilder::parse("/(?:a(b))*/"); $this->assertInstanceOf("REBuilder\Pattern\Regex", $regex); $children = $regex->getChildren(); $this->assertSame(1, count($children)); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[0]); $this->assertSame(false, $children[0]->getCapture()); $children = $children[0]->getChildren(); $this->assertSame(2, count($children)); $this->assertInstanceOf("REBuilder\Pattern\Char", $children[0]); $this->assertInstanceOf("REBuilder\Pattern\SubPattern", $children[1]); $children = $children[1]->getChildren(); $this->assertSame(1, count($children)); $this->assertSame("/(?:a(b))*/", $regex->render()); } public function invalidSubpatterns () { return array( array("(a"), array("a)"), array("(?a)"), array("(?1:a)"), array("(?<invalid?>)"), array("(?<invalid)") ); } /** * @dataProvider invalidSubpatterns * @expectedException REBuilder\Exception\Generic */ public function testInvaliSubpattern ($pattern) { REBuilder\REBuilder::parse("/$pattern/"); } /** * @expectedException REBuilder\Exception\InvalidRepetition */ public function testInvalidRepetition () { REBuilder\REBuilder::parse("/(*)/"); } /** * @expectedException REBuilder\Exception\Generic */ public function testInvalidNameException () { REBuilder\REBuilder::create() ->addSubpattern() ->setName("%"); } /** * @expectedException REBuilder\Exception\InvalidModifier */ public function testInvalidModifierException () { REBuilder\REBuilder::create() ->addSubpattern() ->setModifiers("?"); } /** * @expectedException BadMethodCallException */ public function testCallUndefinedMethodException () { $subpattern = new REBuilder\Pattern\SubPattern(); $subpattern->addUndefinedMethod(); } public function combinedOptions () { return array( array(true, "name", "", false, false, "(?<name>a)"), array(false, "name", "", false, false, "(?:a)"), array(false, "", "i", false, false, "(?i:a)"), array(true, "", "i", false, false, "((?i:a))"), array(true, "", "i", true, false, "((?|(?i:a)))"), array(true, "", "", false, true, "((?>a))"), array(true, "", "i", true, true, "((?|(?>(?i:a))))"), array(false, "", "i", true, true, "(?|(?>(?i:a)))"), array(false, "", "", true, false, "(?|a)"), array(false, "", "", false, true, "(?>a)") ); } /** * @dataProvider combinedOptions */ public function testCombinedOptions ($capture, $name, $modifiers, $groupMatches, $onceOnly, $testCode) { $subpattern = new REBuilder\Pattern\SubPattern($capture, $name, $modifiers, $groupMatches, $onceOnly); $subpattern->addChild(new REBuilder\Pattern\Char("a")); $render = $subpattern->render(); $this->assertSame($testCode, $render); $this->assertSame(1, preg_match("/" . $render . "/", "a")); } public function testObjectGeneration () { $regex = REBuilder\REBuilder::create(); $regex ->addSubpattern(false) ->addControlChar(";") ->setRepetition("+", true); $this->assertSame("/(?:\c;+?)/", $regex . ""); } }
import React from 'react'; import './App.css'; import {personas} from "./modelo/personas"; import {quienEsMayor} from "./utiles/utiles"; function App() { const edades: number[] = [15, 16, 23, 16] return ( <div className="App"> <div> <h3>Personas</h3> {personas.map((persona: string, index: number): JSX.Element => { return ( <div key={`${index}-${persona}`}>{persona}</div> )}) } </div> <div> <h3>Edades</h3> {edades.map((edad: number, index:number): JSX.Element => {return ( <div key={`${index}-${edad}`}>{edad}</div> )}) } </div> <div> <h3>Quien es Mayor</h3> <div >{quienEsMayor(personas[0], edades[0], personas[1], edades[1])}</div> <div >{quienEsMayor(personas[2], edades[2], personas[3], edades[3])}</div> <div >{quienEsMayor(personas[1], edades[1], personas[3], edades[3])}</div> </div> </div> ); } export default App;
// Test code after return in main() char* const SCREEN = (char*)0x0400; char b = 0; void main() { SCREEN[0] = b; return; bb(); SCREEN[1] = b; } void bb(){ b++; }
#------------------------------------------------------------------------------ # # WARNING ! # # This is a generated file. DO NOT EDIT THIS FILE! Your changes will # be lost the next time this file is regenerated. # # This file was generated using asterisk-ari-client ruby gem. # #------------------------------------------------------------------------------ module Ari class Mailbox < Resource attr_reader :name, :old_messages, :new_messages # GET /mailboxes # # Mailboxes # # def self.list(options = {}) path = '/mailboxes' response = client(options).get(path, options) response.map { |hash| Mailbox.new(hash.merge(client: options[:client])) } end # GET /mailboxes/%{mailboxName} # # Mailbox state # # # Parameters: # # mailboxName (required) - Name of the mailbox # def self.get(options = {}) raise ArgumentError.new("Parameter mailboxName must be passed in options hash.") unless options[:mailboxName] path = '/mailboxes/%{mailboxName}' % options response = client(options).get(path, options) Mailbox.new(response.merge(client: options[:client])) end def get(options = {}) self.class.get(options.merge(mailboxId: self.id, client: @client)) end # PUT /mailboxes/%{mailboxName} # # Mailbox state # # # Parameters: # # mailboxName (required) - Name of the mailbox # oldMessages (required) - Count of old messages in the mailbox # newMessages (required) - Count of new messages in the mailbox # def self.update(options = {}) raise ArgumentError.new("Parameter mailboxName must be passed in options hash.") unless options[:mailboxName] raise ArgumentError.new("Parameter oldMessages must be passed in options hash.") unless options[:oldMessages] raise ArgumentError.new("Parameter newMessages must be passed in options hash.") unless options[:newMessages] path = '/mailboxes/%{mailboxName}' % options response = client(options).put(path, options) end def update(options = {}) self.class.update(options.merge(mailboxId: self.id, client: @client)) end # DELETE /mailboxes/%{mailboxName} # # Mailbox state # # # Parameters: # # mailboxName (required) - Name of the mailbox # def self.delete(options = {}) raise ArgumentError.new("Parameter mailboxName must be passed in options hash.") unless options[:mailboxName] path = '/mailboxes/%{mailboxName}' % options response = client(options).delete(path, options) rescue Ari::RequestError => e raise unless e.code == '404' end def delete(options = {}) self.class.delete(options.merge(mailboxId: self.id, client: @client)) end end end Ari::Client.send :define_method, 'mailboxes' do Ari::ListResource.new(self, Ari::Mailbox) end
<?php namespace App\Http\Controllers\Api; use App\Http\Requests\Telegram\SendOrderRequest; use App\Http\Controllers\Controller; use App\Http\Requests\Telegram\SendFeedbackRequest; use App\Jobs\SendFeedback; use App\Jobs\SendOrder; use App\Jobs\SendProduct; use App\Models\Product; use Telegram\Bot\Laravel\Facades\Telegram; class TelegramController extends Controller { public function index() { return Telegram::getUpdates(); } public function sendOrder(SendOrderRequest $request, Product $product) { SendOrder::dispatchNow($request->all(), $product); return response()->json(['status' => __('custom.orderSent')], 201); } public function sendProduct(Product $product) { $product->load(['brand','categories', 'ages', 'media']); SendProduct::dispatchNow($product); return response()->json(['status' => __('custom.productSent')], 201); } public function sendFeedback(SendFeedbackRequest $request) { SendFeedback::dispatchNow($request->all()); return response()->json(['status' => __('custom.feedbackSent')], 201); } }
// Package wraperr packages an error with another wrapped error // This allows errors.Is to work without directly injecting the string of the wrapped error package wraperr // WrapErr wraps an underlying error with another error // // Example usage: // var ErrLimit = errors.New("Limit reached") // ... // func someFunc() error { // return wrapper.WrapErr{Err: fmt.Errorf("Limit %d reached on %s", limit, instance), Wrap: ErrLimit} // } // ... // if errors.Is(err, ErrLimit) { ... } // // This makes it easier to include a custom error message while also allowing type WrapErr struct { Err error Wrap error } // New returns a new WrapErr func New(err, wrap error) WrapErr { return WrapErr{Err: err, Wrap: wrap} } func (e WrapErr) Error() string { return e.Err.Error() } func (e WrapErr) Unwrap() error { return e.Wrap }
{-# LANGUAGE QualifiedDo #-} import Prelude as P hiding (fail) -- Tests that fail is not required with irrefutable patterns main = print $ P.do x <- [1, 2] (_, y) <- [(1, "a"), (2, "b")] P.return (x, y)
[Environment]::SetEnvironmentVariable("BABEL_BROKER", "amqp://guest:guest@localhost:5672/", "User")
CREATE TRIGGER tr_UpdateOrdersDelivery ON Orders FOR UPDATE AS BEGIN DECLARE @oldStatus BIT = ( SELECT Delivered FROM deleted ) DECLARE @newStatus BIT = ( SELECT Delivered FROM inserted ) IF (@oldStatus = 0 AND @newStatus = 1) BEGIN UPDATE Parts SET StockQty += op.Quantity FROM Parts AS p JOIN OrderParts AS op ON op.PartId = p.PartId JOIN Orders AS o ON o.OrderId = op.OrderId JOIN inserted AS i ON i.OrderId = o.OrderId JOIN deleted AS d ON d.OrderId = i.OrderId END END
/* * Copyright © 2008-2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "i915_drv.h" #include "i915_scatterlist.h" #include "i915_pvinfo.h" #include "i915_vgpu.h" /** * DOC: fence register handling * * Important to avoid confusions: "fences" in the i915 driver are not execution * fences used to track command completion but hardware detiler objects which * wrap a given range of the global GTT. Each platform has only a fairly limited * set of these objects. * * Fences are used to detile GTT memory mappings. They're also connected to the * hardware frontbuffer render tracking and hence interact with frontbuffer * compression. Furthermore on older platforms fences are required for tiled * objects used by the display engine. They can also be used by the render * engine - they're required for blitter commands and are optional for render * commands. But on gen4+ both display (with the exception of fbc) and rendering * have their own tiling state bits and don't need fences. * * Also note that fences only support X and Y tiling and hence can't be used for * the fancier new tiling formats like W, Ys and Yf. * * Finally note that because fences are such a restricted resource they're * dynamically associated with objects. Furthermore fence state is committed to * the hardware lazily to avoid unnecessary stalls on gen2/3. Therefore code must * explicitly call i915_gem_object_get_fence() to synchronize fencing status * for cpu access. Also note that some code wants an unfenced view, for those * cases the fence can be removed forcefully with i915_gem_object_put_fence(). * * Internally these functions will synchronize with userspace access by removing * CPU ptes into GTT mmaps (not the GTT ptes themselves) as needed. */ #define pipelined 0 static struct drm_i915_private *fence_to_i915(struct i915_fence_reg *fence) { return fence->ggtt->vm.i915; } static struct intel_uncore *fence_to_uncore(struct i915_fence_reg *fence) { return fence->ggtt->vm.gt->uncore; } static void i965_write_fence_reg(struct i915_fence_reg *fence) { i915_reg_t fence_reg_lo, fence_reg_hi; int fence_pitch_shift; u64 val; if (INTEL_GEN(fence_to_i915(fence)) >= 6) { fence_reg_lo = FENCE_REG_GEN6_LO(fence->id); fence_reg_hi = FENCE_REG_GEN6_HI(fence->id); fence_pitch_shift = GEN6_FENCE_PITCH_SHIFT; } else { fence_reg_lo = FENCE_REG_965_LO(fence->id); fence_reg_hi = FENCE_REG_965_HI(fence->id); fence_pitch_shift = I965_FENCE_PITCH_SHIFT; } val = 0; if (fence->tiling) { unsigned int stride = fence->stride; GEM_BUG_ON(!IS_ALIGNED(stride, 128)); val = fence->start + fence->size - I965_FENCE_PAGE; val <<= 32; val |= fence->start; val |= (u64)((stride / 128) - 1) << fence_pitch_shift; if (fence->tiling == I915_TILING_Y) val |= BIT(I965_FENCE_TILING_Y_SHIFT); val |= I965_FENCE_REG_VALID; } if (!pipelined) { struct intel_uncore *uncore = fence_to_uncore(fence); /* * To w/a incoherency with non-atomic 64-bit register updates, * we split the 64-bit update into two 32-bit writes. In order * for a partial fence not to be evaluated between writes, we * precede the update with write to turn off the fence register, * and only enable the fence as the last step. * * For extra levels of paranoia, we make sure each step lands * before applying the next step. */ intel_uncore_write_fw(uncore, fence_reg_lo, 0); intel_uncore_posting_read_fw(uncore, fence_reg_lo); intel_uncore_write_fw(uncore, fence_reg_hi, upper_32_bits(val)); intel_uncore_write_fw(uncore, fence_reg_lo, lower_32_bits(val)); intel_uncore_posting_read_fw(uncore, fence_reg_lo); } } static void i915_write_fence_reg(struct i915_fence_reg *fence) { u32 val; val = 0; if (fence->tiling) { unsigned int stride = fence->stride; unsigned int tiling = fence->tiling; bool is_y_tiled = tiling == I915_TILING_Y; if (is_y_tiled && HAS_128_BYTE_Y_TILING(fence_to_i915(fence))) stride /= 128; else stride /= 512; GEM_BUG_ON(!is_power_of_2(stride)); val = fence->start; if (is_y_tiled) val |= BIT(I830_FENCE_TILING_Y_SHIFT); val |= I915_FENCE_SIZE_BITS(fence->size); val |= ilog2(stride) << I830_FENCE_PITCH_SHIFT; val |= I830_FENCE_REG_VALID; } if (!pipelined) { struct intel_uncore *uncore = fence_to_uncore(fence); i915_reg_t reg = FENCE_REG(fence->id); intel_uncore_write_fw(uncore, reg, val); intel_uncore_posting_read_fw(uncore, reg); } } static void i830_write_fence_reg(struct i915_fence_reg *fence) { u32 val; val = 0; if (fence->tiling) { unsigned int stride = fence->stride; val = fence->start; if (fence->tiling == I915_TILING_Y) val |= BIT(I830_FENCE_TILING_Y_SHIFT); val |= I830_FENCE_SIZE_BITS(fence->size); val |= ilog2(stride / 128) << I830_FENCE_PITCH_SHIFT; val |= I830_FENCE_REG_VALID; } if (!pipelined) { struct intel_uncore *uncore = fence_to_uncore(fence); i915_reg_t reg = FENCE_REG(fence->id); intel_uncore_write_fw(uncore, reg, val); intel_uncore_posting_read_fw(uncore, reg); } } static void fence_write(struct i915_fence_reg *fence) { struct drm_i915_private *i915 = fence_to_i915(fence); /* * Previous access through the fence register is marshalled by * the mb() inside the fault handlers (i915_gem_release_mmaps) * and explicitly managed for internal users. */ if (IS_GEN(i915, 2)) i830_write_fence_reg(fence); else if (IS_GEN(i915, 3)) i915_write_fence_reg(fence); else i965_write_fence_reg(fence); /* * Access through the fenced region afterwards is * ordered by the posting reads whilst writing the registers. */ } static bool gpu_uses_fence_registers(struct i915_fence_reg *fence) { return INTEL_GEN(fence_to_i915(fence)) < 4; } static int fence_update(struct i915_fence_reg *fence, struct i915_vma *vma) { struct i915_ggtt *ggtt = fence->ggtt; struct intel_uncore *uncore = fence_to_uncore(fence); intel_wakeref_t wakeref; struct i915_vma *old; int ret; fence->tiling = 0; if (vma) { GEM_BUG_ON(!i915_gem_object_get_stride(vma->obj) || !i915_gem_object_get_tiling(vma->obj)); if (!i915_vma_is_map_and_fenceable(vma)) return -EINVAL; if (gpu_uses_fence_registers(fence)) { /* implicit 'unfenced' GPU blits */ ret = i915_vma_sync(vma); if (ret) return ret; } fence->start = vma->node.start; fence->size = vma->fence_size; fence->stride = i915_gem_object_get_stride(vma->obj); fence->tiling = i915_gem_object_get_tiling(vma->obj); } WRITE_ONCE(fence->dirty, false); old = xchg(&fence->vma, NULL); if (old) { /* XXX Ideally we would move the waiting to outside the mutex */ ret = i915_active_wait(&fence->active); if (ret) { fence->vma = old; return ret; } i915_vma_flush_writes(old); /* * Ensure that all userspace CPU access is completed before * stealing the fence. */ if (old != vma) { GEM_BUG_ON(old->fence != fence); i915_vma_revoke_mmap(old); old->fence = NULL; } list_move(&fence->link, &ggtt->fence_list); } /* * We only need to update the register itself if the device is awake. * If the device is currently powered down, we will defer the write * to the runtime resume, see intel_ggtt_restore_fences(). * * This only works for removing the fence register, on acquisition * the caller must hold the rpm wakeref. The fence register must * be cleared before we can use any other fences to ensure that * the new fences do not overlap the elided clears, confusing HW. */ wakeref = intel_runtime_pm_get_if_in_use(uncore->rpm); if (!wakeref) { GEM_BUG_ON(vma); return 0; } WRITE_ONCE(fence->vma, vma); fence_write(fence); if (vma) { vma->fence = fence; list_move_tail(&fence->link, &ggtt->fence_list); } intel_runtime_pm_put(uncore->rpm, wakeref); return 0; } /** * i915_vma_revoke_fence - force-remove fence for a VMA * @vma: vma to map linearly (not through a fence reg) * * This function force-removes any fence from the given object, which is useful * if the kernel wants to do untiled GTT access. */ void i915_vma_revoke_fence(struct i915_vma *vma) { struct i915_fence_reg *fence = vma->fence; intel_wakeref_t wakeref; lockdep_assert_held(&vma->vm->mutex); if (!fence) return; GEM_BUG_ON(fence->vma != vma); GEM_BUG_ON(!i915_active_is_idle(&fence->active)); GEM_BUG_ON(atomic_read(&fence->pin_count)); fence->tiling = 0; WRITE_ONCE(fence->vma, NULL); vma->fence = NULL; with_intel_runtime_pm_if_in_use(fence_to_uncore(fence)->rpm, wakeref) fence_write(fence); } static struct i915_fence_reg *fence_find(struct i915_ggtt *ggtt) { struct i915_fence_reg *fence; list_for_each_entry(fence, &ggtt->fence_list, link) { GEM_BUG_ON(fence->vma && fence->vma->fence != fence); if (atomic_read(&fence->pin_count)) continue; return fence; } /* Wait for completion of pending flips which consume fences */ if (intel_has_pending_fb_unpin(ggtt->vm.i915)) return ERR_PTR(-EAGAIN); return ERR_PTR(-EDEADLK); } int __i915_vma_pin_fence(struct i915_vma *vma) { struct i915_ggtt *ggtt = i915_vm_to_ggtt(vma->vm); struct i915_fence_reg *fence; struct i915_vma *set = i915_gem_object_is_tiled(vma->obj) ? vma : NULL; int err; lockdep_assert_held(&vma->vm->mutex); /* Just update our place in the LRU if our fence is getting reused. */ if (vma->fence) { fence = vma->fence; GEM_BUG_ON(fence->vma != vma); atomic_inc(&fence->pin_count); if (!fence->dirty) { list_move_tail(&fence->link, &ggtt->fence_list); return 0; } } else if (set) { fence = fence_find(ggtt); if (IS_ERR(fence)) return PTR_ERR(fence); GEM_BUG_ON(atomic_read(&fence->pin_count)); atomic_inc(&fence->pin_count); } else { return 0; } err = fence_update(fence, set); if (err) goto out_unpin; GEM_BUG_ON(fence->vma != set); GEM_BUG_ON(vma->fence != (set ? fence : NULL)); if (set) return 0; out_unpin: atomic_dec(&fence->pin_count); return err; } /** * i915_vma_pin_fence - set up fencing for a vma * @vma: vma to map through a fence reg * * When mapping objects through the GTT, userspace wants to be able to write * to them without having to worry about swizzling if the object is tiled. * This function walks the fence regs looking for a free one for @obj, * stealing one if it can't find any. * * It then sets up the reg based on the object's properties: address, pitch * and tiling format. * * For an untiled surface, this removes any existing fence. * * Returns: * * 0 on success, negative error code on failure. */ int i915_vma_pin_fence(struct i915_vma *vma) { int err; if (!vma->fence && !i915_gem_object_is_tiled(vma->obj)) return 0; /* * Note that we revoke fences on runtime suspend. Therefore the user * must keep the device awake whilst using the fence. */ assert_rpm_wakelock_held(vma->vm->gt->uncore->rpm); GEM_BUG_ON(!i915_vma_is_pinned(vma)); GEM_BUG_ON(!i915_vma_is_ggtt(vma)); err = mutex_lock_interruptible(&vma->vm->mutex); if (err) return err; err = __i915_vma_pin_fence(vma); mutex_unlock(&vma->vm->mutex); return err; } /** * i915_reserve_fence - Reserve a fence for vGPU * @ggtt: Global GTT * * This function walks the fence regs looking for a free one and remove * it from the fence_list. It is used to reserve fence for vGPU to use. */ struct i915_fence_reg *i915_reserve_fence(struct i915_ggtt *ggtt) { struct i915_fence_reg *fence; int count; int ret; lockdep_assert_held(&ggtt->vm.mutex); /* Keep at least one fence available for the display engine. */ count = 0; list_for_each_entry(fence, &ggtt->fence_list, link) count += !atomic_read(&fence->pin_count); if (count <= 1) return ERR_PTR(-ENOSPC); fence = fence_find(ggtt); if (IS_ERR(fence)) return fence; if (fence->vma) { /* Force-remove fence from VMA */ ret = fence_update(fence, NULL); if (ret) return ERR_PTR(ret); } list_del(&fence->link); return fence; } /** * i915_unreserve_fence - Reclaim a reserved fence * @fence: the fence reg * * This function add a reserved fence register from vGPU to the fence_list. */ void i915_unreserve_fence(struct i915_fence_reg *fence) { struct i915_ggtt *ggtt = fence->ggtt; lockdep_assert_held(&ggtt->vm.mutex); list_add(&fence->link, &ggtt->fence_list); } /** * intel_ggtt_restore_fences - restore fence state * @ggtt: Global GTT * * Restore the hw fence state to match the software tracking again, to be called * after a gpu reset and on resume. Note that on runtime suspend we only cancel * the fences, to be reacquired by the user later. */ void intel_ggtt_restore_fences(struct i915_ggtt *ggtt) { int i; for (i = 0; i < ggtt->num_fences; i++) fence_write(&ggtt->fence_regs[i]); } /** * DOC: tiling swizzling details * * The idea behind tiling is to increase cache hit rates by rearranging * pixel data so that a group of pixel accesses are in the same cacheline. * Performance improvement from doing this on the back/depth buffer are on * the order of 30%. * * Intel architectures make this somewhat more complicated, though, by * adjustments made to addressing of data when the memory is in interleaved * mode (matched pairs of DIMMS) to improve memory bandwidth. * For interleaved memory, the CPU sends every sequential 64 bytes * to an alternate memory channel so it can get the bandwidth from both. * * The GPU also rearranges its accesses for increased bandwidth to interleaved * memory, and it matches what the CPU does for non-tiled. However, when tiled * it does it a little differently, since one walks addresses not just in the * X direction but also Y. So, along with alternating channels when bit * 6 of the address flips, it also alternates when other bits flip -- Bits 9 * (every 512 bytes, an X tile scanline) and 10 (every two X tile scanlines) * are common to both the 915 and 965-class hardware. * * The CPU also sometimes XORs in higher bits as well, to improve * bandwidth doing strided access like we do so frequently in graphics. This * is called "Channel XOR Randomization" in the MCH documentation. The result * is that the CPU is XORing in either bit 11 or bit 17 to bit 6 of its address * decode. * * All of this bit 6 XORing has an effect on our memory management, * as we need to make sure that the 3d driver can correctly address object * contents. * * If we don't have interleaved memory, all tiling is safe and no swizzling is * required. * * When bit 17 is XORed in, we simply refuse to tile at all. Bit * 17 is not just a page offset, so as we page an object out and back in, * individual pages in it will have different bit 17 addresses, resulting in * each 64 bytes being swapped with its neighbor! * * Otherwise, if interleaved, we have to tell the 3d driver what the address * swizzling it needs to do is, since it's writing with the CPU to the pages * (bit 6 and potentially bit 11 XORed in), and the GPU is reading from the * pages (bit 6, 9, and 10 XORed in), resulting in a cumulative bit swizzling * required by the CPU of XORing in bit 6, 9, 10, and potentially 11, in order * to match what the GPU expects. */ /** * detect_bit_6_swizzle - detect bit 6 swizzling pattern * @ggtt: Global GGTT * * Detects bit 6 swizzling of address lookup between IGD access and CPU * access through main memory. */ static void detect_bit_6_swizzle(struct i915_ggtt *ggtt) { struct intel_uncore *uncore = ggtt->vm.gt->uncore; struct drm_i915_private *i915 = ggtt->vm.i915; u32 swizzle_x = I915_BIT_6_SWIZZLE_UNKNOWN; u32 swizzle_y = I915_BIT_6_SWIZZLE_UNKNOWN; if (INTEL_GEN(i915) >= 8 || IS_VALLEYVIEW(i915)) { /* * On BDW+, swizzling is not used. We leave the CPU memory * controller in charge of optimizing memory accesses without * the extra address manipulation GPU side. * * VLV and CHV don't have GPU swizzling. */ swizzle_x = I915_BIT_6_SWIZZLE_NONE; swizzle_y = I915_BIT_6_SWIZZLE_NONE; } else if (INTEL_GEN(i915) >= 6) { if (i915->preserve_bios_swizzle) { if (intel_uncore_read(uncore, DISP_ARB_CTL) & DISP_TILE_SURFACE_SWIZZLING) { swizzle_x = I915_BIT_6_SWIZZLE_9_10; swizzle_y = I915_BIT_6_SWIZZLE_9; } else { swizzle_x = I915_BIT_6_SWIZZLE_NONE; swizzle_y = I915_BIT_6_SWIZZLE_NONE; } } else { u32 dimm_c0, dimm_c1; dimm_c0 = intel_uncore_read(uncore, MAD_DIMM_C0); dimm_c1 = intel_uncore_read(uncore, MAD_DIMM_C1); dimm_c0 &= MAD_DIMM_A_SIZE_MASK | MAD_DIMM_B_SIZE_MASK; dimm_c1 &= MAD_DIMM_A_SIZE_MASK | MAD_DIMM_B_SIZE_MASK; /* * Enable swizzling when the channels are populated * with identically sized dimms. We don't need to check * the 3rd channel because no cpu with gpu attached * ships in that configuration. Also, swizzling only * makes sense for 2 channels anyway. */ if (dimm_c0 == dimm_c1) { swizzle_x = I915_BIT_6_SWIZZLE_9_10; swizzle_y = I915_BIT_6_SWIZZLE_9; } else { swizzle_x = I915_BIT_6_SWIZZLE_NONE; swizzle_y = I915_BIT_6_SWIZZLE_NONE; } } } else if (IS_GEN(i915, 5)) { /* * On Ironlake whatever DRAM config, GPU always do * same swizzling setup. */ swizzle_x = I915_BIT_6_SWIZZLE_9_10; swizzle_y = I915_BIT_6_SWIZZLE_9; } else if (IS_GEN(i915, 2)) { /* * As far as we know, the 865 doesn't have these bit 6 * swizzling issues. */ swizzle_x = I915_BIT_6_SWIZZLE_NONE; swizzle_y = I915_BIT_6_SWIZZLE_NONE; } else if (IS_G45(i915) || IS_I965G(i915) || IS_G33(i915)) { /* * The 965, G33, and newer, have a very flexible memory * configuration. It will enable dual-channel mode * (interleaving) on as much memory as it can, and the GPU * will additionally sometimes enable different bit 6 * swizzling for tiled objects from the CPU. * * Here's what I found on the G965: * slot fill memory size swizzling * 0A 0B 1A 1B 1-ch 2-ch * 512 0 0 0 512 0 O * 512 0 512 0 16 1008 X * 512 0 0 512 16 1008 X * 0 512 0 512 16 1008 X * 1024 1024 1024 0 2048 1024 O * * We could probably detect this based on either the DRB * matching, which was the case for the swizzling required in * the table above, or from the 1-ch value being less than * the minimum size of a rank. * * Reports indicate that the swizzling actually * varies depending upon page placement inside the * channels, i.e. we see swizzled pages where the * banks of memory are paired and unswizzled on the * uneven portion, so leave that as unknown. */ if (intel_uncore_read(uncore, C0DRB3) == intel_uncore_read(uncore, C1DRB3)) { swizzle_x = I915_BIT_6_SWIZZLE_9_10; swizzle_y = I915_BIT_6_SWIZZLE_9; } } else { u32 dcc = intel_uncore_read(uncore, DCC); /* * On 9xx chipsets, channel interleave by the CPU is * determined by DCC. For single-channel, neither the CPU * nor the GPU do swizzling. For dual channel interleaved, * the GPU's interleave is bit 9 and 10 for X tiled, and bit * 9 for Y tiled. The CPU's interleave is independent, and * can be based on either bit 11 (haven't seen this yet) or * bit 17 (common). */ switch (dcc & DCC_ADDRESSING_MODE_MASK) { case DCC_ADDRESSING_MODE_SINGLE_CHANNEL: case DCC_ADDRESSING_MODE_DUAL_CHANNEL_ASYMMETRIC: swizzle_x = I915_BIT_6_SWIZZLE_NONE; swizzle_y = I915_BIT_6_SWIZZLE_NONE; break; case DCC_ADDRESSING_MODE_DUAL_CHANNEL_INTERLEAVED: if (dcc & DCC_CHANNEL_XOR_DISABLE) { /* * This is the base swizzling by the GPU for * tiled buffers. */ swizzle_x = I915_BIT_6_SWIZZLE_9_10; swizzle_y = I915_BIT_6_SWIZZLE_9; } else if ((dcc & DCC_CHANNEL_XOR_BIT_17) == 0) { /* Bit 11 swizzling by the CPU in addition. */ swizzle_x = I915_BIT_6_SWIZZLE_9_10_11; swizzle_y = I915_BIT_6_SWIZZLE_9_11; } else { /* Bit 17 swizzling by the CPU in addition. */ swizzle_x = I915_BIT_6_SWIZZLE_9_10_17; swizzle_y = I915_BIT_6_SWIZZLE_9_17; } break; } /* check for L-shaped memory aka modified enhanced addressing */ if (IS_GEN(i915, 4) && !(intel_uncore_read(uncore, DCC2) & DCC2_MODIFIED_ENHANCED_DISABLE)) { swizzle_x = I915_BIT_6_SWIZZLE_UNKNOWN; swizzle_y = I915_BIT_6_SWIZZLE_UNKNOWN; } if (dcc == 0xffffffff) { drm_err(&i915->drm, "Couldn't read from MCHBAR. " "Disabling tiling.\n"); swizzle_x = I915_BIT_6_SWIZZLE_UNKNOWN; swizzle_y = I915_BIT_6_SWIZZLE_UNKNOWN; } } if (swizzle_x == I915_BIT_6_SWIZZLE_UNKNOWN || swizzle_y == I915_BIT_6_SWIZZLE_UNKNOWN) { /* * Userspace likes to explode if it sees unknown swizzling, * so lie. We will finish the lie when reporting through * the get-tiling-ioctl by reporting the physical swizzle * mode as unknown instead. * * As we don't strictly know what the swizzling is, it may be * bit17 dependent, and so we need to also prevent the pages * from being moved. */ i915->quirks |= QUIRK_PIN_SWIZZLED_PAGES; swizzle_x = I915_BIT_6_SWIZZLE_NONE; swizzle_y = I915_BIT_6_SWIZZLE_NONE; } i915->ggtt.bit_6_swizzle_x = swizzle_x; i915->ggtt.bit_6_swizzle_y = swizzle_y; } /* * Swap every 64 bytes of this page around, to account for it having a new * bit 17 of its physical address and therefore being interpreted differently * by the GPU. */ static void swizzle_page(struct page *page) { char temp[64]; char *vaddr; int i; vaddr = kmap(page); for (i = 0; i < PAGE_SIZE; i += 128) { memcpy(temp, &vaddr[i], 64); memcpy(&vaddr[i], &vaddr[i + 64], 64); memcpy(&vaddr[i + 64], temp, 64); } kunmap(page); } /** * i915_gem_object_do_bit_17_swizzle - fixup bit 17 swizzling * @obj: i915 GEM buffer object * @pages: the scattergather list of physical pages * * This function fixes up the swizzling in case any page frame number for this * object has changed in bit 17 since that state has been saved with * i915_gem_object_save_bit_17_swizzle(). * * This is called when pinning backing storage again, since the kernel is free * to move unpinned backing storage around (either by directly moving pages or * by swapping them out and back in again). */ void i915_gem_object_do_bit_17_swizzle(struct drm_i915_gem_object *obj, struct sg_table *pages) { struct sgt_iter sgt_iter; struct page *page; int i; if (obj->bit_17 == NULL) return; i = 0; for_each_sgt_page(page, sgt_iter, pages) { char new_bit_17 = page_to_phys(page) >> 17; if ((new_bit_17 & 0x1) != (test_bit(i, obj->bit_17) != 0)) { swizzle_page(page); set_page_dirty(page); } i++; } } /** * i915_gem_object_save_bit_17_swizzle - save bit 17 swizzling * @obj: i915 GEM buffer object * @pages: the scattergather list of physical pages * * This function saves the bit 17 of each page frame number so that swizzling * can be fixed up later on with i915_gem_object_do_bit_17_swizzle(). This must * be called before the backing storage can be unpinned. */ void i915_gem_object_save_bit_17_swizzle(struct drm_i915_gem_object *obj, struct sg_table *pages) { const unsigned int page_count = obj->base.size >> PAGE_SHIFT; struct sgt_iter sgt_iter; struct page *page; int i; if (obj->bit_17 == NULL) { obj->bit_17 = bitmap_zalloc(page_count, GFP_KERNEL); if (obj->bit_17 == NULL) { DRM_ERROR("Failed to allocate memory for bit 17 " "record\n"); return; } } i = 0; for_each_sgt_page(page, sgt_iter, pages) { if (page_to_phys(page) & (1 << 17)) __set_bit(i, obj->bit_17); else __clear_bit(i, obj->bit_17); i++; } } void intel_ggtt_init_fences(struct i915_ggtt *ggtt) { struct drm_i915_private *i915 = ggtt->vm.i915; struct intel_uncore *uncore = ggtt->vm.gt->uncore; int num_fences; int i; INIT_LIST_HEAD(&ggtt->fence_list); INIT_LIST_HEAD(&ggtt->userfault_list); intel_wakeref_auto_init(&ggtt->userfault_wakeref, uncore->rpm); detect_bit_6_swizzle(ggtt); if (!i915_ggtt_has_aperture(ggtt)) num_fences = 0; else if (INTEL_GEN(i915) >= 7 && !(IS_VALLEYVIEW(i915) || IS_CHERRYVIEW(i915))) num_fences = 32; else if (INTEL_GEN(i915) >= 4 || IS_I945G(i915) || IS_I945GM(i915) || IS_G33(i915) || IS_PINEVIEW(i915)) num_fences = 16; else num_fences = 8; if (intel_vgpu_active(i915)) num_fences = intel_uncore_read(uncore, vgtif_reg(avail_rs.fence_num)); ggtt->fence_regs = kcalloc(num_fences, sizeof(*ggtt->fence_regs), GFP_KERNEL); if (!ggtt->fence_regs) num_fences = 0; /* Initialize fence registers to zero */ for (i = 0; i < num_fences; i++) { struct i915_fence_reg *fence = &ggtt->fence_regs[i]; i915_active_init(&fence->active, NULL, NULL); fence->ggtt = ggtt; fence->id = i; list_add_tail(&fence->link, &ggtt->fence_list); } ggtt->num_fences = num_fences; intel_ggtt_restore_fences(ggtt); } void intel_ggtt_fini_fences(struct i915_ggtt *ggtt) { int i; for (i = 0; i < ggtt->num_fences; i++) { struct i915_fence_reg *fence = &ggtt->fence_regs[i]; i915_active_fini(&fence->active); } kfree(ggtt->fence_regs); } void intel_gt_init_swizzling(struct intel_gt *gt) { struct drm_i915_private *i915 = gt->i915; struct intel_uncore *uncore = gt->uncore; if (INTEL_GEN(i915) < 5 || i915->ggtt.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE) return; intel_uncore_rmw(uncore, DISP_ARB_CTL, 0, DISP_TILE_SURFACE_SWIZZLING); if (IS_GEN(i915, 5)) return; intel_uncore_rmw(uncore, TILECTL, 0, TILECTL_SWZCTL); if (IS_GEN(i915, 6)) intel_uncore_write(uncore, ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB)); else if (IS_GEN(i915, 7)) intel_uncore_write(uncore, ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB)); else if (IS_GEN(i915, 8)) intel_uncore_write(uncore, GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW)); else MISSING_CASE(INTEL_GEN(i915)); }
module Lijab module HooksHandler module_function @on_connect = [] @on_disconnect = [] @on_incoming_message = [] @on_presence = [] @on_pre_send_message = [] @on_post_send_message = [] def init @on_connect, @on_disconnect, @on_incoming_message, @on_presence = [], [], [], [] @on_pre_send_message, @on_post_send_message = [], [] Dir[File.join(Config.dirs[:hooks], '**', '*.rb')].each { |f| load f } Main.client.add_message_callback(&method(:handle_message)) Main.contacts.roster.add_presence_callback(&method(:handle_presence)) end def handle_message(msg) return unless msg.body && !msg.body.empty? @on_incoming_message.each do |b| b.call(Main.contacts[msg.from.strip], msg.body) end end def handle_presence(roster_item, old_p, new_p) @on_presence.each do |b| b.call(Main.contacts[roster_item.jid.strip], old_p, new_p) end end def handle_pre_send_message(contact, msg) return msg if @on_pre_send_message.empty? || !msg.body || msg.body.empty? @on_pre_send_message.inject(msg) do |ret_msg, block| args = [contact, ret_msg.body] args.push(msg) if block.arity == 3 m = block.call(*args) break if !m if m.is_a?(Jabber::Message) m else ret_msg.body = m.to_s ret_msg end end end def handle_post_send_message(contact, msg) return if !msg.body || msg.body.empty? @on_post_send_message.each do |block| args = [contact, msg.body] args.push(msg) if block.arity == 3 block.call(*args) end end def handle_connect @on_connect.each { |b| b.call } end def handle_disconnect @on_disconnect.each { |b| b.call } end attr_reader :on_connect, :on_disconnect, :on_incoming_message, :on_presence, :on_pre_send_message, :on_post_send_message module_function :on_connect, :on_disconnect, :on_incoming_message,:on_presence, :on_pre_send_message, :on_post_send_message end module Hooks module_function def on_incoming_message(&block) HooksHandler::on_incoming_message.push(block) end def on_presence(&block) HooksHandler::on_presence.push(block) end def on_pre_send_message(&block) HooksHandler::on_pre_send_message.push(block) end def on_post_send_message(&block) HooksHandler::on_post_send_message.push(block) end def on_connect(&block) HooksHandler::on_connect.push(block) end def on_disconnect(&block) HooksHandler::on_disconnect.push(block) end end end
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef THRIFT_PY_PROTOCOL_H #define THRIFT_PY_PROTOCOL_H #include "ext/types.h" #include <limits> #include <stack> #include <stdint.h> namespace apache { namespace thrift { namespace py { template <typename Impl> class ProtocolBase { public: ProtocolBase() : stringLimit_(std::numeric_limits<int32_t>::max()), containerLimit_(std::numeric_limits<int32_t>::max()), output_(NULL) {} inline virtual ~ProtocolBase(); bool prepareDecodeBufferFromTransport(PyObject* trans); PyObject* readStruct(PyObject* output, PyObject* klass, PyObject* spec_seq, bool immutable); bool prepareEncodeBuffer(); bool encodeValue(PyObject* value, TType type, PyObject* typeargs); PyObject* getEncodedValue(); long stringLimit() const { return stringLimit_; } void setStringLengthLimit(long limit) { stringLimit_ = limit; } long containerLimit() const { return containerLimit_; } void setContainerLengthLimit(long limit) { containerLimit_ = limit; } protected: bool readBytes(char** output, int len); bool readByte(uint8_t& val) { char* buf; if (!readBytes(&buf, 1)) { return false; } val = static_cast<uint8_t>(buf[0]); return true; } bool writeBuffer(char* data, size_t len); void writeByte(uint8_t val) { writeBuffer(reinterpret_cast<char*>(&val), 1); } PyObject* decodeValue(TType type, PyObject* typeargs); bool skip(TType type); inline bool checkType(TType got, TType expected); inline bool checkLengthLimit(int32_t len, long limit); inline bool isUtf8(PyObject* typeargs); inline bool inImmutableContext() { return immutabilityStack_.top(); } std::stack<bool> immutabilityStack_; private: Impl* impl() { return static_cast<Impl*>(this); } long stringLimit_; long containerLimit_; EncodeBuffer* output_; DecodeBuffer input_; }; } } } #include "ext/protocol.tcc" #endif // THRIFT_PY_PROTOCOL_H
require 'test_helper' class PathSetterTest < TestBase class Testing include Wardrobe plugin :path_setter attribute :bar, String, path: 'this/is/a/0/nested' attribute :foo, String, path: 'foo/bar' attribute :boolean, Wardrobe::Boolean, path: 'a/nested/boolean' attribute :array, String, path: %w(this/is/a/0/nested this/is/another/0/nested) end def test_path_setter_success foo = Testing.new({ this: { is: { a: [{ nested: 'thing'}]}}}) assert_equal 'thing', foo.bar end def test_path_array_setter_success_first foo = Testing.new({ this: { is: { a: [{ nested: 'first'}], another: [{ nested: 'second'}]}}}) assert_equal 'first', foo.array end def test_path_array_setter_success_second foo = Testing.new({ this: { is: { another: [{ nested: 'second'}]}}}) assert_equal 'second', foo.array end def test_path_setter_missing foo = Testing.new({ this: { is: {}}}) assert_nil foo.bar end def test_path_setter_missing_key foo = Testing.new({ this: { not: {}}}) assert_nil foo.bar end def test_path_setter_string_in_array assert_raises(Wardrobe::Refinements::Path::PathError) do Testing.new({ this: []}) end end def test_foo_conflict instance = Testing.new({ foo: { bar: 'Test'}}) assert_equal 'Test', instance.foo end def test_non_path_init instance = Testing.new(bar: 'Aye', foo: 'Nay') assert_equal 'Aye', instance.bar assert_equal 'Nay', instance.foo end def test_false_boolean instance = Testing.new({ a: { nested: { boolean: false}}}) assert_equal false, instance.boolean end end
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com using System; using System.Net; using System.Runtime.Serialization; namespace NetExtender.AspNet.Core.Exceptions { [Serializable] public class ServiceException : Exception { public HttpStatusCode StatusCode { get; } = HttpStatusCode.InternalServerError; public ServiceException() { } public ServiceException(String message) : base(message) { } public ServiceException(String message, Exception innerException) : base(message, innerException) { } public ServiceException(HttpStatusCode code) { StatusCode = code; } public ServiceException(HttpStatusCode code, String message) : base(message) { StatusCode = code; } public ServiceException(HttpStatusCode code, String message, Exception innerException) : base(message, innerException) { StatusCode = code; } protected ServiceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
<?php /** * Created by PhpStorm. * User: HGN * Date: 2018/7/16 * Time: 23:25 */ namespace app\teacher\controller; use think\Controller; class Cig extends Controller { public function index(){ $week = db('config')->where('config_key', '=', 'week')->value('config_val'); $week = date("Y-m-d ", $week); $this->assign('week', $week); return $this->fetch('index'); } public function editWeek(){ $week = input('post.week'); $week = strtotime($week); $res = db('config')->where('config_key', '=', 'week')->update(['config_val' => $week]); if ($res) { return json(['valid' => 1, 'msg' => '设置成功']); } else { return json(['valid' => 0, 'msg' => '设置失败']); } } }
import { noop } from '../helper'; import { Howl } from 'howler'; type HowlerInstance = Howl | null; export default function getAPI(howler: HowlerInstance) { if (!howler) return (): Record<string, typeof noop> => new Proxy( {}, { get: (_, prop) => { if (prop === '_howler') return Howl; if (prop === 'seek') return () => 0; return noop; }, } ); return () => ({ _playing: howler.playing.bind(howler), /** * Begins playback of a sound when not playing */ play() { if (!this._playing()) { // Automatically load if we're trying to play // and the howl is not loaded if (this.state() === 'unloaded') howler.load(); howler.play(); } }, /** * Pauses playback of sound or group * If no id given, pauses all playback * @param {Number} id = undefined [sound of group to pause] */ pause: howler.pause.bind(howler), /** * NOTE: no limitation of naming for state :) * Check the load status of the Howl * @return {String} [unloaded, loading or loaded] */ state() { return howler.state(); }, /** * Mutes the sound, but doesn't pause the playback. * @param {Boolean} [muted] [True to mute and false to unmute] * @param {Number} [id] [The sound ID. If none is passed, all sounds in group are muted] */ mute: howler.mute, /** * Get/set the rate of playback for a sound. This method optionally takes 0, 1 or 2 arguments. * @param {Number} [rate] - The rate of playback. 0.5 to 4.0, with 1.0 being normal speed. * @param {Number} [id] - The sound ID. If none is passed, playback rate of all sounds in group will change. */ rate: howler.rate.bind(howler), /** * load audio file */ load: howler.load.bind(howler), /** * Howler instance with all of its functionality */ _howler: howler, }); } // reference api in destroy export type APITypes = ReturnType<ReturnType<typeof getAPI>>;
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.features.logging import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.client.tests.utils.* import kotlinx.io.core.* import kotlin.test.* class RemoteTests : ClientLoader() { @Test fun testDownloadWithNoneLogLevel() = clientTests { config { install(Logging) { level = LogLevel.NONE } } test { client -> val size = 4 * 1024 * 1024 client.get<HttpResponse>("$TEST_SERVER/bytes?size=$size").use { assertEquals(size, it.readBytes().size) } } } }
<?php /** * Created by PhpStorm. * User: Harry * Date: 15-5-2018 * Time: 16:21 */ namespace NIOLAB\oauth2\components\repositories; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException; use NIOLAB\oauth2\models\AccessToken; use NIOLAB\oauth2\models\Scope; use yii\helpers\Json; class AccessTokenRepository implements \League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface { /** * Create a new access token * * @param ClientEntityInterface $clientEntity * @param ScopeEntityInterface[] $scopes * @param mixed $userIdentifier * * @return AccessTokenEntityInterface */ public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null) { $token = new AccessToken(); $token->setClient($clientEntity); $token->setUserIdentifier($userIdentifier); foreach ($scopes as $scope) { $token->addScope($scope); } if (!$token->validate()) { throw OAuthServerException::serverError('Could not get new token: '.Json::encode($token->getErrors())); } return $token; } /** * @inheritDoc */ public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity) { if ($accessTokenEntity instanceof AccessToken) { $accessTokenEntity->expired_at = $accessTokenEntity->getExpiryDateTime()->getTimestamp(); if ($accessTokenEntity->save()) { $scopeIdentifiers = $accessTokenEntity->getScopes(); $scopes = Scope::findAll(['identifier' => $scopeIdentifiers]); foreach ($scopes as $scope) { if ($scope instanceof Scope) { $accessTokenEntity->link('relatedScopes', $scope); } } } } } /** * Revoke an access token. * * @param string $tokenId */ public function revokeAccessToken($tokenId) { $token = AccessToken::find()->where(['identifier'=>$tokenId])->one(); if ($token instanceof AccessToken) { $token->updateAttributes(['status' => AccessToken::STATUS_REVOKED]); } } /** * Check if the access token has been revoked. * * @param string $tokenId * * @return bool Return true if this token has been revoked */ public function isAccessTokenRevoked($tokenId) { $token = AccessToken::find()->where(['identifier'=>$tokenId])->one(); return $token === null || $token->status == AccessToken::STATUS_REVOKED; } }
#!/bin/bash #mkdir data #mkdir output # download bert.ckpt, move to pretrained_model #python data_processor.py python run_classifier.py \ --task_name baidu_95 \ --do_train False \ --do_eval true \ --do_predict true \ --data_dir data/all_labels \ --vocab_file pretrained_model/chinese_L-12_H-768_A-12/vocab.txt \ --bert_config_file pretrained_model/chinese_L-12_H-768_A-12/bert_config.json \ --init_checkpoint pretrained_model/chinese_L-12_H-768_A-12/bert_model.ckpt \ --max_seq_length 128 \ --train_batch_size 32 \ --learning_rate 2e-5 \ --num_train_epochs 6.0 \ --output_dir ./output/epochs6_baidu_95/ # evaluate test #python evaluate_test.py
<?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class SettingsTableSeeder extends Seeder { public function run() { DB::table('settings')->delete(); $record = [ [ 'id' => '1', 'website_title' => 'HeavenTech', 'website_description' => '', 'website_metakeyword' =>'', 'website_email' =>'', 'facebook' => 'https://www.facebook.com/pages/Heaven-Tech/1639277706297947', 'twitter' => 'https://twitter.com/Heaven_Techno' ] ]; DB::table('settings')->insert($record); } }
package utils import ( "testing" ) var ( // to verify whether the service is able to respond and request to multiple website urls urlsDiff = []string{ "https://www.google.co.in/", "https://www.google.co.in/search?q=hello", "https://www.facebook.com/", "https://www.yahoo.com/", } // to verify whether the filters are working as expected or not urlsPermute = []string{ "https:www.google.co.in", "http:www.google.co.in", "google.co.in/", "//www.google.co.in", } ) func TestCLIPing(t *testing.T) { // testing packets on diff urls for _, ele := range urlsDiff { resp, err := CLIPing(ele, 2) if err != nil { t.Errorf("err requesting %s\n", ele) } else { t.Logf("%s\n", *resp) } } // testing packets on permutative urls for _, ele := range urlsPermute { _, err := CLIPing(ele, 2) if err != nil { t.Errorf("err requesting %s\n", ele) } } }
# DesignNXT-Dashboards The sample repository for DesignNXT 2019 .Net Integrations workshops Presentation - https://docs.google.com/presentation/d/1FNgMnPYlj33wi4JoHRaWFEO5YfqBXpZddswW5ezSZoo/edit?usp=sharing Workshop Downloads - https://visualstudio.microsoft.com/vs/community/ - https://marketplace.visualstudio.com/items?itemName=McNeel.GrasshopperAssemblyforv6 - https://marketplace.visualstudio.com/items?itemName=McNeel.RhinoCommontemplatesforv6 Additional Workshop Resources - https://www.nuget.org/packages/rhinocommon - https://www.nuget.org/packages/Grasshopper/7.0.19233.6455-wip - https://www.nuget.org/packages/LiveCharts/ - https://www.nuget.org/packages/LiveCharts.Wpf/ - https://www.nuget.org/packages/MaterialDesignThemes/3.0.0-ci492 - https://www.nuget.org/packages/Extended.Wpf.Toolkit/ - https://www.nuget.org/packages/HelixToolkit/ - https://www.nuget.org/packages/HelixToolkit.Wpf/
[CopyrightLicense]:./license.md # oscicen | Lusca Andrei Hi and welcome to my online hideout.
<?php declare(strict_types = 1); namespace Innmind\SilentCartographer\SendActivity; use Innmind\SilentCartographer\{ SendActivity, Room, Room\Program, Room\Program\Activity, Room\Program\Type, Protocol, RoomActivity, IPC\Process\NullProcess, }; use Innmind\OperatingSystem\CurrentProcess; use Innmind\IPC\{ IPC as IPCInterface, Process, Process\Name, Exception\MessageNotSent, Exception\FailedToConnect, }; final class IPC implements SendActivity { private Room $room; private Type $type; private CurrentProcess $process; private Protocol $protocol; private IPCInterface $ipc; private Name $subRoutine; private ?Process $client = null; public function __construct( Room $room, Type $type, CurrentProcess $process, Protocol $protocol, IPCInterface $ipc, Name $subRoutine ) { $this->room = $room; $this->type = $type; $this->process = $process; $this->protocol = $protocol; $this->ipc = $ipc; $this->subRoutine = $subRoutine; } public function __invoke(Activity $activity): void { // we access the pid here instead of at construct time to allow to always // have the correct pid in case of a fork of the process try { $this->client()->send( $this->protocol->encode(new RoomActivity( new Program( $this->process->id(), $this->type, $this->room, ), $activity, )), ); } catch (MessageNotSent $e) { // nothing to do } } private function client(): Process { if (!$this->ipc->exist($this->subRoutine)) { return new NullProcess($this->subRoutine); } if ($this->client instanceof Process && $this->client->closed()) { $this->client = null; return $this->client(); } try { return $this->client ??= $this->ipc->get($this->subRoutine); } catch (FailedToConnect $e) { return new NullProcess($this->subRoutine); } } }
<md-dialog aria-label="Add New Class"> <form ng-cloak name="addClassForm" novalidate=""> <md-toolbar> <div class="md-toolbar-tools"> <h2>Add New Class</h2> <span flex></span> <md-button class="md-icon-button" ng-click="cancel()"> <md-icon md-svg-src="assets/img/cd-icon-close.svg" aria-label="Close dialog"></md-icon> </md-button> </div> </md-toolbar> <md-dialog-content> <div class="md-dialog-content"> <md-input-container class="md-block" flex-gt-sm=""> <label>Class name</label> <input ng-model="class.class_name" name="name" required="true"> <div ng-messages="addClassForm.name.$error" role="alert"> <div ng-message="required"> Class Name is required </div> </div> </md-input-container> <md-input-container class="md-block" flex-gt-sm=""> <label>Section</label> <input ng-model="class.section" name="section" required="true"> <div ng-messages="addClassForm.section.$error" role="alert"> <div ng-message="required"> You must give a section name </div> </div> </md-input-container> <md-input-container class="md-block" flex-gt-sm=""> <label>Total Students</label> <input ng-model="class.total_student" name="total" type="number" required="true"> <div ng-messages="addClassForm.total.$error" role="alert"> <div ng-message="required"> You must include total student quantity </div> </div> </md-input-container> </div> </md-dialog-content> <md-dialog-actions layout="row"> <span flex></span> <md-button ng-click="answer('cancel',addClassForm)"> Cancel </md-button> <md-button ng-click="answer(class,addClassForm)"> Add </md-button> </md-dialog-actions> </form> </md-dialog>
# frozen_string_literal: true require "rails_helper" describe DegreesHelper do include DegreesHelper describe "#hesa_degree_types_options" do let(:degree_type) { "Bachelor of Arts" } let(:degree_abbreviation) { "BA" } let(:non_uk_degree_type) { "Unknown" } let(:non_uk_degree_types) { %w[Unknown] } before do stub_const("Dttp::CodeSets::DegreeTypes::NON_UK", [non_uk_degree_type]) stub_const("Dttp::CodeSets::DegreeTypes::MAPPING", { degree_type => { abbreviation: degree_abbreviation }, non_uk_degree_type => { abbreviation: nil }, }) end it "iterates over array and prints out correct hesa_degree_types values" do expect(hesa_degree_types_options).to match([ OpenStruct.new(option_name: nil, option_value: nil), OpenStruct.new(option_name: "#{degree_type} (#{degree_abbreviation})", option_value: degree_type), ]) end end describe "#institutions_options" do before do allow(self).to receive(:institutions).and_return(%w[institution]) end it "iterates over array and prints out correct institutions values" do expect(institutions_options.size).to be 2 expect(institutions_options.first.name).to be_nil expect(institutions_options.second.name).to eq "institution" end end describe "#subjects_options" do before do allow(self).to receive(:subjects).and_return(%w[subject]) end it "iterates over array and prints out correct subjects values" do expect(subjects_options.size).to be 2 expect(subjects_options.first.name).to be_nil expect(subjects_options.second.name).to eq "subject" end end describe "#countries_options" do before do allow(self).to receive(:countries).and_return(%w[country]) end it "iterates over array and prints out correct countries values" do expect(countries_options.size).to be 2 expect(countries_options.first.name).to be_nil expect(countries_options.second.name).to eq "country" end end end
/* * Copyright 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "sdk/android/src/jni/pc/peerconnectionfactory.h" #include <memory> #include <utility> #include "api/video_codecs/video_decoder_factory.h" #include "api/video_codecs/video_encoder_factory.h" #include "media/base/mediaengine.h" #include "modules/audio_device/include/audio_device.h" #include "modules/utility/include/jvm_android.h" // We don't depend on the audio processing module implementation. // The user may pass in a nullptr. #include "modules/audio_processing/include/audio_processing.h" // nogncheck #include "rtc_base/event_tracer.h" #include "rtc_base/stringutils.h" #include "rtc_base/thread.h" #include "sdk/android/generated_peerconnection_jni/jni/PeerConnectionFactory_jni.h" #include "sdk/android/native_api/jni/java_types.h" #include "sdk/android/src/jni/jni_helpers.h" #include "sdk/android/src/jni/pc/androidnetworkmonitor.h" #include "sdk/android/src/jni/pc/audio.h" #include "sdk/android/src/jni/pc/icecandidate.h" #include "sdk/android/src/jni/pc/media.h" #include "sdk/android/src/jni/pc/ownedfactoryandthreads.h" #include "sdk/android/src/jni/pc/peerconnection.h" #include "sdk/android/src/jni/pc/video.h" #include "system_wrappers/include/field_trial.h" // Adding 'nogncheck' to disable the gn include headers check. // We don't want to depend on 'system_wrappers:field_trial_default' because // clients should be able to provide their own implementation. #include "system_wrappers/include/field_trial_default.h" // nogncheck namespace webrtc { namespace jni { namespace { PeerConnectionFactoryInterface::Options JavaToNativePeerConnectionFactoryOptions(JNIEnv* jni, const JavaRef<jobject>& options) { int network_ignore_mask = Java_Options_getNetworkIgnoreMask(jni, options); bool disable_encryption = Java_Options_getDisableEncryption(jni, options); bool disable_network_monitor = Java_Options_getDisableNetworkMonitor(jni, options); bool enable_aes128_sha1_32_crypto_cipher = Java_Options_getEnableAes128Sha1_32CryptoCipher(jni, options); PeerConnectionFactoryInterface::Options native_options; // This doesn't necessarily match the c++ version of this struct; feel free // to add more parameters as necessary. native_options.network_ignore_mask = network_ignore_mask; native_options.disable_encryption = disable_encryption; native_options.disable_network_monitor = disable_network_monitor; native_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = enable_aes128_sha1_32_crypto_cipher; return native_options; } } // namespace // Note: Some of the video-specific PeerConnectionFactory methods are // implemented in "video.cc". This is done so that if an application // doesn't need video support, it can just link with "null_video.cc" // instead of "video.cc", which doesn't bring in the video-specific // dependencies. // Field trials initialization string static char* field_trials_init_string = nullptr; // Set in PeerConnectionFactory_initializeAndroidGlobals(). static bool factory_static_initialized = false; static bool video_hw_acceleration_enabled = true; void PeerConnectionFactoryNetworkThreadReady() { RTC_LOG(LS_INFO) << "Network thread JavaCallback"; JNIEnv* env = AttachCurrentThreadIfNeeded(); Java_PeerConnectionFactory_onNetworkThreadReady(env); } void PeerConnectionFactoryWorkerThreadReady() { RTC_LOG(LS_INFO) << "Worker thread JavaCallback"; JNIEnv* env = AttachCurrentThreadIfNeeded(); Java_PeerConnectionFactory_onWorkerThreadReady(env); } void PeerConnectionFactorySignalingThreadReady() { RTC_LOG(LS_INFO) << "Signaling thread JavaCallback"; JNIEnv* env = AttachCurrentThreadIfNeeded(); Java_PeerConnectionFactory_onSignalingThreadReady(env); } jobject NativeToJavaPeerConnectionFactory( JNIEnv* jni, rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> pcf, std::unique_ptr<rtc::Thread> network_thread, std::unique_ptr<rtc::Thread> worker_thread, std::unique_ptr<rtc::Thread> signaling_thread, rtc::NetworkMonitorFactory* network_monitor_factory) { jni::OwnedFactoryAndThreads* owned_factory = new jni::OwnedFactoryAndThreads( std::move(network_thread), std::move(worker_thread), std::move(signaling_thread), nullptr /* legacy_encoder_factory */, nullptr /* legacy_decoder_factory */, network_monitor_factory, pcf.release()); owned_factory->InvokeJavaCallbacksOnFactoryThreads(); return Java_PeerConnectionFactory_Constructor( jni, NativeToJavaPointer(owned_factory)) .Release(); } static void JNI_PeerConnectionFactory_InitializeAndroidGlobals( JNIEnv* jni, const JavaParamRef<jclass>&, jboolean video_hw_acceleration) { video_hw_acceleration_enabled = video_hw_acceleration; if (!factory_static_initialized) { JVM::Initialize(GetJVM()); factory_static_initialized = true; } } static void JNI_PeerConnectionFactory_InitializeFieldTrials( JNIEnv* jni, const JavaParamRef<jclass>&, const JavaParamRef<jstring>& j_trials_init_string) { field_trials_init_string = NULL; if (!j_trials_init_string.is_null()) { const char* init_string = jni->GetStringUTFChars(j_trials_init_string.obj(), NULL); int init_string_length = jni->GetStringUTFLength(j_trials_init_string.obj()); field_trials_init_string = new char[init_string_length + 1]; rtc::strcpyn(field_trials_init_string, init_string_length + 1, init_string); jni->ReleaseStringUTFChars(j_trials_init_string.obj(), init_string); RTC_LOG(LS_INFO) << "initializeFieldTrials: " << field_trials_init_string; } field_trial::InitFieldTrialsFromString(field_trials_init_string); } static void JNI_PeerConnectionFactory_InitializeInternalTracer( JNIEnv* jni, const JavaParamRef<jclass>&) { rtc::tracing::SetupInternalTracer(); } static ScopedJavaLocalRef<jstring> JNI_PeerConnectionFactory_FindFieldTrialsFullName( JNIEnv* jni, const JavaParamRef<jclass>&, const JavaParamRef<jstring>& j_name) { return NativeToJavaString( jni, field_trial::FindFullName(JavaToStdString(jni, j_name))); } static jboolean JNI_PeerConnectionFactory_StartInternalTracingCapture( JNIEnv* jni, const JavaParamRef<jclass>&, const JavaParamRef<jstring>& j_event_tracing_filename) { if (j_event_tracing_filename.is_null()) return false; const char* init_string = jni->GetStringUTFChars(j_event_tracing_filename.obj(), NULL); RTC_LOG(LS_INFO) << "Starting internal tracing to: " << init_string; bool ret = rtc::tracing::StartInternalCapture(init_string); jni->ReleaseStringUTFChars(j_event_tracing_filename.obj(), init_string); return ret; } static void JNI_PeerConnectionFactory_StopInternalTracingCapture( JNIEnv* jni, const JavaParamRef<jclass>&) { rtc::tracing::StopInternalCapture(); } static void JNI_PeerConnectionFactory_ShutdownInternalTracer( JNIEnv* jni, const JavaParamRef<jclass>&) { rtc::tracing::ShutdownInternalTracer(); } jlong CreatePeerConnectionFactoryForJava( JNIEnv* jni, const JavaParamRef<jobject>& jcontext, const JavaParamRef<jobject>& joptions, rtc::scoped_refptr<AudioDeviceModule> audio_device_module, const JavaParamRef<jobject>& jencoder_factory, const JavaParamRef<jobject>& jdecoder_factory, rtc::scoped_refptr<AudioProcessing> audio_processor, std::unique_ptr<FecControllerFactoryInterface> fec_controller_factory) { // talk/ assumes pretty widely that the current Thread is ThreadManager'd, but // ThreadManager only WrapCurrentThread()s the thread where it is first // created. Since the semantics around when auto-wrapping happens in // webrtc/rtc_base/ are convoluted, we simply wrap here to avoid having to // think about ramifications of auto-wrapping there. rtc::ThreadManager::Instance()->WrapCurrentThread(); std::unique_ptr<rtc::Thread> network_thread = rtc::Thread::CreateWithSocketServer(); network_thread->SetName("network_thread", nullptr); RTC_CHECK(network_thread->Start()) << "Failed to start thread"; std::unique_ptr<rtc::Thread> worker_thread = rtc::Thread::Create(); worker_thread->SetName("worker_thread", nullptr); RTC_CHECK(worker_thread->Start()) << "Failed to start thread"; std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create(); signaling_thread->SetName("signaling_thread", NULL); RTC_CHECK(signaling_thread->Start()) << "Failed to start thread"; rtc::NetworkMonitorFactory* network_monitor_factory = nullptr; auto audio_encoder_factory = CreateAudioEncoderFactory(); auto audio_decoder_factory = CreateAudioDecoderFactory(); PeerConnectionFactoryInterface::Options options; bool has_options = !joptions.is_null(); if (has_options) { options = JavaToNativePeerConnectionFactoryOptions(jni, joptions); } // Do not create network_monitor_factory only if the options are // provided and disable_network_monitor therein is set to true. if (!(has_options && options.disable_network_monitor)) { network_monitor_factory = new AndroidNetworkMonitorFactory(); rtc::NetworkMonitorFactory::SetFactory(network_monitor_factory); } rtc::scoped_refptr<AudioMixer> audio_mixer = nullptr; std::unique_ptr<CallFactoryInterface> call_factory(CreateCallFactory()); std::unique_ptr<RtcEventLogFactoryInterface> rtc_event_log_factory( CreateRtcEventLogFactory()); cricket::WebRtcVideoEncoderFactory* legacy_video_encoder_factory = nullptr; cricket::WebRtcVideoDecoderFactory* legacy_video_decoder_factory = nullptr; std::unique_ptr<cricket::MediaEngineInterface> media_engine; if (jencoder_factory.is_null() && jdecoder_factory.is_null()) { #if defined(USE_BUILTIN_SW_CODECS) // This uses the legacy API, which automatically uses the internal SW // codecs in WebRTC. if (video_hw_acceleration_enabled) { legacy_video_encoder_factory = CreateLegacyVideoEncoderFactory(); legacy_video_decoder_factory = CreateLegacyVideoDecoderFactory(); } media_engine.reset(CreateMediaEngine( audio_device_module, audio_encoder_factory, audio_decoder_factory, legacy_video_encoder_factory, legacy_video_decoder_factory, audio_mixer, audio_processor)); #endif } else { // This uses the new API, does not automatically include software codecs. std::unique_ptr<VideoEncoderFactory> video_encoder_factory = nullptr; if (jencoder_factory.is_null()) { #if defined(USE_BUILTIN_SW_CODECS) legacy_video_encoder_factory = CreateLegacyVideoEncoderFactory(); video_encoder_factory = std::unique_ptr<VideoEncoderFactory>( WrapLegacyVideoEncoderFactory(legacy_video_encoder_factory)); #endif } else { video_encoder_factory = std::unique_ptr<VideoEncoderFactory>( CreateVideoEncoderFactory(jni, jencoder_factory)); } std::unique_ptr<VideoDecoderFactory> video_decoder_factory = nullptr; if (jdecoder_factory.is_null()) { #if defined(USE_BUILTIN_SW_CODECS) legacy_video_decoder_factory = CreateLegacyVideoDecoderFactory(); video_decoder_factory = std::unique_ptr<VideoDecoderFactory>( WrapLegacyVideoDecoderFactory(legacy_video_decoder_factory)); #endif } else { video_decoder_factory = std::unique_ptr<VideoDecoderFactory>( CreateVideoDecoderFactory(jni, jdecoder_factory)); } media_engine.reset(CreateMediaEngine( audio_device_module, audio_encoder_factory, audio_decoder_factory, std::move(video_encoder_factory), std::move(video_decoder_factory), audio_mixer, audio_processor)); } rtc::scoped_refptr<PeerConnectionFactoryInterface> factory( CreateModularPeerConnectionFactory( network_thread.get(), worker_thread.get(), signaling_thread.get(), std::move(media_engine), std::move(call_factory), std::move(rtc_event_log_factory), std::move(fec_controller_factory))); RTC_CHECK(factory) << "Failed to create the peer connection factory; " << "WebRTC/libjingle init likely failed on this device"; // TODO(honghaiz): Maybe put the options as the argument of // CreatePeerConnectionFactory. if (has_options) { factory->SetOptions(options); } OwnedFactoryAndThreads* owned_factory = new OwnedFactoryAndThreads( std::move(network_thread), std::move(worker_thread), std::move(signaling_thread), legacy_video_encoder_factory, legacy_video_decoder_factory, network_monitor_factory, factory.release()); owned_factory->InvokeJavaCallbacksOnFactoryThreads(); return jlongFromPointer(owned_factory); } static jlong JNI_PeerConnectionFactory_CreatePeerConnectionFactory( JNIEnv* jni, const JavaParamRef<jclass>&, const JavaParamRef<jobject>& jcontext, const JavaParamRef<jobject>& joptions, jlong native_audio_device_module, const JavaParamRef<jobject>& jencoder_factory, const JavaParamRef<jobject>& jdecoder_factory, jlong native_audio_processor, jlong native_fec_controller_factory) { rtc::scoped_refptr<AudioProcessing> audio_processor = reinterpret_cast<AudioProcessing*>(native_audio_processor); std::unique_ptr<FecControllerFactoryInterface> fec_controller_factory( reinterpret_cast<FecControllerFactoryInterface*>( native_fec_controller_factory)); return CreatePeerConnectionFactoryForJava( jni, jcontext, joptions, reinterpret_cast<AudioDeviceModule*>(native_audio_device_module), jencoder_factory, jdecoder_factory, audio_processor ? audio_processor : CreateAudioProcessing(), std::move(fec_controller_factory)); } static void JNI_PeerConnectionFactory_FreeFactory(JNIEnv*, const JavaParamRef<jclass>&, jlong j_p) { delete reinterpret_cast<OwnedFactoryAndThreads*>(j_p); if (field_trials_init_string) { field_trial::InitFieldTrialsFromString(NULL); delete field_trials_init_string; field_trials_init_string = NULL; } } static void JNI_PeerConnectionFactory_InvokeThreadsCallbacks( JNIEnv*, const JavaParamRef<jclass>&, jlong j_p) { OwnedFactoryAndThreads* factory = reinterpret_cast<OwnedFactoryAndThreads*>(j_p); factory->InvokeJavaCallbacksOnFactoryThreads(); } static jlong JNI_PeerConnectionFactory_CreateLocalMediaStream( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory, const JavaParamRef<jstring>& label) { rtc::scoped_refptr<PeerConnectionFactoryInterface> factory( factoryFromJava(native_factory)); rtc::scoped_refptr<MediaStreamInterface> stream( factory->CreateLocalMediaStream(JavaToStdString(jni, label))); return jlongFromPointer(stream.release()); } static jlong JNI_PeerConnectionFactory_CreateAudioSource( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory, const JavaParamRef<jobject>& j_constraints) { std::unique_ptr<MediaConstraintsInterface> constraints = JavaToNativeMediaConstraints(jni, j_constraints); rtc::scoped_refptr<PeerConnectionFactoryInterface> factory( factoryFromJava(native_factory)); cricket::AudioOptions options; CopyConstraintsIntoAudioOptions(constraints.get(), &options); rtc::scoped_refptr<AudioSourceInterface> source( factory->CreateAudioSource(options)); return jlongFromPointer(source.release()); } jlong JNI_PeerConnectionFactory_CreateAudioTrack( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory, const JavaParamRef<jstring>& id, jlong native_source) { rtc::scoped_refptr<PeerConnectionFactoryInterface> factory( factoryFromJava(native_factory)); rtc::scoped_refptr<AudioTrackInterface> track(factory->CreateAudioTrack( JavaToStdString(jni, id), reinterpret_cast<AudioSourceInterface*>(native_source))); return jlongFromPointer(track.release()); } static jboolean JNI_PeerConnectionFactory_StartAecDump( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory, jint file, jint filesize_limit_bytes) { rtc::scoped_refptr<PeerConnectionFactoryInterface> factory( factoryFromJava(native_factory)); return factory->StartAecDump(file, filesize_limit_bytes); } static void JNI_PeerConnectionFactory_StopAecDump(JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory) { rtc::scoped_refptr<PeerConnectionFactoryInterface> factory( factoryFromJava(native_factory)); factory->StopAecDump(); } static jlong JNI_PeerConnectionFactory_CreatePeerConnection( JNIEnv* jni, const JavaParamRef<jclass>&, jlong factory, const JavaParamRef<jobject>& j_rtc_config, const JavaParamRef<jobject>& j_constraints, jlong observer_p) { rtc::scoped_refptr<PeerConnectionFactoryInterface> f( reinterpret_cast<PeerConnectionFactoryInterface*>( factoryFromJava(factory))); std::unique_ptr<PeerConnectionObserver> observer( reinterpret_cast<PeerConnectionObserver*>(observer_p)); PeerConnectionInterface::RTCConfiguration rtc_config( PeerConnectionInterface::RTCConfigurationType::kAggressive); JavaToNativeRTCConfiguration(jni, j_rtc_config, &rtc_config); // Generate non-default certificate. rtc::KeyType key_type = GetRtcConfigKeyType(jni, j_rtc_config); if (key_type != rtc::KT_DEFAULT) { rtc::scoped_refptr<rtc::RTCCertificate> certificate = rtc::RTCCertificateGenerator::GenerateCertificate( rtc::KeyParams(key_type), rtc::nullopt); if (!certificate) { RTC_LOG(LS_ERROR) << "Failed to generate certificate. KeyType: " << key_type; return 0; } rtc_config.certificates.push_back(certificate); } std::unique_ptr<MediaConstraintsInterface> constraints; if (!j_constraints.is_null()) { constraints = JavaToNativeMediaConstraints(jni, j_constraints); CopyConstraintsIntoRtcConfiguration(constraints.get(), &rtc_config); } rtc::scoped_refptr<PeerConnectionInterface> pc( f->CreatePeerConnection(rtc_config, nullptr, nullptr, observer.get())); return jlongFromPointer( new OwnedPeerConnection(pc, std::move(observer), std::move(constraints))); } static jlong JNI_PeerConnectionFactory_CreateVideoSource( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory, jboolean is_screencast) { OwnedFactoryAndThreads* factory = reinterpret_cast<OwnedFactoryAndThreads*>(native_factory); return jlongFromPointer(CreateVideoSource(jni, factory->signaling_thread(), factory->worker_thread(), is_screencast)); } static jlong JNI_PeerConnectionFactory_CreateVideoTrack( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory, const JavaParamRef<jstring>& id, jlong native_source) { rtc::scoped_refptr<PeerConnectionFactoryInterface> factory( factoryFromJava(native_factory)); rtc::scoped_refptr<VideoTrackInterface> track(factory->CreateVideoTrack( JavaToStdString(jni, id), reinterpret_cast<VideoTrackSourceInterface*>(native_source))); return jlongFromPointer(track.release()); } static void JNI_PeerConnectionFactory_SetVideoHwAccelerationOptions( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory, const JavaParamRef<jobject>& local_egl_context, const JavaParamRef<jobject>& remote_egl_context) { #if defined(USE_BUILTIN_SW_CODECS) OwnedFactoryAndThreads* owned_factory = reinterpret_cast<OwnedFactoryAndThreads*>(native_factory); SetEglContext(jni, owned_factory->legacy_encoder_factory(), local_egl_context); SetEglContext(jni, owned_factory->legacy_decoder_factory(), remote_egl_context); #endif } static jlong JNI_PeerConnectionFactory_GetNativePeerConnectionFactory( JNIEnv* jni, const JavaParamRef<jclass>&, jlong native_factory) { return jlongFromPointer(factoryFromJava(native_factory)); } } // namespace jni } // namespace webrtc
<?php namespace App\Parasut\Enums; use BenSampo\Enum\Enum; /** * @method static static NotBilled() * @method static static NotFormalized() * @method static static Formalized() */ final class ParasutInvoiceStatus extends Enum { const NotBilled = "0"; const NotFormalized = "1"; const Formalized = "2"; }
package leetcode; /** * 前序遍历:根结点 ---> 左子树 ---> 右子树 * * 中序遍历:左子树---> 根结点 ---> 右子树 * * 后序遍历:左子树 ---> 右子树 ---> 根结点 * * 层次遍历:只需按层次遍历即可 * * 二叉树遍历 * */ public class BinaryTree { static class TreeNode { int val; TreeNode left, right; } void traverse(TreeNode root) { if (root == null) { return; } System.out.println(root.val); traverse(root.left); traverse(root.right); } public static void main(String[] args) { BinaryTree bt = new BinaryTree(); TreeNode root = new TreeNode(); root.val = 1; root.left = new TreeNode(); root.left.val = 2; root.right = new TreeNode(); root.right.val = 3; root.left.left = new TreeNode(); root.left.left.val = 4; root.left.right = new TreeNode(); root.left.right.val = 5; root.right.left = new TreeNode(); root.right.left.val = 6; root.right.right = new TreeNode(); root.right.right.val = 7; bt.traverse(root); } }
class Admin::BagLabelsController < ApplicationController before_action :authenticate_user! before_action :authorize_access def index; end def create @registrants = Registrant.includes(:contact_detail).reorder(:sorted_last_name, :first_name).active.all if params[:display_expenses] @registrants = @registrants.includes(:expense_items) end names = [] @registrants.find_each do |reg| record = "\n" record += "<b>##{reg.bib_number}</b> #{reg.last_name}, #{reg.first_name}\n" record += "#{reg.representation}\n" record += reg.registrant_type.capitalize.to_s if params[:display_expenses] reg_summary = reg.expense_items.map(&:name).join(", ") record += "\n<b>Items:</b> #{reg_summary}" if reg_summary.present? end names << record end labels = Prawn::Labels.render(names, type: "Avery5160", shrink_to_fit: true) do |pdf, name| set_font(pdf) pdf.text name, align: :center, inline_format: true end send_data labels, filename: "bag-labels-#{Date.current}.pdf", type: "application/pdf" end private def authorize_access authorize current_user, :registrant_information? end end
import Operation from "../generated/artifacts/operation"; import { TableSASPermission } from "./TableSASPermissions"; export class OperationTableSASPermission { constructor(public readonly permission: string = "") {} public validate(permissions: string): boolean { return this.validatePermissions(permissions); } public validatePermissions(permissions: string): boolean { for (const p of this.permission) { if (permissions.toString().includes(p)) { return true; } } return false; } } // See https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas // Table Service SAS Permissions for table level export const OPERATION_TABLE_SAS_TABLE_PERMISSIONS = new Map< Operation, OperationTableSASPermission >(); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Service_SetProperties, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Service_GetProperties, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Service_GetStatistics, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_Query, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_Create, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_Delete, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_QueryEntities, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_QueryEntitiesWithPartitionAndRowKey, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_UpdateEntity, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_MergeEntity, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_DeleteEntity, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_MergeEntityWithMerge, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_InsertEntity, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_GetAccessPolicy, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_SetAccessPolicy, new OperationTableSASPermission() ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_InsertEntity, new OperationTableSASPermission(TableSASPermission.Add) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_Query, new OperationTableSASPermission(TableSASPermission.Query) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_QueryEntities, new OperationTableSASPermission(TableSASPermission.Query) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_QueryEntitiesWithPartitionAndRowKey, new OperationTableSASPermission(TableSASPermission.Query) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Service_GetProperties, new OperationTableSASPermission(TableSASPermission.Query) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Service_GetStatistics, new OperationTableSASPermission(TableSASPermission.Query) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_Delete, new OperationTableSASPermission(TableSASPermission.Delete) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_DeleteEntity, new OperationTableSASPermission(TableSASPermission.Delete) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_UpdateEntity, new OperationTableSASPermission(TableSASPermission.Update) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_MergeEntity, new OperationTableSASPermission(TableSASPermission.Update) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_MergeEntityWithMerge, new OperationTableSASPermission(TableSASPermission.Update) ); OPERATION_TABLE_SAS_TABLE_PERMISSIONS.set( Operation.Table_Batch, new OperationTableSASPermission( TableSASPermission.Add + TableSASPermission.Delete + TableSASPermission.Query + TableSASPermission.Update ) );
<?php namespace App\Presenters; use Illuminate\Database\Eloquent\Model; class ItemPresenter implements PresenterInterface { public static function present(Model $model) { $category = $model->category; return [ 'id' => $model->id, 'title' => $model->title, 'description' => $model->description, 'price' => $model->price, 'image_url' => $model->image_url, 'count' => $model->count, 'is_sales' => $model->is_sales, 'category' => $category ]; } }
-- Actual parameter values may differ, what you see is a default string representation of values UPDATE cedna.dbo.Pregunta SET Funcion='getEmpresas' WHERE IdPregunta=3 ; UPDATE cedna.dbo.Pregunta SET Funcion='getLugarObra' WHERE IdPregunta=5 ; UPDATE cedna.dbo.Pregunta SET Funcion='getEtapasObra' WHERE IdPregunta=6 ; UPDATE cedna.dbo.Pregunta SET Funcion='getActividadesObra' WHERE IdPregunta=7 ; UPDATE cedna.dbo.Pregunta SET Funcion='getElementosProteccionPersonal' WHERE IdPregunta=8 ; UPDATE cedna.dbo.Pregunta SET Funcion='getRiesgosAmbientales' WHERE IdPregunta=9 ; UPDATE cedna.dbo.Pregunta SET Funcion='getRiesgosAdicionales' WHERE IdPregunta=10 ; UPDATE cedna.dbo.Pregunta SET Funcion='getPruebaDeGases' WHERE IdPregunta=14 ; UPDATE cedna.dbo.Pregunta SET Funcion='getFirmasPermiso' WHERE IdPregunta=15 ; INSERT INTO ajustes(script, diahora, spring, fix) VALUES ('21.sql', GETDATE ( ), 0, 21);
class Review < ApplicationRecord belongs_to :user belongs_to :cigar validates :stars, :summary, presence: true scope :top, -> {where(stars: 5)} def self.top where(stars: 5) end end
-- +goose Up -- +goose StatementBegin ALTER TABLE device_devices RENAME TO device_devices_tmp; CREATE TABLE device_devices ( access_token TEXT PRIMARY KEY, session_id INTEGER, device_id TEXT , localpart TEXT , created_ts BIGINT, display_name TEXT, last_seen_ts BIGINT, ip TEXT, user_agent TEXT, UNIQUE (localpart, device_id) ); INSERT INTO device_devices ( access_token, session_id, device_id, localpart, created_ts, display_name, last_seen_ts, ip, user_agent ) SELECT access_token, session_id, device_id, localpart, created_ts, display_name, created_ts, '', '' FROM device_devices_tmp; DROP TABLE device_devices_tmp; -- +goose StatementEnd -- +goose Down -- +goose StatementBegin ALTER TABLE device_devices RENAME TO device_devices_tmp; CREATE TABLE IF NOT EXISTS device_devices ( access_token TEXT PRIMARY KEY, session_id INTEGER, device_id TEXT , localpart TEXT , created_ts BIGINT, display_name TEXT, UNIQUE (localpart, device_id) ); INSERT INTO device_devices ( access_token, session_id, device_id, localpart, created_ts, display_name ) SELECT access_token, session_id, device_id, localpart, created_ts, display_name FROM device_devices_tmp; DROP TABLE device_devices_tmp; -- +goose StatementEnd
{-# Language FlexibleContexts, TypeFamilies #-} -- Tasty makes it easy to test your code. It is a test framework that can -- combine many different types of tests into one suite. See its website for -- help: <http://documentup.com/feuerbach/tasty>. import qualified Test.Tasty -- Hspec is one of the providers for Tasty. It provides a nice syntax for -- writing tests. Its website has more info: <https://hspec.github.io>. import Test.Tasty.Hspec import SpanningTree import QuickSI import TypeHacks import Types hiding (makeGraph) import qualified Data.Graph.Inductive as G import qualified Data.Map as M import GenMonad as GM import System.Random as R andFlip :: [(a, a, c)] -> [(a, a, c)] andFlip ls = ls ++ [(j, i, l) | (i, j, l) <- ls] exGraph :: G.Gr () () exGraph = G.mkGraph [(i, ()) | i <- [0..4]] $ andFlip [(0, 1, ()), (1, 2, ()), (2, 3, ()), (2, 4, ())] exPattern :: G.Gr () () exPattern = G.mkGraph [(n,()) | n <-[0..3]] $ andFlip [(0, n, ()) | n <- [1..3]] foo :: (Monoid a, Monoid b) => G.Gr a b -> G.Gr a b foo g = GM.runGenMonad (R.mkStdGen 0) g (\_ () -> True) test mkOrder :: (DynGraph g) => g -> [Matcher g] mkOrder = runMST (\x y -> fromIntegral $ 5 - y - x) main :: IO () main = do test <- testSpec "graphgenerator" spec Test.Tasty.defaultMain test -- spec :: Spec -- spec = parallel $ do -- it "is trivially true" $ do -- True `shouldBe` True spec :: Spec spec = parallel $ do it "traversal order should follow weights" $ do map source (mkOrder pat) `shouldBe` [ 0, 3, 2,1 ] where pat :: G.Gr Int Int pat = G.mkGraph [(n,n) | n <-[0..3]] [(0, n, n) | n <- [1..3]]
class AddIndexes < ActiveRecord::Migration[4.2] def change add_index :audio_recordings, [:created_at , :updated_at], name: 'audio_recordings_created_updated_at' add_index :audio_recordings, :site_id end end
package com.liziczh.app.rbac.service.kafka.config; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.NewTopic; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.KafkaAdmin; import lombok.extern.slf4j.Slf4j; /** * @author zhehao.chen */ @Slf4j @Configuration public class KafkaConfig { @Value("${spring.kafka.producer.bootstrap-servers}") private String bootstrapServers; @Value("${spring.kafka.init.create-topics}") private String createTopics; @Value("${spring.kafka.init.partition-num:1}") private String partitionNum; @Value("${spring.kafka.init.replication-factor:1}") private String replicationFactor; @PostConstruct private void createTopic() { if (StringUtils.isNoneBlank(createTopics, partitionNum, replicationFactor)) { List<NewTopic> newTopics = new ArrayList<>(); for (String topicName : createTopics.split(",")) { newTopics.add(new NewTopic(topicName, Integer.parseInt(partitionNum), Short.parseShort(replicationFactor))); } AdminClient client = AdminClient.create(kafkaAdmin().getConfig()); client.createTopics(newTopics); client.close(); } } @Bean public KafkaAdmin kafkaAdmin() { Map<String, Object> configs = new HashMap<>(1); configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); KafkaAdmin admin = new KafkaAdmin(configs); return admin; } }
import React, { useCallback, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import styled from "styled-components"; import l10n from "lib/helpers/l10n"; import { SceneParallaxLayer } from "store/features/entities/entitiesTypes"; import { CoordinateInput } from "ui/form/CoordinateInput"; import { FormField } from "ui/form/FormLayout"; import { Select } from "ui/form/Select"; import { ParallaxSpeedSelect } from "./ParallaxSpeedSelect"; import editorActions from "store/features/editor/editorActions"; interface ParallaxOption { value: number; label: string; } const options: ParallaxOption[] = [ { value: 0, label: `${l10n("FIELD_PARALLAX_NONE")}` }, { value: 1, label: `1 ${l10n("FIELD_LAYER")}` }, { value: 2, label: `2 ${l10n("FIELD_LAYERS")}` }, { value: 3, label: `3 ${l10n("FIELD_LAYERS")}` }, ]; interface ParallaxSelectProps { name: string; sceneHeight: number; value?: SceneParallaxLayer[]; onChange?: (newId: SceneParallaxLayer[] | undefined) => void; } const LayersWrapper = styled.div` background: ${(props) => props.theme.colors.sidebar.well.background}; border-top: 1px solid ${(props) => props.theme.colors.sidebar.border}; margin-left: -10px; margin-right: -10px; margin-top: 10px; margin-bottom: -10px; padding-bottom: 0; box-shadow: ${(props) => props.theme.colors.sidebar.well.boxShadow}; `; const LayerWrapper = styled.div` & ~ div { margin-top: 0px; } `; const LayerIndex = styled.div` flex-shrink: 0; width: 28px; height: 28px; background: ${(props) => props.theme.colors.sidebar.well.hoverBackground}; font-weight: bold; border-radius: 4px; text-align: center; line-height: 28px; `; const LayerRow = styled.div` display: flex; padding: 0 10px; padding-top: 10px; margin-bottom: -5px; & > * { margin-right: 10px; margin-bottom: 10px; } & > *:last-child { margin-right: 0px; } :hover { background: ${(props) => props.theme.colors.sidebar.well.hoverBackground}; ${LayerIndex} { background: ${(props) => props.theme.colors.sidebar.well.background}; } } `; export const defaultValues: SceneParallaxLayer[] = [ { height: 3, speed: 2, }, { height: 3, speed: 1, }, { height: 0, speed: 0, }, ]; const MAX_PARALLAX_HEIGHT = 17; const sliceLayers = ( value: SceneParallaxLayer[] | undefined, length: number ) => { const slicedDefaults = defaultValues.slice(-length); if (!value) { return slicedDefaults; } const heightDiff = slicedDefaults.length - value.length; let heightTotal = 0; return slicedDefaults.map((layer, layerIndex) => { const prev = value[layerIndex - heightDiff]; let newLayer = layer; if (prev) { newLayer = prev; } // Make sure total height isn't > MAX_PARALLAX_HEIGHT if (heightTotal + newLayer.height > MAX_PARALLAX_HEIGHT) { newLayer = { ...newLayer, height: Math.max(1, MAX_PARALLAX_HEIGHT - heightTotal), }; } heightTotal += newLayer.height; return newLayer; }); }; const updateParallaxHeight = ( value: SceneParallaxLayer[], layerIndex: number, height: number ) => { const maxHeight = MAX_PARALLAX_HEIGHT; const maxLayerHeight = maxHeight - Math.max(0, value.length - 2); const newValue = value.map((v, i) => { if (i === layerIndex) { return { ...v, height: Math.min(maxLayerHeight, height), }; } return v; }); // Calculcate new total height const layersHeight = newValue.reduce((memo, layer, layerIndex) => { if (layerIndex < newValue.length - 1) { return memo + layer.height; } return memo; }, 0); // If total is over limit reduce height of other layers let heightOverflow = layersHeight - maxHeight; if (heightOverflow > 0) { return newValue.map((v, i) => { if (i === layerIndex) { return v; } const newHeight = Math.max(1, v.height - heightOverflow); heightOverflow -= v.height - newHeight; return { ...v, height: newHeight, }; }); } return newValue; }; const updateParallaxSpeed = ( value: SceneParallaxLayer[], layerIndex: number, speed: number ) => { return value.map((v, i) => { if (i === layerIndex) { return { ...v, speed, }; } return v; }); }; const ParallaxSelect = ({ name, value, sceneHeight, onChange, }: ParallaxSelectProps) => { const dispatch = useDispatch(); const [selectValue, setSelectValue] = useState<ParallaxOption>(options[0]); useEffect(() => { if (!value) { setSelectValue(options[0]); } else { const selectValue = options.find((o) => o.value === value.length) || options[0]; setSelectValue(selectValue); } }, [value]); const setHoverLayer = useCallback( (layer: number | undefined) => { dispatch(editorActions.setParallaxHoverLayer(layer)); }, [dispatch] ); return ( <div> <Select name={name} value={selectValue} options={options} onChange={(newValue: ParallaxOption) => { if (newValue.value > 0) { onChange?.(sliceLayers(value, newValue.value)); } else { onChange?.(undefined); setHoverLayer(undefined); } }} /> {value && ( <LayersWrapper onMouseLeave={() => setHoverLayer(undefined)}> {value.map((layer, layerIndex) => ( <LayerWrapper key={layerIndex}> <LayerRow onMouseOver={() => setHoverLayer(layerIndex)}> <LayerIndex>{layerIndex + 1}</LayerIndex> <CoordinateInput name={`layer_${layerIndex}_height`} coordinate="h" min={1} value={ layerIndex === value.length - 1 ? sceneHeight : layer.height || undefined } placeholder="1" disabled={layerIndex === value.length - 1} onChange={(e) => { const height = Number(e.currentTarget.value); onChange?.(updateParallaxHeight(value, layerIndex, height)); }} /> <FormField name={`layer_${layerIndex}_speed`}> {layerIndex === 2 && value.length === 3 ? ( <ParallaxSpeedSelect name={`layer_${layerIndex}_speed`} value={0} disabled /> ) : ( <ParallaxSpeedSelect name={`layer_${layerIndex}_speed`} value={layer.speed} onChange={(speed) => { onChange?.( updateParallaxSpeed(value, layerIndex, speed) ); }} /> )} </FormField> </LayerRow> </LayerWrapper> ))} </LayersWrapper> )} </div> ); }; export default ParallaxSelect;
package kafka import ( "context" "fmt" "net" "time" "github.com/segmentio/kafka-go/protocol/describeconfigs" ) // DescribeConfigsRequest represents a request sent to a kafka broker to describe configs type DescribeConfigsRequest struct { // Address of the kafka broker to send the request to. Addr net.Addr // List of resources to update. Resources []DescribeConfigRequestResource // Ignored if API version is less than v1 IncludeSynonyms bool // Ignored if API version is less than v3 IncludeDocumentation bool } type ResourceType int8 const ( ResourceTypeUnknown ResourceType = 0 ResourceTypeAny ResourceType = 1 ResourceTypeTopic ResourceType = 2 ResourceTypeGroup ResourceType = 3 ResourceTypeCluster ResourceType = 4 ResourceTypeBroker ResourceType = 5 ) type DescribeConfigRequestResource struct { // Resource Type ResourceType ResourceType // Resource Name ResourceName string // ConfigNames is a list of configurations to update. ConfigNames []string } // DescribeConfigsResponse represents a response from a kafka broker to a describe config request. type DescribeConfigsResponse struct { // The amount of time that the broker throttled the request. Throttle time.Duration // Resources Resources []DescribeConfigResponseResource } // DescribeConfigResponseResource type DescribeConfigResponseResource struct { // Resource Type ResourceType int8 // Resource Name ResourceName string // Error Error error // ConfigEntries ConfigEntries []DescribeConfigResponseConfigEntry } // DescribeConfigResponseConfigEntry type DescribeConfigResponseConfigEntry struct { ConfigName string ConfigValue string ReadOnly bool // Ignored if API version is greater than v0 IsDefault bool // Ignored if API version is less than v1 ConfigSource int8 IsSensitive bool // Ignored if API version is less than v1 ConfigSynonyms []DescribeConfigResponseConfigSynonym // Ignored if API version is less than v3 ConfigType int8 // Ignored if API version is less than v3 ConfigDocumentation string } // DescribeConfigResponseConfigSynonym type DescribeConfigResponseConfigSynonym struct { // Ignored if API version is less than v1 ConfigName string // Ignored if API version is less than v1 ConfigValue string // Ignored if API version is less than v1 ConfigSource int8 } // DescribeConfigs sends a config altering request to a kafka broker and returns the // response. func (c *Client) DescribeConfigs(ctx context.Context, req *DescribeConfigsRequest) (*DescribeConfigsResponse, error) { resources := make([]describeconfigs.RequestResource, len(req.Resources)) for i, t := range req.Resources { resources[i] = describeconfigs.RequestResource{ ResourceType: int8(t.ResourceType), ResourceName: t.ResourceName, ConfigNames: t.ConfigNames, } } m, err := c.roundTrip(ctx, req.Addr, &describeconfigs.Request{ Resources: resources, IncludeSynonyms: req.IncludeSynonyms, IncludeDocumentation: req.IncludeDocumentation, }) if err != nil { return nil, fmt.Errorf("kafka.(*Client).DescribeConfigs: %w", err) } res := m.(*describeconfigs.Response) ret := &DescribeConfigsResponse{ Throttle: makeDuration(res.ThrottleTimeMs), Resources: make([]DescribeConfigResponseResource, len(res.Resources)), } for i, t := range res.Resources { configEntries := make([]DescribeConfigResponseConfigEntry, len(t.ConfigEntries)) for j, v := range t.ConfigEntries { configSynonyms := make([]DescribeConfigResponseConfigSynonym, len(v.ConfigSynonyms)) for k, cs := range v.ConfigSynonyms { configSynonyms[k] = DescribeConfigResponseConfigSynonym{ ConfigName: cs.ConfigName, ConfigValue: cs.ConfigValue, ConfigSource: cs.ConfigSource, } } configEntries[j] = DescribeConfigResponseConfigEntry{ ConfigName: v.ConfigName, ConfigValue: v.ConfigValue, ReadOnly: v.ReadOnly, ConfigSource: v.ConfigSource, IsDefault: v.IsDefault, IsSensitive: v.IsSensitive, ConfigSynonyms: configSynonyms, ConfigType: v.ConfigType, ConfigDocumentation: v.ConfigDocumentation, } } ret.Resources[i] = DescribeConfigResponseResource{ ResourceType: t.ResourceType, ResourceName: t.ResourceName, Error: makeError(t.ErrorCode, t.ErrorMessage), ConfigEntries: configEntries, } } return ret, nil }
""" pygame-menu https://github.com/ppizarror/pygame-menu TEST EXAMPLES Test example files. """ __all__ = ['ExamplesTest'] from test._utils import BaseRSTest, MenuUtils, PygameEventUtils, \ test_reset_surface import pygame import pygame_menu import pygame_menu.examples.game_selector as game_selector import pygame_menu.examples.multi_input as multi_input import pygame_menu.examples.scroll_menu as scroll_menu import pygame_menu.examples.simple as simple import pygame_menu.examples.timer_clock as timer_clock import pygame_menu.examples.window_resize as window_resize import pygame_menu.examples.other.calculator as calculator import pygame_menu.examples.other.dynamic_button_append as dynamic_button import pygame_menu.examples.other.dynamic_widget_update as dynamic_widget import pygame_menu.examples.other.image_background as image_background import pygame_menu.examples.other.maze as maze import pygame_menu.examples.other.scrollbar as scrollbar import pygame_menu.examples.other.scrollbar_area as scrollbar_area import pygame_menu.examples.other.ui_solar_system as ui_solarsystem import pygame_menu.examples.other.widget_positioning as widget_positioning # Reset the surface as some example could have changed it test_reset_surface() class ExamplesTest(BaseRSTest): def test_example_game_selector(self) -> None: """ Test game selector example. """ game_selector.main(test=True) font = MenuUtils.load_font(MenuUtils.random_font(), 5) game_selector.play_function(['EASY'], font, test=True) pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False)) game_selector.play_function(['MEDIUM'], font, test=True) pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False)) game_selector.play_function(['HARD'], font, test=True) self.assertRaises(ValueError, lambda: game_selector.play_function(['U'], font, test=True)) game_selector.change_difficulty(('HARD', 1), 'HARD') def test_example_multi_input(self) -> None: """ Test multi-input example. """ multi_input.main(test=True) multi_input.check_name_test('name') multi_input.update_menu_sound(('sound', None), True) multi_input.update_menu_sound(('sound', None), False) # Test methods within submenus settings = multi_input.main_menu.get_submenus()[0] settings.get_widget('store').apply() # Check range slider has event rslider = settings.get_widget('range_slider') self.assertIsNotNone(rslider._onchange) self.assertEqual(rslider.get_value(), 50) rslider.set_value(69) rslider.change() self.assertEqual(settings.get_widget('progress').get_value(), 69) more_settings = multi_input.main_menu.get_submenus()[1] # noinspection PyTypeChecker hex_color_widget: 'pygame_menu.widgets.ColorInput' = more_settings.get_widget('hex_color') hex_color_widget.apply() @staticmethod def test_example_scroll_menu() -> None: """ Test scroll menu example. """ scroll_menu.main(test=True) scroll_menu.on_button_click('pygame-menu', 'epic') scroll_menu.on_button_click('pygame-menu') @staticmethod def test_example_simple() -> None: """ Test example simple. """ sel = simple.menu.get_widgets()[1] sel.change(sel.get_value()) btn = simple.menu.get_widgets()[2] btn.apply() def test_example_resizable_window(self) -> None: """ Test resizable window. """ window_resize.on_resize() self.assertEqual(window_resize.menu.get_window_size(), (600, 600)) self.assertEqual(window_resize.menu.get_size(), (450, 420)) @staticmethod def test_example_timer_clock() -> None: """ Test timer clock example. """ pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False)) timer_clock.main(test=True) timer_clock.mainmenu_background() timer_clock.reset_timer() timer_clock.TestCallClassMethod.update_game_settings() color = (-1, -1, -1) timer_clock.change_color_bg((color, 'random',), color, write_on_console=True) def test_example_other_calculator(self) -> None: """ Test calculator example. """ app = calculator.main(test=True) # Process events app.process_events(PygameEventUtils.keydown([pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4, pygame.K_5, pygame.K_PLUS])) self.assertEqual(app.prev, '12345') self.assertEqual(app.op, '+') app.process_events(PygameEventUtils.keydown([pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9, pygame.K_0])) self.assertEqual(app.curr, '67890') app.process_events(PygameEventUtils.keydown(pygame.K_EQUALS)) self.assertEqual(app.op, '') self.assertEqual(app.curr, '80235') self.assertEqual(app.prev, '') app.process_events(PygameEventUtils.keydown([pygame.K_x, pygame.K_2])) self.assertEqual(app.op, 'x') self.assertEqual(app.curr, '2') self.assertEqual(app.prev, '80235') app.process_events(PygameEventUtils.keydown([pygame.K_x])) self.assertEqual(app.op, 'x') self.assertEqual(app.curr, '') self.assertEqual(app.prev, '160470') app.process_events(PygameEventUtils.keydown([pygame.K_PLUS, pygame.K_3, pygame.K_0])) self.assertEqual(app.op, '+') self.assertEqual(app.curr, '30') self.assertEqual(app.prev, '160470') app.process_events(PygameEventUtils.keydown(pygame.K_EQUALS)) self.assertEqual(app.op, '') self.assertEqual(app.curr, '160500') self.assertEqual(app.prev, '') app.process_events(PygameEventUtils.keydown([pygame.K_SLASH, pygame.K_5, pygame.K_MINUS])) self.assertEqual(app.op, '-') self.assertEqual(app.curr, '') self.assertEqual(app.prev, '32100') app.process_events(PygameEventUtils.keydown([pygame.K_3, pygame.K_2, pygame.K_1, pygame.K_0, pygame.K_EQUALS])) self.assertEqual(app.op, '') self.assertEqual(app.curr, '28890') self.assertEqual(app.prev, '') app.process_events(PygameEventUtils.keydown([pygame.K_9, pygame.K_BACKSPACE])) self.assertEqual(app.op, '') self.assertEqual(app.curr, '') self.assertEqual(app.prev, '') # Test methods self.assertRaises(ValueError, lambda: app._format('n')) self.assertEqual(app._format('1.2'), '1') self.assertEqual(app._format('2.0'), '2') # Test selection app.menu._test_print_widgets() b1 = app.menu.get_widgets()[4] b1d = b1.get_decorator() lay = b1.get_attribute('on_layer') self.assertFalse(b1d.is_enabled(lay)) b1.select() self.assertTrue(b1d.is_enabled(lay)) b1.select(False) self.assertFalse(b1d.is_enabled(lay)) def test_example_other_dynamic_button_append(self) -> None: """ Test dynamic button example. """ btn = dynamic_button.add_dynamic_button() self.assertEqual(btn.get_counter_attribute('count'), 0) btn.apply() self.assertEqual(btn.get_counter_attribute('count'), 1) dynamic_button.main(test=True) @staticmethod def test_example_other_dynamic_widget_update() -> None: """ Test dynamic widget update example. """ app = dynamic_widget.App() app.current = 3 app.animate_quit_button(app.quit_button, app.menu) dynamic_widget.main(test=True) app.fake_quit() app._on_selector_change(3, 3) @staticmethod def test_example_other_image_background() -> None: """ Test background image example. """ image_background.main(test=True) def test_example_other_maze(self) -> None: """ Test maze app example. """ app = maze.MazeApp(rows=10) btn = app._menu.get_widget('clear') app._path_found = True btn.apply() self.assertFalse(app._path_found) app._visualize = False # noinspection PyTypeChecker gen: 'pygame_menu.widgets.DropSelect' = app._menu.get_widget('generator') # noinspection PyTypeChecker sol: 'pygame_menu.widgets.DropSelect' = app._menu.get_widget('solver') for i in range(4): gen.set_value(i) sol.set_value(i) app._run_generator() app._run_solver() @staticmethod def test_example_other_scrollbar() -> None: """ Test scrollbar example. """ pygame.event.post(PygameEventUtils.keydown(pygame.K_v, inlist=False)) pygame.event.post(PygameEventUtils.keydown(pygame.K_h, inlist=False)) scrollbar.main(test=True) scrollbar.h_changed(1) scrollbar.v_changed(1) @staticmethod def test_example_other_scrollbar_area() -> None: """ Test scrollbar area example. """ pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False)) scrollbar_area.main(test=True) def test_example_other_ui_solar_system(self) -> None: """ Test solar system. """ app = ui_solarsystem.main(test=True) self.assertFalse(app.menu._disable_draw) app.process_events(PygameEventUtils.keydown([pygame.K_p]), app.menu) self.assertTrue(app.menu._disable_draw) app.process_events(PygameEventUtils.keydown([pygame.K_p, pygame.K_q, pygame.K_e, pygame.K_s, pygame.K_c]), app.menu) self.assertFalse(app.menu._disable_draw) def test_example_other_widget_positioning(self) -> None: """ Test widget positioning. """ widget_positioning.menu.render() self.assertTrue(widget_positioning.f.is_floating()) self.assertTrue(widget_positioning.b1.is_floating()) self.assertTrue(widget_positioning.b2.is_floating())
package net.ndrei.teslacorelib.utils import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos /** * Created by CF on 2017-07-06. */ object BlockPosUtils { fun getCube(entityPos: BlockPos, facing: EnumFacing?, radius: Int, height: Int): BlockCube { val pos1: BlockPos var pos2: BlockPos if (facing != null) { if (facing == EnumFacing.UP) { pos1 = entityPos .offset(EnumFacing.EAST, radius) .offset(EnumFacing.SOUTH, radius) .up(1) pos2 = entityPos .offset(EnumFacing.WEST, radius) .offset(EnumFacing.NORTH, radius) .up(height) } else if (facing == EnumFacing.DOWN) { pos1 = entityPos .offset(EnumFacing.EAST, radius) .offset(EnumFacing.SOUTH, radius) .down(1) pos2 = entityPos .offset(EnumFacing.WEST, radius) .offset(EnumFacing.NORTH, radius) .down(height) } else { // assume horizontal facing val left = facing.rotateYCCW() val right = facing.rotateY() pos1 = entityPos .offset(left, radius) .offset(facing, 1) pos2 = entityPos .offset(right, radius) .offset(facing, radius * 2 + 1) } } else { pos1 = BlockPos(entityPos.x - radius, entityPos.y, entityPos.z - radius) pos2 = BlockPos(entityPos.x + radius, entityPos.y, entityPos.z + radius) } pos2 = pos2.offset(EnumFacing.UP, height - 1) return BlockCube(pos1, pos2) } }
<div class="sub-bar"> <div class="sub-title"> <h4>{{$name}}:</h4> <span>Welcome To web Admin Panel!</span> </div> </div>
#!/bin/bash #-------------1. DATA DOWNLOAD ------------------------- # WE WILL KEEP IT CLEAN AND MAKE A NEW FOLDER mkdir sars cd sars/ #download for Mac (If you are a MacOS user comment out the below command) #curl -o datasets 'https://ftp.ncbi.nlm.nih.gov/pub/datasets/command-line/LATEST/mac/datasets' #download for linux (If you are a linux user comment out the above line) curl -o datasets 'https://ftp.ncbi.nlm.nih.gov/pub/datasets/command-line/LATEST/linux-amd64/datasets' chmod +x datasets #Give permission to access the datasets module #Download complete genomic data for Human Coronavirus ./datasets download virus genome tax-name SARS2 --host human --filename SARS2-all.zip unzip SARS2-all.zip #-------------2. DATA EXTRACTION ------------------------- #Extract batch data echo "Extracting batch sequences from the SARS-CoV2 dataset" python getseq.py cd .. #-------------3. ANALYSIS ------------------------- echo "aligning sequences using MAFFT" mafft --auto --reorder --maxiterate 1000 sequence.fasta > seqalign.fasta # Viewing the alignment on jalview #echo "Viewing the alignment" #jalview seqalign.fasta # constructing a phylogenetic tree echo "constructing a phylogenetic tree using iqtree" iqtree -s seqalign.fasta -nt AUTO -m TEST -bb 1000 # opening the constructed tree echo "opening the tree file" figtree *.treefile
import { Component, OnInit } from '@angular/core'; import { BreakpointObserver } from '@angular/cdk/layout'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { UserService } from '@services/user.service' import { PostService } from '@services/post.service' @Component({ selector: 'app-feed', templateUrl: './feed.component.html', styleUrls: ['./feed.component.scss'] }) export class FeedComponent implements OnInit { asideBookmarks:Observable<boolean>; asideComplentary:Observable<boolean>; user: any; feed: any; constructor(public breakpointObserver: BreakpointObserver, private userService: UserService, private postService: PostService) { this.asideBookmarks = breakpointObserver.observe('(max-width: 1100px)') .pipe(map(result => !result.matches)); this.asideComplentary = breakpointObserver.observe('(max-width: 900px)') .pipe(map(result => !result.matches)); } ngOnInit(): void { if(this.userService.getUser()) { this.user = this.userService.getUser() } else { this.user = this.userService.getUserMockado() } this.getFeed() } getFeed(): void { this.postService.getListagem().subscribe( res => this.feed = res, error => { console.log(error) this.feed = this.postService.getListagemMock() } ); } }
#[doc = "MSGBOX_RD_IRQ_EN_REG register accessor: an alias for `Reg<MSGBOX_RD_IRQ_EN_REG_SPEC>`"] pub type MSGBOX_RD_IRQ_EN_REG = crate::Reg<msgbox_rd_irq_en_reg::MSGBOX_RD_IRQ_EN_REG_SPEC>; #[doc = "Message Box Read Interrupt Enable Register"] pub mod msgbox_rd_irq_en_reg; #[doc = "MSGBOX_RD_IRQ_STATUS_REG register accessor: an alias for `Reg<MSGBOX_RD_IRQ_STATUS_REG_SPEC>`"] pub type MSGBOX_RD_IRQ_STATUS_REG = crate::Reg<msgbox_rd_irq_status_reg::MSGBOX_RD_IRQ_STATUS_REG_SPEC>; #[doc = "Message Box Read Interrupt Status Register"] pub mod msgbox_rd_irq_status_reg; #[doc = "MSGBOX_WR_IRQ_EN_REG register accessor: an alias for `Reg<MSGBOX_WR_IRQ_EN_REG_SPEC>`"] pub type MSGBOX_WR_IRQ_EN_REG = crate::Reg<msgbox_wr_irq_en_reg::MSGBOX_WR_IRQ_EN_REG_SPEC>; #[doc = "Message Box Write Interrupt Enable Register"] pub mod msgbox_wr_irq_en_reg; #[doc = "MSGBOX_WR_IRQ_STATUS_REG register accessor: an alias for `Reg<MSGBOX_WR_IRQ_STATUS_REG_SPEC>`"] pub type MSGBOX_WR_IRQ_STATUS_REG = crate::Reg<msgbox_wr_irq_status_reg::MSGBOX_WR_IRQ_STATUS_REG_SPEC>; #[doc = "Message Box Write Interrupt Status Register"] pub mod msgbox_wr_irq_status_reg; #[doc = "MSGBOX_DEBUG_REG register accessor: an alias for `Reg<MSGBOX_DEBUG_REG_SPEC>`"] pub type MSGBOX_DEBUG_REG = crate::Reg<msgbox_debug_reg::MSGBOX_DEBUG_REG_SPEC>; #[doc = "Message Box Debug Register"] pub mod msgbox_debug_reg; #[doc = "MSGBOX_FIFO_STATUS_REG register accessor: an alias for `Reg<MSGBOX_FIFO_STATUS_REG_SPEC>`"] pub type MSGBOX_FIFO_STATUS_REG = crate::Reg<msgbox_fifo_status_reg::MSGBOX_FIFO_STATUS_REG_SPEC>; #[doc = "Message Box FIFO Status Register"] pub mod msgbox_fifo_status_reg; #[doc = "MSGBOX_MSG_STATUS_REG register accessor: an alias for `Reg<MSGBOX_MSG_STATUS_REG_SPEC>`"] pub type MSGBOX_MSG_STATUS_REG = crate::Reg<msgbox_msg_status_reg::MSGBOX_MSG_STATUS_REG_SPEC>; #[doc = "Message Box Message Status Register"] pub mod msgbox_msg_status_reg; #[doc = "MSGBOX_MSG_REG register accessor: an alias for `Reg<MSGBOX_MSG_REG_SPEC>`"] pub type MSGBOX_MSG_REG = crate::Reg<msgbox_msg_reg::MSGBOX_MSG_REG_SPEC>; #[doc = "Message Box Message Queue Register"] pub mod msgbox_msg_reg; #[doc = "MSGBOX_WR_INT_THRESHOLD_REG register accessor: an alias for `Reg<MSGBOX_WR_INT_THRESHOLD_REG_SPEC>`"] pub type MSGBOX_WR_INT_THRESHOLD_REG = crate::Reg<msgbox_wr_int_threshold_reg::MSGBOX_WR_INT_THRESHOLD_REG_SPEC>; #[doc = "Message Box Write Interrupt Threshold Register"] pub mod msgbox_wr_int_threshold_reg;
C %W% %G% subroutine ruint C C THIS SUBROUTINE CONVERTS THE BUS NUMBERS TO THE SWING C INTERNAL ORDER FOR THE LINE CONTAINING THE UNDERFREQUENCY LI C TRIPPING RELAY AND INITIALIZES THE VOLTAGE TABLES. C IT ALSO SEARCHES THE REMOTE RELAY TABLES TO FIND THE INDICES C OF THE REMOTE RELAYS FOR THIS RELAY. IT IS CALLED BY INITL2. C include 'tspinc/params.inc' include 'tspinc/busnum.inc' include 'tspinc/rrcom.inc' include 'tspinc/rucom.inc' include 'tspinc/namec.inc' include 'tspinc/pointr.inc' include 'tspinc/kntrly.inc' include 'tspinc/prt.inc' include 'tspinc/busvolt.inc' character*8 name1c, name2c character*1 id C C REORDER BUS NUMBERS IN UNDERFREQUENCY LINE RELAY TABLE C do itrr = 1, kntru ibusru(itrr) = indx2n(ibusru(itrr)) jbusru(itrr) = indx2n(jbusru(itrr)) ibusn = ibusru(itrr) jbusn = jbusru(itrr) eiru(itrr) = eyr(ibusn) firu(itrr) = eyi(ibusn) C C SEARCH REMOTE RELAY TABLES TO FIND REMOTE RELAYS C ATTACHED TO THIS RELAY C id = iparru(itrr) if (kntrr .ne. 0) then knt = 0 do ktrr = 1, kntrr if (ibusn .eq. ibs1rr(ktrr)) then if (jbusn .eq. jbs1rr(ktrr)) then if (kompr(id, ipr1rr(ktrr), kdum) .eq. 0) then if (rltprr(ktrr) .eq. 8) then knt = knt + 1 if (knt .gt. 5) goto 100 rltprr(ktrr) = - 1.0 idrrru(knt, itrr) = ktrr endif endif endif endif enddo icd4ru(itrr) = knt goto 110 100 name1c = exnamc(ibusn) kv1 = ixnamn(ibusn) bkv1 = basekv(kv1) name2c = exnamc(jbusn) kv2 = ixnamn(jbusn) bkv2 = basekv(kv2) write (errbuf(1), 10000) name1c, bkv1, name2c, bkv2, id 10000 format (5x, ' UNDERFREQUENCY LINE RELAY ', 2(1x, a8, 1x, & f5.1), 1x, a1, ' HAS MORE THAN 5 REMOTE RELAYS.') iabort = 1 endif 110 continue enddo return end
import React, { Component } from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import times from 'async/times'; import Web3 from "web3"; import abi from "../abi"; import * as cardbaseInstance from "../cardbaseInstance"; import * as myDeckService from "./myDeckService"; import Card from "../Card"; import * as gameService from "../GameBoard/gameService"; import GameStats from "../GameStats"; class MyDeck extends Component { constructor(props) { super(props); this.state = { noOfCards: 0, cards: [], games: [] }; } setupGameCreatedEvent(fromBlock) { cardbaseInstance.get().events.GameCreated({ filter: { _from: cardbaseInstance.getDefaultAddress() }, // Using an array means OR: e.g. 20 or 23 /**fromBlock*/ }, (error, event) => { console.log(error, event); // debugger; // this.props.history.push('/game/1'); }); } startGame() { this.setState({ isStartingGame: true }); cardbaseInstance.get() .methods .startGame() .send({ from: cardbaseInstance.getDefaultAddress() }) .then((res) => { console.log(res); this.props.history.push('/game/1') }); } countCards() { cardbaseInstance.get() .methods.countCards().call({ from: cardbaseInstance.getDefaultAddress() }).then((res) => { this.setState({ noOfCards: Number(res.toString()) }) }); } loadMyCards() { myDeckService.loadMyCards().then(cards => { this.setState({ cards }); }); } loadMyGames() { gameService.loadMyGames().then(games => { debugger; this.setState({ games }); }); } componentDidMount() { this.loadMyCards() this.loadMyGames(); } render() { return ( <div> {this.state.isStartingGame && <h2>The Game is Starting!</h2>} {this.state.isLoading && <h2>Loading!</h2>} <button onClick={() => this.props.history.push('/game/1')}>GO TO GAME 1</button> <button onClick={() => this.props.history.push('/')}>GO TO DECK</button> <button onClick={() => this.startGame()}>START GAME</button> {this.state.noOfCards} <button onClick={() => { }}> show card index owner </button> <button onClick={() => { this.setState({ isLoading: true }); cardbaseInstance.get().methods.createNewCard().send({ from: cardbaseInstance.getDefaultAddress() }) .then(res => { console.log(res); this.setState({ isLoading: false }); }, e => { console.log(e); this.setState({ isLoading: false }); alert("Error!"); }); }}>Create new button</button> <button onClick={() => this.countCards()}>Show card 0</button> <div style={{ padding: "10px" }}> <h1>Your deck: {this.state.cards.length} cards</h1> {this.state.cards.map(card => <Card card={card} />)} </div> <div style={{ padding: "10px" }}> <h1>Your games: {this.state.games.length} games</h1> {this.state.games.map(game => GameStats(game))} </div> </div> ); } } export default MyDeck;
#[macro_use] mod grass_macros; grass_test!( calc_whitespace, "a {\n color: calc( 1 );\n}\n", "a {\n color: calc( 1 );\n}\n" ); grass_test!( calc_newline, "a {\n color: calc(\n);\n}\n", "a {\n color: calc( );\n}\n" ); grass_test!( calc_multiple_args, "a {\n color: calc(1, 2, a, b, c);\n}\n" ); grass_test!( calc_does_not_evaluate_arithmetic, "a {\n color: calc(1 + 2);\n}\n" ); grass_test!( calc_evaluates_interpolated_arithmetic, "a {\n color: calc(#{1 + 2});\n}\n", "a {\n color: calc(3);\n}\n" ); grass_test!(calc_retains_silent_comment, "a {\n color: calc(//);\n}\n"); grass_test!( calc_retains_multiline_comment, "a {\n color: calc(/**/);\n}\n" ); grass_test!(calc_nested_parens, "a {\n color: calc((((()))));\n}\n"); grass_test!( calc_invalid_arithmetic, "a {\n color: calc(2px + 2px + 5%);\n}\n" ); grass_test!( calc_uppercase, "a {\n color: CALC(1 + 1);\n}\n", "a {\n color: calc(1 + 1);\n}\n" ); grass_test!( calc_mixed_casing, "a {\n color: cAlC(1 + 1);\n}\n", "a {\n color: calc(1 + 1);\n}\n" ); grass_test!( calc_browser_prefixed, "a {\n color: -webkit-calc(1 + 2);\n}\n", "a {\n color: -webkit-calc(1 + 2);\n}\n" ); grass_test!( calc_quoted_string, r#"a { color: calc("\ "); }"#, "a {\n color: calc(\" \");\n}\n" ); grass_test!( calc_quoted_string_single_quoted_paren, "a {\n color: calc(\")\");\n}\n", "a {\n color: calc(\")\");\n}\n" ); grass_test!( calc_quoted_string_single_quotes, "a {\n color: calc('a');\n}\n", "a {\n color: calc(\"a\");\n}\n" ); grass_test!( calc_hash_no_interpolation, "a {\n color: calc(#);\n}\n", "a {\n color: calc(#);\n}\n" ); grass_test!( element_whitespace, "a {\n color: element( 1 );\n}\n", "a {\n color: element( 1 );\n}\n" ); grass_test!( element_newline, "a {\n color: element(\n);\n}\n", "a {\n color: element( );\n}\n" ); grass_test!( element_multiple_args, "a {\n color: element(1, 2, a, b, c);\n}\n" ); grass_test!( element_does_not_evaluate_arithmetic, "a {\n color: element(1 + 2);\n}\n" ); grass_test!( element_evaluates_interpolated_arithmetic, "a {\n color: element(#{1 + 2});\n}\n", "a {\n color: element(3);\n}\n" ); grass_test!( element_retains_silent_comment, "a {\n color: element(//);\n}\n" ); grass_test!( element_retains_multiline_comment, "a {\n color: element(/**/);\n}\n" ); grass_test!( element_nested_parens, "a {\n color: element((((()))));\n}\n" ); grass_test!( element_browser_prefixed, "a {\n color: -webkit-element(1 + 2);\n}\n", "a {\n color: -webkit-element(1 + 2);\n}\n" ); grass_test!( expression_whitespace, "a {\n color: expression( 1 );\n}\n", "a {\n color: expression( 1 );\n}\n" ); grass_test!( expression_newline, "a {\n color: expression(\n);\n}\n", "a {\n color: expression( );\n}\n" ); grass_test!( expression_multiple_args, "a {\n color: expression(1, 2, a, b, c);\n}\n" ); grass_test!( expression_does_not_evaluate_arithmetic, "a {\n color: expression(1 + 2);\n}\n" ); grass_test!( expression_evaluates_interpolated_arithmetic, "a {\n color: expression(#{1 + 2});\n}\n", "a {\n color: expression(3);\n}\n" ); grass_test!( expression_retains_silent_comment, "a {\n color: expression(//);\n}\n" ); grass_test!( expression_retains_multiline_comment, "a {\n color: expression(/**/);\n}\n" ); grass_test!( expression_nested_parens, "a {\n color: expression((((()))));\n}\n" ); grass_test!( expression_browser_prefixed, "a {\n color: -webkit-expression(1 + 2);\n}\n", "a {\n color: -webkit-expression(1 + 2);\n}\n" ); grass_test!( progid_whitespace, "a {\n color: progid:( 1 );\n}\n", "a {\n color: progid:( 1 );\n}\n" ); grass_test!( progid_newline, "a {\n color: progid:(\n);\n}\n", "a {\n color: progid:( );\n}\n" ); grass_test!( progid_multiple_args, "a {\n color: progid:(1, 2, a, b, c);\n}\n" ); grass_test!( progid_does_not_evaluate_arithmetic, "a {\n color: progid:(1 + 2);\n}\n" ); grass_test!( progid_evaluates_interpolated_arithmetic, "a {\n color: progid:(#{1 + 2});\n}\n", "a {\n color: progid:(3);\n}\n" ); grass_test!( progid_retains_silent_comment, "a {\n color: progid:(//);\n}\n" ); grass_test!( progid_retains_multiline_comment, "a {\n color: progid:(/**/);\n}\n" ); grass_test!( progid_nested_parens, "a {\n color: progid:((((()))));\n}\n" ); grass_test!( progid_values_after_colon, "a {\n color: progid:apple.bottoM..jeans.boots();\n}\n" ); grass_error!( progid_number_after_colon, "a {\n color: progid:ap1ple.bottoM..jeans.boots();\n}\n", "Error: expected \"(\"." ); grass_test!( progid_uppercase, "a {\n color: PROGID:foo(fff);\n}\n", "a {\n color: progid:foo(fff);\n}\n" ); grass_test!( progid_mixed_casing, "a {\n color: PrOgId:foo(fff);\n}\n", "a {\n color: progid:foo(fff);\n}\n" ); grass_error!( progid_nothing_after, "a { color: progid:", "Error: expected \"(\"." );
(ns slates-in-a-pile.styles.slates.slate-2 (:require [garden.def :refer [defstyles]] [slates-in-a-pile.styles.utils.variables :refer :all] [slates-in-a-pile.styles.utils.helpers :refer :all])) (defstyles slate-2 [:#slate-2 {:color (:hard-blue colours)} [:.backdrop {:background-color (:soft-blue colours)} [:.content (slate-title (:faded-blue colours)) [:.blurb {:float "left" :text-align "left" :width "700px" :margin "60px 0 25px 0"} (pointer (:hard-blue colours)) [:p {:float "left"}]]]]])