text
stringlengths
1
1.05M
package chylex.hee.world.feature.stronghold; import java.util.Random; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityChest; import chylex.hee.init.BlockList; import chylex.hee.system.abstractions.BlockInfo; import chylex.hee.system.abstractions.Meta; import chylex.hee.system.abstractions.facing.Facing4; import chylex.hee.system.util.MathUtil; import chylex.hee.world.feature.WorldGenStronghold; import chylex.hee.world.loot.WeightedLootTable; import chylex.hee.world.structure.dungeon.StructureDungeonPiece; import chylex.hee.world.structure.dungeon.generators.DungeonGeneratorSpreading.ISpreadingGeneratorPieceType; import chylex.hee.world.structure.util.IBlockPicker; import chylex.hee.world.structure.util.IStructureTileEntity; import chylex.hee.world.util.RandomAmount; import chylex.hee.world.util.Size; public abstract class StrongholdPiece extends StructureDungeonPiece{ protected enum Type implements ISpreadingGeneratorPieceType{ CORRIDOR, DOOR, ROOM, DEADEND; @Override public boolean isRoom(){ return this == ROOM || this == DEADEND; // the spreading generator cannot create deadends, so make a couple of them intentionally } @Override public boolean isDoor(){ return this == DOOR; } } protected static final IConnectWith fromRoom = type -> type == Type.CORRIDOR || type == Type.DOOR; protected static final IConnectWith fromDeadEnd = type -> type == Type.CORRIDOR; protected static final IConnectWith fromDoor = type -> true; protected static final IConnectWith withAnything = type -> true; private static final BlockInfo[] blocksStoneBrick = new BlockInfo[]{ new BlockInfo(Blocks.stonebrick, Meta.stoneBrickPlain), new BlockInfo(Blocks.stonebrick, Meta.stoneBrickMossy), new BlockInfo(Blocks.stonebrick, Meta.stoneBrickCracked), new BlockInfo(Blocks.monster_egg, Meta.silverfishPlain), new BlockInfo(Blocks.monster_egg, Meta.silverfishMossy), new BlockInfo(Blocks.monster_egg, Meta.silverfishCracked) }; protected static final IBlockPicker placeStoneBrick = rand -> { int chance = rand.nextInt(100); if (chance < 45)return blocksStoneBrick[0]; else if (chance < 75)return blocksStoneBrick[1]; else if (chance < 95)return blocksStoneBrick[2]; else{ chance = rand.nextInt(100); if (chance < 47)return blocksStoneBrick[3]; else if (chance < 79)return blocksStoneBrick[4]; else return blocksStoneBrick[5]; } }; protected static final IBlockPicker placeStoneBrickPlain = blocksStoneBrick[0]; protected static final IBlockPicker placeStoneBrickChiseled = new BlockInfo(Blocks.stonebrick, Meta.stoneBrickChiseled); protected static final IBlockPicker placeStoneBrickStairs(Facing4 ascendsTowards, boolean flip){ return new BlockInfo(Blocks.stone_brick_stairs, Meta.getStairs(ascendsTowards, flip)); } private static final void generateLoot(WeightedLootTable lootTable, int items, int cobwebs, TileEntityChest chest, Random rand){ while(items-- > 0){ chest.setInventorySlotContents(rand.nextInt(chest.getSizeInventory()), lootTable.generateWeighted(null, rand)); } for(int slot; cobwebs > 0; cobwebs--){ slot = rand.nextInt(chest.getSizeInventory()); if (chest.getStackInSlot(slot) == null)chest.setInventorySlotContents(slot, new ItemStack(rand.nextInt(3) == 0 ? BlockList.ancient_web : Blocks.web)); } } protected static final IStructureTileEntity generateLootGeneral = (tile, rand) -> { generateLoot(WorldGenStronghold.lootGeneral, RandomAmount.aroundCenter.generate(rand, 3, 10), rand.nextInt(7), (TileEntityChest)tile, rand); }; protected static final IStructureTileEntity generateLootLibraryMain = (tile, rand) -> { generateLoot(WorldGenStronghold.lootLibrary, RandomAmount.linear.generate(rand, 9, 11), 2+rand.nextInt(2), (TileEntityChest)tile, rand); }; protected static final IStructureTileEntity generateLootLibrarySecondary = (tile, rand) -> { generateLoot(WorldGenStronghold.lootLibrary, RandomAmount.aroundCenter.generate(rand, 4, 6), 4+rand.nextInt(3), (TileEntityChest)tile, rand); }; public StrongholdPiece(Type type, Size size){ super(type, size); } /** * Determines the multiplier of calculated weight. Using the default settings:<br> * - corridors with several connections get higher increase than rooms, to encourage interesting paths<br> * - rooms have higher importance than corridors, but have a gentler curve with increasing connections */ @Override public final int calculateInstWeight(int availableConnections){ return MathUtil.ceil(Math.pow(availableConnections, getWeightFactor())*getWeightMultiplier()); } protected float getWeightFactor(){ return type == Type.ROOM ? 1.5F : type == Type.CORRIDOR ? 2.5F : 1F; } protected float getWeightMultiplier(){ return type == Type.ROOM ? 2F : type == Type.CORRIDOR ? 1F : 0F; } }
use Shopware\Core\Framework\ShopwareHttpException; class SatispaySettingsInvalidException extends ShopwareHttpException { public function getErrorCode(): string { return 'SATISPAY_PLUGIN__SETTING_EXCEPTION'; } }
using NUnit.Framework; using PackageManagement.Cmdlets.Tests.Helpers; namespace PackageManagement.Cmdlets.Tests { [TestFixture] public class TestableUpdatePackageCmdletTests { [Test] public void TestableUpdatePackageCmdlet_Initialization_Success() { // Arrange var testableCmdlet = new TestableUpdatePackageCmdlet(); // Act - No action required for this test // Assert Assert.NotNull(testableCmdlet.FakeCmdletTerminatingError, "FakeCmdletTerminatingError should not be null"); Assert.NotNull(testableCmdlet.FakePackageManagementConsoleHost, "FakePackageManagementConsoleHost should not be null"); Assert.NotNull(testableCmdlet.FakeUpdatePackageActionsFactory, "FakeUpdatePackageActionsFactory should not be null"); } } }
var frameModule = require("ui/frame"); var dialog = require("tns-core-modules/ui/dialogs"); var Page1ViewModel = require("./page1-view-model"); var page1ViewModel = new Page1ViewModel(); var listViewModule = require("tns-core-modules/ui/list-view"); var Observable = require("data/observable"); var ObservableArray = require("data/observable-array").ObservableArray; var search_data; var place; var array; var locationVEB = ["VEB1500030", "VEB1500029", "VEB1500015", "VEB1500012", "VEB1500013", "VEB1500018", "VEB1500038", "VEB1500014","VEB1500022","VEB1500032", "VEB1500041", "VEB1500026", "VEB1500033", "VEB1500016"]; var locationVET = ["VET0130", "VET0020", "VET0021", "VET0072", "VET0071", "VET0100", "VET0062", "VET0150", "VET0055", "VET0054", "VET0056", "VET0051", "VET0050", "VET0053", "VET0052", "VET0121", "VET0123", "VET0122", "VET0125", "VET0124", "VET0000", "VET0031", "VET0030", "VET0140", "VET0061", "VET0063", "VET0064", "VET0110", "VET0010", "VET0160", "VET0057", "VET0042", "VET0041"]; var location; const appSettings = require("application-settings"); var pageData; function pageLoaded(args) { var page = args.object; var flag = true; array = new ObservableArray(); pageData = new Observable.fromObject({ mytiluse2: array }); search_data = appSettings.getString("data"); var scelta; scelta = page.navigationContext.scelta; if(scelta == 0){ location = locationVET; } else if(scelta == 1){ location = locationVEB; } console.log("SCELTA = " + scelta); console.log("LOG: " + isLogged); if (isLogged == 0) pageData.set("login_status", "Login"); else if (isLogged > 0) pageData.set("login_status", "Logout"); console.log("Privileges = " + appSettings.getNumber("mytiluse",0)); for (place = 0; place < location.length; place++) { pageData.set("isBusy", true);//Load animation pageData.set("isHeigh", "25"); //URL var url = api_base_url + "/products/rms3/forecast/" + location[place] + "?date=" + search_data + "&opt=place"; //START FETCH fetch(url) .then((response) => response.json()) .then((data) => { // FETCH RMS3 if (data.result == "ok") { var scs = data.forecast.scs; var scm = data.forecast.scm.toString(); var id = data.place.id; var name_place = data.place.long_name.it; if (appSettings.getNumber("mytiluse",0) == 1) //Mytiluse privilege { var url_wcm3 = api_base_url + "/products/wcm3/forecast/" + id + "?date=" + search_data; var status; //WORKING! fetch(url_wcm3) .then((response) => response.json()) .then((json) => { //console.log(json); if(json.result == "ok") { status = json.forecast.sts; array.push({ "id": id, "name": name_place, "curDir": "~/images/arrow/" + scs + ".jpg", "curVal": scm + " m/sec", "status": "~/images/status/" + status + ".png" }); array.sort(function (orderA, orderB) { var nameA = orderA.name; var nameB = orderB.name; return (nameA < nameB) ? -1 : (nameA > nameB) ? 1 : 0; }); } else if(json.result == "error") { array.push({ "id": id, "name": name_place, "curDir": "~/images/arrow/" + scs + ".jpg", "curVal": scm + " m/sec", "status": "~/images/status/none.png" }); array.sort(function (orderA, orderB) { var nameA = orderA.name; var nameB = orderB.name; return (nameA < nameB) ? -1 : (nameA > nameB) ? 1 : 0; }); //dialog.alert({title : "Errore", message: "Status non disponibile", okButtonText: "OK"}); } }); } else { array.push({ "id": id, "name": name_place, "curDir": "~/images/arrow/" + scs + ".jpg", "curVal": scm + " m/sec", "status": "~/images/status/none.png" }); array.sort(function (orderA, orderB) { var nameA = orderA.name; var nameB = orderB.name; return (nameA < nameB) ? -1 : (nameA > nameB) ? 1 : 0; }); } } else if (data.result == "error" && flag) { dialog.alert({ title: "Errore", message: data.details + location[place], okButtonText: "OK" }); flag = false; } }) .then(function () { pageData.set("isBusy", false); pageData.set("isHeigh", "0"); }) .catch(error => console.error("[PAGE_1] ERROR ", error)); // END FETCH } page.bindingContext = pageData; }; //Navigation button -> PAGE1 to PAGE2 const Button = require("tns-core-modules/ui/button").Button; const Page = require("tns-core-modules/ui/page").Page; function onTap(args) { const index = args.index; const button = args.object; const page = button.page; const nav = { moduleName: "page_selection/page_selection", context: { send_ind: array.getItem(index).id, send_name: array.getItem(index).name } }; page.frame.navigate(nav); } exports.onTap = onTap; exports.pageLoaded = pageLoaded; exports.onTapAbout = function(args) { const button = args.object; const page = button.page; page.frame.navigate("page_about/page_about"); }; exports.onTapLog = function(args) { const button = args.object; const pageData = button.page; if(isLogged == 0) pageData.frame.navigate("page_login/page_login"); else { dialog.confirm({title: "Disconnessione", message: "Sicuro di voler rimuovere username e password?", okButtonText: "Si",cancelButtonText:"No"}). then(function (result) { if (result) { //pageData.set("login_status", "Login"); isLogged = 0; appSettings.remove("username"); appSettings.remove("password"); appSettings.setNumber("mytiluse", 0); //dialog.alert({ title: "", message: "Disconnesso!", okButtonText: "OK" }); pageData.frame.navigate("home/home-page"); } }) } };
<reponame>cuczhangyi/engineercms function LoadMxDrawX(dwgfile,cabpath,msipath) { var s, classid, Sys = {}, ua = navigator.userAgent.toLowerCase(); (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : (s = ua.match(/trident\/([\d.]+)/)) ? Sys.ie9 = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0, classid = "74A777F8-7A8F-4e7c-AF47-7074828086E2", Sys.ie || Sys.ie9 ? (document.write("<!-- 用来产生编辑状态的ActiveX控件的JS脚本--> "), document.write("<!-- 因为微软的ActiveX新机制,需要一个外部引入的js--> "), document.write('<object id="MxDrawXCtrl" classid="clsid:' + classid + '" '), //document.write('width="85%" height="85%" align="left"> '), document.write('codebase=" ' + cabpath + 'width="100%" height="100%" align="left">'), document.write('<param name="_Version" value="65536"> '), document.write('<param name="_ExtentX" value="24262"> '), document.write('<param name="_ExtentY" value="16219"> '), document.write('<param name="_StockProps" value="0">'), document.write('<param name="DwgFilePath" value="' + dwgfile + '" > '), document.write('<param name="IsRuningAtIE" value="1">'), document.write('<param name="EnablePrintCmd" value="1"> '), document.write('<param name="ShowCommandWindow" value="1"> '), document.write('<param name="ShowToolBars" value="1"> '), document.write('<param name="ShowModelBar" value="1">'), document.write('<param name="Iniset" value=""> '), document.write('<param name="ToolBarFiles" value="">'), document.write('<param name="ShowMenuBar" value="1">'), document.write('<param name="EnableUndo" value="1">'), // document.write('<param name="ShowPropertyWindow" value="1">'), document.write('<SPAN STYLE="color:red">不能装载文档控件。请在检查浏览器的选项中检查浏览器的安全设置。请点击<a href=' + msipath + '>安装控件</a></SPAN>'), document.write('</object>')) : Sys.chrome ? (document.write('<object id="MxDrawXCtrl" clsid="{' + classid + '}" '), document.write('type="application/mxdraw-activex" width="100%" height="100%" align="left" '), document.write('<param name="_Version" value="65536"> '), document.write('<param name="_ExtentX" value="24262"> '), document.write('<param name="_ExtentY" value="16219"> '), document.write('<param name="_StockProps" value="0">'), document.write('<param name="DwgFilePath" value="' + dwgfile + '" > '), document.write('<param name="IsRuningAtIE" value="1">'), document.write('<param name="EnablePrintCmd" value="1"> '), document.write('<param name="ShowCommandWindow" value="1"> '), document.write('<param name="ShowToolBars" value="1"> '), document.write('<param name="ShowModelBar" value="1">'), document.write('<param name="Iniset" value=""> '), document.write('<param name="ToolBarFiles" value="">'), document.write('<param name="ShowMenuBar" value="1">'), document.write('<param name="EnableUndo" value="1">'), document.write('<param name="ShowPropertyWindow" value="1">'), document.write('<param name="Event_ImplementCommandEvent" value="DoCommandEventFunc">'), document.write('<SPAN STYLE="color:red">chrome不能装载文档控件。请在检查浏览器的选项中检查浏览器的安全设置。请点击<a href=' + msipath + '>安装控件</a></SPAN>'), document.write('</object>')) : Sys.firefox ? (document.write("<!-- 需要安装ieTab插件才能使用--> "), document.write("<!-- 右键弹出菜单,点击使用ieTab浏览> --> "), document.write('<div class="no_title"> 不能装载文档控件。1.请在安装ieTab插件,2.然后请点击<a href=' + msipath + '>安装控件</a>, 3.然后右键弹出菜单,点击使用ieTab浏览 </div> ') ) : Sys.opera ? alert("sorry,ntko 暂时不支持opera!") : Sys.safari && alert("sorry,ntko 暂时不支持safari!"); } function isFireFox() { var s, classid, Sys = {}, ua = navigator.userAgent.toLowerCase(); (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : (s = ua.match(/trident\/([\d.]+)/)) ? Sys.ie9 = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0; return Sys.firefox; }
#!/usr/bin/env bash PY="/usr/bin/python3" PP="/usr/bin/pip3" DC="/usr/bin/docker" function check { echo "Checking the need command for library ..." CMD=($PY $DC $PP) for i in "${CMD[@]}" do if [ -e "${i}" ] then echo "${i} ... OK" else echo "${i} ... FAILED" echo "${i} command not found" exit fi done echo "DONE" } function template { echo "Installing docker emulate models..." ARRAY=( "vsdn/flowvisor" "vsdn/host" "vsdn/onos" "vsdn/openvirtex" "vsdn/whitebox" ) for i in ${ARRAY[@]}; do echo "* Downloading model ${i}" $DC pull ${i}:latest echo "Created" done echo "DONE" } function library { SUDO="/usr/bin/sudo" echo "Installing vSDNAgent python library ..." ${SUDO} ${PP} install . &> /dev/null if [ $? -ne 0 ] then echo "Cannot install library " exit fi echo "DONE" } function all { check template library } case $1 in check) check ;; template) template ;; library) library ;; all) all ;; *) echo "option not found" echo "please use the following options:" echo " [check] --------- for checking command necessaries." echo " [template] ------ for installing devices docker." echo " [library] ------- for installing only library." echo " [all] ----------- for executing all options before" esac
# setup history options HISTFILE=~/.histfile HISTSIZE=10000 SAVEHIST=10000 setopt appendhistory setopt histignoredups setopt histignorespace
#!/bin/bash # # -D BOOST_ROOT=/opt/android/boost_1_67_0 set -e orig_path=$PATH base_dir=`pwd` build_type=release # or debug archs=(arm arm64 x86 x86_64) #archs=(x86) for arch in ${archs[@]}; do ldflags="" case ${arch} in "arm") target_host=arm-linux-androideabi ldflags="-march=armv7-a -Wl,--fix-cortex-a8" xarch=armv7-a sixtyfour=OFF ;; "arm64") target_host=aarch64-linux-android xarch="armv8-a" sixtyfour=ON ;; "x86") target_host=i686-linux-android xarch="i686" ;; "x86_64") target_host=x86_64-linux-android xarch="x86-64" sixtyfour=ON ;; *) exit 16 ;; esac OUTPUT_DIR=$base_dir/build/$build_type.$arch mkdir -p $OUTPUT_DIR cd $OUTPUT_DIR PATH=/opt/android/tool/$arch/$target_host/bin:/opt/android/tool/$arch/bin:$PATH CC=clang CXX=clang++ cmake -D BUILD_GUI_DEPS=1 -D BUILD_TESTS=OFF -D ARCH="$xarch" -D STATIC=ON -D BUILD_64=$sixtyfour -D CMAKE_BUILD_TYPE=$build_type -D ANDROID=true -D BUILD_TAG="android" -D BOOST_ROOT=/opt/android/build/boost/$arch -D BOOST_LIBRARYDIR=/opt/android/build/boost/$arch/lib -D OPENSSL_INCLUDE_DIR=/opt/android/build/openssl/include OPENSSL_ROOT_DIR=/opt/android/build/openssl/$arch -D OPENSSL_CRYPTO_LIBRARY=/opt/android/build/openssl/$arch/lib/libcrypto.so -D OPENSSL_SSL_LIBRARY=/opt/android/build/openssl/$arch/lib/libssl.so -D CMAKE_POSITION_INDEPENDENT_CODE:BOOL=true ../.. make -j2 wallet_api find . -path ./lib -prune -o -name '*.a' -exec cp '{}' lib \; TARGET_LIB_DIR=/opt/android/build/amity/$arch/lib rm -rf $TARGET_LIB_DIR mkdir -p $TARGET_LIB_DIR cp $OUTPUT_DIR/lib/*.a $TARGET_LIB_DIR TARGET_INC_DIR=/opt/android/build/amity/include rm -rf $TARGET_INC_DIR mkdir -p $TARGET_INC_DIR cp -a ../../src/wallet/api/wallet2_api.h $TARGET_INC_DIR cd $base_dir done exit 0
<filename>tests/read_log.py # -*- coding: utf-8 -*- """ Created on Fri Feb 5 10:54:25 2021 @author: <NAME> """ import os import pandas as pd import readers.log_reader as lr def read_log_test(): # Event log reading column_names = {'Case ID': 'caseid', 'Activity': 'task', 'lifecycle:transition': 'event_type', 'Resource': 'user'} settings = {'timeformat': '%Y-%m-%dT%H:%M:%S.%f', 'column_names': column_names, 'one_timestamp': False, 'filter_d_attrib': True} log = lr.LogReader(os.path.join('tests', 'fixtures', 'repairExample_modified.xes'), settings) df = pd.DataFrame(log.data) print(df[df.caseid=='1'])
<reponame>gcusnieux/jooby package parser; import org.jooby.Jooby; public class MvcApp extends Jooby { { use(MvcRoutes.class); } }
from setuptools import setup long_description = "" setup( name="aiomultiprocessing", version="0.1", scripts=[], packages=['aiomultiprocessing'], author="<NAME>", author_email="<EMAIL>", long_description=long_description, description='n/a', license="Expat", url="http://pault.ag/", platforms=['any'], entry_points={ 'console_scripts': [ 'dionysus = dionysus.cli:main', ], } )
/* CHALLENGE Given a two strings, write an algorithm to check if they are anagrams of each other. Return true if the pass the test and false if they don't. E.g isAnagram('silent', 'listen') // should return true */ function isAnagram(stringA, stringB) { // Code goes here } module.exports = isAnagram
package narwhalfire.fucket.item; import net.minecraft.item.Item; /** * Base class for fuckets. */ public abstract class FucketBase extends Item { //todo: need to add capabilities to fuckets }
import cgi, cgitb import sendEmailController as sendEmail import ProductAccessMysql as ProductAccess import generateEmailDetails cgitb.enable() def getOrderFromDatabase(self): orderlist = self.listOfOrders self.listbox.delete(0,tk.END) for order in orderlist: self.after(0, self.listbox_insert,order[0] +' - '+ str(order[1]) +' - '+ str(order[2]) +' - '+ order[3] +' - '+ order[4] ) return orderlist print("Content-type: text/html\n\n ") print("<html><head><title><NAME></title></head>") print("<body><h1><NAME>") for b in orderlist: print("<h2>"+b+"</h2>") print("</h1></body>") print("</html> ")
#!/bin/sh export GPU_ID=$1 echo $GPU_ID cd .. export DATASET_DIR="datasets/" export CUDA_VISIBLE_DEVICES=$GPU_ID # Activate the relevant virtual environment: python train_continual_learning_few_shot_system.py --name_of_args_json_file experiment_config/omniglot_variant_SCA_5_way_1_maml++_high-end_shot_preds_True_5_1_LSLR_conditioned_0.json --gpu_to_use $GPU_ID
def findDuplicates_Optimized(arr): duplicates = set() seen = set() for num in arr: if num not in seen: seen.add(num) else: duplicates.add(num) return list(duplicates)
#!/bin/bash # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. set -xeuo pipefail ( export sleep 2; if [[ -v POST_BOOTSTRAP_COMMAND ]]; then bash -c "$POST_BOOTSTRAP_COMMAND" fi ) & exec "$@"
import { RouteItemConfig } from '@/types/app'; import AboutRoute from './about'; import ChartsRoute from './charts'; import TableRoute from './table'; import UserRoute from './user'; import exceptionRoute from './exception'; const Route: RouteItemConfig[] = [AboutRoute, ChartsRoute, TableRoute, UserRoute, exceptionRoute]; export const getFlatRoutes = () => { const tempRoutes: RouteItemConfig[] = []; const FlatRoutes = (routes: RouteItemConfig[], parentPath = '/') => { routes.forEach(item => { tempRoutes.push({ ...item, path: `${parentPath}${item.path}`, }); if (item.children) { FlatRoutes(item.children, `${parentPath}${item.path}/`); } }); }; FlatRoutes(Route); return tempRoutes; }; export default Route;
// setup file import { configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; // configure enzyme-adapter-react for test purposes configure({ adapter: new Adapter(), });
# import datetime import datetime # define datetime object date = datetime.datetime(2020, 4, 22) # convert datetime to string date_str = date.strftime('%Y-%m-%d') # print string print('Date in string format:', date_str)
/* * Copyright 2013 Square Inc. * * 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 com.squareup.wire; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.annotation.Nullable; /** * Converts values of an enum to and from integers using reflection. */ final class RuntimeEnumAdapter<E extends WireEnum> extends EnumAdapter<E> { private final Class<E> type; private @Nullable Method fromValueMethod; // Lazy to avoid reflection during class loading. RuntimeEnumAdapter(Class<E> type) { super(type); this.type = type; } private Method getFromValueMethod() { Method method = this.fromValueMethod; if (method != null) { return method; } try { return fromValueMethod = type.getMethod("fromValue", int.class); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } @Override protected E fromValue(int value) { E constant; try { //noinspection unchecked constant = (E) getFromValueMethod().invoke(null, value); } catch (IllegalAccessException | InvocationTargetException e) { throw new AssertionError(e); } return constant; } @Override public boolean equals(Object o) { return o instanceof RuntimeEnumAdapter && ((RuntimeEnumAdapter) o).type == type; } @Override public int hashCode() { return type.hashCode(); } }
//required modules const router = require("express").Router(); const { User, Property, Location } = require("../models"); const auth = require("../utils/auth"); //the information for all properties router.get("/", auth, async (req, res) => { try { const propertyData = await Property.findAll({ where: { user_id: req.session.user_id, }, attributes: [ "id", "image", "address", "list_price", "beds", "baths", "garage", "stories", "home_type", "sqft", "year_built", ], include: [ { model: User, attributes: ["username"], }, ], }); //map over those properties and render display const properties = propertyData.map((property) => property.get({ plain: true }) ); res.render("saved-properties", { properties, loggedIn: req.session.loggedIn, layout: "dashboard.handlebars", }); } catch (err) { console.log(err); res.status(500).json(err); } }); //route to get the search form router.get("/search", (req, res) => { res.render("search"); }); //route to get the searched homes (not used at the moment) router.get("/searched", auth, (req, res) => { res.render("searched-homes"); }); module.exports = router;
class BankAccount: def __init__(self, account_holder): self.account_holder = account_holder self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount <= self.balance: self.balance -= amount else: print("Insufficient funds") def check_balance(self): return self.balance def display_info(self): print(f"Account Holder: {self.account_holder}") print(f"Account Balance: {self.balance}") # Example usage account1 = BankAccount("John Doe") account1.deposit(1000) account1.display_info() # Output: Account Holder: John Doe, Account Balance: 1000 account1.withdraw(500) account1.display_info() # Output: Account Holder: John Doe, Account Balance: 500 account1.withdraw(1000) # Output: Insufficient funds
/* * Copyright © 2020 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ import { createApplication, closeApplication } from '../utils/application'; import { Application } from '../../../src'; describe('Block related actions', () => { let app: Application; beforeAll(async () => { app = await createApplication('actions-blocks'); }); afterAll(async () => { await closeApplication(app); }); describe('getBlockByID', () => { it('should return valid encoded block', async () => { const expectedBlock = app['_node']['_chain'].lastBlock; const encodedBlock = await app['_channel'].invoke('app:getBlockByID', { id: expectedBlock.header.id.toString('hex'), }); expect(encodedBlock).toBeString(); const block = app['_node']['_chain'].dataAccess.decode( Buffer.from(encodedBlock as string, 'hex'), ); expect(block.header.version).toEqual(expectedBlock.header.version); expect(block.header.height).toEqual(expectedBlock.header.height); }); }); describe('getBlocksByIDs', () => { it('should return valid encoded blocks', async () => { const expectedBlock = app['_node']['_chain'].lastBlock; const encodedBlocks: string[] = await app['_channel'].invoke('app:getBlocksByIDs', { ids: [expectedBlock.header.id.toString('hex')], }); expect(encodedBlocks).toHaveLength(1); const block = app['_node']['_chain'].dataAccess.decode(Buffer.from(encodedBlocks[0], 'hex')); expect(block.header.version).toEqual(expectedBlock.header.version); expect(block.header.height).toEqual(expectedBlock.header.height); }); }); describe('getBlockByHeight', () => { it('should return valid encoded block', async () => { const encodedBlock = await app['_channel'].invoke('app:getBlockByHeight', { height: 2 }); expect(encodedBlock).toBeString(); const block = app['_node']['_chain'].dataAccess.decode( Buffer.from(encodedBlock as string, 'hex'), ); expect(block.header.height).toEqual(2); }); }); describe('getBlocksByHeightBetween', () => { it('should return valid encoded blocks', async () => { const encodedBlocks: string[] = await app['_channel'].invoke('app:getBlocksByHeightBetween', { from: 1, to: 2, }); expect(encodedBlocks).toHaveLength(2); const block = app['_node']['_chain'].dataAccess.decode(Buffer.from(encodedBlocks[0], 'hex')); expect(block.header.height).toEqual(2); }); }); });
import java.util.Arrays; public class Example { public static void main(String[] args) { // Initialize two arrays int[] array1 = {1, 2, 3, 5, 7, 8}; int[] array2 = {2, 3, 5, 6, 8, 9}; // Find the length of both the arrays int length1 = array1.length; int length2 = array2.length; // Initialize an empty array to store the common elements int[] result = new int[length1]; // Iterate through both arrays and check for common elements int k = 0; for (int i = 0; i < length1; i++) { for (int j = 0; j < length2; j++) { if (array1[i] == array2[j]) result[k++] = array1[i]; } } // Print the resulting array System.out.println(Arrays.toString(result)); } }
/* * The MIT License (MIT) * * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.elbauldelprogramador.movementsound; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; /** * Created by: * * <NAME> (elbauldelprogramador.com) * <NAME> * * on 2/9/16. * * This file is part of MovementSound */ public class MainActivity extends AppCompatActivity implements SensorEventListener { /** * Constants for sensors */ private static final float SHAKE_THRESHOLD = 1.1f; private static final int SHAKE_WAIT_TIME_MS = 250; private static final float ROTATION_THRESHOLD = 2.0f; private static final int ROTATION_WAIT_TIME_MS = 100; /** * The sounds to play when a pattern is detected */ private static MediaPlayer soundAcc; private static MediaPlayer soundGyro; /** * Sensors */ private SensorManager mSensorManager; private Sensor mSensorAcc; private Sensor mSensorGyr; private long mShakeTime = 0; private long mRotationTime = 0; /** * UI */ private TextView mGyrox; private TextView mGyroy; private TextView mGyroz; private TextView mAccx; private TextView mAccy; private TextView mAccz; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get the sensors to use mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mSensorAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorGyr = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); // Instanciate the sound to use soundAcc = MediaPlayer.create(this, R.raw.acc); soundGyro = MediaPlayer.create(this, R.raw.gyro); mGyrox = (TextView) findViewById(R.id.gyro_x); mGyroy = (TextView) findViewById(R.id.gyro_y); mGyroz = (TextView) findViewById(R.id.gyro_z); mAccx = (TextView) findViewById(R.id.accele_x); mAccy = (TextView) findViewById(R.id.accele_y); mAccz = (TextView) findViewById(R.id.accele_z); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mSensorAcc, SensorManager.SENSOR_DELAY_NORMAL); mSensorManager.registerListener(this, mSensorGyr, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } @Override public void onSensorChanged(SensorEvent event) { if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { mAccx.setText(R.string.act_main_no_acuracy); mAccy.setText(R.string.act_main_no_acuracy); mAccz.setText(R.string.act_main_no_acuracy); } else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) { mGyrox.setText(R.string.act_main_no_acuracy); mGyroy.setText(R.string.act_main_no_acuracy); mGyroz.setText(R.string.act_main_no_acuracy); } return; } if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { mAccx.setText("x = " + Float.toString(event.values[0])); mAccy.setText("y = " + Float.toString(event.values[1])); mAccz.setText("z = " + Float.toString(event.values[2])); detectShake(event); } else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) { mGyrox.setText("x = " + Float.toString(event.values[0])); mGyroy.setText("y = " + Float.toString(event.values[1])); mGyroz.setText("z = " + Float.toString(event.values[2])); detectRotation(event); } } // References: // - http://jasonmcreynolds.com/?p=388 // - http://code.tutsplus.com/tutorials/using-the-accelerometer-on-android--mobile-22125 /** * Detect a shake based on the ACCELEROMETER sensor * * @param event */ private void detectShake(SensorEvent event) { long now = System.currentTimeMillis(); if ((now - mShakeTime) > SHAKE_WAIT_TIME_MS) { mShakeTime = now; float gX = event.values[0] / SensorManager.GRAVITY_EARTH; float gY = event.values[1] / SensorManager.GRAVITY_EARTH; float gZ = event.values[2] / SensorManager.GRAVITY_EARTH; // gForce will be close to 1 when there is no movement double gForce = Math.sqrt(gX * gX + gY * gY + gZ * gZ); // Change background color if gForce exceeds threshold; // otherwise, reset the color if (gForce > SHAKE_THRESHOLD) { soundAcc.start(); } } } /** * Detect a rotation in on the GYROSCOPE sensor * * @param event */ private void detectRotation(SensorEvent event) { long now = System.currentTimeMillis(); if ((now - mRotationTime) > ROTATION_WAIT_TIME_MS) { mRotationTime = now; // Change background color if rate of rotation around any // axis and in any direction exceeds threshold; // otherwise, reset the color if (Math.abs(event.values[0]) > ROTATION_THRESHOLD || Math.abs(event.values[1]) > ROTATION_THRESHOLD || Math.abs(event.values[2]) > ROTATION_THRESHOLD) { soundGyro.start(); } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
#include <iostream> int main() { int count = 0; int n = 100; count = (n * (n + 1)) / 2; std::cout<<count<<std::endl; return 0; }
<reponame>netosha/ton-dex-contest<filename>lint-staged.config.js module.exports = { '*.{js,jsx,ts,tsx}': ['eslint --fix', 'eslint'], '**/*.ts?(x)': () => 'tsc --noEmit --pretty', '*.json': ['prettier --write'], '**/*.{css,scss}': [ 'stylelint "**/*.{css,scss}" --fix', 'prettier --write', 'stylelint "**/*.{css,scss}"', ], };
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; interface Product { // Define the structure of a product id: number; name: string; price: number; // Add any other relevant fields } @Injectable() export class ProductService { private apiUrl = 'http://localhost:8080/products'; constructor(private http: Http) { } findAll(): Observable<Product[]> { return this.http.get(`${this.apiUrl}/getAllProducts`) .pipe( map((res: Response) => res.json()) ); } }
<filename>app/src/main/java/org/jf/dexlib2/analysis/OdexedFieldInstructionMapper.java /* * Copyright 2013, Google 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 Google Inc. 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 org.jf.dexlib2.analysis; import org.jf.dexlib2.*; import javax.annotation.*; public class OdexedFieldInstructionMapper { private static Opcode[][][][] opcodeMap = new Opcode[][][][]{ //get opcodes new Opcode[][][]{ //iget quick new Opcode[][]{ //odexed new Opcode[]{ /*Z*/ Opcode.IGET_QUICK, /*B*/ Opcode.IGET_QUICK, /*S*/ Opcode.IGET_QUICK, /*C*/ Opcode.IGET_QUICK, /*I,F*/ Opcode.IGET_QUICK, /*J,D*/ Opcode.IGET_WIDE_QUICK, /*L,[*/ Opcode.IGET_OBJECT_QUICK }, //deodexed new Opcode[]{ /*Z*/ Opcode.IGET_BOOLEAN, /*B*/ Opcode.IGET_BYTE, /*S*/ Opcode.IGET_SHORT, /*C*/ Opcode.IGET_CHAR, /*I,F*/ Opcode.IGET, /*J,D*/ Opcode.IGET_WIDE, /*L,[*/ Opcode.IGET_OBJECT } }, //iget volatile new Opcode[][]{ //odexed new Opcode[]{ /*Z*/ Opcode.IGET_VOLATILE, /*B*/ Opcode.IGET_VOLATILE, /*S*/ Opcode.IGET_VOLATILE, /*C*/ Opcode.IGET_VOLATILE, /*I,F*/ Opcode.IGET_VOLATILE, /*J,D*/ Opcode.IGET_WIDE_VOLATILE, /*L,[*/ Opcode.IGET_OBJECT_VOLATILE }, //deodexed new Opcode[]{ /*Z*/ Opcode.IGET_BOOLEAN, /*B*/ Opcode.IGET_BYTE, /*S*/ Opcode.IGET_SHORT, /*C*/ Opcode.IGET_CHAR, /*I,F*/ Opcode.IGET, /*J,D*/ Opcode.IGET_WIDE, /*L,[*/ Opcode.IGET_OBJECT } }, //sget volatile new Opcode[][]{ //odexed new Opcode[]{ /*Z*/ Opcode.SGET_VOLATILE, /*B*/ Opcode.SGET_VOLATILE, /*S*/ Opcode.SGET_VOLATILE, /*C*/ Opcode.SGET_VOLATILE, /*I,F*/ Opcode.SGET_VOLATILE, /*J,D*/ Opcode.SGET_WIDE_VOLATILE, /*L,[*/ Opcode.SGET_OBJECT_VOLATILE }, //deodexed new Opcode[]{ /*Z*/ Opcode.SGET_BOOLEAN, /*B*/ Opcode.SGET_BYTE, /*S*/ Opcode.SGET_SHORT, /*C*/ Opcode.SGET_CHAR, /*I,F*/ Opcode.SGET, /*J,D*/ Opcode.SGET_WIDE, /*L,[*/ Opcode.SGET_OBJECT } } }, //put opcodes new Opcode[][][]{ //iput quick new Opcode[][]{ //odexed new Opcode[]{ /*Z*/ Opcode.IPUT_QUICK, /*B*/ Opcode.IPUT_QUICK, /*S*/ Opcode.IPUT_QUICK, /*C*/ Opcode.IPUT_QUICK, /*I,F*/ Opcode.IPUT_QUICK, /*J,D*/ Opcode.IPUT_WIDE_QUICK, /*L,[*/ Opcode.IPUT_OBJECT_QUICK }, //deodexed new Opcode[]{ /*Z*/ Opcode.IPUT_BOOLEAN, /*B*/ Opcode.IPUT_BYTE, /*S*/ Opcode.IPUT_SHORT, /*C*/ Opcode.IPUT_CHAR, /*I,F*/ Opcode.IPUT, /*J,D*/ Opcode.IPUT_WIDE, /*L,[*/ Opcode.IPUT_OBJECT } }, //iput volatile new Opcode[][]{ //odexed new Opcode[]{ /*Z*/ Opcode.IPUT_VOLATILE, /*B*/ Opcode.IPUT_VOLATILE, /*S*/ Opcode.IPUT_VOLATILE, /*C*/ Opcode.IPUT_VOLATILE, /*I,F*/ Opcode.IPUT_VOLATILE, /*J,D*/ Opcode.IPUT_WIDE_VOLATILE, /*L,[*/ Opcode.IPUT_OBJECT_VOLATILE }, //deodexed new Opcode[]{ /*Z*/ Opcode.IPUT_BOOLEAN, /*B*/ Opcode.IPUT_BYTE, /*S*/ Opcode.IPUT_SHORT, /*C*/ Opcode.IPUT_CHAR, /*I,F*/ Opcode.IPUT, /*J,D*/ Opcode.IPUT_WIDE, /*L,[*/ Opcode.IPUT_OBJECT } }, //sput volatile new Opcode[][]{ //odexed new Opcode[]{ /*Z*/ Opcode.SPUT_VOLATILE, /*B*/ Opcode.SPUT_VOLATILE, /*S*/ Opcode.SPUT_VOLATILE, /*C*/ Opcode.SPUT_VOLATILE, /*I,F*/ Opcode.SPUT_VOLATILE, /*J,D*/ Opcode.SPUT_WIDE_VOLATILE, /*L,[*/ Opcode.SPUT_OBJECT_VOLATILE }, //deodexed new Opcode[]{ /*Z*/ Opcode.SPUT_BOOLEAN, /*B*/ Opcode.SPUT_BYTE, /*S*/ Opcode.SPUT_SHORT, /*C*/ Opcode.SPUT_CHAR, /*I,F*/ Opcode.SPUT, /*J,D*/ Opcode.SPUT_WIDE, /*L,[*/ Opcode.SPUT_OBJECT } } } }; private static int getTypeIndex(char type) { switch (type) { case 'Z': return 0; case 'B': return 1; case 'S': return 2; case 'C': return 3; case 'I': case 'F': return 4; case 'J': case 'D': return 5; case 'L': case '[': return 6; default: } throw new RuntimeException(String.format("Unknown type %s: ", type)); } private static int getOpcodeSubtype(@Nonnull Opcode opcode) { if (opcode.isOdexedInstanceQuick()) { return 0; } else if (opcode.isOdexedInstanceVolatile()) { return 1; } else if (opcode.isOdexedStaticVolatile()) { return 2; } throw new RuntimeException(String.format("Not an odexed field access opcode: %s", opcode.name)); } @Nonnull static Opcode getAndCheckDeodexedOpcodeForOdexedOpcode(@Nonnull String fieldType, @Nonnull Opcode odexedOpcode) { int opcodeType = odexedOpcode.setsRegister() ? 0 : 1; int opcodeSubType = getOpcodeSubtype(odexedOpcode); int typeIndex = getTypeIndex(fieldType.charAt(0)); Opcode correctOdexedOpcode, deodexedOpcode; correctOdexedOpcode = opcodeMap[opcodeType][opcodeSubType][0][typeIndex]; deodexedOpcode = opcodeMap[opcodeType][opcodeSubType][1][typeIndex]; if (correctOdexedOpcode != odexedOpcode) { throw new AnalysisException(String.format("Incorrect field type \"%s\" for %s", fieldType, odexedOpcode.name)); } return deodexedOpcode; } }
<filename>server/users/settings/location/update.js // Save user location // 'use strict'; module.exports = function (N, apiPath) { N.validate(apiPath, { latitude: { type: 'number', minimum: -90, maximum: 90 }, longitude: { type: 'number', minimum: -180, maximum: 180 } }); // Check permissions // N.wire.before(apiPath, async function check_permissions(env) { if (!env.user_info.is_member) { throw N.io.FORBIDDEN; } let can_edit_profile = await env.extras.settings.fetch('can_edit_profile'); if (!can_edit_profile) { throw N.io.FORBIDDEN; } }); // Fetch current user // N.wire.before(apiPath, async function fetch_user(env) { env.data.user = await N.models.users.User.findById(env.user_info.user_id); if (!env.data.user) throw N.io.NOT_FOUND; }); // Save location // N.wire.on(apiPath, async function save_location(env) { env.data.user.location = [ env.params.longitude, env.params.latitude ]; await env.data.user.save(); // trigger location name resolution with priority, // so user will see their own location name on other pages quicker N.models.users.User.resolveLocation(env.data.user._id, env.user_info.locale); }); };
/* * $Id$ * * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.opoo.oqs.dialect; /** * A SQL dialect for Oracle 9 (uses ANSI-style syntax where possible). * */ public class Oracle9Dialect extends AbstractDialect { public Oracle9Dialect() { super(); } public boolean supportsLimit() { return true; } public String getLimitString(String sql, boolean hasOffset) { sql = sql.trim(); boolean isForUpdate = false; if (sql.toLowerCase().endsWith(" for update")) { sql = sql.substring(0, sql.length() - 11); isForUpdate = true; } StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); if (hasOffset) { pagingSelect.append( "select * from ( select row_.*, rownum rownum_ from ( "); } else { pagingSelect.append("select * from ( "); } pagingSelect.append(sql); if (hasOffset) { pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?"); } else { pagingSelect.append(" ) where rownum <= ?"); } if (isForUpdate) { pagingSelect.append(" for update"); } return pagingSelect.toString(); } public boolean bindLimitParametersInReverseOrder() { return true; } public boolean useMaxForLimit() { return true; } public boolean forUpdateOfColumns() { return true; } public String getQuerySequencesString() { return "select sequence_name from user_sequences"; } public String getSelectGUIDString() { return "select rawtohex(sys_guid()) from dual"; } }
def is_convex_hull(nodes, hull): def orientation(p, q, r): val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) if val == 0: return 0 # collinear return 1 if val > 0 else 2 # clockwise or counterclockwise def is_convex(nodes, hull): n = len(nodes) if n < 3: return True prev_orientation = 0 for i in range(n): p = nodes[hull[i % n]] q = nodes[hull[(i + 1) % n]] r = nodes[hull[(i + 2) % n]] o = orientation(p, q, r) if o == 0: continue if prev_orientation == 0: prev_orientation = o elif prev_orientation != o: return False return True return is_convex(nodes, hull)
require File.join(File.dirname(__FILE__), 'base_kde_formula') class Akonadi < BaseKdeFormula homepage 'http://pim.kde.org/akonadi/' url 'http://download.kde.org/stable/akonadi/src/akonadi-1.13.0.tar.bz2' sha1 '9d594b5840e2e5d90057a7e5d8545004a3476bc0' depends_on 'shared-mime-info' depends_on 'mysql' depends_on 'soprano' depends_on 'boost' depends_on 'qt' => ["with-d-bus", "with-qt3support"] kde_build_deps #def patches # {:p0 => [ # "http://bugsfiles.kde.org/attachment.cgi?id=69519" # ]} #end end
const Discord = require('discord.js') const moment = require('moment') let request, response request = require('async-request') module.exports = { name: 'serverstatus', description: 'Fetches server status', aliases: ['server','serverstatus',], async execute (message, args) { try { // Store which server to find the status of let outputName = "Main Server Status" let serverip = "elkia.life" let outputIcon = "https://i.imgur.com/M26k7kA.png" if (args[0] == "penguin") { serverip = "penguin.elkia.life" outputIcon = "https://i.imgur.com/i99HmIl.png" outputName = "Penguin Server Status" } // Find server Status response = await request(`https://mcapi.us/server/status?ip=${serverip}`) const {online, players, server, last_updated} = JSON.parse(response.body) let outputOnline, outputLastOnline if (online) { outputOnline = ":white_check_mark: Online" } else { outputOnline = ":x: Offline" } // Output let logMessage = new Discord.RichEmbed() .setTitle(outputName) .setThumbnail(outputIcon) .setColor(0x00AAAA) .setDescription(`Status: ${outputOnline}\nPlayers: ${players.now} / ${players.max}\nVersion: ${server.name}`) .setFooter(`Last Checked: ${moment(Number(last_updated) * 1000).startOf('second').fromNow()}`) message.channel.send(message.client.eris.getRandomMessage('serverStatusCommand', online), logMessage) } catch (e) { let logMessage = new Discord.RichEmbed() .setTitle('Server Status Error:') .setColor(0xAA00AA) .setDescription(e) message.channel.send(message.client.eris.getRandomMessage('serverStatusCommand', 'error'), logMessage) } } }
#!/bin/bash ########################################################################### # # Copyright 2017 Samsung Electronics All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. # ########################################################################### # apps/tools/mkkconfig.sh # # Copyright (C) 2015 Gregory Nutt. All rights reserved. # Author: Gregory Nutt <gnutt@nuttx.org> # # 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 NuttX 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. # # Get the input parameter list USAGE () { echo "USAGE: mkkconfig.sh [-d] [-h] [-m <menu>] [-o <kconfig-file>]" echo "Where:" echo " <-d>:" echo " Enables debug output" echo " -m <menu>:" echo " Menu description" echo " -o <kconfig-file>:" echo " Identifies the specific configuratin for the selected <board-name>." echo " This must correspond to a sub-directory under the board directory at" echo " under build/configs/<board-name>/." echo " <-h>:" echo " Prints this message and exits." } KCONFIG=Kconfig unset MENU while [ ! -z "$1" ]; do case $1 in -d ) set -x ;; -m ) shift MENU=$1 ;; -o ) shift KCONFIG=$1 ;; -h ) USAGE exit 0 ;; * ) echo "ERROR: Unrecognized argument: $1" USAGE exit 1 ;; esac shift done if [ -f ${KCONFIG} ]; then rm ${KCONFIG} || { echo "ERROR: Failed to remove $PWD/${KCONFIG}"; exit 1; } fi echo mkkconfig in $PWD KCONFIG_LIST=`find $PWD -mindepth 2 -maxdepth 2 -name ${KCONFIG} | sort -n` echo "#" > ${KCONFIG} echo "# For a description of the syntax of this configuration file," >> ${KCONFIG} echo "# see kconfig-language at https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt" >> ${KCONFIG} echo "#" >> ${KCONFIG} echo "# This file is autogenerated, do not edit." >> ${KCONFIG} echo "#" >> ${KCONFIG} echo "" >> ${KCONFIG} if [ ! -z "${MENU}" ]; then echo "menu \"${MENU}\"" >> ${KCONFIG} fi for FILE in ${KCONFIG_LIST}; do echo "source \"${FILE}\"" >> ${KCONFIG} done if [ ! -z "${MENU}" ]; then echo "endmenu # ${MENU}" >> ${KCONFIG} fi
# -*- coding: utf-8 -*- class TagsParam(): def _validate_tags(self): if self.tags is not None: used = set() self.tags = ",".join([x.strip() for x in self.tags.split(',') if x.strip() and x not in used and (used.add(x) or True)]) if not self.tags: return False, 'tags value is empty' return True, None
require File.expand_path(File.dirname(__FILE__) + "/../init.rb") require 'spec' # require 'rubygems' # require 'spec' # require File.join(File.dirname(__FILE__), 'lib')
#!/bin/bash set -e sudo add-apt-repository -y ppa:chris-lea/node.js sudo apt-get update sudo apt-get install -y riak nodejs sudo cp scripts/vagrant/app.config /etc/riak/app.config sudo service riak start mkdir -p userfiles pip install -r requirements.txt npm install export PATH=node_modules/.bin:$PATH cat >settings_local.py <<EOL DEBUG = False SECRET_KEY = "abcedfg" SITE_URL = "http://localhost:8800" EOL
<reponame>takakd/lambda-wrk2 #!/usr/bin/env node import path = require("path"); import "source-map-support/register"; import * as cdk from "@aws-cdk/core"; import {LambdaWrk2Service} from "../lib/lambda-wrk2-service"; // Validate environment variables. if (!process.env.AWS_STACK_NAME) { throw new Error('error AWS_STACK_NAME is undefined') } // Start creating Stack. const app = new cdk.App(); new LambdaWrk2Service(app, process.env.AWS_STACK_NAME, { dockerfilePath: path.join(__dirname, "../../wrk2-cmd/docker"), }); app.synth();
import { Injectable } from '@angular/core'; import { HalFormService } from '@hal-form-client'; import { Observable } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { SessionService } from './session.service'; @Injectable({ providedIn: 'root', }) export class AppInitializationService { constructor(private readonly halFormService: HalFormService, private readonly sessionService: SessionService) {} initialize(): Observable<unknown> { return this.halFormService.initialize().pipe(switchMap(() => this.sessionService.initialize())); } }
import { randomBytes, createCipheriv, createDecipheriv } from "crypto"; import logger from "./logger"; function Crypto(algorithm = "aes-256-ctr") { /** * Criptografa uma string. * @param {String} string Texto a ser criptografado. * @returns {Object} Retorna um objeto com a key 'error'. Caso error * seja 'false', os dados da criptografia virão juntos. Caso error seja * 'true', apenas essa key existirá. */ function enc(string) { try { const key = randomBytes(32); const iv = randomBytes(16); const cipher = createCipheriv(algorithm, key, iv); const encrypted = Buffer.concat([ cipher.update(string), cipher.final(), ]); return { error: false, hash: encrypted.toString("hex"), key, iv }; } catch (err) { logger.error(err.message); return { error: true }; } } /** * Descriptografa um hash. * @param {String} hash Hash a ser descriptografado. * @param {Buffer} key Chave de criptografia do hash. * @param {Buffer} iv IV do hash. * @returns {Object} Retorna um objeto com a key 'error'. Caso error * seja 'false', virá a 'string' com os dados descriptografados. * Caso error seja 'true', apenas essa key existirá. */ function dec({ hash, key, iv }) { try { const decipher = createDecipheriv( algorithm, key, Buffer.from(iv, "hex") ); const decrypted = Buffer.concat([ decipher.update(Buffer.from(hash, "hex")), decipher.final(), ]); return { error: false, result: decrypted.toString() }; } catch (err) { logger.error(err.message); return { error: true }; } } return { enc, dec }; } export default Crypto;
<filename>src/org/mocraft/NagatoKai/utils/Loc.java package org.mocraft.NagatoKai.utils; import org.mocraft.NagatoKai.Nagato; import org.sikuli.script.Location; import java.util.Random; public class Loc extends Nagato { private int width, height; private Location loc = new Location(0, 0); private String imgString = ""; public Loc(int w, int h, int x, int y, String s) { this.width = w - 4; this.height = h - 4; this.loc = new Location(x + 2, y + 2); this.imgString = s; } public int width() { return width; } public int height() { return height; } public Size regionSize() { return new Size(width + 8, height + 8); } public String img() { return imgString; } public Location regionLoc() { return new Location(loc.getX() + instance.zeroPoint.getX() - 4, loc.getY() + instance.zeroPoint.getY() - 4); } public Location topLeftLoc() { return new Location(loc.getX() + instance.zeroPoint.getX(), loc.getY() + instance.zeroPoint.getY()); } public Location centerLoc() { return new Location(instance.zeroPoint.getX() + loc.getX() + width / 2, instance.zeroPoint.getY() + loc.getY() + height / 2); } public Location randomLoc() { Random rand = new Random(); Location l = new Location( instance.zeroPoint.getX() + loc.getX() + rand.nextInt(width), instance.zeroPoint.getY() + loc.getY() + rand.nextInt(height) ); return l; } }
<reponame>oondeo/yett export const TYPE_ATTRIBUTE = 'javascript/blocked' export const jsonStringify = value => { return JSON.stringify(value,replacer,2) } export const jsonParse = value => { return JSON.parse(value,reviver) } export const patternsObj = { blacklist: null, whitelist: null } export const patterns = { blacklist: window.localStorage.YETT_BLACKLIST ? jsonParse(window.localStorage.YETT_BLACKLIST) : window.YETT_BLACKLIST, whitelist: window.localStorage.YETT_WHITELIST ? jsonParse(window.localStorage.YETT_WHITELIST) : window.YETT_WHITELIST, tags: [] } if (! (patterns.blacklist instanceof Array) && (patterns.blacklist instanceof Object)){ patternsObj.blacklist = patterns.blacklist; patterns.blacklist = Object.values(patternsObj.blacklist); } if (! (patterns.whitelist instanceof Array) && (patterns.whitelist instanceof Object)){ patternsObj.whitelist = patterns.whitelist; patterns.whitelist = Object.values(patternsObj.whitelist); } if (patterns.blacklist){ patterns.blacklist.forEach(element => { if (typeof element === 'string'){ const pos = element.indexOf('/') if (pos > 1) { const tag = element.substring(0,pos) if (tag.length > 1) patterns.tags.push(tag) } } }) } // Backup list containing the original blacklisted script elements export const backupScripts = { blacklisted: [] } export const blockNodeNoBackup = (node,blockingType,attribute) => { if(typeof blockingType === "string" && blockingType != "remove"){ let arr = blockingType.split(":") let type = 'src' let value = null if(arr.length < 1){ value = arr[0] }else{ type = arr[0] value = arr[1] } if(!type) type = 'src' if(type.startsWith('_backup_') || type == 'type' ) return false if (node['type'] != TYPE_ATTRIBUTE){ node['_backup_type'] = node['type'] node['type'] = TYPE_ATTRIBUTE } if (type == 'javascript'){ eval(value) }else{ node['_backup_'+type] = node[type] if (attribute === type) return value else node[type] = value } return true } return false } export const blockNode = (node,blockingType) => { const parent = node.parentElement if (!parent) return false backupScripts.blacklisted.push([node.cloneNode(true),parent]) if (blockingType === true || blockingType === 'remove'){ parent.removeChild(node) return true } return blockNodeNoBackup(node,blockingType) } function replacer(key, value) { if (value instanceof RegExp) return ("__REGEXP " + value.toString()); else return value; } function reviver(key, value) { if (value.toString().indexOf("__REGEXP ") == 0) { var m = value.split("__REGEXP ")[1].match(/\/(.*)\/(.*)?/); return new RegExp(m[1], m[2] || ""); } else return value; }
# frozen_string_literal: true module GithubAuthentication class GitCredentialHelper def initialize(pem:, installation_id:, app_id:, storage: nil, stdin: $stdin) @pem = pem @installation_id = installation_id @app_id = app_id @storage = storage @stdin = stdin end def handle_get description = parse_stdin unless description['protocol'] == 'https' && description['host'] == 'github.com' warn("Unsupported description: #{description}") return 2 end token = provider.token(seconds_ttl: min_cache_ttl) puts("password=#{token}") puts('username=api') 0 end private def min_cache_ttl # Tokens are valid for 60 minutes, allow a 10 minute buffer 10 * 60 end def parse_stdin # Credential description is written to STDIN in line delimited key=value form, # see https://git-scm.com/docs/git-credential#IOFMT @stdin.each_line.map { |line| line.split('=', 2).map(&:strip) }.to_h end def provider @provider ||= Provider.new( generator: generator, cache: Cache.new(storage: @storage || ObjectCache.new) ) end def generator @generator ||= Generator::App.new( pem: @pem, app_id: @app_id, installation_id: @installation_id ) end end end
#!/usr/bin/env bash # ###################### # ARGUMENTS HANDLING # ###################### print_help () { cat <<HELP USAGE install_gpg_all.sh <options> <component options> DESCRIPTION Installs a whole GnuPG suite. All arguments which are not recognized by this script are forwarded to install_gpg_component.sh script (<component options>). They must be specified after <options> (if any). EXAMPLES # Installing latest version of all GnuPG software install_gpg_component.sh --suite-version latest # Installing GnuPG 2.1 install_gpg_component.sh --suite-version 2.1 # Passing options to install_gpg_component.sh scripts install_gpg_component.sh --suite-version latest --sudo OPTIONS --suite-version VERSION Defines which version of GnuPG components should be installed. Default is "latest". Following values for VERSION are supported: "2.2" GnuPG 2.2, and matching dependencies. "2.1" GnuPG 2.1, and matching dependencies. "latest" Latest version of GnuPG, and its dependecies. Prefer "latest" over "2.2". "master" Install all GnuPG components from Git master branch. --help, -h Displays this message. HELP } set_default_options() { _arg_suite="latest" _arr_component_options=() } parse_cli_arguments() { while test $# -gt 0 do case "$1" in --suite-version) _arg_suite="$2" shift shift ;; -h|--help) print_help exit 0 ;; *) _arr_component_options=("${@}") break esac done } # Check to see if this file is being run or sourced from another script # See: https://unix.stackexchange.com/a/215279 is_sourced() { [[ "${#FUNCNAME[@]}" -ge 2 ]] \ && [[ "${FUNCNAME[0]}" = is_sourced ]] \ && [[ "${FUNCNAME[1]}" = source ]] } ###################### # BUILDING # ###################### set_compiler_and_linker_flags() { case "${_arg_suite}" in "2.1") # Newer versions of g++ tend to complain about how GnuPG 2.1 uses C++ unions. # In order to prevent build failures, following has to be set. export CXXFLAGS="${CXXFLAGS} -std=c++11" ;; esac } # Usage: # install_gpg_components \ # libgpg-error 1.42 \ # libgcrypt 1.9.2 \ # libassuan latest \ # gnupg master \ # -- "${_arr_component_options[@]}" install_gpg_components() { local component_name component_version component_name_version local component_name_versions=() local is_version_string local parse_version_flip= # internal counter for parsing version string pairs for arg in "$@"; do shift if [[ -n "${parse_version_flip}" ]]; then parse_version_flip= continue fi if [[ "${arg}" = -- ]]; then break else if [[ "${1}" = -- || -z "${1}" ]]; then >&2 echo "Error: version for '${arg}' not specified. Aborting." return 1 fi component_name_versions+=("${arg}:::${1}") parse_version_flip=1 fi done local install_opts=() for component_name_version in "${component_name_versions[@]}"; do component_name="${component_name_version%:::*}" component_version="${component_name_version#*:::}" case "${component_version}" in *.*) is_version_string=1 ;; latest*) is_version_string=1 ;; *) is_version_string= ;; esac install_opts=(--component-name "${component_name}") if [[ -n "${is_version_string}" ]]; then install_opts+=(--component-version "${component_version}") else install_opts+=(--component-git-ref "${component_version}") fi "${__progdir}"/install_gpg_component.sh "${install_opts[@]}" "$@" done } install_suite() { case "${_arg_suite}" in "2.2") install_gpg_components \ libgpg-error 1.33 \ libgcrypt 1.8.6 \ libassuan 2.5.3 \ libksba 1.4.0 \ npth 1.6 \ pinentry 1.1.0 \ gnupg 2.2.20 \ -- "${_arr_component_options[@]}" ;; "2.1") install_gpg_components \ libgpg-error 1.27 \ libgcrypt 1.7.6 \ libassuan 2.4.3 \ libksba 1.3.5 \ npth 1.2 \ pinentry 0.9.5 \ gnupg 2.1.20 \ -- "${_arr_component_options[@]}" ;; "latest") install_gpg_components \ libgpg-error latest \ libgcrypt latest \ libassuan latest \ libksba latest \ npth latest \ pinentry latest \ gnupg latest \ -- "${_arr_component_options[@]}" ;; "master") install_gpg_components \ libgpg-error master \ libgcrypt master \ libassuan master \ libksba master \ npth master \ pinentry master \ gnupg master \ -- "${_arr_component_options[@]}" ;; esac cat <<DONE +-------------------+ | INSTALL COMPLETE! | +-------------------+ DONE } ###################### # ERROR HANDLING # ###################### readonly __progname="$(basename "$0")" readonly __progdir="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)" errx() { echo -e "$__progname: $*" >&2 exit 1 } ###################### # MAIN # ###################### set -e # Early exit if any command returns non-zero status code main() { set_default_options parse_cli_arguments "$@" set_compiler_and_linker_flags install_suite } if ! is_sourced; then main "$@" fi exit 0
<filename>app/src/main/java/com/yunusseker/mvvmarchitecture/ui/main/MainActivity.java package com.yunusseker.mvvmarchitecture.ui.main; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.widget.Toast; import com.yunusseker.mvvmarchitecture.R; import com.yunusseker.mvvmarchitecture.base.BaseActivity; import com.yunusseker.mvvmarchitecture.base.BaseRecyclerAdapter; import com.yunusseker.mvvmarchitecture.base.ItemClickListener; import com.yunusseker.mvvmarchitecture.data.model.PostModel; import com.yunusseker.mvvmarchitecture.data.model.UserModel; import com.yunusseker.mvvmarchitecture.databinding.ActivityMainBinding; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends BaseActivity<MainViewModel,ActivityMainBinding> implements ItemClickListener { List<Object> list =new ArrayList<>(); @Override public int getLayoutRes() { return R.layout.activity_main; } @Override public Class<MainViewModel> getViewModel() {return MainViewModel.class;} @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); UserModel user =new UserModel("yunus"); PostModel postModel =new PostModel("example post"); list.add(user); list.add(postModel); HashMap<Class<?>,Integer> layoutIds =new HashMap<>(); layoutIds.put(UserModel.class,R.layout.row_user); layoutIds.put(PostModel.class,R.layout.row_main); BaseRecyclerAdapter baseAdapter =new BaseRecyclerAdapter(list,null,this); dataBinding.recView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));//TODO inject from mainActivityModule baseAdapter.setLayoutMap(UserModel.class,R.layout.row_user); baseAdapter.setLayoutMap(PostModel.class,R.layout.row_main); dataBinding.recView.setAdapter(baseAdapter); } @Override public void onItemClick(int itemType, int compenentIndex, Object itemData) { if (itemType==1){ Toast.makeText(this, ((UserModel)itemData).getName(), Toast.LENGTH_LONG).show(); }else if (itemType==0){ Toast.makeText(this, ((PostModel)itemData).getTitle(), Toast.LENGTH_LONG).show(); } } }
package proptics.syntax import cats.Applicative import proptics.AnIso_ trait AnIsoSyntax { implicit def anIsoSequenceOps[F[_], S, T, A](iso: AnIso_[S, T, F[A], A]): AnIsoSequenceOps[F, S, T, A] = AnIsoSequenceOps(iso) } final case class AnIsoSequenceOps[F[_], S, T, A](private val iso: AnIso_[S, T, F[A], A]) extends AnyVal { /** invert a structure of S containing F[A] to F[T], a structure T containing A's inside an Applicative Functor */ def sequence(s: S)(implicit ev0: Applicative[F]): F[T] = iso.traverse(s)(identity) }
#!/bin/bash # Check if in script directory path=$(pwd) primary_dir=$(basename $path) if [ "$primary_dir" != "scripts" ]; then cd scripts fi ./code_coverage.sh "keymanager" "base_layer/keymanager/"
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('brewery', '0019_auto_20170813_1114'), ] operations = [ migrations.CreateModel( name='Beer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('style', models.CharField(max_length=50)), ('abv', models.FloatField()), ('brewery', models.ForeignKey(on_delete=models.CASCADE, to='brewery.Brewery')), ], ), ]
n = 10 for i in range(1, n+1): if i % 2 == 0: print(i)
The highest value is 8. list_ints = [2, 5, 3, 4, 8] highest_value = max(list_ints) print('The highest value is ' + str(highest_value) + '.')
const express = require('express'); const path = require('path'); const csv = require('csvtojson'); const csvPokemonPath = './data/pokemon.csv'; const Pokedex = require('pokedex-promise-v2'); const app = express(); // Serve static files from the React app app.use(express.static(path.join(__dirname, 'client/build'))); // Put all API endpoints under '/api' app.get('/api/sample', (req, res) => { res.json('all the pokemon'); }); // pokemon api app.get('/api/pokemon', (req, res) => { csv().fromFile(csvPokemonPath).then((options) => { res.json(options); }); }); app.get('/api/pokemon/:pokemon', (req, res) => { if (req.params.pokemon) { let pokemon = req.params.pokemon.toLowerCase(); let name; let spriteUrl; let types; let weaknesses = []; P.getPokemonByName(pokemon) // with Promise .then(function(response) { // grab details required... if (response.name) { name = response.name; } if (response.sprites && response.sprites.front_default) { spriteUrl = response.sprites.front_default; } if (response.types) { types = response.types.map(x => x.type.name) } // grab weaknesses across types P.getTypeByName(types) .then(function(response) { weaknesses = response.map(x => x.damage_relations.double_damage_from).flat(1).map(x => x.name); let pokemonData = { name, spriteUrl, types, weaknesses }; console.log(JSON.stringify(pokemonData)); res.json(pokemonData); }) .catch(function(error) { console.log('There was an ERROR: ', error); }); }) .catch(function(error) { // TODO: error handling :) console.log('There was an ERROR: ', error); }); } }); app.get('/api/pokemon/type/:type', (req, res) => { if (req.params.type) { let type = req.params.type; let weaknesses = []; // load type details with type P.getTypeByName(type) .then(function(response) { weaknesses = response.map(x => x.damage_relations.double_damage_from).flat(1).map(x => x.name); res.json(weaknesses); }) .catch(function(error) { // TODO: error handling :) console.log('There was an ERROR: ', error); }); } }); // The "catchall" handler: for any request that doesn't // match one above, send back React's index.html file. app.get('*', (req, res) => { res.sendFile(path.join(__dirname+'/client/build/index.html')); }); const port = process.env.PORT || 5000; app.listen(port); const P = new Pokedex(); console.log(`PokeCoach API listening on ${port}`);
let codigoUser = null let linhas = [] let colunas = [] let operacaoFuncionario = null let operacaoRelatorio = null function carregaFuncionarios(btn){ let tbody = window.document.getElementById('dadosCarregados') let dados = window.document.getElementsByClassName('dadoInfo') let obj = window.document.querySelector('#carregarMaisTable') minimoA = (dados != undefined) ? dados.length : 1 let info = { min: minimoA - 1, txt: window.document.getElementById('pesquisaInput').value.trim(), tipo: window.document.getElementById('pesqOP').value.trim(), status: window.document.getElementById('statusOP').value.trim(), sexo: window.document.getElementById('sexoOP').value.trim(), instituicao: window.document.getElementById('instituicaoOP').value.trim(), users: linhas.join() } if(operacaoFuncionario != null){ operacaoFuncionario.abort(); operacaoFuncionario = null; } operacaoFuncionario = $.ajax({ method: "POST", url: "carregaFuncionarios.php", data: info, beforeSend: function(){ if(btn != null){ btn.innerHTML = "" btn.classList.remove("btnCarr") btn.classList.add("loading") } } }) .done(function(res){ if(obj != undefined){ obj.innerHTML = "" obj.remove() } tbody.innerHTML += res }) .fail(function(){ if(operacaoFuncionario == null){ alert("Ocorreu um erro ao tentar carregar mais funcionários") } if(btn != null){ btn.innerHTML = "<i class='fas fa-plus'></i>" btn.classList.remove("loading") btn.classList.add("btnCarr") } }) } //Filtro function abreMoldalFiltro(){ window.document.getElementsByClassName('MoldalOp')[0].style.display = "flex" } function defineFiltro(){ window.document.getElementById('pesquisaInput').value = "" window.document.getElementById('dadosCarregados').innerHTML = "<tr id='carregarMaisTable'><td colspan='12'><button class='loading'></button></td></tr>" carregaFuncionarios(null) window.document.getElementsByClassName('MoldalOp')[0].style.display = "none" } //Pesquisa function pesquisaFuncionario(){ window.document.getElementById('dadosCarregados').innerHTML = "<tr id='carregarMaisTable'><td colspan='12'><button class='loading'></button></td></tr>" carregaFuncionarios(null) } //Função de exclusão function excluirFuncionario(){ let input = window.document.getElementById('inputSenha') if(input.value.trim().length > 0){ if(codigoUser != null){ $.ajax({ method: "POST", url: "deletaUsuario.php", data: {codU: codigoUser, senha: input.value.trim(), instituicao: window.document.getElementById('instituicaoOP').value.trim()}, beforeSend: function(){ window.document.getElementById('moldalLoading').style.display = "flex" } }) .done(function(res){ window.document.getElementById("MoldalAviso").innerHTML = res window.document.getElementById("MoldalAviso").style.display = "flex" window.document.getElementById('moldalLoading').style.display = "none" window.document.getElementById('moldalLoading').style.display = "none" window.document.getElementsByClassName('MoldalOp')[1].style.display = "none" limpaCampoSenha() codigoUser = null window.document.getElementById('inputSenha').value = "" window.document.getElementById('dadosCarregados').innerHTML = "<tr id='carregarMaisTable'><td colspan='12'><button class='loading'></button></td></tr>" carregaFuncionarios(null) //Recarregando mensagens window.document.getElementById('tbodyMsgAviso').innerHTML = `<tr id="trMsgLoading"> <td colspan="4"><button class="loading"></button></td> </tr>` carregaAvisos(null) }) .fail(function(){ alert("Funcionário não deletado, Ocorreu um erro na operação de exclusão") window.document.getElementById('moldalLoading').style.display = "none" }) } }else{ input.style.borderColor = "#5c0101" window.document.getElementById('spanSenha').style.display = "inline" } } function limpaCampoSenha(){ window.document.getElementById('inputSenha').style.borderColor = "#161717" window.document.getElementById('spanSenha').style.display = "none" } function abreMoldalSenha(codigoU){ codigoUser = codigoU window.document.getElementsByClassName('MoldalOp')[1].style.display = "flex" } function selecionaUser(codigo){ let indice = linhas.indexOf(codigo) if(indice == -1){ linhas.push(codigo) }else{ linhas.splice(indice, 1) } } //Funções para gerar o relatório function abreMoldalRelatorio(){ if(linhas.length > 0){ carregaRelatorio() window.document.getElementsByClassName('MoldalOp')[2].style.display = "flex" }else{ alert("Selecione pelo menos um funcionário para emitir o relatório!") } } function veriricaColunas(){ colunas = [] let coluna = window.document.getElementsByClassName('checkboxTable') for(i of coluna){ if(i.checked){ colunas.push(i.value) } } } function carregaRelatorio(){ let dados = { tipo: 3, rows: linhas.join() } if(operacaoRelatorio != null){ operacaoRelatorio.abort(); operacaoRelatorio = null; } operacaoRelatorio = $.ajax({ method: "POST", url: "carregaRelatorio.php", data: dados, beforeSend: function(){ window.document.getElementById("tbodyRelatorio").innerHTML = "<tr><td colspan='16'><button class='loading'></button></td></tr>" } }) .done(function(res){ window.document.getElementById('tbodyRelatorio').innerHTML = res }) .fail(function(){ if(operacaoRelatorio == null){ alert("Ocorreu um erro ao tentar carregar o relatório") } }) } function geraPDF(){ let titulo = window.document.getElementById('tituloRelatorio') let iColunas = window.document.getElementById('columnsPDF') let iLinhas = window.document.getElementById('rowsPDF') let iTitulo = window.document.getElementById('titlePDF') let orientacao = window.document.getElementById('OP') let tamanho = window.document.getElementById('TP') veriricaColunas() if(titulo.value.trim().length > 0){ if(colunas.length > 0){ iColunas.value = colunas.join() iLinhas.value = linhas.join() iTitulo.value = titulo.value.trim() orientacao.value = window.document.getElementById('orientacaoPaper').value.trim() tamanho.value = window.document.getElementById('tamanhoPaper').value.trim() return true }else{ alert("Selecione pelo menos uma coluna!") return false } }else{ alert("Dê um titulo ao seu relatório!") titulo.focus() return false } } function geraExcel(){ let titulo = window.document.getElementById('tituloRelatorio') veriricaColunas() if(titulo.value.trim().length > 0){ if(colunas.length > 0){ let dados = { tipo: 3, columns: colunas.join(), rows: linhas.join(), title: titulo.value.trim() } $.ajax({ method: "POST", url: "geraExcel.php", data: dados }) .done(function(res){ let a = document.createElement("a") a.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(res)) a.setAttribute("download", `${titulo.value.trim()}.xls`) a.click() }) .fail(function(){ alert("Ocorreu um erro ao tentar emitir o relatório") }) }else{ alert("Selecione pelo menos uma coluna!") } }else{ alert("Dê um titulo ao seu relatório!") titulo.focus() } } function Imprimir(){ let titulo = window.document.getElementById('tituloRelatorio') veriricaColunas() if(titulo.value.trim().length > 0){ if(colunas.length > 0){ let dados = { tipo: 3, columns: colunas.join(), rows: linhas.join(), title: titulo.value.trim() } $.ajax({ method: "POST", url: "Imprimir.php", data: dados }) .done(function(res){ const WIDTH = 800 const HEIGHT = 450 const X = (window.outerWidth - WIDTH) / 2 const Y = (window.outerHeight - HEIGHT) / 2 let pagina = window.open("", "_blank", `height=${HEIGHT}, width=${WIDTH}, top=${Y}, left=${X}`) pagina.document.write(res) pagina.document.close() pagina.print() }) .fail(function(){ alert("Ocorreu um erro ao tentar emitir o relatório") }) }else{ alert("Selecione pelo menos uma coluna!") } }else{ alert("Dê um titulo ao seu relatório!") titulo.focus() } } function deletaMoldal(){ window.document.getElementById("MoldalAviso").innerHTML = "" window.document.getElementById("MoldalAviso").style.display = "none" } function abreMoldalEnviaMsg(indice, codigo, tipo){ $.ajax({ method: "POST", url: "carregaUsuarioAviso.php", data: {type: tipo, cod: codigo}, beforeSend: function(){ window.document.getElementById("moldalLoading").style.display = "flex" } }) .done(function(res){ window.document.getElementById("dadosRemetenteAviso").innerHTML = res window.document.getElementById("moldalLoading").style.display = "none" window.document.getElementById("textBoxMensagem").value = "" window.document.getElementById("tituloAviso").value = "" window.document.getElementById("codUsuarioAviso").value = codigo window.document.getElementsByClassName('MoldalMensagens')[indice].style.display = "flex" }) .fail(function(){ alert("Ocorreu um erro ao tentar abrir o formulário de envio de mensagens!") window.document.getElementById("moldalLoading").style.display = "none" }) } function enviaMensagem(){ let msg = window.document.getElementById("textBoxMensagem") let codigo = window.document.getElementById("codUsuarioAviso").value.trim() let titulo = window.document.getElementById("tituloAviso") if(msg.value.trim().length > 0 && titulo.value.trim().length > 0){ $.ajax({ method: "POST", url: "enviaMensagemAviso.php", data: {mensagem: msg.value.trim(), cod: codigo, title: titulo.value.trim()}, beforeSend: function(){ window.document.getElementById("moldalLoading").style.display = "flex" } }) .done(function(res){ window.document.getElementById("MoldalAviso").innerHTML = res window.document.getElementById("MoldalAviso").style.display = "flex" window.document.getElementById('moldalLoading').style.display = "none" msg.value = "" titulo.value = "" }) .fail(function(){ alert("Mensagem não enviada!, Ocorreu um erro ao enviar esta mensagem") window.document.getElementById("moldalLoading").style.display = "none" }) }else{ if(titulo.value.trim().length == 0){ alert("Digite o titulo da mensagem que deseja enviar!") titulo.focus() }else{ alert("Digite a mensagem que deseja enviar!") msg.focus() } } } window.addEventListener("load", function(){ let btn = window.document.getElementsByClassName('fechaMoldalOp') carregaFuncionarios(null) for(i of btn){ i.addEventListener("click", function(){ let moldal = window.document.getElementsByClassName('MoldalOp') for(i of moldal){ i.style.display = "none" } limpaCampoSenha() codigoUser = null window.document.getElementById('inputSenha').value = "" }) } veriricaColunas() })
// https://codeforces.com/contest/1020/problem/C #include <bits/stdc++.h> using namespace std; using ll=long long; using ii=tuple<ll,ll>; using vi=vector<ll>; using vii=vector<ii>; int main(){ ios::sync_with_stdio(0); cin.tie(0); ll n,m,M=10000000000000000LL; cin>>n>>m; vii a; vi b(m); for(int i=0;i<n;i++){ ll p,c; cin>>p>>c; p--; b[p]++; if(p) a.push_back({c,p}); } sort(a.begin(),a.end()); for (int i=1;i<=n;i++){ vi d=b,e(a.size()); ll p,c,k=0; for(int j=0;j<a.size();j++){ tie(c,p)=a[j]; if(d[p]>=i){ d[p]--; k+=c; d[0]++; e[j]=1; } } for(int j=0;j<a.size();j++){ if(d[0]>=i)break; if(e[j])continue; k+=get<0>(a[j]); d[0]++; } M=min(k,M); } cout<<M<<endl; }
class X509FederationRequest: def __init__(self): self._certificate = None self._public_key = None self._intermediate_certificates = None @property def certificate(self): """ **[Required]** Gets the certificate of this X509FederationRequest. """ return self._certificate @property def public_key(self): """ **[Required]** Gets the public key associated with the certificate. """ if self._certificate: # Assuming a method to extract public key from the certificate self._public_key = extract_public_key(self._certificate) return self._public_key else: raise ValueError("No certificate available to retrieve public key") @property def intermediate_certificates(self): """ **[Required]** Gets the intermediate certificates linked to the main certificate. """ if self._certificate: # Assuming a method to retrieve intermediate certificates from the main certificate self._intermediate_certificates = retrieve_intermediate_certificates(self._certificate) return self._intermediate_certificates else: raise ValueError("No certificate available to retrieve intermediate certificates")
<reponame>Lelith/adventofcode19 const utils = require('../utils'); function gravityAssistant(data) { let i = 0; let a = 0; let b = 0; let pointer = 0; let operator = data[0]; while (operator !== 99 && i < (data.length - 1)) { a = data[i + 1]; b = data[i + 2]; pointer = data[i + 3]; console.log(`i: ${i}, a: ${data[a]}, b: ${data[b]}, operator: ${operator}, pointer ${pointer}`); if (operator === 1) { data[pointer] = data[a] + data[b]; } else if (operator === 2) { data[pointer] = data[a] * data[b]; } i += 4; operator = data[i]; } return data; } try { // let data = utils.readInput('./example.txt'); let data = utils.readInput('./input.txt'); data = utils.modDataCommas(data); data[1] = 12; data[2] = 2; const results = gravityAssistant(data); console.log(results); console.log(results[0]); } catch (e) { console.log('Error', e.stack); }
<reponame>benwhitehair/pinkslipproperty.com.au<gh_stars>0 import React from 'react'; const CTA = () => ( <section id="about" className="bg-grey-lightest leading-normal px-8 py-16"> <div className="max-w-lg mx-auto md:mt-16 text-lg"> <h1 className="font-condensed leading-none mb-6 text-5xl uppercase"> Does your property have a pink slip? </h1> <p className="mb-4"> Pinkslip Property is a Port Macquarie based company that provides domestic safety and maintenance services to the Mid North Coast from Forster to Coffs Harbour. </p> <p className="mb-4"> We specialise in smoke alarms, water efficiency, and safety checks of your owner occupier or investment property. </p> <p className="mb-4"> Pinkslip Property is a safety net – an umbrella of services – to ensure your investment is protected, tenants are safe, and your property is compliant with NSW smoke alarm and other legislations governing your investment property. </p> <p className="mb-16"> PSP is a family run, locally based company employing local members of the community. We believe in building a stronger and safer community. </p> <div className="flex items-center justify-center"> <a className="bg-indigo-darker font-bold font-condensed inline-block px-16 py-6 no-underline shadow text-white" href="#services" > <div className="flex items-center leading-none"> <span className="mr-2">More info</span> <span> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className="fill-current h-6 w-6" > <path className="fill-current text-pink-light" d="M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20z" /> <path className="fill-current text-pink-darker" d="M11 12a1 1 0 0 1 0-2h2a1 1 0 0 1 .96 1.27L12.33 17H13a1 1 0 0 1 0 2h-2a1 1 0 0 1-.96-1.27L11.67 12H11zm2-4a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z" /> </svg> </span> </div> </a> </div> </div> </section> ); export default CTA;
import os import shutil import fnmatch def rsync(source_dir, destination_dir, exclude_patterns=None): if not os.path.exists(destination_dir): os.makedirs(destination_dir) for root, dirs, files in os.walk(source_dir): relative_path = os.path.relpath(root, source_dir) destination_path = os.path.join(destination_dir, relative_path) if not os.path.exists(destination_path): os.makedirs(destination_path) for file in files: source_file = os.path.join(root, file) destination_file = os.path.join(destination_path, file) if exclude_patterns and any(fnmatch.fnmatch(file, pattern) for pattern in exclude_patterns): continue if os.path.exists(destination_file): source_mtime = os.path.getmtime(source_file) dest_mtime = os.path.getmtime(destination_file) if source_mtime > dest_mtime: shutil.copy2(source_file, destination_file) else: shutil.copy2(source_file, destination_file) for dir in dirs: source_subdir = os.path.join(source_dir, dir) destination_subdir = os.path.join(destination_dir, dir) rsync(source_subdir, destination_subdir, exclude_patterns) # Example usage source_directory = '/path/to/source' destination_directory = '/path/to/destination' exclude_patterns = ['*target*', '*.idea*', '*.class'] rsync(source_directory, destination_directory, exclude_patterns)
#!/bin/bash set -e echoerr() { echo "$@" 1>&2; } # Split out host and port from DB_HOST env variable IFS=":" read -r DB_HOST_NAME DB_PORT <<< "$DB_HOST" DB_PORT=${DB_PORT:-3306} # create .env file if not there if [ ! -f ".env" ]; then if [[ "${DB_HOST}" ]]; then cat > ".env" <<EOF # Environment APP_ENV=production APP_DEBUG=${APP_DEBUG:-false} APP_KEY=${APP_KEY:-SomeRandomStringWith32Characters} # The below url has to be set if using social auth options # or if you are not using BookStack at the root path of your domain. APP_URL=${APP_URL:-null} # Database details DB_HOST=${DB_HOST:-localhost} DB_DATABASE=${DB_DATABASE:-bookstack} DB_USERNAME=${DB_USERNAME:-bookstack} DB_PASSWORD=${DB_PASSWORD:-password} # Cache and session CACHE_DRIVER=file SESSION_DRIVER=file SESSION_LIFETIME=${SESSION_LIFETIME:-600} SESSION_COOKIE_NAME=${SESSION_COOKIE_NAME:-bookstack_session} SESSION_SECURE_COOKIE=${SESSION_SECURE_COOKIE:-true} # If using Memcached, comment the above and uncomment these #CACHE_DRIVER=memcached #SESSION_DRIVER=memcached QUEUE_DRIVER=sync # Memcached settings # If using a UNIX socket path for the host, set the port to 0 # This follows the following format: HOST:PORT:WEIGHT # For multiple servers separate with a comma MEMCACHED_SERVERS=127.0.0.1:11211:100 # Storage STORAGE_TYPE=${STORAGE_TYPE:-local} STORAGE_IMAGE_TYPE=${STORAGE_TYPE:-local} # Amazon S3 Config STORAGE_S3_KEY=${STORAGE_S3_KEY:-false} STORAGE_S3_SECRET=${STORAGE_S3_SECRET:-false} STORAGE_S3_REGION=${STORAGE_S3_REGION:-false} STORAGE_S3_BUCKET=${STORAGE_S3_BUCKET:-false} # Storage URL # Used to prefix image urls for when using custom domains/cdns STORAGE_URL=${STORAGE_URL:-false} # General auth AUTH_METHOD=${AUTH_METHOD:-standard} # SAML Settings SAML2_NAME=${SAML2_NAME} SAML2_EMAIL_ATTRIBUTE=${SAML2_EMAIL_ATTRIBUTE} SAML2_EXTERNAL_ID_ATTRIBUTE=${SAML2_EXTERNAL_ID_ATTRIBUTE} SAML2_DISPLAY_NAME_ATTRIBUTES=${SAML2_DISPLAY_NAME_ATTRIBUTES} SAML2_IDP_ENTITYID=${SAML2_IDP_ENTITYID} SAML2_AUTOLOAD_METADATA=${SAML2_AUTOLOAD_METADATA:-false} SAML2_IDP_SSO=${SAML2_IDP_SSO} SAML2_IDP_SLO=${SAML2_IDP_SLO} SAML2_IDP_x509=${SAML2_IDP_x509} # Groups SAML Settings SAML2_USER_TO_GROUPS=${SAML2_USER_TO_GROUPS:-false} SAML2_GROUP_ATTRIBUTE=${SAML2_GROUP_ATTRIBUTE} SAML2_REMOVE_FROM_GROUPS=${SAML2_REMOVE_FROM_GROUPS:-false} # Social Authentication information. Defaults as off. GITHUB_APP_ID=${GITHUB_APP_ID:-false} GITHUB_APP_SECRET=${GITHUB_APP_SECRET:-false} GOOGLE_APP_ID=${GOOGLE_APP_ID:-false} GOOGLE_APP_SECRET=${GOOGLE_APP_SECRET:-false} # External services such as Gravatar DISABLE_EXTERNAL_SERVICES=${DISABLE_EXTERNAL_SERVICES:-false} # LDAP Settings LDAP_SERVER=${LDAP_SERVER:-false} LDAP_BASE_DN=${LDAP_BASE_DN:-false} LDAP_DN=${LDAP_DN:-false} LDAP_PASS=${LDAP_PASS:-false} LDAP_USER_FILTER=${LDAP_USER_FILTER:-false} LDAP_VERSION=${LDAP_VERSION:-false} # Mail settings MAIL_DRIVER=${MAIL_DRIVER:-smtp} MAIL_HOST=${MAIL_HOST:-localhost} MAIL_PORT=${MAIL_PORT:-1025} MAIL_USERNAME=${MAIL_USERNAME:-null} MAIL_PASSWORD=${MAIL_PASSWORD:-null} MAIL_ENCRYPTION=${MAIL_ENCRYPTION:-null} # URL used for social login redirects, NO TRAILING SLASH EOF else echo >&2 'error: missing DB_HOST environment variable' exit 1 fi fi # create cert file if not there if [ ! -f "certs/bookstack.${WIKI_NAME}.cnf" ]; then mkdir -p certs cat > "certs/bookstack.${WIKI_NAME}.cnf" <<EOF [req] RANDFILE=/dev/urandom default_bits=3072 default_md=sha256 encrypt_key=no distinguished_name=dn # PrintableStrings only string_mask=MASK:0002 prompt=no x509_extensions=ext # customize the "default_keyfile,", "CN" and "subjectAltName" lines below default_keyfile=certs/sp-key.pem [dn] CN=${PROXY_NAME}.${DOMAIN_NAME} [ext] subjectAltName = DNS:${DOMAIN_NAME}, \ URI:https://${PROXY_NAME}.${DOMAIN_NAME}/${WIKI_NAME}/saml2/metadata subjectKeyIdentifier=hash EOF echo "Generate SAML Certs" openssl req -new -x509 -config ./certs/bookstack.${WIKI_NAME}.cnf -text -out ./certs/sp-cert.pem -days 3650 fi # copy the cert file form saml auth mkdir -p /var/www/html/vendor/onelogin/php-saml/certs cp certs/sp-cert.pem /var/www/bookstack/vendor/onelogin/php-saml/certs/sp.crt cp certs/sp-key.pem /var/www/bookstack/vendor/onelogin/php-saml/certs/sp.key # modify the alias in 000-default.conf with the WIKI_NAME sed -i "s/WIKI_NAME/${WIKI_NAME}/" /etc/apache2/sites-available/000-default.conf echoerr "wait-for-db: waiting for ${DB_HOST_NAME}:${DB_PORT}" timeout 15 bash <<EOT while ! (echo > /dev/tcp/${DB_HOST_NAME}/${DB_PORT}) >/dev/null 2>&1; do sleep 1; done; EOT RESULT=$? if [ $RESULT -eq 0 ]; then # sleep another second for so that we don't get a "the database system is starting up" error sleep 1 echoerr "wait-for-db: done" else echoerr "wait-for-db: timeout out after 15 seconds waiting for ${DB_HOST_NAME}:${DB_PORT}" fi echo "Generating Key..." php artisan key:generate --show echo "Starting Migration..." # DB first set up if [[ "${DB_INIT}" == true ]]; then echo "Starting Initialisation..." cat > "initdb1.php" <<EOF <?php try { \$conn = new PDO("mysql:host=${DB_HOST_NAME}:${DB_PORT};dbname=${DB_DATABASE}", "${DB_USERNAME}", "${DB_PASSWORD}"); // set the PDO error mode to exception \$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); \$sql = "ALTER TABLE pages DROP COLUMN template"; // Prepare statement \$stmt = \$conn->prepare(\$sql); // execute the query \$stmt->execute(); // echo a message to say the UPDATE succeeded echo \$stmt->rowCount(); } catch(PDOException \$e) { echo \$sql . "<br>" . \$e->getMessage(); } \$conn = null; ?> EOF cat > "initdb2.php" <<EOF <?php try { \$conn = new PDO("mysql:host=${DB_HOST_NAME}:${DB_PORT};dbname=${DB_DATABASE}", "${DB_USERNAME}", "${DB_PASSWORD}"); // set the PDO error mode to exception \$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); \$sql = "ALTER TABLE users DROP COLUMN slug"; // Prepare statement \$stmt = \$conn->prepare(\$sql); // execute the query \$stmt->execute(); // echo a message to say the UPDATE succeeded echo \$stmt->rowCount(); } catch(PDOException \$e) { echo \$sql . "<br>" . \$e->getMessage(); } \$conn = null; ?> EOF cat initdb1.php php artisan migrate --force || php initdb1.php php artisan migrate --force || php initdb2.php fi php artisan migrate --force echo "Clearing caches..." php artisan cache:clear php artisan view:clear trap "echo Catching SIGWINCH apache error and perventing it." SIGWINCH exec apache2-foreground
<filename>src/app/views/management/add-edit-super-users.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { SecureAuth } from '../../helpers/secure-auth'; import { UsersService } from '../../services/users/users.service'; import { iFItSuperUser } from '../../models/users/ifit-user'; import { IAngularMyDpOptions } from 'angular-mydatepicker'; import { NgxSpinnerService } from "ngx-spinner"; import { Observable, of } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, map, tap, switchMap } from 'rxjs/operators'; @Component({ selector: 'app-add-edit-super-users', templateUrl: './add-edit-super-users.component.html' }) export class AddEditSuperUsersComponent implements OnInit { id: number; _title: string; iFitUser: iFItSuperUser; _secureAuth: SecureAuth; fileToUpload: File = null; userTypes: []; sexType = [{ id: "male", value: 'Male' }, { id: "female", value: 'Female' }, { id: "other", value: 'Other' }] myDpOptions: IAngularMyDpOptions = { dateRange: false, dateFormat: 'mm/dd/yyyy' }; searchingBusinessOwner: boolean = false; isBusinessOwnerFoundLength: any; searchFailedForBusinessOwner: any; constructor(private _router: Router, private _activatedRoute: ActivatedRoute, private service: UsersService, private spinner: NgxSpinnerService) { this.id = this._activatedRoute.snapshot.params.id; this._secureAuth = new SecureAuth(); if (this.id) { this._title = "Edit"; } else { this._title = "Add"; } this.iFitUser = new iFItSuperUser(); let sidebarRootElement = document.getElementById('root'); sidebarRootElement.style.display = 'block'; let sidebarChildElement = document.getElementById('child'); sidebarChildElement.style.display = 'none'; this.userTypes = []; this.iFitUser.sex = "null"; this.iFitUser.user_type_id = ""; } ngOnInit() { this.GetUserById(); this.GetAllUserTypes(); } GetUserById() { this.spinner.show(); if (this.id !== undefined && this.id !== null) { let _controllerName = 'users'; this.service.getById(_controllerName, this.id).subscribe((ud: any) => { this.iFitUser = ud.res; this.iFitUser.confirmcredentials = ud.res.credentials; if (this.iFitUser.dob) { this.iFitUser.dob = { isRange: false, singleDate: { date: { year: ud.res.dob.substring(10, 6), month: parseInt(ud.res.dob.substring(0, 2)), day: parseInt(ud.res.dob.substring(3, 5)) } } }; } if(this.iFitUser.bownerid) { let selectedBOwnerId = { id: ud.res.bownerid, title: ud.res.business_name } this.iFitUser.bownerid = selectedBOwnerId; } this.spinner.hide(); }); } } GetAllUserTypes() { this.spinner.show(); let _controllerName = 'users/user/types'; this.service.get(_controllerName).subscribe((ud: any) => { this.userTypes = ud.res; this.spinner.hide(); }); } BackToList() { this._router.navigate(["/manage/users"]); } uploadFile(files: File) { this.fileToUpload = files[0]; let element: any = document.getElementById('userImage'); element.src = window.URL.createObjectURL(files[0]); } BusinessOwnersResultFormatBandListValue(value: any) { return value.title; } BusinessOwnersInputFormatBandListValue(value: any) { if (value.title) return value.title return value; } searchBusinessOwner = (text$: Observable<string>) => text$.pipe( debounceTime(300), distinctUntilChanged(), tap(() => this.searchingBusinessOwner = true), switchMap(term => this.service.searchBusinessOwners(term).pipe(tap((obj) => { this.isBusinessOwnerFoundLength = obj.length; this.searchFailedForBusinessOwner = false }), catchError(() => { this.searchFailedForBusinessOwner = true; return of([]); })) ), tap((obj) => { this.isBusinessOwnerFoundLength = obj.length; this.searchingBusinessOwner = false }) ) saves() { this.spinner.show(); let _controllerName = "users"; let bownerid: any = this.iFitUser.bownerid; let formData = new FormData(); formData.append('first_name', this.iFitUser.first_name); formData.append('last_name', this.iFitUser.last_name); formData.append('avatar_uri', this.fileToUpload || this.iFitUser.avatar_uri); formData.append('user_type_id', this.iFitUser.user_type_id); formData.append('about', this.iFitUser.about); formData.append('salutation', this.iFitUser.salutation); formData.append('credentials', this.iFitUser.credentials); formData.append('sex', this.iFitUser.sex || null); formData.append('dob', this.iFitUser.dob && this.iFitUser.dob.singleDate && this.iFitUser.dob.singleDate.formatted); formData.append('phone', this.iFitUser.phone); formData.append('email', this.iFitUser.email); formData.append('address1', this.iFitUser.address1); formData.append('address2', this.iFitUser.address2); formData.append('city', this.iFitUser.city); formData.append('state', this.iFitUser.state); formData.append('zipcode', this.iFitUser.zipcode); formData.append('facility_code', this.iFitUser.facility_code); formData.append('bownerid', bownerid.bownerid); if (this._title.toLowerCase() === 'edit') { formData.append('UserId', this.iFitUser.id); this.service.update(_controllerName, formData).subscribe((ur: any) => { this.spinner.hide(); if (ur !== undefined && ur !== 'undefined' && ur !== null && ur !== 'null' && ur !== '') { this.BackToList(); } }) } else { this.service.save(_controllerName, formData).subscribe((ur: any) => { this.spinner.hide(); if (ur !== undefined && ur !== 'undefined' && ur !== null && ur !== 'null' && ur !== '') { this.BackToList(); } }) } } }
import { connect, NatsConnection, createInbox } from "nats"; import { JetStreamManager, StreamAPI } from "nats"; async function interactWithJetstreamManager( serverConfig: any, streamName: string, streamConfig: any ): Promise<string[]> { const nc = await connect(serverConfig); // Connect to the NATS server const jsm = await nc.jetstreamManager(); // Initialize the Jetstream Manager // Create a new stream with the given name and configuration await jsm.streams.add(streamName, streamConfig); // Retrieve the list of streams and return their names const streams = await jsm.streams.list().next(); const streamNames = streams.map((stream: StreamAPI) => stream.config.name); // Delete the stream with the given name await jsm.streams.delete(streamName); // Close the NATS connection await nc.close(); return streamNames; }
from django_filters.filterset import FilterSet from ..search.filter import SearchFilter from .models import Institution from .searchset import InstitutionSearchSet class InstitutionFilterSet(FilterSet): query = SearchFilter(searchset=InstitutionSearchSet()) class Meta: model = Institution fields = ["query"]
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Catch(CMakePackage): """Catch tests""" homepage = "https://github.com/catchorg/Catch2" url = "https://github.com/catchorg/Catch2/archive/v1.3.0.tar.gz" variant('single_header', default=True, description='Install a single header only.') # - "make install" was added in 1.7.0 # - pkg-config package was added in 2.0.1 # - CMake config package was added in 2.1.2 conflicts('~single_header', when='@:1.6.1') version('2.2.1', '54e56803c84890636bd7fe6c3856b104') version('2.1.0', '70b44068976d46d48f3cd8796f675691d3bc726b') version('2.0.1', '5c191a031edebd0525640ed2f38cbf64bacb1803') version('1.12.1', '7d89cffd9d61f4fdcbdb373b70cc92d1') version('1.12.0', '8fb0a64144a2c1572dd930254c7bbdf504ecbe2d') version('1.11.0', '3c03a022d8ba8dbbc931e1ce9fb28faec4890b8d') version('1.10.0', 'c2033ca00b616e7e703623c68220cf5a8e12bba4') version('1.9.7', '7ea41b48a23bd83f377f05a9dfde2be230cfc1b4') version('1.9.6', 'e6ae3a50c6e4da64410979dcd4b2bb3f7ba1c364') version('1.9.5', '7ba2bb12b5398b8b9ab7a7907f4cd345a55e179a') version('1.9.4', 'b48fce35161160def587bd0d8f0e95969b20b786') version('1.9.3', 'c0db82118496a2dd0637aad352f31d9356bffc28') version('1.9.2', '627fd94d466c0f71ba84010adf82771ed3ce85c7') version('1.9.1', '331e4a5cd32fe4c36b4bea15e5198346f18b5c3f') version('1.9.0', '5bb46e99eea39224189a8a0442ec7790c635a7b0') version('1.8.2', '34b8a2da76befeeaeafc393569538222605dda51') version('1.8.1', 'd5f4ae9603fe27c313bc5b5b23c233bdce5c57f7') version('1.8.0', '7fa6bfc50e6dbb6fd1352f41496650d56a86ac1a') version('1.7.2', '45b0ab04b6da75ce56de25a81f0b0de4c7a62179') version('1.7.1', '3a55985aacd5a5ff8a87c1490bbf65f0122647dc') version('1.7.0', '6f9869cc066721d525bb03e8a9423b806c362140') version('1.6.1', 'e88de5b611c07d5d402142d3dc20b63350fdf76c') version('1.6.0', '21273cbed050b8d4785231d04812d5addf5b71b7') version('1.5.9', '341bee0b642f0dc9bb6fb41243a068239468b703') version('1.5.0', '2d14342c72f12b3f4b975cf6aa8594c8ad43d773') version('1.4.0', '3b3b76a842508386be40d73849627bbe12fb5b7f') version('1.3.5', '2cfd78bce21368355c7d3880df88716084df2186') version('1.3.0', '24cd4e6518273fea20becd47a2e1edbee7ec209a') @when('+single_header') def cmake(self, spec, prefix): pass @when('+single_header') def build(self, spec, prefix): pass @when('+single_header') def install(self, spec, prefix): mkdirp(prefix.include) install(join_path('single_include', 'catch.hpp'), prefix.include) # fakes out spack so it installs a module file mkdirp(join_path(prefix, 'bin'))
#!/bin/bash set -e readonly MY_DIR="$( cd "$( dirname "${0}" )" && pwd )" source ${MY_DIR}/env-vars.sh # - - - - - - - - - - - - - - - - - - - - - - - - - - - wait_till_up() # $1==container_name { local n=10 while [ $(( n -= 1 )) -ge 0 ] do if docker ps --filter status=running --format '{{.Names}}' | grep -q ^${1}$ ; then echo "Up on port ${PORT}" return else sleep 0.2 fi done echo "${1} not up after 2 seconds" docker logs "${1}" exit 1 } # - - - - - - - - - - - - - - - - - - - - - - - - - - - docker run \ --detach \ --name ${APP_CONTAINER} \ --publish ${APP_PORT}:${APP_PORT} \ --env APP_PORT=${APP_PORT} \ ${DOCKER_REGISTRY_URL}/${APP_IMAGE} # This is the container up... wait_till_up ${APP_CONTAINER} # But it might not be ready yet. # Crude readyness test is good enough for now... sleep 2
<reponame>jibrelnetwork/jibrel-contracts-jsapi import should from 'should' import BigNumber from 'bignumber.js' import jibrelContractsApi from '../index' if (process.env.JSON_PATH == null) { throw (new Error('JSON_PATH env variable not found')) } const testParams = require(process.env.JSON_PATH) const eth = jibrelContractsApi.eth const rpcaddr = process.env.RPCADDR || '127.0.0.1' const rpcport = process.env.RPCPORT || 8545 const privateKey = testParams.privateKeys[0] const privateKeyTo = testParams.privateKeys[1] const address = testParams.accounts[0] const to = testParams.accounts[1] const value = new BigNumber(1, 10) const addressWithoutContract = '0x0000000000000000000000000000000000000000' const addressWithContract = testParams.contracts.JNTController const filterOptions = { fromBlock: 0, toBlock: 'latest', } let txHash describe('ETH API', function() { // timeout should be increased to wait while transaction was mined this.timeout(10000) describe('sendTransaction', function() { it('returns transaction hash', function(done) { eth.sendTransaction({ rpcaddr, rpcport, privateKey, to, value, }).then((result) => { txHash = result result.should.be.a.String() result.length.should.be.equal(66) result.should.match(/^0x[a-fA-F0-9]+/) done() }).catch(done) }) }) describe('getBalance', function() { it('returns balance of specific account', function(done) { eth.getBalance({ rpcaddr, rpcport, address, }).then((result) => { result.greaterThan(0).should.be.equal(true) result.toNumber().should.be.greaterThan(0) done() }).catch(done) }) }) describe('getBlockNumber', function() { it('returns block number', function(done) { eth.getBlockNumber({ rpcaddr, rpcport, }).then((result) => { result.should.be.a.Number() result.should.be.greaterThan(0) done() }).catch(done) }) }) describe('getBlock', function() { it('returns block data', function(done) { eth.getBlock({ rpcaddr, rpcport, blockId: 'latest', }).then((result) => { result.should.be.an.Object() result.number.should.be.a.Number() result.hash.should.be.a.String() result.parentHash.should.be.a.String() result.nonce.should.be.a.String() result.sha3Uncles.should.be.a.String() result.logsBloom.should.be.a.String() result.transactionsRoot.should.be.a.String() result.stateRoot.should.be.a.String() result.miner.should.be.a.String() result.difficulty.should.be.an.Object() result.totalDifficulty.should.be.an.Object() result.extraData.should.be.a.String() result.size.should.be.a.Number() result.gasLimit.should.be.a.Number() result.gasUsed.should.be.a.Number() result.timestamp.should.be.greaterThan(0) result.transactions.should.be.an.Array() result.uncles.should.be.an.Array() done() }).catch(done) }) }) describe('getTransaction', function() { it('returns transaction data', function(done) { eth.getTransaction({ rpcaddr, rpcport, transactionHash: txHash, }).then((result) => { result.should.be.an.Object() result.hash.should.be.a.String() result.nonce.should.be.a.Number() result.blockHash.should.be.a.String() result.blockNumber.should.be.a.Number() result.transactionIndex.should.be.a.Number() result.from.should.be.a.String() result.from.should.be.equal(address) result.to.should.be.a.String() result.to.should.be.equal(to) result.value.should.be.an.Object() result.value.toNumber().should.be.equal(value.toNumber()) result.gas.should.be.a.Number() result.gasPrice.should.be.an.Object() result.gasPrice.toNumber().should.be.greaterThan(0) result.input.should.be.a.String() done() }).catch(done) }) }) describe('getTransactionReceipt', function() { it('returns transaction receipt', function(done) { eth.getTransactionReceipt({ rpcaddr, rpcport, transactionHash: txHash, }).then((result) => { result.should.be.an.Object() result.transactionHash.should.be.a.String() result.transactionIndex.should.be.a.Number() result.blockHash.should.be.a.String() result.blockNumber.should.be.a.Number() result.gasUsed.should.be.a.Number() result.cumulativeGasUsed.should.be.a.Number() should(result.contractAddress).be.equal(null) result.logs.should.be.an.Array() done() }).catch(done) }) }) describe('getLogsFilter', function() { let isDone it('returns object for filtering of logs', function(done) { eth.getLogsFilter({ rpcaddr, rpcport, options: filterOptions, }).then((result) => { result.should.be.an.Object() result.watch(function(err, log) { if (err) { return done(err) } log.should.be.an.Object() log.logIndex.should.be.a.Number() log.transactionIndex.should.be.a.Number() log.transactionHash.should.be.a.String() log.transactionHash.length.should.be.equal(66) log.transactionHash.should.match(/^0x[a-fA-F0-9]+/) log.blockHash.should.be.a.String() log.blockNumber.should.be.a.Number() log.address.should.be.a.String() log.data.should.be.a.String() log.topics.should.be.an.Array() // ignore, if this test has already done if (isDone) { return } isDone = true done() }) eth.sendTransaction({ rpcaddr, rpcport, value, to: address, privateKey: privateKeyTo, }).catch(done) }).catch(done) }) }) describe('getPastLogs', function() { it('returns past logs', function(done) { eth.getPastLogs({ rpcaddr, rpcport, options: filterOptions, }).then((result) => { result.should.be.an.Array() result.length.should.be.greaterThan(0) const log = result[result.length - 1] log.should.be.an.Object() log.logIndex.should.be.a.Number() log.transactionIndex.should.be.a.Number() log.transactionHash.should.be.a.String() log.transactionHash.length.should.be.equal(66) log.transactionHash.should.match(/^0x[a-fA-F0-9]+/) log.blockHash.should.be.a.String() log.blockNumber.should.be.a.Number() log.address.should.be.a.String() log.data.should.be.a.String() log.topics.should.be.an.Array() done() }).catch(done) }) }) describe('estimateGas', function() { it('returns the used gas for the simulated transaction', function(done) { eth.estimateGas({ rpcaddr, rpcport, to, value, }).then((result) => { result.should.be.a.Number() result.should.be.greaterThan(0) done() }).catch(done) }) }) describe('getCode', function() { it('contract with empty code', function(done) { eth.getCode({ rpcaddr, rpcport, address: addressWithoutContract, }).then((result) => { result.should.be.a.String() if (result !== '0x' && result !== '0x0') { throw new Error('Result should be 0x or 0x0') } done() }).catch(done) }) it('contract with existing code', function(done) { eth.getCode({ rpcaddr, rpcport, address: addressWithContract, }).then((result) => { result.should.be.a.String() result.should.be.not.equal('0x') result.should.be.not.equal('0x0') result.length.should.be.greaterThan(3) done() }).catch(done) }) }) describe('getNonce', function() { it('nonce for contract address with existing code (without specifying block)', function(done) { eth.getNonce({ rpcaddr, rpcport, address: addressWithContract, }).then((result) => { result.should.be.a.Number() result.should.be.greaterThan(0) done() }).catch(done) }) it('nonce for contract address with existing code (with specifying block)', function(done) { eth.getNonce({ rpcaddr, rpcport, defaultBlock: 'pending', address: addressWithContract, }).then((result) => { result.should.be.a.Number() result.should.be.greaterThan(0) done() }).catch(done) }) }) describe('getGasPrice', function() { it('current gas price', function(done) { eth.getGasPrice({ rpcaddr, rpcport, }).then((result) => { result.should.be.an.Object() result.toNumber().should.be.greaterThan(0) done() }).catch(done) }) }) })
#!/bin/bash set -x go vet ./pkg/... go vet ./cmd/...
<gh_stars>1-10 package tsn.oop.polymorphism; import java.util.Date; public class Robot { private String nameRobot; // поле имени робото public Robot() { // конструктор по-умолчанию nameRobot = "Чудо-Робот"; } public Robot(String nameRobot) { // полиморфный конструктор с дополнительным параметром this.nameRobot = nameRobot; } public void activation() { System.out.println("Приветик, я " + nameRobot + "!"); } public void activation(String name) { System.out.println("Мне нравится твое имя, " + name + "!"); } public void activation(int numCoffee) { System.out.println("Понял, делаю кофе на " + numCoffee + " порции..."); } public void activation(String... friends) { System.out.println("Отлично, отошлю приветсвтвие этим ребятам:"); for (String value : friends) { // цикл по переданным параметрам System.out.println("* " + value); } } public void activation(Date date, String name, int hour, float money) { System.out.format("Хорошо, %tD закину %s в %d часов %.2f тенге на телефон!%n ", date, name, hour, money); } }
#!/bin/sh set -e set -x _modname=$(sed -n '/^\s*name\s*=/{s/.*"\(.\+\).*"/\1/p;q}' modinfo.lua) _modversion=$(sed -n '/^\s*version\s*=/{s/.*"\(.\+\).*"/\1/p;q}' modinfo.lua) _OUT="./out/${_modname// /_}-${_modversion}" _OUTSTEAM="./out/steam/${_modname// /_}" rm -fr "${_OUT}" "${_OUTSTEAM}" "${_OUT}.zip" for f in README.md LICENSE modicon.* modinfo.lua modmain.lua lib/* client/*; do install -Dm755 "$f" "${_OUT}/${f}" done # the ModUploader REALLY wants the mod to be in this subdirectory install -dm755 "$(dirname "${_OUTSTEAM}")" ln -rsf "${_OUT}" "${_OUTSTEAM}" pushd "${_OUT}"/.. zip -r9 "$(basename "${_OUT}")"{.zip,} popd
@objc protocol ___VARIABLE_sceneName___RoutingLogic { func routeToSomewhere(segue: UIStoryboardSegue?) } protocol ___VARIABLE_sceneName___DataPassing { var dataStore: ___VARIABLE_sceneName___DataStore? { get } } class ___VARIABLE_sceneName___Router: NSObject, ___VARIABLE_sceneName___RoutingLogic, ___VARIABLE_sceneName___DataPassing { weak var viewController: ___VARIABLE_sceneName___ViewController? var dataStore: ___VARIABLE_sceneName___DataStore? // Implementing the routing logic method func routeToSomewhere(segue: UIStoryboardSegue?) { // Perform the routing to the new scene using the provided segue // Example: viewController?.performSegue(withIdentifier: "SomeSegueIdentifier", sender: nil) } }
/* eslint-disable prettier/prettier */ import React from "react"; import TodoList from "../../components/TodoList"; export default class Active extends React.Component { constructor(props) { super(props) this.state = {} } render() { const {tasks} = this.props const activeTasks = tasks.filter(task => !task.done) return ( <> <TodoList {...this.props} tasks={activeTasks} /> </> ) } }
public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }
""" You are given a string that contains alphabetical characters (a - z, A - Z) and some other characters ($, !, etc.). For example, one input may be: 'sea!$hells3' Can you reverse only the alphabetical ones? reverseOnlyAlphabetical('sea!$hells3'); // 'sll!$ehaes3' """ import re def reverseOnlyAlphabetical(str): strList = list(re.sub(r'\s+', '', str)) startPointer = 0 endPointer = len(strList)-1 while startPointer <= endPointer: if strList[startPointer].isalpha(): if strList[endPointer].isalpha(): strList[startPointer], strList[endPointer] = strList[endPointer], strList[startPointer] startPointer += 1 endPointer -= 1 else: endPointer -= 1 else: startPointer += 1 return ''.join(strList) if __name__ == '__main__': print(reverseOnlyAlphabetical('sea!$hells3')) print(reverseOnlyAlphabetical('1kas90jda3'))
<gh_stars>1-10 package gv package isi package functional trait BindersPackage { @inline final def pfconst[T](t: T): Any ~~> T = { case _ ⇒ t } @inline final def const[T](t: T): Any ⇒ T = _ ⇒ t @inline final def lazypf[T](t: ⇒ T): Any ~~> T = { case _ ⇒ t } @inline final def lazyconst[T](t: ⇒ T): Any ⇒ T = _ ⇒ t }
<gh_stars>0 import React, { Component } from "react"; import InputMask from "react-input-mask"; class Contact extends React.Component { // Значения полей ввода constructor(props) { super(props); this.state = { fullName: { value: '', type: 'text', name: 'fullName', }, phone: { value: '', type: 'tel', name: 'phone', }, email: { value: '', type: 'email', name: 'email', }, address: { value: '', type: 'text', name: 'address', }, accept: { value: '', type: 'checkbox', name: 'accept', } }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleChecked = this.handleChecked.bind(this); } // Ввод данных handleChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value, }); } handleSubmit(event) { // Отправка данных на результирующую страницу let addressInput = this.addressInput.value; document.getElementById("resultAdrress").innerHTML = addressInput; let phoneInput = this.phoneInput.value; document.getElementById("resultPhone").innerHTML = phoneInput; event.preventDefault(); /* Переход на страницу выбора продукта (можно раскомментировать для отображения только одного блока на странице) let contact = document.getElementById("contact"); contact.style.display = 'none'; let select = document.getElementById("select"); select.style.display = 'flex'; Требуется добавить style={{display: "none"}} */ window.location.href = "#select"; } // Присвоение аттрибута checked handleChecked() { let acceptInput = document.getElementById("acceptInput"); if (!acceptInput.hasAttribute("checked")) { acceptInput.setAttribute("checked", "checked"); } else { acceptInput.removeAttribute("checked", "checked"); } } render() { const contactTitle = "Заполните данные"; return ( <section className="contact" id="contact"> <h2 className="contact-title">{contactTitle}</h2> <form className="contact-form" onSubmit={this.handleSubmit}> <input className="contact-input" id="fullNameInput" type={this.state.fullName.type} value={this.state.fullName.value} name={this.state.fullName.name} pattern="^[А-Яа-яЁё\s]+$" placeholder="ФИО" required maxLength="30" minLength="2" onChange={this.handleChange} /> <br /> <InputMask {...this.props} mask="+7 (999) 999 99 99" maskChar=" " className="contact-input" id="phoneInput" type={this.state.phone.type} value={this.state.phone.value} name={this.state.phone.name} placeholder="Телефон" required onChange={this.handleChange} ref={ref => this.phoneInput = ref} /> <br /> <input className="contact-input" id="emailInput" type={this.state.email.type} value={this.state.email.value} name={this.state.email.name} pattern="[^@\s]+@[^@\s]+" placeholder="<EMAIL>" required maxLength="20" minLength="6" onChange={this.handleChange} /> <br /> <input className="contact-input" id="addressInput" type={this.state.address.type} value={this.state.address.value} name={this.state.address.name} placeholder="Адрес доставки" required maxLength="50" minLength="10" onChange={this.handleChange} ref={ref => this.addressInput = ref} /> <br /> <p className="contact-input--checkbox" > <input type={this.state.accept.type} name={this.state.accept.name} id="acceptInput" required onClick={(e) => this.handleChecked(e)} /> <label htmlFor="acceptInput" className="material-icons" > <span>Я согласен на <a href="">обработку персональных<wbr />данных</a></span> </label> </p> <button className="contact-button">Далее</button> </form> </section> ); } } export default Contact;
<filename>Exercises/Ex04-ObjectComposition/02-ConstructionCrew/constructionCrew.js function solve(worker) { if (worker["handsShaking"] === true){ worker["bloodAlcoholLevel"] += worker["weight"] * worker["experience"] * 0.1; worker["handsShaking"] = false; } return worker; } console.log(solve({ weight: 95, experience: 3, bloodAlcoholLevel: 0, handsShaking: false } ));
# https://docs.docker.com/buildx/working-with-buildx/#build-multi-platform-images [[ -z "${IMAGE:-}" ]] && IMAGE='test' [[ -z "${TAG:-}" ]] && TAG='latest' docker buildx build -t ${IMAGE}:${TAG} --platform linux/amd64 .
<gh_stars>1-10 package main import ( "fmt" "os" "os/exec" "strings" ) var version = "0.1.0" var helpMsg = `NAME: ext - A convention for command extensions USAGE: ext commands... ` func main() { defer rescue() if len(os.Args) < 2 { fmt.Println(helpMsg) os.Exit(1) } switch os.Args[1] { case "-h", "--help": fmt.Println(helpMsg) os.Exit(0) case "-v", "--version": fmt.Println(version) os.Exit(0) } extArgs, err := LookupExtCmd(os.Args[1:]) if err != nil { fmt.Println(err) } extCmd := exec.Command(extArgs[0], extArgs[1:]...) extCmd.Stdin = os.Stdin extCmd.Stdout = os.Stdout extCmd.Stderr = os.Stderr extCmd.Run() } func LookupExtCmd(args []string) ([]string, error) { var err error for i := len(args); i > 0; i-- { extCmd := strings.Join(args[0:i], "-") bin, err := exec.LookPath(extCmd) if err == nil { extArgs := []string{bin} extArgs = append(extArgs, args[i:]...) return extArgs, nil } } return nil, err } func rescue() { if err := recover(); err != nil { args := strings.Join(os.Args, " ") fmt.Printf("Command Failed: %s\n%s\n", args, err) os.Exit(1) } }
<filename>src/scripts/reducers/index.js<gh_stars>0 import combineReducers from "react-combine-reducers"; import genres from "./genres"; import movies from "./movies"; export const reducer = combineReducers({ movies, genres }); console.log(1, reducer, genres, movies); export default reducer;
// Copyright 2017 <NAME>. All rights reserved. // // TODO(tep): Add requisite licensing preamble // Package timespan provides a broad-scaled extension to time.Duration. // // This package provides two types: // // Timespan - An extension to time.Duration // Time - an alias for time.Time (to ease use of Timespan values) // // Most of the functionality provided here is available using functions from // the standard "time" package and is provided here merely as a convenience. // // However, this package's raison d'être is the function ParseTimespan, which // provides the ability to specify a wide variety of broad-scaled time periods // -- from nanoseconds to many years -- as a simple, string value similar to // that parseable by time.ParseDuration. // // For example, a time span of "1 year, 6 months" is specified as "1Y6M" // or, its virtual equivalent, "18 months" as a simple "18M". Timespan // strings can be as simple as "3W" for "3 weeks" or something crazy like // "1Y2M3W4D5h6m7s89ms" which is (hopefully) quite self explanatory. // // Motivation // // Unlike the standard time.Duration, which only provides accuracy and // parseability at resolutions less than a day, a Timespan may cover many days, // weeks, months or even years. It also encapsulates a time.Duration value to // allow for resolutions as small a nanosecond. // // The ambiguities around the length of a day or month (or even year) that // restrict the broader scope of time.Duration are not a problem with Timespan // since it stores each, distinctly varying magnitude separately. // // That said, a Timespan by itself is inherently ambiguous and only acquires // precision when considered in the context of a specific point in time. // Because of this, two separate Timespan values may be functionally equivalent // from the perspective of one point in time but not from another. // // As an example, consider the Timespan values of "2 days" and "48 hours". In // most cases, these two are functionally equivalent; 48 hours is always 48 // hours yet 2 days is sometimes not 48 hours. In the approach to a daylight // savings time cutover, the "2 days" value would be either 47 or 49 hours // (depending on whether we're "springing forward" or "falling back"). // // In most cases however, these ambiguities are understood at the human level // and Timespan will behave as the user intends without much further thought. // // Parsing // // A Timespan string is the conjunction of one or more periods (as // coefficient+magnitude pairs) plus an optional time.Duration string. // // Parsing is governed by the following rules: // // 1. Each period is a coefficient magnitude pair where the coefficient is // a signed integer value and its magnitude is one of the following // single-character indicators: // // Y: Years // M: Months // W: Weeks // D: Days (or optionally 'd') // // 2. Each successive period must be specified in a decreasing magnitude order. // In other words, years must be specified before months and months before // weeks, etc... Periods specified out of order will cause an error. // // 3. The magnitude of each period must be distinct; any restated magnitude // (e.g. "3W-1W"), causes a parsing error. // // 4. The positive or negative sense of each coefficient may be implied or // expressly stated. By default, values are assumed positive until one is // explicitly declared to be negative. Subsequent (implicitly signed) values // are assumed to be negative until an explicit positive coefficient is // encountered. // // 5. Zero value magnitudes may be omitted. // // 6. Each specified magnitude must be accompanied by a coefficient. // // 7. No whitespace is allowed anywhere in the string. // // 8. If supplied, the optional time.Duration string must be at the end of the // string and must (of course) be parseable by time.ParseDuration. // // The natural tendency while parsing a Timespan string is to assume a negative // sign commutes across successive values until it is reversed. In other words, // the stated positive or negative sign is always "sticky" for later values. // // For example, "-1Y2M" is parsed to {Years: -1, Months: -2}. If your intent is // instead for "Years" to be negative and "Months" to be positive (e.g. {Years: // -1, Months: +2}), you must explicitly change the sign back to positive with // "-1Y+2M". // // Since a week is always 7 days, the available "W" magnitude is provided // merely as a convenience; it is not stored as part of the Timespan value. // Coefficients provided in weeks are stored as multiples of 7 days. // // If ParseTimespan is unable to parse the given string, it returns nil and an // appropriate error. // // Grammar // // Finally, for those so inclined, the formal grammar for a Timespan string // is shown in the following Pseudo-BNF: // // <timespan> := <periods> // | <duration> // | <periods> <duration> // // <periods> := <period> // | <periods> <period> // // <period> := <coefficient> MAGNITUDE // | SIGN <coefficient> MAGNITUDE // // <coefficient> := DIGIT // | <coefficient> DIGIT // // DIGIT := '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' // // SIGN := '-' | '+' // // MAGNITUDE := 'Y' | 'M' | 'W' | 'D' | 'd' // // <duration> := {Anything parseable by time.ParseDuration} // package timespan // import "toolman.org/timespan" import ( "fmt" "strings" "time" ) // A Timespan represents a span of time with wide and varying resolutions. // type Timespan struct { // Years in this Timespan Years int // Months in this Timespan Months int // Days in this Timespan Days int // A time.Duration for finer resolutions Duration time.Duration } // ParseTimespan returns a pointer to a new Timespan value which is the result // of parsing a string representation for the desired Timespan. // func ParseTimespan(s string) (*Timespan, error) { ts := &Timespan{} // If s contains no Timespan magnitude characters. we'll short-circuit // to only parsing a time.Duration. if strings.IndexAny(s, "YMWDd") == -1 { var err error if ts.Duration, err = time.ParseDuration(s); err != nil { return nil, timespanError(badDurationErr, err.Error()) } return ts, nil } ms := newMagset() sign := 1 valid := false coef := newCoefficient() for i, r := range s { if d, err := time.ParseDuration(s[i:]); err == nil { ts.Duration = d valid = true break } if ok, err := coef.appendRune(r); err != nil { return nil, err.withTimespan(s) } else if ok { continue } v, err := coef.value(sign) if err != nil { return nil, err.withTimespan(s) } if err := ms.set(r, v); err != nil { return nil, err.withTimespan(s) } if v < 0 { sign = -1 } else { sign = 1 } valid = true coef = newCoefficient() } if !valid { return nil, fmt.Errorf("no value derived for Timespan %q", s) } ts.Years = ms.get('Y') ts.Months = ms.get('M') ts.Days = ms.get('D') ts.Days += ms.get('W') * 7 return ts, nil } // String renders a Timespan into a form parseable by ParseTimespan. func (ts *Timespan) String() string { s := "" if ts.Years != 0 { s = fmt.Sprintf("%dY", ts.Years) } if ts.Months != 0 { s = fmt.Sprintf("%s%dM", s, ts.Months) } if ts.Days != 0 { s = fmt.Sprintf("%s%dD", s, ts.Days) } if ts.Duration != 0 { s = fmt.Sprintf("%s%v", s, ts.Duration) } return s } // From returns the time.Time that results from applying the Timespan ts to the // point in time t. This is shorthand for: // // t.AddDate(ts.Years, ts.Months, ts.Days).Add(ts.Duration) // func (ts *Timespan) From(t time.Time) time.Time { return t.AddDate(ts.Years, ts.Months, ts.Days).Add(ts.Duration) } // Add returns a new *Timespan that is result of adding each member of ots to // its corresponding member in ts. No combining, reduction or carry-over is // performed. // // For example, if you add two Timespan values of 8 and 9 months, the result is // always a Timespan value of 17 months (never 1 Year, 5 Months). // func (ts *Timespan) Add(ots *Timespan) *Timespan { return &Timespan{ Years: ts.Years + ots.Years, Months: ts.Months + ots.Months, Days: ts.Days + ots.Days, Duration: ts.Duration + ots.Duration, } } // Equal determines whether two Timespans are exactly equivalent to each other. // Each member in ts is compared to its corresponding member in ots and all must // be equivalent for Equal to return true. // // The Timespan values of "2 Days" and "48 Hours" are never equivalent in this // context. // func (ts *Timespan) Equal(ots *Timespan) bool { return ts.Duration == ots.Duration && ts.Days == ots.Days && ts.Months == ots.Months && ts.Years == ots.Years } // EqualAt determines whether two Timespans are functionally equivalent. The // Timespan values ts and ots are each evaluated at Time t and the result of // each is compared. EqualAt returns true iff the two evluations resolve to the // same point in time. // func (ts *Timespan) EqualAt(ots *Timespan, t time.Time) bool { return ts.From(t).Sub(t) == ots.From(t).Sub(t) } // Time is a convenience alias for time.Time provided simply to act as // a receiver for the methods below. // type Time time.Time // Add returns a new Time value after applying the given Timespan // func (t Time) Add(ts *Timespan) Time { return Time(ts.From(time.Time(t))) } // TimespansEqual compares the two Timespan values in the context of this Time. // This is the same as: // // ts1.EqualAt(ts2, time.Time(t)) // func (t Time) TimespansEqual(ts1, ts2 *Timespan) bool { return ts1.EqualAt(ts2, time.Time(t)) } // String is shorthand for time.Time(t).String() and is provided to implement // the fmt.Stringer interface. // func (t Time) String() string { return time.Time(t).String() }
/* * Copyright 2021 HM Revenue & Customs * * 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 uk.gov.hmrc.taxhistory.fixtures import play.api.libs.json.JsValue import uk.gov.hmrc.tai.model.rti.RtiEmployment import uk.gov.hmrc.taxhistory.model.utils.TestUtil trait RtiEmployments extends TestUtil { lazy val rtiEmploymentResponse: JsValue = loadFile("/json/rti/response/dummyRti.json") val rtiERTaxablePayTotal: BigDecimal = BigDecimal.valueOf(20000.00) val rtiERTaxTotal: BigDecimal = BigDecimal.valueOf(1880.00) lazy val rtiPartialDuplicateEmploymentsResponse: JsValue = loadFile("/json/rti/response/dummyRtiPartialDuplicateEmployments.json") lazy val rtiNonMatchingEmploymentsResponse: JsValue = loadFile("/json/rti/response/dummyRtiNonMatchingEmployment.json") val rtiEmployment1: RtiEmployment = RtiEmployment(1,"offNo1","ref1",currentPayId = None, payments = Nil, earlierYearUpdates = Nil) val rtiEmployment2: RtiEmployment = RtiEmployment(5,"offNo2","ref2",currentPayId = None, payments = Nil, earlierYearUpdates = Nil) val rtiEmployment3: RtiEmployment = RtiEmployment(3,"offNo3","ref3",currentPayId = None, payments = Nil, earlierYearUpdates = Nil) val rtiEmployment4: RtiEmployment = RtiEmployment(4,"offNo4","ref4",currentPayId = None, payments = Nil, earlierYearUpdates = Nil) }
#!/usr/bin/env bash # # Copyright © 2015-2016 Cask Data, Inc. # # 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. # Logic: # Get version # s3cmd ls to see if repo exists # - yes, sync repo local # - no, create repo dir # copy new packages into repo dir # create repo # sign repo # create tarball # Find our location and base repo directory # Resolve links: $0 may be a link PRG=${0} # Need this for relative symlinks. while [ -h ${PRG} ]; do ls=`ls -ld ${PRG}` link=`expr ${ls} : '.*-> \(.*\)$'` if expr ${link} : '/.*' > /dev/null; then PRG=${link} else PRG=`dirname ${PRG}`/${link} fi done cd `dirname ${PRG}`/.. >&- DISTRIBUTIONS_HOME=`pwd -P` cd `dirname ${DISTRIBUTIONS_HOME}` >&- REPO_HOME=`pwd -P` TARGET_DIR=${DISTRIBUTIONS_HOME}/target STAGE_DIR=${TARGET_DIR}/aptrepo S3_BUCKET=${S3_BUCKET:-repository.cask.co} S3_REPO_PATH=${S3_REPO_PATH:-ubuntu/precise/amd64/cdap} # No leading or trailing slashes VERSION=${VERSION:-$(basename ${TARGET_DIR}/*.deb | head -n 1 | cut -d_ -f2 | cut -d- -f1)} GPG_KEY_NAME=${GPG_KEY_NAME:-${1}} GPG_PASSPHRASE=${GPG_PASSPHRASE:-${2}} __version=${VERSION/-SNAPSHOT/} __maj_min=$(echo ${__version} | cut -d. -f1,2) function die() { echo "ERROR: ${1}" 1>&2; exit 1; } function repo_exists() { if [[ $(s3cmd ls s3://${S3_BUCKET}/${S3_REPO_PATH}/ | grep ${__maj_min}) ]]; then return 0 else return 1 fi } function setup_repo_staging() { mkdir -p ${STAGE_DIR} || return 1 # Create initial Freight repository freight-init \ --gpg=${GPG_KEY_NAME} \ --conf=${STAGE_DIR}/freight.conf \ --libdir=${STAGE_DIR}/lib \ --cachedir=${STAGE_DIR}/${__maj_min} \ --archs=amd64 \ --origin=Cask \ --label=Cask \ ${STAGE_DIR} || return $? # Sync old repository if repo_exists; then echo "Found existing repository at s3://${S3_BUCKET}/${S3_REPO_PATH}/${__maj_min}... copying to staging directory" mkdir -p ${STAGE_DIR}/__tmpdir s3cmd sync --no-preserve s3://${S3_BUCKET}/${S3_REPO_PATH}/${__maj_min} ${STAGE_DIR}/__tmpdir return $? fi return 0 } function add_packages_to_repo_staging() { echo "Adding packages to freight library" mkdir -p ${STAGE_DIR}/lib/apt/precise/cdap || return 1 # __old_repo = ${STAGE_DIR}/__tmpdir/${__maj_min}/pool/${UBUNTU_RELEASE_NAME}/${APT_COMPONENT}/[:alpha:]/${PACKAGE_NAME}/*.deb local __old_repo=$(ls -1 ${STAGE_DIR}/__tmpdir/*/*/*/*/*/*/*.deb 2>/dev/null) if [ -n "${__old_repo}" ]; then for __deb in ${__old_repo}; do cp -f ${__deb} ${STAGE_DIR}/lib/apt/precise/cdap done fi for __deb in $(ls -1 ${REPO_HOME}/*/target/*.deb ${REPO_HOME}/target/*.deb 2>/dev/null); do echo "- ${__deb}" cp -f ${__deb} ${STAGE_DIR}/lib/apt/precise/cdap done } function write_gpg_passphrase() { echo ${GPG_PASSPHRASE} > ${STAGE_DIR}/gpgpass.tmp } function createrepo_in_repo_staging() { write_gpg_passphrase || return 1 echo "Creating repository ${__maj_min} in staging directory" freight-cache --conf=${STAGE_DIR}/freight.conf --gpg=${GPG_KEY_NAME} --passphrase-file=${STAGE_DIR}/gpgpass.tmp apt/precise || return 1 # Replace symlink rm -rf ${STAGE_DIR}/${__maj_min}/dists/precise{/.refs,} && mv ${STAGE_DIR}/${__maj_min}/dists/precise{-*,} || return 1 } function create_definition_file() { [ -f "${STAGE_DIR}/${__maj_min}/cask.list" ] && return echo "Create APT repository definition file" cd ${STAGE_DIR}/${__maj_min} cat <<EOF > cask.list deb [ arch=amd64 ] http://${S3_BUCKET}/${S3_REPO_PATH}/${__maj_min} precise cdap EOF } function create_repo_tarball() { cd ${STAGE_DIR} echo "Create APT repository tarball" # Delete any previous tarballs rm -f ${TARGET_DIR}/cdap-aptrepo-${__maj_min}.tar.gz tar zcf ${TARGET_DIR}/cdap-aptrepo-${__maj_min}.tar.gz ${__maj_min} } # Here we go! setup_repo_staging || die "Something went wrong setting up the staging directory" add_packages_to_repo_staging || die "Failed copying packages to staging directory" createrepo_in_repo_staging || die "Failed to create repository from staging directory" create_definition_file || die "Failed to create repository definition file" create_repo_tarball || die "Failed to create APT repository tarball" echo "Complete: cdap-aptrepo-${__maj_min}.tar.gz created" exit 0 # We made it!
// Define the Platform enum to represent different platforms and their minimum versions enum Platform { case iOS(Int) case android(Int) // Add more cases for other platforms if needed } // Create the PlatformManager class class PlatformManager { var platforms: [String: Platform] = [:] // Method to add a new platform and its minimum version func addPlatform(name: String, platform: Platform) { platforms[name] = platform } // Method to retrieve the minimum version for a given platform func minimumVersion(for platformName: String) -> Int? { if let platform = platforms[platformName] { switch platform { case .iOS(let version), .android(let version): return version } } return nil } } // Usage example let manager = PlatformManager() manager.addPlatform(name: "iOS", platform: .iOS(9)) manager.addPlatform(name: "android", platform: .android(7)) // Retrieve minimum version for a platform if let minimumVersion = manager.minimumVersion(for: "iOS") { print("Minimum iOS version required: \(minimumVersion)") } else { print("Platform not found") }
package com.heima.common.common.storage; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; /** * 一个存储的实体 */ @Setter @Getter public class StorageEntity { /** * 存储类型的列表 * 一个实体可以存储多个数据列表 */ private List<StorageData> dataList = new ArrayList<StorageData>(); /** * 添加一个存储数据 * @param storageData */ public void addStorageData(StorageData storageData) { dataList.add(storageData); } }
from django.db import models from django.forms import ModelForm class Task(models.Model): name = models.CharField(max_length=200) description = models.TextField() class TaskForm(ModelForm): class Meta: model = Task fields = ['name', 'description'] #views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Task from .forms import TaskForm def task_list(request): tasks = Task.objects.all() return render(request, 'task_list.html', {'tasks': tasks}) def create_task(request): form = TaskForm(request.POST or None) if form.is_valid(): form.save() return redirect('task_list') def edit_task(request, id): task = get_object_or_404(Task, pk=id) form = TaskForm(request.POST or None, instance=task) if form.is_valid(): form.save() return redirect('task_list') def delete_task(request, id): task = get_object_or_404(Task, pk=id) task.delete() return redirect('task_list')
<filename>src/java/RingBullet.java<gh_stars>1-10 import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; public class RingBullet extends Bullet{ RingBullet(int x, int y, int direction){ super(x,y,direction); this.velocity = 0.7f; this.power = 1; try{ this.bulletImage = ImageIO.read(new File("assets/ringBulletImage.png")); } catch(IOException e){ e.printStackTrace(); } } }
<gh_stars>1-10 # Generated by Django 3.0.6 on 2020-05-20 14:58 from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ ("reporting", "0005_auto_20200520_1438"), ] operations = [ migrations.AlterField( model_name="encampment", name="location", field=models.CharField( help_text="An intersection or address. Adding a city/state can help accuracy.", max_length=250, ), ), migrations.AlterField( model_name="encampment", name="name", field=models.CharField( help_text="A descriptive name for the encampment, which may be based on the address.", max_length=100, ), ), ]
#!/bin/bash ansible-playbook -i ./inventory/prod/k8s.ini k8s-pre.yml
<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.facebook = void 0; var facebook = { "viewBox": "0 0 1024 1792", "children": [{ "name": "path", "attribs": { "d": "M959 12v264h-157q-86 0-116 36t-30 108v189h293l-39 296h-254v759h-306v-759h-255v-296h255v-218q0-186 104-288.5t277-102.5q147 0 228 12z" } }] }; exports.facebook = facebook;
<reponame>Vladimir-Anfimov/oop-2022 #pragma once #include <string> class Carte { public: virtual std::string GetInfo() = 0; };
#!/bin/sh # This is a generated file; do not edit or check into version control. export "FLUTTER_ROOT=E:\FlutterSdk" export "FLUTTER_APPLICATION_PATH=D:\ASProjects\rammus\example" export "FLUTTER_TARGET=lib\main.dart" export "FLUTTER_BUILD_DIR=build" export "SYMROOT=${SOURCE_ROOT}/../build\ios" export "OTHER_LDFLAGS=$(inherited) -framework Flutter" export "FLUTTER_FRAMEWORK_DIR=E:\FlutterSdk\bin\cache\artifacts\engine\ios" export "FLUTTER_BUILD_NAME=1.0.0" export "FLUTTER_BUILD_NUMBER=1"
<reponame>songningbo/jdk8source /* * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.webkit.dom; import org.w3c.dom.html.HTMLUListElement; public class HTMLUListElementImpl extends HTMLElementImpl implements HTMLUListElement { HTMLUListElementImpl(long peer) { super(peer); } static HTMLUListElement getImpl(long peer) { return (HTMLUListElement)create(peer); } // Attributes public boolean getCompact() { return getCompactImpl(getPeer()); } native static boolean getCompactImpl(long peer); public void setCompact(boolean value) { setCompactImpl(getPeer(), value); } native static void setCompactImpl(long peer, boolean value); public String getType() { return getTypeImpl(getPeer()); } native static String getTypeImpl(long peer); public void setType(String value) { setTypeImpl(getPeer(), value); } native static void setTypeImpl(long peer, String value); }
#!/bin/bash : ${REGION:=$(aws configure get region)} : ${ACCOUNT_ID:=$(aws sts get-caller-identity|jq -r ".Account")} ########################################################### ########### ########### ########################################################### logger() { LOG_TYPE=$1 MSG=$2 COLOR_OFF="\x1b[39;49;00m" case "${LOG_TYPE}" in green) # Green COLOR_ON="\x1b[32;01m";; blue) # Blue COLOR_ON="\x1b[36;01m";; yellow) # Yellow COLOR_ON="\x1b[33;01m";; red) # Red COLOR_ON="\x1b[31;01m";; default) # Default COLOR_ON="${COLOR_OFF}";; *) # Default COLOR_ON="${COLOR_OFF}";; esac TIME=$(date +%F" "%H:%M:%S) echo -e "${COLOR_ON} ${TIME} -- ${MSG} ${COLOR_OFF}" # echo -e "${TIME} -- ${MSG}" >> "${LOG_OUTPUT}" } errorcheck() { if [ $? != 0 ]; then logger "red" "Unrecoverable generic error found in function: [$1]. Check the log. Exiting." exit 1 fi } welcome() { logger "red" "*******************************" logger "red" "*** install proxy service ***" logger "red" "*******************************" } tag() { logger "red" "*****************tag********************************" if [[ $REGION = "cn-northwest-1" ]] || [[ $REGION = "cn-north-1" ]]; then docker tag video-streaming-proxy $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com.cn/video-streaming-proxy:latest else docker tag video-streaming-proxy $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/video-streaming-proxy:latest fi } push() { logger "red" "*****************push********************************" if [[ $REGION = "cn-northwest-1" ]] || [[ $REGION = "cn-north-1" ]]; then docker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com.cn/video-streaming-proxy:latest else docker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/video-streaming-proxy:latest fi } ecr() { logger "red" "*****************create ecr********************************" aws cloudformation deploy \ --template-file proxy/stacks/ecr.stack.yml \ --stack-name video-streaming-proxy-ecr \ --capabilities CAPABILITY_IAM \ --parameter-overrides \ RepositoryName=video-streaming-proxy \ ${PROFILE} } service() { if [[ $REGION = "cn-northwest-1" ]] || [[ $REGION = "cn-north-1" ]]; then aws cloudformation deploy \ --template-file proxy/stacks/service.stack-cn.yml \ --stack-name video-streaming-proxy \ --capabilities CAPABILITY_NAMED_IAM \ --parameter-overrides \ Version=1.0.9 \ DesiredCount=1 \ ${PROFILE} else aws cloudformation deploy \ --template-file proxy/stacks/service.stack.yml \ --stack-name video-streaming-proxy \ --capabilities CAPABILITY_NAMED_IAM \ --parameter-overrides \ Version=1.0.9 \ DesiredCount=1 \ ${PROFILE} fi } main() { welcome # ecr # tag # push service } main
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for RHSA-2012:0308 # # Security announcement date: 2012-02-21 04:53:04 UTC # Script generation date: 2017-01-01 21:13:51 UTC # # Operating System: Red Hat 5 # Architecture: x86_64 # # Vulnerable packages fix on version: # - busybox.x86_64:1.2.0-13.el5 # - busybox-anaconda.x86_64:1.2.0-13.el5 # # Last versions recommanded by security team: # - busybox.x86_64:1.2.0-13.el5 # - busybox-anaconda.x86_64:1.2.0-13.el5 # # CVE List: # - CVE-2006-1168 # - CVE-2011-2716 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo yum install busybox.x86_64-1.2.0 -y sudo yum install busybox-anaconda.x86_64-1.2.0 -y
/* * Copyright (c) 2021 - <NAME> - https://www.yupiik.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.yupiik.bundlebee.core.service; import io.yupiik.bundlebee.core.descriptor.Manifest; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class RequirementService { public void checkRequirements(final Manifest manifest) { if (manifest.getRequirements() == null) { return; } manifest.getRequirements().forEach(this::check); } private void check(final Manifest.Requirement requirement) { if (requirement.getMinBundlebeeVersion() != null && !requirement.getMinBundlebeeVersion().isBlank() && !compareVersion(requirement.getMinBundlebeeVersion(), true)) { throw new IllegalArgumentException("Invalid bundlebee version: " + getBundlebeeVersion() + " expected-min=" + requirement.getMinBundlebeeVersion()); } if (requirement.getMaxBundlebeeVersion() != null && !requirement.getMaxBundlebeeVersion().isBlank() && !compareVersion(requirement.getMaxBundlebeeVersion(), false)) { throw new IllegalArgumentException("Invalid bundlebee version: " + getBundlebeeVersion() + " expected-max=" + requirement.getMaxBundlebeeVersion()); } if (requirement.getForbiddenVersions() != null) { requirement.getForbiddenVersions().forEach(version -> { if (compareVersion(version, null)) { throw new IllegalArgumentException("Invalid bundlebee version: " + getBundlebeeVersion() + " forbidden=" + requirement.getForbiddenVersions()); } }); } } protected String getBundlebeeVersion() { return Constants.VERSION; } private String sanitize(final String version) { if (version.endsWith("-SNAPSHOT")) { return version.substring(version.length() - "-SNAPSHOT".length()); } return version; } private boolean compareVersion(final String version, final Boolean expectNegative) { final var expected = sanitize(version); final var actual = sanitize(getBundlebeeVersion()); final var expectedSegments = expected.split("\\."); final var actualSegments = actual.split("\\."); final int segmentLoopLength = Math.min(expectedSegments.length, actualSegments.length); for (int i = 0; i < segmentLoopLength; i++) { final var exp = expectedSegments[i]; if ("*".equals(exp)) { // TODO: suffix instead of the whole value? it is harder to configure then continue; } final var act = actualSegments[i]; if (exp.equals(act)) { continue; } try { final int expInt = Integer.parseInt(exp); final int actInt = Integer.parseInt(act); final int comp = expInt - actInt; if (expectNegative == null && comp != 0) { return false; } if (comp != 0) { return expectNegative ? comp < 0 : comp > 0; } } catch (final NumberFormatException nfe) { return false; } } return expectedSegments.length < actualSegments.length || // assume wildcard so it matches for the missing segment expectedSegments.length == actualSegments.length; } }
-- MySQL dump 10.13 Distrib 5.6.27, for debian-linux-gnu (x86_64) -- -- Host: 127.0.0.1 Database: blog_example -- ------------------------------------------------------ -- Server version 5.6.27-0ubuntu1 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `posts` -- DROP TABLE IF EXISTS `posts`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `posts` ( `id` int(4) unsigned NOT NULL AUTO_INCREMENT, `date` date DEFAULT NULL, `title` varchar(100) DEFAULT NULL, `resume` varchar(255) DEFAULT NULL, `content` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `posts` -- LOCK TABLES `posts` WRITE; /*!40000 ALTER TABLE `posts` DISABLE KEYS */; INSERT INTO `posts` VALUES (1,'2001-01-01','Eos nullam assentior','Scripta qualisque assueverit ea sed, possit possim nec at, everti adipisci gloriatur cu quo. Ut vix vivendo tincidunt intellegebat, pro nulla inciderint id, id scaevola nominati sed. Quod quas apeirian te vis. Est sint ancillae cu.','<p>Nam elit recusabo deterruisset no, pri no stet expetendis. At facer facilis temporibus vis, mea aliquip aliquid epicuri id. Usu putent omittantur ei, vim et fugit gloriatur. Cum no corpora adipisci qualisque, usu et tollit adipisci theophrastus, cu virtute mandamus cum.</p><p>Illud veritus accumsan per eu, propriae voluptaria delicatissimi quo ex. Vel cu epicurei pertinax. Ubique numquam theophrastus at mei, sea at qualisque patrioque. Ea dicit saepe usu, at nam exerci nostrud, cu rebum civibus mandamus qui. Ex latine dolorum voluptua mei, vis an alia facilisis.</p><p>Ex diam harum dolore pro. Ne has fugit quando petentium, tation scaevola praesent mea id, in tota salutatus efficiendi pro. Per fugit aperiri tincidunt cu. Vel deserunt pertinacia cu. Ius ad purto detracto reprehendunt, at ludus option sea, exerci audire id nam.</p>'),(2,'2005-01-15','An his harum iriure deterruisset.','Lorem ipsum dolor sit amet, amet alia appareat et mel, ei quo sumo summo definitionem. Discere ponderum et nec, sit illum argumentum ei.','<p>Nec id fugit impetus insolens, ad pro regione veritus eloquentiam, has graeci integre interpretaris cu. Eam bonorum ceteros persequeris ne, oblique delectus usu in, quo modus nominati no. Vide soleat cum in, dicam deterruisset eos no. Scaevola volutpat pri ad, delectus postulant ut vix, vis vivendum facilisis id. Per ipsum nulla eu, ut vim omnes vocent tibique, ex eos meis epicuri. Sit dicat graeci salutandi id, eu sea rebum eruditi quaerendum.</p><p>Placerat expetendis eos ad, ne nec iusto gubergren. Honestatis instructior vim ut, ex vim oratio essent viderer. Dico feugait disputationi eam no, in pri animal tamquam epicurei. In est iriure iudicabit, ut dicit elitr eos, vix ut ornatus fabellas elaboraret. Nisl illud ei eos, equidem percipitur has cu. Ea posse quando invidunt eum.</p>'),(3,'2005-03-22','Delicata signiferumque sea te.','Ad eos dictas bonorum assentior, laudem impedit id sea. Ut fierent elaboraret referrentur vel, eu homero torquatos sed. Sed principes assentior scripserit et,','<p>Eum nobis tation tractatos in, movet dolorum adversarium at eam. Per at prima omnes. Usu autem necessitatibus ad. Duis solum epicurei vim ne, no accumsan atomorum delicata pro. Pro id falli ridens, est platonem postulant an, et homero nominavi tacimates eam. Ea eam probo dicant. Pro habemus intellegat no, copiosae scaevola eleifend vel in, mundi complectitur pri ne.</p><p>Per paulo dolor deseruisse cu, discere nostrum phaedrum ius ut, mentitum electram ne vis. Ei porro error eos, ei augue vidisse eum, ex error luptatum petentium cum. Sit eu omnis ullum adipisci. Melius deseruisse te nec. Tollit exerci vix ex.</p><p>Appareat inciderint est cu, an possit dissentias per, usu omnis quidam dolores ea. Stet aeque ei quo, mel at denique reprimique. Id nec prima virtute. Vim ei saepe detracto.</p>'),(4,'2006-06-12','Sea dicant impetus imperdiet at,','Dolor integre definiebas usu ea. In timeam assentior est,','<p>Agam possit patrioque vis no. Cum et veri adhuc. Te nobis consetetur eam, laoreet appareat antiopam id mea. Movet nostrud noluisse pro et. Falli veritus mnesarchum ad quo, adhuc paulo cum te. Paulo discere disputando ut eum, ne veritus menandri assentior usu, vix lorem nostrud sapientem ex. Inermis antiopam quaerendum ius ad.</p><p>Vidit tollit aliquip et ius. Accusamus suscipiantur mea eu, ne nec ludus omnium fuisset. Eius veri consectetuer mei ex, an quot invidunt vix. Te movet tamquam reprehendunt nam, modo mollis vix ex. Eos quod nemore no.</p>'),(5,'2015-01-22','Te ferri singulis eos, ius quando antiopam no.','Possit iracundia definitiones per an. Ornatus urbanitas moderatius est ea. Pri cu latine elaboraret, verear fabulas ad vix.','<p>Ius ea vidit dissentiunt, ne fierent pertinax interpretaris nec. At erat iuvaret quo. Ex sea paulo putent intellegam. Ne mel eripuit senserit, in vix numquam feugait senserit. Cu usu atqui nulla viris. Solet urbanitas assentior cu vel, ei vim alii expetendis.</p><p>Eu eum molestie percipitur. Admodum intellegebat ad duo, nam novum consul civibus in. Pri ut clita graecis euripidis, ea sit brute dicat. Ex vix regione numquam efficiendi, vim ex rebum utroque euripidis. Omnium philosophia theophrastus an quo. Wisi dictas ea ius.</p><p>Mel audiam utroque quaestio te. Propriae recusabo delicatissimi ea nam. Per ad insolens delicatissimi, eam et denique appellantur. Dico iriure pri id. Accumsan iracundia reprehendunt sea ut, ad tamquam posidonium his, sed duis error zril te. Eos eius doctus comprehensam id, ea mea tale salutandi honestatis, ad quo vidit omnis.</p>'),(6,'2007-05-12','No nec consul consequat assueverit.','Te dico voluptua indoctum per, simul dicant definitiones ex pri.','<p>Id bonorum argumentum pri. Partiendo forensibus referrentur duo ea. Volutpat temporibus eu eum. No qui impedit perpetua theophrastus, vim ut amet utamur. Eam ne elit solet soleat, pri an virtute torquatos.</p><p>Atomorum contentiones an pri, sed no odio illud mollis. Tollit labore elaboraret ea usu, tale albucius eum cu. Id summo salutandi explicari vel, in habeo causae deterruisset his. Graecis forensibus eu qui, deleniti constituto ei mei. Vivendo platonem et vix. Percipitur mediocritatem cum an, mnesarchum reformidans delicatissimi ei sea.</p>'),(7,'2013-07-14','Veri vivendo alienum cum cu.','Et modo paulo phaedrum est, et eos.','<p>Veri vivendo alienum cum cu, doming civibus lucilius mel at, eu exerci accumsan pri. Ea idque facer forensibus nec. Eligendi evertitur ex mel, elit causae reformidans eu sit. Ad denique voluptatum mel, usu ex sint definitiones.</p><p>Enim dicta mel eu, eos ad case dictas, no vis zril putent ponderum. Sea aeque iudico principes at, in oblique omittantur theophrastus qui, ut his meis numquam gloriatur. Accusamus molestiae honestatis ex nec, ad odio mollis graecis has. Cu vide feugiat accusata cum. Mea ex accommodare intellegebat. An nobis regione verterem quo, quo id vocent audire.</p><p>Eu est sint dolor, no mei fastidii facilisi consequat. Duo at tempor convenire, in fastidii legendos constituam duo. Ne vide fastidii prodesset sed, eu sit omnesque dignissim posidonium. Qui ut eirmod integre intellegat, eum vide quaeque necessitatibus ut, pro ne error lobortis gubergren. At novum dissentiunt eos, id qui velit graeci, error eripuit menandri mea ex. Te bonorum senserit mediocritatem vis, in epicurei menandri intellegam mea.</p><p>Mei luptatum concludaturque ea, mei ea laboramus argumentum. Augue signiferumque eu mea, nonumes mediocritatem te nec. Ad novum erroribus complectitur vis, et nibh delenit sit, mel an consul commune. Ius prima nostrud suscipit no, ea mutat error dicit pri, pro an nobis suscipit recteque. Nam id aliquip docendi inimicus.</p>'); /*!40000 ALTER TABLE `posts` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2016-04-06 13:20:54
import requests from bs4 import BeautifulSoup # Make the request to the website url = 'https://example.com/search?query=best+laptops+for+gaming' page = requests.get(url) # Parse the html content soup = BeautifulSoup(page.content, 'html.parser') # Extract the search results results = soup.find_all('div', class_='search_result_row') # Store the results in a list results_list = [] for result in results: results_list.append(result.text)
var searchData= [ ['getbyte',['GetByte',['../usart3_8c.html#a05a3d555d7db61ea60d126ad67129b0b',1,'usart3.c']]] ];
#ifndef NLIB_ACCEPTOR_H #define NLIB_ACCEPTOR_H #include "../Lib/lib.h" class EventLoop; class InetAddress; class Acceptor { public: typedef std::function<void ( int sockfd, const InetAddress&)> NewConnectionCallback; Acceptor( EventLoop* loop, const InetAddress& listenAddr, bool reuseport); ~Acceptor(); void setNewConnectionCallback(const NewConnectionCallback& cb) { m_nNewConnectionCallback = cb; } bool listenning() const { return m_bListenning; } void listen(); private: void handleRead(); EventLoop* m_pLoop; Socket m_nAcceptSocket; Channel m_nAcceptChannel; NewConnectionCallback m_nNewConnectionCallback; bool m_bListenning; int m_nIdleFd; }; #endif
<filename>04-first-class-entity/custom-generic-controller-typeorm/src/controller/person-controller.ts<gh_stars>1-10 import { CustomGenericController } from "../custom-generic-controller"; import { User } from "../entity/users-entity"; // example usage of custom generic controller factory, // we used user entity but set different route to avoid conflict export class PersonController extends CustomGenericController(User, c => c.setPath("persons/:id")) { }