text
stringlengths
27
775k
# frozen_string_literal: true require 'opal/nodes/node_with_args' require 'opal/rewriters/break_finder' module Opal module Nodes class IterNode < NodeWithArgs handle :iter children :args, :body attr_accessor :block_arg, :shadow_args def compile inline_params = nil extract_block_arg extract_shadow_args extract_underscore_args split_args to_vars = identity = body_code = nil in_scope do inline_params = process(inline_args_sexp) identity = scope.identify! add_temp "self = #{identity}.$$s || this" compile_block_arg compile_shadow_args compile_inline_args compile_post_args compile_norm_args if compiler.arity_check? compile_arity_check end body_code = stmt(returned_body) to_vars = scope.to_vars end line body_code unshift to_vars unshift "(#{identity} = function(", inline_params, '){' push "}, #{identity}.$$s = self," push " #{identity}.$$brk = $brk," if contains_break? push " #{identity}.$$arity = #{arity}," if compiler.arity_check? push " #{identity}.$$parameters = #{parameters_code}," end # MRI expands a passed argument if the block: # 1. takes a single argument that is an array # 2. has more that one argument # With a few exceptions: # 1. mlhs arg: if a block takes |(a, b)| argument # 2. trailing ',' in the arg list (|a, |) # This flag on the method indicates that a block has a top level mlhs argument # which means that we have to expand passed array explicitly in runtime. if has_top_level_mlhs_arg? push " #{identity}.$$has_top_level_mlhs_arg = true," end if has_trailing_comma_in_args? push " #{identity}.$$has_trailing_comma_in_args = true," end push " #{identity})" end def norm_args @norm_args ||= args.children.select { |arg| arg.type == :arg } end def compile_norm_args norm_args.each do |arg| arg_name, _ = *arg push "if (#{arg_name} == null) #{arg_name} = nil;" end end def compile_block_arg if block_arg scope.block_name = block_arg scope.add_temp block_arg scope_name = scope.identify! line "#{block_arg} = #{scope_name}.$$p || nil;" line "if (#{block_arg}) #{scope_name}.$$p = null;" end end def extract_block_arg *regular_args, last_arg = args.children if last_arg && last_arg.type == :blockarg @block_arg = last_arg.children[0] @sexp = @sexp.updated( nil, [ s(:args, *regular_args), body ] ) end end def compile_shadow_args shadow_args.each do |shadow_arg| arg_name = shadow_arg.children[0] scope.locals << arg_name scope.add_arg(arg_name) end end def extract_shadow_args @shadow_args = [] valid_args = [] return unless args args.children.each do |arg| if arg.type == :shadowarg @shadow_args << arg else valid_args << arg end end @sexp = @sexp.updated( nil, [ args.updated(nil, valid_args), body ] ) end def extract_underscore_args valid_args = [] caught_blank_argument = false args.children.each do |arg| arg_name = arg.children.first if arg_name == :_ unless caught_blank_argument caught_blank_argument = true valid_args << arg end else valid_args << arg end end @sexp = @sexp.updated( nil, [ args.updated(nil, valid_args), body ] ) end def returned_body compiler.returns(body || s(:nil)) end def mlhs_args scope.mlhs_mapping.keys end def has_top_level_mlhs_arg? args.children.any? { |arg| arg.type == :mlhs } end def has_trailing_comma_in_args? if args.loc && args.loc.expression args_source = args.loc.expression.source args_source.match(/,\s*\|/) end end # Returns code used in debug mode to check arity of method call def compile_arity_check unless arity_checks.empty? parent_scope = scope until parent_scope.top? || parent_scope.def? || parent_scope.class_scope? parent_scope = parent_scope.parent end context = if parent_scope.top? "'<main>'" elsif parent_scope.def? "'#{parent_scope.mid}'" elsif parent_scope.class? "'<class:#{parent_scope.name}>'" elsif parent_scope.module? "'<module:#{parent_scope.name}>'" end identity = scope.identity line "if (#{identity}.$$is_lambda || #{identity}.$$define_meth) {" line ' var $arity = arguments.length;' line " if (#{arity_checks.join(' || ')}) { Opal.block_ac($arity, #{arity}, #{context}); }" line '}' end end def contains_break? finder = Opal::Rewriters::BreakFinder.new finder.process(@sexp) finder.found_break? end end end end
import 'package:tiled/tiled.dart'; /// {@template _simple_flips} /// Tiled represents all flips and rotation using three possible flips: /// horizontal, vertical and diagonal. /// This class converts that representation to a simpler one, that uses one /// angle (with pi/2 steps) and one flip (horizontal). All vertical flips are /// represented as horizontal flips + 180º. /// Further reference: /// https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#tile-flipping. /// /// `cos` and `sin` are the cosine and sine of the rotation respectively, and /// and are provided for simple calculation with RSTransform. /// Further reference: /// https://api.flutter.dev/flutter/dart-ui/RSTransform/RSTransform.html /// {@endtemplate} class SimpleFlips { /// The angle (in steps of pi/2 rads), clockwise, around the center of the tile. final int angle; /// The cosine of the rotation. final int cos; /// The sine of the rotation. final int sin; /// Whether to flip (across a central vertical axis). final bool flip; /// {@macro _simple_flips} SimpleFlips(this.angle, this.cos, this.sin, this.flip); /// This is the conversion from the truth table that I drew. factory SimpleFlips.fromFlips(Flips flips) { int angle, cos, sin; bool flip; if (!flips.diagonally && !flips.vertically && !flips.horizontally) { angle = 0; cos = 1; sin = 0; flip = false; } else if (!flips.diagonally && !flips.vertically && flips.horizontally) { angle = 0; cos = 1; sin = 0; flip = true; } else if (flips.diagonally && !flips.vertically && flips.horizontally) { angle = 1; cos = 0; sin = 1; flip = false; } else if (flips.diagonally && flips.vertically && flips.horizontally) { angle = 1; cos = 0; sin = 1; flip = true; } else if (!flips.diagonally && flips.vertically && flips.horizontally) { angle = 2; cos = -1; sin = 0; flip = false; } else if (!flips.diagonally && flips.vertically && !flips.horizontally) { angle = 2; cos = -1; sin = 0; flip = true; } else if (flips.diagonally && flips.vertically && !flips.horizontally) { angle = 3; cos = 0; sin = -1; flip = false; } else if (flips.diagonally && !flips.vertically && !flips.horizontally) { angle = 3; cos = 0; sin = -1; flip = true; } else { // this should be exhaustive throw 'Invalid combination of booleans: $flips'; } return SimpleFlips(angle, cos, sin, flip); } }
/* * Copyright 2018 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import PropTypes from 'prop-types'; import React from 'react'; import _ from 'lodash'; import VizceralExt from './VizceralExt'; const propTypes = { detailedService: PropTypes.string, graph: PropTypes.shape({}).isRequired, onDetailedServiceChange: PropTypes.func.isRequired, searchString: PropTypes.string.isRequired, }; const defaultProps = { detailedService: undefined, }; const style = { colorConnectionLine: 'rgb(160, 150, 160)', }; class DependenciesGraph extends React.Component { constructor(props) { super(props); this.handleObjectHighlighted = this.handleObjectHighlighted.bind(this); } handleObjectHighlighted(highlightedObject) { const { detailedService, onDetailedServiceChange, } = this.props; if (typeof highlightedObject === 'undefined') { onDetailedServiceChange(undefined); return; } if (highlightedObject.type === 'node' && highlightedObject.getName() !== detailedService) { onDetailedServiceChange(highlightedObject.getName()); } } render() { const { graph, searchString } = this.props; let maxVolume = 0; if (graph.allEdges().length > 0) { const maxVolumeEdge = _.maxBy( graph.allEdges(), edge => edge.metrics.normal + edge.metrics.danger, ); maxVolume = maxVolumeEdge.metrics.normal + maxVolumeEdge.metrics.danger; } return ( <div className="dependencies__graph"> <VizceralExt allowDraggingOfNodes targetFramerate={15} traffic={{ renderer: 'region', layout: 'ltrTree', name: 'dependencies-graph', updated: new Date().getTime(), maxVolume: maxVolume * 2000, nodes: graph.allNodes(), connections: graph.allEdges(), }} objectHighlighted={this.handleObjectHighlighted} match={searchString} styles={style} /> </div> ); } } DependenciesGraph.propTypes = propTypes; DependenciesGraph.defaultProps = defaultProps; export default DependenciesGraph;
<?php /* Queue Settings, Queue Names must not have whitespace, or HTML ids fail! */ $conf['queue']['budget']['cpu'] = 8; $conf['queue']['budget']['memory'] = 24; $conf['queue']['budget']['nodes'] = 10; $conf['queue']['blacklight']['cpu'] = 384; $conf['queue']['blacklight']['memory'] = 2048; $conf['queue']['blacklight']['nodes'] = 4; $conf['queue']['default']['cpu'] = 24; $conf['queue']['default']['memory'] = 384; $conf['queue']['default']['nodes'] = 20; $conf['queue']['default']['default'] = 1; $conf['queue']['largememory']['cpu'] = 24; $conf['queue']['largememory']['memory'] = 1024; $conf['queue']['largememory']['nodes'] = 1; /* Recommended and Optional Settings we want the user to specifyn */ $conf['settings']['recommended'] = array('M','N','d'); $conf['settings']['optional'] = array('e','A'); /* Torque Qsub Settings */ /* Special case should have the parameter as its value, and you must handle the logic in a javascript function */ $conf['param']['a']['description'] = 'Date / Time'; $conf['param']['a']['example'] = '02/02/1989'; $conf['param']['A']['description'] = 'Project'; $conf['param']['A']['example'] = 'beeSequencing101'; $conf['param']['b']['description'] = 'pbs_server contact timeout '; $conf['param']['b']['example'] = 'example'; $conf['param']['c']['description'] = 'description'; $conf['param']['c']['example'] = 'example'; $conf['param']['C']['description'] = 'description'; $conf['param']['C']['example'] = 'example'; $conf['param']['d']['description'] = 'Working directory path'; $conf['param']['d']['example'] = '/home/n-z/yournetid/experimentX/run1'; $conf['param']['D']['description'] = 'description'; $conf['param']['D']['example'] = 'example'; $conf['param']['e']['description'] = 'Standard error output file'; $conf['param']['e']['example'] = 'list_of_errors.err'; $conf['param']['f']['description'] = 'Faul Tolerant'; $conf['param']['f']['example'] = 'example'; $conf['param']['h']['description'] = 'description'; $conf['param']['h']['example'] = 'example'; $conf['param']['I']['description'] = 'Use interactive mode'; $conf['param']['I']['example'] = 'example'; $conf['param']['j']['description'] = 'j oe'; $conf['param']['j']['example'] = 'example'; $conf['param']['k']['description'] = 'k oe'; $conf['param']['j']['example'] = 'example'; $conf['param']['l']['description'] = 'resource list'; $conf['param']['l']['example'] = 'ppn:5;etc'; $conf['param']['M']['description'] = 'Email'; $conf['param']['M']['example'] = 'netid@illinois.edu'; $conf['param']['M']['special_case'] = 'M'; $conf['param']['m']['description'] = ''; $conf['param']['m']['example'] = ''; $conf['param']['m']['special_case'] = 'm'; $conf['param']['N']['description'] = 'Job Name'; $conf['param']['N']['example'] = 'example101job'; $conf['param']['o']['description'] = 'description'; $conf['param']['o']['example'] = 'example'; $conf['param']['p']['description'] = 'description'; $conf['param']['p']['example'] = 'example'; $conf['param']['P']['description'] = 'description'; $conf['param']['P']['example'] = 'example'; $conf['param']['q']['description'] = 'queue'; $conf['param']['q']['example'] = 'example'; $conf['param']['r']['description'] = 'description'; $conf['param']['r']['example'] = 'example'; $conf['param']['S']['description'] = 'description'; $conf['param']['S']['example'] = 'example'; $conf['param']['t']['description'] = 'description'; $conf['param']['t']['example'] = 'example'; $conf['param']['T']['description'] = 'description'; $conf['param']['T']['example'] = 'example'; $conf['param']['u']['description'] = 'description'; $conf['param']['u']['example'] = 'example'; $conf['param']['W']['description'] = 'description'; $conf['param']['W']['example'] = 'example'; $conf['param']['v']['description'] = 'description'; $conf['param']['v']['example'] = 'example'; $conf['param']['V']['description'] = 'description'; $conf['param']['V']['example'] = 'example'; $conf['param']['x']['description'] = 'description'; $conf['param']['x']['example'] = 'example'; $conf['param']['X']['description'] = 'use X11 Display'; $conf['param']['X']['example'] = 'example'; $conf['param']['z']['description'] = 'description'; $conf['param']['z']['example'] = 'example'; ?>
package Release_VIII.A_Chapter_9.R10_Cons; import java.util.Random; public class Questions implements SharedCons { Random rand = new Random(); int ask() { int prob = (int) (100*rand.nextDouble()); if(prob<30) return NO; //30% else if(prob<60) return YES; //30% else if(prob<70) return MAYBE; //10% else if(prob<85) return LATER; //15% else if(prob<98) return SOON; //13% else return NEVER; //2% } }
require 'benchmark' total = (ENV['TOTAL'] || 5_000).to_i array = Array.new(total) {|i| i} Benchmark.bmbm do |x| x.report 'empty' do total.times {|i| i } end x.report 'String#<<(fixed)' do str1 = "helluva" str2 = "fool" total.times do |i| str1 << str2 end end x.report 'String#<<(increasing)' do total.times do |i| str1 = "foo" * i % 100 str2 = "a" * i % 100 25.times do str1 << str2 end end end x.report 'String#+(fixed)' do str1 = "helluva" str2 = "fool" total.times do |i| str1 = str1 + str2 end end x.report 'String#+(increasing)' do total.times do |i| str1 = "foo" * i % 100 str2 = "a" * i % 100 25.times do str1 = str1 + str2 end end end x.report 'String#+=(fixed)' do str1 = "helluva" str2 = "fool" total.times do |i| str1 += str2 end end x.report 'String#+=(increasing)' do total.times do |i| str1 = "foo" * i % 100 str2 = "a" * i % 100 25.times do str1 += str2 end end end end
Matthew 9 18-26) The Jewish girl and the Gentile woman girl was 12, woman was sick for 12yr. 20) Jesus, on His way to raise the Jew, healed the Gentile
#!/usr/bin/perl print "Content-Type: text/html\n\n"; print "<ul>\n"; $queryString = $ENV{'QUERY_STRING'}; print "<li>$queryString</li>\n"; print "</ul>\n";
{-# LANGUAGE GADTSyntax #-} module LazyMList where data List m a where Nil :: List m a Cons :: a -> m (List m a) -> List m a type MList m a = m (List m a) nil :: Monad m => MList m a nil = return Nil cons :: Monad m => a -> MList m a -> MList m a cons a = return . Cons a mfoldr :: Monad m => (a -> m r -> m r) -> m r -> MList m a -> m r mfoldr f z ml = do l <- ml case l of Nil -> z Cons a ml' -> f a (mfoldr f z ml') mmap :: Monad m => (a -> b) -> MList m a -> MList m b mmap f = mfoldr (cons . f) nil example :: MList IO Int example = print "a" >> cons 1 (print "b" >> (cons 2 (print "c" >> nil))) mhead :: Monad m => MList m a -> m a mhead ml = do l <- ml case l of Nil -> error "head Nil" Cons a _ -> return a
# ![remark][logo] [![Build][build-badge]][build] [![Coverage][coverage-badge]][coverage] [![Downloads][downloads-badge]][downloads] [![Size][size-badge]][size] [![Sponsors][sponsors-badge]][collective] [![Backers][backers-badge]][collective] [![Chat][chat-badge]][chat] **remark** is a tool that transforms markdown with plugins. These plugins can inspect and change your markup. You can use remark on the server, the client, CLIs, deno, etc. > remark for deno ## License [MIT](license) © [Titus Wormer](https://wooorm.com) <!-- Definitions --> [logo]: https://raw.githubusercontent.com/remarkjs/remark/1f338e72/logo.svg?sanitize=true [build-badge]: https://github.com/remarkjs/remark/workflows/main/badge.svg [build]: https://github.com/remarkjs/remark/actions [coverage-badge]: https://img.shields.io/codecov/c/github/remarkjs/remark.svg [coverage]: https://codecov.io/github/remarkjs/remark [downloads-badge]: https://img.shields.io/npm/dm/remark.svg [downloads]: https://www.npmjs.com/package/remark [size-badge]: https://img.shields.io/bundlephobia/minzip/remark.svg [size]: https://bundlephobia.com/result?p=remark [chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg [chat]: https://github.com/remarkjs/remark/discussions [sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg [backers-badge]: https://opencollective.com/unified/backers/badge.svg [security]: https://github.com/remarkjs/.github/blob/main/security.md [health]: https://github.com/remarkjs/.github [contributing]: https://github.com/remarkjs/.github/blob/main/contributing.md [support]: https://github.com/remarkjs/.github/blob/main/support.md [coc]: https://github.com/remarkjs/.github/blob/main/code-of-conduct.md [collective]: https://opencollective.com/unified [xss]: https://en.wikipedia.org/wiki/Cross-site_scripting [typescript]: https://www.typescriptlang.org [cheat]: https://commonmark.org/help/ [twitter]: https://twitter.com/unifiedjs [site]: https://unifiedjs.com [topic]: https://github.com/topics/remark-plugin [popular]: https://www.npmtrends.com/remark-parse-vs-marked-vs-micromark-vs-markdown-it [types-mdast]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mdast [unified]: https://github.com/unifiedjs/unified [remark-gfm]: https://github.com/remarkjs/remark-gfm [remark-toc]: https://github.com/remarkjs/remark-toc [remark-rehype]: https://github.com/remarkjs/remark-rehype [remark-html]: https://github.com/remarkjs/remark-html [remark-lint]: https://github.com/remarkjs/remark-lint [awesome-remark]: https://github.com/remarkjs/awesome-remark [rehype]: https://github.com/rehypejs/rehype [rehype-sanitize]: https://github.com/rehypejs/rehype-sanitize [mdast]: https://github.com/syntax-tree/mdast [micromark]: https://github.com/micromark/micromark [remark-parse]: packages/remark-parse/ [remark-stringify]: packages/remark-stringify/ [remark-core]: packages/remark/ [remark-cli]: packages/remark-cli/ [list-of-plugins]: doc/plugins.md#list-of-plugins [syntax]: #syntax [syntax-tree]: #syntax-tree [plugins]: #plugins [contribute]: #contribute [sponsor]: #sponsor
<?php ##################### //CONFIGURATIONS ##################### // Define the name of the backup directory define('BACKUP_DIR', 'myBackups' ) ; // Define Database Credentials define('HOST', 'localhost' ) ; define('USER', 'root' ) ; define('PASSWORD', 'root' ) ; define('DB_NAME', 'time' ) ; /* Define the filename for the sql file If you plan to upload the file to Amazon's S3 service , use only lower-case letters */ $fileName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ; // Set execution time limit if(function_exists('max_execution_time')) { if( ini_get('max_execution_time') > 0 ) set_time_limit(0) ; } ########################### //END OF CONFIGURATIONS ########################### // Check if directory is already created and has the proper permissions if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ; if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; // Create an ".htaccess" file , it will restrict direct accss to the backup-directory . $content = 'deny from all' ; $file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ; $file->fwrite($content) ; $mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ; if (mysqli_connect_errno()) { printf("Connect failed: %s", mysqli_connect_error()); exit(); } // Introduction information $return .= "--\n"; $return .= "-- A Mysql Backup System \n"; $return .= "--\n"; $return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n"; $return = "--\n"; $return .= "-- Database : " . DB_NAME . "\n"; $return .= "--\n"; $return .= "-- --------------------------------------------------\n"; $return .= "-- ---------------------------------------------------\n"; $return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ; $return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ; $tables = array() ; // Exploring what tables this database has $result = $mysqli->query('SHOW TABLES' ) ; // Cycle through "$result" and put content into an array while ($row = $result->fetch_row()) { $tables[] = $row[0] ; } // Cycle through each table foreach($tables as $table) { // Get content of each table $result = $mysqli->query('SELECT * FROM '. $table) ; // Get number of fields (columns) of each table $num_fields = $mysqli->field_count ; // Add table information $return .= "--\n" ; $return .= '-- Tabel structure for table `' . $table . '`' . "\n" ; $return .= "--\n" ; $return.= 'DROP TABLE IF EXISTS `'.$table.'`;' . "\n" ; // Get the table-shema $shema = $mysqli->query('SHOW CREATE TABLE '.$table) ; // Extract table shema $tableshema = $shema->fetch_row() ; // Append table-shema into code $return.= $tableshema[1].";" . "\n\n" ; // Cycle through each table-row while($rowdata = $result->fetch_row()) { // Prepare code that will insert data into table $return .= 'INSERT INTO `'.$table .'` VALUES ( ' ; // Extract data of each row for($i=0; $i<$num_fields; $i++) { $return .= '"'.$rowdata[$i] . "\"," ; } // Let's remove the last comma $return = substr("$return", 0, -1) ; $return .= ");" ."\n" ; } $return .= "\n\n" ; } // Close the connection $mysqli->close() ; $return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n" ; $return .= 'COMMIT ; ' . "\n" ; $return .= 'SET AUTOCOMMIT = 1 ; ' . "\n" ; //$file = file_put_contents($fileName , $return) ; $zip = new ZipArchive() ; $resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ; if( $resOpen ){ $zip->addFromString( $fileName , "$return" ) ; } $zip->close() ; $fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ; $message = <<<msg <h2>BACKUP completed ,</h2> the archive has the name of : <b> $fileName </b> and it's file-size is : $fileSize . . msg; echo $message ; // Function to append proper Unit after file-size . function get_file_size_unit($file_size){ switch (true) { case ($file_size/1024 < 1) : return intval($file_size ) ." Bytes" ; break; case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1) : return intval($file_size/1024) ." KB" ; break; default: return intval($file_size/(1024*1024)) ." MB" ; } } ?>
<?php namespace Xinix\BonoAuth; class RequestWrapper { protected $request; public function __construct($request) { $this->request = $request; } public function __call($method, $parameters) { return call_user_func_array(array($this->request, $method), $parameters); } public function getJSON() { return json_decode($this->request->getBody(true), true); } public function getString() { return $this->request->getBody(true); } }
/* * SimpleRelational.cpp * * Created on: Feb 2, 2022 * Author: biplavs */ #include <iostream> #include <cstdlib> using namespace std; // Credit: Based on example in Chapter 14 of C++ book - // Fundamentals of Programming by Richard L. Halterman // Models a mathematical rational number class SimpleRational { int numerator; // private by default // Used for demonstrating public data member // public: int numerator; int denominator; bool valid; // Checks if the rational number is valid public: // Initializes the components of a Rational object SimpleRational(int n, int d): numerator(n), denominator(d) { if (d == 0) { // Flag that rational is not valid valid = false; // Display error message cout << "Zero denominator error\n"; } else valid = true; } SimpleRational(): numerator(0), denominator(1) {} // Allows a client to reassign the numerator void set_numerator(int n) { numerator = n; } // Allows a client to reassign the denominator. // Disallows an illegal fraction (zero denominator). int set_denominator(int d) { if (d != 0) denominator = d; else { // Display error message cout << "ERROR: Zero denominator var passed\n"; valid = false; return 1; // Flag problem } return 0; } // Allows a client to see the numerator's value. int get_numerator() { return numerator; } // Allows a client to see the denominator's value. int get_denominator() { return denominator; } // Allows to see fractions validity. bool get_valid() { return valid; } }; // ** Utility functions ** // Returns the product of two rational numbers SimpleRational static multiply(SimpleRational f1, SimpleRational f2) { int numerator = f1.get_numerator() * f2.get_numerator(); int denominator = f1.get_denominator() * f2.get_denominator(); SimpleRational result(numerator, denominator); return result; } // Prints the parts of the franction void static print_fraction(SimpleRational f) { cout << f.get_numerator() << "/" << f.get_denominator() << "| valid = " << f.get_valid(); }
using System; class Volleyball { static void Main() { string yearType = Console.ReadLine().ToLower(); int p = int.Parse(Console.ReadLine()); int h = int.Parse(Console.ReadLine()); double playedGames = 0; int totalWeekends = 48; int weekendsSofia = totalWeekends - h; playedGames += weekendsSofia * 3 / 4.0; playedGames += p * 2 / 3.0; playedGames += h; if (yearType == "leap") { playedGames *= 1.15; } Console.WriteLine(Math.Floor(playedGames)); } }
/// <reference types="react" /> /** * @private */ export interface StartCallButtonProps { onClickHandler: () => void; isDisabled: boolean; className?: string; /** If set, the button is intended to rejoin an existing call. */ rejoinCall?: boolean; } /** * @private */ export declare const StartCallButton: (props: StartCallButtonProps) => JSX.Element; //# sourceMappingURL=StartCallButton.d.ts.map
package org.dukecon.sessionize.jsondata import kotlinx.serialization.Serializable @Serializable data class Sponsor(val name: String, val groupName: String, val url: String, val icon: String, val sponsorId: String? = null) @Serializable data class SponsorGroup(val groupName: String, val sponsors: List<Sponsor>)
package cn.tursom.storage interface LiveTime { fun getLiveTime(roomId: Int): Long fun roomOnLive(roomId: Int) }
$(function () { $(document).ready(function () { $('.hamburger-fix-menu').click(function () { $('.box-right-line').toggleClass('z-index-style'); $(this).toggleClass('is-active'); $('.footer_box_fixed').fadeToggle(300); $('.box-right-line a:not(:first-child)').fadeToggle(0); $('.box-right-line a:first-child').toggleClass('no-color-menu'); }); $(window).scroll(function () { var top = $(document).scrollTop(); if (top > 80) { $('.box-right-line').addClass('fixed-menu-button'); $('.footer_box_fixed').addClass('fixed-menu'); } else { $('.box-right-line').removeClass('fixed-menu-button'); $('.footer_box_fixed').removeClass('fixed-menu'); } }); function setEqualHeight(columns) { var tallestcolumn = 0; columns.each( function () { currentHeight = jQuery(this).height(); if (currentHeight > tallestcolumn) { tallestcolumn = currentHeight; } } ); columns.height(tallestcolumn); } jQuery(document).ready(function () { setEqualHeight(jQuery(".section_slider_your_amobile .slider .item-slide")); setEqualHeight(jQuery('.news-page .box-content-news-slider')); if (window.matchMedia("screen and (min-width: 768px)").matches) { setEqualHeight(jQuery('.servise-box')); } if (window.matchMedia("screen and (max-width: 600px)").matches) { jQuery('.box-service-color').each(function () { setEqualHeight(jQuery(this).find('.cl-2[data-column="1"]')); setEqualHeight(jQuery(this).find('.cl-2[data-column="2"]')); setEqualHeight(jQuery(this).find('.cl-2[data-column="3"]')); setEqualHeight(jQuery(this).find('.cl-2[data-column="4"]')); setEqualHeight(jQuery(this).find('.cl-2[data-column="5"]')); }); } }); $('.search-header').click(function () { if ($('.search_header_input').hasClass('search_header_input_active')) { $('.search_header_input').removeClass('search_header_input_active'); } else { $('.search_header_input').addClass('search_header_input_active'); $('.search_header_input input[type="text"]').focus(); } } ); $('select').select2({ minimumResultsForSearch: -1 }); $(".list-header").select2({ minimumResultsForSearch: -1, dropdownCssClass: "list-header-dropdown" }); $('select').css('opacity', '1'); $("#my-menu").mmenu({ "slidingSubmenus": false, "extensions": [ "fx-menu-fade", "pagedim-black" ] }); var api_var = $('#my-menu').data('mmenu'); api_var.bind('open:finish', function () { $('.hamburger').addClass('is-active'); } ); api_var.bind('close:finish', function () { $('.hamburger').removeClass('is-active'); } ); $('.main-slider-desktop').slick({ slidesToShow: 1, dots: false, arrows: true, infinite: true, speed: 700, fade: true, cssEase: 'linear', autoplay: true, autoplaySpeed: 4000, prevArrow: '<img class="arrow-prev" src="img/back_w.svg">', nextArrow: '<img class="arrow-next" src="img/next.svg">', }); $('.slider-tel').slick({ slidesToShow: 1, dots: false, arrows: true, infinite: true, speed: 700, autoplay: true, autoplaySpeed: 4000, prevArrow: '<img class="arrow-prev" src="img/back_w.svg">', nextArrow: '<img class="arrow-next" src="img/next.svg">', }); $('.section_slider_your_amobile:not(.not_syle_slider) .slider').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000, dots: false, arrows: false, responsive: [ { breakpoint: 1200, settings: { dots: true, centerMode: false, slidesToShow: 1, slidesToScroll: 1 } } ] }); $('.section_slider_your_amobile.not_syle_slider .slider').slick({ centerPadding: '74px', centerMode: true, infinite: true, slidesToShow: 4, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000, dots: false, arrows: true, prevArrow: '<img class="arrow-prev" src="img/back.svg">', nextArrow: '<img class="arrow-next" src="img/next.svg">', responsive: [ { breakpoint: 1200, settings: { arrows: false, dots: true, centerMode: false, slidesToShow: 1, slidesToScroll: 1 } } ] }); $('#field_time').datetimepicker(); jQuery.datetimepicker.setLocale('ru'); $('div[data-target="#tab2"]').hide(); $('.tabgroup > div').hide(); $('div[data-target="#tab1"]').show(); $('.tabgroup > div:first-of-type').show(); $('.tabs a').click(function (e) { e.preventDefault(); var $this = $(this), tabgroup = '#' + $this.parents('.tabs').data('tabgroup'), others = $this.closest('li').siblings().children('a'), dataTarget = $this.attr('href'); target = $this.attr('href'); others.removeClass('active'); $this.addClass('active'); $(tabgroup).children('div').hide(); $(target).fadeIn(); $('div.box-hide-form').hide(); $('div.box-hide-map').hide(); $('div[data-target="' + dataTarget + '"]').fadeIn(); }); if (document.querySelector('img.down-arrow')) { document.querySelector('img.down-arrow').addEventListener('click', function () { var hideBox = document.querySelector('.box-placemarks'); if (hideBox.classList.contains('box-placemarks-hiiden-show')) { hideBox.classList.remove('box-placemarks-hiiden-show'); } else { hideBox.classList.add('box-placemarks-hiiden-show'); } }); } // ------------------------------------------ ВАЛИДАЦИЯ ФОРМЫ НАЧАЛО ------------------------------------------ jQuery('.error_validate_field_name').hide(); jQuery('.error_validate_field_tel').hide(); jQuery('.error_validate_field_email').hide(); var error_field_name = false; var error_field_tel = false; var error_field_email = false; var error_field_town = false; var error_field_street = false; var error_field_house = false; var error_field_phone_field = false; jQuery('#field_name').focusout(function () { check_field_name(); }); jQuery('#field_tel').focusout(function () { check_field_tel(); }); jQuery('#field_email').focusout(function () { check_field_email(); }); jQuery('#field_town').focusout(function () { check_field_town(); }); jQuery('#field_street').focusout(function () { check_field_street(); }); jQuery('#field_house').focusout(function () { check_field_house(); }); jQuery('#write_question').focusout(function () { check_field_write_question(); }); // jQuery('#phone1_field').focusout(function () { // check_field_phone1_field(); // }); jQuery('#phone2_field').focusout(function () { check_field_phone2_field(); }); function check_field_phone2_field() { var tel_str = jQuery("#phone2_field").val(); var i = tel_str.length - tel_str.replace(/\d/gm, '').length; if (i < 7) { jQuery('#phone2_field').addClass('error_input'); jQuery('.error_validate_field_tel').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_tel').fadeIn(200); error_field_phone_field = true; } else { jQuery('#phone2_field').removeClass('error_input'); jQuery('.error_validate_field_tel').fadeOut(200); } } function check_field_write_question() { var field_write_question = jQuery('#write_question').val() if ((jQuery.trim(field_write_question) == '' )) { jQuery('#write_question').addClass('error_input'); jQuery('.error_validate_field_write_question').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_write_question').fadeIn(200); error_field_write_question = true; } else { jQuery('.error_validate_field_write_question').fadeOut(200); jQuery('#write_question').removeClass('error_input'); } } function check_field_town() { var field_town_length = jQuery('#field_town').val() if ((jQuery.trim(field_town_length) == '' )) { jQuery('#field_town').addClass('error_input'); jQuery('.error_validate_field_town').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_town').fadeIn(200); error_field_town = true; } else { jQuery('.error_validate_field_town').fadeOut(200); jQuery('#field_town').removeClass('error_input'); } } function check_field_street() { var field_street_length = jQuery('#field_street').val() if ((jQuery.trim(field_street_length) == '' )) { jQuery('#field_street').addClass('error_input'); jQuery('.error_validate_field_street').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_street').fadeIn(200); error_field_street = true; } else { jQuery('.error_validate_field_street').fadeOut(200); jQuery('#field_street').removeClass('error_input'); } } function check_field_house() { var field_house_length = jQuery('#field_house').val() if ((jQuery.trim(field_house_length) == '' )) { jQuery('#field_house').addClass('error_input'); jQuery('.error_validate_field_house').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_house').fadeIn(200); error_field_house = true; } else { jQuery('.error_validate_field_house').fadeOut(200); jQuery('#field_house').removeClass('error_input'); } } function check_field_name() { var field_name_length = jQuery('#field_name').val() if ((jQuery.trim(field_name_length) == '' )) { jQuery('#field_name').addClass('error_input'); jQuery('.error_validate_field_name').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_name').fadeIn(200); error_field_name = true; } else { jQuery('.error_validate_field_name').fadeOut(200); jQuery('#field_name').removeClass('error_input'); } } function check_field_tel() { var tel_str = jQuery("#field_tel").val(); var i = tel_str.length - tel_str.replace(/\d/gm, '').length; if (i < 11) { jQuery('#field_tel').addClass('error_input'); jQuery('.error_validate_field_tel').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_tel').fadeIn(200); error_field_tel = true; } else { jQuery('#field_tel').removeClass('error_input'); jQuery('.error_validate_field_tel').fadeOut(200); } } function check_field_email() { var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i); var email_str = jQuery("#field_email").val(); if ((jQuery.trim(email_str) == '')) { jQuery('#field_email').addClass('error_input'); jQuery('.error_validate_field_email').text('Поле обязательно для заполнения'); jQuery('.error_validate_field_email').fadeIn(200); error_field_email = true; } else if (pattern.test(email_str)) { jQuery('#field_email').removeClass('error_input'); jQuery('.error_validate_field_email').fadeOut(200); } else { jQuery('#field_email').addClass('error_input'); jQuery('.error_validate_field_email').text('Неверно введен email'); jQuery('.error_validate_field_email').fadeIn(200); error_field_email = true; } } $.mask.definitions['9'] = ''; $.mask.definitions['n'] = '[0-9]'; $("#field_tel").mask("+7 (940) nnn-nn-nn"); $("#phone1_field").mask("+7 (940)"); $("#phone2_field").mask("nnn-nn-nn"); setTimeout("$('.ymaps-2-1-62-map-copyrights-promo').css('display','none');", 1000); setTimeout("$('.ymaps-2-1-62-copyrights-pane').css('display','none');", 1000); //----------------------- Тыбы на странице FAQ НАЧАЛО ----------------------- $(".section-faq-tabs .tab_content:not(.not-tab-content)").hide(); $(".section-faq-tabs .tab_content:not(.not-tab-content):first").show(); $(".section-faq-tabs .tabs:not(.not-tabs) .point").click(function () { $(".section-faq-tabs .tab_content").hide(); var activeTab = $(this).attr("rel"); $("#" + activeTab).fadeIn(); $(".section-faq-tabs .tabs .point").removeClass("active"); $(this).addClass("active"); }); $(".tabs-select:not(.not-tabs-select)").change(function (e) { e.preventDefault(); $('.box-service-color').removeClass('active'); $(".section-faq-tabs .tab_content").hide(); $(this.value).addClass('active').fadeIn(); }); $(".slider-tabs .section-faq-tabs .tab_content").css({'opacity':'0','z-index':'0'}); $(".slider-tabs .section-faq-tabs .tab_content:first").css({'opacity':'1','z-index':'777'}); $(".slider-tabs .section-faq-tabs .tabs .point").click(function () { $(".slider-tabs .section-faq-tabs .tab_content").css({'opacity':'0','z-index':'0'}); var activeTab = $(this).attr("rel"); $("#" + activeTab).css({'opacity':'1','z-index':'777'}); $(".slider-tabs .section-faq-tabs .tabs .point").removeClass("active"); $(this).addClass("active"); }); $(".slider-tabs .tabs-select").change(function (e) { e.preventDefault(); $('.box-service-color').removeClass('active'); $(".section-faq-tabs .tab_content").css({'opacity':'0','z-index':'0'}); $(this.value).addClass('active').css({'opacity':'1','z-index':'777'}); }); //----------------------- Тыбы на странице FAQ КОНЕЦ ----------------------- //----------------------- Аккардион НАЧАЛО ----------------------- var box_accordion = document.querySelectorAll('.box-service-color'); var i_count; for (i_count = 0; i_count < box_accordion.length; i_count++) { box_accordion[i_count].children[0].addEventListener('click', clickBox); } function clickBox() { var hideBox = this.parentNode; if (hideBox.classList.contains('active-serv')) { hideBox.classList.remove('active-serv'); } else { for (i_count = 0; i_count < box_accordion.length; i_count++) { box_accordion[i_count].classList.remove('active-serv'); } hideBox.classList.add('active-serv'); } } //----------------------- Аккардион КОНЕЦ ----------------------- //----------------------- Активация оплаты НАЧАЛО ----------------------- var cardPay = document.querySelectorAll('.card-pay-item'); var cardPayInput = document.querySelector('.card-pay-value'); for (var f = 0; f < cardPay.length; f++) { cardPay[f].addEventListener('click', acticePay); } function acticePay() { var id = this.getAttribute('id'); cardPayInput.setAttribute('value',id) ; var childrens = this.parentNode.children; if (this.classList.contains('active-pay')) { this.classList.remove('active-pay'); for (var ff = 0; ff < childrens.length; ff++) { if (childrens[ff].classList.contains('active-pay')) { childrens[ff].classList.remove('active-pay'); } } } else { for (var ff = 0; ff < childrens.length; ff++) { if (childrens[ff].classList.contains('active-pay')) { childrens[ff].classList.remove('active-pay'); } } this.classList.add('active-pay'); } } //----------------------- Активация оплаты Аккардион КОНЕЦ ----------------------- //----------------------- Показать ещё Начало ----------------------- var cardPay = document.querySelector('.view-more-pay a'); if (cardPay) { cardPay.onclick = function openBox(e) { e.preventDefault(); var boxHide = document.querySelector('.box-cards-pay'); boxHide.classList.toggle('open-hide-box'); if (boxHide.classList.contains('open-hide-box')) { this.innerHTML = "Скрыть" } else { this.innerHTML = "Показать ещё" } } } var cardPay2 = document.querySelectorAll('.view_more_req'); var linkText = []; for (var aa = 0; aa < cardPay2.length; aa++) { linkText[aa] = cardPay2[aa].innerHTML; cardPay2[aa].setAttribute('data-index', aa); cardPay2[aa].onclick = function (e) { e.preventDefault(); var childrens = this.parentNode.children; var indexElem = this.getAttribute('data-index'); for (var gg = 0; gg < childrens.length; gg++) { if (childrens[gg].classList.contains('open-hide-box')) { childrens[gg].classList.remove('open-hide-box'); this.innerHTML = linkText[indexElem]; } else { childrens[gg].classList.add('open-hide-box'); this.innerHTML = "Скрыть"; } } } } if (window.matchMedia("screen and (max-width: 500px)").matches) { var el = document.querySelectorAll('.box-all-tarifs-data'); for (var gv = 0; gv < el.length; gv++) { var elch = el[gv].children; for (var gf = 0; gf < elch.length; gf++) { var firstChild = elch[0]; if (elch[gf].classList.contains('big-number-wrap')) { elch[gf].parentNode.insertBefore(elch[gf], firstChild.nextSibling) } } } } var viewMore = document.querySelectorAll('.view_more_alltarif'); for (var dd = 0; dd < viewMore.length; dd++) { viewMore[dd].onclick = function (e) { e.preventDefault(); var par = this.parentNode; par.parentNode.classList.toggle('open-all-tarif'); par.children[0].children[0].children[1].classList.toggle('max-heihgt-text'); if (this.parentNode.parentNode.classList.contains('open-all-tarif')) { this.innerHTML = "Скрыть"; } else { this.innerHTML = "Подробнее"; } } } //----------------------- Показать ещё Конец ----------------------- var numberSpace = document.querySelectorAll('.servises-full-line .col1-line'); for (var cc = 0; cc < numberSpace.length; cc++) { var str = numberSpace[cc].innerHTML; var result = str.replace(/([0-9]+)/g, "<span class='space-numb'>$1</span>"); numberSpace[cc].innerHTML= result; var numberSpaceStr = document.querySelectorAll('.servises-full-line .space-numb'); for (var cj = 0; cj < numberSpaceStr.length; cj++) { numberSpaceStr[cj].innerHTML = numberSpaceStr[cj].innerHTML.replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 '); } } var numberSpace2 = document.querySelectorAll('.servises-full-line .col2-line'); for (var cl = 0; cl < numberSpace2.length; cl++) { var str2 = numberSpace2[cl].innerHTML; var strSpace2 = str2.replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 '); numberSpace2[cl].innerHTML= strSpace2; } $('.servises-full-line').css('opacity','1') }); $('.popup-with-zoom-anim').magnificPopup({ type: 'inline', fixedContentPos: true, fixedBgPos: true, overflowY: 'auto', closeBtnInside: true, preloader: false, midClick: true, removalDelay: 300, mainClass: 'my-mfp-zoom-in', closeMarkup: '<div class="mfp-close"></div>' }); $('.box-toggle-map-list>div').each(function(){ $(this).click(function(){ $('.box-toggle-map-list>div').removeClass('active-point'); $(this).addClass('active-point'); $('.none-display').css('display','none'); $('#'+$(this).attr('data-id')).css('display','block'); }) }) });
package io.gitlab.arturbosch.detekt.cli.runners import io.gitlab.arturbosch.detekt.cli.ClasspathResourceConverter import io.gitlab.arturbosch.detekt.cli.CliArgs import io.gitlab.arturbosch.detekt.cli.DEFAULT_CONFIG import java.io.File class ConfigExporter(private val arguments: CliArgs) : Executable { override fun execute() { val configPath = if (arguments.config != null) arguments.config!! else DEFAULT_CONFIG val defaultConfig = ClasspathResourceConverter().convert(DEFAULT_CONFIG).openStream() defaultConfig.copyTo(File(configPath).outputStream()) println("Successfully copied default config to ${File(configPath).absolutePath}") } }
namespace InteriorDesign.Web.Controllers { using System.Security.Claims; using System.Threading.Tasks; using InteriorDesign.Data.Models; using InteriorDesign.Models.InputModels; using InteriorDesign.Services.Contracts; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; public class DesignBoardController : BaseController { private readonly IDesignBoardService designBoardService; private readonly UserManager<ApplicationUser> userManager; public DesignBoardController(IDesignBoardService designBoardService, UserManager<ApplicationUser> userManager) { this.designBoardService = designBoardService; this.userManager = userManager; } [Authorize] [HttpGet("/DesignBoard/Create")] public async Task<IActionResult> Create(string id) { var model = new DesignBoardCreateInputModel { ProjectId = id, CustomerId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value, }; return this.View(model); } [Authorize] [HttpPost("/DesignBoard/Create")] public async Task<IActionResult> Create(DesignBoardCreateInputModel model) { if (this.ModelState.IsValid) { await this.designBoardService.AddDesignBoard(model); } return this.RedirectToAction("Details", "Project", new { id = model.ProjectId }); } } }
import 'package:equatable/equatable.dart'; abstract class ListPageState extends Equatable { const ListPageState(); } class Uninitialized extends ListPageState { @override List<Object> get props => null; @override String toString() => '[State] ListPageState: Uninitialized'; } class Saving extends ListPageState { @override List<Object> get props => null; @override String toString() => '[State] ListPageState: Saving'; } class Saved extends ListPageState { @override List<Object> get props => null; @override String toString() => '[State] ListPageState: Saved'; }
/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ #include <realm.hpp> #include "error_handling.hpp" #include "marshalling.hpp" #include "realm_export_decls.hpp" using namespace realm; using namespace realm::binding; extern "C" { REALM_EXPORT void row_destroy(Row* row_ptr) { handle_errors([&]() { delete row_ptr; }); } REALM_EXPORT size_t row_get_row_index(const Row* row_ptr) { return handle_errors([&]() { return row_ptr->get_index(); }); } REALM_EXPORT size_t row_get_is_attached(const Row* row_ptr) { return handle_errors([&]() { return bool_to_size_t(row_ptr->is_attached()); }); } } // extern "C"
# coding=utf8 import json import traceback from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.contrib.auth.models import User as Auth_User from lib import utils from config import errors ROLE2NAME = { 1: '超管', 0: '一般管' } STATUS2NAME = { 1: '正常', 0: '封停' } @csrf_exempt def test(request): return utils.NormalResp() @csrf_exempt def get_list(request): try: p = request.GET.get('p', 1) n = request.GET.get('n', 30) username = request.GET.get('account') is_superuser = int(request.GET.get('role', -1)) is_active = int(request.GET.get('status', -1)) q = Auth_User.objects if username: q = q.filter(username__icontains=username) if is_superuser != -1: q = q.filter(is_superuser=is_superuser) if is_active != -1: q = q.filter(is_active=is_active) tot = q.count() q = q.order_by('-id') users = q.all()[(p-1)*n:p*n] data = [] for u in users: info = { 'id': u.id, 'account': u.username, 'email': u.email, 'created_at': u.date_joined.strftime('%Y-%m-%d %H:%m:%S'), 'role': int(u.is_superuser), 'role_name': ROLE2NAME[u.is_superuser], 'status': int(u.is_active), 'status_name': STATUS2NAME[u.is_active] } data.append(info) except: traceback.print_exc() return utils.ErrResp(errors.SthWrong) d = {'tot': tot, 'p': p, 'n': n, 'data': data} return utils.NormalResp(d) @csrf_exempt def info(request): try: aid = int(request.GET.get('id', 0)) if not aid: return utils.ErrResp(errors.ArgMis) try: u = Auth_User.objects.get(id=aid) except: return utils.ErrResp(errors.UserNotExists) info = { 'id': u.id, 'account': u.username, 'email': u.email, 'created_at': u.date_joined.strftime('%Y-%m-%d H:M:S'), 'role': u.is_superuser, 'role_name': ROLE2NAME[u.is_superuser], 'status': u.is_active, 'status_name': STATUS2NAME[u.is_active], 'password': '' } except: traceback.print_exc() return utils.ErrResp(errors.SthWrong) return utils.NormalResp(info) @csrf_exempt @require_http_methods(['POST']) def new(request): try: username = request.POST.get('account', '') password = request.POST.get('password', '') email = request.POST.get('email', '') is_superuser = request.POST.get('role', 0) username_exists = Auth_User.objects.filter(username=username).count() if username_exists: return utils.ErrResp(errors.UserExists) email_exists = Auth_User.objects.filter(email=email).count() if email_exists: return utils.ErrResp(errors.EmailExists) if not username or not password or not email: return utils.ErrResp(errors.ArgMis) u = Auth_User.objects.create_user(username, email, password) u.is_superuser = is_superuser u.save() except: traceback.print_exc() return utils.ErrResp(errors.SthWrong) return utils.NormalResp({'id': u.id}) @csrf_exempt @require_http_methods(['POST']) def update(request): try: aid = int(request.POST.get('id', 0)) email = request.POST.get('email', '') is_superuser = int(request.POST.get('role', -1)) is_active = int(request.POST.get('status', -1)) password = request.POST.get('password', '') if not aid: return utils.ErrResp(errors.ArgMis) try: u = Auth_User.objects.get(id=aid) except: return utils.ErrResp(errors.UserNotExists) if email: email_exists = Auth_User.objects.filter(email=email).count() if email_exists: return utils.ErrResp(errors.EmailExists) u.email = email if is_superuser != -1: u.is_superuser = is_superuser if is_active != -1: u.is_active = is_active if password: u.set_password(password) u.save() except: traceback.print_exc() return utils.ErrResp(errors.SthWrong) return utils.NormalResp({'id': aid})
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace InterestRateCalc.Api.Core.Dtos { public class InputObjectDto { public decimal CreditAmount { get; set; } public int Term { get; set; } public decimal ExistingCredit { get; set; } } }
fn bool_to_f64(b: &bool) -> f64 { if *b { 1.0 } else { 0.0 } } pub struct Neuron { threshold: f64, learning_rate: f64, weights: Vec<f64>, } impl Neuron { pub fn new(num_inputs: u32) -> Neuron { Neuron { threshold: 0.9, learning_rate: 0.01, weights: vec![0.0; num_inputs as usize], } } pub fn forward(&self, inputs: &Vec<bool>) -> f64 { if self.weights.len() == inputs.len() { let mut sum = 0.0; for i in 0..self.weights.len() { let input_value = bool_to_f64(&inputs[i]); sum += input_value * self.weights[i]; } return sum.tanh(); } 0.0 } pub fn forward_binary(&self, inputs: &Vec<bool>) -> bool { if self.forward(inputs) > self.threshold { return true; } false } pub fn forward_binary_check(&self, inputs: &Vec<bool>, answer: &bool) -> bool { let result = self.forward_binary(inputs); if result == *answer { return true; } false } pub fn train(&mut self, inputs: &Vec<bool>, answer: &bool) -> bool { let result = self.forward_binary(inputs); let answer_value = bool_to_f64(answer); let result_value = bool_to_f64(&result); for i in 0..self.weights.len() { let input = bool_to_f64(&inputs[i]); self.weights[i] += self.learning_rate * (answer_value - result_value) * input; } self.threshold -= self.learning_rate * (answer_value - result_value); if result == *answer { return true; } false } }
# frozen_string_literal: true module Fumifumi module Magazine class Import def initialize(magazine) @magazine = magazine end def call update_magazine do |magazine| magazine.update! series: series magazine.import!(book) end end private attr_reader :magazine def book @book ||= begin tempfile do |temp| magazine.source.copy_to_local_file(:original, temp.path) Fumifumi::Parser::Epub.new(temp.path).call end end end def update_magazine ApplicationRecord.transaction do magazine.reset! magazine.tap(&Proc.new).reload end end def series_name @series_name ||= Amakanize::SeriesName.new(filename).to_s end def filename File.basename(File.basename(magazine.original_filename, '.*'), '_*') end def series return nil if series_name.empty? Series.find_or_create_by(title: series_name) end def tempfile Tempfile.create(encoding: Encoding::ASCII_8BIT, &Proc.new) end end end end
package com.anqit.spanqit.graphpattern; import com.anqit.spanqit.core.QueryElementCollection; /** * A SPARQL Alternative Graph Pattern. * * @see <a * href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#alternatives"> * SPARQL Alternative Graph Patterns</a> */ class AlternativeGraphPattern extends QueryElementCollection<GroupGraphPattern> implements GraphPattern { private static final String UNION = "UNION"; private static final String DELIMETER = " " + UNION + " "; AlternativeGraphPattern() { super(DELIMETER); } AlternativeGraphPattern(GraphPattern original) { super(DELIMETER); if (original instanceof AlternativeGraphPattern) { copy((AlternativeGraphPattern) original); } else if (original != null && !original.isEmpty()) { elements.add(new GroupGraphPattern(original)); } } private void copy(AlternativeGraphPattern original) { this.elements = original.elements; } AlternativeGraphPattern union(GraphPattern... patterns) { for (GraphPattern pattern : patterns) { elements.add(new GroupGraphPattern(pattern)); } return this; } }
using System; using System.Security.Cryptography; using System.Text; namespace Hawk.Core.Utils { public class CMDHelper { public static string GetMD5Value(string password) { using (var md5 = new MD5CryptoServiceProvider()) { return BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password))); } } public static bool IsSame(string password1, string password2) { using (var md5 = new MD5CryptoServiceProvider()) { var str1 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password1))); var str2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password2))); return str1 == str2; } } #region Public Methods public static string Execute(string command) { var p = new System.Diagnostics.Process(); //设定程序名 p.StartInfo.FileName = "cmd.exe"; //关闭Shell的使用 p.StartInfo.UseShellExecute = false; //重定向标准输入 p.StartInfo.RedirectStandardInput = true; //重定向标准输出 p.StartInfo.RedirectStandardOutput = true; //重定向错误输出 p.StartInfo.RedirectStandardError = true; //设置不显示窗口 p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine(command); //这里就可以输入你自己的命令 var str= p.StandardOutput.ReadLine(); p.Close(); return str; } #endregion } }
using System; using System.Device.Gpio; using System.Device.I2c; using System.IO; using System.Threading; using System.Threading.Tasks; using Iot.Device.CharacterLcd; using Iot.Device.Pcx857x; using Iot.Device.Subscriptions.Abstractions; using Microsoft.Extensions.Configuration; namespace Iot.Device.Subscriptions.StopwatchExample { /// <summary> /// To test this program out, you will need the following: /// 1x Controller Board (RPI, Arduino, etc) /// 1~3x Buttons /// 1x LED Character Panel with standard I2C backpack /// /// Configuring which buttons are enabled, which pins to listen on, and which type of LCD controller to use /// Can all be configured via AppSettings.json, as well as the built in support for Environment Variables, /// Command line Args, and Project Secrets /// /// See AppSettings.json and Configuration.cs for more details on each config value /// </summary> class Program { static async Task Main(string[] args) { Console.WriteLine("Program Started"); var config = BuildConfiguration(args); using var stopwatch = Boilerplate(config); stopwatch.Lcd.DisplayOn = true; stopwatch.Lcd.Clear(); var subscriptionService = BuildSubscriptions(config); var clock = 0L; var buttonDelay = config.BtnSensitivityTicks; var paused = false; await foreach (var subEvent in subscriptionService.Run(stopwatch.Board, CancellationToken.None)) { buttonDelay += subEvent.Delta; if (subEvent.IsClock && !paused) { clock += subEvent.Delta; } if (subEvent.PinNumber == config.ResetBtnPin && buttonDelay > config.BtnSensitivityTicks) { clock = 0L; stopwatch.Lcd.Clear(); buttonDelay = 0L; } if (subEvent.PinNumber == config.PauseBtnPin && buttonDelay > config.BtnSensitivityTicks) { paused = !paused; stopwatch.Lcd.Clear(); buttonDelay = 0L; } if (subEvent.PinNumber == config.StopBtnPin && buttonDelay > config.BtnSensitivityTicks) { break; } stopwatch.Lcd.SetCursorPosition(0, 0); stopwatch.Lcd.Write($"{TimeSpan.FromTicks(clock):g}"); } stopwatch.Lcd.Clear(); stopwatch.Lcd.DisplayOn = false; Console.WriteLine("Program Ended"); } private static Configuration BuildConfiguration(string[] args) { return new ConfigurationBuilder() .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName) .AddEnvironmentVariables() .AddJsonFile("AppSettings.json", true) .AddUserSecrets<Program>(true) .AddCommandLine(args) .Build() .Get<Configuration>(); } private static StopwatchController Boilerplate(Configuration config) { var i2c = I2cDevice.Create(new I2cConnectionSettings(1, config.I2CBusIdInt)); Pcx857x.Pcx857x driver = config.I2CDriver switch { Pcx857xEnum.Pca8574 => new Pca8574(i2c), Pcx857xEnum.Pca8575 => new Pca8575(i2c), Pcx857xEnum.Pcf8574 => new Pcf8574(i2c), Pcx857xEnum.Pcf8575 => new Pcf8575(i2c), _ => throw new ArgumentOutOfRangeException() }; var lcdController = new GpioController(PinNumberingScheme.Logical, driver); Hd44780 lcd = config.LcdSize switch { LcdEnum.Lcd16x2 => new Lcd1602(0, 2, new[] { 4, 5, 6, 7 }, 3, 0.1f, 1, lcdController), LcdEnum.Lcd20x4 => new Lcd2004(0, 2, new[] { 4, 5, 6, 7 }, 3, 0.1f, 1, lcdController), _ => throw new ArgumentOutOfRangeException() }; var boardController = new GpioController(PinNumberingScheme.Board); return new StopwatchController(i2c, driver, lcdController, lcd, boardController); } private static ISubscriptionService BuildSubscriptions(Configuration config) { var collection = new SubscriptionCollection { ClockEnabled = true, ClockRate = config.ClockRate }; if (config.ResetBtnEnabled) { collection.Subscribe(config.ResetBtnPin, config.BtnPinMode, PinEventTypes.Rising); } if (config.PauseBtnEnabled) { collection.Subscribe(config.PauseBtnPin, config.BtnPinMode, PinEventTypes.Rising); } if (config.StopBtnEnabled) { collection.Subscribe(config.StopBtnPin, config.BtnPinMode, PinEventTypes.Rising); } return collection.Build(); } } }
<?php use yii\helpers\Html; use frontend\models\BlogPost; use frontend\models\BlogPostComments; use common\models\User; ?> <div class="comment"> <hgroup> <h5><?=$model['username']?></h5> <h6><?=$model['created_at']?></h6> </hgroup> <section> <?php if($model['image']){?><img src="<?=$model['image']?>"> <?php } ?> <p><?=$model['comment']?></p> </section> </div>
<?php namespace App\Jobs\Install; use App\Abstracts\Job; use App\Utilities\Console; class EnableModule extends Job { protected $alias; protected $company_id; protected $locale; /** * Create a new job instance. * * @param $alias * @param $company_id * @param $locale */ public function __construct($alias, $company_id, $locale = null) { $this->alias = $alias; $this->company_id = $company_id; $this->locale = $locale ?: app()->getLocale(); } /** * Execute the job. * * @return string */ public function handle() { $command = "module:enable {$this->alias} {$this->company_id} {$this->locale}"; $result = Console::run($command); if ($result !== true) { throw new \Exception($result); } } }
#!/bin/bash function get_oss_count() { local mount=${1-/beegfs} echo $(beegfs-ctl --listnodes --nodetype=storage --mount=$mount | wc -l) } function get_mdt_count() { local mount=${1-/beegfs} echo $(beegfs-ctl --listnodes --nodetype=metadata --mount=$mount | wc -l) }
--- title: Commission member Ralph Fossey who tags: - Mar 1960 --- Commission member Ralph Fossey, who owns property on Elliott Key, rejects the sale delay of submerged bay land. Newspapers: **Miami Morning News or The Miami Herald** Page: **10**, Section: **A**
# # Project:: Ansible Role - JumpCloud # # Copyright 2020, Route 1337, LLC, All Rights Reserved. # # Maintainers: # - Matthew Ahrenstein: matthew@route1337.com # # See LICENSE # # Prereqs tests if ['ubuntu', 'centos'].include?(os[:name]) # Verify the /opt/jc directory exists describe file('/opt/jc') do it { should be_directory } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } it { should be_mode 0700 } end # Verify the actual JumpCloud agent is installed via looking for the jcagent.conf describe file('/opt/jc/jcagent.conf') do it { should exist } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } it { should be_mode 0600 } end # Verify the JumpCloud Agent service is running and enabled describe service('jcagent') do it { should be_installed } it { should be_running } it { should be_enabled } end # Verify install script was removed describe file('/tmp/jcinstall.sh') do it { should_not exist } end else # Do nothing end
pub use logos::Span; pub struct Error { pub message: String, pub location: Option<Span>, } impl Error { pub fn new(message: String, location: Option<Span>) -> Error { Error { message, location } } }
<?php namespace common\tests\unit; use common\helpers\DateTimeHelper; use DateTime; class DateTimeMonthIntervalTest extends Unit { public const FORMAT = 'Y-m-d'; public function testFebrurary(): void { $this->tester->assertSame( '2019-02-28', DateTimeHelper::getSameDayNextMonth(new DateTime('2019-01-31')) ->format(static::FORMAT) ); $this->tester->assertSame( '2020-02-29', DateTimeHelper::getSameDayNextMonth(new DateTime('2020-01-31')) ->format(static::FORMAT) ); } }
package me.zouzhipeng; public interface CaptchaGenerator { /** * Generator captcha images automaticlly to destination. * @param folder the folder path to output * @return Successful or failed after created. */ @Deprecated public boolean generate(String folder); /** * Generator captcha images automaticlly to current workspace. * @return Successful or failed after created. */ public boolean generate(); }
using System; namespace pipe { public class RealEnvironmentVariableProvider : IEnvironmentVariableProvider { public string Get(string name) { return Environment.GetEnvironmentVariable(name); } } }
using System.Collections.Generic; namespace Benchmarking { public class ChartData { public string CurveLabel; public string YAxisLabel; public IList<ExperimentResult> Results; } }
using Autofac; using Autofac.Integration.WebApi; using PingYourPackage.API.Model.Dtos; using PingYourPackage.Domain.Entities; using PingYourPackage.Domain.Services; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace PingYourPackage.API.Test.Integration.Controllers { public class AuthControllerIntegrationTest { [Fact, NullCurrentPrincipal] public async Task Returns_200_And_Expected_User_For_The_Authed_User() { // Arrange var mockMemSrv = ServicesMockHelper .GetInitialMembershipServiceMock(); mockMemSrv.Setup(ms => ms.GetUser(Constants.ValidAffiliateUserName) ).Returns<string>( userName => new UserWithRoles { User = new User { Key = Guid.NewGuid(), Name = userName, Email = "foo@bar.com", IsLocked = false, CreatedOn = DateTime.Now.AddDays(-10), LastUpdatedOn = DateTime.Now.AddDays(-5) }, Roles = new List<Role> { new Role { Key = Guid.NewGuid(), Name = "Affiliate" } } } ); var config = IntegrationTestHelper .GetInitialIntegrationTestConfig( GetInitialServices(mockMemSrv.Object)); var request = HttpRequestMessageHelper .ConstructRequest( httpMethod: HttpMethod.Get, uri: string.Format( "https://localhost/{0}", "api/auth"), mediaType: "application/json", username: Constants.ValidAffiliateUserName, password: Constants.ValidAffiliatePassword); // Act var user = await IntegrationTestHelper.GetResponseMessageBodyAsync<UserDto>(config, request, HttpStatusCode.OK); // Assert Assert.Equal(Constants.ValidAffiliateUserName, user.Name); Assert.True(user.Roles.Any( role => role.Name.Equals( "Affiliate", StringComparison.OrdinalIgnoreCase ) ) ); } private static IContainer GetInitialServices( IMembershipService memSrv) { var builder = IntegrationTestHelper .GetEmptyContainerBuilder(); builder.Register(c => memSrv) .As<IMembershipService>() .InstancePerApiRequest(); return builder.Build(); } } }
namespace MeetingCaptureWebApp.Models { public class TaskViewModel { public string Title { get; set; } public string DueDate { get; set; } public string AssignedTo { get; set; } public bool Completed { get; set; } } }
Pull intel from curated feeds online, parse the results and put them into the mysql database.. To setup the db, run 'docker-compose up -d' Schema is auto loaded into DB itip. itip user is created with '#itip2017' as the default password, change this for production obviously.
import React, { useEffect, useState } from 'react'; import reducerRegistry from '@onaio/redux-reducer-registry'; import { Col, Row, Spin } from 'antd'; import { RouteComponentProps } from 'react-router'; import { Store } from 'redux'; import { connect } from 'react-redux'; import { KeycloakService } from '@opensrp/keycloak-service'; import { sendErrorNotification } from '@opensrp/notifications'; import { OpenSRPService } from '@opensrp/react-utils'; import { ROUTE_PARAM_USER_ID, KEYCLOAK_URL_USERS, OPENSRP_CREATE_PRACTITIONER_ENDPOINT, KEYCLOAK_URL_USER_GROUPS, } from '../../constants'; import lang from '../../lang'; import { reducer as keycloakUsersReducer, reducerName as keycloakUsersReducerName, fetchKeycloakUsers, makeKeycloakUsersSelector, KeycloakUser, UserGroup, Practitioner, } from '../../ducks/user'; import { Dictionary } from '@onaio/utils'; import { getExtraData } from '@onaio/session-reducer'; import '../../index.css'; import { FormFields, UserFormProps } from '../forms/UserForm/types'; import { defaultUserFormInitialValues, UserForm } from '../forms/UserForm'; import { getFormValues } from '../forms/UserForm/utils'; reducerRegistry.register(keycloakUsersReducerName, keycloakUsersReducer); /** inteface for route params */ export interface RouteParams { userId: string; } /** props for editing a user view */ export interface EditUserProps { keycloakUser: KeycloakUser | null; keycloakBaseURL: string; opensrpBaseURL: string; extraData: Dictionary; fetchKeycloakUsersCreator: typeof fetchKeycloakUsers; userFormHiddenFields?: UserFormProps['hiddenFields']; userFormRenderFields?: UserFormProps['renderFields']; } /** type intersection for all types that pertain to the props */ export type CreateEditPropTypes = EditUserProps & RouteComponentProps<RouteParams>; /** * * @param props - CreateEditUser component props */ const CreateEditUser: React.FC<CreateEditPropTypes> = (props: CreateEditPropTypes) => { const [userGroupsLoading, setUserGroupsLoading] = useState(false); const [keyCloakUserLoading, setKeyCloakUserLoading] = useState(false); const [userGroupLoading, setUserGroupLoading] = useState(false); const [practitionerLoading, setPractitionerLoading] = useState(false); const [userGroups, setUserGroups] = useState<UserGroup[]>([]); const [assignedUserGroups, setAssignedUserGroups] = useState<UserGroup[]>([]); const [initialValues, setInitialValues] = useState<FormFields>(defaultUserFormInitialValues); const [practitioner, setPractitioner] = useState<Practitioner>(); const { keycloakUser, keycloakBaseURL, opensrpBaseURL, extraData, fetchKeycloakUsersCreator, userFormHiddenFields, userFormRenderFields, } = props; const userId = props.match.params[ROUTE_PARAM_USER_ID]; useEffect(() => { if (!userGroups.length) { setUserGroupsLoading(true); const serve = new KeycloakService(KEYCLOAK_URL_USER_GROUPS, keycloakBaseURL); serve .list() .then((response: UserGroup[]) => setUserGroups(response)) .catch((_: Error) => sendErrorNotification(lang.ERROR_OCCURED)) .finally(() => setUserGroupsLoading(false)); } }, [keycloakBaseURL, opensrpBaseURL, userGroups.length]); /** * Fetch user if userId changes (editing a different user) */ useEffect(() => { if (userId) { setKeyCloakUserLoading(true); const serve = new KeycloakService(KEYCLOAK_URL_USERS, keycloakBaseURL); serve .read(userId) .then((response: KeycloakUser | null | undefined) => { if (response) fetchKeycloakUsersCreator([response]); }) .catch((_: Error) => sendErrorNotification(lang.ERROR_OCCURED)) .finally(() => setKeyCloakUserLoading(false)); } }, [userId, keycloakBaseURL, fetchKeycloakUsersCreator]); /** * Fetch User group of the user being edited */ useEffect(() => { if (userId) { setUserGroupLoading(true); const serve = new KeycloakService( KEYCLOAK_URL_USERS + '/' + userId + KEYCLOAK_URL_USER_GROUPS, keycloakBaseURL ); serve .list() .then((response: UserGroup[]) => setAssignedUserGroups(response)) .catch((_: Error) => sendErrorNotification(lang.ERROR_OCCURED)) .finally(() => setUserGroupLoading(false)); } }, [userId, keycloakBaseURL]); /** * Fetch practitioner data of the user being edited */ useEffect(() => { if (userId) { setPractitionerLoading(true); const serve = new OpenSRPService(OPENSRP_CREATE_PRACTITIONER_ENDPOINT, opensrpBaseURL); serve .read(userId) .then((response: Practitioner | undefined) => { setPractitioner(response); }) .catch((_: Error) => sendErrorNotification(lang.ERROR_OCCURED)) .finally(() => setPractitionerLoading(false)); } }, [userId, opensrpBaseURL]); useEffect(() => { setInitialValues(getFormValues(keycloakUser ?? undefined, practitioner, assignedUserGroups)); }, [keycloakUser, practitioner, assignedUserGroups]); if ( userGroupsLoading || keyCloakUserLoading || userGroupLoading || practitionerLoading || !(userGroups.length > 0) ) return <Spin size="large" />; return ( <Row> <Col span={24}> <UserForm initialValues={initialValues} keycloakBaseURL={keycloakBaseURL} opensrpBaseURL={opensrpBaseURL} userGroups={userGroups} extraData={extraData} hiddenFields={userFormHiddenFields} renderFields={userFormRenderFields} /> </Col> </Row> ); }; export { CreateEditUser }; /** Interface for connected state to props */ interface DispatchedProps { keycloakUser: KeycloakUser | null; extraData: Dictionary; } // connect to store const mapStateToProps = (state: Partial<Store>, ownProps: CreateEditPropTypes): DispatchedProps => { const userId = ownProps.match.params[ROUTE_PARAM_USER_ID]; let keycloakUser = null; if (userId) { const keycloakUsersSelector = makeKeycloakUsersSelector(); const keycloakUsers = keycloakUsersSelector(state, { id: [userId] }); keycloakUser = keycloakUsers.length === 1 ? keycloakUsers[0] : null; } const extraData = getExtraData(state); return { keycloakUser, extraData }; }; /** map props to actions that may be dispatched by component */ const mapDispatchToProps = { fetchKeycloakUsersCreator: fetchKeycloakUsers, }; export const ConnectedCreateEditUser = connect(mapStateToProps, mapDispatchToProps)(CreateEditUser);
# theroasties A website listing the best pubs in London to get a roast dinner, sub-divided by the four cardinal directions.
namespace UnleashedDDD.Sales.Domain.Model.Customers.State { public class CustomerState { } }
<?php /** * Dispatcher tests */ class DispatcherTest extends PHPUnit_Framework_TestCase { private $object; function setUp() { parent::setUp(); $this->object = new Dispatcher(new View()); $this->object->setBootstrap(new Bootstrap()); $this->object->setEventManager(new EventManager()); $this->object->setControllerPath(__DIR__ . '/controllers'); $router = new Router(); $this->object->setRouter($router); } public function testDispatchARoute() { $request = new Request("alone/an"); $this->object->setRequest($request); $route = $this->object->getRouter()->match($request); $content = $this->object->dispatch($route); $this->assertEquals("an-action", $content); } /** * @expectedException RuntimeException */ public function testDispatchAnError() { $request = new Request("/not/exists-this-action"); $this->object->setRequest($request); $route = $this->object->getRouter()->match($request); $this->object->dispatch($route); } public function testHeaderCodes() { $this->object->addHeader("content-type", "text/html", "202"); $headers = $this->object->getHeaders(); $this->assertCount(1, $headers); $this->assertSame(202, $headers[0]["code"]); } public function testSetGetHeaders() { $this->object->addHeader("content-type", "text/html"); $headers = $this->object->getHeaders(); $this->assertCount(1, $headers); $this->object->addHeader("content-disposition", "inline;"); $headers = $this->object->getHeaders(); $this->assertCount(2, $headers); $this->assertStringStartsWith("content-type", $headers[0]["string"]); $this->assertStringEndsWith("text/html", $headers[0]["string"]); $this->assertStringStartsWith("content-disposition", $headers[1]["string"]); $this->assertStringEndsWith("inline;", $headers[1]["string"]); } }
object DM: TDM OldCreateOrder = False OnCreate = DataModuleCreate OnDestroy = DataModuleDestroy Left = 297 Top = 203 Height = 228 Width = 270 object lstImage: TImageList Left = 24 Top = 24 Bitmap = { 494C010107000900040010001000FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600 0000000000003600000028000000400000003000000001002000000000000030 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000008080800000000000000000000000000000000000000000008080 8000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000080000000FF000000FF000000FF000000FF000000FF000000 8000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF0000800000FFFFFF00FFFFFF00FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000008000 0000000000000000000000000000000000000000000000000000000000000000 00000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000 FF000000FF000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF000080000000800000FFFFFF00FFFFFF00FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000008000 0000800000000000000000000000000000000000000000000000000000000000 FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000 FF000000FF000000FF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF000080000000800000008000000080000000800000FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000008000 0000800000008000000000000000000000000000000080808000000080000000 FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000 FF000000FF000000FF0000008000808080000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF000080000000800000FFFFFF00FFFFFF000080 0000FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000008000 00008000000080000000800000000000000000000000000000000000FF000000 FF000000FF00FFFFFF00FFFFFF000000FF000000FF000000FF00FFFFFF00FFFF FF000000FF000000FF000000FF00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF0000800000FFFFFF00FFFFFF000080 0000FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000008000 00008000000080000000000000000000000000000000000000000000FF000000 FF000000FF000000FF00FFFFFF00FFFFFF000000FF00FFFFFF00FFFFFF000000 FF000000FF000000FF000000FF00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF0000800000FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000080 0000FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000008000 00008000000000000000000000000000000000000000000000000000FF000000 FF000000FF000000FF000000FF00FFFFFF00FFFFFF00FFFFFF000000FF000000 FF000000FF000000FF000000FF00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF0000800000FFFFFF00FFFFFF0000800000FFFFFF00FFFFFF00FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000008000 00000000000000000000000000000000000000000000000000000000FF000000 FF000000FF000000FF000000FF00FFFFFF00FFFFFF00FFFFFF000000FF000000 FF000000FF000000FF000000FF00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF0000800000FFFFFF00FFFFFF000080000000800000FFFFFF00FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000800000000000 00000000000000000000000000000000000000000000000000000000FF000000 FF000000FF000000FF00FFFFFF00FFFFFF000000FF00FFFFFF00FFFFFF000000 FF000000FF000000FF000000FF00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF000080000000800000008000000080000000800000FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000080808000000080000000 FF000000FF00FFFFFF00FFFFFF000000FF000000FF000000FF00FFFFFF00FFFF FF000000FF000000FF0000008000808080000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000080000000800000FFFFFF00FFFF FF00FFFFFF00FFFFFF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000 FF000000FF000000FF0000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF0000800000FFFFFF00FFFFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 00000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000 FF000000FF000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000000 0000FFFFFF000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000080000000FF000000FF000000FF000000FF000000FF000000 8000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000FFFF FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000008080800000000000000000000000000000000000000000008080 8000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000008484840084848400848484008484 8400848484008484840084848400848484008484840084848400FFFFFF00C6C6 C60084848400C6C6C600FFFFFF00C6C6C6000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000008484840084848400848484008484 840084848400848484008484840084848400848484008484840084848400FFFF FF0084848400FFFFFF0084848400848484000000000000000000808080008080 8000808080008080800080808000808080008080800080808000808080008080 8000808080008080800080808000808080000000000000000000808080008080 8000808080008080800080808000808080008080800080808000808080008080 8000808080008080800080808000808080000000000000000000808080008080 8000808080008080800080808000808080008080800080808000808080008080 8000808080008080800080808000808080008400000084000000840000008400 00000000000000000000848484008484840084848400FFFFFF00FFFFFF00FFFF FF00840000008400000084000000840000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000808080000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000808080000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000808080000000000000000000000000008400 0000FF00000084000000000000000000000084848400FFFFFF00FFFFFF00FFFF FF00840000000000000000000000000000000000000000000000FFFFFF0000FF FF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00000000000000 0000FFFFFF0000FFFF0000000000808080000000000000000000FFFFFF0000FF FF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00000000000000 0000FFFFFF0000FFFF0000000000808080000000000000000000FFFFFF0000FF FF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00000000000000 0000FFFFFF0000FFFF0000000000808080000000000000000000000000008400 000084000000FF0000008400000000000000FFFFFF00FFFFFF00FFFFFF00FFFF FF0084000000000000000000000000000000000000000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF00000000000000 000000000000FFFFFF000000000080808000808080000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF00000000000000 000000000000FFFFFF000000000080808000000000000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF00000000000000 000000000000FFFFFF0000000000808080000000000000000000000000008400 0000FF00000084000000FF00000000000000FFFFFF00FFFFFF00FFFFFF00FFFF FF00840000000000000000000000000000000000000000000000FFFFFF0000FF FF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF000000000000FF FF00000000000000000000000000808080000000800000000000FFFFFF0000FF FF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF000000000000FF FF00000000000000000000000000808080000000000000000000FFFFFF000000 0000FFFFFF0000000000FFFFFF0000000000FFFFFF0000FFFF000000000000FF FF00000000000000000000000000808080000000000000000000000000008400 000084000000FF0000008400000000000000FFFFFF00FFFF0000FFFFFF00FFFF 000084000000000000000000000000000000000000000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF00000000000000 000000000000000000000000000080808000000080000000800000FFFF00FFFF FF0000FFFF00FFFFFF00808080000000800000FFFF00FFFFFF00000000000000 000000000000000000000000000080808000000000000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000FFFF000000000000000000FFFFFF00000000000000 0000000000000000000000000000808080000000000000000000000000008400 0000FF00000084000000FF00000000000000FFFF0000FFFFFF00FFFF0000FFFF FF0084000000000000000000000000000000FFFFFF0000000000FFFFFF008080 800000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF0000FFFF00FFFFFF0000FF FF00FFFFFF0000FFFF00000000008080800080808000000080008080800000FF FF00FFFFFF00808080000000800080808000FFFFFF0000FFFF00FFFFFF0000FF FF00FFFFFF0000FFFF0000000000808080000000000000000000FFFFFF0000FF FF00FFFFFF0000FFFF00FFFFFF000000000000FFFF0000000000FFFFFF0000FF FF00FFFFFF0000FFFF0000000000808080000000000000000000000000008400 000084000000FF0000008400000000000000FFFFFF00FFFF0000FFFFFF00FFFF 0000840000000000000000000000000000008080800000FFFF0000FFFF008080 8000FFFFFF0000FFFF008080800000FFFF00FFFFFF00FFFFFF0000FFFF00FFFF FF0000FFFF00FFFFFF0000000000808080000000000000008000000080008080 800000FFFF000000800000008000FFFFFF0000FFFF00FFFFFF0000FFFF00FFFF FF0000FFFF00FFFFFF000000000080808000000000000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000FFFF000000000000FFFF000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000000000808080000000000000000000000000008400 0000FF00000084000000FF00000000000000FFFF0000FFFFFF00FFFF0000FFFF FF00840000000000000000000000000000000000000080808000FFFFFF008080 800000FFFF008080800000FFFF00FFFFFF0000FFFF0000FFFF00FFFFFF0000FF FF00FFFFFF0000FFFF0000000000808080000000000080808000000080000000 80000000800000008000FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FF FF00FFFFFF0000FFFF0000000000808080000000000000000000FFFFFF0000FF FF00FFFFFF0000FFFF00FFFFFF000000000000FFFF0000FFFF000000000000FF FF00FFFFFF0000FFFF0000000000808080000000000000000000000000008400 0000840000008400000084000000840000008400000084000000840000008400 000084000000000000000000000000000000808080008080800080808000FFFF FF0080808000FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFF FF0000FFFF00FFFFFF0000000000808080000000000080808000000080000000 800000008000FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFF FF0000FFFF00FFFFFF000000000080808000000000000000000000FFFF00FFFF FF0000FFFF00FFFFFF0000FFFF000000000000FFFF0000FFFF0000000000FFFF FF0000FFFF00FFFFFF0000000000808080000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000FFFFFF0000FFFF008080800000FF FF00FFFFFF008080800080808000808080008080800000000000000000000000 0000000000000000000000000000000000008080800000008000000080000000 8000000080008080800000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000FFFF0000FFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000008080800000FFFF008080 800000FFFF008080800000FFFF00000000000000000000000000000000000000 0000000000000000000000000000000000000000800000008000808080000000 0000000080000000800080808000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000FFFF0000FFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000840000008400000084000000840000000000000000 0000000000000000000000000000000000008080800000FFFF00000000008080 8000FFFFFF00000000008080800000FFFF000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000800000008000808080000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000FFFF0000000000000000008080 800000FFFF000000000000000000808080000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000008000000080008080800000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000080000000 8000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000008080 8000FFFFFF000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000424D3E000000000000003E000000 2800000040000000300000000100010000000000800100000000000000000000 000000000000000000000000FFFFFF0000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000C001FFFFF80F0000C001FFDFF0070000 C001FFCFE0030000C001FFC7C0010000C001FFC380000000C001FFC180000000 C001FFC380000000C001FFC780000000C001FFCF80000000C001FFDF80000000 C001FFFF80000000C001FFFFC0010000C001FFFFE0030000C003FFFFF0070000 C007FFFFF80F0000C00FFFFFFFFF00000000FFFFFFFFFFFF0000C000C000C000 0000800080008000E007800080008000E007801000108010E007800800088008 E007800000008000E007000000008000E007000080008000E007800080008000 E007000080008000FFFF000100018001F81F81FF11FFFF0FF81F24FFF8FFFF87 F81F66FFFC7FFF87FFFFE7FFFFFFFFCF00000000000000000000000000000000 000000000000} end object lstAction: TActionList Images = lstImage Left = 80 Top = 24 object actTaskProp: TAction Category = 'Task' Caption = '&Properties' ImageIndex = 3 ShortCut = 16464 OnExecute = actTaskPropExecute OnUpdate = actTaskPropUpdate end object actTaskAdd: TAction Category = 'Task' Caption = '&Add' ImageIndex = 1 ShortCut = 16462 OnExecute = actTaskAddExecute end object actTaskDelete: TAction Category = 'Task' Caption = '&Delete' ImageIndex = 2 ShortCut = 16452 OnExecute = actTaskDeleteExecute OnUpdate = actTaskPropUpdate end object actTaskRefresh: TAction Category = 'Task' Caption = '&Refresh' ImageIndex = 4 ShortCut = 116 OnExecute = actTaskRefreshExecute end object actTaskRun: TAction Category = 'Task' Caption = '&Run' ImageIndex = 5 ShortCut = 116 OnExecute = actTaskRunExecute OnUpdate = actTaskRunUpdate end object actTaskStop: TAction Category = 'Task' Caption = '&Stop' ImageIndex = 6 ShortCut = 8308 OnExecute = actTaskStopExecute OnUpdate = actTaskStopUpdate end object actFileExit: TAction Category = 'File' Caption = 'E&xit' Hint = 'Exit|Quits the application' ImageIndex = 0 ShortCut = 32883 OnExecute = actFileExitExecute end end end
// // Created by Vetle Wegner Ingeberg on 22/04/2021. // #ifndef AFRODITE_SLOT_HH #define AFRODITE_SLOT_HH #include <Detectors/DetectorFactory.hh> class Slot { private: int detector_number; Detector::DetectorFactory *factory; public: // Construction of a slot is done by giving it a detector type and a distance Slot(const int &dnum = 0, Detector::DetectorFactory *factory = nullptr); // Build the detector in place void Assemble(); }; #endif //AFRODITE_SLOT_HH
package loci package transmitter import scala.language.experimental.macros import scala.reflect.macros.whitebox object DummyImplicit { class Resolvable private[DummyImplicit] object Resolvable { implicit def dummy: Resolvable = new Resolvable implicit def noDummy: Resolvable = macro NoDummyImplicit.skip } class Unresolvable private[DummyImplicit] object Unresolvable { implicit def noDummy: Unresolvable = macro NoDummyImplicit.skip } } object NoDummyImplicit { def skip(c: whitebox.Context): c.Tree = c.abort(c.enclosingPosition, "`noDummy` must not be called") }
import {loadScript} from './react-loader'; import './index.css'; (async function foo() { await loadScript('https://unpkg.com/react@15.6.1/dist/react.js'); await loadScript('https://unpkg.com/react-dom@15.6.1/dist/react-dom.js'); await loadScript( 'https://unpkg.com/react-dom@15.6.1/dist/react-dom-server.js' ); window.React15 = window.React; window.ReactDOM15 = window.ReactDOM; window.ReactDOMServer15 = window.ReactDOMServer; delete window.React; delete window.ReactDOM; delete window.ReactDOMServer; await loadScript('/react.development.js'); await loadScript('/react-dom.development.js'); await loadScript('/react-dom-server.browser.development.js'); const React = (window.React16 = window.React); const ReactDOM = (window.ReactDOM16 = window.ReactDOM); window.ReactDOMServer16 = window.ReactDOMServer; const App = await import('./App'); ReactDOM.render( React.createElement(App.default), document.getElementById('root') ); })();
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ plugins { id("otel.java-conventions") } dependencies { implementation("org.apache.groovy:groovy") }
import styled from "styled-components" import BuildButton from "./BuildButton" import { AnimDuration, Color, mixinResetButtonStyle, overviewItemBorderRadius, SizeUnit, } from "./style-helpers" export const SidebarBuildButton = styled(BuildButton)` ${mixinResetButtonStyle}; width: ${SizeUnit(1)}; height: ${SizeUnit(1)}; background-color: ${Color.gray40}; border-bottom-left-radius: ${overviewItemBorderRadius}; border-top-right-radius: ${overviewItemBorderRadius}; display: flex; align-items: center; flex-shrink: 0; justify-content: center; opacity: 0; pointer-events: none; &.is-building { display: none; } &.is-clickable { pointer-events: auto; cursor: pointer; } &.is-clickable, &.is-queued { opacity: 1; } &.is-selected { background-color: ${Color.gray70}; } &:hover { background-color: ${Color.gray20}; } &.is-selected:hover { background-color: ${Color.grayLightest}; } & .fillStd { transition: fill ${AnimDuration.default} ease; fill: ${Color.gray50}; } &.is-manual .fillStd { fill: ${Color.blue}; } &.is-selected .fillStd { fill: ${Color.black}; } &:hover .fillStd { fill: ${Color.white}; } &.is-selected:hover .fillStd { fill: ${Color.blueDark}; } & .icon { transition: transform ${AnimDuration.short} linear; width: ${SizeUnit(0.75)}; height: ${SizeUnit(0.75)}; } &:active > svg { transform: scale(1.2); } &.is-queued > svg { animation: spin 1s linear infinite; } &.stop-button button { min-width: 0; border: 0; padding: 0; } `
<?php if (!defined('BASEPATH')) { exit('No direct script access allowed.'); } class CKEditorConfig { protected static $config = array(); final private function __construct() {} final private function __clone() {} public static function get($editor_config_key = null, $editor_toolbar_key = null) { $editor_config_key = (string) $editor_config_key; $editor_toolbar_key = (string) $editor_toolbar_key; $editor_config_key = trim(preg_replace('/[^A-Za-z0-9_\-]/', '', $editor_config_key)); $editor_toolbar_key = trim(preg_replace('/[^A-Za-z0-9_\-]/', '', $editor_toolbar_key)); if ($editor_config_key == '') { $editor_config_key = 'default'; } $key = $editor_config_key; if ($editor_toolbar_key != '') { $key .= '_'.$editor_toolbar_key; } else { $editor_toolbar_key = $editor_config_key; } if (isset(self::$config[$key])) { return self::$config[$key]; } // Get editor's configuration. $ci = get_instance(); $config = array(); $ci->config->load('editor_default', true, true); $config_default = $ci->config->item('editor_default'); if (!is_array($config_default)) { $config_default = array(); } if ($editor_config_key != 'default') { $ci->config->load('editor_'.$editor_config_key, true, true); $config = $ci->config->item('editor_'.$editor_config_key); if (!is_array($config)) { $config = array(); } } $config = array_replace_recursive($config_default, $config); if (empty($config['config']['fullPage'])) { if (isset($config['config']['contentsCss'])) { if (!is_array($config['config']['contentsCss'])) { $config['config']['contentsCss'] = (array) $config['config']['contentsCss']; } } else { $config['config']['contentsCss'] = array(); } } self::$config[$key] = $config; // Get toolbar configuration. $ci->config->load('editor_toolbar_'.$editor_toolbar_key, true, true); $config = $ci->config->item('editor_toolbar_'.$editor_toolbar_key); if (!is_array($config)) { $config = array(); } self::$config[$key]['config']['toolbar'] = $editor_toolbar_key; self::$config[$key]['config']['toolbar_'.$editor_toolbar_key] = $config; return self::$config[$key]; } public static function set_read_only(& $config) { if (!is_array($config)) { return; } if (!isset($config['config']) || !is_array($config['config'])) { return; } $config['config']['readOnly'] = true; } }
class Task < ActiveRecord::Base belongs_to :project has_many :comments, dependent: :destroy acts_as_list scope: :project, top_of_list: 0, add_new_at: :top validates :name, presence: true, length: { maximum: 250 } end
#!/bin/bash uglifyjs about.js -m -o about.js uglifyjs footer.js -m -o footer.js uglifyjs home.js -m -o home.js uglifyjs index.js -m -o index.js uglifyjs islogin_admin.js -m -o islogin_admin.js uglifyjs islogin_blog.js -m -o islogin_blog.js uglifyjs islogin_editor.js -m -o islogin_editor.js uglifyjs islogin_home.js -m -o islogin_home.js uglifyjs islogin_tmpblog.js -m -o islogin_tmpblog.js uglifyjs islogin.js -m -o islogin.js uglifyjs login.js -m -o login.js uglifyjs md5.js -m -o md5.js uglifyjs myblog.js -m -o myblog.js uglifyjs search.js -m -o search.js uglifyjs show_tag.js -m -o show_tag.js uglifyjs showMenu.js -m -o showMenu.js uglifyjs submit.js -m -o submit.js uglifyjs to_log_reg_blog.js -m -o to_log_reg_blog.js uglifyjs to_log_reg.js -m -o to_log_reg.js uglifyjs xss.js -m -o xss.js
# List actions. get '/fieldforce/:consumer' do |consumer| erb :field_force, locals: { consumer: consumer } end get '/fieldforce/byId/:fieldworkerid' do |fieldworkerid| erb :field_worker, locals: { fieldworkerid: fieldworkerid } end # search example get '/fieldforce/surname/:surname' do |surname| erb :field_search, locals: { surname: surname } end
# Analysis of ecological distances in R Part of Pat's Code Club series that started 2021-12-06
#!/bin/sh sudo yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm STATUS=$(sudo systemctl status amazon-ssm-agent) if echo $STATUS | grep -q "running"; then echo "Install succeeded" else echo "Install failed" >&2 fi
import { createBaseEntity } from '../lib'; export interface TokenKey { token: string; } export interface TokenProps extends TokenKey { userId: string; } const BaseEntity = createBaseEntity('Token') .props<TokenProps>() .key<TokenKey>(key => `TOKEN:${key.token}`) .build(); export class TokenEntity extends BaseEntity {}
# frozen_string_literal: true # == Schema Information # # Table name: languages # # id :integer not null, primary key # abbreviation :string(255) # default_language :boolean # description :string(255) # name :string(255) # FactoryBot.define do factory :language do name { Faker::Language.unique.name } description { "Language for #{name}" } abbreviation { Faker::Language.unique.abbreviation } default_language { false } trait :with_dialect do abbreviation do pre = ('a'..'z').to_a.shuffle.take(2).join suf = ('A'..'Z').to_a.shuffle.take(2).join [pre, suf].join('_') end end end end
#!/bin/bash source ../spec.sh source ./module_spec.sh countbrokenmansymlinks() { LINKCOUNT="0" BROKENCOUNT="0" for SYMLINK in `find ${BDIR}/fsman/ -type l`; do LINKCOUNT=$(( LINKCOUNT + 1 )) if [ ! -e "${SYMLINK}" ]; then if [ "$1" == "PRINT" ]; then echo "BROKEN: ${SYMLINK}"; fi BROKENCOUNT=$(( BROKENCOUNT + 1 )) fi done echo "Links: ${LINKCOUNT} - Broken: ${BROKENCOUNT}" } fixbrokenmansymlinks() { for SYMLINK in `find ${BDIR}/fsman/ -type l -name "*.gz"`; do if [ ! -e "$SYMLINK" ]; then SOURCE=`ls -l ${SYMLINK} | awk '{print $9}' | sed 's@\.gz@@'` TARGET=`ls -l ${SYMLINK} | awk '{print $11}' | sed 's@\.gz@@'` #echo "Fixing ${SOURCE} -> ${TARGET} ..." rm "${SYMLINK}" ln -s "${TARGET}" "${SOURCE}" fi done } echo "Colocating man pages ..." find ${BDIR}/fsman/ -type f -name "*.gz" -exec gunzip {} \; countbrokenmansymlinks fixbrokenmansymlinks countbrokenmansymlinks PRINT dir2xzm ${BDIR}/fsman 020-man.xzm >/dev/null echo "Colocating documentation ..." find ${BDIR}/fsdoc/ -type f -name "*.gz" -exec gunzip {} \; dir2xzm ${BDIR}/fsdoc 021-doc.xzm >/dev/null if [ -e 003-interp.xzm ] && [ -d ${BDIR}/fspython ]; then echo "Colocating python code ..." rm 003-interp.xzm if [ "${INCPYTHONTWO}" != "Y" ]; then rm -rf ${BDIR}/fspython/usr/${LIBDIR}/python2.7 fi dir2xzm ${BDIR}/fspython 003-interp.xzm >/dev/null fi if [ -e 006-devel.xzm ] && [ -d ${BDIR}/fsdevel ]; then echo "Colocating dev headers ..." rm 006-devel.xzm dir2xzm ${BDIR}/fsdevel 006-devel.xzm >/dev/null fi rm -r ${BDIR}
# render basic data as a link # Used in UMM-S for URL::URLValue # :nodoc: class UmmPreviewLink < UmmPreviewElement def render title = 'Use Service API' if schema_type == 'service' && full_key == 'URL/URLValue' valid_url = validate_link_url(element_value) if valid_url link_to element_value, element_value, title: title else content_tag(:p, element_value) end end # Return nil if cannot be parsed as a URI or if URI does not have a protocol/ # scheme. def validate_link_url(url) begin url if URI.parse(url).scheme rescue URI::InvalidURIError nil end end end
/* * Copyright (c) 2010 Sony Pictures Imageworks Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. Neither the name of Sony Pictures Imageworks nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.imageworks.migration.tests.up_and_down import com.imageworks.migration.{ Cascade, CharacterSet, Check, Default, Limit, Migration, Name, NamedCheck, NotNull, Nullable, OnDelete, OnUpdate, Precision, PrimaryKey, Restrict, Scale, Unicode, Unique, VarbinaryType } class Migrate_20081118201742_CreatePeopleTable extends Migration { val tableName = "scala_migrations_people" def up() { createTable(tableName) { t => t.varbinary("pk_" + tableName, PrimaryKey, Limit(16)) t.varbinary("pk_scala_migrations_location", Limit(16), NotNull) t.integer("employee_id", Unique) t.integer("ssn", NotNull) t.varchar("first_name", Limit(255), NotNull, CharacterSet(Unicode, "utf8_unicode_ci")) t.char("middle_initial", Limit(1), Nullable) t.varchar("last_name", Limit(255), NotNull, CharacterSet(Unicode)) t.timestamp("birthdate", Limit(0), NotNull) t.smallint("height", NotNull, NamedCheck( "chk_height_nonnegative", "height > 0")) t.smallint("weight", NotNull, Check("weight > 0")) t.integer("vacation_days", NotNull, Default("0")) t.bigint("hire_time_micros", NotNull) t.decimal("salary", Precision(7), Scale(2), Check("salary > 0")) t.blob("image") } addIndex(tableName, "ssn", Unique) addForeignKey( on(tableName -> "pk_scala_migrations_location"), references("scala_migrations_location" -> "pk_scala_migrations_location"), OnDelete(Cascade), OnUpdate(Restrict), Name("fk_smp_pk_sml_sml_pk_sml")) if (!addingForeignKeyConstraintCreatesIndex) { addIndex( tableName, "pk_scala_migrations_location", Name("idx_smp_pk_sml")) } addColumn(tableName, "secret_key", VarbinaryType, Limit(16)) addCheck(on(tableName -> "vacation_days"), "vacation_days >= 0") } def down() { removeCheck(on(tableName -> "vacation_days")) removeForeignKey( on(tableName -> "pk_scala_migrations_location"), references("scala_migrations_location" -> "pk_scala_migrations_location"), Name("fk_smp_pk_sml_sml_pk_sml")) if (!addingForeignKeyConstraintCreatesIndex) { removeIndex( tableName, "pk_scala_migrations_location", Name("idx_smp_pk_sml")) } removeIndex(tableName, "ssn") removeColumn(tableName, "secret_key") dropTable(tableName) } }
#!/bin/sh sed -n '10p' file.txt # Alternative # awk 'NR==10' file.txt
package co.theasi.plotly case class Axis( options: AxisOptions ) object Axis { def apply(): Axis = Axis(AxisOptions()) }
<?php namespace app; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; class Borrows extends Model { public function borrowers() { return $this->hasOne('\App\Borrowers', 'id','borrower_id'); } public function book() { return $this->hasOne('\App\Books', 'id', 'book_id'); } public function status() { $today = Carbon::today(); $issued = Carbon::parse($this->created_at); $issue_interval = \DB::table('libraries')->get()->first()->issue_interval; $days_left = $issue_interval - $today->diffInDays($issued); if ($this->lost == 1){ return 'Lost'; } if ($this->cleared == true) { return 'Cleared'; } if ($days_left <= 0) { return 'Charging Fine'; } return $days_left.' Days Left'; } public function fine() { if ($this->status() != 'Charging Fine') { return 'Rs. 0'; } $today = Carbon::today(); $issued = Carbon::parse($this->created_at); $issue_interval = \DB::table('libraries')->get()->first()->issue_interval; $days_gone = $today->diffInDays($issued) - $issue_interval; $fine_amount = \DB::table('libraries')->get()->first()->fine_amount; $total_fine = $fine_amount * $days_gone; return 'RS. '.$total_fine; } }
# frozen_string_literal: true require 'test_helper' describe 'data' do around { |test| VCR.use_cassette('Parts', &test) } subject { WikiData::Fetcher.new(id: 'Q312894').data } it 'should know its ID' do subject[:id].must_equal 'Q312894' end it 'should know the name' do subject[:name].must_equal 'Juhan Parts' end it 'should cope with extended language names' do subject[:name__zh_hant].must_equal '尤漢·帕茨' end it 'should have a birth date' do subject[:birth_date].must_equal '1966-08-27' end end describe 'data preferences' do around { |test| VCR.use_cassette('Parts', &test) } subject { WikiData::Fetcher.new(id: 'Q312894').data(:be) } it 'can prefer Estonian' do data = WikiData::Fetcher.new(id: 'Q312894').data(%i[et be]) data[:name].must_equal 'Juhan Parts' end it 'can prefer Belarussian' do data = WikiData::Fetcher.new(id: 'Q312894').data(%i[be et]) data[:name].must_equal 'Юган Партс' end it 'can fall back on second preference' do data = WikiData::Fetcher.new(id: 'Q312894').data(%i[se be et]) data[:name__se].must_be_nil data[:name].must_equal 'Юган Партс' end it 'falls back on English if no suitable language' do data = WikiData::Fetcher.new(id: 'Q312894').data(%i[se si]) data[:name__se].must_be_nil data[:name__si].must_be_nil data[:name].must_equal 'Juhan Parts' end it 'can take a single string' do data = WikiData::Fetcher.new(id: 'Q312894').data('lv') data[:name].must_equal 'Juhans Partss' end it 'can take a single symbol' do data = WikiData::Fetcher.new(id: 'Q312894').data(:lv) data[:name].must_equal 'Juhans Partss' end end describe 'bracketed names' do around { |test| VCR.use_cassette('Picard', &test) } subject { WikiData::Fetcher.new(id: 'Q21178739').data } it 'should know its ID' do subject[:id].must_equal 'Q21178739' end it 'should strip brackets from names' do subject[:name].must_equal 'Michel Picard' end end describe 'non-English' do around { |test| VCR.use_cassette('Bierasniewa', &test) } subject { WikiData::Fetcher.new(id: 'Q14917860') } it 'should have a Polish name' do subject.data('pl')[:name].must_equal 'Alena Bierasniewa' end it 'should have no English name' do subject.data('en')[:name].must_be_nil end it 'can fetch multiple names' do data = subject.data('pl', 'by', 'en') data[:name__en].must_be_nil data[:name__by].must_be_nil data[:name].must_equal 'Alena Bierasniewa' end end describe 'Kadri Simpson' do around { |test| VCR.use_cassette('Simpson', &test) } subject { WikiData::Fetcher.new(id: 'Q13570003') } it 'should know a non-English name' do subject.data('et')[:name].must_equal 'Kadri Simson' end it 'can fetch multiple names' do data = subject.data(%w[en et]) data[:name__et].must_equal 'Kadri Simson' data[:name__en].must_equal 'Kadri Simson' data[:name].must_equal 'Kadri Simson' end it 'knows names in languages not asked for' do data = subject.data('en', 'et') data[:name__fi].must_equal 'Kadri Simson' end it 'knows multiple wikipedia pages' do data = subject.data(%i[en et]) data[:wikipedia__et].must_equal 'Kadri Simson' data[:wikipedia__en].must_equal 'Kadri Simson' end end describe 'broken' do around { |test| VCR.use_cassette('broken', &test) } subject { WikiData::Fetcher.new(id: 'Q264766') } # https://github.com/klacointe/wikidata-client/issues/13 it 'should have no birth date' do subject.data[:birth_name].must_be_nil end end describe 'odd instance' do around { |test| VCR.use_cassette('nonhuman', &test) } subject { WikiData::Fetcher.new(id: 'Q868585') } it 'should have nothing for non-human' do subject.data('fr').must_be_nil end end describe 'no claims' do around { |test| VCR.use_cassette('noclaims', &test) } subject { WikiData::Fetcher.new(id: 'Q20648365') } it 'should have a name, even if no claims' do subject.data[:name].must_equal 'Jeff Smith' end end describe 'by title' do around { |test| VCR.use_cassette('Rõivas', &test) } subject { WikiData::Fetcher.new(id: 'Q3785077') } it 'should fetch the correct person' do subject.data[:id].must_equal 'Q3785077' end it 'should have the birth date' do subject.data[:birth_date].must_equal '1979-09-26' end end describe 'partial date' do around { |test| VCR.use_cassette('Eesmaa', &test) } subject { WikiData::Fetcher.new(id: 'Q11857954') } it 'should have a short birth date' do subject.data[:birth_date].must_equal '1946' end end describe 'bracketed name' do around { |test| VCR.use_cassette('Eriksson', &test) } subject { WikiData::Fetcher.new(id: 'Q5715984') } it 'should have no brackets in name' do subject.data[:name__sv].must_equal 'Anders Eriksson' end end describe 'untranslated property' do around { |test| VCR.use_cassette('Lupu', &test) } it 'should receive a warning' do orig_err = $stderr $stderr = StringIO.new subject = WikiData::Fetcher.new(id: 'Q312340') subject.data[:name__en].must_equal 'Marian Lupu' $stderr.string.must_include 'Unknown value for P735 for Q312340' $stderr = orig_err end end
; ; Bondwell 2 graphics routines ; ; Stefano Bodrato 2021 ; SECTION code_graphics PUBLIC cleargraphics PUBLIC _cleargraphics PUBLIC clg PUBLIC _clg EXTERN generic_console_cls defc clg = _clg defc _clg = cleargraphics defc cleargraphics = _cleargraphics defc _cleargraphics = generic_console_cls
namespace Gma.QrCodeNet.Encoding.DataEncodation { public abstract class EncoderBase { internal EncoderBase() { } protected virtual int GetDataLength(string content) => content.Length; /// <summary> /// Returns the bit representation of input data. /// </summary> /// <param name="content"></param> /// <returns></returns> internal abstract BitList GetDataBits(string content); /// <summary> /// Returns bit representation of Modevalue. /// </summary> /// <returns></returns> /// <remarks>See Chapter 8.4 Data encodation, Table 2 — Mode indicators</remarks> internal BitList GetModeIndicator() { BitList modeIndicatorBits = new BitList { { (int)0001 << 2, 4 } }; return modeIndicatorBits; } /// <summary> /// /// </summary> /// <param name="characterCount"></param> /// <returns></returns> internal BitList GetCharCountIndicator(int characterCount, int version) { BitList characterCountBits = new BitList(); int bitCount = GetBitCountInCharCountIndicator(version); characterCountBits.Add(characterCount, bitCount); return characterCountBits; } /// <summary> /// Defines the length of the Character Count Indicator, /// which varies according to themode and the symbol version in use /// </summary> /// <returns>Number of bits in Character Count Indicator.</returns> /// <remarks> /// See Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator. /// </remarks> protected abstract int GetBitCountInCharCountIndicator(int version); } }
require 'app_helper' describe 'offender contact list method' do let(:url){ "offenders/#{offender_id}/visits/contact_list" } let(:offender_id){ ENV['NOMIS_API_OFFENDER_ID'] } let(:params){ {} } # Bomb out if no offender_id is given - we need to know a valid # identifier for lots of methods, and there is no way of retrieving # one without knowing more corroborating details (by design) it 'has the required environment variables set' do expect(offender_id).to_not be_nil, "You must supply a valid NOMIS_API_OFFENDER_ID environment variable" end describe 'the response' do let(:response){ NOMIS::API::Get.new(path: url, params: params).execute } describe 'status' do it 'should be 200' do expect( response.status ).to eq("200") end end it 'has no error key' do expect( response.data.keys ).to_not include('error') end describe 'returned data' do let(:data){ response.data } it 'has a contacts key' do expect(data.keys).to include('contacts') end describe 'the contacts key' do it 'is an array' do expect(data['contacts']).to be_a(Array) end end end end end
package lai.ast; public class LaiStatementSetVar extends LaiStatement { public LaiVariable var; public LaiExpression exp; public LaiStatementSetVar(LaiVariable var, LaiExpression exp) { this.var = var; this.exp = exp; this.node_children.add(var); this.node_children.add(exp); } @Override protected String getDebugName() { return "<SetVar>"; } @Override public void resetNodeReferences() { node_children.clear(); this.node_children.add(var); this.node_children.add(exp); } }
--- path: react-custom-hooks-for-later-use date: 2021-04-02T11:06:05.698Z title: React custom hooks for later use description: A place to keep all my custom hooks --- ![](../assets/hooks.png) # Table * [useScroll](#useScroll) * [useWindowSize](#useWindowSize) * [useScreen](#useScreen) * [useStateWithSessionStorage](#useStateWithSessionStorage) ## useScroll <a name="useScroll"></a> Return current user's scroll position and direction. ```tsx import { useState, useEffect } from "react"; type StateType = { lastScrollTop: number; bodyOffset: DOMRect; scrollY: number; scrollX: number; scrollDirection: "down" | "up" | ""; }; export const useScroll = () => { const [state, setState] = useState<StateType>({ lastScrollTop: 0, bodyOffset: document.body.getBoundingClientRect(), scrollY: document.body.getBoundingClientRect().top, scrollX: document.body.getBoundingClientRect().left, scrollDirection: "", }); useEffect(() => { const handleScroll = () => { setState((prevState) => { const prevLastScrollTop = prevState.lastScrollTop; const bodyOffset = document.body.getBoundingClientRect(); return { bodyOffset, scrollY: -bodyOffset.top, scrollX: bodyOffset.left, scrollDirection: prevLastScrollTop > -bodyOffset.top ? "up" : "down", lastScrollTop: -bodyOffset.top, }; }); }; window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll); }, []); return { scrollY: state.scrollY, scrollX: state.scrollX, scrollDirection: state.scrollDirection, }; }; export default useScroll; ``` ## useWindowSize <a name="useWindowSize"></a> Return current user's browser window size. ```tsx import { useState, useEffect } from "react"; type WindowSizeType = { width: number; height: number; }; const useWindowSize = () => { const [windowSize, setWindowSize] = useState<WindowSizeType>({ width: 0, height: 0, }); useEffect(() => { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); }; handleResize(); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return windowSize; }; export default useWindowSize; ``` ## useScreen <a name="useScreen"></a> An extension of \`useWindowSize()\` hook, this one returns which screen size user is in. ```tsx import { useEffect, useState } from "react"; import { useTheme } from "styled-components"; import useWindowSize from "./useWindowSize"; type ScreenType = { isSmall: boolean; isMedium: boolean; isLarge: boolean; }; const parseSize = (breakpoint: string): number => { return parseInt(breakpoint.replace("px", "")); }; const useScreen = () => { const theme = useTheme(); const { width } = useWindowSize(); const [screen, setScreen] = useState<ScreenType>({ isSmall: false, isMedium: false, isLarge: false, }); useEffect(() => { if (width < parseSize(theme.breakpoint.sm)) { setScreen({ isSmall: true, isMedium: false, isLarge: false, }); } else if (width < parseSize(theme.breakpoint.md)) { setScreen({ isSmall: false, isMedium: true, isLarge: false, }); } else { setScreen({ isSmall: false, isMedium: false, isLarge: true, }); } }, [width, theme]); return screen; }; export default useScreen; ``` ## useStateWithSessionStorage <a name="useStateWithSessionStorage"></a> Use state to get and set Session Storage values. ```tsx const useStateWithSessionStorage = (sessionStorageKey: string) => { const [value, setValue] = useState<string>( sessionStorage.getItem(sessionStorageKey) || "" ); useEffect(() => { sessionStorage.setItem(sessionStorageKey, value); }, [value, sessionStorageKey]); return [value, setValue] as const; }; export default useStateWithSessionStorage; ``` ### ...to be update
import PyPlot: subplots type VStyle fill::Union{RGB, Void} function VStyle(;fill=nothing) new(fill) end end style2mplkw(s::VStyle) = Dict(:fill => s.fill) ##Note: Mathematica and Matplotlib don't have nested scopes for the viewports, you can lay ## them over each other, but not inside one another. I am going to go this route, the ## full nested version is too complex, and I am not sure it buys me much. type Viewport # a Viewport is not a grob, and therefore can't contain another Viewport grobs::Array{Grob} # to start I only support npc coordinates for viewports, this needs to change so I can # have inheritence for sub-viewports xy::Array{Float64} width::Float64 height::Float64 clip::Symbol style::VStyle # should likely be a special viewport style # justification # xscale # yscale # angle # layout # layout.pos.row # layout.pos.col # name # I think I should use id like SVG function Viewport(grobs; xy=[0.0, 0.0], width=1.0, height=1.0, clip=:on, style=VStyle()) new(grobs, xy, width, height, clip, style) end end # a Viewport needs to know the Canvas it is in, so the render has an extra argument, # I think I might need to change the name of render, to something more descriptive function render!(f, v::Viewport) ax = f.add_axes(v.xy[1], v.xy[2], v.xy[1] + width, v.xy[2] + height) _addgrob2mpl!(ax, v.grobs) return nothing end #TODO: need to allow for changes to attributes, but not yet sure what the api shoudl be Base.push!(vp::Viewport, grob::Grob) = push!(vp.grobs, grob) type Canvas grobs::Array{Grob} style::Style function Canvas(grobs; style=Style(fill=NC"white")) new(grobs, style) end # function Canvas(vps::Array{Viewport}; style=Style(fill=NC"white")) # new(vps) # end end function _addgrob2mpl!(ax, grobs::Array{Grob}) for g in grobs p = render(g) # assume that we have either lines or patches if pyisinstance(p, mlines.Line2D) ax[:add_line](p) else ax[:add_patch](p) end end return nothing end function render(go::Canvas) # using collections removes all styling, style must be passed into the PatchCollection # patches = [] # for g in go.grobs # push!(patches, render(g)) # end #pcol = mcol.PatchCollection(patches) (fig, ax) = subplots() _addgrob2mpl!(ax, go.grobs) # apply style to axes ax[:patch][:set_facecolor](go.style.fill) ax[:relim]() # resize the axes limits ax[:autoscale_view]() # make sure everyting is visable ax[:set_aspect]("equal") # TODO: make this an option return fig end ##TODO: not really sure this is a container, and not just a style, but it is an attribute # of an AxesView type Spine # this needs to deal with inward/outward styles as well as special "center", or # the different coordinate locations position::Vector{Float64} #bounds #visible::Bool # do I want this, is there a more consistent way to have this on/off #style::Style end type Spines top::Spine bottom::Spine left::Spine right::Spine end type AxesTicks end type Axes spines::Spines #ticks::AxesTicks #labels end type AxesView grobs::Array{Grob} axes::Axes style::Style end
# frozen_string_literal: true module GraphQL module Client module Query class MutationDocument def self.new(schema, name = nil) document = Document.new(schema) mutation = document.add_mutation(name) if block_given? yield mutation end mutation end end end end end
#!/bin/bash # removes a layer which just has baddies SEARCH_STRING="collision_mask = 5" function remove_collision_mask { for file in $(ls $dir) do if [[ "$file" == *tscn ]]; then echo "removing collision mask for ::: '$file' "; sed -i '' 's/collision_mask = 5//g' $file else echo "not a correct file"; fi done }
'use strict'; const asyncTag = (m => /* c8 ignore start */ m.__esModule ? m.default : m /* c8 ignore stop */)(require('async-tag')); const {render: $render, html: $html, svg: $svg} = require('./index.js'); const tag = original => { const tag = asyncTag(original); tag.node = tag; tag.for = () => tag; return tag; }; const html = tag($html); exports.html = html; const svg = tag($svg); exports.svg = svg; const render = (where, what) => { const hole = typeof what === 'function' ? what() : what; return Promise.resolve(hole).then(what => $render(where, what)); }; exports.render = render; (m => { exports.Hole = m.Hole; })(require('./utils.js'));
export 'forms/form_input_field_with_icon.dart'; export 'forms/form_input_field.dart'; export 'forms/form_vertical_spacing.dart'; export 'widgets/primary_button.dart'; export 'widgets/line_button.dart'; export 'widgets/logo_graphic_header.dart'; export 'widgets/dropdown_picker.dart'; export 'widgets/dropdown_picker_with_icon.dart'; export 'widgets/avatar.dart'; export 'widgets/loading.dart'; export 'data_list.dart';
package dk.alexandra.fresco.tools.bitTriples; import dk.alexandra.fresco.tools.bitTriples.elements.MultiplicationTriple; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import org.junit.Assert; import org.junit.Test; public class BitTripleTest extends NetworkedTest{ private List<MultiplicationTriple> runBitTriple(BitTriplesTestContext ctx){ BitTriple bitTriple = new BitTriple( ctx.getResourcePool(), ctx.getNetwork(), ctx.getResourcePool().getLocalSampler().getNext(ctx.getComputationalSecurityBitParameter()), ctx.getResourcePool().getLocalSampler().getNext(ctx.getComputationalSecurityBitParameter())); return bitTriple.getTriples(1024); } private List<MultiplicationTriple> runBitTripleRealisticParameters(BitTriplesTestContext ctx){ BitTriple bitTriple = new BitTriple( ctx.getResourcePool(), ctx.getNetwork(), ctx.getResourcePool().getLocalSampler().getNext(ctx.getComputationalSecurityBitParameter()), ctx.getResourcePool().getLocalSampler().getNext(ctx.getComputationalSecurityBitParameter())); return bitTriple.getTriples(1024); } @Test public void getTriplesTwoParties() { initContexts(2); List<Callable<List<MultiplicationTriple>>> tasks = new ArrayList<>(); tasks.add(() -> runBitTriple(contexts.get(1))); tasks.add(() -> runBitTriple(contexts.get(2))); testRuntime.runPerPartyTasks(tasks); } @Test public void getTriplesTwoPartiesRealisticParameters() { initContexts(2, new BitTripleSecurityParameters()); List<Callable<List<MultiplicationTriple>>> tasks = new ArrayList<>(); tasks.add(() -> runBitTriple(contexts.get(1))); tasks.add(() -> runBitTriple(contexts.get(2))); testRuntime.runPerPartyTasks(tasks); } @Test public void getTriplesThreeParties() { initContexts(3); List<Callable<List<MultiplicationTriple>>> tasks = new ArrayList<>(); tasks.add(() -> runBitTriple(contexts.get(1))); tasks.add(() -> runBitTriple(contexts.get(2))); tasks.add(() -> runBitTriple(contexts.get(3))); testRuntime.runPerPartyTasks(tasks); } @Test public void testTriplesToCreate() { Assert.assertEquals(163,BitTriple.triplesToCreate(50,40)); Assert.assertEquals(2047,BitTriple.triplesToCreate(200,40)); Assert.assertEquals(16389,BitTriple.triplesToCreate(3000,40)); Assert.assertEquals(233016,BitTriple.triplesToCreate(18000,40)); Assert.assertEquals(1864191,BitTriple.triplesToCreate(400000,40)); Assert.assertEquals(63,BitTriple.triplesToCreate(50,64)); Assert.assertEquals(511,BitTriple.triplesToCreate(200,64)); Assert.assertEquals(7281,BitTriple.triplesToCreate(3000,64)); Assert.assertEquals(83885,BitTriple.triplesToCreate(18000,64)); Assert.assertEquals(671088,BitTriple.triplesToCreate(400000,64)); Assert.assertEquals(5368708,BitTriple.triplesToCreate(1000000,64)); } @Test(expected = IllegalArgumentException.class) public void testTriplesToCreateTooLarge40(){ BitTriple.triplesToCreate(1864192,40); } @Test(expected = IllegalArgumentException.class) public void testTriplesToCreateTooLarge64(){ BitTriple.triplesToCreate(5368709,64); } }
module FullCircle class API attr_reader :connection def initialize(connection, response_parser: ResponseParser.new, results_per_page: 20) @connection=connection @response_parser = response_parser @results_per_page = results_per_page end def fetch_events_for_ad(id,params={}) request_params = {page: 1, resultsPerPage: results_per_page, adId: id}.merge(params) response_xml = connection.call_api_method("ad.getEvents", request_params) response_parser.parse(response_xml) end def fetch_coupons_for_ad(id,params={}) request_params = {page: 1, resultsPerPage: results_per_page, adId: id}.merge(params) response_xml = connection.call_api_method("ad.getCoupons", request_params) response_parser.parse(response_xml) end def fetch_jobs_for_ad(id,params={}) request_params = {page: 1, resultsPerPage: results_per_page, adId: id}.merge(params) response_xml = connection.call_api_method("ad.getJobs", request_params) response_parser.parse(response_xml) end def fetch_event_areas(params={}) request_params = {page: 1, resultsPerPage: results_per_page}.merge(params) response_xml = connection.call_api_method("city.getEventAreas", request_params) response_parser.parse(response_xml) end def fetch_upcoming_events(params={}) request_params = {page: 1, resultsPerPage: results_per_page}.merge(params) response_xml = connection.call_api_method("city.getUpcomingEvents", params) response_parser.parse(response_xml, entity_builder: Builders::UpcomingEventBuilder) end def fetch_ads(params={}) request_params = {page: 1, resultsPerPage: results_per_page}.merge(params) response_xml = connection.call_api_method("ad.getList", params) response_parser.parse(response_xml) end private attr_reader :response_parser, :results_per_page end end
! { dg-do run } ! PR41192 NAMELIST input with just a comment ("&NAME ! comment \") error program cmdline ! comment by itself causes error in gfortran call process(' ') call process('i=10 , j=20 k=30 ! change all three values') call process(' ') call process('! change no values')! before patch this failed. end program cmdline subroutine process(string) implicit none character(len=*) :: string character(len=132) :: lines(3) character(len=255) :: message integer :: i=1,j=2,k=3 integer ios namelist /cmd/ i,j,k lines(1)='&cmd' lines(2)=string lines(3)='/' read(lines,nml=cmd,iostat=ios,iomsg=message) if (ios.ne.0) call abort end subroutine process
(ns lucid.distribute.util.sort) (defn all-branch-nodes "returns all nodes in the branche (all-branch-nodes MANIFEST) => ({:coordinate [blah/blah.common \"0.1.0-SNAPSHOT\"], :dependencies [[org.clojure/clojure \"1.6.0\"]], :id \"common\"} ... {:coordinate [blah/blah.resources \"0.1.0-SNAPSHOT\"], :dependencies [[org.clojure/clojure \"1.6.0\"]], :id \"resources\"})" {:added "1.2"} [manifest] (->> (:branches manifest) (map (fn [[k m]] (-> m (select-keys [:coordinate :dependencies]) (assoc :id k)))))) (defn all-branch-deps "returns all internal dependencies (all-branch-deps MANIFEST) => #{[blah/blah.util.data \"0.1.0-SNAPSHOT\"] [blah/blah.util.array \"0.1.0-SNAPSHOT\"] [blah/blah.resources \"0.1.0-SNAPSHOT\"] [blah/blah.web \"0.1.0-SNAPSHOT\"] [blah/blah.core \"0.1.0-SNAPSHOT\"] [blah/blah.common \"0.1.0-SNAPSHOT\"] [blah/blah.jvm \"0.1.0-SNAPSHOT\"]}" {:added "1.2"} [manifest] (->> (:branches manifest) (map (fn [[k m]] (:coordinate m))) (set))) (defn topsort-branch-deps-pass "single topsort pass" {:added "1.2"} [all sl] (reduce (fn [out i] (if (some all (:dependencies i)) out (conj out i))) [] sl)) (defn topsort-branch-deps "sorts and arranges dependencies in order of deployment (topsort-branch-deps MANIFEST) => [[{:coordinate [blah/blah.common \"0.1.0-SNAPSHOT\"], :dependencies [[org.clojure/clojure \"1.6.0\"]], :id \"common\"} ... {:coordinate [blah/blah.web \"0.1.0-SNAPSHOT\"], :dependencies [[org.clojure/clojure \"1.6.0\"] [blah/blah.core \"0.1.0-SNAPSHOT\"] [blah/blah.util.array \"0.1.0-SNAPSHOT\"] [blah/blah.common \"0.1.0-SNAPSHOT\"]], :id \"web\"}]]" {:added "1.2"} [manifest] (let [sl (all-branch-nodes manifest) all (all-branch-deps manifest)] (loop [all all sl sl output []] (if-not (or (empty? sl) (empty? all)) (let [pass (topsort-branch-deps-pass all sl)] (recur (apply disj all (map :coordinate pass)) (filter (fn [x] (some #(not= x %) pass) ) sl) (conj output pass))) output))))
import argparse import logging import sys from typing import List from lxml import etree from lxml import html # type: ignore import pyperclip # type: ignore import requests from .exceptions import DownloadError, NoFileExistsError from .query import DblpQuery def download(url: str, logger: logging.Logger) -> str: try: logger.info("Sending a request: " + url) r = requests.get(url) r.raise_for_status() return r.text except requests.exceptions.HTTPError as e: raise DownloadError(url, f"{e.response.status_code} {e.response.reason}") except requests.exceptions.ConnectionError: raise DownloadError(url, "Connection Error") except requests.exceptions.Timeout: raise DownloadError(url, "Timeout") except requests.exceptions.TooManyRedirects: raise DownloadError(url, "Too many redirects") def download_article_entries(url: str, logger: logging.Logger) -> List[etree._Element]: root: etree._Element = etree.fromstring( download(url, logger).encode('utf-8')) return root.xpath("/result/hits/hit") def download_bib_text(url: str, logger: logging.Logger) -> str: root = html.fromstring(download(url, logger)) return root.xpath("//*[@id=\"bibtex-section\"]/pre[1]")[0].text def format_article_entry(entry: etree._Element) -> str: title = entry.xpath("info/title")[0].text venue = entry.xpath("info/venue")[0].text return title + " in " + venue def get_bib_page_url(entry: etree._Element) -> str: return entry.xpath("info/url")[0].text.replace("rec", "rec/bibtex", 1) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Copy bibtex entry from DBLP") parser.add_argument("-f", "--file", action="store_true", help="interpret query as file path") parser.add_argument("-i", "--info", action="store_true", help="display verbose information") parser.add_argument("-n", "--number", type=int, default=5, help="limit of number of results") parser.add_argument("query", type=str) refine_group = parser.add_argument_group(title="Refine list") refine_group.add_argument("-a", "--author", action="append") refine_group.add_argument("-y", "--year", type=int) refine_group.add_argument("-v", "--venue", type=str) type_group = refine_group.add_mutually_exclusive_group() type_group.add_argument("-c", "--conf", action="store_true", help="Conference and Workshop Papers") type_group.add_argument("-j", "--journal", action="store_true", help="Journal Articles") return parser def _main() -> int: logger: logging.Logger = logging.getLogger(__name__) handler: logging.Handler = logging.StreamHandler(stream=sys.stdout) formatter: logging.Formatter = logging.Formatter() # flake8: noqa handler.setFormatter(formatter) logger.addHandler(handler) parser: argparse.ArgumentParser = build_parser() args: argparse.Namespace = parser.parse_args() if args.info: logger.setLevel(logging.INFO) handler.setLevel(logging.INFO) try: query: DblpQuery = DblpQuery(args, logger) except NoFileExistsError as e: sys.stderr.write("No such file: " + e.path) return 1 if query.title is None: print("No title info: " + args.query) return 0 logger.info("Building a query: " + str(query)) try: article_entries: List[etree._Element] = download_article_entries(query.url, logger) except DownloadError as e: sys.stderr.write(str(e)) return 1 entries_len = len(article_entries) if entries_len == 0: print("No matches: " + str(query)) return 0 entry_num_limit = args.number selected_index = 0 if entries_len > 1: print("\nMultiple results:\n") for i in range(min(entry_num_limit, entries_len)): print(f"({str(i)}) {format_article_entry(article_entries[i])}") if entries_len > entry_num_limit: print("and more omitted results...") while True: print("\nInput an entry index (Ctrl-D to exit):") try: s = input("> ") except EOFError: return 1 try: i = int(s) except ValueError: continue if i < 0 or i >= min(entry_num_limit, entries_len): continue selected_index = i break bib_page_url: str = get_bib_page_url(article_entries[selected_index]) try: bibtext: str = download_bib_text(bib_page_url, logger) except DownloadError as e: sys.stderr.write(str(e)) return 1 print(bibtext) pyperclip.copy(bibtext) return 0
use bevy::prelude::*; use bevy_inspector_egui::Inspectable; const MAX_ANGULAR_VELOCITY: f32 = 30.0; #[derive(Component, Inspectable)] pub struct Body { pub linear_velocity: Vec3, pub angular_velocity: Vec3, #[inspectable(min = 0.0, max = 1.0)] pub elasticity: f32, pub friction: f32, pub mass: Mass, // will be set by collider pub inv_mass: f32, pub center_of_mass: Vec3, pub inertia_tensor: Mat3, pub inverse_inertia_tensor_local: Mat3, // set each frame pub center_of_mass_world: Vec3, pub inverse_inertia_tensor_world: Mat3, } impl Default for Body { fn default() -> Self { Body { linear_velocity: Vec3::default(), angular_velocity: Vec3::default(), elasticity: 1.0, friction: 0.5, mass: Mass::Static, inv_mass: 0.0, center_of_mass: Vec3::ZERO, center_of_mass_world: Vec3::ZERO, inertia_tensor: Mat3::IDENTITY, inverse_inertia_tensor_local: Mat3::IDENTITY, inverse_inertia_tensor_world: Mat3::IDENTITY, } } } impl Body { pub fn center_of_mass_world(&self, t: &GlobalTransform) -> Vec3 { t.translation + t.rotation * self.center_of_mass } pub fn world_to_local(&self, t: &GlobalTransform, world_point: Vec3) -> Vec3 { let tmp = world_point - self.center_of_mass_world; let inv_orientation = t.rotation.conjugate(); inv_orientation * tmp } pub fn apply_impulse_linear(&mut self, impulse: Vec3) { if self.inv_mass == 0.0 { return; } self.linear_velocity += impulse * self.inv_mass; } pub fn apply_impulse_angular(&mut self, impulse: Vec3) { if self.inv_mass == 0.0 { return; } self.angular_velocity += self.inverse_inertia_tensor_world * impulse; // clamp angular velocity if self.angular_velocity.length_squared() > MAX_ANGULAR_VELOCITY * MAX_ANGULAR_VELOCITY { self.angular_velocity = self.angular_velocity.normalize() * MAX_ANGULAR_VELOCITY; } } pub fn apply_impulse(&mut self, impulse_point: Vec3, impulse: Vec3) { if self.inv_mass == 0.0 { return; } // impulse_point is in world space location of the applied impulse // impulse is in world space direction and magnitude of the impulse self.apply_impulse_linear(impulse); // applying impluses must produce torgues though the center of mass let r = impulse_point - self.center_of_mass_world; let dl = r.cross(impulse); // this is in world space self.apply_impulse_angular(dl); } pub fn update(&mut self, transform: &mut GlobalTransform, dt: f32) { // apply linear velocity transform.translation += self.linear_velocity * dt; // we have an angular velocity around the centre of mass, this needs to be converted to // relative body translation. This way we can properly update the rotation of the model let position_com = self.center_of_mass_world; let com_to_position = transform.translation - position_com; // total torque is equal to external applied torques + internal torque (precession) // T = T_external + omega x I * omega // T_external = 0 because it was applied in the collision response function // T = Ia = w x I * w // a = I^-1 (w x I * w) let orientation = Mat3::from_quat(transform.rotation); let inertia_tensor = orientation * self.inertia_tensor * orientation.transpose(); let alpha = inertia_tensor.inverse() * (self .angular_velocity .cross(inertia_tensor * self.angular_velocity)); self.angular_velocity += alpha * dt; // update orientation let d_angle = self.angular_velocity * dt; let angle = d_angle.length(); let inv_angle = angle.recip(); let dq = if inv_angle.is_finite() { Quat::from_axis_angle(d_angle * inv_angle, angle) } else { Quat::IDENTITY }; transform.rotation = (dq * transform.rotation).normalize(); // now get the new body position transform.translation = position_com + dq * com_to_position; // update center of mass and inverse inertia tensor self.center_of_mass_world = transform.translation + transform.rotation * self.center_of_mass; let orientation = Mat3::from_quat(transform.rotation); self.inverse_inertia_tensor_world = orientation * self.inverse_inertia_tensor_local * orientation.transpose(); } } #[derive(Component, Inspectable)] pub enum Mass { Static, Value(f32), }
// +build linux package main import ( "fmt" "log" "os" "github.com/google/gopacket/pcap" ) func (p *packiffer) setInterfaceFriendlyName() { } func displayFriendlyInterfaceName() { devices, err := pcap.FindAllDevs() if err != nil { log.Fatal(err) } displayDevices(devices) os.Exit(0) } func displayDevices(devices []pcap.Interface) { fmt.Println("Devices found:") fmt.Printf("\n") for _, device := range devices { fmt.Println("Name: ", device.Name) fmt.Println("Description: ", device.Description) fmt.Println("Devices addresses: ") for _, address := range device.Addresses { fmt.Println("\t- IP address: ", address.IP) fmt.Println("\t- Subnet mask: ", address.Netmask) } fmt.Printf("\n") } } func display() { displayFriendlyInterfaceName() }
package no.nav.syfo.sykmelding.model data class SykmeldingIdAndFnr( val sykmeldingId: String, val fnr: String )
type RunRef<R> = { readonly errors: unknown[]; readonly result: R; }; function* $run<T, R, U>(iter: Iterator<T, R, U>, ref: any) { do { try { const n = iter.next(); // This sucks?? Why does it need to have === true?? if (n.done === true) { ref.result = n.value; return; } yield n.value; } catch (error) { console.log(error); ref.errors.push(error); continue; } } while (true); } function run<T, R, N>(iter: Iterator<T, R, N>): [RunRef<R>, Generator<T, void, unknown>] { const ref: any = { errors: [] }; return [ref, $run(iter, ref)]; } export function of<T, R, N>(iter: Iterator<T, R, N | undefined>, body: (each: T) => N) { let previous: N | undefined; do { const next = iter.next(previous); if (next.done === true) { return next.value; } previous = body(next.value); } while (true); } // const [ref, iter] = run(range(5)); // for (const each of iter) { // console.log(each); // } // console.log(ref); // should be -1
/// /// venosyd © 2016-2021 /// /// sergio lisan <sels@venosyd.com> /// library opensyd.logs.dialogs.escopos; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:opensyd_flutter/opensyd_flutter.dart'; import 'package:opensyd_providers/opensyd_providers.dart'; import '../app.dart'; /// class EscoposDialog extends StatefulWidget { /// const EscoposDialog(this.refresh); /// final void Function() refresh; @override _EscoposDialogState createState() => _EscoposDialogState(); } /// class _EscoposDialogState extends State<EscoposDialog> { /// EntitiesRepository get entities => Providers.of<EntitiesRepository>(context); /// final _newscopectrl = TextEditingController(); @override Widget build(BuildContext context) => SobreposeDialog( padding: const EdgeInsets.all(16), width: 500, height: 400, child: Column( children: [ // // Row( children: [ // RoundedTextField( text: 'Adicione um novo escopo', controller: _newscopectrl, ).Expanded(), // const FaIcon( FontAwesomeIcons.plusCircle, color: Colors.grey, size: 16, ) // .Ripplefy(action: _add) .Centered() .Width(48), ], ) // .Centered() .Height(56), // // FutureBuilder<List<Namespace>>( future: entities.all<Namespace>(), builder: (_, snap) => snap.hasData // ? ListView.builder( itemCount: snap.data.length, itemBuilder: (_, index) => Text(snap.data[index].name) .Padding(all: 12) .Ripplefy(action: () => _remove(_, snap.data[index])), ) // : Container(), ).Expanded(), ], ), ); /// Future<void> _add() async { if (_newscopectrl.text.isNotEmpty) await entities.save<Namespace>(Namespace()..name = _newscopectrl.text); (widget.refresh ?? () {})(); setState(() {}); } /// void _remove(BuildContext ctx, Namespace namespace) => OpenSyDialogs.choice( context: ctx, message: 'Deseja remover este Escopo?', yesOnPressed: () async { await entities.delete<Namespace>(namespace); (widget.refresh ?? () {})(); setState(() {}); }, ); }
#!/bin/sh windres ./src/versuse-resource.rc -O coff -o ./src/versuse-resource.res g++ -c -Wall ./src/versuse-main.cpp -o ./src/versuse-main.o g++ -static -o ./bin/Versuse3.exe ./src/versuse-main.o ./src/versuse-resource.res -mwindows
/* * Copyright (c) 2015-2020, Virgil Security, Inc. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * (3) Neither the name of virgil nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.virgilsecurity.ratchet.securechat.keysrotation import com.google.gson.annotations.SerializedName /** * This class shows the result of rotateKeys operation. */ class RotationLog { /** * Number of unused one-time keys. */ @SerializedName("one_time_keys_relevant") var oneTimeKeysRelevant = 0 /** * NUmber of one-time keys that were generated and uploaded to the cloud during this operation. */ @SerializedName("one_time_keys_added") var oneTimeKeysAdded = 0 /** * Number of one-time keys that were deleted during this rotation. */ @SerializedName("one_time_keys_deleted") var oneTimeKeysDeleted = 0 /** * Number of one-time keys that were marked orphaned during this operation. */ @SerializedName("one_time_keys_marks_orphaned") var oneTimeKeysMarkedOrphaned = 0 /** * Number of one-time keys that were marked orphaned. */ @SerializedName("one_time_keys_orphaned") var oneTimeKeysOrphaned = 0 /** * Number of relevant long-term keys. */ @SerializedName("long_term_keys_relevant") var longTermKeysRelevant = 0 /** * Number of long-term keys that were generated and uploaded to the cloud during this operation. */ @SerializedName("long_term_keys_added") var longTermKeysAdded = 0 /** * Number of long-term keys that were deleted during this rotation. */ @SerializedName("long_term_keys_deleted") var longTermKeysDeleted = 0 /** * Number of long-term keys that were marked orphaned outdated this operation. */ @SerializedName("long_term_keys_marked_outdated") var longTermKeysMarkedOutdated = 0 /** * Number of long-term keys that were marked orphaned. */ @SerializedName("long_term_keys_outdated") var longTermKeysOutdated = 0 }
using System; using System.Collections.Generic; using System.Text; namespace Mvp.Feature.BasicContent.Models { public class HalfWidthBanner : CtaContent { } }
module AssertJson def assert_json(json_string, &block) if block_given? @json = AssertJson::Json.new(json_string) # json.instance_exec(json, &block) yield @json end end def item(index, &block) @json.item(index, &block) end def has(*args, &block) @json.has(*args, &block) end def has_not(*args, &block) @json.has_not(*args, &block) end class Json def initialize(json_string) @decoded_json = ActiveSupport::JSON.decode(json_string) end def item(index, &block) @index = index yield if block_given? end def element(*args, &block) arg = args.shift token = if @decoded_json.is_a?(Array) if @index @decoded_json[@index] else @decoded_json.shift end else @decoded_json end case token when Hash arg = arg.to_s raise_error("element #{arg} not found") unless token.keys.include?(arg) unless args.empty? second_arg = args.shift gen_error = lambda {raise_error("element #{token[arg].inspect} does not match #{second_arg.inspect}")} case second_arg when Regexp gen_error.call if second_arg !~ token[arg] when Symbol gen_error.call if second_arg.to_s != token[arg] else gen_error.call if second_arg != token[arg] end end when Array raise_error("element #{arg} not found") if token != arg when String case arg when Regexp raise_error("element #{arg.inspect} not found") if token !~ arg else raise_error("element #{arg.inspect} not found") if token != arg.to_s end when NilClass raise_error("no element left") else flunk end if block_given? begin in_scope, @decoded_json = @decoded_json, token.is_a?(Hash) ? token[arg] : token yield ensure @decoded_json = in_scope end end end alias has element def not_element(*args, &block) arg = args.shift token = @decoded_json case token when Array raise_error("element #{arg} found, but not expected") if token.include?(arg.to_s) else raise_error("element #{arg} found, but not expected") if token.keys.include?(arg.to_s) end end alias has_not not_element private def raise_error(message) if Object.const_defined?(:MiniTest) raise MiniTest::Assertion.new(message) else raise Test::Unit::AssertionFailedError.new(message) end end end end
namespace System { public static class Int32Extension { public static unsafe int Reverse(this int value) { return ((value >> 24) & 0xFF) | (value << 24) | ((value >> 8) & 0xFF00) | ((value & 0xFF00) << 8); } public static int Align(this int value, int align) { return (value + align - 1) / align * align; } public static int Clamp(this int value, int min, int max) { if (value <= min) return min; if (value >= max) return max; return value; } } }
import codecs import numpy as np from sklearn.metrics import precision_recall_fscore_support, accuracy_score, classification_report from sklearn.model_selection import KFold from scipy import stats from sklearn.svm import SVC from . import classifiers, retriever, timeseries def _split(data): ret = [] for i in range(0, len(data), 60): if i+60 > len(data): break ret.append( (list(range(i, i+30)), list(range(i+30, i+60))) ) return ret # Auxiliary data cryptocurrencies = ['bitcoin'] estimations = ['count', 'paper'] # data_headers = { 'bitcoin': { 'price': ['positive_topic', 'total_topic', 'positive_reply', 'total_reply'], 'transactions': ['total_topic', 'very_positive_topic', 'very_positive_reply'], } } label_headers = ['price'] # , 'transactions' aode = classifiers.AODE() svclassifier = SVC(kernel='rbf', degree=8, probability=True) kf = KFold(n_splits=10, shuffle=True) # 90% for training, 10% for testing results = {} for cryptocurrency in cryptocurrencies: print('\nTesting for ' + cryptocurrency + ' data set') file_name = 'res/forecasting_results/' + cryptocurrency + '.txt' file_ = codecs.open(file_name, 'w+', 'utf-8') results[cryptocurrency] = {} # Collect data df = retriever.get_data(cryptocurrency)#.apply(stats.zscore) # Binerize labels (Done in get_data) # df = retriever.categorize_labels(df, label_headers) for label in label_headers: results[cryptocurrency][label] = {} # Extract features and labels data = df.drop(columns=label_headers).apply(timeseries.standardize_laggedly).dropna() data = np.array(data[data_headers[cryptocurrency][label]]) # Print some status data_len = len(data) features_amount = data[0].size print('\tTotal data collected: ' + str(data_len)) print('\tTotal of features per data: ' + str(features_amount)) for estimation in estimations: aode = classifiers.AODE() print('\tPerforming 10-Fold estimating probabilities on \'' + estimation + '\' mode') file_.write( 'Results for \'' + label + '\' ' + cryptocurrency + ' estimating probabilities on \'' + estimation + '\' mode:\n' ) results[cryptocurrency][label][estimation] = {} for lag in range(1, 14): # TODO: Time lag is a window not a single element labels = np.array(df[label][10:].shift(-1)) print('\n\n\t\tPredicting with lag =', str(lag)) file_.write('\tLag = ' + str(lag)) # lagged_data = data[lag:] # lagged_labels = labels[lag:] precisions = [] recalls = [] f1s = [] accuracies = [] # for train_indices, test_indices in _split(lagged_data): train_data, test_data = lagged_data[:697], lagged_data[697:] train_labels, test_labels = lagged_labels[:697], lagged_labels[697:] # Training aode.fit(train_data, train_labels, online=False) #svclassifier.fit(train_data, train_labels) # Test pred_labels = [] for element in test_data: pred_labels.append(aode.predict(element, estimation=estimation)) #pred_labels = svclassifier.predict(test_data) # print('\n\n\n\n\n\n') # print(set(train_labels), set(pred_labels)) metrics = precision_recall_fscore_support( test_labels, pred_labels, average='weighted' ) print( '\t\t\t', classification_report(test_labels, pred_labels).replace('\n', '\n\t\t\t') ) precision, recall, f1, _ = metrics accuracy = accuracy_score(test_labels, pred_labels) print('\t\t\tAccuracy:', accuracy) precisions.append(precision) recalls.append(recall) f1s.append(f1) accuracies.append(accuracy) ##### results[cryptocurrency][label][estimation]['precision'] = precisions results[cryptocurrency][label][estimation]['recall'] = recalls results[cryptocurrency][label][estimation]['f1'] = f1s results[cryptocurrency][label][estimation]['accuracy'] = accuracies file_.write('\n\t\tPrecisions: ' + str(precisions)) file_.write('\n\t\t\tMean: ' + str(np.mean(precisions))) file_.write('\n\t\tRecalls: ' + str(recalls)) file_.write('\n\t\t\tMean: ' + str(np.mean(recalls))) file_.write('\n\t\tF1s: ' + str(f1s)) file_.write('\n\t\t\tMean: ' + str(np.mean(f1s))) file_.write('\n\t\tAccuracies: ' + str(accuracies)) file_.write('\n\t\t\tMean: ' + str(np.mean(accuracies)) + '\n\n')
#include "ItemFPPProperties.hpp" #include "engine/app3D/defs/ModelDef.hpp" #include "../../Global.hpp" #include "../../Core.hpp" #include "engine/util/DefDatabase.hpp" #include "../AnimationFramesSetDef.hpp" namespace app { void ItemFPPProperties::expose(engine::DataFile::Node &node) { TRACK; node.var(m_modelDef_defName, "modelDef"); node.var(m_animationFramesSetDef_defName, "animationFramesSetDef"); node.var(m_basePosition, "basePosition"); node.var(m_baseRotation, "baseRotation"); node.var(m_aimPosition, "aimPosition"); node.var(m_aimRotation, "aimRotation"); if(node.getActivityType() == engine::DataFile::Activity::Type::Loading) { auto &defDatabase = Global::getCore().getDefDatabase(); m_modelDef = defDatabase.getDef <engine::app3D::ModelDef> (m_modelDef_defName); m_animationFramesSetDef = defDatabase.getDef <AnimationFramesSetDef> (m_animationFramesSetDef_defName); } } bool ItemFPPProperties::hasModel() const { return static_cast <bool> (m_modelDef); } bool ItemFPPProperties::hasAnimationFramesSetDef() const { return static_cast <bool> (m_animationFramesSetDef); } const engine::app3D::ModelDef &ItemFPPProperties::getModelDef() const { if(!m_modelDef) throw engine::Exception{"FPP model def is nullptr. This should have been checked before."}; return *m_modelDef; } const AnimationFramesSetDef &ItemFPPProperties::getAnimationFramesSetDef() const { if(!m_animationFramesSetDef) throw engine::Exception{"Animation frames set def is nullptr. This should have been checked before."}; return *m_animationFramesSetDef; } const std::shared_ptr <engine::app3D::ModelDef> &ItemFPPProperties::getModelDefPtr() const { if(!m_modelDef) throw engine::Exception{"FPP model def is nullptr. This should have been checked before."}; return m_modelDef; } const std::shared_ptr <AnimationFramesSetDef> &ItemFPPProperties::getAnimationFramesSetDefPtr() const { if(!m_animationFramesSetDef) throw engine::Exception{"Animation frames set def is nullptr. This should have been checked before."}; return m_animationFramesSetDef; } const engine::FloatVec3 &ItemFPPProperties::getBasePosition() const { return m_basePosition; } const engine::FloatVec3 &ItemFPPProperties::getBaseRotation() const { return m_baseRotation; } const engine::FloatVec3 &ItemFPPProperties::getAimPosition() const { return m_aimPosition; } const engine::FloatVec3 &ItemFPPProperties::getAimRotation() const { return m_aimRotation; } } // namespace app
// module.exports 默认是一空对象,和exports 是相等的 'use strict'; // 引入数据库操作db对象 const db = require('../models/db'); //解析文件上传 const formidable = require('formidable'); //引入path核心对象 const path = require('path'); //引入配置对象 const config = require('../config'); /** * [添加音乐] * @param {[type]} req [description] * @param {[type]} res [description] * @param {Function} next [description] * @return {[type]} [description] */ exports.addMusic = (req,res,next)=>{ var form = new formidable.IncomingForm(); form.uploadDir = path.join(config.rootPath,'public/files'); form.parse(req, function(err, fields, files) { if(err) return next(err); // { title: '告白气球', singer: '周杰伦', time: '03:00' } // { file:{} // console.log(fields); // console.log(files); //获取6个字段中的3个 let datas = [fields.title,fields.singer,fields.time]; let sql = 'insert into musics (title,singer,time,'; let params = '(?,?,?'; //两个路径 if(files.file){ //获取文件名 let filename = path.parse(files.file.path).base; //如果上传了文件 datas.push(`/public/files/${filename}`); sql += 'file,'; params += ',?'; } if(files.filelrc){ //获取文件名 let lrcname = path.parse(files.filelrc.path).base; //如果上传了文件 datas.push(`/public/files/${lrcname}`); sql += 'filelrc,'; params += ',?'; } params += ',?)'; sql += 'uid) values '; //用户的id datas.push(req.session.user.id); // console.log(sql); // console.log(params); //插入音乐数据 db.q(sql + params ,datas,(err,data)=>{ res.json({ code:'001', msg:'添加音乐成功' }); }); }); }; /** * [更新音乐] * @param {[type]} req [description] * @param {[type]} res [description] * @param {Function} next [description] * @return {[type]} [description] */ exports.updateMusic = (req,res,next)=>{ var form = new formidable.IncomingForm(); form.uploadDir = path.join(config.rootPath,'public/files'); form.parse(req, function(err, fields, files) { if(err) return next(err); //获取6个字段中的3个 let sql = 'update musics set title=?,singer=?,time=?,'; let datas = [fields.title,fields.singer,fields.time]; //两个路径 if(files.file){ //获取文件名 let filename = path.parse(files.file.path).base; //如果上传了文件 datas.push(`/public/files/${filename}`); sql += 'file=?,'; } if(files.filelrc){ //获取文件名 let lrcname = path.parse(files.filelrc.path).base; //如果上传了文件 datas.push(`/public/files/${lrcname}`); sql += 'filelrc=?,'; } //去除一个逗号 sql = sql.substr(0,sql.length -1); //加上条件 sql += 'where id = ?'; datas.push(fields.id); //更新音乐数据 db.q(sql,datas,(err,data)=>{ res.json({ code:'001', msg:'更新音乐成功' }); }); }); }; /** * 删除音乐 * @param {[type]} req [description] * @param {[type]} res [description] * @param {Function} next [description] * @return {[type]} [description] */ exports.delMusic = (req,res,next)=>{ //获取用户id let userid = req.session.user.id; //1:接收参数 let musicId = req.query.id; //2:db删除数据 db.q('delete from musics where id = ? and uid = ?',[musicId,userid],(err,result)=>{ if(err) return next(err); // console.log(result); //判断是否删除成功 if(result.affectedRows == 0){ //歌曲不存在 return res.json({ code:'002',msg:'歌曲不存在' }); } //删除成功 res.json({ code:'001',msg:'删除成功' }); }); }; /** * 添加音乐 * @param {[type]} req [description] * @param {[type]} res [description] * @param {Function} next [description] * @return {[type]} [description] */ exports.showAddMusic = (req,res,next)=>{ res.render('add.html'); } /** * 音乐列表 * @param {[type]} req [description] * @param {[type]} res [description] * @param {Function} next [description] * @return {[type]} [description] */ exports.showListMusic = (req,res,next)=>{ let userId = req.session.user.id; //以用户id作为查询条件查询音乐表 db.q('select * from musics where uid = ?',[userId],(err,musics)=>{ res.render('list.html',{ //循环,给每个元素加一个索引,利用模板引擎的index属性+1 musics, //musics:musics ES6简写 // user:req.session.user }) }) }
// Copyright 2021 VMware // // 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 registrar //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate import ( "context" "fmt" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/vmware-tanzu/cartographer/pkg/apis/v1alpha1" ) //counterfeiter:generate sigs.k8s.io/controller-runtime/pkg/client.Client //counterfeiter:generate . Logger type Logger interface { Error(err error, msg string, keysAndValues ...interface{}) } type Mapper struct { Client client.Client // fixme We should accept the context, not the logger - then we get the right logger and so does the client Logger Logger } func (mapper *Mapper) TemplateToWorkloadRequests(template client.Object) []reconcile.Request { supplyChains := mapper.templateToSupplyChains(template) var requests []reconcile.Request for _, supplyChain := range supplyChains { reqs := mapper.ClusterSupplyChainToWorkloadRequests(&supplyChain) requests = append(requests, reqs...) } return requests } func (mapper *Mapper) templateToSupplyChains(template client.Object) []v1alpha1.ClusterSupplyChain { templateName := template.GetName() err := mapper.addGVK(template) if err != nil { mapper.Logger.Error(err, fmt.Sprintf("could not get GVK for template: %s", templateName)) return nil } list := &v1alpha1.ClusterSupplyChainList{} err = mapper.Client.List( context.TODO(), list, ) if err != nil { mapper.Logger.Error(err, "list ClusterSupplyChains") return nil } templateKind := template.GetObjectKind().GroupVersionKind().Kind var supplyChains []v1alpha1.ClusterSupplyChain for _, sc := range list.Items { for _, res := range sc.Spec.Resources { if res.TemplateRef.Kind == templateKind && res.TemplateRef.Name == templateName { supplyChains = append(supplyChains, sc) } } } return supplyChains } func (mapper *Mapper) ClusterSupplyChainToWorkloadRequests(object client.Object) []reconcile.Request { var err error supplyChain, ok := object.(*v1alpha1.ClusterSupplyChain) if !ok { mapper.Logger.Error(nil, "cluster supply chain to workload requests: cast to ClusterSupplyChain failed") return nil } list := &v1alpha1.WorkloadList{} err = mapper.Client.List(context.TODO(), list, client.InNamespace(supplyChain.Namespace), client.MatchingLabels(supplyChain.Spec.Selector)) if err != nil { mapper.Logger.Error(fmt.Errorf("client list: %w", err), "cluster supply chain to workload requests: client list") return nil } var requests []reconcile.Request for _, workload := range list.Items { requests = append(requests, reconcile.Request{ NamespacedName: types.NamespacedName{ Name: workload.Name, Namespace: workload.Namespace, }, }) } return requests } func (mapper *Mapper) ClusterDeliveryToDeliverableRequests(object client.Object) []reconcile.Request { var err error delivery, ok := object.(*v1alpha1.ClusterDelivery) if !ok { mapper.Logger.Error(nil, "cluster delivery to deliverable requests: cast to ClusterDelivery failed") return nil } list := &v1alpha1.DeliverableList{} err = mapper.Client.List(context.TODO(), list, client.InNamespace(delivery.Namespace), client.MatchingLabels(delivery.Spec.Selector)) if err != nil { mapper.Logger.Error(fmt.Errorf("client list: %w", err), "cluster delivery to deliverable requests: client list") return nil } var requests []reconcile.Request for _, deliverable := range list.Items { requests = append(requests, reconcile.Request{ NamespacedName: types.NamespacedName{ Name: deliverable.Name, Namespace: deliverable.Namespace, }, }) } return requests } func (mapper *Mapper) RunTemplateToRunnableRequests(object client.Object) []reconcile.Request { var err error runTemplate, ok := object.(*v1alpha1.ClusterRunTemplate) if !ok { mapper.Logger.Error(nil, "run template to runnable requests: cast to run template failed") return nil } list := &v1alpha1.RunnableList{} err = mapper.Client.List(context.TODO(), list) if err != nil { mapper.Logger.Error(fmt.Errorf("client list: %w", err), "run template to runnable requests: client list") return nil } var requests []reconcile.Request for _, runnable := range list.Items { if runTemplateRefMatch(runnable.Spec.RunTemplateRef, runTemplate) { requests = append(requests, reconcile.Request{ NamespacedName: types.NamespacedName{ Name: runnable.Name, Namespace: runnable.Namespace, }, }) } } return requests } // addGVK fulfills the 'GVK of an object returned from the APIServer // https://github.com/kubernetes-sigs/controller-runtime/issues/1517#issuecomment-844703142 func (mapper *Mapper) addGVK(obj client.Object) error { gvks, unversioned, err := mapper.Client.Scheme().ObjectKinds(obj) if err != nil { return fmt.Errorf("missing apiVersion or kind: %s err: %w", obj.GetName(), err) } if unversioned { return fmt.Errorf("unversioned object: %s", obj.GetName()) } if len(gvks) != 1 { return fmt.Errorf("unexpected GVK count: %s", obj.GetName()) } obj.GetObjectKind().SetGroupVersionKind(gvks[0]) return nil } func (mapper *Mapper) TemplateToSupplyChainRequests(template client.Object) []reconcile.Request { supplyChains := mapper.templateToSupplyChains(template) var requests []reconcile.Request for _, supplyChain := range supplyChains { requests = append(requests, reconcile.Request{ NamespacedName: types.NamespacedName{ Name: supplyChain.Name, }, }) } return requests } func (mapper *Mapper) TemplateToDeliveryRequests(template client.Object) []reconcile.Request { templateName := template.GetName() err := mapper.addGVK(template) if err != nil { mapper.Logger.Error(err, fmt.Sprintf("could not get GVK for template: %s", templateName)) return nil } list := &v1alpha1.ClusterDeliveryList{} err = mapper.Client.List( context.TODO(), list, ) if err != nil { mapper.Logger.Error(err, "list ClusterDeliveries") return nil } templateKind := template.GetObjectKind().GroupVersionKind().Kind var requests []reconcile.Request for _, sc := range list.Items { for _, res := range sc.Spec.Resources { if res.TemplateRef.Kind == templateKind && res.TemplateRef.Name == templateName { requests = append(requests, reconcile.Request{ NamespacedName: types.NamespacedName{ Name: sc.Name, }, }) } } } return requests } func runTemplateRefMatch(ref v1alpha1.TemplateReference, runTemplate *v1alpha1.ClusterRunTemplate) bool { if ref.Name != runTemplate.Name { return false } return ref.Kind == "ClusterRunTemplate" || ref.Kind == "" }
INSERT INTO baseline_rr ( map_unit_id, map_unit_name, indirect_benefits, base_contribution, rr_rating, wildfire_rating, wildfire_contribution, total_reserve, mz3, mz4, mz5, breed_baseline, summer_baseline, winter_baseline) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
using System; namespace ServiceFabric.BackupRestore.Web.Models { public class BackupEnabledServiceReference { public Uri ApplicationName { get; set; } public Uri ServiceName { get; set; } public Guid Int64RangePartitionGuid { get; set; } public Uri Endpoint { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MCR.views { public partial class ServerSettingDialog : Form { private NetStatesManager netStatesManager; public ServerSettingDialog(NetStatesManager netStatesManager) { this.netStatesManager = netStatesManager; InitializeComponent(); var port = netStatesManager.getPort(); portTbx.Text = Convert.ToString(port); } private void portTbx_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(portTbx.Text) && !char.IsDigit(portTbx.Text.Last())) portTbx.Text.Remove(portTbx.Text.Length-1); } private void okBtn_Click(object sender, EventArgs e) { int port = Convert.ToInt32(portTbx.Text); netStatesManager.setPort(port); MessageBox.Show("設置完成!伺服器將偵聽 " + port + " port。請重啟伺服器。"); } } }
package sqlite import ( "github.com/go-jet/jet/v2/internal/jet" ) type onConflict interface { WHERE(indexPredicate BoolExpression) conflictTarget conflictTarget } type conflictTarget interface { DO_NOTHING() InsertStatement DO_UPDATE(action conflictAction) InsertStatement } type onConflictClause struct { insertStatement InsertStatement indexExpressions []jet.ColumnExpression whereClause jet.ClauseWhere do jet.Serializer } func (o *onConflictClause) WHERE(indexPredicate BoolExpression) conflictTarget { o.whereClause.Condition = indexPredicate return o } func (o *onConflictClause) DO_NOTHING() InsertStatement { o.do = jet.Keyword("DO NOTHING") return o.insertStatement } func (o *onConflictClause) DO_UPDATE(action conflictAction) InsertStatement { o.do = action return o.insertStatement } func (o *onConflictClause) Serialize(statementType jet.StatementType, out *jet.SQLBuilder, options ...jet.SerializeOption) { if len(o.indexExpressions) == 0 && o.do == nil { return } out.NewLine() out.WriteString("ON CONFLICT") if len(o.indexExpressions) > 0 { out.WriteString("(") jet.SerializeColumnExpressionNames(o.indexExpressions, statementType, out, jet.ShortName) out.WriteString(")") } o.whereClause.Serialize(statementType, out, jet.SkipNewLine, jet.ShortName) out.IncreaseIdent(7) jet.Serialize(o.do, statementType, out) out.DecreaseIdent(7) } type conflictAction interface { jet.Serializer WHERE(condition BoolExpression) conflictAction } // SET creates conflict action for ON_CONFLICT clause func SET(assigments ...ColumnAssigment) conflictAction { conflictAction := updateConflictActionImpl{} conflictAction.doUpdate = jet.KeywordClause{Keyword: "DO UPDATE"} conflictAction.Serializer = jet.NewSerializerClauseImpl(&conflictAction.doUpdate, &conflictAction.set, &conflictAction.where) conflictAction.set = assigments return &conflictAction } type updateConflictActionImpl struct { jet.Serializer doUpdate jet.KeywordClause set jet.SetClauseNew where jet.ClauseWhere } func (u *updateConflictActionImpl) WHERE(condition BoolExpression) conflictAction { u.where.Condition = condition return u }