text
stringlengths
1
1.05M
#!/bin/bash # # Usage: ./create_my_python_buildpack.sh <buildpack-dir> # if [[ $1 ]]; then echo "Creating a new python buildpack in ${buildpack_dir}" else echo "Usage: ./create_my_python_buildpack.sh <buildpack-dir>" exit 1 fi buildpack_dir="$1" bin_dir="${buildpack_dir}/bin" resources_dir="${buildpack_dir}/resources" modules_dir="${resources_dir}/modules" pipzip="https://files.pythonhosted.org/packages/ce/ea/9b445176a65ae4ba22dce1d93e4b5fe182f953df71a145f557cffaffc1bf/pip-19.3.1.tar.gz#md5=1aaaf90fbafc50e7ba1e66ffceb00960" pipurl="https://pypi.org/project/pip/" setuptoolszip="https://files.pythonhosted.org/packages/ab/41/ab6ae1937191de0c9cbc115d0e91e335f268aa1cd85524c86e5970fdb68a/setuptools-42.0.0.zip#md5=0b79291e2781b707f5bc325b745b9c3c" setuptoolsurl="https://pypi.org/project/setuptools/" mkdir -p ${buildpack_dir} rm -rf ${buildpack_dir}/* mkdir -p ${buildpack_dir}/bin mkdir -p ${buildpack_dir}/resources mkdir -p ${buildpack_dir}/resources/modules echo "Creating bin/detect" cat > ${buildpack_dir}/bin/detect <<- "EOFDETECT" #!/usr/bin/env bash BUILD_DIR=$1 if [ ! -f $BUILD_DIR/runtime.txt ]; then exit 1 fi if grep -q python- "$BUILD_DIR/runtime.txt"; then echo detected `cat $BUILD_DIR/runtime.txt` exit 0 fi exit 1 EOFDETECT chmod 755 ${buildpack_dir}/bin/detect echo "Creating bin/compile" cat > ${buildpack_dir}/bin/compile <<- "EOFCOMPILE" #!/usr/bin/env bash FCOMPILE=`readlink -f "$0"` BPDIR=`dirname $FCOMPILE` BPDIR=`readlink -f "$BPDIR/.."` BUILD_DIR=$1 CACHE=$2 #HTTP_PROXY=proxy:8080 #export HTTPS_PROXY=http://proxy.wdf.sap.corp:8080 #export HTTP_PROXY=http://proxy.wdf.sap.corp:8080 if [ ! -f $BUILD_DIR/runtime.txt ];then echo echo BUILPACK: Abort. Cannot find runtime.txt in application directory. echo BUILPACK: Please provide runtime.txt with content Python-x.x.x , example Python-3.4.4 echo exit 1 fi runtime=`cat "$BUILD_DIR"/runtime.txt` minus=`expr index "$runtime" -` if [ "$minus" == "0" ];then echo "cannot understand runtime.txt" echo $runtime exit 1 fi lang=${runtime:0:minus} version=${runtime:minus} echo echo BUILDPACK: Detected language $lang echo BUILDPACK: Detected version $version echo versionxx=${version%.*} versionx=${versionxx%.*} mkdir -p work mkdir -p $CACHE/compiled/Python-$version runtimedir=`readlink -f "$BUILD_DIR/.buildpack"` mkdir -p $runtimedir pyexe=$runtimedir/bin/python PATH_PY=$runtimedir/lib/python$versionxx PATH_PY=$PATH_PY:$runtimedir/lib/python$versionxx/lib-dynload PATH_PY=$PATH_PY:$runtimedir/lib64/python$versionxx/lib-dynload PATH_PY=$PATH_PY:$runtimedir/lib/python$versionxx/plat-linux PATH_PY=$PATH_PY:$runtimedir/lib64/python$versionxx/plat-linux export PYTHONPATH=$PATH_PY export PYTHONHOME=$runtimedir pytgz=$CACHE/compiled/Python-${version}.tar.gz if [ ! -f $pytgz ];then pytgz=/tmp/Python-${version}.tar.gz fi if [ ! -f $pytgz ];then echo echo "BUILDPACK: Cached python build $pytgz not found" echo if [ ! -f $BPDIR/resources/python/Python-$version.tgz ];then echo echo "BUILDPACK: Downloading python source https://www.python.org/ftp/python/$version/Python-$version.tgz" echo wget -O work/Python-$version.tgz https://www.python.org/ftp/python/$version/Python-$version.tgz wgetexit=$? if [ $wgetexit -ne 0 ];then echo echo "BUILDPACK: Abort -- Python source download failed" echo "BUILDPACK: You can put python tar.gz in the BUILDPACK/resources/python and re-create the buildpack to avoid download from internet" echo exit $wgetexit fi else cp resources/python/Python-$version.tgz work fi gzip -d -f work/Python-$version.tgz tar -xf work/Python-$version.tar -C work if [ ! -f /usr/include/zlib.h ];then echo echo "BUILDPACK: Library zlib missing, not found /usr/include/zlib.h" echo d_zlib=work/Python-$version/Modules/zlib if [ -d $d_zlib ];then pushd $d_zlib echo echo "BUILDPACK: Build python provided zlib" echo ./configure --prefix=$runtimedir make -j 8 make install zmakeexit=$? if [ $zmakeexit -ne 0 ];then echo echo "BUILDPACK: Warning - failed to make install python provided zlib work/Python-$version/Modules/zlib" echo "BUILDPACK: Ignore last failure" echo fi popd else echo echo "BUILDPACK: Warning - Not found python provided zlib $d_zlib" echo fi fi pushd work/Python-$version echo echo "BUILDPACK: Installing python runtime to $runtimedir" echo ./configure --prefix=$runtimedir --exec-prefix=$runtimedir make -j 8 make altinstall makeexit=$? popd if [ $makeexit -ne 0 ];then echo echo BUILDPACK: Abort -> Make failed in buildpack compile step echo exit $makeexit fi if [ ! -f $pyexe ];then echo echo BUILDPACK: cp $runtimedir/bin/python$versionxx $pyexe echo cp $runtimedir/bin/python$versionxx $pyexe fi echo echo BUILDPACK: PYTHONPATH=$PYTHONPATH echo echo "BUILDPACK: Yo!" echo "pwd:" pwd echo "BUILDPACK: Copying files from resources/modules/*.tar.gz" echo $BPDIR/resources/modules/*.tar.gz echo for f in $BPDIR/resources/modules/*.tar.gz do echo " BUILDPACK: cp $f work" cp $f work fname_tar_gz=${f##*/} fname_tar=${fname_tar_gz%.*} echo " BUILDPACK: Unzip" echo " BUILDPACK: gzip -d -f work/$fname_tar_gz" gzip -d -f work/$fname_tar_gz echo " BUILDPACK: Xtract" echo " BUILDPACK: tar -xf work/$fname_tar -C work" tar -xf work/$fname_tar -C work done echo "BUILDPACK: Copying files from resources/modules/*.zip" echo $BPDIR/resources/modules/*.zip echo pwd for f in $BPDIR/resources/modules/*.zip do echo " BUILDPACK: cp $f work" cp $f work fname_zip=${f##*/} echo " BUILDPACK: Unzip" pushd work echo " BUILDPACK: unzip -q -u $fname_zip" unzip -q -u $fname_zip popd done echo "BUILDPACK: Build setuptools" pwd pushd work/setuptools* echo "BUILDPACK: $pyexe setup.py build install" $pyexe setup.py build install setupexit=$? if [ $setupexit -ne 0 ];then echo echo "BUILDPACK: Abort --> Failed to install python module setuptools" echo exit $setupexit fi popd echo "BUILDPACK: Build pip" pushd work/pip* echo "BUILDPACK: $pyexe setup.py build install" $pyexe setup.py build install setupexit=$? if [ $setupexit -ne 0 ];then echo echo "BUILDPACK: WARNING --> Ignored:Failed to install python module pip" echo fi popd tar -cf $CACHE/compiled/Python-$version.tar -C $runtimedir . gzip $CACHE/compiled/Python-$version.tar echo echo BUILDPACK: Cached python build $CACHE/compiled/Python-$version.tar.gz echo cp $CACHE/compiled/Python-$version.tar.gz /tmp/Python-$version.tar.gz else echo echo "BUILDPACK: Cached python build found $pytgz" echo cp $pytgz work gzip -d -f work/Python-$version.tar.gz tar -xf work/Python-$version.tar -C $runtimedir fi echo echo "BUILDPACK: Python executable $pyexe" echo `"$pyexe" --version` echo moduleinstall=0 if [ -f $BUILD_DIR/requirements.txt ];then echo echo BUILDPACK: Try to execute python -m pip install -r r$BUILD_DIR/requirements.txt echo $pyexe -m pip install -r $BUILD_DIR/requirements.txt moduleinstall=$? fi if [ $moduleinstall -ne 0 ] && [ -d $BUILD_DIR/vendor ];then echo echo "BUILDPACK: Install app vendor packages using pip" echo $pyexe -m pip install $BUILD_DIR/vendor/* echo $pyexe -m pip install $BUILD_DIR/vendor/* moduleinstall=$? if [ $moduleinstall -ne 0 ];then echo echo "BUILDPACK: Install app vendor tar.gz packages without pip" echo for f in $BUILD_DIR/vendor/*.tar.gz do if [ -f $f ];then echo echo "BUILDPACK: Installing vendor package $f" echo cp $f work fname_tar_gz=${f##*/} fname_tar=${fname_tar_gz%.*} fname=${fname_tar%.*} gzip -d -f work/$fname_tar_gz tar -xf work/$fname_tar -C work pushd work/$fname $pyexe setup.py build install popd fi done fi fi EOFCOMPILE chmod 755 ${buildpack_dir}/bin/compile echo "Creating bin/release" cat > ${buildpack_dir}/bin/release <<- "EOFRELEASE" #!/usr/bin/env bash set -e BUILD_DIR=$1 FRELEASE=`readlink -f "$0"` BPDIR=`dirname $FRELEASE` BPDIR=`readlink -f "$BPDIR/.."` mkdir -p $BUILD_DIR/.profile.d cp $BPDIR/resources/env.sh $BUILD_DIR/.profile.d echo "---" ##echo "config_vars:" ##echo " PYTHONHOME: $HOME/.buildpack" echo "default_process_types:" echo " web: .buildpack/bin/python server.py" EOFRELEASE chmod 755 ${buildpack_dir}/bin/release echo "Creating bin/finalize" cat > ${buildpack_dir}/bin/finalize <<- "EOFRELEASE" #!/usr/bin/env bash set -euo pipefail BUILD_DIR=$1 #CACHE_DIR=$2 #DEPS_DIR=$3 #DEPS_IDX=$4 #PROFILE_DIR=${5:-} #export BUILDPACK_DIR=`dirname $(readlink -f ${BASH_SOURCE%/*})` #source "$BUILDPACK_DIR/scripts/install_go.sh" #output_dir=$(mktemp -d -t finalizeXXX) echo "-----> Running go build finalize" #pushd $BUILDPACK_DIR # $GoInstallDir/go/bin/go build -mod=vendor -o $output_dir/finalize ./src/python/finalize/cli #popd echo "Build" #$output_dir/finalize "$BUILD_DIR" "$CACHE_DIR" "$DEPS_DIR" "$DEPS_IDX" "$PROFILE_DIR" EOFRELEASE chmod 755 ${buildpack_dir}/bin/finalize echo "Creating resources/env.sh" cat > ${buildpack_dir}/resources/env.sh <<- "EOFENVSH" #!/usr/bin/env bash FENV=`readlink -f "$0"` DDROPLET=`dirname $FENV` echo env.sh echo user `whoami` echo dir `pwd` export PYTHONHOME=$DDROPLET/app/.buildpack PYLIB=$(echo $DDROPLET/app/.buildpack/lib/python*/) PYLIB64=$(echo $DDROPLET/app/.buildpack/lib64/python*/) export PYTHONPATH=$PYLIB/:$PYLIB/lib-dynload:$PYLIB64/:$PYLIB64/lib-dynload echo PYTHONHOME=$PYTHONHOME echo PYTHONPATH=$PYTHONPATH EOFENVSH echo "Creating VERSION file" cat > ${buildpack_dir}/VERSION <<- "EOFVERSION" 0.0.1 EOFVERSION echo "Creating README file" cat > ${buildpack_dir}/README.md <<- "EOFREADMEMD" # sap_python_buildpack Very thin and simple buildpack, implemented completely in BASH. Can work both in offline and online mode. # How it works * Detect : checks if the app folder contains file runtime.txt containing runtime specification python-<python version> * Tries to find python sources \<\<buildpack\>\>/resources/python/Python-$version.tgz * If not found, downloads https://www.python.org/ftp/python/$version/Python-$version.tgz * Compiles python sources * Install python modules \<\<buildpack\>\>/resources/modules/*.tar.gz * Caches python build to cache folder * Tries to install dependencies described in \<\<app folder\>\>/requirements.txt using pip * If it fails, tries to install modules from \<\<app folder\>\>/vendor # Offline mode This buildpack can work in offline mode i.e. with no internet connection. All supported python runtimes must be provided as .tgz files in buildpack folder/resources/python folder. So you basically git clone this buildpack, then you download the supported python versions in the resources/python folder and then create the buildpack in CF or in XS # Online mode In this case no changes are required to this buildpack, the python version will be downloaded in the compile phase. # Application prerequisites Expected files in app folder: * server.py * runtime.txt with sample content "python-3.4.4" or "python-3.5.5" `cat 'python-3.4.4' >runtime.txt` * Offline mode: vendor folder containing all dependent modules Sample commands to download modules: `python -m pip download -d \<\<app folder\>\>/vendor pyhdb` `python -m pip install -d \<\<app folder\>\>/vendor -r \<\<app folder\>\>/requirements.txt` * Online mode: requirements.txt in the app folder # Limitations * Hardcoded sap corporate proxy (Removed by Andrew Lunde I830671 for public Internet use.) * Tested on OS: Ubuntu, Suse linux * Tested with python versions: 3.4.4 3.5.0 EOFREADMEMD cd ${buildpack_dir}/resources/modules echo "Getting...PIP from $pipurl" wget ${pipzip} echo "Done..." echo "Getting...setuptools from $setuptoolsurl" wget ${setuptoolszip} echo "Done..." cd ../.. echo "Finished creating a new python buildpack in ${buildpack_dir}\n" echo "" echo "Install the buildpack with: (use an unused position number if 99 is occupied)" echo "" echo "xs create-buildpack my_python_buildpack ${buildpack_dir} 99" echo ""
def pairs_sum_to_value(array, target): seen = set() output = set() for item in array: a = target - item if a not in seen: seen.add(item) else: output.add( (min(item,a), max(item,a)) ) return output # Driver code array = [5, 6, 7, 8] target = 10 print(pairs_sum_to_value(array, target)) # Output: {(5, 5), (6, 4), (7, 3), (8, 2)}
#include <stdio.h> int main(void){ float F, C; int lower, upper, step; lower = -20; upper = 300; step = 20; F = lower; while(F <= upper){ C = (5.0/9.0)*(F-32); printf("%3.2f\t%3.0f\n", F, C); F += step; } }
<gh_stars>0 /** * Created by Admin on 2/20/2018. */ var container, stats; var group; var camera, controls, scene, renderer; window.requestAbort = false; var strDownloadMime = "image/octet-stream"; var mmInPx = 3.779528; var previewCount = 0; var previewProject = function (data, backgrounds, generate) { // 1 mm = 3.779528 px; 1 px = 0.264583 mm var threeJsTimeOut = setTimeout(function () { $("#container").removeClass('loader'); $("#container").css('background-color', '#74d0db'); window.camera_pox = data.zomMax; window.bac = backgrounds; var heightSize = 0; window.index = 0; var texture; countSaveImages(data,backgrounds); $(".time-round").html('(' + timeRound + ' IMAGES)'); $(".time-round-generate").html(timeRound); function init() { if (generate) { var widthDiv = data.projectMaxSize['width']; var heightDiv = data.projectMaxSize['height']; } else { var widthDiv = $('#project-view').innerWidth(); var heightDiv = window.innerHeight - heightSize; } camera = new THREE.PerspectiveCamera(50, widthDiv / heightDiv, 0.1, 1000); camera.position.set(0, 0, window.camera_pox); // camera.position.set( current_object.e_left, current_object.e_center, current_object.e_right ); controls = new THREE.OrbitControls(camera); controls.addEventListener('change', render); scene = new THREE.Scene(); if (!generate) { scene.background = texture; } geometry = new THREE.BoxGeometry(data.width, data.height, data.depth); //7, 10, 1.2, 4, 4, 1 20, 15, 5 var map_1 = THREE.ImageUtils.loadTexture(data.rightImg); map_1.anisotropy = 16; material1 = new THREE.MeshPhongMaterial({map: map_1}); var map_2 = THREE.ImageUtils.loadTexture(data.backImg); map_2.anisotropy = 16; material2 = new THREE.MeshPhongMaterial({map: map_2}); var map_3 = THREE.ImageUtils.loadTexture(data.leftImg); map_3.anisotropy = 16; material3 = new THREE.MeshPhongMaterial({map: map_3}); var map_4 = THREE.ImageUtils.loadTexture(data.frontImg); map_4.anisotropy = 16; material4 = new THREE.MeshPhongMaterial({map: map_4}); // main visible var map_5 = THREE.ImageUtils.loadTexture(data.topImg); map_5.anisotropy = 16; material5 = new THREE.MeshPhongMaterial({map: map_5}); // top bottom var map_6 = THREE.ImageUtils.loadTexture(data.bottomImg); map_6.anisotropy = 16; material6 = new THREE.MeshPhongMaterial({map: map_6}); // top bottom materials = [ material1, material3, material5, material6, material4, material2 ]; meshFaceMaterial = new THREE.MeshFaceMaterial(materials); mesh = new THREE.Mesh(geometry, meshFaceMaterial); mesh.updateMatrix(); mesh.position.z = 0; scene.add(mesh); // group.add(mesh); var lightIntensity = '.' + data.lightIntensity; var environLightIntensity = '.' + data.environLightIntensity; light = new THREE.PointLight(0xffffff, lightIntensity); // light.position.set(50, 60, 100); // // scene.add(light); window.lightx = data.lightx; window.lighty = data.lighty; window.lightz = data.lightz; window.x = 0; window.y = 0; if (previewCount == 0) { var lightInterval = setInterval(function () { light.position.set(window.x, window.y, window.lightz); window.x++; window.y++; if (x == window.lightx) { x = -window.lightx; } if (y == window.lighty) { y = -window.lighty; } scene.add(light); }, 1000); } light_b = new THREE.AmbientLight(0xbbbbbb, environLightIntensity); scene.add(light_b); // renderer renderer = new THREE.WebGLRenderer({antialias: true, alpha: true, preserveDrawingBuffer: true}); renderer.setClearColor(0x000000, 0); renderer.setSize(widthDiv, heightDiv); container = document.getElementById('container'); container.appendChild(renderer.domElement); if (!generate) { window.addEventListener('resize', onWindowResize, false); } if (generate) { var pathArray = data.pathname.split('/') var projectId = pathArray[pathArray.length - 1]; if (data.projectsIdes) { var projectsIdes = data.projectsIdes; } window.saveImagesCount = 0; var imageSaveInterval = setInterval(function () { if (!window.requestAbort) { var strMime = "image/png"; var imgData = renderer.domElement.toDataURL(strMime); var data = { 'projectId': projectId, 'imgData': imgData, } if (saveImagesCount <= timeRound) { saveImagesCount = saveImagesCount + backgrounds.length; if (saveImagesCount >= timeRound){ $(".saved-images-count").html(timeRound); }else { $(".saved-images-count").html(saveImagesCount); } $.ajax({ type: "POST", url: '/save-images-ajax', async: true, cache: true, data: data, success: function (res) { } }); } else { if (projectsIdes && projectsIdes.length > 0) { clearInterval(imageSaveInterval); generateQueueProjects(projectsIdes); }else { window.location.replace("/projects"); } } } }, 1000); } } window.flag = true; window.zommMin = data.zommMin; window.zomMax = data.zomMax; texture = new THREE.Color(0x74d0db); if (previewCount == 0) { if (generate == true) { // setInterval(function () { // texture = new THREE.TextureLoader().load(window.bac[window.index]) // if (window.index == window.bac.length - 1) { // window.index = 0; // } else { // window.index++; // } // scene.background = texture; // // }, 4000); } // if (generate == true) { var zoomInterval = setInterval(function () { camera.position.set(0, 0, window.camera_pox); window.camera_pox--; if (window.camera_pox == window.zommMin) { window.camera_pox = window.zomMax; } }, 500); // } } window.verticalRot = data.verticalRot * 2 * Math.PI / 360; window.horizontalRot = data.horizontalRot * 2 * Math.PI / 360; window.verticalFlag = false; window.horizontalFlag = false; function animate() { requestAnimationFrame(animate); // mesh.rotation.z += 180 / Math.PI * 0.0002; // if (generate == true){ if (verticalFlag) { mesh.rotation.x -= 180 / Math.PI * 0.0001; if (mesh.rotation.x < 0) { window.verticalFlag = false; } } if (!verticalFlag) { mesh.rotation.x += 180 / Math.PI * 0.0001; if (mesh.rotation.x > verticalRot) { window.verticalFlag = true; } } if (horizontalFlag) { mesh.rotation.y -= 180 / Math.PI * 0.0001; if (mesh.rotation.y < 0) { window.horizontalFlag = false; } } if (!horizontalFlag) { mesh.rotation.y += 180 / Math.PI * 0.0001; if (mesh.rotation.y > horizontalRot) { window.horizontalFlag = true; } } // } controls.update(); render(); } function onWindowResize() { var widthDiv = $('#project-view').innerWidth(); var heightDiv = window.innerHeight - heightSize; camera.aspect = widthDiv / heightDiv; camera.updateProjectionMatrix(); renderer.setSize(widthDiv, heightDiv); render(); } function render() { renderer.render(scene, camera); } init(); if (previewCount == 0) { animate(); } previewCount++; }, 3000) };
package lu.uni.bicslab.greenbot.android.ui.fragment.compare; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import java.util.ArrayList; import java.util.List; import lu.uni.bicslab.greenbot.android.R; import lu.uni.bicslab.greenbot.android.datamodel.ProductCategoryModel; import lu.uni.bicslab.greenbot.android.datamodel.ProductModel; import lu.uni.bicslab.greenbot.android.other.CompareModel; import lu.uni.bicslab.greenbot.android.datamodel.IndicatorModel; import lu.uni.bicslab.greenbot.android.other.Utils; public class CustomCompareGridAdapter extends RecyclerView.Adapter<CustomCompareGridAdapter.CustomViewHolder> { private final List<CompareModel> compareModels; private final Context mcontext; int positionViewpager; private final List<List<IndicatorModel>> modelIndicatorModelss; // Lists of indicators grouped by category public static class CustomViewHolder extends RecyclerView.ViewHolder { CardView card_view_main; TextView txt_categoryname; ImageView img_product_icon; ImageView img_category_icon; RecyclerView recycler_viewindicator; public CustomViewHolder(View view) { super(view); this.card_view_main = view.findViewById(R.id.card_view); this.txt_categoryname = view.findViewById(R.id.txt_categoryname); this.img_product_icon = view.findViewById(R.id.img_product_icon); this.img_category_icon = view.findViewById(R.id.img_category_icon); this.recycler_viewindicator = view.findViewById(R.id.indicator_view); } } public CustomCompareGridAdapter(Context mcontext, int positionViewpager, List<CompareModel> mCompareModelList) { this.compareModels = mCompareModelList; this.mcontext = mcontext; this.positionViewpager = positionViewpager; modelIndicatorModelss = new ArrayList<>(); for (int i=0; i<compareModels.size(); i++ ) { if(positionViewpager == 0) modelIndicatorModelss.add(compareModels.get(i).getmCompareItemsModel().getIndCatEnvironmentlist()); else if(positionViewpager == 1) modelIndicatorModelss.add(compareModels.get(i).getmCompareItemsModel().getIndCatEconomicList()); else if(positionViewpager == 2) modelIndicatorModelss.add(compareModels.get(i).getmCompareItemsModel().getIndCatSociallist()); else modelIndicatorModelss.add(compareModels.get(i).getmCompareItemsModel().getIndCatGoodGevernanceList()); } } @Override public CustomCompareGridAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.comare_row, parent, false); CustomCompareGridAdapter.CustomViewHolder myViewHolder = new CustomCompareGridAdapter.CustomViewHolder(view); return myViewHolder; } @Override public void onBindViewHolder(CustomCompareGridAdapter.CustomViewHolder holder, int position) { ProductModel model = compareModels.get(position).getProductModelForcompare(); ProductCategoryModel categoryModel = Utils.getProductCategoryByID(mcontext, model.getCategory()); ImageView iv_product_icon = holder.img_product_icon; ImageView iv_category_icon = holder.img_category_icon; RecyclerView recycler_viewindicator = holder.recycler_viewindicator; Log.e("eee position", "" + positionViewpager); Drawable image = Utils.getDrawableImage(mcontext, model.getImage_url()); Glide.with(mcontext).load(image).apply(RequestOptions.centerCropTransform()).into(iv_product_icon); //Glide.with(mcontext).load(image).error(R.drawable.ic_menu_gallery).into(iv_product_icon); Glide.with(mcontext).load(Utils.getDrawableImage(mcontext, categoryModel.getIcon_name())).error(R.drawable.ic_menu_gallery).into(iv_category_icon); CustomCompareListRowAdapter adapter = new CustomCompareListRowAdapter(mcontext, positionViewpager, modelIndicatorModelss.get(position)); // Colored frame around compared/featured product if(compareModels.get(position).IsReference()) holder.card_view_main.setCardBackgroundColor(Color.YELLOW); recycler_viewindicator.setAdapter(adapter); recycler_viewindicator.setLayoutManager(new LinearLayoutManager(mcontext)); } @Override public int getItemCount() { return compareModels.size(); } }
<reponame>geethavijay/ds-algo-py<gh_stars>1-10 from data_structures.linked_list.single_linked_list import Node def random_list(): return Node(25, Node(12, Node(35, Node(6, Node(15, Node(45)))))) def ascending_list(): return Node(10, Node(20, Node(30, Node(40, Node(50, Node(60, Node(70))))))) def palindrome_list(): return Node(10, Node(20, Node(30, Node(40, Node(30, Node(20, Node(10))))))) def another_ascending_list(): return Node(12, Node(22, Node(33, Node(45, Node(53, Node(61, Node(78))))))) def combined_ascending_list(): return Node(10, Node(12, Node(20, Node(22, Node(30, Node(33, Node(40, Node(45, Node(50, Node(53, Node(60, Node(61, Node(70, Node(78)))))))))))))) def descending_list(): return Node(70, Node(60, Node(50, Node(40, Node(30, Node(20, Node(10))))))) def duplicate_list(): return Node(10, Node(20, Node(30, Node(40, Node(10, Node(20, Node(30, Node(40)))))))) def non_duplicate_list(): return Node(10, Node(20, Node(30, Node(40))))
<reponame>dezhidki/rss-aggro import React, { Component } from "react"; import { setFavouritesOrder } from "../actions"; import { connect } from "react-redux"; import { SortableContainer, SortableElement, arrayMove } from "react-sortable-hoc"; import { FeedItem } from "../components"; const SortableItem = SortableElement(({ value }) => { return ( <FeedItem item={value} /> ); }); const SortableList = SortableContainer(({ items, indices }) => { return ( <div> {indices.map((index, i) => ( <SortableItem key={items[index].key} value={items[index]} index={i} /> ))} </div> ); }); class FavouritesView extends Component { constructor(props) { super(props); this.state = { sortMode: false, items: [] }; } enableSortMode = e => { e.preventDefault(); this.setState({ sortMode: true, items: new Array(this.props.favouriteItems.length).fill().map((v, index) => index) }); }; cancelSort = e => { e.preventDefault(); this.setState({ sortMode: false, items: [] }); }; handleSort = ({ oldIndex, newIndex }) => { this.setState({ items: arrayMove(this.state.items, oldIndex, newIndex) }); }; saveChanges = e => { e.preventDefault(); let newIndices = [...this.state.items]; this.setState({ sortMode: false, items: [] }); this.props.setFavouritesOrder(newIndices); }; resetSort = e => { e.preventDefault(); this.props.setFavouritesOrder(null); }; render() { let content; if (this.props.favouriteItems.length > 0) { if (this.state.sortMode) content = <SortableList items={this.props.favouriteItems} indices={this.state.items} onSortEnd={this.handleSort} lockAxis="y" />; else content = this.props.favouriteItems.map(item => ( <FeedItem key={item.key} item={item} /> )); } else content = ( <p>You don't have anything favourited :(</p> ); let button; if (this.state.sortMode) button = [ <a key="0" href="#" className="btn-big save-name" onClick={this.saveChanges}>Save</a>, <a key="1" href="#" className="btn-big cancel-name" onClick={this.cancelSort}>Cancel changes</a> ]; else button = [ <a key="2" href="#" className="btn-big change-name" onClick={this.enableSortMode}>Sort</a>, <a key="3" href="#" className="btn-big delete-feed" onClick={this.resetSort}>Reset sort order</a>, ]; return ( <div> <div className="feed-view-header"> <h1 className="feed-header">Favourites</h1> {this.props.favouriteItems.length > 0 && button} </div> <hr /> {content} </div> ); } } function mapStateToProps(state) { return { favouriteItems: state.app.user.favourite_stories }; } function mapActionsToProps(dispatch) { return { setFavouritesOrder: order => dispatch(setFavouritesOrder(order)) }; } export default connect(mapStateToProps, mapActionsToProps)(FavouritesView);
import nextConnect from 'next-connect'; import middleware from '../../../middlewares/middleware'; import isEmail from 'validator/lib/isEmail'; import normalizeEmail from 'validator/lib/normalizeEmail'; import assert from 'assert'; import bcrypt from 'bcrypt'; import { v4 } from 'uuid'; import jwt from 'jsonwebtoken'; const handler = nextConnect(); handler.use(middleware); function createUser(db, name, email, password, callback) { const collection = db.collection('users'); bcrypt.hash(password, 10, function(err, hash) { // Store hash in your password DB. collection.insertOne( { _id: v4(), name, email, password: <PASSWORD>, signupDate: new Date().toString(), //emailVerified: false }, function(err, userCreated) { assert.strictEqual(err, null); callback(userCreated); }, ); }); } handler.post(async (req, res) => { const name = req.body.name; const email = normalizeEmail(req.body.email); const password = req.body.password; if (!isEmail(email)) { res.status(400).send('El email introducido no es valido'); return; } if (!email || !name || !password) { res.status(400).send('Missing field(s)'); return; } req.db.collection('users').findOne({email}, function(err, user) { if (err) { res.status(500).json({error: true, message: 'Error finding User'}); return; } if (!user) { // proceed to Create createUser(req.db, name, email, password, function(creationResult) { if (creationResult.ops.length === 1) { const user = creationResult.ops[0]; const token = jwt.sign( {userId: user.userId, email: user.email}, process.env.JWT_SECRET, { expiresIn: 3000, //50 minutes }, ); res.status(200).json({token}); return; } }); } else { // User exists res.status(403).json({error: true, message: 'Username or Email exists'}); return; } }) }) export default handler;
<gh_stars>0 package com.linda.framework.rpc.serialize; import com.linda.framework.rpc.cluster.JSONUtils; import com.linda.framework.rpc.cluster.TestBean; import com.linda.framework.rpc.cluster.serializer.simple.SimpleInput; import com.linda.framework.rpc.cluster.serializer.simple.SimpleOutput; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.StringUtils; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by lin on 2016/12/2. */ public class SimpleoutTest { public static void SimpleObjectTest()throws IOException, IllegalAccessException, InstantiationException, ClassNotFoundException{ TestBean testBean = new TestBean(); testBean.setLimit(4); testBean.setMessage("ggggggggggggggggggggggggggggggggggggggggggggg"); testBean.setOffset(43432); testBean.setOrder("645gdfghdfghdf"); SimpleOutput simple = new SimpleOutput(testBean); byte[] bytes = simple.writeObject(); String hex = new String(bytes); System.out.println(hex); SimpleInput sipt = new SimpleInput(bytes); Object obj = sipt.readObject(); System.out.println(JSONUtils.toJSON(obj)); } public static void mapTest() throws IOException, IllegalAccessException, InstantiationException, ClassNotFoundException { HashMap map = new HashMap(); map.put(1,555); List<Long> list = new ArrayList<Long>(); list.add(56777L); map.put("55666",list); map.put("null",null); TestBean testBean = new TestBean(); testBean.setLimit(4); testBean.setMessage("ggggggggggggggggggggggggggggggggggggggggggggg"); testBean.setOffset(43432); testBean.setOrder("645gdfghdfghdf"); map.put("obj",testBean); map.put("jhhh",list.toArray()); SimpleOutput simple = new SimpleOutput(map); byte[] bytes = simple.writeObject(); SimpleInput sipt = new SimpleInput(bytes); Object obj = sipt.readObject(); System.out.println(JSONUtils.toJSON(obj)); } public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException, ClassNotFoundException { mapTest(); } }
#!/bin/bash # # Perform a formatting of the go code base by running gofmt. # -x: print a trace (debug) # -u: treat unset variables # -o pipefail: return value of a pipeline # -o posix: match the standard set -uo pipefail # Constant variables PATH_TOPLEVEL="$(git rev-parse --show-superproject-working-tree --show-toplevel | head -1)" readonly PATH_TOPLEVEL PATH_SCRIPTDIR="$(dirname "$(realpath "$0")")" readonly PATH_SCRIPTDIR readonly FILE_LOG="${PATH_SCRIPTDIR}""/gofmt.log" readonly REGEX_PATTERNS="^(?!.*\/?!*(\.git|vendor|CHANGELOG.md)).*\.(go)$" # Options L_FLAG="all" while getopts 'l:' flag; do case "${flag}" in l) L_FLAG="${OPTARG}" ;; *) "[error] Unexpected option: ${flag}" ;; esac done readonly L_FLAG # Control flow logic cd "${PATH_TOPLEVEL}" || exit LIST="" if [[ "${L_FLAG}" == "ci" ]]; then LIST=$(git diff --submodule=diff --diff-filter=d --name-only --line-prefix="${PATH_TOPLEVEL}/" remotes/origin/main... | grep -P "${REGEX_PATTERNS}" | xargs) elif [[ "${L_FLAG}" == "diff" ]]; then LIST=$(git diff --submodule=diff --diff-filter=d --name-only --line-prefix="${PATH_TOPLEVEL}/" remotes/origin/HEAD... | grep -P "${REGEX_PATTERNS}" | xargs) elif [[ "${L_FLAG}" == "staged" ]]; then LIST=$(git diff --submodule=diff --diff-filter=d --name-only --line-prefix="${PATH_TOPLEVEL}/" --cached | grep -P "${REGEX_PATTERNS}" | xargs) elif [[ "${L_FLAG}" == "repo" ]]; then LIST=$(git ls-tree --full-tree -r --name-only HEAD | grep -P "${REGEX_PATTERNS}" | xargs -r printf -- "${PATH_TOPLEVEL}/%s ") elif [[ "${L_FLAG}" == "all" ]]; then LIST=$(git ls-files --recurse-submodules | grep -P "${REGEX_PATTERNS}" | xargs -r printf -- "${PATH_TOPLEVEL}/%s ") else echo "[error] Unexpected option: ${L_FLAG}" &> "${FILE_LOG}" exit 2 fi readonly LIST # Run analyzer if [[ -n "${LIST}" ]]; then readonly CLI="gofmt -s -l -d" ( for line in ${LIST}; do eval "${CLI}" "${line}" done ) &> "${FILE_LOG}" else exit 255 fi # Analyze log if [[ -f "${FILE_LOG}" && -s "${FILE_LOG}" ]]; then exit 1 else rm -f "${FILE_LOG}" fi
<filename>app/home/views/__init__.py<gh_stars>0 from django.shortcuts import render from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse from .helpers import * from .home_view import * from .biz_view import * from .mus_view import * from .vbt_view import * from .config import *
/* * */ package net.community.chest.aspectj.test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * <P>Copyright as per GPLv2</P> * @author <NAME>. * @since Aug 29, 2010 9:36:53 AM */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface AnnotatedStereotypeCollected { String value () default ""; }
<filename>charles-university/deep-learning/labs/12/q_network.py #!/usr/bin/env python3 import numpy as np import tensorflow as tf import mountain_car_evaluator class Network: def __init__(self, threads, seed=42): # Create an empty graph and a session graph = tf.Graph() graph.seed = seed self.session = tf.Session(graph = graph, config=tf.ConfigProto(inter_op_parallelism_threads=threads, intra_op_parallelism_threads=threads)) def construct(self, args, num_states, num_actions): with self.session.graph.as_default(): # Input states self.states = tf.placeholder(tf.int32, [None]) # Input q_values (uses as targets for training) self.q_values = tf.placeholder(tf.float32, [None, num_actions]) # TODO: Compute one-hot representation of self.states. # TODO: Compute the q_values as a single fully connected layer without activation, # with `num_actions` outputs, using the one-hot encoded states. It is important # to use such trivial architecture for the network to train at all. # Training # TODO: Perform the training, using mean squared error of the given # `q_values` and the predicted ones. # Initialize variables self.session.run(tf.global_variables_initializer()) def predict(self, states): # TODO: Predict q_values for given states def train(self, states, q_values): # TODO: Given states and target Q-values, perform the training if __name__ == "__main__": # Fix random seed np.random.seed(42) # Parse arguments import argparse parser = argparse.ArgumentParser() parser.add_argument("--episodes", default=500, type=int, help="Training episodes.") parser.add_argument("--epsilon", default=0.1, type=float, help="Exploration factor.") parser.add_argument("--epsilon_final", default=0.1, type=float, help="Final exploration factor.") parser.add_argument("--gamma", default=1.0, type=float, help="Discounting factor.") parser.add_argument("--learning_rate", default=0.01, type=float, help="Learning rate.") parser.add_argument("--render_each", default=0, type=int, help="Render some episodes.") parser.add_argument("--threads", default=1, type=int, help="Maximum number of threads to use.") args = parser.parse_args() # Create the environment env = mountain_car_evaluator.environment(discrete=True) # Construct the network network = Network(threads=args.threads) network.construct(args, env.states, env.actions) evaluating = False epsilon = args.epsilon while True: # TODO: decide if we want to start evaluating -- maybe after already processing # args.episodes (i.e., env.episode >= args.episodes), but you can use other logis. # Perform episode state, done = env.reset(evaluating), False while not done: if args.render_each and env.episode > 0 and env.episode % args.render_each == 0: env.render() # TODO: compute q_values using the network and action using epsilon-greedy policy. action = ... next_state, reward, done, _ = env.step(action) # Perform the network update # TODO: Compute the q_values of the next_state # TODO: Update the goal q_values for the state `state`, using the TD update # for action `action` (leaving the q_values for different actions unchanged). # TODO: Train the network using the computed goal q_values for state `state`. state = next_state # Epsilon interpolation if args.epsilon_final: epsilon = np.exp(np.interp(env.episode + 1, [0, args.episodes], [np.log(args.epsilon), np.log(args.epsilon_final)]))
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.csp.sentinel.cluster.server; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import com.alibaba.csp.sentinel.cluster.ClusterStateManager; import com.alibaba.csp.sentinel.cluster.registry.ConfigSupplierRegistry; import com.alibaba.csp.sentinel.cluster.server.config.ClusterServerConfigManager; import com.alibaba.csp.sentinel.cluster.server.config.ServerTransportConfig; import com.alibaba.csp.sentinel.cluster.server.config.ServerTransportConfigObserver; import com.alibaba.csp.sentinel.cluster.server.connection.ConnectionManager; import com.alibaba.csp.sentinel.init.InitExecutor; import com.alibaba.csp.sentinel.log.RecordLog; import com.alibaba.csp.sentinel.util.HostNameUtil; import com.alibaba.csp.sentinel.util.StringUtil; /** * @author <NAME> * @since 1.4.0 */ public class SentinelDefaultTokenServer implements ClusterTokenServer { private final boolean embedded; private ClusterTokenServer server; private int port; private final AtomicBoolean shouldStart = new AtomicBoolean(false); static { InitExecutor.doInit(); } /*** * 初始化一个SentinelDefaultTokenServer,默认不是内嵌的 */ public SentinelDefaultTokenServer() { this(false); } public SentinelDefaultTokenServer(boolean embedded) { this.embedded = embedded; ClusterServerConfigManager.addTransportConfigChangeObserver(new ServerTransportConfigObserver() { @Override public void onTransportConfigChange(ServerTransportConfig config) { changeServerConfig(config); } }); initNewServer(); } /*** * 初始化一个新的newServer * 1、获得服务端的port。然后创建一个NettyTransportServer监听port */ private void initNewServer() { if (server != null) { return; } int port = ClusterServerConfigManager.getPort(); if (port > 0) { this.server = new NettyTransportServer(port); this.port = port; } } private synchronized void changeServerConfig(ServerTransportConfig config) { if (config == null || config.getPort() <= 0) { return; } int newPort = config.getPort(); if (newPort == port) { return; } try { if (server != null) { stopServer(); } this.server = new NettyTransportServer(newPort); this.port = newPort; startServerIfScheduled(); } catch (Exception ex) { RecordLog.warn("[SentinelDefaultTokenServer] Failed to apply modification to token server", ex); } } private void startServerIfScheduled() throws Exception { if (shouldStart.get()) { if (server != null) { server.start(); ClusterStateManager.markToServer(); if (embedded) { RecordLog.info("[SentinelDefaultTokenServer] Running in embedded mode"); handleEmbeddedStart(); } } } } private void stopServer() throws Exception { if (server != null) { server.stop(); if (embedded) { handleEmbeddedStop(); } } } private void handleEmbeddedStop() { String namespace = ConfigSupplierRegistry.getNamespaceSupplier().get(); if (StringUtil.isNotEmpty(namespace)) { ConnectionManager.removeConnection(namespace, HostNameUtil.getIp()); } } private void handleEmbeddedStart() { String namespace = ConfigSupplierRegistry.getNamespaceSupplier().get(); if (StringUtil.isNotEmpty(namespace)) { // Mark server global mode as embedded. ClusterServerConfigManager.setEmbedded(true); if (!ClusterServerConfigManager.getNamespaceSet().contains(namespace)) { Set<String> namespaceSet = new HashSet<>(ClusterServerConfigManager.getNamespaceSet()); namespaceSet.add(namespace); ClusterServerConfigManager.loadServerNamespaceSet(namespaceSet); } // Register self to connection group. ConnectionManager.addConnection(namespace, HostNameUtil.getIp()); } } @Override public void start() throws Exception { if (shouldStart.compareAndSet(false, true)) { startServerIfScheduled(); } } @Override public void stop() throws Exception { if (shouldStart.compareAndSet(true, false)) { stopServer(); } } }
<reponame>hieutran3010/EnglishOnline import styled from 'styled-components/macro'; export const TextSearchContainer = styled.div` padding: 8px; .ant-input-group { display: flex !important; } `;
export IMAGE_TAG=$(cat VERSION) export AARCH=`uname -m` export IMAGE_NAME=jmx-prometheus-exporter export DOCKER_CLI_EXPERIMENTAL=enabled docker manifest create --amend cachengo/$IMAGE_NAME:$IMAGE_TAG cachengo/$IMAGE_NAME-x86_64:$IMAGE_TAG cachengo/$IMAGE_NAME-aarch64:$IMAGE_TAG docker manifest push cachengo/$IMAGE_NAME:$IMAGE_TAG
<filename>lib/swagger/schema/object.rb require_relative '../schema' class Swagger::Schema::Object < Swagger::Schema def type 'object' end def properties properties_hash.values end def property(key) properties_hash[key] end def displayed_type "<a href=\"##{unique_key}\">#{name}</a>".html_safe end def default_sample_value "<< #{displayed_type} >>".html_safe end private def properties_hash if @_properties.nil? @_properties = { } if fields.key?('properties') fields['properties'].each do |name, value| @_properties[name] = Swagger::Schema.factory(name, value, @specification) end end end @_properties end end
<filename>app.js<gh_stars>0 /* * Copyright 2016 NIIT Ltd, Wipro Ltd. * * 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. * * Contributors: * * 1. <NAME> * 2. <NAME> * 3. <NAME> * 4. <NAME> * 5. <NAME> * 6. <NAME> * 7. <NAME> */ //Third party modules var favicon = require('serve-favicon'); var express = require('express'), mongoose = require('mongoose'), path = require('path'), bodyParser = require('body-parser'), expressSession = require('express-session'), flash = require('connect-flash'), cookieParser = require('cookie-parser'), passport = require('passport'), compress = require('compression'); LocalStrategy = require('passport-local').Strategy; //custom modules var indexRouter = require('./routes/indexRouter'), userRouter = require('./routes/userRouter'), widgetRouter = require('./routes/widgetRouter'), widgetMdxRouter = require('./routes/widgetMdxRouter'), dashboardRouter = require('./routes/dashboardRouter'), chartdataRouter = require('./routes/chartDataRouter'), dbConfig = require('./config/db'), Credential = dbConfig.credentialModel, gridRouter = require('./routes/gridRouter'), commentsRouter = require('./routes/commentsRouter'), dashboardRouter = require('./routes/dashboardRouter'); uploadImageRouter=require('./routes/uploadImageRouter'); var app = express(); var env = app.get('env'); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); //enable expression app.use(compress()); var cpath = env == 'production' ? '../public' : 'public' ; app.use(express.static(path.join(__dirname, cpath))); app.use(favicon(path.join(__dirname, cpath, 'favicon.ico'))); // instruct the app to use the `bodyParser()` middleware for all routes app.use(cookieParser('tobo')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(flash()); //initialize passort sessions app.use(expressSession({ secret: 'keyboard cat', cookie: { maxAge: 3600000 }, proxy: true, resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); passport.use(new LocalStrategy(Credential.authenticate())); passport.serializeUser(Credential.serializeUser()); passport.deserializeUser(Credential.deserializeUser()); app.use('/', indexRouter); app.use('/user', userRouter); app.use('/dashboard', dashboardRouter); app.use('/widgets', widgetRouter); app.use('/widgetsMdx', widgetMdxRouter); app.use('/comment', commentsRouter); app.use('/chartdata', chartdataRouter); app.use('/execute', gridRouter); app.use('/upload',uploadImageRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not found'); err.status = 404; next(); }); // error handlers // development error handler // will print stacktrace if(app.get('env') === 'development') { app.use(function(err, req, res, next) { console.log("in error handler", err); res.status(err.status || 500); res.render('error', { message: "err.message", error: err }); }); } //Should log errors in a file if(app.get('env') === 'production') { app.use(function(err, req, res, next) { console.log("in error handler", err); res.status(err.status || 500); res.render('error', { message: "err.message", error: err }); }); } module.exports = app;
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class DepSolver { public static void main(String[] args) { List<String> sourceFiles = new ArrayList<>(); String classpath = ""; String sourcepath = ""; String outputDir = ""; // Parse command-line arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-sourcepath")) { sourcepath = args[i + 1]; } else if (args[i].equals("-classpath")) { classpath = args[i + 1]; } else if (args[i].equals("-d")) { outputDir = args[i + 1]; } else { sourceFiles.add(args[i]); } } // Resolve dependencies and compile try { String sourceFilesStr = String.join(" ", sourceFiles); String command = "javac -cp " + classpath + " -sourcepath " + sourcepath + " -d " + outputDir + " " + sourceFilesStr; Process process = Runtime.getRuntime().exec(command); process.waitFor(); System.out.println("Compiled classes output to " + outputDir + " directory"); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
<gh_stars>10-100 package com.shareyi.molicode.vo.user; import java.util.Date; /** * 用户登录信息万 * * @author david * @date 2019/7/3 */ public class LoginUserVo { /** * 用户名 */ private String userName; /** * 用户昵称 */ private String nickName; /** * 密码 */ private String password; /** * 性别 */ private Integer gender; /** * 出生日期 */ private java.util.Date birthDay; /** * 角色码 */ private String roleCode; /** * 备注 */ private String remark; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { return "LoginUserVo{" + "userName='" + userName + '\'' + ", nickName='" + nickName + '\'' + ", password='" + password + '\'' + ", gender=" + gender + ", birthDay=" + birthDay + ", roleCode='" + roleCode + '\'' + ", remark='" + remark + '\'' + '}'; } }
#!/bin/bash # Waits for resources to be "Ready" before allowing build pipeline to continue # Ensure strict mode and predictable pipeline failure set -euo pipefail # Get AKS creds message="Merging AKS credentials" echo -e "\nSTARTED: $message..." az aks get-credentials --resource-group "$AKS_RG_NAME" --name "$AKS_CLUSTER_NAME" --overwrite-existing echo -e "FINISHED: $message.\n" # Testing kubectl kubectl version --short # Wait pod_name="nexus-0" message="Waiting for Ready condition on pod: [$pod_name]" echo -e "\nSTARTED: $message..." kubectl --namespace ingress wait pod $pod_name --for condition=ready --timeout=5m echo -e "FINISHED: $message."
<gh_stars>0 //package old.testies_old; // //import actions.NotSupportedYetAct; //import strikepackage.Browser; // //import java.util.ArrayList; // //public class Testie { // public static void main(String[] args) { //// LocalDateTime ldt = new LocalDateTime(); //// LocalTime localTime = LocalTime.now(); //// System.out.println(localTime); //// LocalDate localDate = LocalDate.now(); //// System.out.println(localDate); //// LocalDateTime localDateTime = LocalDateTime.now(); //// System.out.println(localDateTime); //// //// DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("HHmmss"); //// DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("ddMMYY"); //// String f1 = formatter1.format(localTime); //// String f2 = formatter2.format(localDate); //// String merge = f1+"_"+f2; //// System.out.println(f1); //// System.out.println(f2); //// System.out.println(merge); // // Browser browser = new Browser(); // check(); // System.out.println("OwO"); // ArrayList<String> arrayList = new ArrayList<>(); // arrayList.add("toss_a_troll"); //// arrayList.add("10000m"); // NotSupportedYetAct act = new NotSupportedYetAct(arrayList, browser); // act.run(); // System.out.println("1--------"); // System.out.println(act.toString()); // ArrayList<String> arrayList2 = new ArrayList<>(); // arrayList2.add(act.toString()); // System.out.println("2--------"); // int counter = 0; // for (String tmp : arrayList2) { // System.out.println(counter+") "+tmp); // counter++; // } // // // browser.getWebDriver().close(); // browser.getWebDriver().quit(); // // } // // private static void check() { // int num = 4; // if (num != 5) { // return; // } else { // System.out.println("num+5: " + (num + 5)); // } // // System.out.println("blah blah"); // } //}
#!/usr/bin/env bash shopt -s extglob YES_PATTERN='@([yY]|[yY][Ee][Ss])' NO_PATTERN='@([nN]|[n|N][O|o])' USE_GPG=0 __2fash_print_help_new() { echo "" __2fash_print_help_usage_head "${FASH_COMMAND} new [OPTION]..." echo "" __2fash_print_help_head "OPTIONS" __2fash_print_help_command "--help, -h" "show help" echo "" } for arg in $@; do case ${arg} in -d=*) FASH_DIRECTORY_ACCOUNTS="${arg#*=}" shift ;; --help|-h) __2fash_print_help_new exit shift ;; esac done __2fash_new_gpg_ask() { __2fash_read_text_label_bold "Generate new GPG key? (y/N)" read ask case ${ask} in ${YES_PATTERN}) echo -e "${FORMAT_NORM}" gpg --full-gen-key --keyid-format long ;; esac } __2fash_use_gpg_ask() { __2fash_read_text_label_bold "Use GPG encryption? (Y/n)" read ask case ${ask} in ${NO_PATTERN}) ;; *) echo -e "${FORMAT_NORM}" USE_GPG=1 __2fash_new_gpg_ask ;; esac } __2fash_read_2fa() { __2fash_read_text_label_bold "2FA Label" read "$1" [[ "$1" = "" ]] && echo_error "Invalid label" && exit 1 __2fash_throw_error_if_account_exists "$1" __2fash_read_text_label "2FA Secret" read -s "$2" } __2fash_read_gpg_data() { echo "" __2fash_read_text_label_bold "GnuPG user id (email)" read "$1" __2fash_read_text_label_bold "GnuPG key id (format: rsa0000/0000000000000000)" read "$2" } __2fash_print_end() { echo -e " ${FORMAT_NORM}Run the following command to get a code:" echo -e " ${FORMAT_INV}${FORMAT_BOLD}${FASH_COMMAND} c $1${FORMAT_NORM}" } __2fash_new_2fa_without_gpg() { echo "" __2fash_read_2fa tfa_label tfa_secret account_directory="$FASH_DIRECTORY_ACCOUNTS/$tfa_label" secret_file="$account_directory/.secret" echo "" echo "" mkdir -p "$account_directory" echo -en "$tfa_secret" > "$secret_file" echo "" __2fash_print_end "$tfa_label" exit 0 } __2fash_new_2fa_with_gpg() { __2fash_read_gpg_data gpg_uid gpg_kid echo "" __2fash_read_2fa tfa_label tfa_secret account_directory="$FASH_DIRECTORY_ACCOUNTS/$tfa_label" gpgdata_file="$account_directory/.gpgdata" secret_file="$account_directory/.secret" echo "" echo "" mkdir -p "$account_directory" echo -en "uid: $gpg_uid\nkid: $gpg_kid" > "$gpgdata_file" echo -en "$tfa_secret" > "$secret_file" gpg -u "$gpg_kid" -r "$gpg_uid" --encrypt "$secret_file" && echo -en "\n "; rm "$secret_file" __2fash_print_end "$tfa_label" echo "" exit 0 } echo "" __2fash_use_gpg_ask [[ ${USE_GPG} = 1 ]] && __2fash_new_2fa_with_gpg || __2fash_new_2fa_without_gpg
import numpy as np from typing import List, Union def largest_bounding_box_area(bounding_boxes: np.ndarray, detect_multiple_faces: bool) -> Union[int, List[int]]: areas = (bounding_boxes[:, 2] - bounding_boxes[:, 0]) * (bounding_boxes[:, 3] - bounding_boxes[:, 1]) max_area = np.max(areas) if detect_multiple_faces: max_indices = np.where(areas == max_area)[0] return max_indices.tolist() else: max_index = np.argmax(areas) return max_index
"""Test for error's user_error.""" import json import unittest from sqlalchemy_jsonapi import errors from sqlalchemy_jsonapi import __version__ class TestUserError(unittest.TestCase): """Tests for errors.user_error.""" def test_user_error(self): """Create user error succesfully.""" status_code = 400 title = 'User Error Occured' detail = 'Testing user error' pointer = '/test' actual = errors.user_error( status_code, title, detail, pointer) data = { 'errors': [{ 'status': status_code, 'source': {'pointer': '{0}'.format(pointer)}, 'title': title, 'detail': detail, }], 'jsonapi': { 'version': '1.0' }, 'meta': { 'sqlalchemy_jsonapi_version': __version__ } } expected = json.dumps(data), status_code self.assertEqual(expected, actual)
class EmployeeDatabase { constructor() { this.employees = new Map(); } addEmployee(name, id, position) { this.employees.set(id, { name, position }); } getEmployee(id) { const employee = this.employees.get(id); if (employee) { return { name: employee.name, position: employee.position }; } else { return "Employee not found"; } } updateEmployee(id, newName, newPosition) { if (this.employees.has(id)) { this.employees.set(id, { name: newName, position: newPosition }); } else { console.log("Employee not found"); } } deleteEmployee(id) { if (this.employees.has(id)) { this.employees.delete(id); } else { console.log("Employee not found"); } } } // Example usage const database = new EmployeeDatabase(); database.addEmployee("John Doe", 1, "Manager"); database.addEmployee("Jane Smith", 2, "Developer"); console.log(database.getEmployee(1)); // Output: { name: 'John Doe', position: 'Manager' } database.updateEmployee(2, "Jane Johnson", "Senior Developer"); console.log(database.getEmployee(2)); // Output: { name: 'Jane Johnson', position: 'Senior Developer' } database.deleteEmployee(1); console.log(database.getEmployee(1)); // Output: "Employee not found"
<reponame>amawaziny/utils<filename>faces-utils/src/main/java/org/qfast/component/primefaces/export/DataExporter.java /* * Copyright 2009-2012 Prime Teknoloji. * * 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.qfast.component.primefaces.export; import java.io.IOException; import javax.el.ELContext; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.faces.component.StateHolder; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import org.primefaces.component.datatable.DataTable; import org.primefaces.component.panelgrid.PanelGrid; public class DataExporter implements ActionListener, StateHolder { private ValueExpression target; private ValueExpression type; private ValueExpression fileName; private ValueExpression encoding; private ValueExpression pageOnly; private ValueExpression selectionOnly; private MethodExpression preProcessor; private MethodExpression postProcessor; public DataExporter() { } public DataExporter(ValueExpression target, ValueExpression type, ValueExpression fileName, ValueExpression pageOnly, ValueExpression selectionOnly, ValueExpression encoding, MethodExpression preProcessor, MethodExpression postProcessor) { this.target = target; this.type = type; this.fileName = fileName; this.pageOnly = pageOnly; this.selectionOnly = selectionOnly; this.preProcessor = preProcessor; this.postProcessor = postProcessor; this.encoding = encoding; } @Override public void processAction(ActionEvent event) { FacesContext context = FacesContext.getCurrentInstance(); ELContext elContext = context.getELContext(); String tableId = (String) target.getValue(elContext); String exportAs = (String) type.getValue(elContext); String outputFileName = fileName.getValue(elContext).toString(); String encodingType = "UTF-8"; if (encoding != null) { encodingType = (String) encoding.getValue(elContext); } boolean isPageOnly = false; if (pageOnly != null) { isPageOnly = pageOnly.isLiteralText() ? Boolean.valueOf(pageOnly.getValue(context.getELContext()).toString()) : (Boolean) pageOnly.getValue(context.getELContext()); } boolean isSelectionOnly = false; if (selectionOnly != null) { isSelectionOnly = selectionOnly.isLiteralText() ? Boolean.valueOf(selectionOnly.getValue(context.getELContext()).toString()) : (Boolean) selectionOnly.getValue(context.getELContext()); } try { Exporter exporter = ExporterFactory.getExporterForType(exportAs); UIComponent component = event.getComponent().findComponent(tableId); if (component == null) { throw new FacesException("Cannot find component \"" + tableId + "\" in view."); } if (component instanceof DataTable) { DataTable table = (DataTable) component; exporter.export(context, table, outputFileName, isPageOnly, isSelectionOnly, encodingType, preProcessor, postProcessor); } else if (component instanceof PanelGrid) { PanelGrid table = (PanelGrid) component; exporter.export(context, table, outputFileName, isPageOnly, isSelectionOnly, encodingType, preProcessor, postProcessor); } else { throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName() + "\", exporter must target a PrimeFaces DataTable or PanelGrid."); } context.responseComplete(); } catch (IOException e) { throw new FacesException(e); } } @SuppressWarnings("unused") private int[] resolveExcludedColumnIndexes(Object columnsToExclude) { if (columnsToExclude == null || columnsToExclude.equals("")) { return null; } else { String[] columnIndexesAsString = ((String) columnsToExclude).split(","); int[] indexes = new int[columnIndexesAsString.length]; for (int i = 0; i < indexes.length; i++) { indexes[i] = Integer.parseInt(columnIndexesAsString[i].trim()); } return indexes; } } @Override public boolean isTransient() { return false; } @Override public void setTransient(boolean value) { //NoOp } @Override public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; target = (ValueExpression) values[0]; type = (ValueExpression) values[1]; fileName = (ValueExpression) values[2]; pageOnly = (ValueExpression) values[3]; selectionOnly = (ValueExpression) values[4]; preProcessor = (MethodExpression) values[5]; postProcessor = (MethodExpression) values[6]; encoding = (ValueExpression) values[7]; } @Override public Object saveState(FacesContext context) { Object values[] = new Object[8]; values[0] = target; values[1] = type; values[2] = fileName; values[3] = pageOnly; values[4] = selectionOnly; values[5] = preProcessor; values[6] = postProcessor; values[7] = encoding; return ((Object[]) values); } }
<filename>packages/eslint-config-vue/index.js module.exports = { extends: [ '@smartlinkdev/eslint-config', 'plugin:vue/recommended', ], parserOptions: { parser: 'babel-eslint', }, plugins: [ 'vue', ], rules: { 'vue/max-attributes-per-line': [2, { singleline: 2, multiline: { max: 1, allowFirstLine: false, }, }], 'vue/component-name-in-template-casing': ['error', 'kebab-case', { registeredComponentsOnly: true, ignores: [], }], 'vue/no-potential-component-option-typo': ['error', { presets: ['vue', 'vue-router'], custom: [], threshold: 1, }], 'vue/no-reserved-component-names': ['error'], 'vue/padding-line-between-blocks': ['error', 'always'], }, };
#!/bin/bash mvn clean install && java -jar target/benchmarks.jar
<filename>client/app.js var hsbc = angular.module('Hsbc', ['ngMaterial', 'ngRoute']); hsbc.config(function($routeProvider, $locationProvider, $mdThemingProvider){ $routeProvider .when('/', { controller:'EditionController', templateUrl:'views/edition-current.html' }) .when('/edycje/:id', { controller:'EditionController', templateUrl:'views/edition-old.html' }) .when('/zadania', { controller:'CaseController', templateUrl:'views/cases.html' }) .when('/zwyciezcy', { controller:'EditionController', templateUrl:'views/winners.html' }) .when('/partnerzy', { controller: 'EditionController', templateUrl: 'views/partners.html' }) .when('/organizatorzy', { controller:'OrgController', templateUrl:'views/org.html' }) .when('/kontakt', { controller:'ContactController', templateUrl:'views/contact.html' }) .otherwise({ redirectTo: '/' }); //TODO: Omit # used in front-end routing with: //$locationProvider.html5Mode(true); }); hsbc.run(['$anchorScroll', function ($anchorScroll) { $anchorScroll.yOffset = 0; }]); hsbc.controller('MainController', function($scope, $mdSidenav, $location, $anchorScroll, $mdDialog) { console.log('Main controller is running...'); $scope.openLeftMenu = function() { $mdSidenav('left').toggle(); }; $scope.goToAnchor = function(target) { if($location.hash() !== target) { $location.hash(target); } else { $anchorScroll(); } }; $scope.showConfirm = function() { // Appending dialog to document.body to cover sidenav in docs app $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector('#HsbcDialogContainer'))) .clickOutsideToClose(true) .title('Użycie Cookies') .textContent('Używamy plików cookie, aby usprawnić doświadczenie naszych użytkowników. Cookies to małe pliki, które są przechowywane na komputerze i mają na celu zidentyfikowanie naszych użytkowników. Zamykając tę wiadomość zgadzasz się na wykorzystanie przez nas plików cookie, chyba że zdecydujesz się je wyłączyć.') .ariaLabel('Użycie Cookies') .ok('OK') .targetEvent() ); var confirm = $mdDialog.alert() .clickOutsideToClose(true) .title('Użycie Cookies') .textContent('') .ariaLabel('Użycie Cookies') .ok('OK'); }; });
#!/usr/bin/env bash set -o errexit set -o nounset main() { echo "Hello, World!" } main
<gh_stars>10-100 package com.networknt.eventuate.common.impl; import com.networknt.eventuate.common.Int128; import java.util.Optional; public class EventIdTypeAndData { private Int128 id; private String eventType; private String eventData; private Optional<String> metadata; public EventIdTypeAndData() { } public EventIdTypeAndData(Int128 id, String eventType, String eventData, Optional<String> metadata) { this.id = id; this.eventType = eventType; this.eventData = eventData; this.metadata = metadata; } @Override public String toString() { return "EventIdTypeAndData{" + "id=" + id + ", eventType='" + eventType + '\'' + ", eventData='" + eventData + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EventIdTypeAndData that = (EventIdTypeAndData) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (eventType != null ? !eventType.equals(that.eventType) : that.eventType != null) return false; return eventData != null ? eventData.equals(that.eventData) : that.eventData == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (eventType != null ? eventType.hashCode() : 0); result = 31 * result + (eventData != null ? eventData.hashCode() : 0); return result; } public Int128 getId() { return id; } public void setId(Int128 id) { this.id = id; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public String getEventData() { return eventData; } public Optional<String> getMetadata() { return metadata; } public void setMetadata(Optional<String> metadata) { this.metadata = metadata; } public void setEventData(String eventData) { this.eventData = eventData; } }
const common = require('../common') const lang = { femininize: s => `${s}e`, // See http://la-conjugaison.nouvelobs.com/regles/grammaire/les-noms-219.php isFeminine: s => { const last6 = common.last(s, 6) const last5 = common.last(s, 5) const last4 = common.last(s, 4) const last3 = common.last(s, 3) const last2 = common.last(s, 2) const last1 = common.last(s, 1) if (last6 === 'euille') { return false } else if (last5 === 'aille') { return true } else if (last5 === 'eille') { return true } else if (last4 === 'ueil') { return false } else if (last4 === 'euil') { return false } else if (last3 === 'ail') { return false } else if (last3 === 'tié') { return true } else if (last3 === 'eil') { return false } else if (last2 === 'ée') { return true } else if (last2 === 'té') { return true } else if (last1 === 'e') { return true } return false }, isPlural: s => { const last4 = common.last(s, 4) const last3 = common.last(s, 3) const last1 = common.last(s, 1) if (last4 === 'ails') { return true } else if (last4 === 'eaux') { return true } else if (last3 === 'aux') { return true } else if (last3 === 'eux') { return true } else if (last3 === 'aux') { return true } else if (last3 === 'ous') { return true } else if (last1 === 's') { return true } else if (last1 === 'x') { return true } else if (last1 === 'z') { return true } return false }, le: s => { const first1 = common.first(s, 1) if (common.isVowel(first1)) { return `l'${s}` } else if (lang.isPlural(s)) { return `les ${s}` } else if (lang.isFeminine(s)) { return `la ${s}` } return `le ${s}` }, un: s => { if (lang.isPlural(s)) { return `des ${s}` } else if (lang.isFeminine(s)) { return `une ${s}` } return `un ${s}` }, s: s => { const last3 = common.last(s, 3) const last2 = common.last(s, 2) const last1 = common.last(s, 1) if (last3 === 'ail') { return `${s}s` } else if (last3 === 'eau') { return `${s}x` } else if (last2 === 'au') { return `${s}x` } else if (last2 === 'eu') { return `${s}x` } else if (last2 === 'au') { return `${s}x` } else if (last2 === 'ou') { return `${s}s` } else if (last1 === 's') { return s } else if (last1 === 'x') { return s } else if (last1 === 'z') { return s } return false } } module.exports = Object.assign({}, common, lang)
<gh_stars>0 const express = require('express'); const postSignUser = require('./postSignUser'); const User = express.Router(); User.post('/sign', async (request, response) => { try { response.json({ success: true, data: await postSignUser(request.body), }); } catch (error) { response.status(error.status).json({ success: false, data: error, }); } }); module.exports = User;
#pragma once #include <iostream> #include <limits> #include <memory> #include <mutex> #include <vector> #include <parallel_hashmap/phmap.h> #include "abstract_array.h" #include "aggregation_kd_node.h" #include "attribute.h" #include "ba_tree.h" #include "box.h" #include "owned_array.h" struct WriteOptions { bool find_best_axis = false; float max_split_imbalance_ratio = 4.f; float max_overfull_aggregator_factor = 1.5f; bool build_local_trees = true; uint32_t fixed_num_aggregators = 0; }; struct RankAggregationInfo { int rank = -1; uint64_t num_particles = -1; RankAggregationInfo(const int rank, const uint64_t num_particles); RankAggregationInfo() = default; }; /* A very simple median-split kd tree */ struct AggregationTree { Box bounds; uint32_t num_aggregators; uint64_t num_points; std::vector<AttributeDescription> attributes; phmap::flat_hash_map<std::string, size_t> attrib_ids; ArrayHandle<AggregationKdNode> nodes; ArrayHandle<uint32_t> leaf_indices; ArrayHandle<RankAggregationInfo> primitives; ArrayHandle<uint32_t> bitmap_dictionary; ArrayHandle<uint16_t> node_bitmap_ids; // May be null if not stored in file ArrayHandle<glm::vec2> node_attrib_ranges; std::string bat_prefix; // The trees which have been loaded by the traversal phmap::flat_hash_map<uint64_t, std::shared_ptr<BATree>> loaded_trees; bool enable_range_filtering = true; bool enable_bitmap_filtering = true; AggregationTree(const Box &bounds, const uint64_t num_points, const ArrayHandle<AggregationKdNode> &nodes, const ArrayHandle<uint32_t> &leaf_indices, const ArrayHandle<RankAggregationInfo> &primitives); // When loaded from disk we no longer have the leaf indices info since it's // only needed during aggregation AggregationTree(const Box &bounds, const uint32_t num_aggregators, const uint64_t num_points, const std::vector<AttributeDescription> &attributes, const ArrayHandle<AggregationKdNode> &nodes, const ArrayHandle<uint32_t> &bitmap_dictionary, const ArrayHandle<uint16_t> &node_bitmap_ids, const ArrayHandle<glm::vec2> &node_attrib_ranges, const std::string &bat_prefix); AggregationTree() = default; // Called on the write side to build the attribute bitmaps and ranges for the inner nodes void initialize_attributes(const std::vector<AttributeDescription> &attributes, const std::vector<uint32_t> &aggregator_attribute_bitmaps, const std::vector<glm::vec2> &aggregator_attribute_ranges); // Query the particles contained in some box, retrieving just those particles // which are new for the selected quality level given the previous one template <typename Fn> QueryStats query_box_progressive(const Box &b, std::vector<AttributeQuery> *attrib_queries, float prev_quality, float current_quality, const Fn &callback); // Query all particles contained in some bounding box // The callback should take the point id, position, and list of attributes to read // the point's attributes from, if desired. The function signature should be: // void (const size_t id, const glm::vec3 &pos, const std::vector<Attribute> &attributes) template <typename Fn> QueryStats query_box(const Box &b, std::vector<AttributeQuery> *attrib_queries, float quality, const Fn &callback); // For debugging/testing: query the splitting planes of the tree void get_splitting_planes(std::vector<Plane> &planes, const Box &query_box, std::vector<AttributeQuery> *attrib_queries, float quality); // Get the IDs of the BATrees which contain the query box std::vector<size_t> get_overlapped_subtree_ids(const Box &b) const; // Utility function to iterate through the BATrees and process them with the // callback. Mainly for the inspector, to get meta-data about the aggregtor's trees template <typename Fn> void iterate_aggregator_trees(const Fn &fn); private: void initialize_node_attributes( const size_t n, const std::vector<uint32_t> &aggregator_attribute_bitmaps, const std::vector<glm::vec2> &aggregator_attribute_ranges, const phmap::flat_hash_map<int, size_t> &aggregator_indices, std::vector<uint32_t> &node_bitmaps, OwnedArrayHandle<glm::vec2> &attrib_ranges); bool node_overlaps_query(uint32_t n, const std::vector<AttributeQuery> &query, const std::vector<size_t> &query_indices, QueryStats &stats) const; std::shared_ptr<BATree> fetch_tree(const size_t tree_id); }; template <typename Fn> QueryStats AggregationTree::query_box_progressive(const Box &b, std::vector<AttributeQuery> *attrib_queries, float prev_quality, float current_quality, const Fn &callback) { QueryStats stats; if (!b.overlaps(bounds)) { return stats; } if (prev_quality == current_quality && current_quality != 0.f) { return stats; } std::vector<size_t> query_indices; std::vector<uint32_t> global_bitmasks; if (attrib_queries) { for (auto &a : *attrib_queries) { auto fnd = attrib_ids.find(a.name); if (fnd == attrib_ids.end()) { throw std::runtime_error("Request for attribute " + a.name + " which does not exist"); } query_indices.push_back(fnd->second); a.data_type = attributes[fnd->second].data_type; a.bitmask = a.query_bitmask(attributes[fnd->second].range); global_bitmasks.push_back(a.bitmask); } } prev_quality = remap_quality(prev_quality); current_quality = remap_quality(current_quality); std::array<size_t, 64> node_stack = {0}; size_t stack_idx = 0; size_t current_node = 0; while (true) { const AggregationKdNode &node = nodes->at(current_node); if (!node.is_leaf()) { bool traverse_left = b.lower[node.split_axis()] < node.split_pos; bool traverse_right = b.upper[node.split_axis()] > node.split_pos; if (attrib_queries && traverse_left) { traverse_left = traverse_left && node_overlaps_query( current_node + 1, *attrib_queries, query_indices, stats); } if (attrib_queries && traverse_right) { traverse_right = traverse_right && node_overlaps_query( node.right_child_offset(), *attrib_queries, query_indices, stats); } // If both overlap, descend both children following the left first if (traverse_left && traverse_right) { node_stack[stack_idx] = node.right_child_offset(); stack_idx++; current_node = current_node + 1; continue; } else if (traverse_left) { current_node = current_node + 1; continue; } else if (traverse_right) { current_node = node.right_child_offset(); continue; } } else { auto tree = fetch_tree(node.aggregator_rank); // Sub-tree ranges are local to the subtree, so we need to remap the query masks for (size_t i = 0; i < query_indices.size(); ++i) { const size_t attr = query_indices[i]; const glm::vec2 &global_range = attributes[attr].range; const glm::vec2 &subtree_range = tree->attributes[attr].range; (*attrib_queries)[i].bitmask = remap_bitmask(global_bitmasks[i], global_range, subtree_range); } tree->query_box_log(b, attrib_queries, query_indices, prev_quality, current_quality, callback, stats); for (size_t i = 0; i < query_indices.size(); ++i) { (*attrib_queries)[i].bitmask = global_bitmasks[i]; } } // Pop the stack to get the next node to traverse if (stack_idx > 0) { --stack_idx; current_node = node_stack[stack_idx]; } else { break; } } return stats; } template <typename Fn> QueryStats AggregationTree::query_box(const Box &b, std::vector<AttributeQuery> *attrib_queries, float quality, const Fn &callback) { return query_box_progressive(b, attrib_queries, 0.f, quality, callback); } template <typename Fn> void AggregationTree::iterate_aggregator_trees(const Fn &fn) { for (size_t i = 0; i < nodes->size(); ++i) { const auto &node = nodes->at(i); if (node.is_leaf()) { auto tree = fetch_tree(node.aggregator_rank); fn(tree); } } }
#!/bin/sh # # Copyright (c) 2018-2022, Christer Edwards <christer.edwards@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * 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 the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. . /usr/local/share/bastille/common.sh usage() { error_exit "Usage: bastille pkg [-H|--host] TARGET command [args]" } # Handle special-case commands first. case "$1" in help|-h|--help) usage ;; esac if [ $# -lt 1 ]; then usage fi for _jail in ${JAILS}; do info "[${_jail}]:" bastille_jail_path=$(/usr/sbin/jls -j "${_jail}" path) if [ -f "/usr/sbin/mport" ]; then jexec -l -U root "${_jail}" /usr/sbin/mport "$@" elif [ -f "${bastille_jail_path}/usr/bin/apt" ]; then jexec -l "${_jail}" /usr/bin/apt "$@" elif [ "${USE_HOST_PKG}" = 1 ]; then /usr/sbin/pkg -j "${_jail}" "$@" else jexec -l -U root "${_jail}" /usr/sbin/pkg "$@" fi echo done
package com.nortal.spring.cw.core.web.util; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import com.nortal.spring.cw.core.model.FileHolderModel; import com.nortal.spring.cw.core.web.factory.FileStreamFactory; /** * Utiliit, kuhu on koondatud faili alla laadimisega seotud toimingud * * @author <NAME> <<EMAIL>> * @since 04.04.2014 */ public final class DownloadUtil { /** * Faili alla laadimine * * @param response * {@link HttpServletResponse} * @param fileModel * {@link FileModel} * @throws IOException */ public static void download(HttpServletResponse response, FileHolderModel fileModel) throws IOException { if (fileModel.getFileHolder() == null) { InputStream inputStream = FileStreamFactory.instance(FileStreamFactory.DATABASE).getFileStream(fileModel); if (fileModel.getFileSize() <= Integer.MAX_VALUE) { response.setContentLength(fileModel.getFileSize().intValue()); } download(response, fileModel.getFileColumnName(), fileModel.getFilename(), inputStream); inputStream.close(); } else { download(response, fileModel.getFileColumnName(), fileModel.getFilename(), fileModel.getFileHolder().getData()); } } /** * Faili alla laadimine * * @param response * {@link HttpServletResponse} * @param mimeType * {@link String} Faili tüüp * @param filename * {@link String} Faili nimi * @param data * {@link String} Faili sisu * @throws IOException */ public static void download(HttpServletResponse response, String mimeType, String filename, String data) throws IOException { download(response, mimeType, filename, data.getBytes()); } /** * Faili alla laadimine * * @param response * {@link HttpServletResponse} * @param mimeType * {@link String} Faili tüüp * @param filename * {@link String} Faili nimi * @param data * Faili sisu * @throws IOException */ public static void download(HttpServletResponse response, String mimeType, String filename, byte[] data) throws IOException { prepareDownload(response, mimeType, filename); response.setContentLength(data.length); response.getOutputStream().write(data); } /** * Faili alla laadmine * * @param response * {@link HttpServletResponse} * @param mimeType * {@link String} Faili tüüp * @param filename * {@link String} Faili nimi * @param inputStream * {@link InputStream} Faili sisu * @throws IOException */ public static void download(HttpServletResponse response, String mimeType, String filename, InputStream inputStream) throws IOException { prepareDownload(response, mimeType, filename); BufferedInputStream bis = new BufferedInputStream(inputStream); int ch = 0; byte[] buf = new byte[10000]; while ((ch = bis.read(buf)) >= 0) { response.getOutputStream().write(buf, 0, ch); } } /** * Faili alla laadimise ette valmistamine. Faili alla laadimiseks lisatakse {@link HttpServletResponse} juurde faili laadimist toetavad * päringu vastuse päised * * @param response * {@link HttpServletResponse} * @param mimeType * Faili tüüp * @param filename * Faili nimi */ public static void prepareDownload(HttpServletResponse response, String mimeType, String filename) { response.setHeader("Cache-Control", "private"); response.setHeader("Pragma", "private"); response.setHeader("Content-Transfer-Encoding", "binary"); response.setContentType(mimeType); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); Cookie cookie1 = new Cookie("downloadToken", "true"); cookie1.setMaxAge(20); response.addCookie(cookie1); } }
#!/bin/bash ###################### COPYRIGHT/COPYLEFT ###################### # (C) 2020 Michael Soegtrop # Released to the public under the # Creative Commons CC0 1.0 Universal License # See https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt ###################### USER CHOICES ##################### # parallel or sequential build if [ -z "${COQ_PLATFORM_PARALLEL:+x}" ] || [ -z "${COQ_PLATFORM_JOBS:+x}" ] then cat <<EOH =============================== PARALLEL BUILD =============================== The Coq platform opam build has two levels of parallelism: - parallel build of (independent) opam packages - parallel build inside the make of each opam package Since a single coqc call can take more than 1 GB of RAM and since the two above kinds of parallelism multiply, the total amount of memory can be large. But it is not as bad as one might expect: test show that a full parallel build takes less than 14GB of RAM with 15 parallel make jobs. With 32 GB or RAM a parallel package build with 16 make jobs is recommended. With 16 GB of RAM a parallel package build with 4 make jobs is recommended. With 8 GB of RAM a sequential package build with 4 make jobs is recommended. With 4 GB+1GB swap a sequential packahge build with 2 make jobs is recommended. With less RAM, you might have to remove failing packages, e.g. VST. In order to remove packages, just edit this script at "PACKAGE SELECTION". In case these recommendations don't work for you, please report an issue at: https://github.com/coq/platform/issues =============================== PARALLEL BUILD =============================== EOH ask_user_opt2_cancel "Build opam packages parallel (p) or sequential (s)?" pP "parallel" sS "sequential" COQ_PLATFORM_PARALLEL=$ANSWER ask_user_mumber "Number of parallel make jobs" 1 16 COQ_PLATFORM_JOBS=$ANSWER fi
#!/bin/bash # remediation = none cat > /boot/grub2/grub.cfg << EOM set root='cd' EOM
/* * Copyright (C) Lightbend Inc. <https://www.lightbend.com> */ package play.japi.twirl.compiler; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import scala.Option; import scala.collection.JavaConverters$; import scala.collection.Seq; import scala.io.Codec; import scala.util.Properties$; public class TwirlCompiler { public static final Set<String> DEFAULT_IMPORTS; static { Set<String> imports = new HashSet<>(); imports.addAll(JavaConverters$.MODULE$ .seqAsJavaListConverter(play.twirl.compiler.TwirlCompiler$.MODULE$.DefaultImports()).asJava()); DEFAULT_IMPORTS = Collections.unmodifiableSet(imports); } public static Optional<File> compile(File source, File sourceDirectory, File generatedDirectory, String formatterType, Collection<String> additionalImports, List<String> constructorAnnotations) { Charset sourceEncoding = Charset.forName(Properties$.MODULE$.sourceEncoding()); return compile(source, sourceDirectory, generatedDirectory, formatterType, additionalImports, constructorAnnotations, new Codec(sourceEncoding), false); } public static Optional<File> compile(File source, File sourceDirectory, File generatedDirectory, String formatterType, Collection<String> additionalImports, List<String> constructorAnnotations, Codec codec, boolean inclusiveDot) { Seq<String> scalaAdditionalImports = JavaConverters$.MODULE$.asScalaBufferConverter(new ArrayList<String>(additionalImports)).asScala(); Seq<String> scalaConstructorAnnotations = JavaConverters$.MODULE$.asScalaBufferConverter(constructorAnnotations).asScala(); Option<File> option = play.twirl.compiler.TwirlCompiler.compile(source, sourceDirectory, generatedDirectory, formatterType, scalaAdditionalImports, scalaConstructorAnnotations, codec, inclusiveDot); return Optional.ofNullable(option.nonEmpty() ? option.get() : null); } }
#!/bin/bash # Copyright 2017 Hossein Hadian # 2018 Ashish Arora set -e stage=0 nj=70 # download_dir{1,2,3} points to the database path on the JHU grid. If you have not # already downloaded the database you can set it to a local directory # This corpus can be purchased here: # https://catalog.ldc.upenn.edu/{LDC2012T15,LDC2013T09/,LDC2013T15/} download_dir1=/export/corpora/LDC/LDC2012T15/data download_dir2=/export/corpora/LDC/LDC2013T09/data download_dir3=/export/corpora/LDC/LDC2013T15/data writing_condition1=/export/corpora/LDC/LDC2012T15/docs/writing_conditions.tab writing_condition2=/export/corpora/LDC/LDC2013T09/docs/writing_conditions.tab writing_condition3=/export/corpora/LDC/LDC2013T15/docs/writing_conditions.tab data_splits_dir=data/download/data_splits images_scp_dir=data/local overwrite=false subset=false augment=false use_extra_corpus_text=true . ./cmd.sh ## You'll want to change cmd.sh to something that will work on your system. ## This relates to the queue. . ./path.sh . ./utils/parse_options.sh # e.g. this parses the above options # if supplied. ./local/check_tools.sh mkdir -p data/{train,test,dev}/data mkdir -p data/local/{train,test,dev} if [ $stage -le 0 ]; then if [ -f data/train/text ] && ! $overwrite; then echo "$0: Not processing, probably script have run from wrong stage" echo "Exiting with status 1 to avoid data corruption" exit 1; fi echo "$0: preparing data...$(date)" local/prepare_data.sh --data_splits $data_splits_dir --download_dir1 $download_dir1 \ --download_dir2 $download_dir2 --download_dir3 $download_dir3 \ --use_extra_corpus_text $use_extra_corpus_text for set in test train dev; do data_split_file=$data_splits_dir/madcat.$set.raw.lineid local/extract_lines.sh --nj $nj --cmd $cmd --data_split_file $data_split_file \ --download_dir1 $download_dir1 --download_dir2 $download_dir2 \ --download_dir3 $download_dir3 --writing_condition1 $writing_condition1 \ --writing_condition2 $writing_condition2 --writing_condition3 $writing_condition3 \ --data data/local/$set --subset $subset --augment $augment || exit 1 done echo "$0: Processing data..." for set in dev train test; do local/process_data.py $download_dir1 $download_dir2 $download_dir3 \ $data_splits_dir/madcat.$set.raw.lineid data/$set $images_scp_dir/$set/images.scp \ $writing_condition1 $writing_condition2 $writing_condition3 --augment $augment --subset $subset image/fix_data_dir.sh data/${set} done fi if [ $stage -le 1 ]; then echo "$0: Obtaining image groups. calling get_image2num_frames $(date)." image/get_image2num_frames.py data/train image/get_allowed_lengths.py --frame-subsampling-factor 4 10 data/train for set in test dev train; do echo "$0: Extracting features and calling compute_cmvn_stats for dataset: $set. $(date)" local/extract_features.sh --nj $nj --cmd $cmd --feat-dim 40 data/$set steps/compute_cmvn_stats.sh data/$set || exit 1; done echo "$0: Fixing data directory for train dataset $(date)." utils/fix_data_dir.sh data/train fi if [ $stage -le 2 ]; then echo "$0: Preparing BPE..." cut -d' ' -f2- data/train/text | utils/lang/bpe/reverse.py | \ utils/lang/bpe/prepend_words.py | \ utils/lang/bpe/learn_bpe.py -s 700 > data/local/bpe.txt for set in test train dev; do cut -d' ' -f1 data/$set/text > data/$set/ids cut -d' ' -f2- data/$set/text | utils/lang/bpe/reverse.py | \ utils/lang/bpe/prepend_words.py | \ utils/lang/bpe/apply_bpe.py -c data/local/bpe.txt \ | sed 's/@@//g' > data/$set/bpe_text mv data/$set/text data/$set/text.old paste -d' ' data/$set/ids data/$set/bpe_text > data/$set/text rm -f data/$set/bpe_text data/$set/ids done echo "$0:Preparing dictionary and lang..." local/prepare_dict.sh utils/prepare_lang.sh --num-sil-states 4 --num-nonsil-states 8 --sil-prob 0.0 --position-dependent-phones false \ data/local/dict "<sil>" data/lang/temp data/lang utils/lang/bpe/add_final_optional_silence.sh --final-sil-prob 0.5 data/lang fi if [ $stage -le 3 ]; then echo "$0: Calling the flat-start chain recipe... $(date)." local/chain/run_e2e_cnn.sh fi lang_decode=data/lang lang_rescore=data/lang_rescore_6g decode_e2e=true if [ $stage -le 4 ]; then echo "$0: Estimating a language model for decoding..." local/train_lm.sh utils/format_lm.sh data/lang data/local/local_lm/data/arpa/6gram_big.arpa.gz \ data/local/dict/lexicon.txt $lang_decode utils/build_const_arpa_lm.sh data/local/local_lm/data/arpa/6gram_unpruned.arpa.gz \ data/lang $lang_rescore fi if [ $stage -le 5 ] && $decode_e2e; then echo "$0: $(date) stage 5: decoding end2end setup..." utils/mkgraph.sh --self-loop-scale 1.0 $lang_decode \ exp/chain/e2e_cnn_1a/ exp/chain/e2e_cnn_1a/graph || exit 1; steps/nnet3/decode.sh --acwt 1.0 --post-decode-acwt 10.0 --nj $nj --cmd "$cmd" \ exp/chain/e2e_cnn_1a/graph data/test exp/chain/e2e_cnn_1a/decode_test || exit 1; steps/lmrescore_const_arpa.sh --cmd "$cmd" $lang_decode $lang_rescore \ data/test exp/chain/e2e_cnn_1a/decode_test{,_rescored} || exit 1 echo "$0: Done. Date: $(date). Results:" local/chain/compare_wer.sh exp/chain/e2e_cnn_1a/ fi
import React, { useState } from "react"; import "./App.css"; // material-ui components import AppBar from "material-ui/AppBar"; import Drawer from "material-ui/Drawer"; import MenuItem from "material-ui/MenuItem"; import { Route, Switch, Link, Redirect } from "react-router-dom"; import LandingPage from "./components/Landing"; import Recognize from "./components/Recognize"; import Register from "./components/Register"; import Gallery from "./components/Gallery"; import { loadFaceRecognitionModel, loadSsdMobilenetv1Model, loadFaceLandmarkModel, loadTinyFaceDetectorModel, loadFaceLandmarkTinyModel, } from "face-api.js"; const App = () => { const [toggle, setToggle] = useState(false); const toggleDrawerMenu = () => { setToggle(!toggle); }; const handleClose = () => { setToggle(false); }; React.useEffect(() => { async function fetchModal() { Promise.all([ loadTinyFaceDetectorModel("/models"), loadFaceLandmarkTinyModel("/models"), loadSsdMobilenetv1Model("/models"), loadFaceLandmarkModel("/models"), loadFaceRecognitionModel("/models"), ]); } fetchModal(); }, []); return ( <div> <AppBar className="app-bar" title="CAMERIA" onLeftIconButtonClick={() => toggleDrawerMenu()} zDepth={2} /> <Drawer docked={false} width={200} open={toggle} onRequestChange={(toggle) => setToggle(toggle)} > <Link to={"/"} className="link"> <MenuItem onClick={() => handleClose()}>Home</MenuItem> </Link> <Link to={"/recognize"} className="link"> <MenuItem onClick={() => handleClose()}>Recognize</MenuItem> </Link> <Link to={"/register"} className="link"> <MenuItem onClick={() => handleClose()}>Register</MenuItem> </Link> <Link to={"/gallery"} className="link"> <MenuItem onClick={() => handleClose()}>Gallery</MenuItem> </Link> </Drawer> <Switch> <Route exact path="/" component={LandingPage} /> <Route exact path="/recognize" component={Recognize} /> <Route exact path="/register" component={Register} /> <Route exact path="/gallery" component={Gallery} /> <Redirect component={LandingPage} /> </Switch> </div> ); }; export default App;
# encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. require 'new_relic/agent/datastores' require 'new_relic/agent/datastores/redis' module NewRelic module Agent module Instrumentation module Redis extend self UNKNOWN = "unknown".freeze LOCALHOST = "localhost".freeze def host_for(client) client.path ? LOCALHOST : client.host rescue => e NewRelic::Agent.logger.debug "Failed to retrieve Redis host: #{e}" UNKNOWN end def port_path_or_id_for(client) client.path || client.port rescue => e NewRelic::Agent.logger.debug "Failed to retrieve Redis port_path_or_id: #{e}" UNKNOWN end end end end end DependencyDetection.defer do # Why not :redis? newrelic-redis used that name, so avoid conflicting named :redis_instrumentation depends_on do defined? ::Redis end depends_on do NewRelic::Agent.config[:disable_redis] == false end depends_on do NewRelic::Agent::Datastores::Redis.is_supported_version? && NewRelic::Agent::Datastores::Redis.safe_from_third_party_gem? end executes do NewRelic::Agent.logger.info 'Installing Redis Instrumentation' Redis::Client.class_eval do alias_method :call_without_new_relic, :call if RUBY_VERSION < "2.7.0" def call(*args, &block) operation = args[0][0] statement = ::NewRelic::Agent::Datastores::Redis.format_command(args[0]) hostname = NewRelic::Agent::Instrumentation::Redis.host_for(self) port_path_or_id = NewRelic::Agent::Instrumentation::Redis.port_path_or_id_for(self) segment = NewRelic::Agent::Tracer.start_datastore_segment( product: NewRelic::Agent::Datastores::Redis::PRODUCT_NAME, operation: operation, host: hostname, port_path_or_id: port_path_or_id, database_name: db ) begin segment.notice_nosql_statement(statement) if statement NewRelic::Agent::Tracer.capture_segment_error segment do call_without_new_relic(*args, &block) end ensure segment.finish if segment end end else def call(*args, **kwargs, &block) operation = args[0][0] statement = ::NewRelic::Agent::Datastores::Redis.format_command(args[0]) hostname = NewRelic::Agent::Instrumentation::Redis.host_for(self) port_path_or_id = NewRelic::Agent::Instrumentation::Redis.port_path_or_id_for(self) segment = NewRelic::Agent::Tracer.start_datastore_segment( product: NewRelic::Agent::Datastores::Redis::PRODUCT_NAME, operation: operation, host: hostname, port_path_or_id: port_path_or_id, database_name: db ) begin segment.notice_nosql_statement(statement) if statement NewRelic::Agent::Tracer.capture_segment_error segment do call_without_new_relic(*args, **kwargs, &block) end ensure segment.finish if segment end end end alias_method :call_pipeline_without_new_relic, :call_pipeline if RUBY_VERSION < "2.7.0" def call_pipeline(*args, &block) pipeline = args[0] operation = pipeline.is_a?(::Redis::Pipeline::Multi) ? NewRelic::Agent::Datastores::Redis::MULTI_OPERATION : NewRelic::Agent::Datastores::Redis::PIPELINE_OPERATION statement = ::NewRelic::Agent::Datastores::Redis.format_pipeline_commands(pipeline.commands) hostname = NewRelic::Agent::Instrumentation::Redis.host_for(self) port_path_or_id = NewRelic::Agent::Instrumentation::Redis.port_path_or_id_for(self) segment = NewRelic::Agent::Tracer.start_datastore_segment( product: NewRelic::Agent::Datastores::Redis::PRODUCT_NAME, operation: operation, host: hostname, port_path_or_id: port_path_or_id, database_name: db ) begin segment.notice_nosql_statement(statement) NewRelic::Agent::Tracer.capture_segment_error segment do call_pipeline_without_new_relic(*args, &block) end ensure segment.finish if segment end end else def call_pipeline(*args, **kwargs, &block) pipeline = args[0] operation = pipeline.is_a?(::Redis::Pipeline::Multi) ? NewRelic::Agent::Datastores::Redis::MULTI_OPERATION : NewRelic::Agent::Datastores::Redis::PIPELINE_OPERATION statement = ::NewRelic::Agent::Datastores::Redis.format_pipeline_commands(pipeline.commands) hostname = NewRelic::Agent::Instrumentation::Redis.host_for(self) port_path_or_id = NewRelic::Agent::Instrumentation::Redis.port_path_or_id_for(self) segment = NewRelic::Agent::Tracer.start_datastore_segment( product: NewRelic::Agent::Datastores::Redis::PRODUCT_NAME, operation: operation, host: hostname, port_path_or_id: port_path_or_id, database_name: db ) begin segment.notice_nosql_statement(statement) NewRelic::Agent::Tracer.capture_segment_error segment do call_pipeline_without_new_relic(*args, **kwargs, &block) end ensure segment.finish if segment end end end alias_method :connect_without_new_relic, :connect if RUBY_VERSION < "2.7.0" def connect(*args, &block) hostname = NewRelic::Agent::Instrumentation::Redis.host_for(self) port_path_or_id = NewRelic::Agent::Instrumentation::Redis.port_path_or_id_for(self) segment = NewRelic::Agent::Tracer.start_datastore_segment( product: NewRelic::Agent::Datastores::Redis::PRODUCT_NAME, operation: NewRelic::Agent::Datastores::Redis::CONNECT, host: hostname, port_path_or_id: port_path_or_id, database_name: db ) begin NewRelic::Agent::Tracer.capture_segment_error segment do connect_without_new_relic(*args, &block) end ensure segment.finish if segment end end else def connect(*args, **kwargs, &block) hostname = NewRelic::Agent::Instrumentation::Redis.host_for(self) port_path_or_id = NewRelic::Agent::Instrumentation::Redis.port_path_or_id_for(self) segment = NewRelic::Agent::Tracer.start_datastore_segment( product: NewRelic::Agent::Datastores::Redis::PRODUCT_NAME, operation: NewRelic::Agent::Datastores::Redis::CONNECT, host: hostname, port_path_or_id: port_path_or_id, database_name: db ) begin NewRelic::Agent::Tracer.capture_segment_error segment do connect_without_new_relic(*args, **kwargs, &block) end ensure segment.finish if segment end end end end end end
<reponame>tenebrousedge/ruby-packer require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../../../shared/enumerator/with_object', __FILE__) describe "Enumerator#each_with_object" do it_behaves_like :enum_with_object, :each_with_object end
<gh_stars>0 // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tendermint/farming/v1beta1/tx.proto package types import ( context "context" fmt "fmt" github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" types "github.com/cosmos/cosmos-sdk/types" _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" _ "github.com/regen-network/cosmos-proto" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" _ "google.golang.org/protobuf/types/known/timestamppb" io "io" math "math" math_bits "math/bits" time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // MsgCreateFixedAmountPlan defines a SDK message for creating a new fixed // amount farming plan. type MsgCreateFixedAmountPlan struct { // name specifies the name for the plan Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // creator defines the bech32-encoded address of the creator for the private plan, termination address is also set to // this creator. Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` // staking_coin_weights specifies coins weight for the plan StakingCoinWeights github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,3,rep,name=staking_coin_weights,json=stakingCoinWeights,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"staking_coin_weights" yaml:"staking_coin_weights"` // start_time specifies the start time of the plan StartTime time.Time `protobuf:"bytes,4,opt,name=start_time,json=startTime,proto3,stdtime" json:"start_time" yaml:"start_time"` // end_time specifies the end time of the plan EndTime time.Time `protobuf:"bytes,5,opt,name=end_time,json=endTime,proto3,stdtime" json:"end_time" yaml:"end_time"` // epoch_amount specifies the distributing amount for each epoch EpochAmount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=epoch_amount,json=epochAmount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"epoch_amount" yaml:"epoch_amount"` } func (m *MsgCreateFixedAmountPlan) Reset() { *m = MsgCreateFixedAmountPlan{} } func (m *MsgCreateFixedAmountPlan) String() string { return proto.CompactTextString(m) } func (*MsgCreateFixedAmountPlan) ProtoMessage() {} func (*MsgCreateFixedAmountPlan) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{0} } func (m *MsgCreateFixedAmountPlan) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgCreateFixedAmountPlan) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCreateFixedAmountPlan.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgCreateFixedAmountPlan) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCreateFixedAmountPlan.Merge(m, src) } func (m *MsgCreateFixedAmountPlan) XXX_Size() int { return m.Size() } func (m *MsgCreateFixedAmountPlan) XXX_DiscardUnknown() { xxx_messageInfo_MsgCreateFixedAmountPlan.DiscardUnknown(m) } var xxx_messageInfo_MsgCreateFixedAmountPlan proto.InternalMessageInfo // MsgCreateFixedAmountPlanResponse defines the MsgCreateFixedAmountPlanResponse response type. type MsgCreateFixedAmountPlanResponse struct { } func (m *MsgCreateFixedAmountPlanResponse) Reset() { *m = MsgCreateFixedAmountPlanResponse{} } func (m *MsgCreateFixedAmountPlanResponse) String() string { return proto.CompactTextString(m) } func (*MsgCreateFixedAmountPlanResponse) ProtoMessage() {} func (*MsgCreateFixedAmountPlanResponse) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{1} } func (m *MsgCreateFixedAmountPlanResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgCreateFixedAmountPlanResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCreateFixedAmountPlanResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgCreateFixedAmountPlanResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCreateFixedAmountPlanResponse.Merge(m, src) } func (m *MsgCreateFixedAmountPlanResponse) XXX_Size() int { return m.Size() } func (m *MsgCreateFixedAmountPlanResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgCreateFixedAmountPlanResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgCreateFixedAmountPlanResponse proto.InternalMessageInfo // MsgCreateRatioPlan defines a SDK message for creating a new ratio farming // plan. type MsgCreateRatioPlan struct { // name specifies the name for the plan Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // creator defines the bech32-encoded address of the creator for the private plan, termination address is also set to // this creator. Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` // staking_coin_weights specifies coins weight for the plan StakingCoinWeights github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,3,rep,name=staking_coin_weights,json=stakingCoinWeights,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"staking_coin_weights" yaml:"staking_coin_weights"` // start_time specifies the start time of the plan StartTime time.Time `protobuf:"bytes,4,opt,name=start_time,json=startTime,proto3,stdtime" json:"start_time" yaml:"start_time"` // end_time specifies the end time of the plan EndTime time.Time `protobuf:"bytes,5,opt,name=end_time,json=endTime,proto3,stdtime" json:"end_time" yaml:"end_time"` // epoch_ratio specifies the distributing amount by ratio EpochRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=epoch_ratio,json=epochRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"epoch_ratio" yaml:"epoch_ratio"` } func (m *MsgCreateRatioPlan) Reset() { *m = MsgCreateRatioPlan{} } func (m *MsgCreateRatioPlan) String() string { return proto.CompactTextString(m) } func (*MsgCreateRatioPlan) ProtoMessage() {} func (*MsgCreateRatioPlan) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{2} } func (m *MsgCreateRatioPlan) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgCreateRatioPlan) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCreateRatioPlan.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgCreateRatioPlan) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCreateRatioPlan.Merge(m, src) } func (m *MsgCreateRatioPlan) XXX_Size() int { return m.Size() } func (m *MsgCreateRatioPlan) XXX_DiscardUnknown() { xxx_messageInfo_MsgCreateRatioPlan.DiscardUnknown(m) } var xxx_messageInfo_MsgCreateRatioPlan proto.InternalMessageInfo // MsgCreateRatioPlanResponse defines the Msg/MsgCreateRatioPlanResponse // response type. type MsgCreateRatioPlanResponse struct { } func (m *MsgCreateRatioPlanResponse) Reset() { *m = MsgCreateRatioPlanResponse{} } func (m *MsgCreateRatioPlanResponse) String() string { return proto.CompactTextString(m) } func (*MsgCreateRatioPlanResponse) ProtoMessage() {} func (*MsgCreateRatioPlanResponse) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{3} } func (m *MsgCreateRatioPlanResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgCreateRatioPlanResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCreateRatioPlanResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgCreateRatioPlanResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCreateRatioPlanResponse.Merge(m, src) } func (m *MsgCreateRatioPlanResponse) XXX_Size() int { return m.Size() } func (m *MsgCreateRatioPlanResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgCreateRatioPlanResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgCreateRatioPlanResponse proto.InternalMessageInfo // MsgStake defines a SDK message for staking coins into the farming plan. type MsgStake struct { // farmer defines the bech32-encoded address of the farmer Farmer string `protobuf:"bytes,1,opt,name=farmer,proto3" json:"farmer,omitempty"` // staking_coins specifies coins to stake StakingCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=staking_coins,json=stakingCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"staking_coins" yaml:"staking_coins"` } func (m *MsgStake) Reset() { *m = MsgStake{} } func (m *MsgStake) String() string { return proto.CompactTextString(m) } func (*MsgStake) ProtoMessage() {} func (*MsgStake) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{4} } func (m *MsgStake) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgStake) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgStake.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgStake) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgStake.Merge(m, src) } func (m *MsgStake) XXX_Size() int { return m.Size() } func (m *MsgStake) XXX_DiscardUnknown() { xxx_messageInfo_MsgStake.DiscardUnknown(m) } var xxx_messageInfo_MsgStake proto.InternalMessageInfo // MsgStakeResponse defines the Msg/MsgStakeResponse response type. type MsgStakeResponse struct { } func (m *MsgStakeResponse) Reset() { *m = MsgStakeResponse{} } func (m *MsgStakeResponse) String() string { return proto.CompactTextString(m) } func (*MsgStakeResponse) ProtoMessage() {} func (*MsgStakeResponse) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{5} } func (m *MsgStakeResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgStakeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgStakeResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgStakeResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgStakeResponse.Merge(m, src) } func (m *MsgStakeResponse) XXX_Size() int { return m.Size() } func (m *MsgStakeResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgStakeResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgStakeResponse proto.InternalMessageInfo // MsgUnstake defines a SDK message for performing unstaking of coins from the // farming plan. type MsgUnstake struct { // farmer defines the bech32-encoded address of the farmer Farmer string `protobuf:"bytes,1,opt,name=farmer,proto3" json:"farmer,omitempty"` // unstaking_coins specifies coins to stake UnstakingCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=unstaking_coins,json=unstakingCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"unstaking_coins" yaml:"unstaking_coins"` } func (m *MsgUnstake) Reset() { *m = MsgUnstake{} } func (m *MsgUnstake) String() string { return proto.CompactTextString(m) } func (*MsgUnstake) ProtoMessage() {} func (*MsgUnstake) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{6} } func (m *MsgUnstake) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgUnstake) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgUnstake.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgUnstake) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgUnstake.Merge(m, src) } func (m *MsgUnstake) XXX_Size() int { return m.Size() } func (m *MsgUnstake) XXX_DiscardUnknown() { xxx_messageInfo_MsgUnstake.DiscardUnknown(m) } var xxx_messageInfo_MsgUnstake proto.InternalMessageInfo // MsgUnstakeResponse defines the Msg/MsgUnstakeResponse response type. type MsgUnstakeResponse struct { } func (m *MsgUnstakeResponse) Reset() { *m = MsgUnstakeResponse{} } func (m *MsgUnstakeResponse) String() string { return proto.CompactTextString(m) } func (*MsgUnstakeResponse) ProtoMessage() {} func (*MsgUnstakeResponse) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{7} } func (m *MsgUnstakeResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgUnstakeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgUnstakeResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgUnstakeResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgUnstakeResponse.Merge(m, src) } func (m *MsgUnstakeResponse) XXX_Size() int { return m.Size() } func (m *MsgUnstakeResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgUnstakeResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgUnstakeResponse proto.InternalMessageInfo // MsgHarvest defines a SDK message for claiming rewards from the farming plan. type MsgHarvest struct { // farmer defines the bech32-encoded address of the farmer Farmer string `protobuf:"bytes,1,opt,name=farmer,proto3" json:"farmer,omitempty"` // staking_coin_denoms is the set of denoms of staked coins as a source of the reward for // harvesting StakingCoinDenoms []string `protobuf:"bytes,2,rep,name=staking_coin_denoms,json=stakingCoinDenoms,proto3" json:"staking_coin_denoms,omitempty" yaml:"staking_coin_denoms"` } func (m *MsgHarvest) Reset() { *m = MsgHarvest{} } func (m *MsgHarvest) String() string { return proto.CompactTextString(m) } func (*MsgHarvest) ProtoMessage() {} func (*MsgHarvest) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{8} } func (m *MsgHarvest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgHarvest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgHarvest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgHarvest) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgHarvest.Merge(m, src) } func (m *MsgHarvest) XXX_Size() int { return m.Size() } func (m *MsgHarvest) XXX_DiscardUnknown() { xxx_messageInfo_MsgHarvest.DiscardUnknown(m) } var xxx_messageInfo_MsgHarvest proto.InternalMessageInfo // MsgHarvestResponse defines the Msg/MsgHarvestResponse response type. type MsgHarvestResponse struct { } func (m *MsgHarvestResponse) Reset() { *m = MsgHarvestResponse{} } func (m *MsgHarvestResponse) String() string { return proto.CompactTextString(m) } func (*MsgHarvestResponse) ProtoMessage() {} func (*MsgHarvestResponse) Descriptor() ([]byte, []int) { return fileDescriptor_a33d9a3ff13f514a, []int{9} } func (m *MsgHarvestResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgHarvestResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgHarvestResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgHarvestResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgHarvestResponse.Merge(m, src) } func (m *MsgHarvestResponse) XXX_Size() int { return m.Size() } func (m *MsgHarvestResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgHarvestResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgHarvestResponse proto.InternalMessageInfo func init() { proto.RegisterType((*MsgCreateFixedAmountPlan)(nil), "cosmos.farming.v1beta1.MsgCreateFixedAmountPlan") proto.RegisterType((*MsgCreateFixedAmountPlanResponse)(nil), "cosmos.farming.v1beta1.MsgCreateFixedAmountPlanResponse") proto.RegisterType((*MsgCreateRatioPlan)(nil), "cosmos.farming.v1beta1.MsgCreateRatioPlan") proto.RegisterType((*MsgCreateRatioPlanResponse)(nil), "cosmos.farming.v1beta1.MsgCreateRatioPlanResponse") proto.RegisterType((*MsgStake)(nil), "cosmos.farming.v1beta1.MsgStake") proto.RegisterType((*MsgStakeResponse)(nil), "cosmos.farming.v1beta1.MsgStakeResponse") proto.RegisterType((*MsgUnstake)(nil), "cosmos.farming.v1beta1.MsgUnstake") proto.RegisterType((*MsgUnstakeResponse)(nil), "cosmos.farming.v1beta1.MsgUnstakeResponse") proto.RegisterType((*MsgHarvest)(nil), "cosmos.farming.v1beta1.MsgHarvest") proto.RegisterType((*MsgHarvestResponse)(nil), "cosmos.farming.v1beta1.MsgHarvestResponse") } func init() { proto.RegisterFile("tendermint/farming/v1beta1/tx.proto", fileDescriptor_a33d9a3ff13f514a) } var fileDescriptor_a33d9a3ff13f514a = []byte{ // 785 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x56, 0xcd, 0x4e, 0xdb, 0x4a, 0x18, 0x8d, 0x21, 0x04, 0x18, 0xb8, 0x97, 0xcb, 0x90, 0x8b, 0x8c, 0xa1, 0x76, 0xe4, 0x4a, 0x55, 0x44, 0x85, 0x5d, 0xd2, 0x4d, 0xc5, 0xae, 0x01, 0x15, 0x54, 0x29, 0x55, 0x65, 0x5a, 0xf5, 0x67, 0x13, 0x39, 0xc9, 0x60, 0x2c, 0xf0, 0x4c, 0xea, 0x99, 0x50, 0xe8, 0xb2, 0x55, 0x25, 0xba, 0xa9, 0x78, 0x84, 0xaa, 0xbb, 0x76, 0xdb, 0x65, 0x5f, 0x80, 0x25, 0xcb, 0xaa, 0x8b, 0x50, 0xc1, 0x1b, 0xf0, 0x04, 0x95, 0x67, 0xc6, 0x96, 0x81, 0x90, 0x90, 0x5d, 0x17, 0x5d, 0xc5, 0x63, 0x9f, 0xef, 0xf8, 0x3b, 0xe7, 0x3b, 0x33, 0x0e, 0xb8, 0xc9, 0x10, 0x6e, 0xa0, 0x30, 0xf0, 0x31, 0xb3, 0x37, 0xdc, 0xe8, 0xd7, 0xb3, 0x77, 0x16, 0x6b, 0x88, 0xb9, 0x8b, 0x36, 0xdb, 0xb5, 0x9a, 0x21, 0x61, 0x04, 0x4e, 0xd7, 0x09, 0x0d, 0x08, 0xb5, 0x24, 0xc0, 0x92, 0x00, 0x2d, 0xef, 0x11, 0x8f, 0x70, 0x88, 0x1d, 0x5d, 0x09, 0xb4, 0x36, 0x23, 0xd0, 0x55, 0xf1, 0x40, 0x96, 0x8a, 0x47, 0xba, 0x58, 0xd9, 0x35, 0x97, 0xa2, 0xe4, 0x35, 0x75, 0xe2, 0x63, 0xf9, 0xdc, 0xf0, 0x08, 0xf1, 0xb6, 0x91, 0xcd, 0x57, 0xb5, 0xd6, 0x86, 0xcd, 0xfc, 0x00, 0x51, 0xe6, 0x06, 0x4d, 0x01, 0x30, 0xbf, 0x64, 0x81, 0x5a, 0xa1, 0xde, 0x72, 0x88, 0x5c, 0x86, 0x1e, 0xf8, 0xbb, 0xa8, 0x71, 0x3f, 0x20, 0x2d, 0xcc, 0x1e, 0x6f, 0xbb, 0x18, 0x42, 0x90, 0xc5, 0x6e, 0x80, 0x54, 0xa5, 0xa0, 0x14, 0x47, 0x1d, 0x7e, 0x0d, 0x55, 0x30, 0x5c, 0x8f, 0xc0, 0x24, 0x54, 0x07, 0xf8, 0xed, 0x78, 0x09, 0x3f, 0x2b, 0x20, 0x4f, 0x99, 0xbb, 0xe5, 0x63, 0xaf, 0x1a, 0xb5, 0x50, 0x7d, 0x8d, 0x7c, 0x6f, 0x93, 0x51, 0x75, 0xb0, 0x30, 0x58, 0x1c, 0x2b, 0xcd, 0x59, 0xb2, 0xf3, 0xa8, 0xd7, 0x58, 0xb1, 0xb5, 0x82, 0xea, 0xcb, 0xc4, 0xc7, 0x65, 0xe7, 0xb0, 0x6d, 0x64, 0xce, 0xda, 0xc6, 0xec, 0x9e, 0x1b, 0x6c, 0x2f, 0x99, 0x9d, 0x78, 0xcc, 0xaf, 0xc7, 0xc6, 0x6d, 0xcf, 0x67, 0x9b, 0xad, 0x9a, 0x55, 0x27, 0x81, 0x34, 0x42, 0xfe, 0x2c, 0xd0, 0xc6, 0x96, 0xcd, 0xf6, 0x9a, 0x88, 0xc6, 0x94, 0xd4, 0x81, 0x92, 0x25, 0x5a, 0x3d, 0x13, 0x1c, 0xf0, 0x39, 0x00, 0x94, 0xb9, 0x21, 0xab, 0x46, 0x46, 0xa8, 0xd9, 0x82, 0x52, 0x1c, 0x2b, 0x69, 0x96, 0x70, 0xc9, 0x8a, 0x5d, 0xb2, 0x9e, 0xc4, 0x2e, 0x95, 0x6f, 0xc8, 0xbe, 0x26, 0x93, 0xbe, 0x64, 0xad, 0x79, 0x70, 0x6c, 0x28, 0xce, 0x28, 0xbf, 0x11, 0xc1, 0xa1, 0x03, 0x46, 0x10, 0x6e, 0x08, 0xde, 0xa1, 0x9e, 0xbc, 0xb3, 0x92, 0x77, 0x42, 0xf0, 0xc6, 0x95, 0x82, 0x75, 0x18, 0xe1, 0x06, 0xe7, 0x7c, 0xaf, 0x80, 0x71, 0xd4, 0x24, 0xf5, 0xcd, 0xaa, 0xcb, 0xa7, 0xa2, 0xe6, 0xb8, 0x95, 0x33, 0x1d, 0xad, 0xe4, 0x3e, 0xae, 0x4a, 0xde, 0x29, 0xc9, 0x9b, 0x2a, 0x8e, 0xfc, 0x2b, 0x5e, 0xc3, 0x3f, 0x61, 0xde, 0x18, 0x2f, 0x15, 0x61, 0x58, 0xca, 0xee, 0x7f, 0x32, 0x32, 0xa6, 0x09, 0x0a, 0x57, 0x45, 0xc5, 0x41, 0xb4, 0x49, 0x30, 0x45, 0xe6, 0xdb, 0x2c, 0x80, 0x09, 0xc8, 0x71, 0x99, 0x4f, 0xfe, 0x26, 0xe9, 0x4f, 0x48, 0x12, 0x02, 0x62, 0xa0, 0xd5, 0x30, 0x9a, 0x89, 0x9a, 0x8b, 0x0c, 0x2f, 0xaf, 0x44, 0xa5, 0x3f, 0xdb, 0xc6, 0xad, 0xeb, 0x79, 0x71, 0xd6, 0x36, 0x60, 0x3a, 0x56, 0x9c, 0xca, 0x74, 0x00, 0x5f, 0xf1, 0x59, 0xcb, 0xa0, 0xcc, 0x01, 0xed, 0x72, 0x06, 0x92, 0x88, 0x7c, 0x53, 0xc0, 0x48, 0x85, 0x7a, 0xeb, 0xcc, 0xdd, 0x42, 0x70, 0x1a, 0xe4, 0xa2, 0x43, 0x10, 0x85, 0x32, 0x1a, 0x72, 0x05, 0xf7, 0x15, 0xf0, 0x4f, 0x7a, 0x74, 0x54, 0x1d, 0xe8, 0x15, 0xfd, 0x35, 0x69, 0x44, 0xfe, 0xf2, 0xe0, 0x69, 0x7f, 0xd9, 0x1f, 0x4f, 0x8d, 0x9b, 0x4a, 0x4d, 0x10, 0xfc, 0x17, 0x37, 0x9d, 0x28, 0xf9, 0xae, 0x00, 0x50, 0xa1, 0xde, 0x53, 0x4c, 0xbb, 0x6a, 0xf9, 0xa8, 0x80, 0x89, 0x16, 0xee, 0x53, 0xcd, 0x43, 0xa9, 0x66, 0x5a, 0xa8, 0xb9, 0x50, 0xdf, 0x9f, 0x9e, 0x7f, 0x93, 0xea, 0xb4, 0xa2, 0x3c, 0xdf, 0xa9, 0xb2, 0xf9, 0x44, 0xd3, 0x1b, 0x2e, 0x69, 0xcd, 0x0d, 0x77, 0x10, 0x65, 0x57, 0x4a, 0x7a, 0x04, 0xa6, 0xce, 0x6d, 0xac, 0x06, 0xc2, 0x24, 0x10, 0xaa, 0x46, 0xcb, 0xfa, 0x59, 0xdb, 0xd0, 0x3a, 0xec, 0x3e, 0x01, 0x32, 0x9d, 0xc9, 0x54, 0x33, 0x2b, 0xfc, 0xde, 0xb9, 0x8e, 0xe4, 0xbb, 0xe3, 0x8e, 0x4a, 0x1f, 0xb2, 0x60, 0xb0, 0x42, 0x3d, 0xf8, 0x4e, 0x01, 0xff, 0x77, 0xfe, 0x4e, 0xdd, 0xb1, 0x3a, 0x7f, 0x4f, 0xad, 0xab, 0x8e, 0x2b, 0xed, 0x5e, 0xbf, 0x15, 0x71, 0x37, 0xf0, 0x15, 0x98, 0xb8, 0x78, 0xb8, 0xcd, 0xf7, 0x24, 0x4b, 0xb0, 0x5a, 0xe9, 0xfa, 0xd8, 0xe4, 0x95, 0xeb, 0x60, 0x48, 0x6c, 0x96, 0x42, 0x97, 0x62, 0x8e, 0xd0, 0x8a, 0xbd, 0x10, 0x09, 0xe9, 0x0b, 0x30, 0x1c, 0xe7, 0xd6, 0xec, 0x52, 0x24, 0x31, 0xda, 0x7c, 0x6f, 0x4c, 0x9a, 0x3a, 0xce, 0x4f, 0x37, 0x6a, 0x89, 0xe9, 0x4a, 0x7d, 0x21, 0x0b, 0xe5, 0xd5, 0xc3, 0x13, 0x5d, 0x39, 0x3a, 0xd1, 0x95, 0x5f, 0x27, 0xba, 0x72, 0x70, 0xaa, 0x67, 0x8e, 0x4e, 0xf5, 0xcc, 0x8f, 0x53, 0x3d, 0xf3, 0x72, 0x21, 0xb5, 0x1b, 0x3a, 0xfc, 0x05, 0xdb, 0x4d, 0xae, 0xf8, 0xc6, 0xa8, 0xe5, 0xf8, 0x49, 0x7a, 0xf7, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0x75, 0x71, 0xd2, 0xf4, 0xaf, 0x09, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // MsgClient is the client API for Msg service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type MsgClient interface { // CreateFixedAmountPlan defines a method for creating a new fixed amount // farming plan CreateFixedAmountPlan(ctx context.Context, in *MsgCreateFixedAmountPlan, opts ...grpc.CallOption) (*MsgCreateFixedAmountPlanResponse, error) // CreateRatioPlan defines a method for creating a new ratio farming plan CreateRatioPlan(ctx context.Context, in *MsgCreateRatioPlan, opts ...grpc.CallOption) (*MsgCreateRatioPlanResponse, error) // Stake defines a method for staking coins into the farming plan Stake(ctx context.Context, in *MsgStake, opts ...grpc.CallOption) (*MsgStakeResponse, error) // Unstake defines a method for unstaking coins from the farming plan Unstake(ctx context.Context, in *MsgUnstake, opts ...grpc.CallOption) (*MsgUnstakeResponse, error) // harvest defines a method for claiming farming rewards Harvest(ctx context.Context, in *MsgHarvest, opts ...grpc.CallOption) (*MsgHarvestResponse, error) } type msgClient struct { cc grpc1.ClientConn } func NewMsgClient(cc grpc1.ClientConn) MsgClient { return &msgClient{cc} } func (c *msgClient) CreateFixedAmountPlan(ctx context.Context, in *MsgCreateFixedAmountPlan, opts ...grpc.CallOption) (*MsgCreateFixedAmountPlanResponse, error) { out := new(MsgCreateFixedAmountPlanResponse) err := c.cc.Invoke(ctx, "/cosmos.farming.v1beta1.Msg/CreateFixedAmountPlan", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *msgClient) CreateRatioPlan(ctx context.Context, in *MsgCreateRatioPlan, opts ...grpc.CallOption) (*MsgCreateRatioPlanResponse, error) { out := new(MsgCreateRatioPlanResponse) err := c.cc.Invoke(ctx, "/cosmos.farming.v1beta1.Msg/CreateRatioPlan", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *msgClient) Stake(ctx context.Context, in *MsgStake, opts ...grpc.CallOption) (*MsgStakeResponse, error) { out := new(MsgStakeResponse) err := c.cc.Invoke(ctx, "/cosmos.farming.v1beta1.Msg/Stake", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *msgClient) Unstake(ctx context.Context, in *MsgUnstake, opts ...grpc.CallOption) (*MsgUnstakeResponse, error) { out := new(MsgUnstakeResponse) err := c.cc.Invoke(ctx, "/cosmos.farming.v1beta1.Msg/Unstake", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *msgClient) Harvest(ctx context.Context, in *MsgHarvest, opts ...grpc.CallOption) (*MsgHarvestResponse, error) { out := new(MsgHarvestResponse) err := c.cc.Invoke(ctx, "/cosmos.farming.v1beta1.Msg/Harvest", in, out, opts...) if err != nil { return nil, err } return out, nil } // MsgServer is the server API for Msg service. type MsgServer interface { // CreateFixedAmountPlan defines a method for creating a new fixed amount // farming plan CreateFixedAmountPlan(context.Context, *MsgCreateFixedAmountPlan) (*MsgCreateFixedAmountPlanResponse, error) // CreateRatioPlan defines a method for creating a new ratio farming plan CreateRatioPlan(context.Context, *MsgCreateRatioPlan) (*MsgCreateRatioPlanResponse, error) // Stake defines a method for staking coins into the farming plan Stake(context.Context, *MsgStake) (*MsgStakeResponse, error) // Unstake defines a method for unstaking coins from the farming plan Unstake(context.Context, *MsgUnstake) (*MsgUnstakeResponse, error) // harvest defines a method for claiming farming rewards Harvest(context.Context, *MsgHarvest) (*MsgHarvestResponse, error) } // UnimplementedMsgServer can be embedded to have forward compatible implementations. type UnimplementedMsgServer struct { } func (*UnimplementedMsgServer) CreateFixedAmountPlan(ctx context.Context, req *MsgCreateFixedAmountPlan) (*MsgCreateFixedAmountPlanResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateFixedAmountPlan not implemented") } func (*UnimplementedMsgServer) CreateRatioPlan(ctx context.Context, req *MsgCreateRatioPlan) (*MsgCreateRatioPlanResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateRatioPlan not implemented") } func (*UnimplementedMsgServer) Stake(ctx context.Context, req *MsgStake) (*MsgStakeResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Stake not implemented") } func (*UnimplementedMsgServer) Unstake(ctx context.Context, req *MsgUnstake) (*MsgUnstakeResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Unstake not implemented") } func (*UnimplementedMsgServer) Harvest(ctx context.Context, req *MsgHarvest) (*MsgHarvestResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Harvest not implemented") } func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) } func _Msg_CreateFixedAmountPlan_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgCreateFixedAmountPlan) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).CreateFixedAmountPlan(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/cosmos.farming.v1beta1.Msg/CreateFixedAmountPlan", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).CreateFixedAmountPlan(ctx, req.(*MsgCreateFixedAmountPlan)) } return interceptor(ctx, in, info, handler) } func _Msg_CreateRatioPlan_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgCreateRatioPlan) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).CreateRatioPlan(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/cosmos.farming.v1beta1.Msg/CreateRatioPlan", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).CreateRatioPlan(ctx, req.(*MsgCreateRatioPlan)) } return interceptor(ctx, in, info, handler) } func _Msg_Stake_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgStake) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).Stake(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/cosmos.farming.v1beta1.Msg/Stake", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).Stake(ctx, req.(*MsgStake)) } return interceptor(ctx, in, info, handler) } func _Msg_Unstake_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgUnstake) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).Unstake(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/cosmos.farming.v1beta1.Msg/Unstake", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).Unstake(ctx, req.(*MsgUnstake)) } return interceptor(ctx, in, info, handler) } func _Msg_Harvest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgHarvest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).Harvest(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/cosmos.farming.v1beta1.Msg/Harvest", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).Harvest(ctx, req.(*MsgHarvest)) } return interceptor(ctx, in, info, handler) } var _Msg_serviceDesc = grpc.ServiceDesc{ ServiceName: "cosmos.farming.v1beta1.Msg", HandlerType: (*MsgServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "CreateFixedAmountPlan", Handler: _Msg_CreateFixedAmountPlan_Handler, }, { MethodName: "CreateRatioPlan", Handler: _Msg_CreateRatioPlan_Handler, }, { MethodName: "Stake", Handler: _Msg_Stake_Handler, }, { MethodName: "Unstake", Handler: _Msg_Unstake_Handler, }, { MethodName: "Harvest", Handler: _Msg_Harvest_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "tendermint/farming/v1beta1/tx.proto", } func (m *MsgCreateFixedAmountPlan) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgCreateFixedAmountPlan) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgCreateFixedAmountPlan) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.EpochAmount) > 0 { for iNdEx := len(m.EpochAmount) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.EpochAmount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x32 } } n1, err1 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.EndTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.EndTime):]) if err1 != nil { return 0, err1 } i -= n1 i = encodeVarintTx(dAtA, i, uint64(n1)) i-- dAtA[i] = 0x2a n2, err2 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.StartTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.StartTime):]) if err2 != nil { return 0, err2 } i -= n2 i = encodeVarintTx(dAtA, i, uint64(n2)) i-- dAtA[i] = 0x22 if len(m.StakingCoinWeights) > 0 { for iNdEx := len(m.StakingCoinWeights) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.StakingCoinWeights[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a } } if len(m.Creator) > 0 { i -= len(m.Creator) copy(dAtA[i:], m.Creator) i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) i-- dAtA[i] = 0x12 } if len(m.Name) > 0 { i -= len(m.Name) copy(dAtA[i:], m.Name) i = encodeVarintTx(dAtA, i, uint64(len(m.Name))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MsgCreateFixedAmountPlanResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgCreateFixedAmountPlanResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgCreateFixedAmountPlanResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *MsgCreateRatioPlan) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgCreateRatioPlan) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgCreateRatioPlan) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size := m.EpochRatio.Size() i -= size if _, err := m.EpochRatio.MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x32 n3, err3 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.EndTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.EndTime):]) if err3 != nil { return 0, err3 } i -= n3 i = encodeVarintTx(dAtA, i, uint64(n3)) i-- dAtA[i] = 0x2a n4, err4 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.StartTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.StartTime):]) if err4 != nil { return 0, err4 } i -= n4 i = encodeVarintTx(dAtA, i, uint64(n4)) i-- dAtA[i] = 0x22 if len(m.StakingCoinWeights) > 0 { for iNdEx := len(m.StakingCoinWeights) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.StakingCoinWeights[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a } } if len(m.Creator) > 0 { i -= len(m.Creator) copy(dAtA[i:], m.Creator) i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) i-- dAtA[i] = 0x12 } if len(m.Name) > 0 { i -= len(m.Name) copy(dAtA[i:], m.Name) i = encodeVarintTx(dAtA, i, uint64(len(m.Name))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MsgCreateRatioPlanResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgCreateRatioPlanResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgCreateRatioPlanResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *MsgStake) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgStake) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgStake) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.StakingCoins) > 0 { for iNdEx := len(m.StakingCoins) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.StakingCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } } if len(m.Farmer) > 0 { i -= len(m.Farmer) copy(dAtA[i:], m.Farmer) i = encodeVarintTx(dAtA, i, uint64(len(m.Farmer))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MsgStakeResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgStakeResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgStakeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *MsgUnstake) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgUnstake) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgUnstake) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.UnstakingCoins) > 0 { for iNdEx := len(m.UnstakingCoins) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.UnstakingCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } } if len(m.Farmer) > 0 { i -= len(m.Farmer) copy(dAtA[i:], m.Farmer) i = encodeVarintTx(dAtA, i, uint64(len(m.Farmer))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MsgUnstakeResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgUnstakeResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgUnstakeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *MsgHarvest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgHarvest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgHarvest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.StakingCoinDenoms) > 0 { for iNdEx := len(m.StakingCoinDenoms) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.StakingCoinDenoms[iNdEx]) copy(dAtA[i:], m.StakingCoinDenoms[iNdEx]) i = encodeVarintTx(dAtA, i, uint64(len(m.StakingCoinDenoms[iNdEx]))) i-- dAtA[i] = 0x12 } } if len(m.Farmer) > 0 { i -= len(m.Farmer) copy(dAtA[i:], m.Farmer) i = encodeVarintTx(dAtA, i, uint64(len(m.Farmer))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MsgHarvestResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgHarvestResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgHarvestResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func encodeVarintTx(dAtA []byte, offset int, v uint64) int { offset -= sovTx(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *MsgCreateFixedAmountPlan) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Name) if l > 0 { n += 1 + l + sovTx(uint64(l)) } l = len(m.Creator) if l > 0 { n += 1 + l + sovTx(uint64(l)) } if len(m.StakingCoinWeights) > 0 { for _, e := range m.StakingCoinWeights { l = e.Size() n += 1 + l + sovTx(uint64(l)) } } l = github_com_gogo_protobuf_types.SizeOfStdTime(m.StartTime) n += 1 + l + sovTx(uint64(l)) l = github_com_gogo_protobuf_types.SizeOfStdTime(m.EndTime) n += 1 + l + sovTx(uint64(l)) if len(m.EpochAmount) > 0 { for _, e := range m.EpochAmount { l = e.Size() n += 1 + l + sovTx(uint64(l)) } } return n } func (m *MsgCreateFixedAmountPlanResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *MsgCreateRatioPlan) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Name) if l > 0 { n += 1 + l + sovTx(uint64(l)) } l = len(m.Creator) if l > 0 { n += 1 + l + sovTx(uint64(l)) } if len(m.StakingCoinWeights) > 0 { for _, e := range m.StakingCoinWeights { l = e.Size() n += 1 + l + sovTx(uint64(l)) } } l = github_com_gogo_protobuf_types.SizeOfStdTime(m.StartTime) n += 1 + l + sovTx(uint64(l)) l = github_com_gogo_protobuf_types.SizeOfStdTime(m.EndTime) n += 1 + l + sovTx(uint64(l)) l = m.EpochRatio.Size() n += 1 + l + sovTx(uint64(l)) return n } func (m *MsgCreateRatioPlanResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *MsgStake) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Farmer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } if len(m.StakingCoins) > 0 { for _, e := range m.StakingCoins { l = e.Size() n += 1 + l + sovTx(uint64(l)) } } return n } func (m *MsgStakeResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *MsgUnstake) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Farmer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } if len(m.UnstakingCoins) > 0 { for _, e := range m.UnstakingCoins { l = e.Size() n += 1 + l + sovTx(uint64(l)) } } return n } func (m *MsgUnstakeResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *MsgHarvest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Farmer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } if len(m.StakingCoinDenoms) > 0 { for _, s := range m.StakingCoinDenoms { l = len(s) n += 1 + l + sovTx(uint64(l)) } } return n } func (m *MsgHarvestResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func sovTx(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozTx(x uint64) (n int) { return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *MsgCreateFixedAmountPlan) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgCreateFixedAmountPlan: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgCreateFixedAmountPlan: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Creator = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StakingCoinWeights", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.StakingCoinWeights = append(m.StakingCoinWeights, types.DecCoin{}) if err := m.StakingCoinWeights[len(m.StakingCoinWeights)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StartTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.StartTime, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field EndTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.EndTime, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field EpochAmount", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.EpochAmount = append(m.EpochAmount, types.Coin{}) if err := m.EpochAmount[len(m.EpochAmount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgCreateFixedAmountPlanResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgCreateFixedAmountPlanResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgCreateFixedAmountPlanResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgCreateRatioPlan) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgCreateRatioPlan: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgCreateRatioPlan: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Creator = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StakingCoinWeights", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.StakingCoinWeights = append(m.StakingCoinWeights, types.DecCoin{}) if err := m.StakingCoinWeights[len(m.StakingCoinWeights)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StartTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.StartTime, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field EndTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.EndTime, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field EpochRatio", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.EpochRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgCreateRatioPlanResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgCreateRatioPlanResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgCreateRatioPlanResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgStake) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgStake: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgStake: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Farmer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Farmer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StakingCoins", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.StakingCoins = append(m.StakingCoins, types.Coin{}) if err := m.StakingCoins[len(m.StakingCoins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgStakeResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgStakeResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgStakeResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgUnstake) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgUnstake: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgUnstake: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Farmer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Farmer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field UnstakingCoins", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.UnstakingCoins = append(m.UnstakingCoins, types.Coin{}) if err := m.UnstakingCoins[len(m.UnstakingCoins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgUnstakeResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgUnstakeResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgUnstakeResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgHarvest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgHarvest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgHarvest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Farmer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Farmer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StakingCoinDenoms", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.StakingCoinDenoms = append(m.StakingCoinDenoms, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgHarvestResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgHarvestResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgHarvestResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipTx(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthTx } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupTx } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthTx } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") )
(function () { var m = dtm.model('csd-osc', 'instr').register(); var params = { iNum: 1 }; m.modules = { pitch: dtm.a(72), div: dtm.a(16) }; m.output = function (c) { var p = m.modules.pitch.get('next'); var div = m.modules.div.get('next'); c.div(div); var i = params.iNum; if (typeof(i) === 'number') { i = 'i'.concat(i); } else { i = 'i\\"'+i+'\\"'; } dtm.osc.send('/csd/event', [i, 0, 0.1, p]); return m.parent; }; m.mod.pitch = function (src, literal) { mapper(src, 'pitch'); if (!literal) { m.modules.pitch.normalize().rescale(60, 90).round(); } return m.parent; }; m.mod.div = function (src, literal) { mapper(src, 'div'); if (!literal) { m.modules.div.normalize().scale(1, 5).round().powof(2); } return m.parent; }; m.param.name = function (src, literal) { params.iNum = src; return m.parent; }; // TODO: this needs to be a core function? function mapper(src, dest) { if (typeof(src) === 'number') { m.modules[dest] = dtm.array(src); } else if (typeof(src) === 'string') { m.modules[dest] = dtm.array(src).classify(); } else { if (src.constructor === Array) { m.modules[dest] = dtm.array(src); } else if (isDtmArray(src)) { if (src.get('type') === 'string') { m.modules[dest] = src.clone().classify(); } else { m.modules[dest] = src.clone(); } } else if (src.type === 'dtm.model') { } else if (src.type === 'dtm.synth') { m.modules[dest] = src; } } } return m; })();
<reponame>mkoncek/javapackages-bootstrap<filename>mbi/dist/src/org/fedoraproject/mbi/tool/dist/LicensingDist.java /*- * Copyright (c) 2020 Red Hat, 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 org.fedoraproject.mbi.tool.dist; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.fedoraproject.mbi.Reactor; import org.fedoraproject.mbi.dist.DistRequest; /** * @author <NAME> */ public class LicensingDist { private final Reactor reactor; private final DistRequest dist; public LicensingDist( DistRequest dist ) { this.reactor = dist.getReactor(); this.dist = dist; } public void doDist() throws Exception { var licensesDir = dist.getInstallRoot().resolve( dist.getLicensesPath() ); Files.createDirectories( licensesDir ); for ( var project : reactor.getProjects() ) { var licensing = project.getLicensing(); for ( var file : licensing.getFiles() ) { var path = reactor.getProjectDir( project ).resolve( file ); if ( !Files.isRegularFile( path ) ) { throw new RuntimeException( "License file for " + project.getName() + " does not exist: " + file ); } Files.copy( path, licensesDir.resolve( project.getName() + "-" + path.getFileName() ) ); } if ( licensing.getText() != null ) { Files.writeString( licensesDir.resolve( project.getName() + "-" + "COPYING" ), licensing.getText(), StandardOpenOption.CREATE_NEW ); } } } }
<reponame>chylex/Hardcore-Ender-Expansion<gh_stars>10-100 package chylex.hee.block.override; import java.util.List; import java.util.Random; import net.minecraft.block.BlockEndPortal; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import chylex.hee.game.save.SaveData; import chylex.hee.game.save.types.player.PortalFile; import chylex.hee.mechanics.causatum.Causatum; import chylex.hee.mechanics.causatum.Causatum.Progress; import chylex.hee.system.abstractions.Meta; import chylex.hee.system.abstractions.Pos; import chylex.hee.system.abstractions.Pos.PosMutable; import chylex.hee.system.abstractions.facing.Facing4; import chylex.hee.tileentity.TileEntityEndPortalCustom; import chylex.hee.world.TeleportHandler; import chylex.hee.world.util.EntityPortalStatus; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockEndPortalCustom extends BlockEndPortal{ private final EntityPortalStatus portalStatus = new EntityPortalStatus(); public BlockEndPortalCustom(){ super(Material.portal); setBlockUnbreakable().setResistance(6000000F); setTickRandomly(true); } @Override public TileEntity createNewTileEntity(World world, int meta){ return new TileEntityEndPortalCustom(); } @Override public void updateTick(World world, int x, int y, int z, Random rand){ Pos pos = Pos.at(x, y, z); int meta = pos.getMetadata(world); if (meta != Meta.endPortalActive && meta != Meta.endPortalDisabled)pos.setAir(world); } @Override public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity){ if (entity.posY <= y+0.05D && entity instanceof EntityPlayerMP){ Pos pos = Pos.at(x, y, z); int meta = pos.getMetadata(world); EntityPlayerMP player = (EntityPlayerMP)entity; if (meta == Meta.endPortalActive){ if (portalStatus.onTouch(player)){ if (world.provider.dimensionId == 0){ SaveData.player(player, PortalFile.class).setStrongholdPos(findCenterPortalBlock(world, pos)); Causatum.progress(player, Progress.INTO_THE_END); TeleportHandler.toEnd(player); } else TeleportHandler.toOverworld(player); } } else if (meta != Meta.endPortalDisabled){ pos.setAir(world); return; } } } @Override public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta){ return Meta.endPortalActive; } @Override public void onBlockAdded(World world, int x, int y, int z){ world.scheduleBlockUpdate(x, y, z, this, 1); } @Override public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB checkAABB, List list, Entity entity){ AxisAlignedBB collisionBox = AxisAlignedBB.getBoundingBox(x, y, z, x+1D, y+0.025D, z+1D); if (checkAABB.intersectsWith(collisionBox))list.add(collisionBox); } @Override @SideOnly(Side.CLIENT) public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player){ return new ItemStack(this, 1, Pos.at(x, y, z).getMetadata(world)); } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(World world, int x, int y, int z, Random rand){ if (Pos.at(x, y, z).getMetadata(world) == Meta.endPortalActive && rand.nextInt(7) == 0){ world.spawnParticle("smoke", x+rand.nextDouble(), y+0.25D, z+rand.nextDouble(), 0D, 0D, 0D); } } private Pos findCenterPortalBlock(World world, Pos anyPos){ PosMutable pos1 = new PosMutable(anyPos), pos2 = new PosMutable(anyPos); while(pos1.move(Facing4.NORTH_NEGZ).getBlock(world) == this); pos1.move(Facing4.SOUTH_POSZ); while(pos1.move(Facing4.WEST_NEGX).getBlock(world) == this); pos1.move(Facing4.EAST_POSX); while(pos2.move(Facing4.SOUTH_POSZ).getBlock(world) == this); pos2.move(Facing4.NORTH_NEGZ); while(pos2.move(Facing4.EAST_POSX).getBlock(world) == this); pos2.move(Facing4.WEST_NEGX); return pos1.offset((pos2.getX()-pos1.getX())/2, 0, (pos2.getZ()-pos1.getZ())/2); } }
<gh_stars>0 #include <condition_variable> #include <regex> #include <unordered_set> #include <mesytec-mvlc/mesytec-mvlc.h> #include <lyra/lyra.hpp> /* mini-daq-replay ================================================ open and init ------------- ZipReader open find archive member openEntry -> ReadHandle preamble = read_preamble(ReadHandle) -> magic bytes, system events preamble file format check (magic bytes) build CrateConfig from preamble systemevent data prepare reading ---------------- parser callback setup snoopQueues thread(run_readout_parser) ReplayWorker <- does the actual reading from file connected via snoopQueues read ----------------- replayWorker.start() replayWorker.waitableState().wait() ---- snoopqueues sentinel handling to terminate the readout parser simpler direct call interface ============================================= handle = open_listfile(filename) if (!handle->isOpen()) print handle->errorCode, handle->errorString auto crateConfig = handle->getCrateConfig(); while (auto data = read_next_event(handle)) { if (data->type == SystemEvent) { if (data->systemEvent->subtype == TimeTick) print "got a timetick" } else if (data->type == EventData) { data->eventIndex data->eventName data->moduleCount data->moduleNames data->moduleData[moduleIndex].ptr; data->moduleData[moduleIndex].size; } auto stats = handle->getStats() } close_listfile(handle); */ using std::cout; using std::cerr; using std::endl; using namespace mesytec::mvlc; using namespace mesytec::mvlc::readout_parser; struct EventData { enum Type { SystemEvent, ReadoutEvent }; Type type; size_t linearEventNumber = 0u; // SystemEvent DataBlock systemEventData; // ReadoutEvent int eventIndex; std::vector<ModuleData> moduleData; }; class Handle { private: struct Sync { bool ready = false; bool processed = false; std::mutex m; std::condition_variable cv; }; const size_t BufferSize = util::Megabytes(1); const size_t BufferCount = 10; Sync sync_; std::atomic<bool> replayDone_; CrateConfig crateConfig_; EventData currentData_; // parser ReadoutParserCallbacks parserCallbacks_; ReadoutParserState parserState_; Protected<readout_parser::ReadoutParserCounters> parserCounters_; std::thread parserThread_; // reader listfile::ZipReader zr_; listfile::ReadHandle *rh_; std::unique_ptr<ReplayWorker> replayWorker_; ReadoutBufferQueues snoopQueues_; // terminate and monitor thread std::thread monitorThread_; void monitor() { replayWorker_->waitableState().wait( [] (const ReplayWorker::State &state) { return state == ReplayWorker::State::Idle; }); if (parserThread_.joinable()) { if (auto sentinel = snoopQueues_.emptyBufferQueue().dequeue(std::chrono::seconds(1))) { sentinel->clear(); snoopQueues_.filledBufferQueue().enqueue(sentinel); } parserThread_.join(); } replayDone_ = true; } public: Handle(const std::string &filename) : replayDone_(false) , parserCounters_({}) , snoopQueues_(BufferSize, BufferCount) { // open listfile zr_.openArchive(filename); auto entryNames = zr_.entryNameList(); auto it = std::find_if( std::begin(entryNames), std::end(entryNames), [] (const std::string &entryName) { static const std::regex re(R"foo(.+\.mvlclst(\.lz4)?)foo"); return std::regex_search(entryName, re); }); if (it == std::end(entryNames)) throw std::runtime_error("No listfile found in archive"); auto entryName = *it; rh_ = zr_.openEntry(entryName); auto preamble = listfile::read_preamble(*rh_); if (!(preamble.magic == listfile::get_filemagic_eth() || preamble.magic == listfile::get_filemagic_usb())) throw std::runtime_error("invalid file format"); if (auto configSection = preamble.findCrateConfig()) crateConfig_ = crate_config_from_yaml(configSection->contentsToString()); // parser parserCallbacks_.eventData = [this] ( int eventIndex, const readout_parser::ModuleData *moduleDataList, unsigned moduleCount) { std::unique_lock<std::mutex> guard(sync_.m); sync_.cv.wait(guard, [this] () { return sync_.processed; }); currentData_.type = EventData::ReadoutEvent; currentData_.linearEventNumber++; currentData_.systemEventData = {}; currentData_.eventIndex = eventIndex; currentData_.moduleData.clear(); std::copy( moduleDataList, moduleDataList+moduleCount, std::back_inserter(currentData_.moduleData)); sync_.ready = true; sync_.processed = false; guard.unlock(); sync_.cv.notify_one(); }; parserCallbacks_.systemEvent = [this] ( const u32 *header, u32 size) { std::unique_lock<std::mutex> guard(sync_.m); sync_.cv.wait(guard, [this] () { return sync_.processed; }); currentData_.type = EventData::SystemEvent; currentData_.linearEventNumber++; currentData_.systemEventData = { header, size }; currentData_.eventIndex = -1; currentData_.moduleData.clear(); sync_.ready = true; sync_.processed = false; guard.unlock(); sync_.cv.notify_one(); }; parserState_ = readout_parser::make_readout_parser(crateConfig_.stacks); parserThread_ = std::thread( readout_parser::run_readout_parser, std::ref(parserState_), std::ref(parserCounters_), std::ref(snoopQueues_), std::ref(parserCallbacks_)); // reader/replayWorker replayWorker_ = std::make_unique<ReplayWorker>(snoopQueues_, rh_); auto fRunning = replayWorker_->start(); fRunning.get(); // monitor monitorThread_ = std::thread(&Handle::monitor, this); } EventData *readNextEvent() { // Unblock the callbacks and let the parser thread fill // currentData_ with the next event. { std::unique_lock<std::mutex> guard(sync_.m); sync_.ready = false; sync_.processed = true; guard.unlock(); sync_.cv.notify_one(); } // Wait for the parser to be done. std::unique_lock<std::mutex> guard(sync_.m); while (!sync_.cv.wait_for( guard, std::chrono::milliseconds(100), [this] () { return sync_.ready || replayDone_; })); if (sync_.ready) { assert(!sync_.processed); return &currentData_; } return nullptr; } ~Handle() { replayWorker_->stop(); if (monitorThread_.joinable()) monitorThread_.join(); assert(!parserThread_.joinable()); // should not happen if (parserThread_.joinable()) parserThread_.join(); } }; std::unique_ptr<Handle> open_listfile(const std::string &filename) { auto ret = std::make_unique<Handle>(filename); return ret; } EventData *read_next_event(Handle &handle) { return handle.readNextEvent(); } EventData *read_next_event(std::unique_ptr<Handle> &handle) { return read_next_event(*handle); } int main(int argc, char *argv[]) { if (argc < 2) return 1; if (auto handle = open_listfile(argv[1])) { size_t expectedEventNumber = 1u; size_t systemEvents = 0u; size_t readoutEvents = 0u; while (auto data = read_next_event(handle)) { //if (data->type == EventData::SystemEvent) // cout << "SystemEvent "; //else if (data->type == EventData::ReadoutEvent) // cout << "ReadoutEvent "; //cout << data->linearEventNumber << "\n"; if (data->type == EventData::SystemEvent) ++systemEvents; else if (data->type == EventData::ReadoutEvent) ++readoutEvents; assert(data->linearEventNumber == expectedEventNumber); ++expectedEventNumber; } cout << "Read " << expectedEventNumber - 1 << " events" << "\n"; cout << "systemEvents: " << systemEvents << ", readoutEvents: " << readoutEvents << "\n"; } return 0; }
/* * Copyright © 2019 <NAME>. */ package grpc import ( "context" "github.com/golang/protobuf/proto" "github.com/hedzr/voxr-api/api/v10" ) func (s *ImCoreService) SearchGlobalX(ctx context.Context, req proto.Message) (res proto.Message, err error) { return s.SearchGlobal(ctx, req.(*v10.SearchGlobalReq)) } func (s *ImCoreService) SearchGlobal(ctx context.Context, req *v10.SearchGlobalReq) (res *v10.SearchGlobalReply, err error) { return }
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { setError } from '~/actions/errors'; import { default as toggleSelected } from '~/actions/select'; import { showModal, hideModal } from '~/actions/modal'; import { nodebalancers as api } from '~/api'; import { setSource } from '~/actions/source'; import { setTitle } from '~/actions/title'; import { DeleteModalBody } from 'linode-components/modals'; import CreateHelper from '~/components/CreateHelper'; import { List } from 'linode-components/lists'; import { Table } from 'linode-components/tables'; import { ListBody } from 'linode-components/lists/bodies'; import { ListHeader } from 'linode-components/lists/headers'; import { ButtonCell, CheckboxCell, LinkCell, } from 'linode-components/tables/cells'; import { RegionCell, IPAddressCell, } from '~/components/tables/cells'; import { MassEditControl } from 'linode-components/lists/controls'; const OBJECT_TYPE = 'nodebalancers'; export class IndexPage extends Component { static async preload({ dispatch }) { try { await dispatch(api.all()); } catch (response) { // eslint-disable-next-line no-console console.error(response); dispatch(setError(response)); } } constructor(props) { super(props); this.deleteNodeBalancers = this.deleteNodeBalancers.bind(this); } async componentDidMount() { const { dispatch } = this.props; dispatch(setSource(__filename)); dispatch(setTitle('NodeBalancers')); } deleteNodeBalancers(nodebalancers) { const { dispatch } = this.props; const nodebalancersArr = Array.isArray(nodebalancers) ? nodebalancers : [nodebalancers]; dispatch(showModal('Delete NodeBalancer(s)', <DeleteModalBody onOk={async () => { const ids = nodebalancersArr.map(function (nodebalancer) { return nodebalancer.id; }); await Promise.all(ids.map(id => dispatch(api.delete(id)))); dispatch(toggleSelected(OBJECT_TYPE, ids)); dispatch(hideModal()); }} onCancel={() => dispatch(hideModal())} items={nodebalancersArr.map(n => n.label)} typeOfItem="NodeBalancers" /> )); } render() { const { dispatch, nodebalancers, selectedMap } = this.props; // TODO: add sort function in config definition const data = Object.values(nodebalancers.nodebalancers); // TODO: add mass edit controls to nodebalancers const renderNodeBalancers = (data) => ( <List> <ListHeader> <div className="pull-sm-left"> <MassEditControl data={data} dispatch={dispatch} massEditOptions={[ { name: 'Delete', action: this.deleteNodeBalancers }, ]} selectedMap={selectedMap} objectType={OBJECT_TYPE} toggleSelected={toggleSelected} /> </div> </ListHeader> <ListBody> <Table columns={[ { cellComponent: CheckboxCell, headerClassName: 'CheckboxColumn' }, { className: 'RowLabelCell', cellComponent: LinkCell, hrefFn: (nodebalancer) => { return `/nodebalancers/${nodebalancer.label}`; }, }, { cellComponent: IPAddressCell, headerClassName: 'IPAddressColumn' }, { cellComponent: RegionCell }, { cellComponent: ButtonCell, headerClassName: 'ButtonColumn', onClick: (nodebalancer) => { this.deleteNodeBalancers(nodebalancer); }, text: 'Delete', }, ]} data={data} selectedMap={selectedMap} disableHeader onToggleSelect={(record) => { dispatch(toggleSelected(OBJECT_TYPE, record.id)); }} /> </ListBody> </List> ); return ( <div className="PrimaryPage container"> <header className="PrimaryPage-header"> <div className="PrimaryPage-headerRow clearfix"> <h1 className="float-sm-left">NodeBalancers</h1> <Link to="/nodebalancers/create" className="linode-add btn btn-primary float-sm-right"> <span className="fa fa-plus"></span> Add a NodeBalancer </Link> </div> </header> <div className="PrimaryPage-body"> {data.length ? renderNodeBalancers(data) : ( <CreateHelper label="NodeBalancers" href="/nodebalancers/create" linkText="Add a NodeBalancer" /> )} </div> </div> ); } } IndexPage.propTypes = { dispatch: PropTypes.func, nodebalancers: PropTypes.object, selectedMap: PropTypes.object.isRequired, }; function select(state) { return { nodebalancers: state.api.nodebalancers, selectedMap: state.select.selected[OBJECT_TYPE] || {}, }; } export default connect(select)(IndexPage);
export SECRET_KEY='secretkey123' export MAIL_USERNAME='adinomuruthi1@gmail.com' export MAIL_PASSWORD='Wiseman1995' python3 manage.py server
Eigen::MatrixXd computeNumericalJacobian(const Eigen::VectorXd& params, const double step, const Eigen::VectorXd& error, const Eigen::MatrixXd& T_OL, const ResidualFunction& residual) { Eigen::MatrixXd T_OL_jacobian_numeric(error.size(), params.size()); for (int i = 0; i < params.size(); ++i) { Eigen::VectorXd perturb = Eigen::VectorXd::Zero(params.size()); perturb(i) = step; Eigen::MatrixXd perturbed_error; residual.Evaluate(params + perturb, perturbed_error.data(), nullptr); T_OL.manifoldPlus(perturb); T_OL_jacobian_numeric.col(i) = (perturbed_error - error) / step; } return T_OL_jacobian_numeric; }
dotnet new mauilib -o ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat -n Xamarin.CommunityToolkit.MauiCompat dotnet new mauilib -o ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat -n Xamarin.CommunityToolkit.Markup.MauiCompat dotnet new sln -o ./src/CommunityToolkit/ -n Xamarin.CommunityToolkit.MauiCompat dotnet sln ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat.sln add ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/Xamarin.CommunityToolkit.MauiCompat.csproj dotnet new sln -o ./src/Markup/ -n Xamarin.CommunityToolkit.Markup.MauiCompat dotnet sln ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat.sln add ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/Xamarin.CommunityToolkit.Markup.MauiCompat.csproj sed -i '' 's/;net6.0-maccatalyst//g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/Xamarin.CommunityToolkit.MauiCompat.csproj sed -i '' 's/;net6.0-maccatalyst//g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/**/Xamarin.CommunityToolkit.Markup.MauiCompat.csproj printf > ./src/CommunityToolkit/Directory.build.props "<Project> <PropertyGroup> <Nullable>enable</Nullable> <PackageId>Xamarin.CommunityToolkit.MauiCompat</PackageId> <Summary>A .NET MAUI Comapatible version of Xamarin.CommunityToolkit, a community-created toolkit with common Xamarin converters, effects, behaviors etc.</Summary> <PackageTag>maui,net,xamarin,ios,android,uwp,xamarin.forms,effects,controls,converters,animations,toolkit,kit,communitytoolkit,xamarincommunitytoolkit,watchos,tvos,tizen,Microsoft.Toolkit.Xamarin.Forms</PackageTag> <Title>Xamarin.CommunityToolkit.MauiCompat</Title> <Description>Xamarin.CommunityToolkit.MauiCompat is a collection of Animations, Behaviors, Converters, and Effects for mobile development with .NET MAUI. It is the .NET MAUI Compatible version of Xamarin.CommunityToolkit.</Description> <PackageIcon>icon.png</PackageIcon> <PackageVersion>\$(Version)\$(VersionSuffix)</PackageVersion> <Authors>Microsoft</Authors> <Owners>microsoft</Owners> <NeutralLanguage>en</NeutralLanguage> <Copyright>© Microsoft Corporation. All rights reserved.</Copyright> <RepositoryUrl>https://github.com/xamarin/XamarinCommunityToolkit</RepositoryUrl> <PackageReleaseNotes>See: http://aka.ms/xct-release-notes</PackageReleaseNotes> <DefineConstants>\$(DefineConstants);</DefineConstants> <UseFullSemVerForNuGet>false</UseFullSemVerForNuGet> <PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <PackageProjectUrl>https://github.com/xamarin/XamarinCommunityToolkit</PackageProjectUrl> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <Version>1.3.0-pre4</Version> </PropertyGroup> <ItemGroup> <Compile Include=\"**/*.shared.cs\" /> <Compile Include=\"**/*.shared.*.cs\" /> <None Include=\"../../../LICENSE\" PackagePath=\"\" Pack=\"true\" /> <None Include=\"../../../assets/XamarinCommunityToolkit_128x128.png\" PackagePath=\"icon.png\" Pack=\"true\" /> </ItemGroup> <ItemGroup Condition=\" \$(TargetFramework.Contains(-android)) \"> <Compile Include=\"**\*.android.cs\" /> <Compile Include=\"**\*.android.*.cs\" /> <AndroidResource Include=\"Resources\**\*.axml\" /> <AndroidResource Include=\"Resources\**\*.xml\" /> <AndroidResource Include=\"Resources\**\*.png\" /> </ItemGroup> <ItemGroup Condition=\" \$(TargetFramework.Contains(-ios)) \"> <Compile Include=\"**\*.ios.cs\" /> <Compile Include=\"**\*.ios.*.cs\" /> </ItemGroup> <ItemGroup Condition=\" \$(TargetFramework.Contains('-windows')) \"> <Compile Include=\"**\*.uwp.cs\" /> <Compile Include=\"**\*.uwp.*.cs\" /> </ItemGroup> <ItemGroup Condition=\" \$(TargetFramework.Contains('-maccatalyst')) \"> <Compile Include=\"**\*.macos.cs\" /> <Compile Include=\"**\*.macos.*.cs\" /> </ItemGroup> <ItemGroup Condition=\" !\$(TargetFramework.Contains('-')) \"> <Compile Include=\"**\*.netstandard.cs\" /> <Compile Include=\"**\*.netstandard.*.cs\" /> </ItemGroup> <PropertyGroup Condition=\" !\$(TargetFramework.Contains('-')) \"> <DefineConstants>\$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> </Project>" printf > ./src/Markup/Directory.build.props "<Project> <PropertyGroup> <Nullable>enable</Nullable> <PackageId>Xamarin.CommunityToolkit.Markup.MauiCompat</PackageId> <Summary>A .NET MAUI-compatible community-created toolkit with C# Markup classes and fluent helper methods</Summary> <Authors>Microsoft</Authors> <Owners>Microsoft</Owners> <NeutralLanguage>en</NeutralLanguage> <Copyright>© Microsoft Corporation. All rights reserved.</Copyright> <PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageProjectUrl>https://github.com/xamarin/XamarinCommunityToolkit</PackageProjectUrl> <RepositoryUrl>https://github.com/xamarin/XamarinCommunityToolkit</RepositoryUrl> <PackageReleaseNotes>See: http://aka.ms/xct-release-notes</PackageReleaseNotes> <DefineConstants>\$(DefineConstants);</DefineConstants> <UseFullSemVerForNuGet>false</UseFullSemVerForNuGet> <Title>Xamarin.CommunityToolkit.Markup.MauiCompat</Title> <Description>Xamarin Community Toolkit Markup MauiCompat is a set of fluent helper methods and classes to simplify building declarative .NET MAUI user interfaces in C#</Description> <PackageIcon>icon.png</PackageIcon> <Product>\$(AssemblyName) (\$(TargetFramework))</Product> <PackageVersion>\$(Version)\$(VersionSuffix)</PackageVersion> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <Version>1.3.0-pre4</Version> <PackageTags>maui,net,xamarin,xamarin.forms,toolkit,kit,communitytoolkit,xamarincommunitytoolkit,markup,csharpformarkup,csharp,csharpmarkup</PackageTags> </PropertyGroup> <ItemGroup> <None Include=\"../../../LICENSE\" PackagePath=\"\" Pack=\"true\" /> <None Include=\"../../../assets/XamarinCommunityToolkit_128x128.png\" PackagePath=\"icon.png\" Pack=\"true\" /> </ItemGroup> </Project>" find ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/ -name "*" ! -name "*.csproj" -delete find ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/ -name "*" ! -name "*.csproj" -delete rsync -avr --exclude='*.csproj' --exclude='bin' --exclude='obj' ./src/CommunityToolkit/Xamarin.CommunityToolkit/ ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/ rsync -avr --exclude='*.csproj' --exclude='bin' --exclude='obj' ./src/Markup/Xamarin.CommunityToolkit.Markup/ ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/ # Preserve sed -i '' 's/\[Preserve(/\[Microsoft.Maui.Controls.Internals.Preserve(/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Internals sed -i '' 's/using Xamarin.Forms.Internals/using Microsoft.Maui.Controls.Internals/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' '/Forms.Internals.Log/d' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # WeakEventManager sed -i '' 's/ Forms.WeakEventManager/ Microsoft.Maui.Controls.WeakEventManager/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Forms.Image sed -i '' 's/Xamarin.Forms.Image/Microsoft.Maui.Controls.Image/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Forms.Image/Microsoft.Maui.Controls.Image/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Colors sed -i '' 's/ Forms\.Color\.Default/ default(Microsoft.Maui.Graphics.Color)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/Snackbar/**/**.cs sed -i '' 's/ Color\.Default\./ new Microsoft.Maui.Graphics.Color()./g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/Snackbar/**/SnackBarAppearance*.cs sed -i '' 's/ Color\.Default/ default(Microsoft.Maui.Graphics.Color)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/Snackbar/**/**.cs sed -i '' 's/ == Forms.Color.Default/ .Equals(new Microsoft.Maui.Graphics.Color())/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ == XColor.Default/ .Equals(new Microsoft.Maui.Graphics.Color())/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Color = Xamarin.Forms.Color;/using Color = Microsoft.Maui.Graphics.Color;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ Color\./ Colors./g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\tColor\./\tColors./g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Xamarin.Forms.Color/Microsoft.Maui.Graphics.Color/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ Forms\.Color/ Microsoft.Maui.Graphics.Color/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\tForms\.Color/\tMicrosoft.Maui.Graphics.Color/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Colors\.From/Color\.From/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Colors.Default/new Microsoft.Maui.Graphics.Color()/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ Color.FromRgba/ new Microsoft.Maui.Graphics.Color/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\tColor.FromRgba/\tnew Microsoft.Maui.Graphics.Color/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.R,/.Red,/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.G,/.Green,/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.B,/.Blue,/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.A,/.Alpha,/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.R /.Red /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.G /.Green /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.B /.Blue /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.A /.Alpha /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.R)/.Red)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.G)/.Green)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.B)/.Blue)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.A)/.Alpha)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.A:/.Alpha:/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/r.IsDefault)/r.IsDefault())/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/.MultiplyAlpha(/.MultiplyAlpha((float)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.Hue/.GetHue()/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.Saturation/.GetSaturation()/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.Luminosity/.GetLuminosity()/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Nullability sed -i '' 's/event EventHandler<VisualElementChangedEventArgs>? ElementChanged/event EventHandler<VisualElementChangedEventArgs> ElementChanged/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\.PropertyName\./.PropertyName?./g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/(object sender, PropertyChangedEventArgs e)/(object? sender, PropertyChangedEventArgs e)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # PlatformEffect sed -i '' 's/: Xamarin.Forms.Platform.iOS.PlatformEffect/: Microsoft.Maui.Controls.Platform.PlatformEffect/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/: PlatformEffect/: Microsoft.Maui.Controls.Platform.PlatformEffect/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Platforms sed -i '' 's/if MONOANDROID10_0/if ANDROID/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/if MONOANDROID/if ANDROID/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/if !MONOANDROID/if ANDROID/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/if __ANDROID_29__/if ANDROID/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms.Platform.Android.FastRenderers;/using Microsoft.Maui.Controls.Compatibility.Platform.Android.FastRenderers;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms.Platform.Android;/using Microsoft.Maui.Controls.Compatibility.Platform.Android; using Microsoft.Maui.Controls.Platform;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms.Platform.iOS/using Microsoft.Maui.Controls.Compatibility.Platform.iOS/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms.Platform.GTK/using Microsoft.Maui.Controls.Compatibility.Platform.GTK/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms.Platform.Tizen/using Microsoft.Maui.Controls.Compatibility.Platform.Tizen/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms.Platform.UWP/using Microsoft.Maui.Controls.Compatibility.Platform.UWP/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms.Platform.MacOS/using Microsoft.Maui.Controls.Compatibility.Platform.MacOS/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Xamarin.Forms.PlatformConfiguration/Microsoft.Maui.Controls.PlatformConfiguration/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Xamarin.Forms.Platform/Microsoft.Maui.Controls.Compatibility.Platform/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # IVisualElementRenderer sed -i '' '/IVisualElementRenderer.ViewGroup/d' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/event EventHandler<VisualElementChangedEventArgs>/event EventHandler<Microsoft.Maui.Controls.Platform.VisualElementChangedEventArgs>/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/new VisualElementChangedEventArgs/new Microsoft.Maui.Controls.Platform.VisualElementChangedEventArgs/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/new ElementChangedEventArgs/new Microsoft.Maui.Controls.Platform.ElementChangedEventArgs/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/(ElementChangedEventArgs/(Microsoft.Maui.Controls.Platform.ElementChangedEventArgs/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # TextAlignment sed -i '' 's/Xamarin.Forms.TextAlignment/Microsoft.Maui.TextAlignment/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # ElementChangedEventArgs sed -i '' 's/override void OnElementChanged(ElementChangedEventArgs/override void OnElementChanged(Microsoft.Maui.Controls.Platform.ElementChangedEventArgs/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # XAML sed -i '' 's/using Xamarin.Forms.Xaml;/using Microsoft.Maui.Controls.Xaml;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Forms.Xaml/Microsoft.Maui.Controls.Xaml/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Effects sed -i '' 's/Xamarin.Forms.ExportEffect(/Microsoft.Maui.Controls.ExportEffect(/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs ## Font sed -i '' 's/Element.Font/Element.ToFont()/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs ## Internals sed -i '' 's/Element.Font/Element.ToFont()/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs #Forms.Internals.Log # TypeConverter sed -i '' 's/Xamarin.Forms.TypeConverter/System.ComponentModel.TypeConverter/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\[TypeConverter/\[System.ComponentModel.TypeConverter/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\[TypeConversion/\[System.ComponentModel.TypeConverter/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\[Microsoft.Maui.Controls.Xaml.TypeConversion/\[System.ComponentModel.TypeConverter/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\[Forms.TypeConverter/\[System.ComponentModel.TypeConverter/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ TypeConverter/ System.ComponentModel.TypeConverter/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Xamarin.Forms.UriTypeConverter/Microsoft.Maui.Controls.UriTypeConverter/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ConvertFromInvariantString(string value)/ConvertFrom(System.ComponentModel.ITypeDescriptorContext? context, System.Globalization.CultureInfo? culture, object valueObject)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ConvertFromInvariantString(string\? value)/ConvertFrom(System.ComponentModel.ITypeDescriptorContext? context, System.Globalization.CultureInfo? culture, object valueObject)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Font sed -i '' '/else if (e.PropertyName == Label.FontProperty.PropertyName)/,+1d' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Font.FontSize/Font.Size/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Controls sed -i '' 's/Xamarin.Forms.Page/Microsoft.Maui.Controls.Page/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Xamarin.Forms.View/Microsoft.Maui.Controls.View/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Forms.View/Microsoft.Maui.Controls.View/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Layouts sed -i '' 's/ Layout / Microsoft.Maui.Controls.Layout /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ Layout)/ Microsoft.Maui.Controls.Layout)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using static Xamarin.Forms.AbsoluteLayout/using static Microsoft.Maui.Controls.Compatibility.AbsoluteLayout;using Microsoft.Maui.Layouts;using AbsoluteLayout = Microsoft.Maui.Controls.Compatibility.AbsoluteLayout/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/StackLayout/\tMicrosoft.Maui.Controls.StackLayout/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ GridLength/ Microsoft.Maui.GridLength/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\tGridLength/\tMicrosoft.Maui.GridLength/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/(GridLength/(Microsoft.Maui.GridLength/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/<GridLength/<Microsoft.Maui.GridLength/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/ Grid/ Microsoft.Maui.Controls.Compatibility.Grid/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/\tGrid/\tMicrosoft.Maui.Controls.Compatibility.Grid/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/(Grid/(Microsoft.Maui.Controls.Compatibility.Grid/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/<Grid/<Microsoft.Maui.Controls.Compatibility.Grid/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # Graphics sed -i '' 's/Xamarin.Forms.Point/Microsoft.Maui.Graphics.Point/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Xamarin.Forms.Size/Microsoft.Maui.Graphics.Size/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/Xamarin.Forms.View/Microsoft.Maui.Controls.View/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # ViewExtensions sed -i '' 's/\tViewExtensions./\tMicrosoft.Maui.Controls.ViewExtensions./g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs # *.android.cs sed -i '' 's/ContainerView/Microsoft.Maui.Controls.Compatibility.Platform.Android.ContainerView/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' 's/View.Context.ToPixels(/Microsoft.Maui.ContextExtensions.ToPixels(View.Context ?? throw new NullReferenceException(), /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' 's/Context.ToPixels(/Microsoft.Maui.ContextExtensions.ToPixels(Context, /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' 's/context.ToPixels(/Microsoft.Maui.ContextExtensions.ToPixels(context, /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' 's/Resource.Id/Xamarin.CommunityToolkit.MauiCompat.Resource.Id/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' 's/Resource.Layout/Xamarin.CommunityToolkit.MauiCompat.Resource.Layout/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' '1s/^/using Path = Android.Graphics.Path;/' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' '1s/^/using Paint = Android.Graphics.Paint;/' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs sed -i '' 's/ShapeDrawable/global::Android.Graphics.Drawables.ShapeDrawable/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/*.android.cs # TextSwitcherRenderer.android.cs sed -i '' 's/(visualElementRenderer?.OnTouchEvent(e) ?? false) || //g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/TextSwitcherRenderer.android.cs sed -i '' 's/f.ToScaledPixel()/(float)f.Size/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/TextSwitcherRenderer.android.cs sed -i '' 's/children.ForEach(/Array.ForEach(children,/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/TextSwitcherRenderer.android.cs ## PlatformTouchEffect.ios.cs sed -i '' 's/(isStarted ? color : control.BackgroundColor).ToCGColor()/Microsoft.Maui.ColorExtensions.ToCGColor(isStarted ? color : control.BackgroundColor)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/PlatformTouchEffect.ios.cs ## DrawingViewRenderer.ios.cs sed -i '' 's/void OnLinesCollectionChanged(object sender/void OnLinesCollectionChanged(object? sender/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/DrawingViewRenderer.ios.cs sed -i '' 's/currentPoint.ToPoint()/CoreGraphicsExtensions.ToPoint(currentPoint)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/DrawingViewRenderer.ios.cs # DrawingViewService.ios.cs sed -i '' 's/backgroundColor.ToCGColor()/Microsoft.Maui.ColorExtensions.ToCGColor(backgroundColor)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/DrawingViewService.ios.cs sed -i '' 's/strokeColor.ToCGColor()/Microsoft.Maui.ColorExtensions.ToCGColor(strokeColor)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/DrawingViewService.ios.cs sed -i '' 's/line.LineColor.ToCGColor()/Microsoft.Maui.ColorExtensions.ToCGColor(line.LineColor)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/DrawingViewService.ios.cs # SnackbarAppearance.ios.cs sed -i '' '1s/^/using Microsoft.Maui;using Microsoft.Maui.Controls.Compatibility.Platform.iOS;using Microsoft.Maui.Graphics;/' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/SnackbarAppearance.ios.cs sed -i '' 's/Forms.Font/Microsoft.Maui.Font/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/SnackbarAppearance.ios.cs # Snackbar.android.cs sed -i '' 's/await GetRendererWithRetries(sender)/(await GetRendererWithRetries(sender))?.View ?? sender.ToNative(sender.Handler.MauiContext)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/SnackBar.android.cs sed -i '' 's/renderer.View/renderer/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/SnackBar.android.cs # VisualFeedbackEffectRouter.ios.cs sed -i '' 's/color.A /color.Alpha /g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/SnackbarAppearance.ios.cs # IconTintColorEffectRouter.android.cs sed -i '' 's/args.PropertyName?.Equals(IconTintColorEffect.TintColorProperty.PropertyName)/args.PropertyName?.Equals(IconTintColorEffect.TintColorProperty.PropertyName) is true/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.android.cs sed -i '' 's/args.PropertyName?.Equals(Microsoft.Maui.Controls.Image.SourceProperty.PropertyName)/args.PropertyName?.Equals(Microsoft.Maui.Controls.Image.SourceProperty.PropertyName) is true/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.android.cs sed -i '' 's/args.PropertyName?.Equals(Microsoft.Maui.Controls.ImageButton.SourceProperty.PropertyName)/args.PropertyName?.Equals(Microsoft.Maui.Controls.ImageButton.SourceProperty.PropertyName) is true/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.android.cs sed -i '' 's/SetImageViewTintColor(ImageView image, Color color)/SetImageViewTintColor(ImageView image, Microsoft.Maui.Graphics.Color color)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.android.cs sed -i '' 's/SetButtonTintColor(Button button, Color color)/SetButtonTintColor(Button button, Microsoft.Maui.Graphics.Color color)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.android.cs # IconTintColorEffectRouter.ios.cs sed -i '' 's/args.PropertyName?.Equals(IconTintColorEffect.TintColorProperty.PropertyName)/args.PropertyName?.Equals(IconTintColorEffect.TintColorProperty.PropertyName) is true/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.ios.cs sed -i '' 's/args.PropertyName?.Equals(Image.SourceProperty.PropertyName)/args.PropertyName?.Equals(Microsoft.Maui.Controls.Image.SourceProperty.PropertyName) is true/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.ios.cs sed -i '' 's/args.PropertyName?.Equals(ImageButton.SourceProperty.PropertyName)/args.PropertyName?.Equals(Microsoft.Maui.Controls.ImageButton.SourceProperty.PropertyName) is true/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/IconTintColorEffectRouter.ios.cs # SemanticEffectRouterBase.ios.cs sed -i '' 's/(T)Element.Effects.FirstOrDefault(e => e is T)/(T)Element.Effects.First(e => e is T);/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/SemanticEffectRouterBase.ios.cs # CameraViewRenderer.android.cs sed -i '' 's/visualElementRenderer?.OnTouchEvent(e) is true || //g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/CameraViewRenderer.android.cs sed -i '' 's/static void MeasureExactly(AView control, VisualElement? element, Context? context)/static void MeasureExactly(AView control, VisualElement? element, Context context)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/CameraViewRenderer.android.cs sed -i '' 's/Context.GetFragmentManager();/Microsoft.Maui.ContextExtensions.GetFragmentManager(Context ?? throw new NullReferenceException()) ?? throw new InvalidOperationException();/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/CameraViewRenderer.android.cs # VisualElementExtension.shared.cs sed -i '' 's/v,/(float)v,/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/VisualElementExtension.shared.cs sed -i '' 's/, v/, (float)v/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/VisualElementExtension.shared.cs # NativeSnackBar.ios.macos.cs sed -i '' 's/public SnackBarLayout Microsoft.Maui.Controls.Layout/public SnackBarLayout Layout/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/NativeSnackBar.ios.macos.cs # VisualFeedbackEffect.shared.cs sed -i '' 's/nativeColor.Alpha/nativeColor.A/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/VisualFeedbackEffect.shared.cs # VisualFeedbackEffectRouter.shared.cs sed -i '' 's/nativeColor.Alpha/nativeColor.A/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/VisualFeedbackEffectRouter.android.cs # PlatformShadowEffect.ios.macos.cs sed -i '' 's/ShadowEffect.GetColor(Element).ToCGColor()/Microsoft.Maui.ColorExtensions.ToCGColor(ShadowEffect.GetColor(Element))/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/PlatformShadowEffect.ios.macos.cs sed -i '' 's/using Xamarin.CommunityToolkit.Android.Effects;/using System;using Xamarin.CommunityToolkit.Android.Effects;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/PlatformShadowEffect.android.cs # PlatformTouchEffect.android.cs sed -i '' 's/ViewGroup? Group => Container ?? Control as ViewGroup;/ViewGroup? Group => (Container ?? Control) as ViewGroup;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/PlatformTouchEffect.android.cs sed -i '' 's/XColor.Transparent/Microsoft.Maui.Graphics.Colors.Transparent/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/PlatformTouchEffect.android.cs # ColorExtension.shared.cs sed -i '' 's/(double)/(float)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithRed(this Color baseColor, double newR)/WithRed(this Color baseColor, float newR)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithGreen(this Color baseColor, double newG)/WithGreen(this Color baseColor, float newG)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithBlue(this Color baseColor, double newB)/WithBlue(this Color baseColor, float newB)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithAlpha(this Color baseColor, double newA)/WithAlpha(this Color baseColor, float newA)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithCyan(this Color baseColor, double newC)/WithCyan(this Color baseColor, float newC)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithMagenta(this Color baseColor, double newM)/WithMagenta(this Color baseColor, float newM)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithYellow(this Color baseColor, double newY)/WithYellow(this Color baseColor, float newY)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/WithBlackKey(this Color baseColor, double newK)/WithBlackKey(this Color baseColor, float newK)/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/double GetPercentBlackKey/float GetPercentBlackKey/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/double GetPercentCyan/float GetPercentCyan/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/double GetPercentMagenta/float GetPercentMagenta/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs sed -i '' 's/double GetPercentYellow/float GetPercentYellow/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/ColorExtension.shared.cs # TouchEffect.shared.cs sed -i '' 's/OnLayoutChildAdded(layout, new ElementEventArgs(view));/OnLayoutChildAdded(layout, new ElementEventArgs((Element)view));/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/TouchEffect.shared.cs # GravatarImageExtension.shared.cs sed -i '' 's/using System;/using System;using Microsoft.Extensions.DependencyInjection;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/GravatarImageExtension.shared.cs # AvatarView.shared.cs sed -i '' 's/using System;/using System;using static Microsoft.Maui.Controls.Compatibility.AbsoluteLayout;using Microsoft.Maui.Layouts;using AbsoluteLayout = Microsoft.Maui.Controls.Compatibility.AbsoluteLayout;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/AvatarView.shared.cs sed -i '' 's/uriSource\.GetStreamAsync/((IStreamImageSource)uriSource).GetStreamAsync/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/AvatarView.shared.cs # MotionEventHelper.android.cs sed -i '' '/if (layout.CascadeInputTransparent)/,+1d' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/MotionEventHelper.android.cs # StateLayoutController.shared.cs sed -i '' 's/Microsoft.Maui.Controls.Grid/Microsoft.Maui.Controls.Compatibility.Grid/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/StateLayoutController.shared.cs # TabBadgeTemplate.shared.cs sed -i '' 's/Frame/Microsoft.Maui.Controls.Frame/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/TabBadgeTemplate.shared.cs # CameraFragment.android.cs sed -i '' 's/MauiCompat.Resource.Layout.CameraFragment/MauiCompat.Resource.Layout.camerafragment/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/CameraFragment.android.cs # Replace Xamarin.Forms Namespace sed -i '' 's/using Xamarin.Forms;/using Microsoft.Maui; using Microsoft.Maui.Controls; using Microsoft.Maui.Graphics; using Microsoft.Maui.Controls.Compatibility;/g' ./src/CommunityToolkit/Xamarin.CommunityToolkit.MauiCompat/**/**.cs sed -i '' 's/using Xamarin.Forms;/using Microsoft.Maui; using Microsoft.Maui.Controls; using Microsoft.Maui.Graphics; using Microsoft.Maui.Controls.Compatibility;/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/**/**.cs sed -i '' 's/using Microsoft.Maui.Controls.Compatibility;/using Microsoft.Maui.Controls.Compatibility;using Microsoft.Maui.Layouts;using FlexLayout = Microsoft.Maui.Controls.FlexLayout;/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/ViewInFlexLayoutExtensions.cs sed -i '' 's/Xamarin.Forms/Microsoft.Maui.Controls/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/ElementExtensions.cs sed -i '' 's/Xamarin.Forms.Rectangle/Microsoft.Maui.Graphics.Rectangle/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/RelativeLayout.cs sed -i '' 's/Xamarin.Forms.RelativeLayout/Microsoft.Maui.Controls.Compatibility.RelativeLayout/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/RelativeLayout.cs sed -i '' 's/Xamarin.Forms.View/Microsoft.Maui.Controls.View/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/RelativeLayout.cs sed -i '' 's/Xamarin.Forms.Constraint/Microsoft.Maui.Controls.Compatibility.Constraint/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/RelativeLayout.cs sed -i '' 's/using Microsoft.Maui.Controls.Compatibility;/using Microsoft.Maui.Controls.Compatibility;using Grid = Microsoft.Maui.Controls.Grid;/g' ./src/Markup/Xamarin.CommunityToolkit.Markup.MauiCompat/ViewInGridExtensions.cs
function mapEventToIcon(eventType) { switch (eventType) { case 'PushEvent': return 'md-git-commit'; case 'ForkEvent': return 'md-git-network'; case 'IssuesEvent': return 'md-alert'; case 'WatchEvent': return 'md-eye'; case 'PullRequestEvent': return 'md-git-pull-request'; default: return 'md-question'; // Default icon for unknown event types } }
<html> <head> <title>Live Preview</title> <script> function updatePreview() { document.getElementById('preview').innerHTML = document.getElementById('input').value; } </script> </head> <body> <textarea id="input" onkeyup="updatePreview()"></textarea> <div id="preview" style="background-color:lightgray; padding: 10px; height: 300px; overflow-y: auto;"></div> </body> </html>
public static void giveGift(String gift1, String gift2, String gift3) { System.out.println("You have received " + gift1 + ", " + gift2 + ", and " + gift3); }
<filename>.babelrc.js<gh_stars>1-10 const withTests = { presets: [ [ '@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3', targets: { node: 'current' } }, ], ], plugins: [ 'babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node', '@babel/plugin-transform-runtime', ], }; module.exports = { ignore: ['./lib/codemod/src/transforms/__testfixtures__'], presets: [ ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }], '@babel/preset-typescript', '@babel/preset-react', '@babel/preset-flow', ], plugins: [ [ '@babel/plugin-proposal-decorators', { legacy: true, }, ], ['@babel/plugin-proposal-class-properties', { loose: true }], '@babel/plugin-proposal-export-default-from', '@babel/plugin-syntax-dynamic-import', ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }], 'babel-plugin-macros', ['emotion', { sourceMap: true, autoLabel: true }], ], env: { test: withTests, }, overrides: [ { test: './examples/vue-kitchen-sink', presets: ['babel-preset-vue'], env: { test: withTests, }, }, { test: './examples/rax-kitchen-sink', presets: [ ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }], ['babel-preset-rax', { development: process.env.BABEL_ENV === 'development' }], ], }, { test: './lib', presets: [ ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }], '@babel/preset-react', ], plugins: [ ['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }], '@babel/plugin-proposal-export-default-from', '@babel/plugin-syntax-dynamic-import', ['@babel/plugin-proposal-class-properties', { loose: true }], 'babel-plugin-macros', ['emotion', { sourceMap: true, autoLabel: true }], '@babel/plugin-transform-react-constant-elements', 'babel-plugin-add-react-displayname', ], env: { test: withTests, }, }, { test: './app/react-native', presets: ['module:metro-react-native-babel-preset'], plugins: ['babel-plugin-macros', ['emotion', { sourceMap: true, autoLabel: true }]], }, { test: [ './lib/node-logger', './lib/codemod', './addons/storyshots', '**/src/server/**', '**/src/bin/**', ], presets: [ [ '@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', targets: { node: '8.11', }, corejs: '3', }, ], ], plugins: [ 'emotion', 'babel-plugin-macros', ['@babel/plugin-proposal-class-properties', { loose: true }], '@babel/plugin-proposal-object-rest-spread', '@babel/plugin-proposal-export-default-from', ], env: { test: withTests, }, }, ], };
#!/usr/bin/env bash ############################################################################### # Copyright (c) 2016-21, Lawrence Livermore National Security, LLC # and RAJA project contributors. See the RAJA/COPYRIGHT file for details. # # SPDX-License-Identifier: (BSD-3-Clause) ############################################################################### BUILD_SUFFIX=lc_blueos-clang-7.1.0 rm -rf build_${BUILD_SUFFIX} 2>/dev/null mkdir build_${BUILD_SUFFIX} && cd build_${BUILD_SUFFIX} module load cmake/3.14.5 cmake \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_CXX_COMPILER=/usr/tce/packages/clang/clang-7.1.0/bin/clang++ \ -C ../host-configs/lc-builds/blueos/clang_X.cmake \ -DENABLE_OPENMP=On \ -DCMAKE_INSTALL_PREFIX=../install_${BUILD_SUFFIX} \ "$@" \ ..
#!/bin/bash exec 2>&1 LC_ALL=C DB="$2" SED="s/rows inserted/.n_writeops_done/g;s/'//g" echo "insert into t1 values (0,0,0) insert into t1 values (1,1,2) insert into t1 values (2,1,2) insert into t1 values (2,1,2) insert into t1 values (3,1,2) insert into t1 values (3,1,2) insert into t1 values (3,1,2) insert into t1 values (4,1,2) insert into t1 values (4,1,2) insert into t1 values (4,1,2) insert into t1 values (4,1,2) insert into t1 values (5,1,2) insert into t1 values (5,1,2) insert into t1 values (5,1,2) insert into t1 values (5,1,2) insert into t1 values (5,1,2)" | cdb2sql -s ${CDB2_OPTIONS} $DB default - | sed "$SED"
#!/bin/bash EXE_FILE=$1 LIB_PROJ_ROOT=$2 XCLBIN_FILE=$3 echo "XCL_MODE=${XCL_EMULATION_MODE}" if [ "${XCL_EMULATION_MODE}" != "hw_emu" ] then cp $LIB_PROJ_ROOT/common/data/sample.txt . echo -e "\n\n----------Comparing files after Decompression---------\n" cmd1=$(diff sample.txt sample.txt.zst.orig) if [ $? -eq 0 ] then echo "files are the same" else echo "files are different" echo "$cmd1" fi fi
// バリデーション関連 errorMessage export class ErrorMessage { private _params: string[]; private _message: string[]; private _code: string; constructor(error) { this._params = error.params; this._message = error.messages; this._code = error.code; } params(separator: string = ", "): string { if(this._params == null) { return null; } return this._params.join(separator) } paramsArray(): string[] { return this._params } messagesArray(): string[] { return this._message } messages(separator: string = ", "): string { if(this._message == null) { return null; } return this._message.join(separator) } }
/* * GRAL: GRAphing Library for Java(R) * * (C) Copyright 2009-2012 <NAME> <dev[at]erichseifert.de>, * <NAME> <michael[at]erichseifert.de> * * This file is part of GRAL. * * GRAL is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GRAL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GRAL. If not, see <http://www.gnu.org/licenses/>. */ package de.erichseifert.gral.plots.points; import java.awt.Shape; import de.erichseifert.gral.graphics.Drawable; import de.erichseifert.gral.plots.settings.Key; import de.erichseifert.gral.plots.settings.SettingsStorage; /** * <p>An interface providing functions for rendering points in a plot. * It defines methods for:</p> * <ul> * <li>Retrieving the point of a certain row in a DataTable</li> * <li>Getting and setting the points color</li> * <li>Getting and setting the bounds of the points</li> * </ul> */ public interface PointRenderer extends SettingsStorage { /** Key for specifying the {@link java.awt.Shape} instance defining the form of the point. */ Key SHAPE = new Key("point"); //$NON-NLS-1$ /** Key for specifying an instance either of {@link de.erichseifert.gral.plots.colors.ColorMapper} or {@link java.awt.Paint} that will be used to paint the point shapes. */ Key COLOR = new Key("point.color"); //$NON-NLS-1$ /** Key for specifying a {@link Boolean} value whether the data value of a point is displayed or not. */ Key VALUE_DISPLAYED = new Key("point.value.displayed"); //$NON-NLS-1$ /** Key for specifying a {@link Integer} value for the index of the column that contains the displayed values. */ Key VALUE_COLUMN = new Key("point.value.column"); //$NON-NLS-1$ /** Key for specifying the {@link java.text.Format} instance to be used to format the displayed data values. */ Key VALUE_FORMAT = new Key("point.value.format"); //$NON-NLS-1$ /** Key for specifying a {@link de.erichseifert.gral.util.Location} value for the positioning of the data value relative to the data point. */ Key VALUE_LOCATION = new Key("point.value.location"); //$NON-NLS-1$ /** Key for specifying a {@link Number} value that positions the value horizontally. */ Key VALUE_ALIGNMENT_X = new Key("point.value.alignment.x"); //$NON-NLS-1$ /** Key for specifying a {@link Number} value that positions the value vertically. */ Key VALUE_ALIGNMENT_Y = new Key("point.value.alignment.y"); //$NON-NLS-1$ /** Key for specifying a {@link Number} value for setting the rotation of the value in degrees. */ Key VALUE_ROTATION = new Key("point.value.rotation"); //$NON-NLS-1$ /** Key for specifying a {@link Number} value for the distance of values to the point. The distance is specified relative to the font height. */ Key VALUE_DISTANCE = new Key("point.value.distance"); //$NON-NLS-1$ /** Key for specifying the {@link java.awt.Paint} instance to be used to paint the value. */ Key VALUE_COLOR = new Key("point.value.paint"); //$NON-NLS-1$ /** Key for specifying an instance either of {@link de.erichseifert.gral.plots.colors.ColorMapper} or {@link java.awt.Paint} that will be used to paint the value text. */ Key VALUE_FONT = new Key("point.value.font"); //$NON-NLS-1$ /** Key for specifying a {@link Boolean} value whether the error value is displayed. */ Key ERROR_DISPLAYED = new Key("point.error.displayed"); //$NON-NLS-1$ /** Key for specifying a {@link Integer} value for the index of the column that contains the upper error value. */ Key ERROR_COLUMN_TOP = new Key("point.error.columnTop"); //$NON-NLS-1$ /** Key for specifying a {@link Integer} value for the index of the column that contains the lower error value. */ Key ERROR_COLUMN_BOTTOM = new Key("point.error.columnBottom"); //$NON-NLS-1$ /** Key for specifying the {@link java.awt.Paint} instance to be used to paint the error bars. */ Key ERROR_COLOR = new Key("point.error.paint"); //$NON-NLS-1$ /** Key for specifying an instance either of {@link de.erichseifert.gral.plots.colors.ColorMapper} or {@link java.awt.Paint} that will be used to paint the error bars. */ Key ERROR_SHAPE = new Key("point.error.shape"); //$NON-NLS-1$ /** Key for specifying the {@link java.awt.Stroke} instance defining the error bars. */ Key ERROR_STROKE = new Key("point.error.stroke"); //$NON-NLS-1$ /** * Returns a {@code Shape} instance that can be used for further * calculations. * @param data Information on axes, renderers, and values. * @return Outline that describes the point's shape. */ Shape getPointShape(PointData data); /** * Returns the graphical representation to be drawn for the specified data * value. * @param data Information on axes, renderers, and values. * @param shape Outline that describes the point's shape. * @return Component that can be used to draw the point. */ Drawable getPoint(PointData data, Shape shape); }
<filename>osc/server_test.go package osc import ( "net" "sync" "testing" "time" "golang.org/x/net/context" ) func TestHandle(t *testing.T) { server, err := NewServer("localhost:6677") if err != nil { t.Errorf("unexpected error; %s", err) } if err := server.Handle("/address/test", func(msg *Message) {}); err != nil { t.Error("Expected that OSC address '/address/test' is valid") } } func TestHandleWithInvalidAddress(t *testing.T) { server, err := NewServer("localhost:6677") if err != nil { t.Errorf("unexpected error; %s", err) } if err := server.Handle("/address*/test", func(msg *Message) {}); err == nil { t.Error("Expected error with '/address*/test'") } } func TestMessageDispatching(t *testing.T) { finish := make(chan bool) start := make(chan bool) done := sync.WaitGroup{} done.Add(2) // Start the OSC server in a new go-routine go func() { conn, err := net.ListenPacket("udp", "localhost:6677") if err != nil { t.Fatal(err) } defer conn.Close() server, err := NewServer("localhost:6677") if err != nil { t.Fatal(err) } err = server.Handle("/address/test", func(msg *Message) { if len(msg.Arguments) != 1 { t.Error("Argument length should be 1 and is: " + string(len(msg.Arguments))) } if msg.Arguments[0].(int32) != 1122 { t.Error("Argument should be 1122 and is: " + string(msg.Arguments[0].(int32))) } // Stop OSC server conn.Close() finish <- true }) if err != nil { t.Error("Error adding message handler") } start <- true server.Serve(context.Background(), conn) }() go func() { timeout := time.After(5 * time.Second) select { case <-timeout: case <-start: time.Sleep(500 * time.Millisecond) client := NewClient("localhost", 6677) msg := NewMessage("/address/test") msg.Append(int32(1122)) client.Send(msg) } done.Done() select { case <-timeout: case <-finish: } done.Done() }() done.Wait() } func TestMessageReceiving(t *testing.T) { finish := make(chan bool) start := make(chan bool) done := sync.WaitGroup{} done.Add(2) // Start the server in a go-routine go func() { server := mockServer() c, err := net.ListenPacket("udp", "localhost:6677") if err != nil { t.Fatal(err) } defer c.Close() // Start the client start <- true packet, err := server.ReceivePacket(context.Background(), c) if err != nil { t.Error("Server error") return } if packet == nil { t.Error("nil packet") return } msg := packet.(*Message) if msg.CountArguments() != 2 { t.Errorf("Argument length should be 2 and is: %d\n", msg.CountArguments()) } if msg.Arguments[0].(int32) != 1122 { t.Error("Argument should be 1122 and is: " + string(msg.Arguments[0].(int32))) } if msg.Arguments[1].(int32) != 3344 { t.Error("Argument should be 3344 and is: " + string(msg.Arguments[1].(int32))) } c.Close() finish <- true }() go func() { timeout := time.After(5 * time.Second) select { case <-timeout: case <-start: client := NewClient("localhost", 6677) msg := NewMessage("/address/test") msg.Append(int32(1122)) msg.Append(int32(3344)) time.Sleep(500 * time.Millisecond) client.Send(msg) } done.Done() select { case <-timeout: case <-finish: } done.Done() }() done.Wait() } func TestReadTimeout(t *testing.T) { start := make(chan bool) wg := sync.WaitGroup{} wg.Add(2) go func() { defer wg.Done() select { case <-time.After(5 * time.Second): t.Fatal("timed out") case <-start: client := NewClient("localhost", 6677) msg := NewMessage("/address/test1") err := client.Send(msg) if err != nil { t.Fatal(err) } time.Sleep(150 * time.Millisecond) msg = NewMessage("/address/test2") err = client.Send(msg) if err != nil { t.Fatal(err) } } }() go func() { defer wg.Done() timeout := 100 * time.Millisecond server := mockServer() c, err := net.ListenPacket("udp", "localhost:6677") if err != nil { t.Fatal(err) } defer c.Close() start <- true ctx, _ := context.WithTimeout(context.Background(), timeout) p, err := server.ReceivePacket(ctx, c) if err != nil { t.Errorf("server error: %v", err) return } if got, want := p.(*Message).Address, "/address/test1"; got != want { t.Errorf("wrong address; got = %s, want = %s", got, want) return } // Second receive should time out since client is delayed 150 milliseconds ctx, _ = context.WithTimeout(context.Background(), timeout) if _, err = server.ReceivePacket(ctx, c); err == nil { t.Errorf("expected error") return } // Next receive should get it ctx, _ = context.WithTimeout(context.Background(), timeout) p, err = server.ReceivePacket(ctx, c) if err != nil { t.Errorf("server error: %v", err) return } if got, want := p.(*Message).Address, "/address/test2"; got != want { t.Errorf("wrong address; got = %s, want = %s", got, want) return } }() wg.Wait() } func mockServer() *Server { return &Server{Addr: "localhost"} }
<filename>src/utils/render/index.ts export * from './render'; export * from './is-newline';
import statistics def remove_outliers(data, stdev_cutoff_factor): if not data: return [] # Return an empty list for empty input data mean = statistics.mean(data) stdev = statistics.stdev(data) upper_threshold = mean + (stdev * stdev_cutoff_factor) lower_threshold = mean - (stdev * stdev_cutoff_factor) noOutlier_list = [x for x in data if x >= lower_threshold and x <= upper_threshold] return noOutlier_list
#!/usr/bin/env bash # Library of functions related to Bash Strings # # @author Michael Strache # Prevent this library from being sourced more than once [[ ${_GUARD_BFL_STRING:-} -eq 1 ]] && return 0 || declare -r _GUARD_BFL_STRING=1 # **************************************************************************** # # Dependencies # # **************************************************************************** # # **************************************************************************** # # Main # # **************************************************************************** # # Tests if STRING contains SUBSTRING # # @param String STRING The string to be tested # @param String SUBSTRING The string to check for # # @return Boolean true if SUBSTRING was found, otherwise false function String::contains() { local -r STRING="${1:-}"; shift local -r SUBSTRING="${1:-}"; shift [[ "${STRING}" == *"${SUBSTRING}"* ]] } # Escapes all special characters in STRING # # @param String STRING String to escape values in # # @return String STRING with escaped special characters function String::escape() { local -r STRING="${1:-}"; shift if [[ -z ${STRING} ]]; then echo '' return 0 fi printf -v var '%q\n' "${STRING}" echo "$var" } # Tests if STRING represents a floating point number # # @param String STRING The string to be tested # # @return Boolean true if STRING is a floating point number, otherwise false function String::is_float() { local -r STRING="${1:-}"; shift [[ ${STRING} =~ ^[-+]?[0-9]*[.,]?[0-9]+$ ]] } # Tests if STRING represents a hexadecimal number # # @param String STRING The string to be tested # # @return Boolean true if STRING is a hexadecimal number, otherwise false function String::is_hex_number() { local -r STRING="${1:-}"; shift [[ ${STRING} =~ ^[0-9a-fA-F]+$ ]] } # Tests if STRING represents an integer # # @param String STRING The string to be tested # # @return Boolean true if STRING is a integer number, otherwise false function String::is_integer() { local -r STRING="${1:-}"; shift [[ ${STRING} =~ ^[-+]?[0-9]+$ ]] } # Tests if STRING represents a natural number # # @param String STRING The string to be tested # # @return Boolean true if STRING is a natural number, otherwise false function String::is_natural_number() { local -r STRING="${1:-}"; shift [[ ${STRING} =~ ^[0-9]+$ ]] } # Tests if STRING represents a number of any kind # # @param String STRING The string to be tested # # @return Boolean true if STRING is a number, otherwise false function String::is_number() { local -r STRING="${1:-}"; shift String::is_natural_number "${STRING}" || String::is_integer "${STRING}" || String::is_float "${STRING}" } # Tests if STRING is a version string (e.g. 1.0.0 or 1.0.0-SNAPSHOT) # # @param String STRING The string to be tested # # @return Boolean true if STRING is a version string, otherwise false function String::is_version() { local -r STRING="${1:-}"; shift [[ ${STRING} =~ ^[[:digit:]]+(\.[[:digit:]]+){0,2}(-[[:alnum:]]+)?$ ]] } # Replaces each occurrence of TARGET in STRING with REPLACEMENT # # @param String STRING The string to be tested # @param String TARGET The sequence of char values to be replaced # @param String REPLACEMENT The replacement sequence of char values # # @return String STRING with TARGET being replaced function String::replace() { local -r STRING="${1:-}"; shift # Escaping special characters in TARGET and REPLACEMENT local -r TARGET="$( sed -e 's/[]\/$*.^|[]/\\&/g' <<<"${1:-}" )"; shift local -r REPLACEMENT="$( sed -e 's/[\/&]/\\&/g' <<<"${1:-}" )"; shift # Is true when either TARGET or REPLACEMENT are not specified (-> the call only has one or two parameters) if [[ -z ${REPLACEMENT} ]]; then echo "${STRING}" else sed "s/${TARGET}/${REPLACEMENT}/g" <<< "${STRING}" fi } # Returns the string representation of an array, containing all fragments of STRING splitted using REGEX # Example: String::split "foo--bar" "-+" -> "( foo bar )" # # @param String STRING The string to be splitted # @param String REGEX Delimiting regular expression # # @return String String representation of an array with the splitted STRING function String::split() { local -r STRING="${1:-}"; shift local -r REGEX="${1:-}"; shift if [[ -z ${REGEX} ]]; then echo "( ${STRING} )" return 0 fi # The MacOS version does not support the '-r' option but instead has the '-E' option doing the same if sed -r "s/-/ /" <<< "" &>/dev/null; then local -r SED_OPTION="-r" else local -r SED_OPTION="-E" fi echo "( $( sed ${SED_OPTION} "s/${REGEX}/ /g" <<< "${STRING}" ) )" } # Tests if STRING starts with PREFIX # # @param String STRING The string to be tested # @param String PREFIX The prefix # # @return Boolean true if STRING starts with PREFIX, otherwise false function String::starts_with() { local -r STRING="${1:-}"; shift local -r PREFIX="${1:-}"; shift [[ ${STRING} =~ ^${PREFIX}.* ]] } # Converts STRING to lower case # # @param String STRING The string to be converted # # @return String Lower case representation of STRING function String::to_lowercase() { local -r STRING="${1:-}"; shift echo "${STRING,,}" } # Converts STRING to upper case # # @param String STRING The string to be converted # # @return String Upper case representation of STRING function String::to_uppercase() { local -r STRING="${1:-}"; shift echo "${STRING^^}" }
const { NotImplementedError } = require('../extensions/index.js'); // const { Node } = require('../extensions/list-tree.js'); /** * Implement simple binary search tree according to task description * using Node from extensions */ module.exports = class BinarySearchTree { constructor(){ this.root1 = null; } root() { return this.root1; } add(data) { let newNode = new Node(data); if(this.root1 == null) { this.root1 = newNode; } else { this.insetNode(this.root1, newNode); } } insetNode(node,newNode) { if(node.data > newNode.data) { if(node.left == null) { node.left = newNode; } else { this.insetNode(node.left,newNode) } } else { if(node.right == null) { node.right = newNode; } else { this.insetNode(node.right,newNode); } } } has(data) { if(this.root1.data == data) { return true; } else{ return this.hasNode(this.root1,data) } } hasNode(node,data) { if(node.data > data) { if(node.left == null) { return false; } if(node.left.data == data) { return true; } else { return this.hasNode(node.left,data); } } else { if(node.right == null) { return false; } if(node.right.data == data) { return true; } else { return this.hasNode(node.right, data); } } } find(data) { if(this.root1.data == data) { return this.root1; } else { return this.nodeFind(this.root1,data); } } nodeFind(node,data) { if(node.data > data) { if(node.left == null) { return null; } if(node.left.data == data) { return node.left; } else { return this.nodeFind(node.left,data); } } else { if(node.right == null) { return null; } if(node.right.data == data) { return node.right; } else { return this.nodeFind(node.right, data); } } } remove(data) { this.root1 = this.removeNode(this.root1,data); } removeNode(node,data) { if(node == null) { return null; } else{ if(node.data > data) { node.left = this.removeNode(node.left, data); return node; } else { if(node.data < data) { node.right = this.removeNode(node.right, data); return node; } else { if(node.left == null && node.right == null) { node = null; return node; } if(node.left == null) { node = node.right; return node; } if(node.right == null) { node = node.left; return node; } let aux = this.findMinNode(node.right); node.data = aux.data; node.right = this.removeNode(node.right, aux.data); return node; } } } } findMinNode(node){ if(node.left == null) { return node; } else{ return this.findMinNode(node.left); } } min() { if(this.root1.data == null) { return null; } else { return this.findMin(this.root1); } } findMin(node) { if(node.left == null) { return node.data; } else { return this.findMin(node.left); } } max() { if(this.root1.data == null) { return null; } else { return this.findMax(this.root1); } } findMax(node) { if(node.right == null) { return node.data; } else{ return this.findMax(node.right); } } } class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } }
<gh_stars>1-10 /* TITLE Concatenate strings Chapter18Exercise5.cpp "<NAME>roustrup "C++ Programming: Principles and Practice."" COMMENT Objcective: Write a function, cat_dot(), that concatenated two strings with a dot in between. Input: - Output: - Author: <NAME> Date: 25.12.2015 */ #include <iostream> #include <string> std::string cat_dot (const std::string& s1, const std::string& s2, const std::string middle_char = ".") { return s1 + middle_char + s2; } int main () { try { std::string s1 = "Hristo"; std::string s2 = "Botev"; std::cout << cat_dot(s1, s2); } catch (std::exception& e) { std::cerr << e.what(); } catch (...) { std::cerr << "Unhandled exception\n"; } getchar(); }
<gh_stars>1-10 # frozen_string_literal: true require 'rails_helper' RSpec.describe OnboardingHeader::OnboardingHeader, type: :component do subject { render_inline(described_class.new(**params)) } let(:params) { { logo: '/onboarding/logo.png' } } it { should have_css('.OnboardingHeader') } end
<reponame>WlodzimierzKorza/small_eod from django.contrib import admin from .models import Key, Scope admin.register(Scope) admin.register(Key)
package com.symbel.orienteeringquiz.adapter; import android.content.DialogInterface; import android.os.Handler; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.SaveCallback; import com.symbel.orienteeringquiz.R; import com.symbel.orienteeringquiz.activity.ActivityQuizMixto; import com.symbel.orienteeringquiz.model.ImagenPerfil; import com.symbel.orienteeringquiz.model.Simbolo; import com.symbel.orienteeringquiz.model.Usuario; import com.symbel.orienteeringquiz.utils.BitManage; import com.symbel.orienteeringquiz.utils.Constants; import com.symbel.orienteeringquiz.utils.DialogManager; import com.symbel.orienteeringquiz.utils.SharedPreference; import com.symbel.orienteeringquiz.utils.Utilidades; import java.util.ArrayList; import java.util.List; public class AdapterQuizMixto extends RecyclerView.Adapter { private ArrayList<Simbolo> simbolosQuiz; private ActivityQuizMixto activity; private String textoPregunta; private int ronda, aciertos, currentPunt; private int numeroMaximoSimbolos = 98; public AdapterQuizMixto(ArrayList<Simbolo> simbolosQuiz, ActivityQuizMixto activity, String textoPregunta) { this.simbolosQuiz = simbolosQuiz; this.activity = activity; this.textoPregunta = textoPregunta; ronda = activity.getRonda(); aciertos = activity.getAciertos(); currentPunt = activity.getCurrentPunt(); } @Override public int getItemViewType(int position) { return 0; } // Create new views (invoked by the layout manager) @Override public AdapterQuizMixto.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View itemLayoutView; itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_quiz, parent, false); // create ViewHolder return new AdapterQuizMixto.ViewHolder(itemLayoutView); } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { // Get data from your itemsData at this position try { final AdapterQuizMixto.ViewHolder viewHolder = (AdapterQuizMixto.ViewHolder) holder; final Simbolo simbolo = simbolosQuiz.get(position); // Replace the contents of the view with that itemsData if (simbolo.getUrl() != null) { BitManage.loadBitmap(simbolo.getUrl(), viewHolder.ivSimbolo, activity); } else { viewHolder.ivSimbolo.setImageResource(R.drawable.baliza); } viewHolder.cvSimbolo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (simbolo.getDescripcionCorta().equalsIgnoreCase(textoPregunta)) { //ACIERTO viewHolder.ivSimbolo.setImageResource(R.drawable.check_ok); setDialogAcierto(simbolo.getDescripcionCorta()); } else { //ERROR viewHolder.ivSimbolo.setImageResource(R.drawable.check_ko); setDialogFallo(simbolo.getDescripcionCorta()); } } }); } catch (Exception e) { e.printStackTrace(); } } // Return the size of your itemsData (invoked by the layout manager) @Override public int getItemCount() { return simbolosQuiz.size(); } // inner class to hold a reference to each item of RecyclerView public static class ViewHolder extends RecyclerView.ViewHolder { public ImageView ivSimbolo; public CardView cvSimbolo; public ViewHolder(View itemLayoutView) { super(itemLayoutView); try { ivSimbolo = (ImageView) itemLayoutView.findViewById(R.id.ivSimbolo); cvSimbolo = (CardView) itemLayoutView.findViewById(R.id.cvSimbolo); } catch (Exception e) { e.printStackTrace(); } } } private void setDialogAcierto(String descripcionCorta) { //ACTUALIZAMOS EL JUEGO updateJuego(); DialogInterface.OnDismissListener dismissDialog = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { //CADA X RONDAS, UN SIMBOLO MAS int cantidad = activity.getSYMBOLSTOGET(); if (esMultiplo(aciertos) && cantidad <= numeroMaximoSimbolos) { cantidad++; activity.setSYMBOLSTOGET(cantidad); } activity.nuevoJuego(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { // Actions to do after 2 seconds DialogManager.dismiss(); } }, 2000); } }; String message = activity.getString(R.string.has_acertado, descripcionCorta); DialogManager.dialogShow(activity, dismissDialog, message, R.drawable.check_ok); /*DialogInterface.OnClickListener positiveClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //CADA X RONDAS, UN SIMBOLO MAS int cantidad = activity.getSYMBOLSTOGET(); if (esMultiplo(aciertos) && cantidad <= numeroMaximoSimbolos) { cantidad++; activity.setSYMBOLSTOGET(cantidad); } activity.nuevoJuego(); DialogManager.dismiss(); } }; String positiveMessage = activity.getString(R.string.continuar); String title = activity.getString(R.string.felicidades); String message = activity.getString(R.string.has_acertado, descripcionCorta); DialogManager.dialogAccept(activity, title, message, positiveClick, positiveMessage, R.drawable.check_ok);*/ } private void updateJuego() { aciertos++; currentPunt = currentPunt + ronda; ronda++; activity.setAciertos(aciertos); activity.setRonda(ronda); activity.setCurrentPunt(currentPunt); } private void setDialogFallo(String descripcionCorta) { setFallo(); DialogInterface.OnClickListener positiveClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { DialogManager.dismiss(); activity.onBackPressed(); } }; String positiveMessage = activity.getString(R.string.dialog_aceptar); String title = activity.getString(R.string.fin_juego); String message = activity.getString(R.string.has_fallado, descripcionCorta); DialogManager.dialogAccept(activity, title, message, positiveClick, positiveMessage, R.drawable.check_ko); } private void setFallo() { //AL FALLAR ACTUALIZAMOS SU CLASIFICACION O LA CREAMOS Usuario user = SharedPreference.loadUsuario(); final String username = user.getUsername(); final String club = user.getClub(); ParseQuery<ParseObject> query = ParseQuery.getQuery(Constants.CLASIFICACION); query.whereEqualTo("nombreUsuario", username); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> objects, ParseException e) { try { if (e == null) { if (objects.size() > 0) { //SI TIENE CLASIFICACION Y SU PUNTUACION ES MAYOR A LA ACTUAL, LA ACTUALIZAMOS ParseObject object = objects.get(0); if (object.getInt("puntuacion") < currentPunt) { object.put("puntuacion", currentPunt); object.saveInBackground(); updateSharedPreference(); } }else { //SI NO TIENE, LA CREAMOS createClasificacion(username, club); } }else { Utilidades.showSnackbar(activity.getCurrentFocus(), e.getMessage()); } } catch (Exception f) { f.printStackTrace(); } } }); } private void createClasificacion(String username, String club) { ParseObject clasificacion = new ParseObject(Constants.CLASIFICACION); clasificacion.put("nombreUsuario", username); clasificacion.put("club", club); clasificacion.put("puntuacion", currentPunt); clasificacion.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { //GUARDAMOS EN LOCAL LA NUEVA CLASIFICAION ImagenPerfil imagenPerfil = SharedPreference.loadImagenPerfil(); SharedPreference.removeImagenPerfil(); imagenPerfil.setPuntuacion(currentPunt); SharedPreference.saveImagenPerfil(imagenPerfil); } }); } private void updateSharedPreference() { try { ImagenPerfil imagenPerfil = SharedPreference.loadImagenPerfil(); SharedPreference.removeImagenPerfil(); imagenPerfil.setPuntuacion(currentPunt); SharedPreference.saveImagenPerfil(imagenPerfil); } catch (Exception e) { e.printStackTrace(); } } public static boolean esMultiplo(int numero) { if (numero % 3 == 0) { return true; } else { return false; } } }
<reponame>vidalvasconcelos/minha-receita package transform import ( "fmt" "io" ) type sourceType string const ( venues sourceType = "ESTABELE" motives = "MOTICSV" main = "EMPRECSV" cities = "MUNICCSV" cnaes = "CNAECSV" countries = "PAISCSV" natures = "NATJUCSV" partners = "SOCIOCSV" qualifications = "QUALSCSV" simple = "SIMPLES" ) type lineCount struct { total int64 err error } type source struct { dir string files []string readers []*archivedCSV totalLines int64 } func (s *source) createReaders() error { var as []*archivedCSV for _, p := range s.files { r, err := newArchivedCSV(p, separator) if err != nil { return fmt.Errorf("error reading %s: %w", p, err) } as = append(as, r) } s.readers = as return nil } func (s *source) close() error { for _, r := range s.readers { if err := r.close(); err != nil { return fmt.Errorf("error closing %s: %w", r.path, err) } } return nil } func (s *source) resetReaders() error { if err := s.close(); err != nil { return fmt.Errorf("error closing readers: %w", err) } if err := s.createReaders(); err != nil { return fmt.Errorf("error creating readers: %w", err) } return nil } func (s *source) countLinesFor(a *archivedCSV, q chan<- lineCount) { var t int64 for { _, err := a.read() if err == io.EOF { break } if err != nil { q <- lineCount{0, err} return } t++ } q <- lineCount{t, nil} } func (s *source) countLines() error { q := make(chan lineCount) for _, r := range s.readers { go s.countLinesFor(r, q) } for range s.readers { r := <-q if r.err != nil { return fmt.Errorf("error counting lines: %w", r.err) } s.totalLines += r.total } close(q) s.resetReaders() return nil } func newSource(t sourceType, d string) (*source, error) { ls, err := PathsForSource(t, d) if err != nil { return nil, fmt.Errorf("error getting files for %s in %s: %w", string(t), d, err) } s := source{dir: d, files: ls} s.createReaders() s.countLines() return &s, nil }
<gh_stars>0 import sublime import sublime_plugin import os import re import subprocess import json BOOLEAN_MAP = {'true': True, 'false': False, '1': True, '0': False} class ExampleCommand(sublime_plugin.EventListener): """ Plugin for controlled scss autocompilation Usage: In your main scss file you simple add: // out: <filepath> // sourcemap: <true | false> // compress: <true | false> <filepath> may be relative In the including files you need to simply add: // main: ../path/to/main.scss This would trigger that file every time you'd be saving the including one """ @staticmethod def _parse_parameter_value(value): """ Checks if value in available data of boolean representation """ if value in BOOLEAN_MAP: return BOOLEAN_MAP[value] return value def on_post_save(self, view): if view.file_name().split('.')[-1].lower() == 'scss': regions_of_keywords = view.find_all( r"(out|sourcemap|compress|main):\s(.+css|.+scss|true|false)", sublime.IGNORECASE ) parameters = {} for region in regions_of_keywords: text = view.substr(region) parameters.update( {text.split(':')[0].strip(): self._parse_parameter_value(text.split(':')[1].strip())} ) print(parameters) if parameters: main_file = None if 'main' in parameters: main_file = os.path.join( os.path.dirname(view.file_name()), parameters['main'] ) parameters = self._get_parameters_from_main_file( file_name=os.path.join( os.path.dirname(view.file_name()), parameters['main'] ) ) self._compile( main_file or view.file_name(), **parameters ) def _get_parameters_from_main_file(self, file_name): """ Reads the main file to parse parameters from there Args: file_name: absolute path to main file Returns: parameter dict """ if os.path.exists(file_name): with open(file_name, 'r') as f: main_file_content = f.read() match = re.findall( r"(out|sourcemap|compress|main):\s(.+css|.+less|true|false)", main_file_content ) if match: return dict( zip( [m[0] for m in match], [self._parse_parameter_value(m[1]) for m in match] ) ) return {} def _compile(self, file_name, out, compress=False, sourcemap=False): """ SCSS compilation itself. It calls system `node-sass-chokidar` command that should be available after `npm install -g node-sass-chokidar` and the it should be added to the path """ print('compile scss') destination = os.path.join( os.path.dirname(file_name), out ) env = os.environ.copy() if sublime.platform() == 'osx': env['PATH'] += ':/usr/local/bin' elif sublime.platform() == 'windows': env['PATH'] += ';%s\AppData\Roaming\\npm' % os.path.expanduser("~") else: env['PATH'] += ':/usr/bin' compile_command = [ "node-sass-chokidar", str(file_name), str(destination), '--output-style=compressed' if compress else '', '--source-map=true' if sourcemap else '', ] print( " ".join(compile_command) ) proc = subprocess.Popen( compile_command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True if sublime.platform() == 'windows' else False ) out, err = proc.communicate() if err: error = err.decode('utf-8') error = json.loads(error) formatted = re.sub("(\[\d+m)","", error['message']) sublime.error_message(formatted)
#!/usr/bin/env zsh function omz { [[ $# -gt 0 ]] || { _omz::help return 1 } local command="$1" shift # Subcommand functions start with _ so that they don't # appear as completion entries when looking for `omz` (( $+functions[_omz::$command] )) || { _omz::help return 1 } _omz::$command "$@" } function _omz { local -a cmds subcmds cmds=( 'changelog:Print the changelog' 'help:Usage information' 'plugin:Manage plugins' 'pr:Manage Oh My Zsh Pull Requests' 'theme:Manage themes' 'update:Update Oh My Zsh' ) if (( CURRENT == 2 )); then _describe 'command' cmds elif (( CURRENT == 3 )); then case "$words[2]" in changelog) local -a refs refs=("${(@f)$(command git for-each-ref --format="%(refname:short):%(subject)" refs/heads refs/tags)}") _describe 'command' refs ;; plugin) subcmds=('info:Get plugin information' 'list:List plugins') _describe 'command' subcmds ;; pr) subcmds=('test:Test a Pull Request' 'clean:Delete all Pull Request branches') _describe 'command' subcmds ;; theme) subcmds=('use:Load a theme' 'list:List themes') _describe 'command' subcmds ;; esac elif (( CURRENT == 4 )); then case "$words[2]::$words[3]" in plugin::info) compadd "$ZSH"/plugins/*/README.md(.N:h:t) \ "$ZSH_CUSTOM"/plugins/*/README.md(.N:h:t) ;; theme::use) compadd "$ZSH"/themes/*.zsh-theme(.N:t:r) \ "$ZSH_CUSTOM"/**/*.zsh-theme(.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::) ;; esac fi return 0 } compdef _omz omz ## Utility functions function _omz::confirm { # If question supplied, ask it before reading the answer # NOTE: uses the logname of the caller function if [[ -n "$1" ]]; then _omz::log prompt "$1" "${${functrace[1]#_}%:*}" fi # Read one character read -r -k 1 # If no newline entered, add a newline if [[ "$REPLY" != $'\n' ]]; then echo fi } function _omz::log { # if promptsubst is set, a message with `` or $() # will be run even if quoted due to `print -P` setopt localoptions nopromptsubst # $1 = info|warn|error|debug # $2 = text # $3 = (optional) name of the logger local logtype=$1 local logname=${3:-${${functrace[1]#_}%:*}} # Don't print anything if debug is not active if [[ $logtype = debug && -z $_OMZ_DEBUG ]]; then return fi # Choose coloring based on log type case "$logtype" in prompt) print -Pn "%S%F{blue}$logname%f%s: $2" ;; debug) print -P "%F{white}$logname%f: $2" ;; info) print -P "%F{green}$logname%f: $2" ;; warn) print -P "%S%F{yellow}$logname%f%s: $2" ;; error) print -P "%S%F{red}$logname%f%s: $2" ;; esac >&2 } ## User-facing commands function _omz::help { cat <<EOF Usage: omz <command> [options] Available commands: help Print this help message changelog Print the changelog plugin <command> Manage plugins pr <command> Manage Oh My Zsh Pull Requests theme <command> Manage themes update Update Oh My Zsh EOF } function _omz::changelog { local version=${1:-HEAD} format=${3:-"--text"} if ! command git -C "$ZSH" show-ref --verify refs/heads/$version &>/dev/null && \ ! command git -C "$ZSH" show-ref --verify refs/tags/$version &>/dev/null && \ ! command git -C "$ZSH" rev-parse --verify "${version}^{commit}" &>/dev/null; then cat <<EOF Usage: omz changelog [version] NOTE: <version> must be a valid branch, tag or commit. EOF return 1 fi "$ZSH/tools/changelog.sh" "$version" "${2:-}" "$format" } function _omz::plugin { (( $# > 0 && $+functions[_omz::plugin::$1] )) || { cat <<EOF Usage: omz plugin <command> [options] Available commands: info <plugin> Get information of a plugin list List all available Oh My Zsh plugins EOF return 1 } local command="$1" shift _omz::plugin::$command "$@" } function _omz::plugin::info { if [[ -z "$1" ]]; then echo >&2 "Usage: omz plugin info <plugin>" return 1 fi local readme for readme in "$ZSH_CUSTOM/plugins/$1/README.md" "$ZSH/plugins/$1/README.md"; do if [[ -f "$readme" ]]; then (( ${+commands[less]} )) && less "$readme" || cat "$readme" return 0 fi done if [[ -d "$ZSH_CUSTOM/plugins/$1" || -d "$ZSH/plugins/$1" ]]; then _omz::log error "the '$1' plugin doesn't have a README file" else _omz::log error "'$1' plugin not found" fi return 1 } function _omz::plugin::list { local -a custom_plugins builtin_plugins custom_plugins=("$ZSH_CUSTOM"/plugins/*(-/N:t)) builtin_plugins=("$ZSH"/plugins/*(-/N:t)) # If the command is being piped, print all found line by line if [[ ! -t 1 ]]; then print -l ${(q-)custom_plugins} ${(q-)builtin_plugins} return fi if (( ${#custom_plugins} )); then print -P "%U%BCustom plugins%b%u:" print -l ${(q-)custom_plugins} | column fi if (( ${#builtin_plugins} )); then (( ${#custom_plugins} )) && echo # add a line of separation print -P "%U%BBuilt-in plugins%b%u:" print -l ${(q-)builtin_plugins} | column fi } function _omz::pr { (( $# > 0 && $+functions[_omz::pr::$1] )) || { cat <<EOF Usage: omz pr <command> [options] Available commands: clean Delete all PR branches (ohmyzsh/pull-*) test <PR_number_or_URL> Fetch PR #NUMBER and rebase against master EOF return 1 } local command="$1" shift _omz::pr::$command "$@" } function _omz::pr::clean { ( set -e builtin cd -q "$ZSH" # Check if there are PR branches local fmt branches fmt="%(color:bold blue)%(align:18,right)%(refname:short)%(end)%(color:reset) %(color:dim bold red)%(objectname:short)%(color:reset) %(color:yellow)%(contents:subject)" branches="$(command git for-each-ref --sort=-committerdate --color --format="$fmt" "refs/heads/ohmyzsh/pull-*")" # Exit if there are no PR branches if [[ -z "$branches" ]]; then _omz::log info "there are no Pull Request branches to remove." return fi # Print found PR branches echo "$branches\n" # Confirm before removing the branches _omz::confirm "do you want remove these Pull Request branches? [Y/n] " # Only proceed if the answer is a valid yes option [[ "$REPLY" != [yY$'\n'] ]] && return _omz::log info "removing all Oh My Zsh Pull Request branches..." command git branch --list 'ohmyzsh/pull-*' | while read branch; do command git branch -D "$branch" done ) } function _omz::pr::test { # Allow $1 to be a URL to the pull request if [[ "$1" = https://* ]]; then 1="${1:t}" fi # Check the input if ! [[ -n "$1" && "$1" =~ ^[[:digit:]]+$ ]]; then echo >&2 "Usage: omz pr test <PR_NUMBER_or_URL>" return 1 fi # Save current git HEAD local branch branch=$(builtin cd -q "$ZSH"; git symbolic-ref --short HEAD) || { _omz::log error "error when getting the current git branch. Aborting..." return 1 } # Fetch PR onto ohmyzsh/pull-<PR_NUMBER> branch and rebase against master # If any of these operations fail, undo the changes made ( set -e builtin cd -q "$ZSH" # Get the ohmyzsh git remote command git remote -v | while read remote url _; do case "$url" in https://github.com/ohmyzsh/ohmyzsh(|.git)) found=1; break ;; git@github.com:ohmyzsh/ohmyzsh(|.git)) found=1; break ;; esac done (( $found )) || { _omz::log error "could not found the ohmyzsh git remote. Aborting..." return 1 } # Fetch pull request head _omz::log info "fetching PR #$1 to ohmyzsh/pull-$1..." command git fetch -f "$remote" refs/pull/$1/head:ohmyzsh/pull-$1 || { _omz::log error "error when trying to fetch PR #$1." return 1 } # Rebase pull request branch against the current master _omz::log info "rebasing PR #$1..." command git rebase master ohmyzsh/pull-$1 || { command git rebase --abort &>/dev/null _omz::log warn "could not rebase PR #$1 on top of master." _omz::log warn "you might not see the latest stable changes." _omz::log info "run \`zsh\` to test the changes." return 1 } _omz::log info "fetch of PR #${1} successful." ) # If there was an error, abort running zsh to test the PR [[ $? -eq 0 ]] || return 1 # Run zsh to test the changes _omz::log info "running \`zsh\` to test the changes. Run \`exit\` to go back." command zsh -l # After testing, go back to the previous HEAD if the user wants _omz::confirm "do you want to go back to the previous branch? [Y/n] " # Only proceed if the answer is a valid yes option [[ "$REPLY" != [yY$'\n'] ]] && return ( set -e builtin cd -q "$ZSH" command git checkout "$branch" -- || { _omz::log error "could not go back to the previous branch ('$branch')." return 1 } ) } function _omz::theme { (( $# > 0 && $+functions[_omz::theme::$1] )) || { cat <<EOF Usage: omz theme <command> [options] Available commands: list List all available Oh My Zsh themes use <theme> Load an Oh My Zsh theme EOF return 1 } local command="$1" shift _omz::theme::$command "$@" } function _omz::theme::list { local -a custom_themes builtin_themes custom_themes=("$ZSH_CUSTOM"/**/*.zsh-theme(-.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::)) builtin_themes=("$ZSH"/themes/*.zsh-theme(-.N:t:r)) # If the command is being piped, print all found line by line if [[ ! -t 1 ]]; then print -l ${(q-)custom_themes} ${(q-)builtin_themes} return fi if (( ${#custom_themes} )); then print -P "%U%BCustom themes%b%u:" print -l ${(q-)custom_themes} | column fi if (( ${#builtin_themes} )); then (( ${#custom_themes} )) && echo # add a line of separation print -P "%U%BBuilt-in themes%b%u:" print -l ${(q-)builtin_themes} | column fi } function _omz::theme::use { if [[ -z "$1" ]]; then echo >&2 "Usage: omz theme use <theme>" return 1 fi # Respect compatibility with old lookup order if [[ -f "$ZSH_CUSTOM/$1.zsh-theme" ]]; then source "$ZSH_CUSTOM/$1.zsh-theme" elif [[ -f "$ZSH_CUSTOM/themes/$1.zsh-theme" ]]; then source "$ZSH_CUSTOM/themes/$1.zsh-theme" elif [[ -f "$ZSH/themes/$1.zsh-theme" ]]; then source "$ZSH/themes/$1.zsh-theme" else _omz::log error "theme '$1' not found" return 1 fi } function _omz::update { local last_commit=$(cd "$ZSH"; git rev-parse HEAD) # Run update script if [[ "$1" != --unattended ]]; then ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh" --interactive else ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh" fi # Update last updated file zmodload zsh/datetime echo "LAST_EPOCH=$(( EPOCHSECONDS / 60 / 60 / 24 ))" >! "${ZSH_CACHE_DIR}/.zsh-update" # Remove update lock if it exists command rm -rf "$ZSH/log/update.lock" # Restart the zsh session if there were changes if [[ "$1" != --unattended && "$(cd "$ZSH"; git rev-parse HEAD)" != "$last_commit" ]]; then # Old zsh versions don't have ZSH_ARGZERO local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" # Check whether to run a login shell [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" fi }
# coding=utf-8 # Copyright 2020 The Tensor2Robot 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. # Lint as: python3 """Gin configurable functions returning tf.Tensors based on the global_step. """ from typing import Optional, Sequence, Text, Union import gin import numpy as np import tensorflow.compat.v1 as tf @gin.configurable def piecewise_linear(boundaries, values, name = None): """Piecewise linear function assuming given values at given boundaries. Args: boundaries: A list of `Tensor`s or `int`s or `float`s with strictly increasing entries. The first entry must be 0. values: A list of `Tensor`s or float`s or `int`s that specifies the values at the `boundaries`. It must have the same number of elements as `boundaries`, and all elements should have the same type. name: A string. Optional name of the operation. Defaults to 'PiecewiseConstant'. Returns: A 0-D Tensor. Its value is `values[0]` if `x < boundaries[0]` and `values[-1]` if `x >= boundaries[-1]. If `boundaries[i] <= x < boundaries[i+1]` it is the linear interpolation between `values[i]` and `values[i+1]`: `values[i] + (values[i+1]-values[i]) * (x-boundaries[i]) / (boundaries[i+1]-boundaries[i])`. Raises: AssertionError: if values or boundaries is empty, or not the same size. """ global_step = tf.train.get_or_create_global_step() with tf.name_scope(name, 'PiecewiseLinear', [global_step, boundaries, values, name]) as name: values = tf.convert_to_tensor(values) x = tf.cast(tf.convert_to_tensor(global_step), values.dtype) boundaries = tf.cast(tf.convert_to_tensor(boundaries), values.dtype) num_boundaries = np.prod(boundaries.shape.as_list()) num_values = np.prod(values.shape.as_list()) assert num_boundaries > 0, 'Need more than 0 boundaries' assert num_values > 0, 'Need more than 0 values' assert num_values == num_boundaries, ('boundaries and values must be of ' 'same size') # Make sure there is an unmet last boundary with the same value as the # last one that was passed in, and at least one boundary was met. values = tf.concat([values, tf.reshape(values[-1], [1])], 0) boundaries = tf.concat( [boundaries, tf.reshape(tf.maximum(x + 1, boundaries[-1]), [1])], 0) # Make sure there is at least one boundary that was already met, with the # same value as the first one that was passed in. values = tf.concat([tf.reshape(values[0], [1]), values], 0) boundaries = tf.concat( [tf.reshape(tf.minimum(x - 1, boundaries[0]), [1]), boundaries], 0) # Identify index of the last boundary that was passed. unreached_boundaries = tf.reshape( tf.where(tf.greater(boundaries, x)), [-1]) unreached_boundaries = tf.concat( [unreached_boundaries, [tf.cast(tf.size(boundaries), tf.int64)]], 0) index = tf.reshape(tf.reduce_min(unreached_boundaries), [1]) # Get values at last and next boundaries. value_left = tf.reshape(tf.slice(values, index - 1, [1]), []) left_boundary = tf.reshape(tf.slice(boundaries, index - 1, [1]), []) value_right = tf.reshape(tf.slice(values, index, [1]), []) right_boundary = tf.reshape(tf.slice(boundaries, index, [1]), []) # Calculate linear interpolation. a = (value_right - value_left) / (right_boundary - left_boundary) b = value_left - a * left_boundary return a * x + b @gin.configurable def exponential_decay(initial_value = 0.0001, decay_steps = 10000, decay_rate = 0.9, staircase = True): """Create a value that decays exponentially with global_step. Args: initial_value: A scalar float32 or float64 Tensor or a Python number. The initial value returned for global_step == 0. decay_steps: A scalar int32 or int64 Tensor or a Python number. Must be positive. See the decay computation in `tf.exponential_decay`. decay_rate: A scalar float32 or float64 Tensor or a Python number. The decay rate. staircase: Boolean. If True, decay the value at discrete intervals. Returns: value: Scalar tf.Tensor with the value decaying based on the globat_step. """ global_step = tf.train.get_or_create_global_step() value = tf.exponential_decay( learning_rate=initial_value, global_step=global_step, decay_steps=decay_steps, decay_rate=decay_rate, staircase=staircase) return value
def fibonacci(n) seq = [0,1] (2..n).each do |i| seq << seq[i-1] + seq[i-2] end return seq end puts "The fibonacci sequence till the #{n}th term is #{fibonacci(7)}."
<filename>src/spectra/utils/OtherUtil.java /* * Copyright 2016 jagrosh. * * 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 spectra.utils; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.MultipleGradientPaint; import java.awt.RadialGradientPaint; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; import net.dv8tion.jda.entities.Guild; import net.dv8tion.jda.entities.User; import net.dv8tion.jda.utils.MiscUtil; import spectra.Argument; import spectra.Command; import spectra.PermLevel; import spectra.SpConst; /** * * @author <NAME> (jagrosh) */ public class OtherUtil { public static ArrayList<String> readFileLines(String filename) { BufferedReader reader; try{ reader = new BufferedReader(new FileReader(filename)); }catch(FileNotFoundException e){return null;} ArrayList<String> items = new ArrayList<>(); try{ while(true) { String next = reader.readLine(); if(next==null) break; items.add(next.trim()); } reader.close(); return items; }catch(IOException e){ return null; } } public static ArrayList<String> readTrueFileLines(String filename) { BufferedReader reader; try{ reader = new BufferedReader(new FileReader(filename)); }catch(FileNotFoundException e){return null;} ArrayList<String> items = new ArrayList<>(); try{ while(true) { String next = reader.readLine(); if(next==null) break; items.add(next); } reader.close(); return items; }catch(IOException e){ return null; } } public static File writeArchive(String text, String txtname) { File f = new File("WrittenFiles"+File.separatorChar+txtname+".txt"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) { String lines[] = text.split("\n"); for(String line: lines) { writer.write(line+"\r\n"); } writer.flush(); }catch(IOException e){System.err.println("ERROR saving file: "+e);} return f; } public static BufferedImage imageFromUrl(String url) { if(url==null) return null; try { URL u = new URL(url); URLConnection urlConnection = u.openConnection(); urlConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"); //urlConnection.setRequestProperty("authorization", jda.getAuthToken()); return ImageIO.read(urlConnection.getInputStream()); } catch(IOException|IllegalArgumentException e) { System.err.println("[ERROR] Retrieving image: "+e); } return null; } public static BufferedImage makeWave(Color c) { BufferedImage bi = new BufferedImage(128,128,BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2d = bi.createGraphics(); g2d.setComposite(AlphaComposite.SrcOver); g2d.setColor(Color.black); g2d.fillRect(0, 0, 128, 128); float radius = 28+(float)(Math.random()*4); float[] dist = {0.0f,.03f, .08f,.3f, 1.0f}; Color[] colors = {new Color(255,255,255,255),new Color(255,255,255,255), new Color(c.getRed(),c.getGreen(),c.getBlue(),15),new Color(c.getRed(), c.getGreen(),c.getBlue(),5), new Color(c.getRed(),c.getGreen(),c.getBlue(),0)}; int times = 2+(int)(Math.random()*3); for(int j=0;j<times;j++) { double accel=0; int height = 64; for(int i=-(int)radius;i<128+(int)radius;i++) { accel+=(Math.random()*2)-1; if(accel>2.1) accel-=.3; if(accel<-2.1) accel+=.3; if(height<48) accel+=.7; if(height>80) accel-=.7; height+=(int)accel; Point2D center = new Point2D.Float(i, height); RadialGradientPaint p =new RadialGradientPaint(center, radius, dist, colors,MultipleGradientPaint.CycleMethod.NO_CYCLE); g2d.setPaint(p); g2d.fillRect(0, 0, 128, 128); } } return bi; } public static File drawPlot(Guild guild, OffsetDateTime now) { long start = MiscUtil.getCreationTime(guild.getId()).toEpochSecond(); long end = now.toEpochSecond(); int width = 1000; int height = 600; List<User> joins = new ArrayList<>(guild.getUsers()); Collections.sort(joins, (User a, User b) -> guild.getJoinDateForUser(a).compareTo(guild.getJoinDateForUser(b))); BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2d = bi.createGraphics(); g2d.setComposite(AlphaComposite.SrcOver); g2d.setColor(Color.black); g2d.fillRect(0, 0, width, height); double lastX = 0; int lastY = height; for(int i=0; i<joins.size(); i++) { double x = (((guild.getJoinDateForUser(joins.get(i)).toEpochSecond() - start) * width) / (end-start)); int y = height - ((i * height) / joins.size()); double angle = (x==lastX) ? 1.0 : Math.tan((double)(lastY-y)/(x-lastX))/(Math.PI/2); g2d.setColor(Color.getHSBColor((float)angle/4, 1.0f, 1.0f)); g2d.drawLine((int)x, y, (int)lastX, lastY); lastX=x; lastY=y; } g2d.setFont(g2d.getFont().deriveFont(24f)); g2d.setColor(Color.WHITE); g2d.drawString("0 - "+joins.size()+" Users", 20, 26); g2d.drawString(MiscUtil.getCreationTime(guild.getId()).format(DateTimeFormatter.RFC_1123_DATE_TIME), 20, 60); g2d.drawString(now.format(DateTimeFormatter.RFC_1123_DATE_TIME), 20, 90); File f = new File("plot.png"); try { ImageIO.write(bi, "png", f); } catch (IOException ex) { System.out.println("[ERROR] An error occured drawing the plot."); } return f; } public static String compileCommands(Command[] commands) { StringBuilder builder = new StringBuilder("Spectra Commands (v"+SpConst.VERSION+")\n"); for(PermLevel level : PermLevel.values()) { if(level==PermLevel.JAGROSH) continue; builder.append("\n# ").append(level==PermLevel.EVERYONE ? "User" : (level==PermLevel.MODERATOR ? "Moderator" : "Admin")).append(" Commands\n"); for(Command cmd : commands) { if(level.isAtLeast(cmd.getLevel())) builder.append(compileCommand(cmd,"","",level)); } } return builder.toString(); } private static String compileCommand(Command command, String lineStart, String parentchain, PermLevel level) { String fullCommand = parentchain.length()==0 ? command.getName() : parentchain+" "+command.getName(); StringBuilder builder = new StringBuilder(); if(lineStart.length()==0) builder.append("<a name=\"").append(command.getName()).append("\">**").append(fullCommand).append("**</a><br>\n"); else builder.append(lineStart).append("**").append(fullCommand).append("**<br>\n"); if(level == command.getLevel()) { builder.append(lineStart).append("Usage: `").append(SpConst.PREFIX).append(fullCommand).append(Argument.arrayToString(command.getArguments())).append("`<br>\n"); if(command.getAliases().length>0) { builder.append("Aliases:"); for(String alias : command.getAliases()) builder.append(" ").append(alias); builder.append("<br>\n"); } builder.append(lineStart).append("*").append(command.getLongHelp()).append("*\n\n"); } else if(command.getChildren().length == 0) return ""; StringBuilder childBuilder = new StringBuilder(); for(Command cmd: command.getChildren()) if(level.isAtLeast(cmd.getLevel())) childBuilder.append(compileCommand(cmd,lineStart+"> ",fullCommand,level)); if(level != command.getLevel() && childBuilder.length() == 0) return ""; return builder.toString()+childBuilder.toString(); } }
import { useCallback, useState } from "react"; function useQueueState<T>(initialList: T[]): [ T[], { enqueue: (item: T) => number; dequeue: () => T | undefined; peek: () => T | undefined; length: number; } ] { const [list, setList] = useState<T[]>([...initialList]); const enqueue = useCallback( (item: T) => { const newList = [...list, item]; setList(newList); return newList.length; }, [list] ); const dequeue = useCallback(() => { if (list.length > 0) { const firstItem = list[0]; setList([...list.slice(1)]); return firstItem; } return undefined; }, [list]); const peek = useCallback(() => { if (list.length > 0) { return list[0]; } return undefined; }, [list]); const controls = { dequeue, enqueue, length: list.length, peek, }; return [list, controls]; } export { useQueueState };
<reponame>kfuzaylov/moff describe('Moff.modules API', function() { describe('Moff.modules.create', function() { beforeAll(function() { Moff.modules.create('Slideshow', { js: ['fixtures/depend.js'], css: ['fixtures/depend.css'] }, function() {} ); }); it('creates Moff.Module class in storage', function() { expect(Moff.modules._testonly._moduleClassStorage.Slideshow).not.toBeUndefined(); }); it('registers constructor and dependency files', function() { expect(typeof Moff.modules._testonly._moduleClassStorage.Slideshow.constructor).toEqual('function'); expect(typeof Moff.modules._testonly._moduleClassStorage.Slideshow.depend).toEqual('object'); }); it('does not overwrite existing class', function() { Moff.modules.create('Slideshow', function() {}); expect(typeof Moff.modules._testonly._moduleClassStorage.Slideshow.depend).toEqual('object'); }); }); describe('Moff.modules.initClass', function() { var beforeInit, init, afterInit; beforeAll(function(done) { var div = document.createElement('div'); div.innerHTML = '<div class="inside"></div>'; div.className = 'mod-wrapper'; var inside = document.createElement('div'); inside.className = 'inside'; document.body.appendChild(div); document.body.appendChild(inside); Moff.modules.create('Module2', function() { this.scopeSelector = '.mod-wrapper'; this.events = ['event1', 'event2']; this.beforeInit = function() { beforeInit = true; expect(this.id).toBeUndefined(); expect(this.moduleName).toBeUndefined(); expect(this.scope).toBeNull(); }; this.init = function() { init = true; }; this.afterInit = function() { afterInit = true; }; }); Moff.modules.initClass('Slideshow', { id: 43, config: {}, afterInit() { done(); } }); }); it('loads all dependency files', function() { expect(document.querySelectorAll('[src="fixtures/depend.js"], [href="fixtures/depend.css"]').length).toEqual(2); var s = document.querySelector('script[src="fixtures/depend.js"]'); s.parentNode.removeChild(s); }); it('beforeInit and init hooks access the properties', function() { Moff.modules.initClass('Module2', {id: 'modId'}); }); it('runs init hooks', function() { expect(beforeInit).toBe(true); expect(afterInit).toBe(true); expect(init).toBe(true); }); it('registers module scope', function() { expect(Moff.modules.get('Module2').scope.className).toEqual('mod-wrapper'); }); it('register events', function() { expect(Array.isArray(Moff.event._testonly._eventStore.event1)).toBe(true); expect(Array.isArray(Moff.event._testonly._eventStore.event2)).toBe(true); }); }); describe('Moff.modules.get', function() { var moduleObject; beforeAll(function() { moduleObject = Moff.modules.get('Module2'); }); it('gets module class object by name', function() { expect(typeof moduleObject).toEqual('object'); Moff.modules.initClass('Module2', {id: 'modId'}); expect(Array.isArray(Moff.modules.get('Module2'))).toBe(true); expect(Moff.modules.get('Module2').length).toEqual(2); }); }); describe('Moff.modules.getAll', function() { it('gets all class instances by name', function() { expect(Object.keys(Moff.modules.getAll()).length).toEqual(2); }); }); describe('Moff.modules.getBy', function() { it('gets filtered class instances by passed property', function() { expect(Moff.modules.getBy('id', 'modId').length).toEqual(2); expect(Moff.modules.getBy('class', 'Module2').length).toEqual(2); }); }); describe('Moff.modules.remove', function() { it('removes all objects by class name', function() { Moff.modules.remove('Module2'); expect(Moff.modules.get('Module2')).toBeUndefined(); Moff.modules.initClass('Module2', {id: 'modId2'}); expect(typeof Moff.modules.get('Module2')).toEqual('object'); Moff.modules.remove('Module2'); expect(Moff.modules._testonly._moduleObjectStorage.Module2).toBeUndefined(); Moff.modules.initClass('Module2', {id: 'modId2'}); var module2 = Moff.modules.get('Module2'); Moff.modules.remove(module2); expect(Moff.modules._testonly._moduleObjectStorage.Module2).toBeUndefined(); }); }); }); describe('Moff.Module Base Class', function() { beforeAll(function() { Moff.modules.create('TesModule', function() {}); Moff.modules.initClass('TesModule'); Moff.modules.initClass('Module2'); }); describe('Initialized module class', function() { var moduleObject, testObject; beforeAll(function() { moduleObject = Moff.modules.get('Module2'); testObject = Moff.modules.get('TesModule'); }); it('has find method to search inside module scope', function() { expect(typeof testObject.find).toEqual('function'); expect(moduleObject.find('.inside').length).toEqual(1); }); it('has scopeSelector property', function() { expect(testObject.scopeSelector).not.toBeUndefined(); }); it('has scope property', function() { expect(testObject.scope).not.toBeUndefined(); expect(typeof moduleObject.scope).toEqual('object'); }); it('set only defined scope', function() { moduleObject.scopeSelector = null; moduleObject.setScope(); expect(moduleObject.scope.className).toEqual('mod-wrapper'); }); it('has events property', function() { expect(Array.isArray(testObject.events)).toBe(true); }); it('has beforeInit, afterInit and init hooks', function() { expect(typeof testObject.beforeInit).toEqual('function'); expect(typeof testObject.afterInit).toEqual('function'); expect(typeof testObject.init).toEqual('function'); }); }); describe('Moff.Module.reopen method', function() { var test; beforeAll(function() { Moff.Module.reopen({ newProp: 1, newMethod() { return 1; } }); Moff.modules.create('Test', function() {}); Moff.modules.initClass('Test'); test = Moff.modules.get('Test'); }); it('adds new methods and properties', function() { expect(test.newProp).toEqual(1); expect(typeof test.newMethod).toEqual('function'); expect(test.newMethod()).toEqual(1); }); it('overwrites methods and properties', function() { Moff.Module.reopen({ newProp: 3, newMethod: function() { return 2; } }); Moff.modules.create('Test2', function() {}); Moff.modules.initClass('Test2'); var test = Moff.modules.get('Test2'); expect(test.newProp).toEqual(3); expect(typeof test.newMethod).toEqual('function'); expect(test.newMethod()).toEqual(2); }); }); });
#!/bin/bash export PY_VERSION=$1 if [ $PY_VERSION = 'py27' ]; then export PY='python27'; export PIP='pip-2.7'; fi if [ $PY_VERSION = 'py36' ]; then export PY='python36'; export PIP='pip-3.6'; fi rm -f ~/.status; echo "$($PIP list | grep mx;)" >> ~/.status; echo "$($PIP list | grep horovod;)" >> ~/.status; echo "$($PIP list | grep gluon;)" >> ~/.status; echo "$($PY -c 'import mxnet; print(mxnet.__version__)')" >> ~/.status; echo "$($PY -c 'import gluonnlp; print(gluonnlp.__version__)')" >> ~/.status; echo "$($PY -c 'import horovod; print(horovod.__version__)')" >> ~/.status;
#!/bin/bash #SBATCH --time=90:55:00 #SBATCH --account=vhs #SBATCH --job-name=lustre_1n_6t_6d_1000f_617m_10i #SBATCH --nodes=1 #SBATCH --nodelist=comp02 #SBATCH --output=./results/exp_nodes/run-1/lustre_1n_6t_6d_1000f_617m_10i/slurm-%x-%j.out source /home/vhs/Sea/.venv/bin/activate srun -N1 ../scripts/clear_client_pc.sh start=`date +%s.%N` srun -N 1 bash ./results/exp_nodes/run-1/lustre_1n_6t_6d_1000f_617m_10i/n0_sea_parallel.sh & wait end=`date +%s.%N` runtime=$( echo "$end - $start" | bc -l ) echo "Runtime: $runtime"
<filename>src/main/java/cn/springmvc/service/SkuCheckDetailService.java package cn.springmvc.service; import java.util.List; import cn.springmvc.model.SkuCheckDetail; import cn.springmvc.model.Difference; public interface SkuCheckDetailService { public List<SkuCheckDetail> getAllDetailsBySkuCheckId(String skuCheckId) throws Exception; public int insertSkuDetail(List<SkuCheckDetail> detail) throws Exception; public List<Difference> getSkuDifference(String id1,String id2)throws Exception; public int addSkuDetailNum(String skuCheckId , String goodsNo, String num); public int subSkuDetailNum(String skuCheckId, String goodsNo, String num); }
#!/usr/bin/env bash # ----------------------------------------------------------------------------- # Info: # Miroslav Vidovic # githubuser.sh # 20.12.2016.-17:18:33 # ----------------------------------------------------------------------------- # Description: # Given a GitHub username, pulls information about the user usin the GitHub # API. # Usage: # githubuser.sh username # ----------------------------------------------------------------------------- # Script: if [ $# -ne 1 ]; then echo "Usage: $0 <username>" exit 1 fi curl -s "https://api.github.com/users/$1" | \ awk -F'"' ' /\"name\":/ { print $4" is the name of the GitHub user." } /\"location\":/{ print $4" is the users location." } /\"bio\":/{ print $4" is written in the users bio." } /\"followers\":/{ split($3, a, " ") sub(/,/, "", a[2]) print "The user has "a[2]" followers." } /\"following\":/{ split($3, a, " ") sub(/,/, "", a[2]) print "The user is following "a[2]" other users." } /\"public_repos\":/{ split($3, a, " ") sub(/,/, "", a[2]) print "The user has "a[2]" public repositories." } /\"public_gists\":/{ split($3, a, " ") sub(/,/, "", a[2]) print "The user has "a[2]" public gists." } /\"created_at\":/{ print "The account was created on "$4"." } ' exit 0
userInput = input('Enter your input (or "quit" to stop): ') responses = [] while userInput != 'quit': responses.append(userInput) userInput = input('Enter your input (or "quit" to stop): ') print(responses)
/*///////////////////////////////////////////////////////////////////////// // // // iReader! (c) 2010 Samabox. All rights reserved. // // // /////////////////////////////////////////////////////////////////////////*/ var extension; var Settings; var Utils; var anyValueModified = false; function init() { extension = chrome.extension.getBackgroundPage(); Settings = extension.Settings; Utils = extension.Utils; initUI(); loadOptions(); } function initUI() { $("#body input, #body select").change(function() { anyValueModified = true; }); $("#chkHotkey").change(function(event) { $("#txtHotkey")[0].disabled = this.checked ? "" : "disabled"; if (this.checked) $("#txtHotkey").focus(); }); $("#txtHotkey")[0].addEventListener("keydown", function(event) { var hotkey = new Hotkey(event); $("#txtHotkey").val(hotkey.toString(true))[0].hotkey = hotkey; return true; }); $("#txtHotkey")[0].addEventListener("keyup", function(event) { $("#txtHotkey").val(this.hotkey.toString()); return true; }); $("#txtBackgroundOpacity").change(function() { $("#preview table").css("background-color", "rgba(0, 0, 0, " + (this.value / 100) + ")"); }); $("#cmbArticleWidth").change(function() { var percent = parseInt($("#cmbArticleWidth option:selected").val()); var maxWidth = 250; var width = percent * maxWidth / 100; $("#preview .page").css("width", width + "px").css("margin-left", (-width / 2) + "px"); }); $("#cmbArticleMargin").change(function() { var percent = parseInt($("#cmbArticleMargin option:selected").val()); var pageWidth = $("#preview .page").width(); var width = percent * pageWidth / 100; $("#preview .page div").css("margin", width + "px"); }); $("#cmbFontFamily").change(function() { $("#preview .page").css("font-family", $("#cmbFontFamily option:selected").val()); }); $("#chkJustifyText").change(function() { if ($(this).is(":checked")) $("#preview .page").css("text-align", "justify"); else $("#preview .page").css("text-align", ""); }); $("#version").text("v " + extension.appVersion); // Reverse buttons order on Linux and Mac OS X if (!Utils.OS.isWindows) { var btnSaveContainer = $("#btnSave").parent(); btnSaveContainer.next().next().insertBefore(btnSaveContainer); btnSaveContainer.next().insertBefore(btnSaveContainer); } } function loadOptions() { if (Settings.getValue("hotkeyEnabled", "false") != "false") $("#chkHotkey").attr("checked", "checked").change(); var hotkey = Settings.getObject("hotkey"); if (hotkey) hotkey = new Hotkey(hotkey); else hotkey = new Hotkey(true, true, false, "U+0050", 80); $("#txtHotkey").val(hotkey.toString())[0].hotkey = hotkey; $("#txtBackgroundOpacity").val(Settings.getValue("backgroundOpacity", "80")).change(); if (Settings.getValue("useGmail", "false") != "false") $("#chkUseGmail").attr("checked", "checked"); if (Settings.getValue("smoothScrollEnabled", "false") == "true") $("#chkSmoothScroll").attr("checked", "checked"); if (Settings.getValue("animationsEnabled", "false") == "true") $("#chkAnimations").attr("checked", "checked"); var fontFamily = Settings.getValue("currentFontFamily", "Palatino"); $("#cmbFontFamily option[value='" + fontFamily + "']").attr("selected", "selected").change(); var articleWidth = Settings.getValue("articleWidth", "70%"); $("#cmbArticleWidth option[value='" + articleWidth + "']").attr("selected", "selected").change(); var articleMargin = Settings.getValue("articleMargin", "10%"); $("#cmbArticleMargin option[value='" + articleMargin + "']").attr("selected", "selected").change(); if (Settings.getValue("justifyTextEnabled", "true") != "false") $("#chkJustifyText").attr("checked", "checked").change(); } function saveOptions() { Settings.setValue("hotkeyEnabled", $("#chkHotkey").is(":checked")); var hotkey = $("#txtHotkey")[0].hotkey; Settings.setObject("hotkey", hotkey.isValid() ? hotkey : new Hotkey()); Settings.setValue("backgroundOpacity", $("#txtBackgroundOpacity").val()); Settings.setValue("useGmail", $("#chkUseGmail").is(":checked")); Settings.setValue("smoothScrollEnabled", $("#chkSmoothScroll").is(":checked")); Settings.setValue("animationsEnabled", $("#chkAnimations").is(":checked")); Settings.setValue("currentFontFamily", $("#cmbFontFamily option:selected").val()); Settings.setValue("articleWidth", $("#cmbArticleWidth option:selected").val()); Settings.setValue("articleMargin", $("#cmbArticleMargin option:selected").val()); Settings.setValue("justifyTextEnabled", $("#chkJustifyText").is(":checked")); InfoTip.showMessage("Options Saved..", InfoTip.types.success); loadOptions(); anyValueModified = false; } function closeWindow() { if (anyValueModified && InfoTip.confirm("Save changed values?")) saveOptions(); chrome.tabs.getSelected(undefined, function(tab) { chrome.tabs.remove(tab.id); }); } /** * @constructor */ function Hotkey(ctrlKey, shiftKey, altKey, keyIdentifier, keyCode) { if (typeof arguments[0] == "object") { var hotkey = arguments[0]; this.ctrlKey = !!hotkey.ctrlKey; this.shiftKey = !!hotkey.shiftKey; this.altKey = !!hotkey.altKey; this.keyIdentifier = hotkey.keyIdentifier; this.keyCode = hotkey.keyCode; } else { this.ctrlKey = !!ctrlKey; this.shiftKey = !!shiftKey; this.altKey = !!altKey; this.keyIdentifier = keyIdentifier; this.keyCode = keyCode; } this.isValid = function() { return (this.keyCode >= 32 && (this.ctrlKey || this.shiftKey || this.altKey)); }; this.toString = function(dontCheckValidity) { if (!dontCheckValidity && !this.isValid()) return ""; var result = []; if (this.ctrlKey) result.push(Utils.OS.isMac ? "⌘" : "Ctrl"); if (this.shiftKey) result.push("Shift"); if (this.altKey) result.push(Utils.OS.isMac ? "⌥" : "Alt"); if (this.keyCode) { var keyChar = String.fromCharCode(this.keyCode); result.push(keyChar.trim().length > 0 ? keyChar : "Key(" + this.keyCode + ")"); } return result.join(Utils.OS.isMac ? "-" : "+"); }; }
#!/bin/bash # 本脚本的作用是 # 1. 项目打包 # 2. 上传云主机 # 3. 远程登录云主机并执行reset脚本 # 请设置云主机的IP地址和账户 # 例如 ubuntu@122.152.206.172 REMOTE= # 请设置本地SSH私钥文件id_rsa路径 # 例如 /home/litemall/id_rsa ID_RSA= if test -z "$REMOTE" then echo "请设置云主机登录IP地址和账户" exit -1 fi if test -z "$ID_RSA" then echo "请设置云主机登录IP地址和账户" exit -1 fi DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" cd $DIR/../.. LITEMALL_HOME=$PWD echo "LITEMALL_HOME $LITEMALL_HOME" # 项目打包 cd $LITEMALL_HOME ./deploy/util/package.sh # 上传云主机 cd $LITEMALL_HOME scp -i $ID_RSA -r ./deploy $REMOTE:/home/ubuntu/ # 远程登录云主机并执行reset脚本 ssh $REMOTE -i $ID_RSA << eeooff cd /home/ubuntu sudo ./deploy/bin/reset.sh exit eeooff
/* * Azure Functions OpenAPI Extension * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.api; import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; import io.swagger.client.ApiException; import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; import io.swagger.client.ProgressRequestBody; import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import io.swagger.client.model.HttpErrorResponse; import io.swagger.client.model.HttpGenericListObjectResponseAppsDocumentSwagger; import io.swagger.client.model.HttpGenericObjectResponseCreateApp; import io.swagger.client.model.HttpSimpleMessageObjectResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class AccountApi { private ApiClient apiClient; public AccountApi() { this(Configuration.getDefaultApiClient()); } public AccountApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for createApp * @param authorization Common Identity Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call createAppCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/organizations/apps"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (authorization != null) localVarHeaderParams.put("Authorization", apiClient.parameterToString(authorization)); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createAppValidateBeforeCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException("Missing the required parameter 'authorization' when calling createApp(Async)"); } com.squareup.okhttp.Call call = createAppCall(authorization, progressListener, progressRequestListener); return call; } /** * Create App * Create an application for a particular organization. * @param authorization Common Identity Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return HttpGenericObjectResponseCreateApp * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public HttpGenericObjectResponseCreateApp createApp(String authorization) throws ApiException { ApiResponse<HttpGenericObjectResponseCreateApp> resp = createAppWithHttpInfo(authorization); return resp.getData(); } /** * Create App * Create an application for a particular organization. * @param authorization Common Identity Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return ApiResponse&lt;HttpGenericObjectResponseCreateApp&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<HttpGenericObjectResponseCreateApp> createAppWithHttpInfo(String authorization) throws ApiException { com.squareup.okhttp.Call call = createAppValidateBeforeCall(authorization, null, null); Type localVarReturnType = new TypeToken<HttpGenericObjectResponseCreateApp>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Create App (asynchronously) * Create an application for a particular organization. * @param authorization Common Identity Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call createAppAsync(String authorization, final ApiCallback<HttpGenericObjectResponseCreateApp> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createAppValidateBeforeCall(authorization, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<HttpGenericObjectResponseCreateApp>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for deleteApp * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call deleteAppCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/organizations/apps/{appname}"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (authorization != null) localVarHeaderParams.put("Authorization", apiClient.parameterToString(authorization)); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call deleteAppValidateBeforeCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException("Missing the required parameter 'authorization' when calling deleteApp(Async)"); } com.squareup.okhttp.Call call = deleteAppCall(authorization, progressListener, progressRequestListener); return call; } /** * Delete App * Delete an application from a particular organization. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return HttpSimpleMessageObjectResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public HttpSimpleMessageObjectResponse deleteApp(String authorization) throws ApiException { ApiResponse<HttpSimpleMessageObjectResponse> resp = deleteAppWithHttpInfo(authorization); return resp.getData(); } /** * Delete App * Delete an application from a particular organization. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return ApiResponse&lt;HttpSimpleMessageObjectResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<HttpSimpleMessageObjectResponse> deleteAppWithHttpInfo(String authorization) throws ApiException { com.squareup.okhttp.Call call = deleteAppValidateBeforeCall(authorization, null, null); Type localVarReturnType = new TypeToken<HttpSimpleMessageObjectResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Delete App (asynchronously) * Delete an application from a particular organization. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call deleteAppAsync(String authorization, final ApiCallback<HttpSimpleMessageObjectResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = deleteAppValidateBeforeCall(authorization, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<HttpSimpleMessageObjectResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for listApps * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call listAppsCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/organizations/apps"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (authorization != null) localVarHeaderParams.put("Authorization", apiClient.parameterToString(authorization)); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call listAppsValidateBeforeCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException("Missing the required parameter 'authorization' when calling listApps(Async)"); } com.squareup.okhttp.Call call = listAppsCall(authorization, progressListener, progressRequestListener); return call; } /** * List Apps * Lists Apps for a particular organization. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return HttpGenericListObjectResponseAppsDocumentSwagger * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public HttpGenericListObjectResponseAppsDocumentSwagger listApps(String authorization) throws ApiException { ApiResponse<HttpGenericListObjectResponseAppsDocumentSwagger> resp = listAppsWithHttpInfo(authorization); return resp.getData(); } /** * List Apps * Lists Apps for a particular organization. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return ApiResponse&lt;HttpGenericListObjectResponseAppsDocumentSwagger&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<HttpGenericListObjectResponseAppsDocumentSwagger> listAppsWithHttpInfo(String authorization) throws ApiException { com.squareup.okhttp.Call call = listAppsValidateBeforeCall(authorization, null, null); Type localVarReturnType = new TypeToken<HttpGenericListObjectResponseAppsDocumentSwagger>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * List Apps (asynchronously) * Lists Apps for a particular organization. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call listAppsAsync(String authorization, final ApiCallback<HttpGenericListObjectResponseAppsDocumentSwagger> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = listAppsValidateBeforeCall(authorization, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<HttpGenericListObjectResponseAppsDocumentSwagger>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for rotateAppKey * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call rotateAppKeyCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/organizations/apps/{appname}/key"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (authorization != null) localVarHeaderParams.put("Authorization", apiClient.parameterToString(authorization)); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call rotateAppKeyValidateBeforeCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException("Missing the required parameter 'authorization' when calling rotateAppKey(Async)"); } com.squareup.okhttp.Call call = rotateAppKeyCall(authorization, progressListener, progressRequestListener); return call; } /** * Rotate App Key * Rotates a secret key for a particular application. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return HttpGenericObjectResponseCreateApp * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public HttpGenericObjectResponseCreateApp rotateAppKey(String authorization) throws ApiException { ApiResponse<HttpGenericObjectResponseCreateApp> resp = rotateAppKeyWithHttpInfo(authorization); return resp.getData(); } /** * Rotate App Key * Rotates a secret key for a particular application. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @return ApiResponse&lt;HttpGenericObjectResponseCreateApp&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<HttpGenericObjectResponseCreateApp> rotateAppKeyWithHttpInfo(String authorization) throws ApiException { com.squareup.okhttp.Call call = rotateAppKeyValidateBeforeCall(authorization, null, null); Type localVarReturnType = new TypeToken<HttpGenericObjectResponseCreateApp>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Rotate App Key (asynchronously) * Rotates a secret key for a particular application. * @param authorization Cisco CI Bearer Token Prefix token with &#x27;Bearer &#x27; (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call rotateAppKeyAsync(String authorization, final ApiCallback<HttpGenericObjectResponseCreateApp> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = rotateAppKeyValidateBeforeCall(authorization, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<HttpGenericObjectResponseCreateApp>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } /** * Build call for updateAppAttributes * @param authorization Common Identity Bearer Token (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call updateAppAttributesCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/v1/organizations/apps/{appname}/attributes"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); if (authorization != null) localVarHeaderParams.put("Authorization", apiClient.parameterToString(authorization)); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { }; return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updateAppAttributesValidateBeforeCall(String authorization, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException("Missing the required parameter 'authorization' when calling updateAppAttributes(Async)"); } com.squareup.okhttp.Call call = updateAppAttributesCall(authorization, progressListener, progressRequestListener); return call; } /** * Update App Attributes * Updates an Apps Attributes * @param authorization Common Identity Bearer Token (required) * @return HttpSimpleMessageObjectResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public HttpSimpleMessageObjectResponse updateAppAttributes(String authorization) throws ApiException { ApiResponse<HttpSimpleMessageObjectResponse> resp = updateAppAttributesWithHttpInfo(authorization); return resp.getData(); } /** * Update App Attributes * Updates an Apps Attributes * @param authorization Common Identity Bearer Token (required) * @return ApiResponse&lt;HttpSimpleMessageObjectResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<HttpSimpleMessageObjectResponse> updateAppAttributesWithHttpInfo(String authorization) throws ApiException { com.squareup.okhttp.Call call = updateAppAttributesValidateBeforeCall(authorization, null, null); Type localVarReturnType = new TypeToken<HttpSimpleMessageObjectResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Update App Attributes (asynchronously) * Updates an Apps Attributes * @param authorization Common Identity Bearer Token (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call updateAppAttributesAsync(String authorization, final ApiCallback<HttpSimpleMessageObjectResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = updateAppAttributesValidateBeforeCall(authorization, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<HttpSimpleMessageObjectResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
<gh_stars>0 package test.backend.www.model; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(of = "id") public class Airport implements Comparable<Airport> { private final Integer id; private final String name; private final String city; private final String country; private String countryCode; private final String iataFaaCode; private final String icaoCode; private final GeoPoint position; public Airport(String line) { String[] fields = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); // Field 0 - Airport ID Unique OpenFlights identifier for this airport. // Field 1 - Name Name of airport. May or may not contain the City name. // Field 2 - City Main city served by airport. May be spelled // differently from Name. // Field 3 - Country Country or territory where airport is located. // Field 4 - IATA/FAA // 3-letter FAA code, for airports located in Country "United States of // America". // 3-letter IATA code, for all other airports. Blank if not assigned. // Field 5 - ICAO 4-letter ICAO code. Blank if not assigned. // Field 6 - Latitude Decimal degrees, usually to six significant // digits. Negative is South, positive is North. // Field 7 - Longitude Decimal degrees, usually to six significant // digits. Negative is West, positive is East. // Field 8 - Altitude In feet. // Field 9 - Timezone Hours offset from UTC. Fractional hours are // expressed as decimals, eg. India is 5.5. // Field 10 - DST Daylight savings time. One of E (Europe), A // (US/Canada), S (South America), O (Australia), Z (New Zealand), N // (None) or U // (Unknown). // Field 11 - See also: Help: Time // Field 12 - Tz database time zone Timezone in "tz" (Olson) format, eg. // "America/Los_Angeles". id = Integer.valueOf(fields[0]); name = fields[1].replaceAll("\"", ""); city = fields[2].replaceAll("\"", ""); country = fields[3].replaceAll("\"", ""); iataFaaCode = fields[4].replaceAll("\"", ""); icaoCode = fields[5].replaceAll("\"", ""); Coordinate latitude = Coordinate.latitudeFromDecimalDegrees(Double.parseDouble(fields[6])); Coordinate longitude = Coordinate.longitudeFromDecimalDegrees(Double.parseDouble(fields[7])); position = new GeoPoint(latitude, longitude); } @Override public int compareTo(Airport o) { return id.compareTo(o.getId()); } }
from discord.ext import commands class Swatter(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, message): if self.bot.user in message.mentions: await message.add_reaction('\U0001f5de') if 'skynet' in message.content.lower(): await message.add_reaction('\U0001f916') @commands.Cog.listener(name='on_raw_reaction_add') async def on_raw_reaction_add(self, payload): # Check if the reaction is added by the bot itself if payload.user_id == self.bot.user.id: return # Your implementation to remove a specific reaction from a message channel = self.bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) await message.remove_reaction(payload.emoji, self.bot.get_user(payload.user_id)) @commands.command() async def remove_reaction(self, ctx, message_id: int, reaction: str): # Your implementation to remove the specified reaction from the message message = await ctx.channel.fetch_message(message_id) for react in message.reactions: if str(react.emoji) == reaction: async for user in react.users(): await message.remove_reaction(react.emoji, user) break
import ICountry from '../../Api/Models/Country'; export const initialState = { countries: [] as ICountry[], defaultCountries: [] as ICountry[], }; export type DadosVencimentoPayload = { countries: ICountry[]; }; export type EditCountryPayload = { country: ICountry; }; export type SourceCountryPayload = { country: string; }; export type ContriesAction = | { type: 'ADD_COUNTRIES'; payload: DadosVencimentoPayload; } | { type: 'EDIT_COUNTRY'; payload: EditCountryPayload; } | { type: 'SOURCE_COUNTRY'; payload: SourceCountryPayload; }; export default function countriesManager(state = initialState, action: ContriesAction) { switch (action.type) { case 'ADD_COUNTRIES': { return { ...state, countries: [...action.payload.countries], defaultCountries: [...action.payload.countries], }; } case 'EDIT_COUNTRY': { const { country } = action.payload; const stateCountry = state.countries.map((oldCountry) => { if (oldCountry['_id'] === country['_id']) { return country; } return oldCountry; }); return { ...state, countries: stateCountry, defaultCountries: stateCountry, }; } case 'SOURCE_COUNTRY': { const stateCountry = state.defaultCountries.filter((country) => country.name.includes(action.payload.country)); return { ...state, countries: [...stateCountry], }; } default: return state; } }
<gh_stars>1-10 /* Copyright (c) 2013, Groupon, 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 GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.nakala.core; import junit.framework.Assert; import org.junit.Test; import java.io.ByteArrayInputStream; /** * @author <EMAIL> */ public class JobFlowSpecsDefinitionTest { private static final String SPECS = "top:\n" + " value_type: map\n" + " required:\n" + " - collection_reader\n" + " - collection_analyzer\n" + " - data_stores\n" + "collection_reader:\n" + " value_type: map\n" + " required:\n" + " - class_name\n" + " parameters:\n" + " - collection_name\n" + " - db_name\n" + " - file_name\n" + " - host\n" + " - id_field\n" + " - label_field\n" + " - port\n" + " - separator\n" + " - table_name\n" + " - text_field\n" + " - title_field\n" + "collection_analyzer:\n" + " value_type: map\n" + " required:\n" + " - class_name\n" + " parameters:\n" + " - analyzer\n" + " - block_filter\n" + " - find_best_parameters\n" + " - min_df\n" + " - normalizers\n" + " - pass_filter\n" + " - representer\n" + " - stopwords\n" + " - tokenizer\n" + " - max_threshold\n" + " - min_threshold\n" + " - threshold_step\n" + "data_stores:\n" + " value_type: list\n" + " list_type: data_store\n" + "data_store:\n" + " value_type: map\n" + " required:\n" + " - class_name\n" + " parameters:\n" + " - collection_name\n" + " - db_name\n" + " - file_name\n" + " - host\n" + " - port\n" + " - table_name\n" + "normalizer:\n" + " value_type: map\n" + " required:\n" + " - class_name\n" + "parameters:\n" + " value_type: map\n" + "class_name:\n" + " value_type: string\n" + "db_name:\n" + " value_type: string\n" + "host:\n" + " value_type: string\n" + "port:\n" + " value_type: string\n" + "table_name:\n" + " value_type: string\n" + "collection_name:\n" + " value_type: string\n" + "file_name:\n" + " value_type: string\n" + "separator:\n" + " value_type: string\n" + "id_field:\n" + " value_type: string\n" + "label_field:\n" + " value_type: string\n" + "text_field:\n" + " value_type: string\n" + "title_field:\n" + " value_type: string\n" + "analyzer:\n" + " value_type: map\n" + "block_filter:\n" + " value_type: map\n" + "find_best_parameters:\n" + " value_type: boolean\n" + "min_df:\n" + " value_type: integer\n" + "normalizers:\n" + " value_type: list\n" + " list_type: normalizer\n" + "pass_filter:\n" + " value_type: map\n" + "representer:\n" + " value_type: map\n" + "stopwords:\n" + " value_type: map\n" + "tokenizer:\n" + " value_type: map\n" + "max_threshold:\n" + " value_type: double\n" + "min_threshold:\n" + " value_type: double\n" + "threshold_step:\n" + " value_type: double\n" + "domains:\n" + " value_type: list\n" + " list_type: string\n"; @Test public void testJobFlowSpecsDefinition() throws Exception { JobFlowSpecsDefinition definition = new JobFlowSpecsDefinition(); definition.initialize(new ByteArrayInputStream(SPECS.getBytes())); Assert.assertEquals(JobFlowSpecsDefinition.MAP, definition.getValueType("top")); Assert.assertEquals(3, definition.getRequired("top").size()); Assert.assertTrue(definition.getRequired("top").contains(SimpleJobFlowSpecs.COLLECTION_READER)); Assert.assertTrue(definition.getRequired("top").contains(SimpleJobFlowSpecs.COLLECTION_ANALYZER)); Assert.assertTrue(definition.getRequired("top").contains(SimpleJobFlowSpecs.DATA_STORES)); Assert.assertEquals(JobFlowSpecsDefinition.MAP, definition.getValueType("collection_reader")); Assert.assertEquals(1, definition.getRequired("collection_reader").size()); Assert.assertTrue(definition.getRequired("collection_reader").contains(JobFlowSpecsDefinition.CLASS_NAME)); Assert.assertEquals(11, definition.getParameters("collection_reader").size()); Assert.assertEquals(JobFlowSpecsDefinition.MAP, definition.getValueType("collection_analyzer")); Assert.assertEquals(JobFlowSpecsDefinition.LIST, definition.getValueType("data_stores")); Assert.assertEquals(JobFlowSpecsDefinition.STRING, definition.getValueType("class_name")); Assert.assertEquals(JobFlowSpecsDefinition.DOUBLE, definition.getValueType("max_threshold")); Assert.assertEquals(JobFlowSpecsDefinition.LIST, definition.getValueType("normalizers")); Assert.assertEquals(JobFlowSpecsDefinition.LIST, definition.getValueType("domains")); Assert.assertEquals(JobFlowSpecsDefinition.STRING, definition.getListType("domains")); Assert.assertEquals("normalizer", definition.getListType("normalizers")); } }
<reponame>sunnya97/solidstate-contracts const describeBehaviorOfProxy = require('./Proxy.behavior.js'); let deploy = async function () { const implementationFactory = await ethers.getContractFactory('Ownable'); const implementationInstance = await implementationFactory.deploy(); await implementationInstance.deployed(); const factory = await ethers.getContractFactory('ProxyMock'); const instance = await factory.deploy( implementationInstance.address ); return await instance.deployed(); }; describe('Proxy', function () { // eslint-disable-next-line mocha/no-setup-in-describe describeBehaviorOfProxy({ deploy, implementationFunction: 'owner()', implementationFunctionArgs: [], }); });
<reponame>ssloth/ezlinker-frontend import { useFormModal, useDrawer, useFormDrawer, useModal } from './usePopup'; import useVisualLayout from './useVisualLayout'; import createUseRestful from './createUseRestful'; import { useTable } from './useTable'; export { useFormModal, createUseRestful, useDrawer, useFormDrawer, useModal, useTable, useVisualLayout, };
const customer = { name : 'John Doe', address : '555 Main Street, Anytown, USA', email : 'john.doe@example.com' };
def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr)-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] arr = [4, 2, 5, 6, 3, 1] bubble_sort(arr) print(arr)
define :update_proxy, app: nil do app = params[:app] template "/usr/lib/systemd/system/#{app}-instance.service" do source 'proxy/proxy_instance.service.erb' variables app: app end execute 'systemctl daemon-reload' service app.name do service_name "#{app}-instance.service" action [:enable, :stop, :start] end end
def has_organisation_access(user_id, organisation_uuid): # Implementation of has_organisation_access function to check if the user has access to the organization # This function should return True if the user has access to the organization, and False otherwise pass # Replace with actual implementation class OrganisationDeleteView(OrganisationBaseView, DeleteView): def get_success_url(self): return reverse('organisations:organisation_list') def has_permission(self, user, uuid): # Check if the user has the permission to delete the organization return user.has_perm('organisations.delete_organisation') and has_organisation_access(user.id, uuid) def dispatch(self, request, *args, **kwargs): # Enforce permission check before allowing the deletion to proceed if not self.has_permission(request.user, kwargs.get('uuid')): raise PermissionDenied return super().dispatch(request, *args, **kwargs)
<filename>user/api/role/v1/role_http.pb.go // Code generated by protoc-gen-go-http. DO NOT EDIT. // versions: // protoc-gen-go-http v2.1.3 package v1 import ( context "context" http "github.com/go-kratos/kratos/v2/transport/http" binding "github.com/go-kratos/kratos/v2/transport/http/binding" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the kratos package it is being compiled against. var _ = new(context.Context) var _ = binding.EncodeURL const _ = http.SupportPackageIsVersion1 type RoleServiceHTTPServer interface { CreateRole(context.Context, *CreateRoleRequest) (*Role, error) DeleteRole(context.Context, *DeleteRoleRequest) (*DeleteRoleResponse, error) GetRole(context.Context, *GetRoleRequest) (*Role, error) GetRolePermission(context.Context, *GetRolePermissionRequest) (*GetRolePermissionResponse, error) ListRoles(context.Context, *ListRolesRequest) (*ListRolesResponse, error) PatchRolePermission(context.Context, *PatchRolePermissionRequest) (*PatchRolePermissionResponse, error) UpdateRole(context.Context, *UpdateRoleRequest) (*Role, error) UpdateRolePermission(context.Context, *UpdateRolePermissionRequest) (*UpdateRolePermissionResponse, error) } func RegisterRoleServiceHTTPServer(s *http.Server, srv RoleServiceHTTPServer) { r := s.Route("/") r.POST("/v1/role/list", _RoleService_ListRoles0_HTTP_Handler(srv)) r.GET("/v1/roles", _RoleService_ListRoles1_HTTP_Handler(srv)) r.GET("/v1/role/{id}", _RoleService_GetRole0_HTTP_Handler(srv)) r.POST("/v1/role", _RoleService_CreateRole0_HTTP_Handler(srv)) r.PATCH("/v1/role/{role.id}", _RoleService_UpdateRole0_HTTP_Handler(srv)) r.PUT("/v1/role/{role.id}", _RoleService_UpdateRole1_HTTP_Handler(srv)) r.DELETE("/v1/role/{id}", _RoleService_DeleteRole0_HTTP_Handler(srv)) r.GET("/v1/role/{id}/permission", _RoleService_GetRolePermission0_HTTP_Handler(srv)) r.PUT("/v1/role/{id}/permission", _RoleService_UpdateRolePermission0_HTTP_Handler(srv)) r.PATCH("/v1/role/{id}/permission", _RoleService_PatchRolePermission0_HTTP_Handler(srv)) } func _RoleService_ListRoles0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in ListRolesRequest if err := ctx.Bind(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/ListRoles") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.ListRoles(ctx, req.(*ListRolesRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*ListRolesResponse) return ctx.Result(200, reply) } } func _RoleService_ListRoles1_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in ListRolesRequest if err := ctx.BindQuery(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/ListRoles") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.ListRoles(ctx, req.(*ListRolesRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*ListRolesResponse) return ctx.Result(200, reply) } } func _RoleService_GetRole0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in GetRoleRequest if err := ctx.BindQuery(&in); err != nil { return err } if err := ctx.BindVars(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/GetRole") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.GetRole(ctx, req.(*GetRoleRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*Role) return ctx.Result(200, reply) } } func _RoleService_CreateRole0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in CreateRoleRequest if err := ctx.Bind(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/CreateRole") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.CreateRole(ctx, req.(*CreateRoleRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*Role) return ctx.Result(200, reply) } } func _RoleService_UpdateRole0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in UpdateRoleRequest if err := ctx.Bind(&in); err != nil { return err } if err := ctx.BindVars(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/UpdateRole") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.UpdateRole(ctx, req.(*UpdateRoleRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*Role) return ctx.Result(200, reply) } } func _RoleService_UpdateRole1_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in UpdateRoleRequest if err := ctx.Bind(&in); err != nil { return err } if err := ctx.BindVars(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/UpdateRole") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.UpdateRole(ctx, req.(*UpdateRoleRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*Role) return ctx.Result(200, reply) } } func _RoleService_DeleteRole0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in DeleteRoleRequest if err := ctx.BindQuery(&in); err != nil { return err } if err := ctx.BindVars(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/DeleteRole") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.DeleteRole(ctx, req.(*DeleteRoleRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*DeleteRoleResponse) return ctx.Result(200, reply) } } func _RoleService_GetRolePermission0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in GetRolePermissionRequest if err := ctx.BindQuery(&in); err != nil { return err } if err := ctx.BindVars(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/GetRolePermission") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.GetRolePermission(ctx, req.(*GetRolePermissionRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*GetRolePermissionResponse) return ctx.Result(200, reply) } } func _RoleService_UpdateRolePermission0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in UpdateRolePermissionRequest if err := ctx.Bind(&in); err != nil { return err } if err := ctx.BindVars(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/UpdateRolePermission") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.UpdateRolePermission(ctx, req.(*UpdateRolePermissionRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*UpdateRolePermissionResponse) return ctx.Result(200, reply) } } func _RoleService_PatchRolePermission0_HTTP_Handler(srv RoleServiceHTTPServer) func(ctx http.Context) error { return func(ctx http.Context) error { var in PatchRolePermissionRequest if err := ctx.Bind(&in); err != nil { return err } if err := ctx.BindVars(&in); err != nil { return err } http.SetOperation(ctx, "/user.api.role.v1.RoleService/PatchRolePermission") h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { return srv.PatchRolePermission(ctx, req.(*PatchRolePermissionRequest)) }) out, err := h(ctx, &in) if err != nil { return err } reply := out.(*PatchRolePermissionResponse) return ctx.Result(200, reply) } } type RoleServiceHTTPClient interface { CreateRole(ctx context.Context, req *CreateRoleRequest, opts ...http.CallOption) (rsp *Role, err error) DeleteRole(ctx context.Context, req *DeleteRoleRequest, opts ...http.CallOption) (rsp *DeleteRoleResponse, err error) GetRole(ctx context.Context, req *GetRoleRequest, opts ...http.CallOption) (rsp *Role, err error) GetRolePermission(ctx context.Context, req *GetRolePermissionRequest, opts ...http.CallOption) (rsp *GetRolePermissionResponse, err error) ListRoles(ctx context.Context, req *ListRolesRequest, opts ...http.CallOption) (rsp *ListRolesResponse, err error) PatchRolePermission(ctx context.Context, req *PatchRolePermissionRequest, opts ...http.CallOption) (rsp *PatchRolePermissionResponse, err error) UpdateRole(ctx context.Context, req *UpdateRoleRequest, opts ...http.CallOption) (rsp *Role, err error) UpdateRolePermission(ctx context.Context, req *UpdateRolePermissionRequest, opts ...http.CallOption) (rsp *UpdateRolePermissionResponse, err error) } type RoleServiceHTTPClientImpl struct { cc *http.Client } func NewRoleServiceHTTPClient(client *http.Client) RoleServiceHTTPClient { return &RoleServiceHTTPClientImpl{client} } func (c *RoleServiceHTTPClientImpl) CreateRole(ctx context.Context, in *CreateRoleRequest, opts ...http.CallOption) (*Role, error) { var out Role pattern := "/v1/role" path := binding.EncodeURL(pattern, in, false) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/CreateRole")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) if err != nil { return nil, err } return &out, err } func (c *RoleServiceHTTPClientImpl) DeleteRole(ctx context.Context, in *DeleteRoleRequest, opts ...http.CallOption) (*DeleteRoleResponse, error) { var out DeleteRoleResponse pattern := "/v1/role/{id}" path := binding.EncodeURL(pattern, in, true) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/DeleteRole")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "DELETE", path, nil, &out, opts...) if err != nil { return nil, err } return &out, err } func (c *RoleServiceHTTPClientImpl) GetRole(ctx context.Context, in *GetRoleRequest, opts ...http.CallOption) (*Role, error) { var out Role pattern := "/v1/role/{id}" path := binding.EncodeURL(pattern, in, true) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/GetRole")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "GET", path, nil, &out, opts...) if err != nil { return nil, err } return &out, err } func (c *RoleServiceHTTPClientImpl) GetRolePermission(ctx context.Context, in *GetRolePermissionRequest, opts ...http.CallOption) (*GetRolePermissionResponse, error) { var out GetRolePermissionResponse pattern := "/v1/role/{id}/permission" path := binding.EncodeURL(pattern, in, true) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/GetRolePermission")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "GET", path, nil, &out, opts...) if err != nil { return nil, err } return &out, err } func (c *RoleServiceHTTPClientImpl) ListRoles(ctx context.Context, in *ListRolesRequest, opts ...http.CallOption) (*ListRolesResponse, error) { var out ListRolesResponse pattern := "/v1/roles" path := binding.EncodeURL(pattern, in, true) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/ListRoles")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "GET", path, nil, &out, opts...) if err != nil { return nil, err } return &out, err } func (c *RoleServiceHTTPClientImpl) PatchRolePermission(ctx context.Context, in *PatchRolePermissionRequest, opts ...http.CallOption) (*PatchRolePermissionResponse, error) { var out PatchRolePermissionResponse pattern := "/v1/role/{id}/permission" path := binding.EncodeURL(pattern, in, false) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/PatchRolePermission")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "PATCH", path, in, &out, opts...) if err != nil { return nil, err } return &out, err } func (c *RoleServiceHTTPClientImpl) UpdateRole(ctx context.Context, in *UpdateRoleRequest, opts ...http.CallOption) (*Role, error) { var out Role pattern := "/v1/role/{role.id}" path := binding.EncodeURL(pattern, in, false) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/UpdateRole")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "PUT", path, in, &out, opts...) if err != nil { return nil, err } return &out, err } func (c *RoleServiceHTTPClientImpl) UpdateRolePermission(ctx context.Context, in *UpdateRolePermissionRequest, opts ...http.CallOption) (*UpdateRolePermissionResponse, error) { var out UpdateRolePermissionResponse pattern := "/v1/role/{id}/permission" path := binding.EncodeURL(pattern, in, false) opts = append(opts, http.Operation("/user.api.role.v1.RoleService/UpdateRolePermission")) opts = append(opts, http.PathTemplate(pattern)) err := c.cc.Invoke(ctx, "PUT", path, in, &out, opts...) if err != nil { return nil, err } return &out, err }
def filter_even_numbers(numbers): even_numbers = [] for i in numbers: if i % 2 == 0: even_numbers.append(i) return even_numbers filtered = filter_even_numbers([3, 4, 5, 6, 7]) print(filtered)