text
stringlengths
27
775k
package fr.philr.medimail.pop3access; import java.net.Socket; public interface POP3ServerFactory { public void handleConnection(Socket clientSocket); }
using System; namespace ngWithJwt.Models { public class User { public string UserName { get; set; } public string Password { get; set; } public string ConfirmedPassword { get; set; } public string GivenName { get; set; } public string FamilyName { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } } }
<?php namespace backend\modules\test\models; use Yii; /** * This is the model class for table "test_multichoice". * * @property integer $id * @property integer $alone * @property string $content * @property string $options * @property string $answer * @property string $note * @property integer $chapter * @property integer $sum * @property integer $wrong * @property double $level * @property string $source * @property string $date */ class TestMultiChoice extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'test_multichoice'; } /** * @inheritdoc */ public function rules() { return [ [['alone', 'chapter', 'sum', 'wrong'], 'integer'], [['content', 'options', 'answer'], 'required'], [['level'], 'number'], [['date'], 'safe'], [['content'], 'string', 'max' => 300], [['options', 'note'], 'string', 'max' => 500], [['answer'], 'string', 'max' => 200], [['source'], 'string', 'max' => 100] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'alone' => 'Alone', 'content' => 'Content', 'options' => 'Options', 'answer' => 'Answer', 'note' => 'Note', 'chapter' => 'Chapter', 'sum' => 'Sum', 'wrong' => 'Wrong', 'level' => 'Level', 'source' => 'Source', 'date' => 'Date', ]; } }
#Mask [Try it here](http://www.stagexl.org/samples/mask/ "StageXL Mask Sample") --- This is a simple demo showing some flowers and the effect when different masks are applied. A mask hides the area of a DisplayObject which is outside of the bounds of the mask. Only the pixels inside of the mask are visible. The Mask demo uses 3 masks with different shapes. The first two masks are simple shapes in the form of a rectangle and a circle. The third mask uses a custom shape which is defined by a list of points - in this example the shape of a star. You can also create masks with a shape that follows the graphics path of a StageXL Shape class, but this is outside of the scope of this sample. If you look at the source code, you see that the sample starts with the initialization of the StageXL Stage and RenderLoop. Nothing special here. Next the instances of the masks are created. var rectangleMask = new Mask.rectangle(100, 100, 740, 300); var circleMask = new Mask.circle(470, 250, 200); var customMask = new Mask.custom(starPath); The HTML of this sample contains 4 buttons. Button 1 removes the mask and buttons 2 to 4 assigns one of the three masks shown above. When the user clicks on one of the buttons we assign a new value to the *flowerField.mask* property. querySelector('#mask-none').onClick.listen((e) => flowerField.mask = null); querySelector('#mask-rectangle').onClick.listen((e) => flowerField.mask = rectangleMask); querySelector('#mask-circle').onClick.listen((e) => flowerField.mask = circleMask); querySelector('#mask-custom').onClick.listen((e) => flowerField.mask = customMask); Now we only have to load some nice looking flower images and create a field of flowers. We use the ResourceManager and a texture atlas which contains the images of three different flowers. Once the ResourceManager has finished loading we create a new instance of FlowerField (see source code). resourceManager = new ResourceManager() ..addTextureAtlas('flowers', 'images/Flowers.json', TextureAtlasFormat.JSONARRAY) ..load().then((_) { flowerField = new FlowerField(); flowerField.x = 470; flowerField.y = 250; stage.addChild(flowerField); }); The sample also shows one additional button labeled with "Spin". If the users clicks on this button the field of flowers and the mask are rotated around it's center. stage.juggler.tween(flowerField, 2.0, TransitionFunction.easeInOutBack) ..animate.rotation.to(math.PI * 4.0) ..onComplete = () => flowerField.rotation = 0.0; --- To learn more about Dart and the StageXL library, please follow these links: * Dart programming language: <http://www.dartlang.org/> * StageXL homepage: <http://www.stagexl.org/> * StageXL on GitHub: <http://www.github.com/bp74/StageXL>
/* eslint-disable react/no-array-index-key */ import React from 'react' import { Box, Link as MaterialLink, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, } from '@material-ui/core' import { Link } from 'react-router-dom' import styled from 'styled-components/macro' import { flatten, isEmpty } from 'lodash-es' import { Card } from '../cards' import { HighlightedText, LoadingOverlay, Result, StatusTag, TableFilter } from '../index' import { getTraces_getTraces_traces as Trace } from '../../graphql/queries/types/getTraces' import { formatDateTime, formatDuration, getMatches, safeParse } from '../../utils' import { LogType } from '../logs/log.component' const Wrapper: typeof TableContainer = styled(({ loading, ...props }) => ( <TableContainer {...props} /> ))<{ loading: boolean }>` min-height: ${(p) => (p.loading ? '360px' : 'auto')}; position: relative; ` const Traces = styled(Table)` tr:last-child { td { border: none; } } ` const LogsWrapper = styled.div` padding: 0 20px; max-height: 150px; overflow-y: auto; ` const LogsTitle = styled.div` padding: 0 20px; margin-bottom: 10px; ` const Flex = styled.div` display: flex; ` interface TracesCardProps { traces?: Trace[] statuses: string[] setStatuses: (newStatus: string[]) => void searchTerm?: string className?: string loading?: boolean } const availableStatuses = ['ERROR', 'OK'] export const TracesCard = ({ className, traces, statuses, setStatuses, loading, searchTerm, }: TracesCardProps) => ( <Wrapper component={Card} className={className} loading={loading && isEmpty(traces)}> {loading && <LoadingOverlay />} <Traces aria-label="traces table"> <TableHead> <TableRow> <TableCell>Request</TableCell> <TableCell>Unit Name</TableCell> <TableCell> <Flex> Status <TableFilter selectedValue={statuses} values={availableStatuses} onChange={setStatuses} /> </Flex> </TableCell> <TableCell>Duration</TableCell> <TableCell>Time</TableCell> </TableRow> </TableHead> {!isEmpty(traces) && ( <TableBody> {traces?.map((row) => { let logs: string[] = [] if (searchTerm && !loading) { const parsedLogs = safeParse(row?.logs) ?? [] logs = flatten( parsedLogs .filter((log: LogType) => log.message?.includes(searchTerm)) .map((log: LogType) => getMatches(log.message, searchTerm)), ) } return ( <React.Fragment key={row.id}> <TableRow hover> <TableCell scope="row"> <MaterialLink to={`/traces/${row.id}`} component={Link}> <HighlightedText text={row.externalId} highlight={searchTerm} /> </MaterialLink> </TableCell> <TableCell scope="row">{row.unitName}</TableCell> <TableCell> <StatusTag status={row.status} /> </TableCell> <TableCell>{formatDuration(row.duration)}</TableCell> <TableCell>{formatDateTime(row.start)}</TableCell> </TableRow> {!isEmpty(logs) && ( <TableRow> <TableCell colSpan={5}> <LogsTitle>Found search term in logs (first 10 matches): </LogsTitle> <LogsWrapper> {logs.slice(0, 10).map((log, index) => ( <Box key={index} mb={2}> <HighlightedText text={log} highlight={searchTerm} /> </Box> ))} </LogsWrapper> </TableCell> </TableRow> )} </React.Fragment> ) })} </TableBody> )} </Traces> {!loading && isEmpty(traces) && <Result type="empty" />} </Wrapper> )
## Obtaining Wikipedia as a Python dictionary We adapt the Wikipedia extractor available in https://github.com/attardi/wikiextractor (all code is available in the arwiki folder). From Wikipedia dumps we will turn it to a Python dictionary to be able to access it as: ``` wikipedia['لبنان'] = [" لبنان أو (رسمياً: الجمهوريّة اللبنانيّة)، هي دولة عربية واقعة في الشرق الأوسط في غرب القارة الآسيوية.", ... ] ``` **Steps**: All scripts here are located in the **arwiki** folder. * First download Wikipedia dump available at: https://dumps.wikimedia.org/arwiki/20190520/arwiki-20190520-pages-articles-multistream.xml.bz2 and unzip to .xml (you can use older versions also). * Create a temporary **empty** folder, say it's location is TEMP_DIRECTORY, Use arwiki/wikiextractor.py to do a first step extraction of the dump to your (if you use Linux instead of '^' write '\'): **Note:** This command will create a bunch of folders in your TEMP_DIRECTORY named AA, AB, ... and will take up to 10 minutes (there are 660k articles in total). ```shell python WikiExtractor.py ^ arwiki-20190201-pages-articles-multistream.xml ^ --processes 16 ^ --o . ^ --no-templates ^ --json ``` * Now using the output of WikiExtractor we will build a Python dictionary of Arabic Wikipedia and save it in pickle form (if you are not familiar with Pickle check https://wiki.python.org/moin/UsingPickle, we will use it extensively here), pick an OUTPUT_DIRECTORY: ```shell python arwiki_to_dict.py ^ -i TEMP_DIRECTORY ^ -o OUTPUT_DIRECTORY ``` This command will create a file called arwiki.p of size 1.2GB in your output directory and this is your pickled Wikipedia. * You can safely now delete your TEMP_DIRECTORY
1. 模式匹配 1. 变量匹配 val v42 = 42 Some(3) match { case Some(`v42`) => println("42") //不用反引号,理解为变量,一直输出42 引用前面定义的变量 case _ => println("Not 42") //输出 } 2. 变量绑定匹配 val person = Person("Tony",18) person match { // 使用 @ 将匹配的对象绑定到变量名上 case p @ Person(_,age) => println(s"${p.name},age is $age") case _ => println("Not a person") } 2. 集合框架(By default, Scala always picks immutable collections) 1. scala.collection:两种特性兼顾 2. scala.collection.immutable:不可变 3. scala.collection.mutable:可变
require_relative 'spec_helper' describe "Changes to ActionController" do let(:controller) { InstanceMethodDummy.new } describe "is_tablet_device?" do let(:user_agent) { Object.new } let(:expected_result) { Object.new } it "should return the result from the tablet module" do controller.user_agent = user_agent ::MobileFu::Tablet.stubs(:is_a_tablet_device?).with(user_agent).returns expected_result controller.is_tablet_device?.must_be_same_as expected_result end end end class InstanceMethodDummy include ActionController::MobileFu::InstanceMethods attr_accessor :user_agent def request @request ||= begin r = Object.new r.stubs(:user_agent).returns user_agent r end end end
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Runtime.CompilerServices; using static Root; public readonly struct ApiPack : IApiPack { public ApiExtractSettings ExtractSettings {get;} public FS.FolderPath Root => ExtractSettings.ExtractRoot; [MethodImpl(Inline)] public ApiPack(ApiExtractSettings settings) { ExtractSettings = settings; } public Timestamp Timestamp => ParseTimestamp().Data; public bool IsTimestamped => ParseTimestamp().Ok; Outcome<Timestamp> ParseTimestamp() { if(Root.IsEmpty) return default; return ApiExtractSettings.timestamp(Root, out _); } public string Format() => string.Format("{0}: {1}", ParseTimestamp(), Root); public override string ToString() => Format(); } }
# CONFLICTS This document explains why certain conflicts were added to `composer.json` and refereneces related issues. - `doctrine/inflector:^1.4`: Inflector 1.4 changes pluralization of `taxon` from `taxons` (used in Sylius) to `taxa`. References: https://github.com/doctrine/inflector/issues/147 - `symfony/doctrine-bridge:4.4.16`: This version of Doctrine Bridge introduces a bug that causes an issue related to `ChannelPricing` mapping. References: https://github.com/Sylius/Sylius/issues/11970, https://github.com/symfony/symfony/issues/38861 - `laminas/laminas-code": "^4.0.0`: Throw many syntax exceptions after running `vendor/bin/psalm --show-info=false` on `php7.4` ``` Error: Syntax error, unexpected T_STRING, expecting T_PAAMAYIM_NEKUDOTAYIM on line 480 Error: Syntax error, unexpected T_VARIABLE, expecting ')' on line 480 Error: Syntax error, unexpected ')' on line 481 Error: Syntax error, unexpected T_STRING, expecting T_PAAMAYIM_NEKUDOTAYIM on line 495 Error: Syntax error, unexpected T_VARIABLE, expecting ')' on line 495 Error: Syntax error, unexpected ')' on line 496 Error: Syntax error, unexpected T_STRING, expecting T_PAAMAYIM_NEKUDOTAYIM on line 59 Error: Syntax error, unexpected T_VARIABLE, expecting ')' on line 59 Error: Syntax error, unexpected ',' on line 59 Error: Syntax error, unexpected ')' on line 63 Error: Syntax error, unexpected T_STRING, expecting T_PAAMAYIM_NEKUDOTAYIM on line 105 Error: Syntax error, unexpected T_VARIABLE, expecting ')' on line 105 Error: Syntax error, unexpected ')' on line 107 Error: Syntax error, unexpected T_VARIABLE, expecting ')' on line 161 Error: Syntax error, unexpected ',' on line 161 Error: Syntax error, unexpected ')' on line 163 Error: Syntax error, unexpected T_VARIABLE, expecting ')' on line 185 Error: Syntax error, unexpected ',' on line 185 Error: Syntax error, unexpected ')' on line 187 Error: Syntax error, unexpected T_STRING, expecting T_PAAMAYIM_NEKUDOTAYIM on line 161 Error: Syntax error, unexpected T_VARIABLE, expecting ')' on line 161 Error: Syntax error, unexpected ')' on line 161 Error: Process completed with exit code 1. ``` References: https://github.com/laminas/laminas-code/issues/67
// Copyright 2013 Beego Web authors // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // Package routers implemented controller methods of beego. package routers import ( "strings" "time" "github.com/astaxie/beego" "github.com/beego/i18n" ) var ( AppVer string IsPro bool ) var langTypes []*langType // Languages are supported. // langType represents a language type. type langType struct { Lang, Name string } // baseRouter implemented global settings for all other routers. type baseRouter struct { beego.Controller i18n.Locale } // Prepare implemented Prepare method for baseRouter. func (this *baseRouter) Prepare() { beego.Info("Prepare url", this.Ctx.Request.URL.String()) // Setting properties. this.Data["AppVer"] = AppVer this.Data["IsPro"] = IsPro this.Data["PageStartTime"] = time.Now() // Redirect to make URL clean. if this.setLangVer() { i := strings.Index(this.Ctx.Request.RequestURI, "?") this.Redirect(this.Ctx.Request.RequestURI[:i], 302) return } } // setLangVer sets site language version. func (this *baseRouter) setLangVer() bool { isNeedRedir := false hasCookie := false // 1. Check URL arguments. lang := this.Input().Get("lang") // 2. Get language information from cookies. if len(lang) == 0 { lang = this.Ctx.GetCookie("lang") hasCookie = true } else { isNeedRedir = true } // Check again in case someone modify by purpose. if !i18n.IsExist(lang) { lang = "" isNeedRedir = false hasCookie = false } // 3. Get language information from 'Accept-Language'. if len(lang) == 0 { al := this.Ctx.Request.Header.Get("Accept-Language") if len(al) > 4 { al = al[:5] // Only compare first 5 letters. if i18n.IsExist(al) { lang = al } } } // 4. Default language is English. if len(lang) == 0 { lang = "en-US" isNeedRedir = false } curLang := langType{ Lang: lang, } // Save language information in cookies. if !hasCookie { this.Ctx.SetCookie("lang", curLang.Lang, 1<<31-1, "/") } restLangs := make([]*langType, 0, len(langTypes)-1) for _, v := range langTypes { if lang != v.Lang { restLangs = append(restLangs, v) } else { curLang.Name = v.Name } } // Set language properties. this.Lang = lang this.Data["Lang"] = curLang.Lang this.Data["CurLang"] = curLang.Name this.Data["RestLangs"] = restLangs return isNeedRedir }
% The "BlinkLED" program. % The for structure repeats the program ten times. for count : 1 .. 10 % Turns the LED on. parallelput (1) % Keeps the LED on for 500 milliseconds. delay (500) % Turns the LED off. parallelput (0) % Keeps the LED off for 300 milliseconds. delay (300) % Ends once the program has repeated ten times. end for
const fs = require('fs') const _ = require('./helper') module.exports = (filedir, bridge) => { let filepaths = bridge.dirs[filedir] let content = '' // 合并文件 filepaths.forEach((path) => { content += fs.readFileSync(path, {encoding: 'utf8'}) }) // 替换include content = _.includeReplace(bridge.folder + filedir, content) return content }
import React from 'react'; import PropTypes from 'prop-types'; import { NavigationContainer } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { Appbar, withTheme } from 'react-native-paper'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import Color from 'color'; import ChartsScreen from '../screens/ChartsScreen'; import SettingsScreen from '../screens/SettingsScreen'; const Tab = createBottomTabNavigator(); const Navigation = (props) => { const { theme, sensorData, writeNewSettings } = props; const primaryColor = Color(theme.colors.primary); const title = 'BVM Ventilator Covid-19'; return ( <NavigationContainer> <Tab.Navigator screenOptions={({ route }) => ({ tabBarIcon: () => { let iconName; if (route.name === 'Charts') { iconName = 'chart-areaspline'; } else if (route.name === 'Settings') { iconName = 'tune'; } return ( <Icon name={iconName} size={25} color={theme.colors.accent} /> ); }, })} tabBarOptions={{ activeTintColor: theme.colors.accent, inactiveTintColor: theme.colors.accent, activeBackgroundColor: primaryColor.darken(0.07).rgb(), inactiveBackgroundColor: theme.colors.primary, labelStyle: { fontSize: 15, }, style: { borderTopWidth: 0, }, tabStyle: { borderTopWidth: 0, }, }}> <Tab.Screen name="Charts"> {(screenProps) => ( <> <Appbar.Header> <Appbar.Content title={`Charts | ${title}`} /> </Appbar.Header> <ChartsScreen {...screenProps} sensorData={sensorData} /> </> )} </Tab.Screen> <Tab.Screen name="Settings"> {(screenProps) => ( <> <Appbar.Header> <Appbar.Content title={`Settings | ${title}`} /> </Appbar.Header> <SettingsScreen {...screenProps} writeNewSettings={writeNewSettings} /> </> )} </Tab.Screen> </Tab.Navigator> </NavigationContainer> ); }; Navigation.propTypes = { sensorData: PropTypes.array.isRequired, writeNewSettings: PropTypes.func.isRequired, }; export default withTheme(Navigation);
{{ config(materialized='view') }} -- stg_snowdepth_data with source as ( select * from {{ source('snowdepth', 'V_snowdepth_intensive_data') }} ), stg_snowdepth_data as ( select sn_region, sn_locality, sn_section, sn_site, sn_plot::int, t_date::date, v_observer, v_depth::int, extract(YEAR from t_date::date) as year from source where 1 is not null ) select * from stg_snowdepth_data
/** * @file Runnable_Demo.cpp * * @author Modified by David Zemon */ #include <PropWare/concurrent/runnable.h> #include <PropWare/PropWare.h> #include <PropWare/hmi/output/synchronousprinter.h> #include <PropWare/gpio/pin.h> using PropWare::Runnable; using PropWare::Pin; class TalkingThread: public Runnable { public: template<size_t N> TalkingThread(const uint32_t (&stack)[N]) : Runnable(stack) { } void run() { while (1) { pwSyncOut.printf("Hello from cog %u (0x%08X)! %u\n", cogid(), (unsigned int) this, CNT); waitcnt(250 * MILLISECOND + CNT); } } }; class BlinkingThread: public Runnable { public: template<size_t N> BlinkingThread(const uint32_t (&stack)[N], const Pin::Mask mask) : Runnable(stack), m_mask(mask) { } void run() { const Pin pin(this->m_mask, Pin::Dir::OUT); while (1) { pin.toggle(); waitcnt(250 * MILLISECOND + CNT); } } private: const Pin::Mask m_mask; }; /** * @example Runnable_Demo.cpp * * Run code in a total of four cogs. Two of them will simply blink LEDs. The other two demonstrate a thread-safe way to * use a serial terminal simultaneously from two different cogs. * * @include PropWare_Runnable/CMakeLists.txt */ int main(int argc, char *argv[]) { uint32_t stack[3][70]; TalkingThread talkingThread(stack[0]); BlinkingThread blink16(stack[1], Pin::Mask::P16); BlinkingThread blink17(stack[2], Pin::Mask::P17); int8_t cog = Runnable::invoke(talkingThread); pwSyncOut.printf("Talking thread (0x%08X) started in cog %d\n", (unsigned int) &talkingThread, cog); cog = Runnable::invoke(blink16); pwSyncOut.printf("Blink16 thread (0x%08X) started in cog %d\n", (unsigned int) &blink16, cog); cog = Runnable::invoke(blink17); pwSyncOut.printf("Blink17 thread (0x%08X) started in cog %d\n", (unsigned int) &blink17, cog); while (1) { pwSyncOut.printf("Hello from cog %u! %u\n", cogid(), CNT); waitcnt(250 * MILLISECOND + CNT); } }
## # Copyright (c) 2012-2015 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## """ Defines a set of HTTP requests to execute and return results. """ class HTTPTestBase(object): """ Base class for an HTTP request that executes and results are returned for. """ class SQLResults(object): def __init__(self, count, rows, timing): self.count = count self.rows = rows self.timing = timing def __init__(self, label, sessions, logFilePath, logFilePrefix): """ @param label: label used to identify the test @type label: C{str} """ self.label = label self.sessions = sessions self.logFilePath = logFilePath self.logFilePrefix = logFilePrefix self.result = None def execute(self, count): """ Execute the HTTP request and read the results. """ self.prepare() self.clearLog() self.doRequest() self.collectResults(count) self.cleanup() return self.result def prepare(self): """ Do some setup prior to the real request. """ pass def clearLog(self): """ Clear the server's SQL log file. """ open(self.logFilePath, "w").write("") def doRequest(self): """ Execute the actual HTTP request. Sub-classes override. """ raise NotImplementedError def collectResults(self, event_count): """ Parse the server log file to extract the details we need. """ def extractInt(line): pos = line.find(": ") return int(line[pos + 2:]) def extractFloat(line): pos = line.find(": ") return float(line[pos + 2:]) # Need to skip over stats that are unlabeled data = open(self.logFilePath).read() lines = data.splitlines() offset = 0 while True: if lines[offset] == "*** SQL Stats ***": if lines[offset + 2].startswith("Label: <"): count = extractInt(lines[offset + 4]) rows = extractInt(lines[offset + 5]) timing = extractFloat(lines[offset + 6]) self.result = HTTPTestBase.SQLResults(count, rows, timing) break offset += 1 else: self.result = HTTPTestBase.SQLResults(-1, -1, 0.0) # Archive current sqlstats file with open("%s-%s-%d-%s" % (self.logFilePath, self.logFilePrefix, event_count, self.label), "w") as f: f.write(data) def cleanup(self): """ Do some cleanup after the real request. """ pass
/* * @Description: 基本形状 参考: * 官网:http://wiki.ros.org/action/fullsearch/rviz/Tutorials/Markers%3A%20Basic%20Shapes?action=fullsearch&context=180&value=linkto%3A%22rviz%2FTutorials%2FMarkers%3A+Basic+Shapes%22 * 中文博客: https://www.cnblogs.com/wxt11/p/6561283.html * @Author: HCQ * @Company(School): UCAS * @Email: [email protected] * @Date: 2020-11-18 16:48:13 * @LastEditTime: 2020-11-19 14:54:10 * @FilePath: /ROS/catkin_wp/src/learning_visualization/src/1basic_shapes.cpp */ #include "ros/ros.h" #include "visualization_msgs/Marker.h" #include <math.h> int main(int argc,char** argv) { ros::init(argc,argv,"basic_shapes"); ros::NodeHandle n; ros::Rate r(1); ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("visualization_marker",1); // 话题 //将我们的初始形状类型设置为立方体cube uint32_t shape = visualization_msgs::Marker::CUBE; while(ros::ok()) { visualization_msgs::Marker marker; //设置frame ID and timestamp。有关这些信息,请参见TF教程。 marker.header.frame_id = "/my_frame"; // frame_id 和rviz对应起来 marker.header.stamp = ros::Time::now(); //设置此标记的namespace和id。这用于创建唯一的id //任何使用相同namespace和id发送的标记都将覆盖旧标记 marker.ns = "basic_shapes"; marker.id = 0; // 每次获取到机器人的位姿后,就在对应点发布一个标志,然后将lifetime设为0,也就是无限久地保存~~ // 但是需要注意一点,让ns或者id变量每次都不一样,否则ns和id一直一样的话,后面的操作会覆盖前面的操作,也就一直只能看到最新的了。建议每次让id+=1。 //设置the marker type。最初是CUBE,并且在那个和SPHERE,ARROW和CYLINDER之间循环 marker.type = shape; // //设置marker action。选项包括ADD,DELETE和new marker.action = visualization_msgs::Marker::ADD; // 设置the pose of the marker。这是相对于标头中指定的frame/time的完整6DOF pose marker.pose.position.x = 0; marker.pose.position.y = 0; marker.pose.position.z = 0; marker.pose.orientation.x = M_PI; // π 3.1415 Roll:两侧摆动 marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; //设置标记的比例尺scale -1x1x1,此处表示1m marker.scale.x = 1.0; marker.scale.y = 1.0; marker.scale.z = 1.0; // 设置颜色-确保将alpha设置为非零值! marker.color.r = 0.0f; marker.color.g = 1.0f; marker.color.b = 0.0f; marker.color.a = 1.0; marker.lifetime = ros::Duration(); // Publish the marker while(marker_pub.getNumSubscribers() < 1) { if(!ros::ok()) { return 0; } ROS_WARN_ONCE("Please create a subscriber to the marker"); sleep(1); } marker_pub.publish(marker); // 发布消息 marker 消息msg // 在不同形状之间循环 Cycle between different shapes switch(shape) { case visualization_msgs::Marker::CUBE: // 立方体 shape = visualization_msgs::Marker::SPHERE; // 球 break; case visualization_msgs::Marker::SPHERE: // 球 shape = visualization_msgs::Marker::ARROW; break; case visualization_msgs::Marker::ARROW: // 箭头 shape = visualization_msgs::Marker::CYLINDER; break; case visualization_msgs::Marker::CYLINDER: // 圆柱 shape = visualization_msgs::Marker::CUBE; break; } r.sleep(); } }
require_relative "scraper.rb" require_relative "sports.rb" require 'nokogiri' require 'colorize' class TempPostgame::CLI BASE_PATH = "http://www.thepostgame.com/tag/nfl" def call puts "Welcome to temp Postgame" menu make_sports_menu add_attributes_to_stories display_stories end def menu puts "Read latest stories about sports you like..................... Enter any number between [1-9] OR type list sports - to display sports names - you want to read stories about OR type exit" end def make_sports_menu sports_array = Scraper.scrape_menu(BASE_PATH) Sports.create_from_collection(sports_array) end def add_attributes_to_stories stories_array = Scraper.scrape_stories_details(BASE_PATH) stories_array.each do |story| Sports.create_from_collection_stories(story) end end def display_stories end end
<?php namespace App\Services; use App\Imports\ExcelImport; use Illuminate\Support\Collection; use Excel; class UploadsExcel{ protected $file; public function __construct($file) { $this -> file = $file; } /** * excel解析之后,会包含sheet分页和所有的列,这儿取出第一页 * * @return array excel解析的多维数组 */ public function getCodetoArray(){ $codes = Excel::toArray(new ExcelImport, $this -> file); $codes = $this -> firstSheet($codes); $codes = $this -> firstCol($codes); return $codes; } /** * excel解析之后,会包含sheet分页和所有的列,这儿取出第一页 * * @param [array] $arr * @return array */ protected function firstSheet($arr){ return $arr[0]; } /** * excel解析之后,会包含sheet分页和所有的列,这儿取出第一列 * * @param [array] $codes * @return collection */ protected function firstCol($codes) { $collection = new Collection(); foreach($codes as $code){ $collection->push($code[0]); } return $collection; } }
using UnityEngine; using System.Collections; public enum AN_CameraCaptureType { Thumbnail = 0, FullSizePhoto = 1 }
--- title: 2020-09-28_19.36.28 pos: -174.063 33.00000 -414.98 world: minecraft:the_nether cover: /images/2020-09-28_19.36.28.png --- ![](/images/2020-09-28_19.36.28.png)
#!/bin/sh # Don't ask ssh password all the time #if [ "$(uname -s)" = "Darwin" ]; then # git config --global credential.helper osxkeychain #else # git config --global credential.helper cache #fi # better diffs if command -v diff-so-fancy >/dev/null 2>&1; then git config --global core.pager "diff-so-fancy | less --tabs=4 -RFX" git config --global color.ui true git config --global color.diff-highlight.oldNormal "red bold" git config --global color.diff-highlight.oldHighlight "red bold 52" git config --global color.diff-highlight.newNormal "green bold" git config --global color.diff-highlight.newHighlight "green bold 22" git config --global color.diff.meta "11" git config --global color.diff.frag "magenta bold" git config --global color.diff.commit "yellow bold" git config --global color.diff.old "red bold" git config --global color.diff.new "green bold" git config --global color.diff.whitespace "red reverse" fi
'use strict'; /** * Module dependencies */ var path = require('path'), mongoose = require('mongoose'), FRTest = mongoose.model('FRTest'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); /** * Create an Facial Recognition Test */ exports.createfacialRecog = function (req, res) { var facialRecogTest = new FRTest(req.body); // facialRecogTest.provider = 'local'; facialRecogTest.user = req.user; facialRecogTest.save(function (err) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(facialRecogTest); } }); };
# Exercises ## Use partial or bind You can often use more general functions to define more specific functions. - Define function `power()` which is an alias to `Math.pow()`. - Implement function `square()` which returns a number to the power of two. - `bind()` function `power(base, power)` to obtain function `cube(n)`. ## Use closure Use constructor-like function that returns a function to define different specific functions. ## Use lambdas (arrow functions) Use nested functions for functional inheritance. ## Use bind Use method bind() to existing function to apply preceding arguments and obtain a new function. ## Use curry Given function `someFunc()` which accepts `n` arguments (e.g. 3 arguments). Implement function `curry()` that generates other function which accepts `someFunc()` arguments partially and supplies them to `someFunc()`: ```js const func = curry(3, someFunc); func(a)(b)(c) === someFunc(a, b, c) // true func(a, b)(c) === someFunc(a, b, c) // true func(a)(b, c) === someFunc(a, b, c) // true ``` ## Exercises Implement one-argument function that passes its argument to another function and returns an object which has the same function: ```js func(a).func(b).func(c) === someFunc(a, b, c) // true ```
import React from "react"; import Login from "../components/authentication/Login"; import LoggedOutLayout from "../components/common/LoggedOutLayout"; function login() { return ( <LoggedOutLayout> <Login /> </LoggedOutLayout> ); } export default login;
import { injectable, createContainer, createStore, action, state, createState, ReactantAction, } from '../..'; test('base `@state`', () => { @injectable() class Counter { @state count1 = 0; @state others = { list: [] as number[], }; @state count = createState<number, ReactantAction>((_state = 0, _action) => _action.type === (this as any).name ? _action.state.count : _state ); @action increase() { this.count += 1; } @action increase1() { this.count1 += 1; } @action add() { this.others.list.push(this.others.list.length); } } const ServiceIdentifiers = new Map(); const modules = [Counter]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const counter = container.get(Counter); const store = createStore(modules, container, ServiceIdentifiers); expect(counter.count).toBe(0); expect(Object.values(store.getState())).toEqual([ { count: 0, count1: 0, others: { list: [] } }, ]); counter.increase(); expect(counter.count).toBe(1); counter.add(); expect(counter.others.list).toEqual([0]); expect(Object.values(store.getState())).toEqual([ { count: 1, count1: 0, others: { list: [0] } }, ]); counter.increase1(); expect(counter.count1).toBe(1); }); test('`@state` about inheritance', () => { @injectable() class BaseCounter { @state count = 0; @state state = { test: 'test', }; @action add() { this.state.test += '1'; } @action increase() { this.count += 1; } } @injectable() class Counter extends BaseCounter { @state count = 10; } const ServiceIdentifiers = new Map(); const modules = [Counter]; const container = createContainer({ ServiceIdentifiers, modules, options: { defaultScope: 'Singleton', }, }); const counter = container.get(Counter); const store = createStore(modules, container, ServiceIdentifiers); expect(counter.count).toBe(10); counter.increase(); expect(counter.count).toBe(11); counter.add(); expect(counter.state.test).toBe('test1'); // console.log(store.getState()); const ServiceIdentifiers1 = new Map(); const container1 = createContainer({ ServiceIdentifiers: ServiceIdentifiers1, modules, options: { defaultScope: 'Singleton', }, }); const counter1 = container1.get(Counter); const store1 = createStore(modules, container1, ServiceIdentifiers1); expect(counter1.count).toBe(10); counter1.increase(); expect(counter1.count).toBe(11); counter1.add(); expect(counter1.state.test).toBe('test1'); });
(comment re-core, Copyright 2012 Ronen Narkis, narkisr.com Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns re-core.api.core "Core api components" (:require [clojure.java.io :refer (file)] [re-core.ssl :refer (generate-store)] [re-core.api :refer (app)] [ring.adapter.jetty :refer (run-jetty)] [components.core :refer (Lifecyle)] [re-core.common :refer (get! get* import-logging)] )) (import-logging) (def jetty (atom nil)) (defn cert-conf "Celetial cert configuration" [k] (get! :re-core :cert k)) (defn default-key "Generates a default keystore if missing" [] (when-not (.exists (file (cert-conf :keystore))) (info "generating a default keystore") (generate-store (cert-conf :keystore) (cert-conf :password)))) (defrecord Jetty [] Lifecyle (setup [this] (default-key)) (start [this] (info "Starting jetty") (reset! jetty (run-jetty (app true) {:port (get! :re-core :port) :join? false :ssl? true :keystore (cert-conf :keystore) :key-password (cert-conf :password) :ssl-port (get! :re-core :https-port)})) ) (stop [this] (when @jetty (info "Stopping jetty") (.stop @jetty) (reset! jetty nil)))) (defn instance "creates a Elastic components" [] (Jetty.))
package org.hildan.fxlog.view; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.function.Consumer; import java.util.function.Function; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.binding.IntegerExpression; import javafx.beans.binding.ListBinding; import javafx.beans.property.ObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.stage.Window; import com.sun.javafx.scene.control.skin.TableViewSkin; import com.sun.javafx.scene.control.skin.VirtualFlow; import org.controlsfx.control.textfield.CustomTextField; import org.controlsfx.control.textfield.TextFields; public class UIUtils { /** * Adds a clear button to the right of the text field. The little cross appears only when the field is not empty. * * @param customTextField * the text field to decorate */ public static void makeClearable(CustomTextField customTextField) { try { Method method = TextFields.class.getDeclaredMethod("setupClearButtonField", TextField.class, ObjectProperty.class); method.setAccessible(true); method.invoke(null, customTextField, customTextField.rightProperty()); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } public static BooleanBinding noItemIsSelected(TableView<?> tableView) { return tableView.getSelectionModel().selectedItemProperty().isNull(); } public static BooleanBinding firstItemIsSelected(TableView<?> tableView) { return tableView.getSelectionModel().selectedIndexProperty().isEqualTo(0); } public static BooleanBinding lastItemIsSelected(TableView<?> tableView) { IntegerExpression lastIndex = Bindings.createIntegerBinding(() -> tableView.getItems().size() - 1, tableView.itemsProperty()); return tableView.getSelectionModel().selectedIndexProperty().isEqualTo(lastIndex); } /** * Scrolls the given table view to the given item. This is nicer than {@link TableView#scrollTo(int)} because it * doesn't put the target item at the top, but rather at about a third of the screen. * * @param table * the table view to scroll * @param index * the index to scroll to */ @SuppressWarnings("WeakerAccess") public static void scrollTo(TableView table, int index) { int numberOfVisibleItems = getNumberOfVisibleItems(table); table.scrollTo(index - numberOfVisibleItems / 3); } @SuppressWarnings("WeakerAccess") public static int getNumberOfVisibleItems(TableView table) { return getLastVisibleRowIndex(table) - getFirstVisibleRowIndex(table); } public static int getFirstVisibleRowIndex(TableView table) { VirtualFlow<?> flow = getVirtualFlow(table); if (flow == null || flow.getFirstVisibleCellWithinViewPort() == null) { return 0; } int indexFirst = flow.getFirstVisibleCellWithinViewPort().getIndex(); if (indexFirst >= table.getItems().size()) { return table.getItems().size() - 1; } else { return indexFirst; } } @SuppressWarnings("WeakerAccess") public static int getLastVisibleRowIndex(TableView table) { VirtualFlow<?> flow = getVirtualFlow(table); if (flow == null || flow.getLastVisibleCellWithinViewPort() == null) { return 0; } int index = flow.getLastVisibleCellWithinViewPort().getIndex(); if (index >= table.getItems().size()) { return table.getItems().size() - 1; } else { return index; } } private static VirtualFlow<?> getVirtualFlow(TableView table) { TableViewSkin<?> skin = (TableViewSkin) table.getSkin(); if (skin == null) { return null; } return (VirtualFlow) skin.getChildren().get(1); } public static void whenWindowReady(Node anyChild, Consumer<? super Window> handler) { ChangeListener<Scene> onNewScene = (obsScene, oldScene, newScene) -> { ChangeListener<? super Window> oneShotWindowListener = asOneShotListener(asListener(handler)); newScene.windowProperty().addListener(oneShotWindowListener); }; anyChild.sceneProperty().addListener(asOneShotListener(onNewScene)); } private static <T> ChangeListener<T> asListener(Consumer<T> handler) { return (obs, oldValue, newValue) -> handler.accept(newValue); } private static <T> ChangeListener<T> asOneShotListener(ChangeListener<T> handler) { return new ChangeListener<T>() { public void changed(ObservableValue<? extends T> obs, T oldValue, T newValue) { handler.changed(obs, oldValue, newValue); obs.removeListener(this); } }; } public static <S, C> ListBinding<C> selectList(ObservableValue<S> source, Function<S, ObservableList<C>> getList) { return new ListBinding<C>() { { bind(source); } @Override protected ObservableList<C> computeValue() { S sourceValue = source.getValue(); if (sourceValue != null) { return getList.apply(sourceValue); } else { return FXCollections.emptyObservableList(); } } }; } }
import { inject, injectable } from 'inversify'; import { HTMLInputProvider, InputKey, InputProvider } from '@uni.js/html-input'; import { ClientSideManager } from '@uni.js/client'; import * as Events from '../../event/internal'; @injectable() export class PickDropManager extends ClientSideManager { constructor(@inject(HTMLInputProvider) private input: InputProvider) { super(); } doFixedUpdateTick() { if (this.input.keyDown(InputKey.Q)) { this.emitEvent(Events.DropItemEvent, {}); } if (this.input.keyDown(InputKey.R)) { this.emitEvent(Events.PickItemEvent, {}); } } }
--- author: person layout: post-full title: FastKat 2 featimg: https://www.omiod.com/gfx/fastkat/fastkat-2-logo.png tags: [text] embed: https://www.omiod.com/games/FK2/ category: [standard] --- Avoid hitting the particles by moving with your mouse. Try to stay alive and earn as many points as possible.
#!/usr/bin/env bats load test_helpers/utilities setup_file() { echo "# 🚧" >&3 docker-compose up --detach collector app-sdk wait_for_ready_app 'app-sdk' curl --silent "http://localhost:5001" wait_for_traces } teardown_file() { cp collector/data.json collector/data-results/data-sdk.json docker-compose stop app-sdk docker-compose restart collector wait_for_flush } # TESTS @test "Manual instrumentation produces span with name of span" { result=$(span_names_for 'examples') assert_equal "$result" '"greetings"' } @test "Manual instrumentation adds custom attribute" { result=$(span_attributes_for "examples" | jq "select(.key == \"custom_field\").value.stringValue") assert_equal "$result" '"important value"' }
--- uid: System.Web.UI.Design.Directives.SchemaElementNameAttribute ms.author: "riande" --- --- uid: System.Web.UI.Design.Directives.SchemaElementNameAttribute.Value ms.author: "riande" --- --- uid: System.Web.UI.Design.Directives.SchemaElementNameAttribute.#ctor(System.String) ms.author: "riande" ---
module Profitwell class Plans include Request def all request( "get", resource_path("plans") ) end def find(plan_id) request( "get", resource_path("plans/#{plan_id}") ) end def create(params = {}) request( "post", resource_path("plans"), options: params ) end def update(plan_id, params = {}) request( "put", resource_path("plans/#{plan_id}"), options: params ) end private def a_request response = HTTParty.send("get", Profitwell.base_endpoint + "/plans/", headers: { 'Content-Type': Profitwell.content_type, 'Authorization': Profitwell.access_token }) end end end
import { BigNumber } from '@0x/utils'; import { Web3Wrapper } from '@0x/web3-wrapper'; // HACK (xianny): copied from asset-swapper, which will replace this package const ONE_AMOUNT = new BigNumber(1); const ETHER_TOKEN_DECIMALS = 18; export const numberPercentageToEtherTokenAmountPercentage = (percentage: number): BigNumber => { return Web3Wrapper.toBaseUnitAmount(ONE_AMOUNT, ETHER_TOKEN_DECIMALS).multipliedBy(percentage); };
#!/usr/bin/env bash sed -i.bak "s/\( *\)s\.version\( *\)=\( *\)\".*\"/\1s\.version\2=\3\"${LD_RELEASE_VERSION}\"/" ios/LaunchdarklyReactNativeClient.podspec rm -f ios/LaunchdarklyReactNativeClient.podspec.bak sed -i.bak "s/\( *\)\"version\"\( *\):\( *\)\".*\"/\1\"version\"\2:\3\"${LD_RELEASE_VERSION}\"/" package.json rm -f package.json.bak
import { QuestionsType } from "./conf"; import { OpenTDBResponse } from "./providers/openTrivia"; import { ProviderList } from "./providers/providers"; export class Question { answers: Answer[]; type: QuestionsType; category: string; text: string; number: number; getCorrectAnswer() { return this.answers.find(answer => answer.isCorrect); } isAnswerCorrect(id: number) { return id != null && this.answers[id].isCorrect; } } export class Answer { answerText: string; isCorrect: boolean; constructor(text: string, isCorrect: boolean) { this.answerText = text; this.isCorrect = isCorrect; } }
package pl.wicherska.songs; import pl.wicherska.songs.handlers.UserAction; import pl.wicherska.songs.interfaces.UserActionHandler; import pl.wicherska.songs.util.ScannerWrapper; import java.util.Map; public class ApplicationRunner implements Runnable { private final Map<UserAction, UserActionHandler> handlers; private final ScannerWrapper scannerWrapper; public ApplicationRunner(Map<UserAction, UserActionHandler> handlers, ScannerWrapper scannerWrapper) { this.handlers = handlers; this.scannerWrapper = scannerWrapper; } public void run() { do { handlers.get(scannerWrapper.nextEnum(UserAction.class)).handle(); System.out.println("Do you want to continue?"); } while (scannerWrapper.nextBoolean()); } }
#!/bin/sh echo "running init.sh script" export SERVICEUSER_USERNAME=$(cat /secret/serviceuser/username) export SERVICEUSER_PASSWORD=$(cat /secret/serviceuser/password)
# API Backends Examples in this directory are intended to provide basic working backend CSRF-protected APIs, compatible with the JavaScript frontend examples available in the [`examples/javascript-frontends`](../javascript-frontends). In addition to CSRF protection, these backends provide the CORS configuration required for communicating the CSRF cookies and headers with JavaScript client code running in the browser. See [`examples/javascript-frontends`](../javascript-frontends/README.md) for details on CORS and CSRF configuration compatibility requirements.
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: test-connection.lisp ;;;; Purpose: Tests for CLSQL database connections ;;;; Authors: Marcus Pearce and Kevin M. Rosenberg ;;;; Created: March 2004 ;;;; ;;;; This file is part of CLSQL. ;;;; ;;;; CLSQL users are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ************************************************************************* (in-package #:clsql-tests) (setq *rt-connection* '( (deftest :connection/1 (let ((database (clsql:find-database (clsql:database-name clsql:*default-database*) :db-type (clsql-sys:database-type clsql:*default-database*)))) (eql (clsql-sys:database-type database) *test-database-type*)) t) (deftest :connection/2 (clsql-sys::string-to-list-connection-spec "localhost/dbname/user/passwd") ("localhost" "dbname" "user" "passwd")) (deftest :connection/3 (clsql-sys::string-to-list-connection-spec "dbname/user@hostname") ("hostname" "dbname" "user")) (deftest :connection/execute-command ;;check that we can issue basic commands. (values (clsql-sys:execute-command "CREATE TABLE DUMMY (foo integer)") (clsql-sys:execute-command "DROP TABLE DUMMY")) nil nil) (deftest :connection/query ;;check that we can do a basic query (first (clsql:query "SELECT 1" :flatp t :field-names nil)) 1) (deftest :connection/query-command ;;queries that are commands (no result set) shouldn't cause breakage (values (clsql-sys:query "CREATE TABLE DUMMY (foo integer)") (clsql-sys:query "DROP TABLE DUMMY")) nil nil) (deftest :connection/pool/procedure-mysql (unwind-protect (progn (clsql-sys:disconnect) (test-connect :pool t) (clsql-sys:execute-command "CREATE PROCEDURE prTest () BEGIN SELECT 1 \"a\",2 \"b\",3 \"c\" ,4 \"d\" UNION SELECT 5,6,7,8; END;") (clsql-sys:disconnect) (test-connect :pool t) (let ((p0 (clsql-sys:query "CALL prTest();" :flatp t))) (clsql-sys:disconnect) (test-connect :pool t) (let ((p1 (clsql-sys:query "CALL prTest();" :flatp t))) (clsql-sys:disconnect) (test-connect :pool t) (values p0 p1)))) (ignore-errors (clsql-sys:execute-command "DROP PROCEDURE prTest;")) (test-connect)) ((1 2 3 4) (5 6 7 8)) ((1 2 3 4) (5 6 7 8))) ))
<?php namespace Tests\Feature; use Tests\TestCase; use App\Report; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\DatabaseMigrations; class ReportTest extends TestCase { public static function setUpBeforeClass() : void { shell_exec('php artisan migrate:fresh --seed'); } public static function tearDownAfterClass() : void { parent::tearDownAfterClass(); shell_exec('php artisan migrate:fresh --seed'); } public function testNewReportInDatabase() { $report = Report::create([ 'title' => 'Test report', 'description' => 'Test report description', 'lat' => '52.261111', 'lng' => '76.951111', 'videos' => [ 'https://www.youtube.com/watch?v=jsYwFizhncE', 'https://www.youtube.com/watch?v=PFDu9oVAE-g', 'https://www.youtube.com/watch?v=aircAruvnKk', 'https://www.youtube.com/watch?v=3d6DsjIBzJ4', ] ]); $dbreport = Report::all()->last(); $this->assertEquals($dbreport->title, 'Test report'); $this->assertEquals($dbreport->description, 'Test report description'); $this->assertEquals($dbreport->lat, '52.261111'); $this->assertEquals($dbreport->lng, '76.951111'); $this->assertEquals($dbreport->videos, [ 'https://www.youtube.com/watch?v=jsYwFizhncE', 'https://www.youtube.com/watch?v=PFDu9oVAE-g', 'https://www.youtube.com/watch?v=aircAruvnKk', 'https://www.youtube.com/watch?v=3d6DsjIBzJ4', ]); $dbreport->delete(); $report = Report::create([ 'title' => 'Test report 2', 'description' => 'Test report description 2', 'lat' => '52.261112', 'lng' => '76.951112', 'videos' => [ '' ], ]); } public function testNewReportDisplayed() { $user = \App\User::findOrFail(1); $report = Report::create([ 'title' => 'Test report', 'description' => 'Test report description', 'lat' => '52.269111', 'lng' => '76.953111', 'videos' => [ 'https://www.youtube.com/watch?v=jsYwFizhncE', 'https://www.youtube.com/watch?v=PFDu9oVAE-g', 'https://www.youtube.com/watch?v=aircAruvnKk', 'https://www.youtube.com/watch?v=3d6DsjIBzJ4', ], ]); $response = $this->actingAs($user)->get('/'); $response->assertSee('Test report'); $response->assertSee('Test report description'); $response->assertSee(52.269111); $response->assertSee(76.953111); $response->assertSeeInOrder([ 'jsYwFizhncE', 'PFDu9oVAE-g', 'aircAruvnKk', '3d6DsjIBzJ4', ]); $report->delete(); } public function testReportEditInDatabase() { $report = Report::first(); $report->title = 'Edited report title'; $report->description = 'Edited report description'; $report->lat = '52.269999'; $report->lng = '76.959999'; $report->videos = null; $report->save(); $dbreport = Report::first(); $this->assertEquals($dbreport->title, 'Edited report title'); $this->assertEquals($dbreport->description, 'Edited report description'); $this->assertEquals($dbreport->lat, '52.269999'); $this->assertEquals($dbreport->lng, '76.959999'); $this->assertEquals($dbreport->videos, null); } public function testNewReportWithImagesInDatabase() { $report = factory(\App\Report::class)->state('test')->create([ 'images' => [ '/public/assets/images/auth-img.png', '/public/assets/images/auth-img-2.png', '/public/assets/images/auth-img-3.png', '/public/assets/images/catword.png', '/public/assets/images/404.png', ], ]); $dbreport = Report::all()->last(); $this->assertEqualsCanonicalizing($dbreport->images, [ '/public/assets/images/auth-img.png', '/public/assets/images/auth-img-2.png', '/public/assets/images/auth-img-3.png', '/public/assets/images/catword.png', '/public/assets/images/404.png', ]); } public function testReportImagesAreDisplayedOnFrontPage() { $user = \App\User::findOrFail(1); $report = factory(\App\Report::class)->state('test')->create([ 'images' => [ '/public/assets/images/auth-img.png', '/public/assets/images/auth-img-2.png', '/public/assets/images/auth-img-3.png', '/public/assets/images/catword.png', '/public/assets/images/404.png', ], ]); $response = $this->actingAs($user)->get('/'); $response->assertStatus(200); $response->assertSeeInOrder([ '/public/assets/images/auth-img.png', '/public/assets/images/auth-img-2.png', '/public/assets/images/auth-img-3.png', '/public/assets/images/catword.png', '/public/assets/images/404.png', ]); } }
#!/bin/bash domain="$1" #python ./scripts/prep_hdf5.py \ # --w2v ./w2v/glove.6B.300d.txt \ # --name ./data/preprocessed/"$domain"_MATE \ # --data ./data/set_dataset/"$domain".trn \ # --lemmatize python ./scripts/prep_hdf5_inference.py \ --data ./data/set_dataset/"$domain".trn \ --name ./data/preprocessed/"$domain"_MATE_ALL \ --vocab ./data/preprocessed/"$domain"_MATE_word_mapping.txt \ --products ./data/preprocessed/"$domain"_MATE_product_mapping.txt \ --lemmatize echo
--- title: Views page_title: Views | Telerik UI FileManager HtmlHelper for ASP.NET Core description: "Get familiar with Grid and Thumbs Views in Telerik UI FileManager for ASP.NET Core." slug: htmlhelpers_filemanager_aspnetcore_views position: 4 --- # Views Overview
import java.io.IOException; import java.net.URL; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; /** * Extracts the size from an image. The image is identified by an URI. * Does not read the entire image, just the headers. * * @author dan */ public class ImageInfo { /** * Get the image size. * * @param uri The systemId of the image. * @return A formatted string containing the width and the height, * separated by a comma. If the image could not be read, the returned * string is "-1,-1". */ public static String getImageSize(String uri) { int width = -1; int height = -1; try { URL url = new URL(uri); ImageInputStream imageInputStream = ImageIO.createImageInputStream(url.openConnection().getInputStream()); Iterator<ImageReader> iter = ImageIO.getImageReaders(imageInputStream); if (iter.hasNext()) { ImageReader reader = iter.next(); try { reader.setInput(imageInputStream); width = reader.getWidth(reader.getMinIndex()); height = reader.getHeight(reader.getMinIndex()); } catch (IOException e) { // Continue with the next reader. } finally { reader.dispose(); try { imageInputStream.close(); } catch (IOException e) { // Ignore } } } } catch (IOException ex) { System.err.println("Cannot determine the image size for " + uri + " because of " + ex); } return width + "," + height; } }
require 'rails_helper' describe SurveyResponseValidation, type: :service do describe '#call' do let(:test_collection) { create(:test_collection, :completed) } let(:survey_response) { create(:survey_response, test_collection: test_collection) } subject { SurveyResponseValidation.new(survey_response) } context 'with single idea' do context 'no questions answered' do it 'returns false' do expect(subject.call).to be false end end context 'some questions answered' do let!(:question_answer) do question_id, idea_id = subject.answerable_ids.first create(:question_answer, survey_response: survey_response, question_id: question_id, idea_id: idea_id) end it 'returns false' do expect(subject.call).to be false end end context 'all questions answered' do let!(:question_answers) do subject.answerable_ids.map do |question_id, idea_id| create(:question_answer, survey_response: survey_response, question_id: question_id, idea_id: idea_id) end end it 'returns true' do # 1 intro, 4 idea questions, 1 outro expect(subject.answerable_ids.count).to eq 6 expect(subject.call).to be true end end end context 'with multiple ideas' do let(:test_collection) { create(:test_collection, :two_ideas, :completed) } context 'no questions answered' do it 'returns false' do expect(subject.call).to be false end end context 'some questions answered' do let!(:question_answer) do question_id, idea_id = subject.answerable_ids.first create(:question_answer, survey_response: survey_response, question_id: question_id, idea_id: idea_id) end it 'returns false' do expect(subject.call).to be false end end context 'all questions answered' do let!(:question_answers) do subject.answerable_ids.map do |question_id, idea_id| create(:question_answer, survey_response: survey_response, question_id: question_id, idea_id: idea_id) end end it 'returns true' do # 1 intro, 4 idea questions x2, 1 outro expect(subject.answerable_ids.count).to eq 10 expect(subject.call).to be true end end context 'switching to in-collection test' do before do test_collection.update(collection_to_test: create(:collection)) test_collection.hide_or_show_section_questions! end context 'all questions answered' do let!(:question_answers) do subject.answerable_ids.map do |question_id, idea_id| create(:question_answer, survey_response: survey_response, question_id: question_id, idea_id: idea_id) end end it 'returns true' do # should just be the 4 idea questions, and only once expect(subject.answerable_ids.count).to eq 4 expect(subject.call).to be true end end end end end end
FactoryBot.define do factory :authentication_token do user { create(:support_user) } hashed_token { SecureRandom.uuid } end end
// "Change type to 'CharSequence'" "true" interface A { val x: CharSequence } class B(override val x: Any<caret>) : A
<?php /** * This file is part of the Phalcon Framework. * * (c) Phalcon Team <[email protected]> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ declare(strict_types=1); namespace Phalcon\Test\Unit\Tag; use Phalcon\Tag; use Phalcon\Test\Fixtures\Helpers\TagSetup; use UnitTester; class SetDefaultsCest extends TagSetup { /** * Tests Phalcon\Tag :: setDefaults() * * @author Phalcon Team <[email protected]> * @since 2018-11-13 */ public function tagSetDefaults(UnitTester $I) { $I->wantToTest('Tag - setDefaults()'); $data = [ 'property1' => 'testVal1', 'property2' => 'testVal2', 'property3' => 'testVal3', ]; Tag::setDefaults($data); $I->assertTrue( Tag::hasValue('property1') ); $I->assertTrue( Tag::hasValue('property2') ); $I->assertTrue( Tag::hasValue('property3') ); $I->assertFalse( Tag::hasValue('property4') ); $I->assertEquals( 'testVal1', Tag::getValue('property1') ); $I->assertEquals( 'testVal2', Tag::getValue('property2') ); $I->assertEquals( 'testVal3', Tag::getValue('property3') ); } }
/* * Copyright (c) 2018-present, [email protected]. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "../include/BaseDrawer.h" #include "log.h" BaseDrawer::BaseDrawer() { } BaseDrawer::~BaseDrawer() { glDeleteBuffers(1, &vbo); if (GL_NONE != program) glDeleteProgram(program); delete[]position; delete[]texCoordinate; // if (GL_NONE != vao) { // GLES30.glDeleteVertexArrays(1, &vao); // } } void BaseDrawer::init() { createVBOs(); // xy float *texCoordinate = new float[8]{ 0.0f, 0.0f,//LEFT,BOTTOM 1.0f, 0.0f,//RIGHT,BOTTOM 0.0f, 1.0f,//LEFT,TOP 1.0f, 1.0f//RIGHT,TOP }; // st float *position = new float[8]{ -1.0f, -1.0f,//LEFT,BOTTOM 1.0f, -1.0f,//RIGHT,BOTTOM -1.0f, 1.0f,//LEFT,TOP 1.0f, 1.0f//RIGHT,TOP }; updateLocation(texCoordinate, position); delete[]texCoordinate; delete[]position; program = getProgram(); aPositionLocation = static_cast<GLuint>(getAttribLocation("aPosition")); uTextureLocation = getUniformLocation("uTexture"); aTextureCoordinateLocation = static_cast<GLuint>(getAttribLocation("aTextureCoord")); } void BaseDrawer::draw(GLuint texture) { useProgram(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glUniform1i(uTextureLocation, 0); enableVertex(aPositionLocation, aTextureCoordinateLocation); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(aPositionLocation); glDisableVertexAttribArray(aTextureCoordinateLocation); glBindTexture(GL_TEXTURE_2D, GL_NONE); glUseProgram(GL_NONE); programUsed = false; glFlush(); } void BaseDrawer::useProgram() { if (programUsed) return; glUseProgram(program); programUsed = true; } GLuint BaseDrawer::createProgram(string vertex, string fragment) { GLuint program = glCreateProgram(); if (program == GL_NONE) { LOGE("Create program failed: %d", glGetError()); } GLuint vertexShader = createShader(GL_VERTEX_SHADER, vertex); GLuint fragmentShader = createShader(GL_FRAGMENT_SHADER, fragment); if (GL_NONE == vertexShader || GL_NONE == fragmentShader) { return GL_NONE; } //附着顶点和片段着色器 glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); //链接program glLinkProgram(program); //告诉OpenGL ES使用此program glUseProgram(program); return program; } /** * Create a shader. * @param type Shader type. * @param shader Shader source code. */ GLuint BaseDrawer::createShader(GLenum type, string shader) { GLuint shaderId = glCreateShader(type); if (shaderId == 0) { LOGE("Create Shader Failed: %d", glGetError()); return 0; } //加载Shader代码 const char *str = shader.c_str(); glShaderSource(shaderId, 1, &str, 0); //编译Shader glCompileShader(shaderId); GLint status; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &status); if (GL_TRUE != status) { #ifdef GL_DEBUG GLint len; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &len); vector<char> log(static_cast<unsigned int>(len)); glGetShaderInfoLog(shaderId, len, nullptr, log.data()); string str(begin(log), end(log)); Logcat::e("HWVC", "BaseDrawer::createShader(%d) error:%s >>>>>>>>> Source: %s", type, str.c_str(), shader.c_str()); #endif glDeleteShader(shaderId); shaderId = GL_NONE; } return shaderId; } void BaseDrawer::enableVertex(GLuint posLoc, GLuint texLoc) { updateVBOs(); if (enableVAO) { _enableVAO(posLoc, texLoc); return; } glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableVertexAttribArray(posLoc); glEnableVertexAttribArray(texLoc); //xy glVertexAttribPointer(posLoc, COUNT_PER_VERTEX, GL_FLOAT, GL_FALSE, 0, 0); //st glVertexAttribPointer(texLoc, COUNT_PER_VERTEX, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<const void *>(VERTEX_BYTE_SIZE)); glBindBuffer(GL_ARRAY_BUFFER, GL_NONE); } void BaseDrawer::_enableVAO(GLuint posLoc, GLuint texLoc) { // if (GL_NONE != vao) { // glGenVertexArrays(1, &vao); // glBindVertexArray(vao); // glBindBuffer(GL_ARRAY_BUFFER, vbo); // // glEnableVertexAttribArray(posLoc); // glEnableVertexAttribArray(texLoc); // // glVertexAttribPointer(posLoc, COORDS_PER_VERTEX, GL_FLOAT, false, 0, 0); // glVertexAttribPointer(texLoc, TEXTURE_COORDS_PER_VERTEX, GL_FLOAT, false, 0, // COORDS_BYTE_SIZE); // glBindVertexArray(GL_NONE); // } // glBindVertexArray(vao); } void BaseDrawer::updateVBOs() { if (!requestUpdateLocation) return; requestUpdateLocation = false; rotateVertex(rotation); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, VERTEX_BYTE_SIZE, position); glBufferSubData(GL_ARRAY_BUFFER, VERTEX_BYTE_SIZE, VERTEX_BYTE_SIZE, texCoordinate); glBindBuffer(GL_ARRAY_BUFFER, GL_NONE); } void BaseDrawer::createVBOs() { glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, VERTEX_BYTE_SIZE * 2, nullptr, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, GL_NONE); } void BaseDrawer::updateLocation(float *texCoordinate, float *position) { if (texCoordinate) { memcpy(this->texCoordinate, texCoordinate, VERTEX_BYTE_SIZE); } if (position) { memcpy(this->position, position, VERTEX_BYTE_SIZE); } requestUpdateLocation = true; } GLint BaseDrawer::getAttribLocation(string name) { return glGetAttribLocation(program, name.c_str()); } GLint BaseDrawer::getUniformLocation(string name) { return glGetUniformLocation(program, name.c_str()); } void BaseDrawer::setRotation(int rotation) { this->rotation = rotation; this->requestUpdateLocation = true; } void BaseDrawer::rotateVertex(int rotation) { int size = 0; switch (rotation) { case ROTATION_VERTICAL: { size = 4 * 4; float *tmp = new float[4]; memcpy(tmp, position, size); memcpy(position, &position[4], size); memcpy(&position[4], tmp, size); delete[]tmp; break; } case ROTATION_HORIZONTAL: { size = 2 * 4; int offset = 0; float *tmp = new float[2]; memcpy(tmp, &position[offset], size); memcpy(&position[offset], &position[offset + 2], size); memcpy(&position[offset + 2], tmp, size); offset = 4; memcpy(tmp, &position[offset], size); memcpy(&position[offset], &position[offset + 2], size); memcpy(&position[offset + 2], tmp, size); delete[]tmp; break; } default: break; } } void BaseDrawer::setUniform1f(GLint location, float value) { glUniform1f(location, value); }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the HiGHS linear optimization suite */ /* */ /* Written and engineered 2008-2021 at the University of Edinburgh */ /* */ /* Available as open-source under the MIT License */ /* */ /* Authors: Julian Hall, Ivet Galabova, Qi Huangfu, Leona Gottwald */ /* and Michael Feldmeier */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file ipm/IpxSolution.h * @brief */ #ifndef IPM_IPX_SOLUTION_H_ #define IPM_IPX_SOLUTION_H_ #include <stdint.h> #include <vector> #include "util/HighsInt.h" typedef HighsInt ipxint; struct IpxSolution { ipxint num_col; ipxint num_row; std::vector<double> ipx_col_value; std::vector<double> ipx_row_value; std::vector<double> ipx_col_dual; std::vector<double> ipx_row_dual; std::vector<ipxint> ipx_col_status; std::vector<ipxint> ipx_row_status; }; #endif
module LogManager class LogsController < ApplicationController layout 'log_layout' def index @app_name = Rails.application.class.parent_name.underscore.humanize @environment = Rails.env log_file_path = "#{Rails.root}/log/#{@environment}.log" @file_size = File.size(log_file_path) @file_size = LogManager::Utils.human_file_size(@file_size) file = File.open(log_file_path) @file_data = file.readlines.map(&:chomp) file.close end end end
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // RUN: %hermes --target=HBC -O %s | %FileCheck %s --match-full-lines // RUN: %hermes --target=HBC -O -dump-ra %s | %FileCheck %s --check-prefix=CHKRA --match-full-lines // Using a Phi in a successor of a Phi predecessor block: // B0: // ... // B1: // %p = PhiInst %a, B0, %b, B2 // ... // B2: // CondBranchInst ..., B1, B3 // B3: // Use %p var glob = null; function bad(param1, param2) { for (;;) { if (param2) param2.foo = 0; if (!param2) { glob = param1; return null; } param1 = param2; } return null; } bad("foo", null); print("phi"); //CHECK: phi print(glob); //CHECK-NEXT: foo //CHKRA-LABEL:function bad(param1, param2) : null //CHKRA-NEXT:frame = [] //CHKRA-NEXT:%BB0: //CHKRA-NEXT: $Reg3 @0 [1...4) %0 = HBCLoadParamInst 1 : number //CHKRA-NEXT: $Reg2 @1 [2...12) %1 = HBCLoadParamInst 2 : number //CHKRA-NEXT: $Reg0 @2 [3...12) %2 = HBCLoadConstInst 0 : number //CHKRA-NEXT: $Reg3 @3 [4...6) %3 = MovInst %0 //CHKRA-NEXT: $Reg1 @4 [empty] %4 = BranchInst %BB1 //CHKRA-NEXT:%BB1: //CHKRA-NEXT: $Reg3 @5 [1...7) [11...12) %5 = PhiInst %3, %BB0, %10, %BB2 //CHKRA-NEXT: $Reg1 @6 [7...14) %6 = MovInst %5 //CHKRA-NEXT: $Reg4 @7 [empty] %7 = CondBranchInst %1, %BB3, %BB2 //CHKRA-NEXT:%BB3: //CHKRA-NEXT: $Reg4 @8 [empty] %8 = StorePropertyInst %2 : number, %1, "foo" : string //CHKRA-NEXT: $Reg4 @9 [empty] %9 = BranchInst %BB2 //CHKRA-NEXT:%BB2: //CHKRA-NEXT: $Reg3 @10 [11...12) %10 = MovInst %1 //CHKRA-NEXT: $Reg0 @11 [empty] %11 = CondBranchInst %10, %BB1, %BB4 //CHKRA-NEXT:%BB4: //CHKRA-NEXT: $Reg0 @12 [13...14) %12 = HBCGetGlobalObjectInst //CHKRA-NEXT: $Reg0 @13 [empty] %13 = StorePropertyInst %6, %12 : object, "glob" : string //CHKRA-NEXT: $Reg0 @14 [15...16) %14 = HBCLoadConstInst null : null //CHKRA-NEXT: $Reg0 @15 [empty] %15 = ReturnInst %14 : null //CHKRA-NEXT:function_end
# frozen_string_literal: true # 二代健保:公司代扣總額 module HealthInsuranceService class CompanyWithhold include Callable attr_reader :year, :month def initialize(year, month) @year = year @month = month end def call premium end private def premium PayrollDetail.monthly_excess_payment(year: year, month: month).reduce(0) do |sum, row| sum + HealthInsuranceService::BonusIncome.call(Payroll.find(row.payroll_id)) end end end end
--- layout: external-link title: Analyzing Socrata data in Microsoft Excel&reg; via OData external_url: https://support.socrata.com/hc/en-us/articles/202950718 ---
namespace hugobelman.wkhtmltopdf { public class WkHtmlToPdfHeaderFooter { private string center; private string left; private string right; private string htmlUrl; private string fontName; private float fontSize = 12.0F; private float spacing = 0.0F; public string Center { get => center; set => center = value; } public string Left { get => left; set => left = value; } public string Right { get => right; set => right = value; } public string HtmlUrl { get => htmlUrl; set => htmlUrl = value; } public string FontName { get => fontName; set => fontName = value; } public float FontSize { get => fontSize; set => fontSize = value; } public float Spacing { get => spacing; set => spacing = value; } public WkHtmlToPdfHeaderFooter() { } public WkHtmlToPdfHeaderFooter(string center, string left, string right) : this(center) { this.left = left; this.right = right; } public WkHtmlToPdfHeaderFooter(string center, string left, string right, string fontName, float fontSize) { this.Center = center; this.Left = left; this.Right = right; this.FontName = fontName; this.FontSize = fontSize; } public WkHtmlToPdfHeaderFooter(string htmlUrl) { this.HtmlUrl = htmlUrl; } } }
--- title: "博客的由来" layout: post date: 2020-02-19 20:16 image: /assets/images/markdown.jpg headerImage: false tag: - essay - preface star: false category: blog author: Zbh description: 在标题下面显示的内容 --- 虽然是colone的但是我想试试,自己也不会弄所以拿别人的样式改一改,原创是谁我也不太清楚,我clone的人他也是clone的。
module FilterParameters PREVIOUS_PARAMETER_PREFIX = 'prev_'.freeze def filter_params parameters.reject do |param| param.in? %w[utf8 authenticity_token page] end end def filter_params_without_previous_parameters remove_previous_parameters(filter_params) end def merge_previous_parameters(all_parameters) previous_parameters.each do |key, value| next if value == 'none' all_parameters[key.delete_prefix(PREVIOUS_PARAMETER_PREFIX)] = value end remove_previous_parameters(all_parameters) end private def parameters return request.query_parameters if %w[GET HEAD].include?(request.method) request.request_parameters end def previous_parameters parameters.select { |key, _value| key.start_with? PREVIOUS_PARAMETER_PREFIX } end def remove_previous_parameters(all_parameters) all_parameters.reject { |key, _value| key.start_with? PREVIOUS_PARAMETER_PREFIX } end end
package com.kylecorry.trail_sense.shared import android.content.res.ColorStateList import android.graphics.Color import android.widget.ImageButton import android.widget.SeekBar import androidx.fragment.app.Fragment import com.google.android.material.bottomnavigation.BottomNavigationView import com.kylecorry.andromeda.core.system.GeoUri import com.kylecorry.andromeda.core.units.PixelCoordinate import com.kylecorry.andromeda.location.IGPS import com.kylecorry.andromeda.signal.CellNetworkQuality import com.kylecorry.andromeda.signal.ICellSignalSensor import com.kylecorry.sol.math.SolMath.roundPlaces import com.kylecorry.sol.math.Vector2 import com.kylecorry.sol.units.DistanceUnits import com.kylecorry.sol.units.Speed import com.kylecorry.sol.units.TimeUnits import com.kylecorry.trail_sense.main.MainActivity import com.kylecorry.trail_sense.R import com.kylecorry.trail_sense.navigation.beacons.domain.Beacon import com.kylecorry.trail_sense.navigation.paths.domain.PathPoint import com.kylecorry.trail_sense.shared.database.Identifiable fun Fragment.requireMainActivity(): MainActivity { return requireActivity() as MainActivity } fun Fragment.requireBottomNavigation(): BottomNavigationView { return requireActivity().findViewById(R.id.bottom_navigation) } fun IGPS.getPathPoint(pathId: Long): PathPoint { return PathPoint( -1, pathId, location, altitude, time ) } fun PixelCoordinate.toVector2(): Vector2 { return Vector2(x, y) } fun Vector2.toPixel(): PixelCoordinate { return PixelCoordinate(x, y) } fun <T : Identifiable> Array<T>.withId(id: Long): T? { return firstOrNull { it.id == id } } fun <T : Identifiable> Collection<T>.withId(id: Long): T? { return firstOrNull { it.id == id } } fun SeekBar.setOnProgressChangeListener(listener: (progress: Int, fromUser: Boolean) -> Unit) { setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { listener(progress, fromUser) } override fun onStartTrackingTouch(seekBar: SeekBar?) { } override fun onStopTrackingTouch(seekBar: SeekBar?) { } }) } fun GeoUri.Companion.from(beacon: Beacon): GeoUri { val params = mutableMapOf( "label" to beacon.name ) if (beacon.elevation != null) { params["ele"] = beacon.elevation.roundPlaces(2).toString() } return GeoUri(beacon.coordinate, null, params) } fun ImageButton.flatten() { backgroundTintList = ColorStateList.valueOf(Color.TRANSPARENT) elevation = 0f } val ZERO_SPEED = Speed(0f, DistanceUnits.Meters, TimeUnits.Seconds) fun ICellSignalSensor.networkQuality(): CellNetworkQuality? { val signal = signals.maxByOrNull { it.strength } return signal?.let { CellNetworkQuality(it.network, it.quality) } }
import {Request, Response, NextFunction} from "express" import * as uuid from "uuid" // TESTING PATCH RELEASE export const userMiddleware = (req: Request, res: Response, next: NextFunction) => { const uwuid = req.cookies.uwuid if (!uwuid) { const id = uuid.v1() res.cookie("uwuid", id) } next() } export default { userMiddleware, }
using Test using HDF5 using DSGE path = dirname(@__FILE__) m = AnSchorfheide() Γ0, Γ1, C, Ψ, Π = eqcond(m) stake = 1 + 1e-6 #G1, C, impact, fmat, fwt, ywt, gev, eu, loose = gensys(Γ0, Γ1, C, Ψ, Π, stake) G1, C, impact, eu = gensys(Γ0, Γ1, C, Ψ, Π, stake) file = "$path/../reference/gensys.h5" G1_exp = h5read(file, "G1_gensys") C_exp = h5read(file,"C_gensys") impact_exp = h5read(file, "impact") eu_exp = h5read(file, "eu") @testset "Check gensys outputs match reference" begin @test @test_matrix_approx_eq G1_exp G1 @test @test_matrix_approx_eq C_exp C @test @test_matrix_approx_eq impact_exp impact @test isequal(eu_exp, eu) end
// https://www.codechef.com/problems/PALL01 #include <iostream> using namespace std; bool is_palindrome() { string number; cin >> number; int delimiter = number.size() - 1; for (int i = 0; i < number.size() / 2; i++) { if (number[i] != number[delimiter]) return false; delimiter--; } return true; } int main() { int t; cin >> t; bool palindrome_check; for (int i = 0; i < t; i++) { palindrome_check = is_palindrome(); if (palindrome_check) cout << "wins" << endl; else cout << "losses" << endl; } return 0; }
--- title: Links --- [My personal Site](http://thomaskoefod.com) ← more links in here if you want [Some notes about and around programming that I have done in the past](http://koefod.us/wp/) [list of different editors I have used](http://koefod.us/wp/editors/) [The Modern JavaScript Tutorial](https://javascript.info/)
/* * Copyright (c) 2017. Yuriy Stul */ package com.stulsoft.aws.test2 import java.io.{ByteArrayInputStream, ByteArrayOutputStream} import org.scalatest.{FlatSpec, Matchers} /** * @author Yuriy Stul */ class MainTest extends FlatSpec with Matchers { behavior of "Main" "greeting" should "return text" in { val input = new ByteArrayInputStream( """ |{ | "firstName": "Robert 13", | "lastName": "Dole 65432" |} """.stripMargin.getBytes()) val output = new ByteArrayOutputStream() Main.greeting(input, output) output.toString shouldBe "Greetings Robert 13 Dole 65432." } }
# AlwaysBaseball Date : 2020 / 09 / 11 # Motivation & Purpose Side Project - Baseball Ecosystem 1. Timeline Wall 2. Like & Comment 3. Live Game Watching 4. Game Recording 5. Team Management 6. Profile Setting 7. MVVM Design Pattern 8. Localization # App Store [Always Baseball - Reviewing](https://apps.apple.com/tw/) # Demo Timeline Wall ![](https://i.imgur.com/reqG8va.gif) Like & Comment ![](https://i.imgur.com/TFhyzOs.gif) Live Game Watching ![](https://i.imgur.com/3SuHBIw.gif) Game Recording ![](https://i.imgur.com/Jk9wSLQ.gif) ![](https://i.imgur.com/qjKlhzL.gif) ![](https://i.imgur.com/EI2nWrD.gif) Team Management ![](https://i.imgur.com/wlVh4qF.gif) ![](https://i.imgur.com/Ou4NXS6.gif) ![](https://i.imgur.com/zyuWhbQ.gif) Profile Setting ![](https://i.imgur.com/JrpUVFO.gif) # Contacts Chien-Yu Yeh <br>[email protected]
require_relative '../excel' require_relative '../util/not_supported_exception' class AstCopyFormula attr_accessor :rows_to_move attr_accessor :columns_to_move def initialize self.rows_to_move = 0 self.columns_to_move = 0 end DO_NOT_MAP = {:number => true, :string => true, :blank => true, :null => true, :error => true, :boolean_true => true, :boolean_false => true, :operator => true, :comparator => true} def copy(ast) return ast unless ast.is_a?(Array) operator = ast[0] if respond_to?(operator) send(operator,*ast[1..-1]) elsif DO_NOT_MAP[operator] return ast else [operator,*ast[1..-1].map {|a| copy(a) }] end end def cell(reference) r = Reference.for(reference) [:cell,r.offset(rows_to_move,columns_to_move)] end def area(start,finish) s = Reference.for(start).offset(rows_to_move,columns_to_move) f = Reference.for(finish).offset(rows_to_move,columns_to_move) [:area,s,f] end def column_range(reference) raise NotSupportedException.new("Column ranges not suported in AstCopyFormula") end def row_range(reference) raise NotSupportedException.new("Row ranges not suported in AstCopyFormula") end end
import { connect, MapDispatchToProps, MapStateToProps } from "react-redux"; import { addCategory, updateCategory } from "./CategoryModal.actions"; import CategoryModalComponent from "./CategoryModal.component"; import { AddCategoryFailureAction, ADD_CATEGORY, UpdateCategoryFailureAction, UPDATE_CATEGORY, } from "./CategoryModal.types"; type modalType = "add" | "update"; export interface CategoryProp { id: number; type: "Income" | "Expense"; name: string; parent?: number; } interface OwnProps { open: boolean; type?: modalType; onClose?: () => void; category?: CategoryProp; } interface StateProps { error?: | AddCategoryFailureAction["error"] | UpdateCategoryFailureAction["error"]; income: { id: number; name: string }[]; expense: { id: number; name: string }[]; } interface DispatchProps { onSubmit(cb?: ActionCallback): (data: CategoryForm) => void; } const mapStateToProps: MapStateToProps<StateProps, OwnProps> = ( { errors, categories }, { type } ) => { const error: StateProps["error"] = errors[type === "update" ? UPDATE_CATEGORY : ADD_CATEGORY]; const income = categories.income.map((v) => ({ id: v.id, name: v.name })); const expense = categories.expense.map((v) => ({ id: v.id, name: v.name })); return { income, expense, error: error || undefined }; }; const mapDispatchToProps: MapDispatchToProps<DispatchProps, OwnProps> = ( dispatch, { type, category } ) => ({ onSubmit: (cb) => (data) => { if (type === "update") { if (data.name === category?.name) delete (data as Partial<CategoryForm>).name; dispatch(updateCategory(category?.id as number, data, cb)); return; } dispatch(addCategory(data, cb)); }, }); export type Props = OwnProps & StateProps & DispatchProps; export default connect( mapStateToProps, mapDispatchToProps )(CategoryModalComponent);
if [ -e ".git/hooks/pre-push" ]; then #get version string cd PHPFramework sh makeDocumentation.sh # ok else echo 'Creating pre-push git hook...' echo '#!/bin/sh' > .git/hooks/pre-push echo 'if [ -x ./_pre_push.sh ]; then' >> .git/hooks/pre-push echo ' source ./_pre_push.sh' >> .git/hooks/pre-push echo 'else' >> .git/hooks/pre-push echo ' echo MISSING PRE-PUSH' >> .git/hooks/pre-push echo 'fi' >> .git/hooks/pre-push fi
--- title: shuffle_order_engine 类 | Microsoft Docs ms.custom: '' ms.date: 11/04/2016 ms.technology: - cpp-standard-libraries ms.topic: reference f1_keywords: - random/std::shuffle_order_engine - random/std::shuffle_order_engine::base - random/std::shuffle_order_engine::discard - random/std::shuffle_order_engine::operator() - random/std::shuffle_order_engine::base_type - random/std::shuffle_order_engine::seed dev_langs: - C++ helpviewer_keywords: - std::shuffle_order_engine [C++] - std::shuffle_order_engine [C++], base - std::shuffle_order_engine [C++], discard - std::shuffle_order_engine [C++], base_type - std::shuffle_order_engine [C++], seed ms.assetid: 0bcd1fb0-44d7-4e59-bb1b-4a9b673a960d author: corob-msft ms.author: corob ms.workload: - cplusplus ms.openlocfilehash: 7893f992fa19cdef8713ec4c9fd755c7cd1b465e ms.sourcegitcommit: 761c5f7c506915f5a62ef3847714f43e9b815352 ms.translationtype: MT ms.contentlocale: zh-CN ms.lasthandoff: 09/07/2018 ms.locfileid: "44100308" --- # <a name="shuffleorderengine-class"></a>shuffle_order_engine 类 通过对从其基引擎中返回的值进行重新排序,生成随机序列。 ## <a name="syntax"></a>语法 ```cpp template <class Engine, size_t K> class shuffle_order_engine; ``` ### <a name="parameters"></a>参数 *引擎*<br/> 基引擎类型。 *K*<br/> **表大小**。 缓冲区(表)中的元素数。 **前提条件**:`0 < K` ## <a name="members"></a>成员 |||| |-|-|-| |`shuffle_order_engine::shuffle_order_engine`|`shuffle_order_engine::base`|`shuffle_order_engine::discard`| |`shuffle_order_engine::operator()`|`shuffle_order_engine::base_type`|`shuffle_order_engine::seed`| 有关引擎成员的详细信息,请参阅 [\<random>](../standard-library/random.md)。 ## <a name="remarks"></a>备注 此模板类描述了通过对其基引擎返回的值进行重新排序来产生值的引擎适配器。 每个构造函数填充内部表与*K*由基引擎返回的值和值请求时从表中选择一个随机元素。 ## <a name="requirements"></a>要求 **标头:**\<random> **命名空间:** std ## <a name="see-also"></a>请参阅 [\<random>](../standard-library/random.md)<br/>
package no.skatteetaten.aurora.gobo.graphql.certificate import com.expediagroup.graphql.server.operations.Query import graphql.schema.DataFetchingEnvironment import no.skatteetaten.aurora.gobo.integration.skap.CertificateService import no.skatteetaten.aurora.gobo.security.checkValidUserToken import org.springframework.stereotype.Component @Component class CertificateQuery(private val certificateService: CertificateService) : Query { suspend fun certificates(dfe: DataFetchingEnvironment): CertificatesConnection { dfe.checkValidUserToken() val certificates = certificateService.getCertificates().map { CertificateEdge(it) } return CertificatesConnection(edges = certificates, pageInfo = null) } }
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call(UsersSeeder::class); $this->call(QuestionsTableSeeder::class); $this->call(JobsTypesTableSeeder::class); $this->call(SectorOportunitysTableSeeder::class); $this->call(UbicationOportunitysTableSeeder::class); $this->call(TimeZoneOportunitysTableSeeder::class); $this->call(TypeOportunitysTableSeeder::class); $this->call(ProfesionsTableSeeder::class); $this->call(StatusOportunitySeeder::class); $this->call(AptitudSeeder::class); $this->call(StatusAplicantsSeeder::class); $this->call(NegotiationStatusesSeeder::class); $this->call(CountriesSeeder::class); $this->call(ModuleLabelsSeeder::class); $this->call(QuestionsSeeder::class); $this->call(TaskPrioritiesSeeder::class); $this->call(TaskQueueSeeder::class); $this->call(TaskTypesSeeder::class); $this->call(ContactTypesSeeder::class); $this->call(JobFunctionSeeder::class); // $this->call(GroupSeeder::class); // $this->call(AplicantsTableSeeder::class); } }
<?php namespace Nickwest\EloquentForms\Test\view\defaults\fields; use Sunra\PhpSimple\HtmlDomParser; use Nickwest\EloquentForms\Field; use Nickwest\EloquentForms\Test\FieldViewTestCase; use Nickwest\EloquentForms\Test\ThemeTestInterfaces\fileFieldTestInterface; class fileFieldTest extends FieldViewTestCase implements fileFieldTestInterface { protected $test_value = 'yoda.pdf'; protected $test_type = 'file'; // Run all basic tests public function test_field_has_correct_value_attribute_when_changed() { $this->Field->attributes->value = $this->test_value; $dom = HtmlDomParser::str_get_html($this->Field->makeView()->render()); $remove_button = current($dom->find($this->test_tag)); $file_link = current($dom->find('div[class=file-link]')); $this->assertEquals('Remove', $remove_button->value); $this->assertEquals('yoda.pdf', trim($file_link->plaintext)); } public function test_remove_button_can_have_a_different_value() { $this->Field->attributes->value = $this->test_value; $this->Field->file_delete_button_value = 'Obliterate'; $dom = HtmlDomParser::str_get_html($this->Field->makeView()->render()); $remove_button = current($dom->find($this->test_tag)); $this->assertEquals('Obliterate', $remove_button->value); } }
Before submitting a new issue, please search on the issue tracker first (https://github.com/neveldo/jQuery-Mapael/issues) ## Description <!--- Describe what you want to achieve --> <!--- Provide a working example if possible (e.g. using JSFiddle https://jsfiddle.net/) --> ## Expected Behavior <!--- If you're describing a bug, tell us what should happen --> <!--- If you're suggesting a change/improvement, tell us how it should work --> ## Current Behavior <!--- If describing a bug, tell us what happens instead of the expected behavior --> <!--- If suggesting a change/improvement, explain the difference from current behavior --> ## Environment <!--- Include all relevant details about your environment --> * Mapael version: * Raphael version: * Browser Name and version: * Operating System and version (desktop or mobile):
--- pid: '5037' object_pid: '3110' label: Feast of the Gods with Marriage of Peleus and Thetis artist: janbrueghel provenance_date: '1827' provenance_location: Copenhagen provenance_text: 'Inventory of the Royal Cabinet of Curiosity, inv. #1023' collection: provenance order: '0437' ---
package coop.rchain.casper.helper import cats.syntax.all._ import cats.effect.Sync import coop.rchain.rspace.state.{RSpaceExporter, RSpaceImporter, RSpaceStateManager} final case class RSpaceStateManagerTestImpl[F[_]: Sync]() extends RSpaceStateManager[F] { override def exporter: RSpaceExporter[F] = ??? override def importer: RSpaceImporter[F] = ??? override def isEmpty: F[Boolean] = ??? }
package com.ascn.richlife.model.role; /** * 角色模型信息 */ public class RoleModelInfo { /** * 头像信息 */ private String headImgInfo; /** * 人物信息 */ private String personImgInfo; /** * 模型 */ private int modelId; /** * 模型路径 */ private String modelPath; public String getHeadImgInfo() { return headImgInfo; } public RoleModelInfo setHeadImgInfo(String headImgInfo) { this.headImgInfo = headImgInfo; return this; } public String getPersonImgInfo() { return personImgInfo; } public RoleModelInfo setPersonImgInfo(String personImgInfo) { this.personImgInfo = personImgInfo; return this; } public int getModelId() { return modelId; } public RoleModelInfo setModelId(int modelId) { this.modelId = modelId; return this; } public String getModelPath() { return modelPath; } public RoleModelInfo setModelPath(String modelPath) { this.modelPath = modelPath; return this; } }
module Emojidex module Data # collects and condenses UTF moji codes within a collection module CollectionMojiData attr_reader :moji_code_string, :moji_code_index def condense_moji_code_data @moji_code_string = '' @moji_code_index = {} @emoji.values.each do |moji| unless moji.moji.nil? @moji_code_string << moji.moji @moji_code_index[moji.moji] = moji.code end end end end end end
package core // Code generated by github.com/tinylib/msgp DO NOT EDIT. import ( "bytes" "testing" "github.com/tinylib/msgp/msgp" ) func TestMarshalUnmarshalControlMsg(t *testing.T) { v := ControlMsg{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after UnmarshalMsg(): %q", len(left), left) } left, err = msgp.Skip(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after Skip(): %q", len(left), left) } } func BenchmarkMarshalMsgControlMsg(b *testing.B) { v := ControlMsg{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.MarshalMsg(nil) } } func BenchmarkAppendMsgControlMsg(b *testing.B) { v := ControlMsg{} bts := make([]byte, 0, v.Msgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalControlMsg(b *testing.B) { v := ControlMsg{} bts, _ := v.MarshalMsg(nil) b.ReportAllocs() b.SetBytes(int64(len(bts))) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := v.UnmarshalMsg(bts) if err != nil { b.Fatal(err) } } } func TestEncodeDecodeControlMsg(t *testing.T) { v := ControlMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) m := v.Msgsize() if buf.Len() > m { t.Log("WARNING: TestEncodeDecodeControlMsg Msgsize() is inaccurate") } vn := ControlMsg{} err := msgp.Decode(&buf, &vn) if err != nil { t.Error(err) } buf.Reset() msgp.Encode(&buf, &v) err = msgp.NewReader(&buf).Skip() if err != nil { t.Error(err) } } func BenchmarkEncodeControlMsg(b *testing.B) { v := ControlMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) en := msgp.NewWriter(msgp.Nowhere) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.EncodeMsg(en) } en.Flush() } func BenchmarkDecodeControlMsg(b *testing.B) { v := ControlMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) rd := msgp.NewEndlessReader(buf.Bytes(), b) dc := msgp.NewReader(rd) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { err := v.DecodeMsg(dc) if err != nil { b.Fatal(err) } } } func TestMarshalUnmarshalFnMsg(t *testing.T) { v := FnMsg{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after UnmarshalMsg(): %q", len(left), left) } left, err = msgp.Skip(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after Skip(): %q", len(left), left) } } func BenchmarkMarshalMsgFnMsg(b *testing.B) { v := FnMsg{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.MarshalMsg(nil) } } func BenchmarkAppendMsgFnMsg(b *testing.B) { v := FnMsg{} bts := make([]byte, 0, v.Msgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalFnMsg(b *testing.B) { v := FnMsg{} bts, _ := v.MarshalMsg(nil) b.ReportAllocs() b.SetBytes(int64(len(bts))) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := v.UnmarshalMsg(bts) if err != nil { b.Fatal(err) } } } func TestEncodeDecodeFnMsg(t *testing.T) { v := FnMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) m := v.Msgsize() if buf.Len() > m { t.Log("WARNING: TestEncodeDecodeFnMsg Msgsize() is inaccurate") } vn := FnMsg{} err := msgp.Decode(&buf, &vn) if err != nil { t.Error(err) } buf.Reset() msgp.Encode(&buf, &v) err = msgp.NewReader(&buf).Skip() if err != nil { t.Error(err) } } func BenchmarkEncodeFnMsg(b *testing.B) { v := FnMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) en := msgp.NewWriter(msgp.Nowhere) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.EncodeMsg(en) } en.Flush() } func BenchmarkDecodeFnMsg(b *testing.B) { v := FnMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) rd := msgp.NewEndlessReader(buf.Bytes(), b) dc := msgp.NewReader(rd) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { err := v.DecodeMsg(dc) if err != nil { b.Fatal(err) } } } func TestMarshalUnmarshalPossibleRes(t *testing.T) { v := PossibleRes{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after UnmarshalMsg(): %q", len(left), left) } left, err = msgp.Skip(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after Skip(): %q", len(left), left) } } func BenchmarkMarshalMsgPossibleRes(b *testing.B) { v := PossibleRes{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.MarshalMsg(nil) } } func BenchmarkAppendMsgPossibleRes(b *testing.B) { v := PossibleRes{} bts := make([]byte, 0, v.Msgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalPossibleRes(b *testing.B) { v := PossibleRes{} bts, _ := v.MarshalMsg(nil) b.ReportAllocs() b.SetBytes(int64(len(bts))) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := v.UnmarshalMsg(bts) if err != nil { b.Fatal(err) } } } func TestEncodeDecodePossibleRes(t *testing.T) { v := PossibleRes{} var buf bytes.Buffer msgp.Encode(&buf, &v) m := v.Msgsize() if buf.Len() > m { t.Log("WARNING: TestEncodeDecodePossibleRes Msgsize() is inaccurate") } vn := PossibleRes{} err := msgp.Decode(&buf, &vn) if err != nil { t.Error(err) } buf.Reset() msgp.Encode(&buf, &v) err = msgp.NewReader(&buf).Skip() if err != nil { t.Error(err) } } func BenchmarkEncodePossibleRes(b *testing.B) { v := PossibleRes{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) en := msgp.NewWriter(msgp.Nowhere) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.EncodeMsg(en) } en.Flush() } func BenchmarkDecodePossibleRes(b *testing.B) { v := PossibleRes{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) rd := msgp.NewEndlessReader(buf.Bytes(), b) dc := msgp.NewReader(rd) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { err := v.DecodeMsg(dc) if err != nil { b.Fatal(err) } } } func TestMarshalUnmarshalResultMsg(t *testing.T) { v := ResultMsg{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after UnmarshalMsg(): %q", len(left), left) } left, err = msgp.Skip(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after Skip(): %q", len(left), left) } } func BenchmarkMarshalMsgResultMsg(b *testing.B) { v := ResultMsg{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.MarshalMsg(nil) } } func BenchmarkAppendMsgResultMsg(b *testing.B) { v := ResultMsg{} bts := make([]byte, 0, v.Msgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalResultMsg(b *testing.B) { v := ResultMsg{} bts, _ := v.MarshalMsg(nil) b.ReportAllocs() b.SetBytes(int64(len(bts))) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := v.UnmarshalMsg(bts) if err != nil { b.Fatal(err) } } } func TestEncodeDecodeResultMsg(t *testing.T) { v := ResultMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) m := v.Msgsize() if buf.Len() > m { t.Log("WARNING: TestEncodeDecodeResultMsg Msgsize() is inaccurate") } vn := ResultMsg{} err := msgp.Decode(&buf, &vn) if err != nil { t.Error(err) } buf.Reset() msgp.Encode(&buf, &v) err = msgp.NewReader(&buf).Skip() if err != nil { t.Error(err) } } func BenchmarkEncodeResultMsg(b *testing.B) { v := ResultMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) en := msgp.NewWriter(msgp.Nowhere) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.EncodeMsg(en) } en.Flush() } func BenchmarkDecodeResultMsg(b *testing.B) { v := ResultMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) rd := msgp.NewEndlessReader(buf.Bytes(), b) dc := msgp.NewReader(rd) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { err := v.DecodeMsg(dc) if err != nil { b.Fatal(err) } } } func TestMarshalUnmarshalWTimeMsg(t *testing.T) { v := WTimeMsg{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after UnmarshalMsg(): %q", len(left), left) } left, err = msgp.Skip(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d bytes left over after Skip(): %q", len(left), left) } } func BenchmarkMarshalMsgWTimeMsg(b *testing.B) { v := WTimeMsg{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.MarshalMsg(nil) } } func BenchmarkAppendMsgWTimeMsg(b *testing.B) { v := WTimeMsg{} bts := make([]byte, 0, v.Msgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalWTimeMsg(b *testing.B) { v := WTimeMsg{} bts, _ := v.MarshalMsg(nil) b.ReportAllocs() b.SetBytes(int64(len(bts))) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := v.UnmarshalMsg(bts) if err != nil { b.Fatal(err) } } } func TestEncodeDecodeWTimeMsg(t *testing.T) { v := WTimeMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) m := v.Msgsize() if buf.Len() > m { t.Log("WARNING: TestEncodeDecodeWTimeMsg Msgsize() is inaccurate") } vn := WTimeMsg{} err := msgp.Decode(&buf, &vn) if err != nil { t.Error(err) } buf.Reset() msgp.Encode(&buf, &v) err = msgp.NewReader(&buf).Skip() if err != nil { t.Error(err) } } func BenchmarkEncodeWTimeMsg(b *testing.B) { v := WTimeMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) en := msgp.NewWriter(msgp.Nowhere) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.EncodeMsg(en) } en.Flush() } func BenchmarkDecodeWTimeMsg(b *testing.B) { v := WTimeMsg{} var buf bytes.Buffer msgp.Encode(&buf, &v) b.SetBytes(int64(buf.Len())) rd := msgp.NewEndlessReader(buf.Bytes(), b) dc := msgp.NewReader(rd) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { err := v.DecodeMsg(dc) if err != nil { b.Fatal(err) } } }
package no.nav.syfo.testutil.generator import no.nav.syfo.oversikthendelse.domain.OversikthendelseType import no.nav.syfo.oversikthendelse.retry.KOversikthendelseRetry import no.nav.syfo.testutil.UserConstants.ARBEIDSTAKER_FNR import java.time.LocalDateTime import java.util.* val generateKOversikthendelseRetry = KOversikthendelseRetry( created = LocalDateTime.now(), retryTime = LocalDateTime.now(), retriedCount = 0, fnr = ARBEIDSTAKER_FNR.value, oversikthendelseType = OversikthendelseType.OPPFOLGINGSPLANLPS_BISTAND_MOTTATT.name, personOppgaveId = 1, personOppgaveUUID = UUID.randomUUID().toString(), ).copy()
#!/bin/sh # Copyright (c) 2021-2022 Apptainer a Series of LF Projects LLC # For website terms of use, trademark policy, privacy policy and other # project policies see https://lfprojects.org/policies # Copyright (c) 2018-2021, Sylabs Inc. All rights reserved. # This software is licensed under a 3-clause BSD license. Please consult the # LICENSE.md file distributed with the sources of this project regarding your # rights to use or distribute this software. # # Copyright (c) 2017, SingularityWare, LLC. All rights reserved. # # See the COPYRIGHT.md file at the top-level directory of this distribution and at # https://github.com/apptainer/apptainer/blob/main/COPYRIGHT.md. # # This file is part of the Apptainer Linux container project. It is subject to the license # terms in the LICENSE.md file found in the top-level directory of this distribution and # at https://github.com/apptainer/apptainer/blob/main/LICENSE.md. No part # of Apptainer, including this file, may be copied, modified, propagated, or distributed # except according to the terms contained in the LICENSE.md file. if test -n "${SINGULARITY_APPNAME:-}"; then # The active app should be exported export SINGULARITY_APPNAME if test -d "/scif/apps/${SINGULARITY_APPNAME:-}/"; then SCIF_APPS="/scif/apps" SCIF_APPROOT="/scif/apps/${SINGULARITY_APPNAME:-}" export SCIF_APPROOT SCIF_APPS PATH="/scif/apps/${SINGULARITY_APPNAME:-}:/scif/apps/singularity:$PATH" # Automatically add application bin to path if test -d "/scif/apps/${SINGULARITY_APPNAME:-}/bin"; then PATH="/scif/apps/${SINGULARITY_APPNAME:-}/bin:$PATH" elif test -d "/scif/apps/singularity/bin"; then PATH="/scif/apps/singularity/bin:$PATH" fi # Automatically add application lib to LD_LIBRARY_PATH if test -d "/scif/apps/${SINGULARITY_APPNAME:-}/lib"; then LD_LIBRARY_PATH="/scif/apps/${SINGULARITY_APPNAME:-}/lib:$LD_LIBRARY_PATH" export LD_LIBRARY_PATH elif test -d "/scif/apps/singularity/lib"; then LD_LIBRARY_PATH="/scif/apps/singularity/lib:$LD_LIBRARY_PATH" export LD_LIBRARY_PATH fi # Automatically source environment if [ -f "/scif/apps/${SINGULARITY_APPNAME:-}/scif/env/01-base.sh" ]; then . "/scif/apps/${SINGULARITY_APPNAME:-}/scif/env/01-base.sh" elif [ -f "/scif/apps/singularity/scif/env/01-base.sh" ]; then . "/scif/apps/singularity/scif/env/01-base.sh" "$@" fi if [ -f "/scif/apps/${SINGULARITY_APPNAME:-}/scif/env/90-environment.sh" ]; then . "/scif/apps/${SINGULARITY_APPNAME:-}/scif/env/90-environment.sh" elif [ -f "/scif/apps/singularity/scif/env/90-environment.sh" ]; then . "/scif/apps/singularity/scif/env/90-environment.sh" "$@" fi export PATH else echo "Could not locate the container application: ${SINGULARITY_APPNAME}" exit 1 fi fi
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'admin/application_settings/general.html.haml' do let_it_be(:user) { create(:admin) } let_it_be(:app_settings) { build(:application_setting) } before do assign(:application_setting, app_settings) allow(view).to receive(:current_user).and_return(user) end describe 'maintenance mode' do let(:maintenance_mode_flag) { true } let(:license_allows) { true } before do stub_feature_flags(maintenance_mode: maintenance_mode_flag) allow(Gitlab::Geo).to receive(:license_allows?).and_return(license_allows) render end context 'when license does not allow' do let(:license_allows) { false } it 'does not show the Maintenance mode section' do expect(rendered).not_to have_css('#js-maintenance-mode-toggle') end end context 'when license allows' do it 'shows the Maintenance mode section' do expect(rendered).to have_css('#js-maintenance-mode-toggle') end end end end
import { beforeEach, describe, it, } from '@bigtest/mocha'; import { visit } from '@bigtest/react'; import { expect } from 'chai'; import translations from '../../../translations/ui-users/en'; import setupApplication from '../helpers/setup-application'; import ChargeFeeFineInteractor from '../interactors/charge-fee-fine'; import FeeFineHistoryInteractor from '../interactors/fee-fine-history'; import FeeFineDetails from '../interactors/fee-fine-details'; describe('Charge and pay fee/fine', () => { const chargeFeeFine = new ChargeFeeFineInteractor(); setupApplication({ currentUser: { curServicePoint: { id: 1 }, }, }); describe('from the user detail view', () => { let user; let account; beforeEach(async function () { const owner = this.server.create('owner', { owner: 'testOwner', id: 'testOwner' }); this.server.create('payment', { nameMethod: 'visa', ownerId: owner.id, }); const feeFine = this.server.create('feefine', { feeFineType: 'testFineType', id: 'testFineType', ownerId: owner.id, defaultAmount: 500 }); user = this.server.create('user'); account = this.server.create('account', { userId: user.id, loanId: '' }); this.server.create('feefineaction', { accountId: account.id, amountAction: 500, balance: 500, userId: user.id, typeAction: feeFine.feeFineType, }); this.server.create('check-pay', { accountId: account.id, amount: '500.00', allowed: true, remainingAmount: '0.00' }); this.server.get('/payments'); this.server.get('/accounts'); this.server.get('/accounts/:id', (schema, request) => { return schema.accounts.find(request.params.id).attrs; }); this.server.get('/feefines'); visit(`/users/${user.id}/charge`); await chargeFeeFine.whenLoaded(); }); it('should display charge form', () => { expect(chargeFeeFine.form.isPresent).to.be.true; }); describe('Set Fee/Fine data', async () => { beforeEach(async () => { await chargeFeeFine.ownerSelect.whenLoaded(); await chargeFeeFine.ownerSelect.selectAndBlur('testOwner'); }); it('should select owner options', () => { expect(chargeFeeFine.ownerSelect.optionCount).to.equal(2); }); describe('Set Fee/Fine data', async () => { beforeEach(async () => { await chargeFeeFine.typeSelect.whenLoaded(); await chargeFeeFine.typeSelect.selectAndBlur('testFineType'); }); it('should select fee fine type options', () => { expect(chargeFeeFine.typeSelect.optionCount).to.equal(2); }); it('should display amount', () => { expect(chargeFeeFine.amountField.val).to.equal('500.00'); }); describe('Charge and pay fee/fine', () => { beforeEach(async () => { await chargeFeeFine.submitChargeAndPay.click(); }); it('displays payment modal', () => { expect(chargeFeeFine.paymentModal.isPresent).to.be.true; }); it('displays payment modal amount field', () => { expect(chargeFeeFine.paymentModalAmountField.value).to.equal('500.00'); }); describe('Choose payment method', () => { beforeEach(async () => { await chargeFeeFine.paymentModalAmountField.pressTab(); await chargeFeeFine.paymentModalSelect.selectAndBlur('visa'); }); it('displays payment modal select option', () => { expect(chargeFeeFine.paymentModalSelect.value).to.equal('visa'); }); it('displays pay button', () => { expect(chargeFeeFine.paymentModalButton.isPresent).to.be.true; expect(chargeFeeFine.paymentModalButtonIsDisabled).to.be.false; }); describe('pay fine', () => { beforeEach(async () => { await chargeFeeFine.paymentModalButton.click(); }); it('displays confirmation modal', () => { expect(chargeFeeFine.confirmationModal.body.isPresent).to.be.true; }); describe.skip('confirm fine payment', () => { beforeEach(async () => { await chargeFeeFine.confirmationModal.confirmButton.click(); }); it('show successfull callout', () => { expect(chargeFeeFine.callout.successCalloutIsPresent).to.be.true; }); describe('visit created Fee/Fine details page', () => { beforeEach(function () { visit(`/users/${user.id}/accounts/view/${account.id}`); }); it('displays source of fee/fine', () => { expect(FeeFineHistoryInteractor.mclAccountActions.rows(0).cells(6).content).to.equal('User, Test'); expect(FeeFineHistoryInteractor.mclAccountActions.rows(1).cells(6).content).to.equal('User, Test'); }); it('displays loan details', () => { expect(FeeFineDetails.loanDetails.label.text).to.equal(translations['details.label.loanDetails']); expect(FeeFineDetails.loanDetails.value.text).to.equal('-'); }); }); }); }); }); }); }); }); }); });
use crate::{ key::{BeaconChainKey, DBPathKey, LocalMetricsKey, MetricsRegistryKey}, map_persistent_err_to_500, }; use beacon_chain::{BeaconChain, BeaconChainTypes}; use iron::prelude::*; use iron::{status::Status, Handler, IronResult, Request, Response}; use persistent::Read; use prometheus::{Encoder, Registry, TextEncoder}; use std::path::PathBuf; use std::sync::Arc; pub use local_metrics::LocalMetrics; mod local_metrics; /// Yields a handler for the metrics endpoint. pub fn build_handler<T: BeaconChainTypes + 'static>( beacon_chain: Arc<BeaconChain<T>>, db_path: PathBuf, metrics_registry: Registry, ) -> impl Handler { let mut chain = Chain::new(handle_metrics::<T>); let local_metrics = LocalMetrics::new().unwrap(); local_metrics.register(&metrics_registry).unwrap(); chain.link(Read::<BeaconChainKey<T>>::both(beacon_chain)); chain.link(Read::<MetricsRegistryKey>::both(metrics_registry)); chain.link(Read::<LocalMetricsKey>::both(local_metrics)); chain.link(Read::<DBPathKey>::both(db_path)); chain } /// Handle a request for Prometheus metrics. /// /// Returns a text string containing all metrics. fn handle_metrics<T: BeaconChainTypes + 'static>(req: &mut Request) -> IronResult<Response> { let beacon_chain = req .get::<Read<BeaconChainKey<T>>>() .map_err(map_persistent_err_to_500)?; let r = req .get::<Read<MetricsRegistryKey>>() .map_err(map_persistent_err_to_500)?; let local_metrics = req .get::<Read<LocalMetricsKey>>() .map_err(map_persistent_err_to_500)?; let db_path = req .get::<Read<DBPathKey>>() .map_err(map_persistent_err_to_500)?; // Update metrics that are calculated on each scrape. local_metrics.update(&beacon_chain, &db_path); let mut buffer = vec![]; let encoder = TextEncoder::new(); // Gather `DEFAULT_REGISTRY` metrics. encoder.encode(&prometheus::gather(), &mut buffer).unwrap(); // Gather metrics from our registry. let metric_families = r.gather(); encoder.encode(&metric_families, &mut buffer).unwrap(); let prom_string = String::from_utf8(buffer).unwrap(); Ok(Response::with((Status::Ok, prom_string))) }
module V2 class EditionsController < ApplicationController def index query = Queries::KeysetPagination.new( Queries::KeysetPagination::GetEditions.new(edition_params), pagination_params, ) render json: Presenters::KeysetPaginationPresenter.new( query, request.original_url ).present end private def edition_params params .permit( :order, :locale, :publishing_app, :per_page, :before, :after, document_types: [], fields: [], states: [], ) end def pagination_params { per_page: edition_params[:per_page], before: edition_params[:before].try(:split, ","), after: edition_params[:after].try(:split, ","), } end end end
#!/bin/bash go run main.go temp 100 go run main.go length 100 go run main.go weight 100
plugins { kotlin("jvm") id("org.openapi.generator") } group = rootProject.group version = rootProject.version repositories { mavenCentral() } //зависимости у каждого модуля - свои dependencies { val kotestVersion: String by project val openapiVersion: String by project val kotlinVersion: String by project implementation(kotlin("stdlib")) implementation("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion") implementation("com.squareup.moshi:moshi-kotlin:1.9.2") implementation("com.squareup.moshi:moshi-adapters:1.9.2") implementation("com.squareup.okhttp3:okhttp:4.2.2") //testImplementation(kotlin("test")) //в одноплатформенных проектах рекомендуется использовать Junit 5 //отличия в аннотациях и наличие параметризованных тестов //в mp с ним может быть камасутра //Junit 5 begin testImplementation(kotlin("test-junit5")) testImplementation(platform("org.junit:junit-bom:5.7.1")) testImplementation("org.junit.jupiter:junit-jupiter") //Junit 5 end //kottest begin testImplementation("io.kotest:kotest-runner-junit5:$kotestVersion") testImplementation("io.kotest:kotest-assertions-core:$kotestVersion") testImplementation("io.kotest:kotest-property:$kotestVersion") //kottest end } //Junit 5 begin tasks { test { useJUnitPlatform() } } //Junit 5 end openApiGenerate { val basePackage = "${project.group}.transport.main.openapi" packageName.set(basePackage) generatorName.set("kotlin-server") //kotlin, kotlinserver configOptions.apply { //много параметров, см. доку //put("library", "jvm-okhttp4") put("library", "ktor") //put("requestDateConverter", "toString") } //inputSpec.set("${rootProject.projectDir}/specs/catalog-category-api.yaml") inputSpec.set("${rootProject.projectDir}/specs/catalog-classification-api.yaml") //inputSpec.set("${rootProject.projectDir}/specs/catalog-demand-api.yaml") //inputSpec.set("${rootProject.projectDir}/specs/marketplace-demand-api.yaml") //inputSpec.set("${rootProject.projectDir}/specs/catalog-api.yaml") //inputSpec.set("${rootProject.projectDir}/specs/pet-shop.yaml") } openApiValidate { val basePackage = "${project.group}.transport.main.openapi" inputSpec.set("${rootProject.projectDir}/specs/catalog-api.yaml") //inputSpec.set("${rootProject.projectDir}/specs/pet-shop.yaml") } sourceSets.main { java.srcDirs("$buildDir/generate-resources/main/src/main/kotlin") } tasks { compileKotlin.get().dependsOn(openApiGenerate) }
using System.Windows.Controls; namespace TrialManager.Views { /// <summary> /// Interaction logic for DataImportView.xaml /// </summary> public partial class EventSeparationView : UserControl { public EventSeparationView() { InitializeComponent(); } } }
using SmartSql.Data; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace SmartSql.TypeHandlers { public class NullableSByteTypeHandler : AbstractNullableTypeHandler<SByte?, AnyFieldType> { protected override SByte? GetValueWhenNotNull(DataReaderWrapper dataReader, int columnIndex) { return Convert.ToSByte(dataReader.GetValue(columnIndex)); } } }
#! /usr/bin/env perl # Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html use strict; use warnings; use File::Spec::Functions qw(:DEFAULT abs2rel); use File::Copy; use OpenSSL::Glob; use OpenSSL::Test qw/:DEFAULT srctop_dir srctop_file bldtop_dir bldtop_file/; use OpenSSL::Test::Utils; BEGIN { setup("test_fipsinstall"); } use lib srctop_dir('Configurations'); use lib bldtop_dir('.'); use platform; plan skip_all => "Test only supported in a fips build" if disabled("fips"); plan tests => 29; my $infile = bldtop_file('providers', platform->dso('fips')); my $fipskey = $ENV{FIPSKEY} // '00'; # Read in a text $infile and replace the regular expression in $srch with the # value in $repl and output to a new file $outfile. sub replace_line_file_internal { my ($infile, $srch, $repl, $outfile) = @_; my $msg; open(my $in, "<", $infile) or return 0; read($in, $msg, 1024); close $in; $msg =~ s/$srch/$repl/; open(my $fh, ">", $outfile) or return 0; print $fh $msg; close $fh; return 1; } # Read in the text input file 'fips.cnf' # and replace a single Key = Value line with a new value in $value. # OR remove the Key = Value line if the passed in $value is empty. # and then output a new file $outfile. # $key is the Key to find sub replace_line_file { my ($key, $value, $outfile) = @_; my $srch = qr/$key\s*=\s*\S*\n/; my $rep; if ($value eq "") { $rep = ""; } else { $rep = "$key = $value\n"; } return replace_line_file_internal('fips.cnf', $srch, $rep, $outfile); } # Read in the text input file 'test/fips.cnf' # and replace the .cnf file used in # .include fipsmodule.cnf with a new value in $value. # and then output a new file $outfile. # $key is the Key to find sub replace_parent_line_file { my ($value, $outfile) = @_; my $srch = qr/fipsmodule.cnf/; my $rep = "$value"; return replace_line_file_internal(srctop_file("test", 'fips.cnf'), $srch, $rep, $outfile); } # fail if no module name ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', '-provider_name', 'fips', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect'])), "fipsinstall fail"); # fail to verify if the configuration file is missing ok(!run(app(['openssl', 'fipsinstall', '-in', 'dummy.tmp', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail"); # output a fips.cnf file containing mac data ok(run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect'])), "fipsinstall"); # verify the fips.cnf file ok(run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify"); ok(replace_line_file('module-mac', '', 'fips_no_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_no_module_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail no module mac"); ok(replace_line_file('install-mac', '', 'fips_no_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_no_install_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail no install indicator mac"); ok(replace_line_file('module-mac', '00:00:00:00:00:00', 'fips_bad_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_bad_module_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail if invalid module integrity value"); ok(replace_line_file('install-mac', '00:00:00:00:00:00', 'fips_bad_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_bad_install_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail if invalid install indicator integrity value"); ok(replace_line_file('install-status', 'INCORRECT_STATUS_STRING', 'fips_bad_indicator.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_bad_indicator.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail if invalid install indicator status"); # fail to verify the fips.cnf file if a different key is used ok(!run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail bad key"); # fail to verify the fips.cnf file if a different mac digest is used ok(!run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA512', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail incorrect digest"); # corrupt the module hmac ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'HMAC'])), "fipsinstall fails when the module integrity is corrupted"); # corrupt the first digest ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'SHA1'])), "fipsinstall fails when the digest result is corrupted"); # corrupt another digest ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'SHA3'])), "fipsinstall fails when the digest result is corrupted"); # corrupt cipher encrypt test ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'AES_GCM'])), "fipsinstall fails when the AES_GCM result is corrupted"); # corrupt cipher decrypt test ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'AES_ECB_Decrypt'])), "fipsinstall fails when the AES_ECB result is corrupted"); # corrupt DRBG ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'CTR'])), "fipsinstall fails when the DRBG CTR result is corrupted"); # corrupt a KAS test SKIP: { skip "Skipping KAS DH corruption test because of no dh in this build", 1 if disabled("dh"); ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'DH', '-corrupt_type', 'KAT_KA'])), "fipsinstall fails when the kas result is corrupted"); } # corrupt a Signature test SKIP: { skip "Skipping Signature DSA corruption test because of no dsa in this build", 1 if disabled("dsa"); ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'DSA', '-corrupt_type', 'KAT_Signature'])), "fipsinstall fails when the signature result is corrupted"); } # corrupt an Asymmetric cipher test SKIP: { skip "Skipping Asymmetric RSA corruption test because of no rsa in this build", 1 if disabled("rsa"); ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-corrupt_desc', 'RSA_Encrypt', '-corrupt_type', 'KAT_AsymmetricCipher'])), "fipsinstall fails when the asymmetric cipher result is corrupted"); } # 'local' ensures that this change is only done in this file. local $ENV{OPENSSL_CONF_INCLUDE} = abs2rel(curdir()); ok(replace_parent_line_file('fips.cnf', 'fips_parent.cnf') && run(app(['openssl', 'fipsinstall', '-config', 'fips_parent.cnf'])), "verify fips provider loads from a configuration file"); ok(replace_parent_line_file('fips_no_module_mac.cnf', 'fips_parent_no_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_no_module_mac.cnf'])), "verify load config fail no module mac"); ok(replace_parent_line_file('fips_no_install_mac.cnf', 'fips_parent_no_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_no_install_mac.cnf'])), "verify load config fail no install mac"); ok(replace_parent_line_file('fips_bad_indicator.cnf', 'fips_parent_bad_indicator.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_bad_indicator.cnf'])), "verify load config fail bad indicator"); ok(replace_parent_line_file('fips_bad_install_mac.cnf', 'fips_parent_bad_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_bad_install_mac.cnf'])), "verify load config fail bad install mac"); ok(replace_parent_line_file('fips_bad_module_mac.cnf', 'fips_parent_bad_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_bad_module_mac.cnf'])), "verify load config fail bad module mac"); my $stconf = "fipsmodule_selftest.cnf"; ok(run(app(['openssl', 'fipsinstall', '-out', $stconf, '-module', $infile, '-self_test_onload'])), "fipsinstall config saved without self test indicator"); ok(!run(app(['openssl', 'fipsinstall', '-in', $stconf, '-module', $infile, '-verify'])), "fipsinstall config verify fails without self test indicator"); ok(run(app(['openssl', 'fipsinstall', '-in', $stconf, '-module', $infile, '-self_test_onload', '-verify'])), "fipsinstall config verify passes when self test indicator is not present");
module SimplelogicaTheGame class Bullet include Sprite SPEED = 400 # pixels / second def initialize(x, y) self.initialize_sprite @image = $game.images[:bullet] @radius = 10 @x = x @y = y @z = 1 end def update # move upwards @y -= SPEED * $game.delta # collisions against enemies $game.enemies.each do |enemy| if self.colliding?(enemy) # destroy both enemy and bullet enemy.kill! self.kill! $game.score += enemy.points # increase score $game.fx[:kill].play(0.6) # play explosion sfx end end # destroy the laser when out of the screen self.kill! if @y < -15 end end end
package rout import ( "fmt" "net/http" ht "net/http/httptest" "net/url" "regexp" "testing" ) var ( stringNop = func(string) {} stringsNop = func([]string) {} errorNop = func(error) {} boolNop = func(bool) {} ) func BenchmarkRoute(b *testing.B) { rew := ht.NewRecorder() req := tReqSpecific() b.ResetTimer() for range iter(b.N) { tServe(rew, req) } } func tRou(meth, path string) Rou { return Rou{Method: meth, Pattern: path} } func tReqRou(meth, path string) Rou { return Rou{Req: tReq(meth, path)} } func tReq(meth, path string) hreq { return &http.Request{ Method: meth, URL: &url.URL{Path: path}, } } func tReqSpecific() hreq { return tReq(http.MethodPost, `/api/match/0e60feee70b241d38aa37ab55378f926`) } func tServe(rew hrew, req hreq) { try(MakeRou(rew, req).Route(benchRoutes)) } func benchRoutes(r R) { r.Sta(`/api`).Sub(benchRoutesApi) } func benchRoutesApi(r R) { r.Sta(`/api/9bbb5`).Sub(unreachableRoute) r.Sta(`/api/3b002`).Sub(unreachableRoute) r.Sta(`/api/ac134`).Sub(unreachableRoute) r.Sta(`/api/e7c64`).Sub(unreachableRoute) r.Sta(`/api/424da`).Sub(unreachableRoute) r.Sta(`/api/4cddb`).Sub(unreachableRoute) r.Sta(`/api/fabe0`).Sub(unreachableRoute) r.Sta(`/api/210c4`).Sub(unreachableRoute) r.Sta(`/api/c4abd`).Sub(unreachableRoute) r.Sta(`/api/82863`).Sub(unreachableRoute) r.Sta(`/api/9ef98`).Sub(unreachableRoute) r.Sta(`/api/f565f`).Sub(unreachableRoute) r.Sta(`/api/f82b7`).Sub(unreachableRoute) r.Sta(`/api/d7403`).Sub(unreachableRoute) r.Sta(`/api/21838`).Sub(unreachableRoute) r.Sta(`/api/1acff`).Sub(unreachableRoute) r.Sta(`/api/a0771`).Sub(unreachableRoute) r.Sta(`/api/c2bce`).Sub(unreachableRoute) r.Sta(`/api/24bef`).Sub(unreachableRoute) r.Sta(`/api/091ee`).Sub(unreachableRoute) r.Sta(`/api/782d4`).Han(unreachableHan) r.Sta(`/api/eeabb`).Han(unreachableHan) r.Sta(`/api/5ffc7`).Han(unreachableHan) r.Sta(`/api/0f265`).Han(unreachableHan) r.Sta(`/api/2c970`).Han(unreachableHan) r.Sta(`/api/ac36c`).Han(unreachableHan) r.Sta(`/api/8b8d8`).Han(unreachableHan) r.Sta(`/api/3faf4`).Han(unreachableHan) r.Sta(`/api/65ddd`).Han(unreachableHan) r.Sta(`/api/34f35`).Han(unreachableHan) r.Sta(`/api/f74f2`).Han(unreachableHan) r.Sta(`/api/8031d`).Han(unreachableHan) r.Sta(`/api/9bfb8`).Han(unreachableHan) r.Sta(`/api/cf538`).Han(unreachableHan) r.Sta(`/api/becce`).Han(unreachableHan) r.Sta(`/api/183f4`).Han(unreachableHan) r.Sta(`/api/3cafa`).Han(unreachableHan) r.Sta(`/api/05453`).Han(unreachableHan) r.Sta(`/api/f25c7`).Han(unreachableHan) r.Sta(`/api/2e1f1`).Han(unreachableHan) r.Sta(`/api/match`).Sub(reachableRoute) if !*r.Done { panic(`unexpected non-done router state`) } } func reachableRoute(r R) { r.Exa(`/api/match`).Methods(unreachableRoute) r.Pat(`/api/match/{}`).Methods(func(r R) { r.Get().Han(unreachableHan) r.Put().Han(unreachableHan) r.Post().Func(reachableFunc) r.Delete().Han(unreachableHan) }) } func reachableFunc(rew hrew, _ hreq) { rew.WriteHeader(201) } func unreachableRoute(R) { panic(`unreachable`) } func unreachableHan(hreq) hhan { panic(`unreachable`) } func Benchmark_error_ErrNotFound_string(b *testing.B) { for range iter(b.N) { stringNop(NotFound(http.MethodPost, `/some/path`).Error()) } } func Benchmark_error_ErrNotFound_interface(b *testing.B) { for range iter(b.N) { errorNop(NotFound(http.MethodPost, `/some/path`)) } } func Benchmark_error_fmt_Errorf(b *testing.B) { for range iter(b.N) { errorNop(fmt.Errorf( `[rout] routing error (HTTP status 404): no such endpoint: %q %q`, http.MethodPost, `/some/path`, )) } } func Benchmark_error_fmt_Sprintf(b *testing.B) { for range iter(b.N) { stringNop(fmt.Sprintf( `[rout] routing error (HTTP status 404): no such endpoint: %q %q`, http.MethodPost, `/some/path`, )) } } func Benchmark_error_fmt_Sprintf_ErrNotFound(b *testing.B) { for range iter(b.N) { errorNop(ErrNotFound(fmt.Sprintf( `[rout] routing error (HTTP status 404): no such endpoint: %q %q`, http.MethodPost, `/some/path`, ))) } } func Benchmark_bound_methods(b *testing.B) { for range iter(b.N) { benchBoundMethod() } } func benchBoundMethod() { try(MakeRou(nil, staticReq).Route(staticState.Route)) } var staticState State type State struct{ _ map[string]string } func (self *State) Route(r R) { r.Exa(`/get`).Get().Func(self.Get) r.Exa(`/post`).Post().Han(self.Post) r.Exa(`/patch`).Patch().Han(self.Patch) } func (self *State) Get(hrew, hreq) { panic(`unreachable`) } func (self *State) Post(hreq) hhan { panic(`unreachable`) } func (self *State) Patch(hreq) hhan { return nil } func Benchmark_regexp_MatchString_hit(b *testing.B) { reg := regexp.MustCompile(`^/one/two/([^/]+)/([^/]+)$`) b.ResetTimer() for range iter(b.N) { boolNop(reg.MatchString( `/one/two/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_regexp_MatchString_miss(b *testing.B) { reg := regexp.MustCompile(`^/one/two/([^/]+)/([^/]+)$`) b.ResetTimer() for range iter(b.N) { boolNop(reg.MatchString( `/one/two/three/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_regexp_FindStringSubmatch_hit(b *testing.B) { reg := regexp.MustCompile(`^/one/two/([^/]+)/([^/]+)$`) b.ResetTimer() for range iter(b.N) { stringsNop(reg.FindStringSubmatch( `/one/two/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_regexp_FindStringSubmatch_miss(b *testing.B) { reg := regexp.MustCompile(`^/one/two/([^/]+)/([^/]+)$`) b.ResetTimer() for range iter(b.N) { stringsNop(reg.FindStringSubmatch( `/one/two/three/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_Pat_Match_hit(b *testing.B) { var pat Pat try(pat.Parse(`/one/two/{}/{}`)) b.ResetTimer() for range iter(b.N) { boolNop(pat.Match( `/one/two/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_Pat_Match_miss(b *testing.B) { var pat Pat try(pat.Parse(`/one/two/{}/{}`)) b.ResetTimer() for range iter(b.N) { boolNop(pat.Match( `/one/two/three/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_Pat_Submatch_hit(b *testing.B) { var pat Pat try(pat.Parse(`/one/two/{}/{}`)) b.ResetTimer() for range iter(b.N) { stringsNop(pat.Submatch( `/one/two/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_Pat_Submatch_miss(b *testing.B) { var pat Pat try(pat.Parse(`/one/two/{}/{}`)) b.ResetTimer() for range iter(b.N) { stringsNop(pat.Submatch( `/one/two/three/24b6d268f6dd4031b58de9b30e12b0e0/5a8f3d3c357749e4980aab3deffcb840`, )) } } func Benchmark_Pat_Exact_hit(b *testing.B) { pat := Pat{`/one/two/24b6d268f6dd4031b58de9b30e12b0e0`} b.ResetTimer() for range iter(b.N) { boolNop(pat.Match(`/one/two/24b6d268f6dd4031b58de9b30e12b0e0`)) } } func Benchmark_Pat_Exact_miss(b *testing.B) { pat := Pat{`/one/two/24b6d268f6dd4031b58de9b30e12b0e0`} b.ResetTimer() for range iter(b.N) { boolNop(pat.Match(`/one/two/5a8f3d3c357749e4980aab3deffcb840`)) } } func Benchmark_regexp_MustCompile(b *testing.B) { for range iter(b.N) { _ = regexp.MustCompile(`^/one/two/([^/]+)/([^/]+)$`) } } func Benchmark_Pat_Parse(b *testing.B) { for range iter(b.N) { var pat Pat try(pat.Parse(`/one/two/{}/{}`)) } }
import { html, css} from "lit-element"; import { PageViewElement } from "./page-view-element.js"; import { connect } from "pwa-helpers/connect-mixin.js"; // This element is connected to the Redux store. import { store } from "../store.js"; import { loadData, nextIndex, prevIndex, } from "../actions/data.js"; import { selectExpandedCurrentMapData, selectPageExtra, selectCurrentDataIndex, } from "../selectors.js"; import { GIF_COMMAND } from "../frame.js"; // We are lazy loading its reducer. import data from "../reducers/data.js"; store.addReducers({ data }); //rendevous point with screenshot service. Duplicated in screenshot.js const CURRENT_INDEX_VARIABLE = 'current_index'; const PREVIOUS_MAP_VARIABLE = 'previous_map'; const RENDER_COMPLETE_VARIABLE = 'render_complete'; const GIF_NAME_VARIABLE = 'gif_name'; window[RENDER_COMPLETE_VARIABLE] = false; window[PREVIOUS_MAP_VARIABLE] = () => { //The main-view will set this high when update is done window[RENDER_COMPLETE_VARIABLE] = false; store.dispatch(prevIndex()); }; import "./frame-visualization.js"; // These are the shared styles needed by this element. import { SharedStyles } from "./shared-styles.js"; import { updateIndex } from '../actions/data.js'; const FRAME_DATA_FILE_NAME = 'frame_data.json'; const SAMPLE_FRAME_DATA_FILE_NAME = 'frame_data.SAMPLE.json'; const fetchData = async() => { let res; let fetchErrored = false; try { res = await fetch("/" + FRAME_DATA_FILE_NAME); } catch (err) { fetchErrored = err; } if (fetchErrored || !res.ok) { console.warn(FRAME_DATA_FILE_NAME + ' not found. Using ' + SAMPLE_FRAME_DATA_FILE_NAME + ' instead.'); res = await fetch("/" + SAMPLE_FRAME_DATA_FILE_NAME); } const data = await res.json(); store.dispatch(loadData(data)); }; class MainView extends connect(store)(PageViewElement) { static get properties() { return { // This is the data from the store. _expandedMapData: { type: Object }, _pageExtra: { type: String }, _currentIndex: { type: Number }, }; } static get styles() { return [ SharedStyles, css` :host { position:relative; height:100vh; width: 100vw; } .container { display: flex; justify-content: center; align-items: center; height: 100%; width: 100%; background-color: var(--override-app-background-color, var(--app-background-color, #356F9E)); } ` ]; } firstUpdated() { fetchData(); document.addEventListener('keydown', e => this._handleKeyDown(e)); } _handleKeyDown(e) { //We have to hook this to issue content editable commands when we're //active. But most of the time we don't want to do anything. if (!this.active) return; if (e.key == 'ArrowRight') { store.dispatch(nextIndex()); } else if (e.key == 'ArrowLeft') { store.dispatch(prevIndex()); } } render() { return html` <style> :host { --app-background-color: ${this._backgroundColor} } </style> <div class='container'> <frame-visualization .data=${this._expandedMapData}></frame-visualization> </div> `; } get _backgroundColor() { if (!this._expandedMapData) return 'transparent'; if (!this._expandedMapData.colors) return 'transparent'; return this._expandedMapData.colors.background.hex; } // This is called every time something is updated in the store. stateChanged(state) { this._expandedMapData = selectExpandedCurrentMapData(state); this._pageExtra = selectPageExtra(state); this._currentIndex = selectCurrentDataIndex(state); this.updateComplete.then(() => { window[RENDER_COMPLETE_VARIABLE] = true; }); } updated(changedProps) { if (changedProps.has('_pageExtra')) { const index = this._pageExtra ? parseInt(this._pageExtra) : -1; store.dispatch(updateIndex(index)); } if (changedProps.has('_currentIndex')) { window[CURRENT_INDEX_VARIABLE] = this._currentIndex; } if (changedProps.has('_expandedMapData')) { const data = this._expandedMapData || {}; window[GIF_NAME_VARIABLE] = data[GIF_COMMAND]; } } } window.customElements.define("main-view", MainView);
/** * \file obj-chest.c * \brief Encapsulation of chest-related functions * * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke * Copyright (c) 2012 Peter Denison * * This work is free software; you can redistribute it and/or modify it * under the terms of either: * * a) the GNU General Public License as published by the Free Software * Foundation, version 2, or * * b) the "Angband licence": * This software may be copied and distributed for educational, research, * and not for profit purposes provided that this copyright and statement * are included in all such copies. Other copyrights may also apply. */ #include "angband.h" #include "cave.h" #include "mon-lore.h" #include "obj-chest.h" #include "obj-identify.h" #include "obj-make.h" #include "obj-pile.h" #include "obj-tval.h" #include "obj-util.h" #include "player-calcs.h" #include "player-timed.h" #include "player-util.h" /** * Each chest has a certain set of traps, determined by pval * Each chest has a "pval" from 1 to the chest level (max 55) * If the "pval" is negative then the trap has been disarmed * The "pval" of a chest determines the quality of its treasure * Note that disarming a trap on a chest also removes the lock. */ static const byte chest_traps[64] = { 0, /* 0 == empty */ (CHEST_POISON), (CHEST_LOSE_STR), (CHEST_LOSE_CON), (CHEST_LOSE_STR), (CHEST_LOSE_CON), /* 5 == best small wooden */ 0, (CHEST_POISON), (CHEST_POISON), (CHEST_LOSE_STR), (CHEST_LOSE_CON), (CHEST_POISON), (CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_SUMMON), /* 15 == best large wooden */ 0, (CHEST_LOSE_STR), (CHEST_LOSE_CON), (CHEST_PARALYZE), (CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_SUMMON), (CHEST_PARALYZE), (CHEST_LOSE_STR), (CHEST_LOSE_CON), (CHEST_EXPLODE), /* 25 == best small iron */ 0, (CHEST_POISON | CHEST_LOSE_STR), (CHEST_POISON | CHEST_LOSE_CON), (CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_PARALYZE), (CHEST_POISON | CHEST_SUMMON), (CHEST_SUMMON), (CHEST_EXPLODE), (CHEST_EXPLODE | CHEST_SUMMON), /* 35 == best large iron */ 0, (CHEST_SUMMON), (CHEST_EXPLODE), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_POISON | CHEST_PARALYZE), (CHEST_EXPLODE), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_POISON | CHEST_PARALYZE), /* 45 == best small steel */ 0, (CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_POISON | CHEST_PARALYZE | CHEST_LOSE_STR), (CHEST_POISON | CHEST_PARALYZE | CHEST_LOSE_CON), (CHEST_POISON | CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_POISON | CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_POISON | CHEST_PARALYZE | CHEST_LOSE_STR | CHEST_LOSE_CON), (CHEST_POISON | CHEST_PARALYZE), (CHEST_POISON | CHEST_PARALYZE), /* 55 == best large steel */ (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), (CHEST_EXPLODE | CHEST_SUMMON), }; /** * The type of trap a chest has */ byte chest_trap_type(const struct object *obj) { s16b trap_value = obj->pval; if (trap_value >= 0) return chest_traps[trap_value]; else return chest_traps[-trap_value]; } /** * Determine if a chest is trapped */ bool is_trapped_chest(const struct object *obj) { if (!tval_is_chest(obj)) return FALSE; /* Disarmed or opened chests are not trapped */ if (obj->pval <= 0) return FALSE; /* Some chests simply don't have traps */ return (chest_traps[obj->pval] != 0); } /** * Determine if a chest is locked or trapped */ bool is_locked_chest(const struct object *obj) { if (!tval_is_chest(obj)) return FALSE; /* Disarmed or opened chests are not locked */ return (obj->pval > 0); } /** * Unlock a chest */ void unlock_chest(struct object *obj) { obj->pval = (0 - obj->pval); } /** * Determine if a grid contains a chest matching the query type, and * return a pointer to the first such chest */ struct object *chest_check(int y, int x, enum chest_query check_type) { struct object *obj; /* Scan all objects in the grid */ for (obj = square_object(cave, y, x); obj; obj = obj->next) { /* Check for chests */ switch (check_type) { case CHEST_ANY: if (tval_is_chest(obj)) return obj; break; case CHEST_OPENABLE: if (tval_is_chest(obj) && (obj->pval != 0)) return obj; break; case CHEST_TRAPPED: if (is_trapped_chest(obj) && object_is_known(obj)) return obj; break; } } /* No chest */ return NULL; } /** * Return the number of grids holding a chests around (or under) the character. * If requested, count only trapped chests. */ int count_chests(int *y, int *x, enum chest_query check_type) { int d, count; /* Count how many matches */ count = 0; /* Check around (and under) the character */ for (d = 0; d < 9; d++) { /* Extract adjacent (legal) location */ int yy = player->py + ddy_ddd[d]; int xx = player->px + ddx_ddd[d]; /* No (visible) chest is there */ if (!chest_check(yy, xx, check_type)) continue; /* Count it */ ++count; /* Remember the location of the last chest found */ *y = yy; *x = xx; } /* All done */ return count; } /** * Allocate objects upon opening a chest * * Disperse treasures from the given chest, centered at (x,y). * * Small chests often contain "gold", while Large chests always contain * items. Wooden chests contain 2 items, Iron chests contain 4 items, * and Steel chests contain 6 items. The "value" of the items in a * chest is based on the level on which the chest is generated. * * Judgment of size and construction of chests is currently made from the name. */ static void chest_death(int y, int x, struct object *chest) { int number, value; bool tiny; struct object *treasure; /* Small chests often hold "gold" */ tiny = strstr(chest->kind->name, "Small") ? TRUE : FALSE; /* Determine how much to drop (see above) */ if (strstr(chest->kind->name, "wooden")) number = 2; else if (strstr(chest->kind->name, "iron")) number = 4; else if (strstr(chest->kind->name, "steel")) number = 6; else number = 2 * (randint1(3)); /* Zero pval means empty chest */ if (!chest->pval) number = 0; /* Determine the "value" of the items */ value = chest->origin_depth - 10 + 2 * chest->sval; if (value < 1) value = 1; /* Drop some objects (non-chests) */ for (; number > 0; --number) { /* Small chests often drop gold */ if (tiny && (randint0(100) < 75)) treasure = make_gold(value, "any"); /* Otherwise drop an item, as long as it isn't a chest */ else { treasure = make_object(cave, value, FALSE, FALSE, FALSE, NULL, 0); if (!treasure) continue; if (tval_is_chest(treasure)) { mem_free(treasure); continue; } } /* Record origin */ treasure->origin = ORIGIN_CHEST; treasure->origin_depth = chest->origin_depth; /* Drop it in the dungeon */ drop_near(cave, treasure, 0, y, x, TRUE); } /* Empty */ chest->pval = 0; /* Known */ object_notice_everything(chest); } /** * Chests have traps too. * * Exploding chest destroys contents (and traps). * Note that the chest itself is never destroyed. */ static void chest_trap(int y, int x, struct object *obj) { int trap; /* Ignore disarmed chests */ if (obj->pval <= 0) return; /* Obtain the traps */ trap = chest_traps[obj->pval]; /* Lose strength */ if (trap & (CHEST_LOSE_STR)) { msg("A small needle has pricked you!"); take_hit(player, damroll(1, 4), "a poison needle"); effect_simple(EF_DRAIN_STAT, "0", STAT_STR, 0, 0, NULL); } /* Lose constitution */ if (trap & (CHEST_LOSE_CON)) { msg("A small needle has pricked you!"); take_hit(player, damroll(1, 4), "a poison needle"); effect_simple(EF_DRAIN_STAT, "0", STAT_CON, 0, 0, NULL); } /* Poison */ if (trap & (CHEST_POISON)) { msg("A puff of green gas surrounds you!"); effect_simple(EF_TIMED_INC, "10+1d20", TMD_POISONED, 0, 0, NULL); } /* Paralyze */ if (trap & (CHEST_PARALYZE)) { msg("A puff of yellow gas surrounds you!"); effect_simple(EF_TIMED_INC, "10+1d20", TMD_PARALYZED, 0, 0, NULL); } /* Summon monsters */ if (trap & (CHEST_SUMMON)) { msg("You are enveloped in a cloud of smoke!"); effect_simple(EF_SUMMON, "2+1d3", 0, 0, 0, NULL); } /* Explode */ if (trap & (CHEST_EXPLODE)) { msg("There is a sudden explosion!"); msg("Everything inside the chest is destroyed!"); obj->pval = 0; take_hit(player, damroll(5, 8), "an exploding chest"); } } /** * Attempt to open the given chest at the given location * * Assume there is no monster blocking the destination * * Returns TRUE if repeated commands may continue */ bool do_cmd_open_chest(int y, int x, struct object *obj) { int i, j; bool flag = TRUE; bool more = FALSE; /* Attempt to unlock it */ if (obj->pval > 0) { /* Assume locked, and thus not open */ flag = FALSE; /* Get the "disarm" factor */ i = player->state.skills[SKILL_DISARM]; /* Penalize some conditions */ if (player->timed[TMD_BLIND] || no_light()) i = i / 10; if (player->timed[TMD_CONFUSED] || player->timed[TMD_IMAGE]) i = i / 10; /* Extract the difficulty */ j = i - obj->pval; /* Always have a small chance of success */ if (j < 2) j = 2; /* Success -- May still have traps */ if (randint0(100) < j) { msgt(MSG_LOCKPICK, "You have picked the lock."); player_exp_gain(player, 1); flag = TRUE; } else { /* We may continue repeating */ more = TRUE; event_signal(EVENT_INPUT_FLUSH); msgt(MSG_LOCKPICK_FAIL, "You failed to pick the lock."); } } /* Allowed to open */ if (flag) { /* Apply chest traps, if any */ chest_trap(y, x, obj); /* Let the Chest drop items */ chest_death(y, x, obj); /* Ignore chest if autoignore calls for it */ player->upkeep->notice |= PN_IGNORE; } /* Empty chests were always ignored in ignore_item_okay so we * might as well ignore it here */ if (obj->pval == 0) obj->ignore = TRUE; /* Redraw chest, to be on the safe side (it may have been ignored) */ square_light_spot(cave, y, x); /* Result */ return (more); } /** * Attempt to disarm the chest at the given location * * Assume there is no monster blocking the destination * * Returns TRUE if repeated commands may continue */ bool do_cmd_disarm_chest(int y, int x, struct object *obj) { int i, j; bool more = FALSE; /* Get the "disarm" factor */ i = player->state.skills[SKILL_DISARM]; /* Penalize some conditions */ if (player->timed[TMD_BLIND] || no_light()) i = i / 10; if (player->timed[TMD_CONFUSED] || player->timed[TMD_IMAGE]) i = i / 10; /* Extract the difficulty */ j = i - obj->pval; /* Always have a small chance of success */ if (j < 2) j = 2; /* Must find the trap first. */ if (!object_is_known(obj)) { msg("I don't see any traps."); } else if (!is_trapped_chest(obj)) { /* Already disarmed/unlocked or no traps */ msg("The chest is not trapped."); } else if (randint0(100) < j) { /* Success (get a lot of experience) */ msgt(MSG_DISARM, "You have disarmed the chest."); player_exp_gain(player, obj->pval); obj->pval = (0 - obj->pval); } else if ((i > 5) && (randint1(i) > 5)) { /* Failure -- Keep trying */ more = TRUE; event_signal(EVENT_INPUT_FLUSH); msg("You failed to disarm the chest."); } else { /* Failure -- Set off the trap */ msg("You set off a trap!"); chest_trap(y, x, obj); } /* Result */ return (more); }
# API namespaces methods module VK::Namespaces module ClassMethods private def create_default_namespaces! default_namespaces.each do |namespace| define_method namespace do instance_variable_get("@#{ namespace }") || instance_variable_set("@#{ namespace }", VK::Methods.new(namespace, handler)) end end end def default_namespaces @names ||= YAML.load_file(File.expand_path('../namespaces.yml', __FILE__)) end end module InstanceMethods # Execute VK stored procedure (see {https://vk.com/dev/execute}) # # @param [Hash] params execute method params # @option code [String] VKScript # # @example Call API method with code param # application.execute code: 'return 1 + 1;' #=> 2 # # @example Call user-stored procedure with arguments # application.execute.user_proc_name a: { b: 1, c: 2} #=> computed result # # @return servers response # # @raise [VK::APIError] with API error def execute(params = {}, &block) if params.empty? @execute ||= VK::Methods.new(:execute, handler) else method_missing(:execute, params, &block) end end private # @!attribute [r] namespace # @return [String] API namespace name attr_reader :namespace # @private def method_missing(method_name, *args, &block) api_method = VK::Utils.camelize(method_name) api_full_method = namespace ? [namespace, api_method].join('.') : api_method result = handler.call(api_full_method, args.first || {}) metaclass.send(:define_method, method_name) do |params={}| handler.call(api_full_method, params) end metaclass.send(:alias_method, api_method, method_name) result end # @!attribute [r] handler # @return [String] Request handler def handler @handler ||= self.method(:vk_call) end def metaclass class << self; self; end end end def self.included(receiver) receiver.extend ClassMethods receiver.send :include, InstanceMethods end end
import 'dart:ui'; import 'package:flutter/material.dart' hide Image, Texture; import 'package:vector_math/vector_math_64.dart'; import 'clip_coordinates.dart'; import 'textures.dart'; import 'painters.dart'; import 'camera_body.dart'; import 'extensions.dart'; class Mesh extends StatelessWidget { final Widget child; final Aabb2 viewPort; final CameraMesh mesh; final Texture texture; final Image imageTexture; final Color color; final bool clip; Mesh(this.viewPort, {this.child, this.mesh, this.texture, this.color, this.imageTexture, this.clip = false}); @override Widget build(BuildContext context) { return ClipCoordinates( container: viewPort.rect, rect: mesh.containingRect.rect, child: CustomPaint( isComplex: true, willChange: false, child: child, painter: MeshPainter(mesh, texture: texture, color: color, imageTexture: imageTexture, clipRect: clip ? viewPort.rect : null), )); } }
package com.alexvanyo.composelife.algorithm import androidx.annotation.IntRange import androidx.compose.ui.unit.IntOffset import com.alexvanyo.composelife.model.CellState import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import kotlin.math.ceil import kotlin.math.log2 @Suppress("TooManyFunctions") class HashLifeAlgorithm( private val backgroundDispatcher: CoroutineDispatcher, ) : GameOfLifeAlgorithm { /** * The map containing the "canonical" [MacroCell.CellNode]s. This ensures that there is exactly one instance of * each equivalent [MacroCell.CellNode] (which makes comparing [MacroCell.CellNode]s possible with just reference * checking). * * TODO: Prune this map as needed. */ private val canonicalCellMap = mutableMapOf<MacroCell.CellNode, MacroCell.CellNode>() /** * The memoization map for [MacroCell.CellNode.computeNextGeneration]. * * TODO: Prune this map as needed. */ private val cellMap = mutableMapOf<MacroCell.CellNode, MacroCell.CellNode>() /** * The memoization map for [MacroCell.size]. * * TODO: Prune this map as needed. */ private val cellSizeMap = mutableMapOf<MacroCell.CellNode, Int>() /** * Computes the next generation for the given [MacroCell.CellNode]. * * For simplicity, this function will return a [MacroCell.CellNode] that is half as big, centered on this node. * (in other words, a [MacroCell.CellNode] with a decremented level). * * This function is memoized by [cellMap]. */ @Suppress("LongMethod", "ComplexMethod") private fun MacroCell.CellNode.computeNextGeneration(): MacroCell.CellNode { require(level >= 2) val alreadyComputed = cellMap[this] if (alreadyComputed != null) return alreadyComputed nw as MacroCell.CellNode ne as MacroCell.CellNode sw as MacroCell.CellNode se as MacroCell.CellNode val computed = if (level == 2) { nw.nw as MacroCell.Cell nw.ne as MacroCell.Cell nw.sw as MacroCell.Cell nw.se as MacroCell.Cell ne.nw as MacroCell.Cell ne.ne as MacroCell.Cell ne.sw as MacroCell.Cell ne.se as MacroCell.Cell sw.nw as MacroCell.Cell sw.ne as MacroCell.Cell sw.sw as MacroCell.Cell sw.se as MacroCell.Cell se.nw as MacroCell.Cell se.ne as MacroCell.Cell se.sw as MacroCell.Cell se.se as MacroCell.Cell val nwCount = listOf( nw.nw.isAlive, nw.ne.isAlive, ne.nw.isAlive, nw.sw.isAlive, ne.sw.isAlive, sw.nw.isAlive, sw.ne.isAlive, se.nw.isAlive ).count { it } val newNw = when (nw.se) { MacroCell.Cell.AliveCell -> if (nwCount in 2..3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell MacroCell.Cell.DeadCell -> if (nwCount == 3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell } val neCount = listOf( nw.ne.isAlive, ne.nw.isAlive, ne.ne.isAlive, nw.se.isAlive, ne.se.isAlive, sw.ne.isAlive, se.nw.isAlive, se.ne.isAlive ).count { it } val newNe = when (ne.sw) { MacroCell.Cell.AliveCell -> if (neCount in 2..3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell MacroCell.Cell.DeadCell -> if (neCount == 3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell } val swCount = listOf( nw.sw.isAlive, nw.se.isAlive, ne.sw.isAlive, sw.nw.isAlive, se.nw.isAlive, sw.sw.isAlive, sw.se.isAlive, se.sw.isAlive ).count { it } val newSw = when (sw.ne) { MacroCell.Cell.AliveCell -> if (swCount in 2..3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell MacroCell.Cell.DeadCell -> if (swCount == 3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell } val seCount = listOf( nw.se.isAlive, ne.sw.isAlive, ne.se.isAlive, sw.ne.isAlive, se.ne.isAlive, sw.se.isAlive, se.sw.isAlive, se.se.isAlive ).count { it } val newSe = when (se.nw) { MacroCell.Cell.AliveCell -> if (seCount in 2..3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell MacroCell.Cell.DeadCell -> if (seCount == 3) MacroCell.Cell.AliveCell else MacroCell.Cell.DeadCell } MacroCell.CellNode( nw = newNw, ne = newNe, sw = newSw, se = newSe ).makeCanonical() } else { val n00 = centeredSubnode(nw) val n01 = centeredHorizontal(nw, ne) val n02 = centeredSubnode(ne) val n10 = centeredVertical(nw, sw) val n11 = centeredSubSubnode(this) val n12 = centeredVertical(ne, se) val n20 = centeredSubnode(sw) val n21 = centeredHorizontal(sw, se) val n22 = centeredSubnode(se) MacroCell.CellNode( nw = MacroCell.CellNode( nw = n00, ne = n01, sw = n10, se = n11 ).makeCanonical().computeNextGeneration(), ne = MacroCell.CellNode( nw = n01, ne = n02, sw = n11, se = n12 ).makeCanonical().computeNextGeneration(), sw = MacroCell.CellNode( nw = n10, ne = n11, sw = n20, se = n21 ).makeCanonical().computeNextGeneration(), se = MacroCell.CellNode( nw = n11, ne = n12, sw = n21, se = n22 ).makeCanonical().computeNextGeneration(), ).makeCanonical() } cellMap[this] = computed return computed } private fun centeredSubnode(node: MacroCell.CellNode): MacroCell.CellNode { node.nw as MacroCell.CellNode node.ne as MacroCell.CellNode node.sw as MacroCell.CellNode node.se as MacroCell.CellNode return MacroCell.CellNode( nw = node.nw.se, ne = node.ne.sw, sw = node.sw.ne, se = node.se.nw ).makeCanonical() } private fun centeredHorizontal(w: MacroCell.CellNode, e: MacroCell.CellNode): MacroCell.CellNode { w.ne as MacroCell.CellNode w.se as MacroCell.CellNode e.nw as MacroCell.CellNode e.sw as MacroCell.CellNode return MacroCell.CellNode( nw = w.ne.se, ne = e.nw.sw, sw = w.se.ne, se = e.sw.nw ).makeCanonical() } private fun centeredVertical(n: MacroCell.CellNode, s: MacroCell.CellNode): MacroCell.CellNode { n.se as MacroCell.CellNode n.sw as MacroCell.CellNode s.nw as MacroCell.CellNode s.ne as MacroCell.CellNode return MacroCell.CellNode( nw = n.sw.se, ne = n.se.sw, sw = s.nw.ne, se = s.ne.nw ).makeCanonical() } private fun centeredSubSubnode(node: MacroCell.CellNode): MacroCell.CellNode { node.nw as MacroCell.CellNode node.ne as MacroCell.CellNode node.sw as MacroCell.CellNode node.se as MacroCell.CellNode node.nw.se as MacroCell.CellNode node.ne.sw as MacroCell.CellNode node.sw.ne as MacroCell.CellNode node.se.nw as MacroCell.CellNode return MacroCell.CellNode( nw = node.nw.se.se, ne = node.ne.sw.sw, sw = node.sw.ne.ne, se = node.se.nw.nw ).makeCanonical() } override suspend fun computeGenerationWithStep( cellState: CellState, @IntRange(from = 0) step: Int, ): CellState = withContext(backgroundDispatcher) { computeGenerationWithStepImpl( cellState = cellState.toHashLifeCellState(), step = step ) } private tailrec fun computeGenerationWithStepImpl( cellState: HashLifeCellState, @IntRange(from = 0) step: Int, ): HashLifeCellState = if (step == 0) { cellState } else { computeGenerationWithStepImpl( cellState = computeNextGeneration(cellState), step = step - 1 ) } /** * Returns the [HashLifeCellState] corresponding to the next generation. */ @Suppress("ComplexMethod") private tailrec fun computeNextGeneration(cellState: HashLifeCellState): HashLifeCellState { val node = cellState.macroCell as MacroCell.CellNode if (node.level > 3) { node.nw as MacroCell.CellNode node.nw.nw as MacroCell.CellNode node.nw.ne as MacroCell.CellNode node.nw.sw as MacroCell.CellNode node.nw.se as MacroCell.CellNode node.ne as MacroCell.CellNode node.ne.nw as MacroCell.CellNode node.ne.ne as MacroCell.CellNode node.ne.sw as MacroCell.CellNode node.ne.se as MacroCell.CellNode node.sw as MacroCell.CellNode node.sw.nw as MacroCell.CellNode node.sw.ne as MacroCell.CellNode node.sw.sw as MacroCell.CellNode node.sw.se as MacroCell.CellNode node.se as MacroCell.CellNode node.se.nw as MacroCell.CellNode node.se.ne as MacroCell.CellNode node.se.sw as MacroCell.CellNode node.se.se as MacroCell.CellNode @Suppress("ComplexCondition") if (node.nw.nw.size() == 0 && node.nw.ne.size() == 0 && node.nw.ne.size() == 0 && node.nw.se.nw.size() == 0 && node.nw.se.ne.size() == 0 && node.nw.se.sw.size() == 0 && node.ne.nw.size() == 0 && node.ne.ne.size() == 0 && node.ne.se.size() == 0 && node.ne.sw.nw.size() == 0 && node.ne.sw.ne.size() == 0 && node.ne.sw.se.size() == 0 && node.sw.nw.size() == 0 && node.sw.sw.size() == 0 && node.sw.se.size() == 0 && node.sw.ne.nw.size() == 0 && node.sw.ne.sw.size() == 0 && node.sw.ne.se.size() == 0 && node.se.ne.size() == 0 && node.se.sw.size() == 0 && node.se.se.size() == 0 && node.se.nw.ne.size() == 0 && node.se.nw.sw.size() == 0 && node.se.nw.se.size() == 0 ) { return HashLifeCellState( offset = cellState.offset + IntOffset(1 shl (node.level - 2), 1 shl (node.level - 2)), macroCell = cellState.macroCell.computeNextGeneration() ) } } // If our primary macro cell would be too small or the resulting macro cell wouldn't be the correct result // (due to an expanding pattern), expand the main macro cell and compute. return computeNextGeneration(cellState.expandCentered()) } private fun MacroCell.size(): Int = when (this) { MacroCell.Cell.AliveCell -> 1 MacroCell.Cell.DeadCell -> 0 is MacroCell.CellNode -> { cellSizeMap.getOrPut(this) { nw.size() + ne.size() + sw.size() + se.size() } } } private fun HashLifeCellState.expandCentered(): HashLifeCellState { val node = macroCell as MacroCell.CellNode val sameLevelEmptyCell = createEmptyMacroCell(node.level) val smallerLevelEmptyCell = createEmptyMacroCell(node.level - 1) val cell = MacroCell.CellNode( nw = MacroCell.CellNode( nw = sameLevelEmptyCell, ne = sameLevelEmptyCell, sw = sameLevelEmptyCell, se = MacroCell.CellNode( nw = smallerLevelEmptyCell, ne = smallerLevelEmptyCell, sw = smallerLevelEmptyCell, se = node.nw ).makeCanonical() ).makeCanonical(), ne = MacroCell.CellNode( nw = sameLevelEmptyCell, ne = sameLevelEmptyCell, sw = MacroCell.CellNode( nw = smallerLevelEmptyCell, ne = smallerLevelEmptyCell, sw = node.ne, se = smallerLevelEmptyCell ).makeCanonical(), se = sameLevelEmptyCell ).makeCanonical(), sw = MacroCell.CellNode( nw = sameLevelEmptyCell, ne = MacroCell.CellNode( nw = smallerLevelEmptyCell, ne = node.sw, sw = smallerLevelEmptyCell, se = smallerLevelEmptyCell ).makeCanonical(), sw = sameLevelEmptyCell, se = sameLevelEmptyCell ).makeCanonical(), se = MacroCell.CellNode( nw = MacroCell.CellNode( nw = node.se, ne = smallerLevelEmptyCell, sw = smallerLevelEmptyCell, se = smallerLevelEmptyCell ).makeCanonical(), ne = sameLevelEmptyCell, sw = sameLevelEmptyCell, se = sameLevelEmptyCell ).makeCanonical() ) val offsetDiff = 3 * (1 shl (node.level - 1)) return HashLifeCellState( offset = offset + IntOffset(-offsetDiff, -offsetDiff), macroCell = cell ) } private fun CellState.toHashLifeCellState(): HashLifeCellState { if (this is HashLifeCellState) return this val xValues = aliveCells.map { it.x } val yValues = aliveCells.map { it.y } val minX = xValues.minOrNull() ?: 0 val maxX = xValues.maxOrNull() ?: 0 val minY = yValues.minOrNull() ?: 0 val maxY = yValues.maxOrNull() ?: 0 val minimumLevel = ceil( maxOf( log2((maxX - minX).toDouble()), log2((maxY - minY).toDouble()) ) ).toInt().coerceAtLeast(3) val offset = IntOffset(minX, minY) val macroCell = createMacroCell( cellState = this, offset = offset, level = minimumLevel ) return HashLifeCellState( offset = offset, macroCell = macroCell ) } private fun createEmptyMacroCell(level: Int): MacroCell = if (level == 0) { MacroCell.Cell.DeadCell } else { val smallerEmptyMacroCell = createEmptyMacroCell(level - 1) MacroCell.CellNode( smallerEmptyMacroCell, smallerEmptyMacroCell, smallerEmptyMacroCell, smallerEmptyMacroCell ).makeCanonical() } private fun createMacroCell(cellState: CellState, offset: IntOffset, level: Int): MacroCell = if (level == 0) { if (offset in cellState.aliveCells) { MacroCell.Cell.AliveCell } else { MacroCell.Cell.DeadCell } } else { val offsetDiff = 1 shl (level - 1) MacroCell.CellNode( createMacroCell(cellState, offset, level - 1), createMacroCell(cellState, offset + IntOffset(offsetDiff, 0), level - 1), createMacroCell(cellState, offset + IntOffset(0, offsetDiff), level - 1), createMacroCell(cellState, offset + IntOffset(offsetDiff, offsetDiff), level - 1), ).makeCanonical() } private fun MacroCell.withCell(target: IntOffset, isAlive: Boolean): MacroCell = when (this) { MacroCell.Cell.AliveCell, MacroCell.Cell.DeadCell -> { require(target == IntOffset.Zero) if (isAlive) { MacroCell.Cell.AliveCell } else { MacroCell.Cell.DeadCell } } is MacroCell.CellNode -> { val offsetDiff = 1 shl (level - 1) val isNorth = target.y < offsetDiff val isWest = target.x < offsetDiff if (isNorth) { if (isWest) { MacroCell.CellNode( nw = nw.withCell(target, isAlive), ne = ne, sw = sw, se = se ).makeCanonical() } else { MacroCell.CellNode( nw = nw, ne = ne.withCell(target + IntOffset(-offsetDiff, 0), isAlive), sw = sw, se = se ).makeCanonical() } } else { if (isWest) { MacroCell.CellNode( nw = nw, ne = ne, sw = sw.withCell(target + IntOffset(0, -offsetDiff), isAlive), se = se ).makeCanonical() } else { MacroCell.CellNode( nw = nw, ne = ne, sw = sw, se = se.withCell(target + IntOffset(-offsetDiff, -offsetDiff), isAlive) ).makeCanonical() } } } } private fun MacroCell.iterator( offset: IntOffset, ): Iterator<IntOffset> = iterator { when (this@iterator) { MacroCell.Cell.AliveCell -> yield(offset) MacroCell.Cell.DeadCell -> Unit is MacroCell.CellNode -> { val offsetDiff = 1 shl (level - 1) yieldAll(nw.iterator(offset)) yieldAll(ne.iterator(offset + IntOffset(offsetDiff, 0))) yieldAll(sw.iterator(offset + IntOffset(0, offsetDiff))) yieldAll(se.iterator(offset + IntOffset(offsetDiff, offsetDiff))) } } } @Suppress("NestedBlockDepth") private fun MacroCell.contains(target: IntOffset): Boolean = when (this) { MacroCell.Cell.AliveCell -> { require(target == IntOffset.Zero) true } MacroCell.Cell.DeadCell -> { require(target == IntOffset.Zero) false } is MacroCell.CellNode -> { if (size() == 0) { false } else { val offsetDiff = 1 shl (level - 1) val isNorth = target.y < offsetDiff val isWest = target.x < offsetDiff if (isNorth) { if (isWest) { nw.contains(target) } else { ne.contains(target + IntOffset(-offsetDiff, 0)) } } else { if (isWest) { sw.contains(target + IntOffset(0, -offsetDiff)) } else { se.contains(target + IntOffset(-offsetDiff, -offsetDiff)) } } } } } private fun MacroCell.CellNode.makeCanonical(): MacroCell.CellNode = canonicalCellMap.getOrPut(this) { this } private inner class HashLifeCellState( val offset: IntOffset, val macroCell: MacroCell, ) : CellState() { init { // Check the invariant for the macroCell check(macroCell.level >= 3) } override val aliveCells: Set<IntOffset> = object : Set<IntOffset> { override val size: Int by lazy { macroCell.size() } override fun contains(element: IntOffset): Boolean { val target = element - offset val size = 1 shl macroCell.level return if (target.x in 0 until size && target.y in 0 until size) { macroCell.contains(target) } else { false } } override fun containsAll(elements: Collection<IntOffset>): Boolean = elements.all { contains(it) } override fun isEmpty(): Boolean = size == 0 override fun iterator(): Iterator<IntOffset> = macroCell.iterator(offset) } override fun offsetBy(offset: IntOffset) = HashLifeCellState( offset = this.offset + offset, macroCell = macroCell ) override fun withCell(offset: IntOffset, isAlive: Boolean): CellState { var hashLifeCellState = this var target: IntOffset while ( run { target = offset - hashLifeCellState.offset val size = 1 shl hashLifeCellState.macroCell.level target.x !in 0 until size || target.y !in 0 until size } ) { hashLifeCellState = hashLifeCellState.expandCentered() } return HashLifeCellState( offset = hashLifeCellState.offset, macroCell = hashLifeCellState.macroCell.withCell(target, isAlive) ) } override fun toString(): String = "HashLifeCellState(${aliveCells.toSet()})" } } private sealed class MacroCell { abstract val level: Int sealed class Cell : MacroCell() { override val level = 0 abstract val isAlive: Boolean object AliveCell : Cell() { override val isAlive = true } object DeadCell : Cell() { override val isAlive = false } } data class CellNode( val nw: MacroCell, val ne: MacroCell, val sw: MacroCell, val se: MacroCell, ) : MacroCell() { override val level = nw.level + 1 val hashCode by lazy { var hash = level hash *= 31 hash += nw.hashCode() hash *= 31 hash += ne.hashCode() hash *= 31 hash += sw.hashCode() hash *= 31 hash += se.hashCode() hash } override fun hashCode(): Int = hashCode override fun equals(other: Any?): Boolean = if (other !is CellNode) { false } else { other.level == level && other.nw === nw && other.ne === ne && other.sw === sw && other.se === se } } }
class AssignmentsController < ApplicationController def index @assignments = authorize Assignment.all @user = current_user @participants = Participant.all @participants_list = [] @participants.each do |p| if p.personal_questionnaire.nil? PersonalQuestionnaire.create("participant_id": p.id) end participant = SimpleParticipantSerializer.new(p) @participants_list.push(participant) end @templates = ActionItem.where(is_template: true).order('created_at DESC') @templates_list = [] @templates.each do |template| serialized_action_item = ActionItemSerializer.new(template) @templates_list.push(serialized_action_item) end end end
export { default as DeleteManager } from './DeleteManager.js' export { default as InsertManager } from './InsertManager.js' export { default as SelectManager } from './SelectManager.js' export { default as TreeManager } from './TreeManager.js' export { default as UpdateManager } from './UpdateManager.js'
#!/usr/bin/env bash NEW_TAG=$(date +'%Y.%m.%d') TAG_REPLACEMENT=".version=\"${NEW_TAG}\"" cat package.json | jq -r "${TAG_REPLACEMENT}" > package.json.tmp rm -f package.json mv package.json.tmp package.json git add package.json git commit -m "v${NEW_TAG}" git tag "${NEW_TAG}" -m "v${NEW_TAG}" || exit 1
package com.github.gmazzo.gradle.plugins.generators import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.PropertySpec object BuildConfigKotlinFileGenerator : BuildConfigKotlinGenerator() { override fun FileSpec.Builder.addFields(fields: List<PropertySpec>) = fields.fold(this) { acc, it -> acc.addProperty(it) } }