text:
Q: Knockout JS remove option if value is greater than (on foreach) I have a json array that has a device name and quantity. If the quantity is two and the user adds two items to the foreach for that name (they select from the drop down field) I'd like to hide that device name option from the drop down menu.
*Edit*
Rune seems that he has the correct answer, however I cannot figure out how to integrate it into my code. Here is my code: http://jsfiddle.net/QTUqD/1/
<form id="extMngForm">

                Extension
                Name
                Email
                Voicemail Pin
                Device
                MAC Address
                Ship To

 Add Extension

Previous

Next

</form>
<form id="extMngForm">

                Extension
                Name
                Email
                Voicemail Pin
                Device
                MAC Address
                Ship To

 Add Extension

Previous

Next

</form>

window.ExtListViewModel = new function () {
    var self = this;
    window.viewModel = self;

    self.list = ko.observableArray();

    self.pageSize = ko.observable(10);
    self.pageIndex = ko.observable(0);
    self.selectedItem = ko.observable();
    self.extQty = ko.observable();
    self.devices = ko.observableArray(['devices']);

    self.addressList = ko.observableArray(['addressList']);
    self.edit = function (item) {
        if($('#extMngForm').valid()) {
            self.selectedItem(item);
        }
    };

    self.cancel = function () {
        self.selectedItem(null);
    };

    self.add = function () {
        if($('#extMngForm').valid()) {
            var newItem = new Extension();
            self.list.push(newItem);
            self.selectedItem(newItem);
            self.moveToPage(self.maxPageIndex());
        }
    };
    self.remove = function (item) {

            if (confirm('Are you sure you wish to delete this item?')) {

                    self.list.remove(item);
                    if (self.pageIndex() > self.maxPageIndex()) {
                        self.moveToPage(self.maxPageIndex());
                    }

            }
            $('.error').hide();
    };
    self.save = function () {
        if($('#extMngForm').valid()) {
            self.selectedItem(null);
        };
    };

    self.templateToUse = function (item) {
        return self.selectedItem() === item ? 'editExts' : 'extItems';
    };

    self.pagedList = ko.dependentObservable(function () {
        var size = self.pageSize();
        var start = self.pageIndex() * size;
        return self.list.slice(start, start + size);
    });
    self.maxPageIndex = ko.dependentObservable(function () {
        return Math.ceil(self.list().length / self.pageSize()) - 1;
    });
    self.previousPage = function () {
        if (self.pageIndex() > 0) {
            self.pageIndex(self.pageIndex() - 1);
        }
    };
    self.nextPage = function () {
        if (self.pageIndex() < self.maxPageIndex()) {
            self.pageIndex(self.pageIndex() + 1);
        }
    };
    self.allPages = ko.dependentObservable(function () {
        var pages = [];
        for (i = 0; i <= self.maxPageIndex() ; i++) {
            pages.push({ pageNumber: (i + 1) });
        }
        return pages;
    });
    self.moveToPage = function (index) {
        self.pageIndex(index);
    };

};

ko.applyBindings(ExtListViewModel, document.getElementById('extMng'));

function Extension(extension, name, email, vmpin, device, macAddress, shipTo){
    this.extension = ko.observable(extension);
    this.name = ko.observable(name);
    this.email = ko.observable(email);
    this.vmpin = ko.observable(vmpin);
    this.device = ko.observable(device);
    this.macAddress = ko.observable(macAddress);
    this.shipTo = ko.observable(shipTo);
}

A: Without knowing how your markup or view model looks like, I'm assuming you're mapping your devices. I would map the following "Device" object and work with it. To be more specific, I'd have to see your code in a JSBin or something.
var Device = function(data) {
   var self = this;
   ko.mapping.fromJS(data, { }, self);
   // self.name added via mapping
   // self.quantity added via mapping
   self.numberOfDevicesShown = ko.observable();
   self.showDevice = ko.computed(function(){ // use this property in the markup
       return self.numberOfDevicesShown() >= self.quantitity();
   })
};

var viewModelMapping = {
    'devices': {
        create: function(options) {
        return new Device(options.data);
    }
};

var ViewModel = function(data) {
    var self = this;
    ko.mapping.fromJS(data,viewModelMapping,self);
}

$(document).ready(function () {
    vm = new ViewModel(initialViewModelData);
    ko.applyBindings(vm);
});

In your markup you can do something like this:
<select data-bind="foreach: devices">

        <option></option>

</select>

You can read more about mapping in the Customizing object construction using "create" and Customizing object updating using "update" sections here

A: Here's an approach based on adding a new computed for available devices on the main viewmodel object, plus a helper function. It's not ideal for all cases and there's probably ways to simplify this, but I've run out of juice for now :P
self.availableDevices = ko.computed(function() {
    var usedQuantities = {}; // for each device id, store the used quantity
    ko.utils.arrayForEach(self.list(), function(item) {
        var device = item.device();
        if (device) {
            usedQuantities[device.id] = 1 + (usedQuantities[device.id] || 0);
        }
    });

    return ko.utils.arrayFilter(self.devices(), function(device) {
        var usedQuantity = usedQuantities[device.id] || 0;
        return device.quantity > usedQuantity;
    });
});

// need this to add back item's selected device to its device-options,
// and to maintain original order of devices
self.devicesForItem = function(item) {
    var availableDevices = self.availableDevices();
    return ko.utils.arrayFilter(self.devices(), function(device) {
        return device === item.device() || availableDevices.indexOf(device) !== -1;
    });
}

and the corresponding binding (note: no use of optionsValue):
<select style="width:100px;" data-bind="options: $root.devicesForItem($data), optionsText: 'name', value: device"></select>

Updated JSFiddle: http://jsfiddle.net/antishok/QTUqD/6/
Some other small changes I made to your fiddle so it'll work: changed extQty to 20, added example devices, fixed element ID for ko.applyBindings, commented form validation stuff.. maybe a couple more ;p (also included different bootstrap css)


text:
Q: vuejs webpack npm run watch I have a problem since I upgraded from version node (8 -> 14) and npm (6 -> 7).
Now when I run the following command:
npm run watch

I have the following error:
[webpack-cli] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.optimization.splitChunks should be one of these:
   false | object { automaticNameDelimiter?, automaticNameMaxLength?, cacheGroups?, chunks?, enforceSizeThreshold?, fallbackCacheGroup?, filename?, hidePathInfo?, maxAsyncRequests?, maxInitialRequests?, maxSize?, minChunks?, minSize?, name? }
   -> Optimize duplication and caching by splitting chunks by shared modules and cache group
   Details:
    * configuration.optimization.splitChunks.cacheGroups['styles-public\css\web\***\app'] has an unknown property 'type'. These properties are valid:
      object { automaticNameDelimiter?, automaticNameMaxLength?, automaticNamePrefix?, chunks?, enforce?, enforceSizeThreshold?, filename?, maxAsyncRequests?, maxInitialRequests?, maxSize?, minChunks?, minSize?, name?, priority?, reuseExistingChunk?, test? }
    * configuration.optimization.splitChunks.cacheGroups['styles-public\css\pro\***\app'] has an unknown property 'type'. These properties are valid:
      object { automaticNameDelimiter?, automaticNameMaxLength?, automaticNamePrefix?, chunks?, enforce?, enforceSizeThreshold?, filename?, maxAsyncRequests?, maxInitialRequests?, maxSize?, minChunks?, minSize?, name?, priority?, reuseExistingChunk?, test? }
 - configuration.output.chunkFilename should be a string.
   -> The filename of non-entry chunks as relative path inside the `output.path` directory.
 - configuration.stats has an unknown property 'preset'. These properties are valid:
   object { all?, assets?, assetsSort?, builtAt?, cached?, cachedAssets?, children?, chunkGroups?, chunkModules?, chunkOrigins?, chunks?, chunksSort?, colors?, context?, depth?, entrypoints?, env?, errorDetails?, errors?, exclude?, excludeAssets?, excludeModules?, hash?, logging?, loggingDebug?, loggingTrace?, maxModules?, moduleAssets?, moduleTrace?, modules?, modulesSort?, nestedModules?, optimizationBailout?, outputPath?, performance?, providedExports?, publicPath?, reasons?, source?, timings?, usedExports?, version?, warnings?, warningsFilter? }
npm ERR! code 2
npm ERR! path C:\wamp64\www\app
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js --watch

I deleted my node_modules directory.
I reinstalled everything. I still have the error.
Do you know where it can come from?
See my package.json file and my webpack.mix.js file below.
package.json
{
    "name": "app",
    "version": "1.0.0",
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "cross-env": "^7.0.3",
        "jquery": "^3.5.1",
        "laravel-mix": "^6.0.13",
        "lodash": "^4.17.15",
        "opn": "^6.0.0",
        "popper.js": "^1.16.1",
        "postcss": "^8.1.14",
        "resolve-url-loader": "^3.1.2",
        "sass": "^1.26.8",
        "sass-loader": "^7.3.1",
        "vue-template-compiler": "^2.6.11",
        "webpack": "^4.46.0",
        "webpack-cli": "^4.5.0",
        "webpack-serve": "^3.2.0"
    },
    "dependencies": {
        "@ckeditor/ckeditor5-build-classic": "^20.0.0",
        "@ckeditor/ckeditor5-image": "^20.0.0",
        "@ckeditor/ckeditor5-vue": "^1.0.1",
        "@fortawesome/fontawesome-free": "^5.15.2",
        "@fortawesome/fontawesome-svg-core": "^1.2.34",
        "@fortawesome/free-solid-svg-icons": "^5.15.2",
        "@fortawesome/vue-fontawesome": "^2.0.2",
        "@fullcalendar/bootstrap": "^5.3.0",
        "@fullcalendar/core": "^5.3.0",
        "@fullcalendar/daygrid": "^5.3.0",
        "@fullcalendar/interaction": "^5.3.0",
        "@fullcalendar/timegrid": "^5.3.0",
        "@fullcalendar/vue": "^5.3.0",
        "axios": "^0.21.1",
        "bootstrap": "^4.6.0",
        "bootstrap-vue": "^2.15.0",
        "es6-promise": "^4.2.8",
        "fullcalendar": "^5.1.0",
        "mapbox-gl": "^0.53.1",
        "moment": "^2.27.0",
        "npm": "^7.6.3",
        "v-calendar": "^1.0.0-beta.23",
        "vee-validate": "^3.3.7",
        "vue": "^2.6.12",
        "vue-analytics": "^5.22.1",
        "vue-i18n": "^8.23.0",
        "vue-mapbox": "^0.4.1",
        "vue-phone-number-input": "^1.1.10",
        "vue-recaptcha": "^1.3.0",
        "vue-router": "^3.3.4",
        "vue-select": "^3.11.2",
        "vue-swatches": "^2.1.0",
        "vuex": "^3.5.1",
        "vuex-persist": "^2.2.0"
    }
}

webpack.mix.js
const mix = require('laravel-mix');
const path = require('path');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
    .js('resources/js/app.js', 'public/js')
    .webpackConfig({
        resolve: {
            alias: {
                '@components': path.resolve(__dirname, 'resources/js/components/'),
                '@router': path.resolve(__dirname, 'resources/js/router/'),
                '@store': path.resolve(__dirname, 'resources/js/store/')
            }
        }
    });

Thank you.

A: *

*Do you have npm watch npm install npm-watch
There are some install additional plug-ins,
In package.json
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"watch": "vue-cli-service build --watch",
"dev": "vue-cli-service build --mode development"
},

In package.json did you add "watch": "npm-watch",
watch script:
{
  "watch": {
    "test": "{src,test}/*.js"
  },
  "scripts": {
    "test": "tape test/*.js",
    "watch": "npm-watch"
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: issue with getIntent() i need to open XML file with app that i am developing...the code is:
<intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="*/*" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="file"  android:host="*" android:pathPattern=".*\\.xml"  android:mimeType="*/*"  />
        </intent-filter>

and it is ok!
but i need, when i click on file, to get data from xml file.
In fragment if i write:
Intent intent = getIntent();
intent.getData().toString();

getIntent() is written in red by IDE...why?

A: If you're calling getIntent() from a Fragment you need to get the Activity on which it's running. So try
Intent intent = getActivity().getIntent();
Hope it helps

A: Try getActivity().getIntent().If outside Activity, you need an instance of the activity


text:
Q: I cannot include my database to an .exe file I want to convert my .py files into an .exe file. To do this, I'm using auto-py-to-exe, but when I convert it, my database is not included. I can start my application, but when I'm on a window which need data from my database, it's not displayed.
pyinstaller -y -w --add-data "C:/Users/..../..../..../..../Base_SAV.db";"."
...
"C:/..../..../..../..../..../MyCatSAV_Final.py"

My application works, as long as it doesn't need access to the database

A: You don't have to include the database. sqlite3 database is regular file which is created in your script current directory. There is no "standard place" for a sqlite3 database.
Assuming you create your database like this:
conn = sqlite3.connect("Base_SAV.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS(--------------)")
con.commit()
con.close()

and you compile it to executable you don't need to include the database you created in your working directory.As soon as you run the executable the database will be created in the folder which you have you exe file.
So pyinstaller command to convert it to executable should be:
pyinstaller --windowed --onfile    MyCatSAV_Final.py

which will work perfectly.

A: I created a project and in this project my I created a seperate database.py file and refer my database.py to main.py like this
**con = sqlite3.connect(database=r'ims.db ')
cur = con.cursor()**

but after creating main.exe my database file is not working


text:
Q: Is it appropriate to use conjectures in contest? Is it appropriate to use conjectures in math contest?
I've been to fair amount of math contest and as far as I know the judges want a solid proof for every step take to make to solve the problem. But is using a conjecture a good idea? Will they accept the answer or will they deduct points?
Conjectures are statements that are based on an incomplete information and are unproven. But many famous conjectures can solve a contest problem.
Let's imagine we are given an equation with 3 variables we need to find solutions for it in prime numbers. We somehow come up to this equation:
$A^{11} + B^7 = C^{13}$
At this point we could use the Beal's conjecture to prove that $A,B \text{ and } C$ have to have a common factor in order to have a solution. But this means that they are not prime numbers, leading to that there isn't prime solution for that equation.
But until now the Beal's conjecture isn't proven. Should I use it?
Also there are lot of well-know conjectures like both Goldbach conjecture, Collatz conjecture, Fermat-Catalan conjecture...
P.S. I don't want a solution with proof for the equation I just think of it.

A: No, it is not appropriate to use conjectures to do a question in any written exam or test or contest unless it is explicitly stated otherwise. Doing mathematics is all about proofs, and conjectures are statements which have neither been proven nor disproven.


text:
Q: How do I link modules in ghc? I have a haskell program that uses Data.Set and Data.IntMap, what flags do I need to give GHC to get it to link those libraries in? Simple question, I know, but the man pages didn't help me and I don't know where to look.

A: Adding --make will tell GHC to find all the dependencies and do all the linking for you automatically:

GHC will figure out all the modules in
  the program by following the imports
  from these initial modules. It will
  then attempt to compile each module
  which is out of date, and finally, if
  there is a Main module, the program
  will also be linked into an
  executable.


text:
Q: Which registers should executable loader install before start a program? For example, I have simple C program that only have main function that just returns 0. What registers should loader (Linux exec loader, I guess) install before start a program? I didn't find information about this except stack pointer register.

A: This functionality you ascribe to the loader is usually called crt0 or crt0.o.  It usually has an entry point called __start, that the operating system will transfer initial control to.
It is part of the basic C library code and it takes control of the new process, ultimately to invoke your main.  Depending on the environment it runs in it might have to actually open stdin & stdout, and collect the command line parameters into an argv array to pass to your main.  Initially as you suspect it may establish the stack pointer register, however, that may be done already by exec, depending of course.  It may also establish a (global) data pointer again depending on the architecture (if it uses one) and the operating system (whether it has already done this or not).
Since the C main is a 100% normal C function, the arguments will be passed to it using the same calling convention and register usage as most any other function with the same signature.  The calling convention varies across different compilers and operating systems, so a good bet is to decompile your C main and see how it accesses it's parameters.


text:
Q: zlib compressing byte array? I have this uncompressed byte array:
0E 7C BD 03 6E 65 67 6C 65 63 74 00 00 00 00 00 00 00 00 00 42 52 00 00 01 02 01
00 BB 14 8D 37 0A 00 00 01 00 00 00 00 05 E9 05 E9 00 00 00 00 00 00 00 00 00 00
00 00 00 00 01 00 00 00 00 00 81 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 05 00 00 01 00 00 00

And I need to compress it using the deflate algorithm (implemented in zlib), from what I searched the equivalent in C# would be using GZipStream but I can't match the compressed resulted at all.
Here is the compressing code:
public byte[] compress(byte[] input)
{
    using (MemoryStream ms = new MemoryStream())
    {
        using (GZipStream deflateStream = new GZipStream(ms, CompressionMode.Compress))
        {
            deflateStream.Write(input, 0, input.Length);
        }
        return ms.ToArray();
    }
}

Here is the result of the above compressing code:
1F 8B 08 00 00 00 00 00 04 00 ED BD 07 60 1C 49 96 25 26 2F 6D CA 7B 7F 4A F5 4A
D7 E0 74 A1 08 80 60 13 24 D8 90 40 10 EC C1 88 CD E6 92 EC 1D 69 47 23 29 AB 2A
81 CA 65 56 65 5D 66 16 40 CC ED 9D BC F7 DE 7B EF BD F7 DE 7B EF BD F7 BA 3B 9D
4E 27 F7 DF FF 3F 5C 66 64 01 6C F6 CE 4A DA C9 9E 21 80 AA C8 1F 3F 7E 7C 1F 3F
22 7E 93 9F F9 FB 7F ED 65 7E 51 E6 D3 F6 D7 30 CF 93 57 BF C6 AF F1 6B FE 5A BF
E6 AF F1 F7 FE 56 7F FC 03 F3 D9 AF FB 5F DB AF 83 E7 0F FE 35 23 1F FE BA F4 FE
AF F1 6B FC 1A FF 0F 26 EC 38 82 5C 00 00 00

Here is the result I am expecting:
78 9C E3 AB D9 CB 9C 97 9A 9E 93 9A 5C C2 00 03 4E 41 0C 0C 8C 4C 8C 0C BB 45 7A
CD B9 80 4C 90 18 EB 4B D6 97 0C 28 00 2C CC D0 C8 C8 80 09 58 21 B2 00 65 6B 08
C8

What I am doing wrong, could some one help me out there ?

A: First, some information: DEFLATE is the compression algorithm, it is defined in RFC 1951.  DEFLATE is used in the ZLIB and GZIP formats, defined in RFC 1950 and 1952 respectively, which essentially are thin wrappers around DEFLATE bytestreams.  The wrappers provide metadata such as, the name of the file, timestamps, CRCs or Adlers, and so on.
.NET's base class library implements a DeflateStream that produces a raw DEFLATE bytestream, when used for compression.  When used in decompression it consumes a raw DEFLATE bytestream.  .NET also provides a GZipStream, which is just a GZIP wrapper around that base.  There is no ZlibStream in the .NET base class library - nothing that produces or consumes ZLIB.  There are some tricks to doing it, you can search around.
The deflate logic in .NET exhibits a behavioral anomaly, where previously compressed data can actually be inflated, significantly, when "compressed".  This was the source of a Connect bug raised with Microsoft, and has been discussed here on SO.  This may be what you are seeing, as far as ineffective compression.  Microsoft have rejected the bug, because while it is ineffective for saving space, the compressed stream is not invalid, in other words it can be "decompressed" by any compliant DEFLATE engine.
In any case, as someone else posted, the compressed bytestream produced by different compressors may not necessarily be the same. It depends on their default settings, and the application-specified settings for the compressor. Even though the compressed bytestreams are different, they may still decompress to the same original bytestream. On the other hand the thing you used to compress was GZIP, while it appears what you want is ZLIB. While they are related, they are not the same; you cannot use GZipStream to produce a ZLIB bytestream. This is the primary source of the difference you see.

I think you want a ZLIB stream.
The free managed Zlib in the DotNetZip project implements compressing streams for all of the three formats (DEFLATE, ZLIB, GZIP).  The DeflateStream and GZipStream work the same way as the .NET builtin classes, and there's a ZlibStream class in there, that does what you think it does. None of these classes exhibit the behavior anomaly I described above.

In code it looks like this:
    byte[] original = new byte[] {
        0x0E, 0x7C, 0xBD, 0x03, 0x6E, 0x65, 0x67, 0x6C,
        0x65, 0x63, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x42, 0x52, 0x00, 0x00,
        0x01, 0x02, 0x01, 0x00, 0xBB, 0x14, 0x8D, 0x37,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x05, 0xE9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x81, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00,
        0x01, 0x00, 0x00, 0x00
    };

    var compressed = Ionic.Zlib.ZlibStream.CompressBuffer(original);

The output is like this:
0000    78 DA E3 AB D9 CB 9C 97 9A 9E 93 9A 5C C2 00 03     x...........\...
0010    4E 41 0C 0C 8C 4C 8C 0C BB 45 7A CD 61 62 AC 2F     NA...L...Ez.ab./
0020    19 B0 82 46 46 2C 82 AC 40 FD 40 0A 00 35 25 07     ...FF,..@.@..5%.
0030    CE                                                  .

To decompress,
    var uncompressed = Ionic.Zlib.ZlibStream.UncompressBuffer(compressed);

You can see the documentation on the static CompressBuffer method.

EDIT
The question is raised, why is DotNetZip producing 78 DA for the first two bytes instead of 78 9C?  The difference is immaterial.  78 DA encodes "max compression", while 78 9C encodes "default compression". As you can see in the data, for this small sample, the actual compressed bytes are exactly the same whether using BEST or DEFAULT. Also, the compression level information is not used during decompression.  It has no effect in your application.
If you don't want "max" compression, in other words if you are very set on getting 78 9C as the first two bytes, even though it doesn't matter, then you cannot use the CompressBuffer convenience function, which uses the best compression level under the covers.  Instead you can do this:
  var compress = new Func<byte[], byte[]>( a => {
        using (var ms = new System.IO.MemoryStream())
        {
            using (var compressor =
                   new Ionic.Zlib.ZlibStream( ms,
                                              CompressionMode.Compress,
                                              CompressionLevel.Default ))
            {
                compressor.Write(a,0,a.Length);
            }

            return ms.ToArray();
        }
    });

  var original = new byte[] { .... };
  var compressed = compress(original);

The result is:
0000    78 9C E3 AB D9 CB 9C 97 9A 9E 93 9A 5C C2 00 03     x...........\...
0010    4E 41 0C 0C 8C 4C 8C 0C BB 45 7A CD 61 62 AC 2F     NA...L...Ez.ab./
0020    19 B0 82 46 46 2C 82 AC 40 FD 40 0A 00 35 25 07     ...FF,..@.@..5%.
0030    CE                                                  .

A: Quite simply what you got had a GZip header. What you want is the simpler Zlib header. ZLib has options for GZip header, Zlib header or no header. Typically the Zlib header is used unless the data is associated with a disk file (in which case GZip header is used.) Apparently, there is no way with .Net library to write a zlib header (even though this is by far the most common header used in file formats). Try http://dotnetzip.codeplex.com/.
You can quickly test all the different zlib options using HexEdit (Operations->Compression->Settings).  See http://www.hexedit.com . It took me 10 minutes to check your data by simply pasting your compressed bytes into HexEdit and decompressing. Also tried compressing your orignal bytes with GZip and ZLib headers as a double-check. Note that you may have to fiddle with the settings to get exactly the bytes you were expecting.


text:
Q: Finding minimum and maximum points with Lagrange Multipliers I need to use Lagrange Multipliers to find the maximum and minimum values of the function:
$f(x,y)=2e^{xy}$
subject to the given constraints:
$2x^2+y^2=32$
So I went through some examples, and I got:
$x=\pm2\sqrt{2}$ and $y=\pm4$ (Wolfram confirms).
Now I'm having trouble finding the maximum and the minimum.
I understood that If I want to find out if  $(2\sqrt2,4)$ is maxima or minima, then I'll take for example $x=3$, and by the constraint, this point will be $(3,\sqrt{14})$, and check if this value is greater or smaller than (for example) $(2\sqrt2,4)$, and if it is bigger - then my $(2\sqrt2,4)$ is a minimum.
But in my example, $3>2\sqrt2$ and $4>\sqrt{14}$, isn't it problematic?
This seems a bit messy. First, am I right? Second, any other way to do so, that is not much complicated?

A: I didn't check the calculation, but in general, once we have obtained the possible max/min points by Lagrange Multipliers, we simply need to plug the values into $f(x,y)$ and determine the max/min values, that is:

*

*$f(2\sqrt 2,4)=2e^{8\sqrt 2}=\dots$

*$\dots$

In this case it is not difficult to see that

*

*$f_{max}=f(2\sqrt 2,4)=f(-2\sqrt 2,-4)=2e^{8\sqrt 2}$

*$f_{min}=f(-2\sqrt 2,4)=f(2\sqrt 2,-4)=2e^{-8\sqrt 2}$

A: The points found are guaranteed to be maxima or minima, so it's enough to plug each pair back into $f(x)$ to determine which are which
Doing the way you suggested is not problematic, it's only required that the points are on the contraint, an ellipse in this case. If you plug, say, $(2\sqrt{2},4)$ and $(3,\sqrt{14})$
$$2e^{8\sqrt{2}}\approx  163874.4$$
$$2e^{3\sqrt{14}}\approx 149959.3$$
So it doesn't matter that $3>2\sqrt{2}$ because $\sqrt{14} < 4$. The process of Lagrange multipliers sorted it out for you already by finding the values that beat all the others

A: You don't really need to "plug" any numbers into the function in order to answer your question.  The function  $ \ f(x,y) \ = \ 2e^{xy} \ $ has  symmetry about the origin [ $ \ f(x,y) \ = \ f(-x,-y) \ $ ] .  The constraint curve $ \ 2x^2 \ + \ y^2 \ = \ 32 \ $ is an ellipse centered on the origin, so we expect a critical point in any quadrant to be "mirrored" by a critical point of the same kind in the diagonally-opposite quadrant.
You found two critical values for $ \ x \ $ and $ \ y \ $ each, producing four critical points in all, one in each quadrant as anticipated.  The product $ \ xy \ $ is positive in the first and third quadrants and negative in the second and fourth.  Thus, the exponent in $  \ 2e^{xy} \ $ is positive at $ \ (2\sqrt2 \ , \ 4) \ $  and $ \ (-2\sqrt2 \ , \ -4) \ $  , producing the absolute maxima for our function, with the exponent being negative at $ \ (2\sqrt2 \ , \ -4) \ $ and $ \ (-2\sqrt2 \ , \ 4) \ $  , where the absolute minima are located.  (The values are as shown by user.)


text:
Q: I cannot get javascript to function properly I'm working on this small project for college. I need to make and interactive page using html/css/javascript. The problem is, my javascript doesn't work, I've tried using lecturers script that is meant to work 100%, but even then it doesn't. I checked my browser settings, and made sure that javascript is allowed. Maybe someone can see what the problem is.
I'm currently trying to make a slider for this page and connect it to a .js file. I used same code our lecturer showed. Slider is there, but it is not displaying the value for me. Here's my html code
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Disney Game</title>
        <link rel="stylesheet" href="stylesheet.css">

                    <form action="" onsubmit="return false;">
                        How much do you like Disney?:

                            0<input type="range" min="0" max="10" id="likeDisney">10

                    </form>

And here is the javascript code:
document.getElementById("likeDisney").onchange= slide;
function slide()
{
    var likedisney = document.getElementById("likeDisney").value;
    if (likedisney>6) {
        document.getElementById("opinion").innerHTML="Love it!";
        }
        else if (likedisney>4) {
            document.getElementById("opinion").innerHTML="Like it!";
        }
    else {
        document.getElementById("opinion").innerHTML="Not a fan of Disney";
        }
}


text:
Q: Find File Path with Several Words of the Name my file name format is like this:
Apple price 04/13-04/15.xlsx
Apple price 04/16-04/18.xlsx
Orange price 04/13-04/15.xlsx

I'm now using the code as follows, using 'Apple' as filter. Is there anyway I can use double filter (also use 04/15 as filter)?
i = "Apple"
basePath = r'C:\Users\username\Desktop'
glob.glob(os.path.join(basePath,'*{0}*.xls'.format(i)))

A: What if you use regular expressions(re library) to filter so that you can add those in the same line.


text:
Q: Why can't I break or place blocks in Minecraft? I was playing on a single player modded survival and I went to check the forums for help with one mod. When I got back on my game I couldn't mine or place blocks and I've tried switching to /gamemode 0 but this only happened in my modded survival. I can still place and break blocks in vanilla Minecraft.

A: Not being able to do that means you're in adventure mode. Remember that now you can use /gamemode a, s, or c to change your gamemode to avoid things like this happening again.

A: type in /gamemode s
you are in adventure mode it will turn adventure mode off


text:
Q: DateTime.TryParseExact single second I have time results from races in many different formats (more or less any combination of hour, minute, second and millisecond):

*

*01:22:51.15

*22:15.12

*15.0

*12:21

*...

I parse them with a list of valid formats and so far all the formats work except one: The single second format, e.g. "5".
For some reason the following list (containing "s" as the 1st item) does not help me to parse the string "5" into a DateTime, "25" works fine though.
var timeString = "5";
var timeFormats = new[] { "s", "s.f", "s.ff", "ss", "ss.f", "ss.ff", "m:ss", "m:ss.f", "m:ss.ff", "mm:ss", "mm:ss.f", "mm:ss.ff", "H:mm:ss", "H:mm:ss.f", "H:mm:ss.ff", "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff" };
DateTime timeValue;
DateTime.TryParseExact(timeString, timeFormats, null, DateTimeStyles.None, out timeValue);

Any idea why this does not work as I expect it to? Or is there a cleaner way to cover all these time formats without adding another nuget package...?
Cheers!

A: Because there is only one character in the format, it is being treated as the Sortable standard format, rather than as a custom format with seconds.
To change this, prefix the custom format with a % character, as in "%s".  See "Using single custom format specifiers".
Also, recognize that if these are actual elapsed times of races, TimeSpan is a more appropriate data structure than DateTime.  Be careful when switching, as not all formatting tokens are identical between the two objects.  In particular, TimeSpan uses h for hours, not H.  See Custom TimeSpan Format Strings.


text:
Q: Numpy: Inverse Transforming Different Size Array I'm trying to get the hang of normalizing my data, doing some work on it and then changing it back.  When doing an inverse_transform do I have to always pass in the exact same shape as it was when I did a fit_transform?  The code below will give me a "non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,3)"
import numpy as np
from sklearn.preprocessing import MinMaxScaler

first = np.array([[  1.2345, 1.220000,1.26245],
 [  1.234,1.220000,7.0901],
 [  1.23450,1.22000,1.14795]])

scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(first)
new_dataset = dataset[:,:1]
trainPredict2 = scaler.inverse_transform(new_dataset)

A: You don't have to pass a data set with exactly the same shape, but the number of columns must match the original data set as each row is interpreted as a record and each column is interpreted as a feature. And you can not miss features for your testing data set, technically. So for instance, slicing the rows will still work:
new_dataset = dataset[:1,:]
trainPredict2 = scaler.inverse_transform(new_dataset)

This gives back the first row of your original data set:
trainPredict2
# array([[ 1.2345 ,  1.22   ,  1.26245]])

If you really want to inverse one or two features, you can calculate this by inversing the min-max transformation x′:=(x−xmin)/(xmax−xmin) formula, :
scaler.data_range_[:1] * dataset[:,:1] + scaler.data_min_[:1]
# array([[ 1.2345],
#        [ 1.234 ],
#        [ 1.2345]])

This gives back the first column of your original data set.


text:
Q: How to use sns.catplot to visualize the change of a dataset I have a dataset that changes mean and variance after time, but still is in the same range of y values. I want visualize the change of the data. Here is the plot with the features I'm looking for:

Unfortunately I don't know how to create such a beauty. I tried the seaborn.catplot() function but I'm missing the option to visualize the mean and the connections of the individual datapoints.
import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

dist_1 = np.random.beta(2.,2.,250)
dist_2 = np.random.beta(3.,4.,250)
data = {"dist 1": dist_1, "dist 2": dist_2}
df = pd.DataFrame(data=data)
sns.catplot(data=df, s=3.)
plt.show()

The result would be something like this:

Any ideas to add the missing features?

A: To get a categorical plot you need to create a data frame that contains a categorical column. I made slight modifications to your code with respect to the column names -
    import numpy as np
    import seaborn as sns
    import pandas as pd
    import matplotlib.pyplot as plt
dist_1 = np.random.beta(2.,2.,250)
dist_2 = np.random.beta(3.,4.,250)
data = {"dist1": dist_1, "dist2": dist_2}
df = pd.DataFrame(data=data)
df['id'] = df.index

I added a column for the index of each row so that I can use it to convert this wide dataframe into a long one.
long_df = pd.wide_to_long(df, 'dist', 'id', 'cat').reset_index()
long_df.head()
#   id  cat      dist
#0   0    1  0.558567
#1   1    1  0.265868
#2   2    1  0.076470
#3   3    1  0.891855
#4   4    1  0.215208

Now I want to use the cat column on the x-axis of the catplot, dist on the y-axis and create a point plot for each row in the original dataframe.
sns.catplot(x="cat", y="dist", hue='id', kind="point", data=long_df, legend=False)
plt.show()

This gives you the following plot -

Bonus: You can also do the same using a line plot and add the markers for mean.
mean_df = long_df.groupby('cat')['dist'].mean().reset_index()
mean_df
#   cat      dist
#0    1  0.535771
#1    2  0.399939
fig = plt.figure()
ax1 = fig.add_subplot(111)
sns.lineplot(x='cat', y='dist', hue='id', data=long_df, legend=False, ax=ax1)
ax1.plot(mean_df['cat'], mean_df['dist'], 'x')
plt.show()

Which gives you -

The 'X' on each category represents the mean. Hope that helps!


text:
Q: UIImagePickerControllerSourceTypeSavedPhotosAlbum stay at the top of screen in ios 5 I have a problem with UIImagePickerControllerSourceTypeSavedPhotosAlbum in ios 5. When I present modally UIPickerController I want to be at the bottom of the screen and see my last photos but I'm staying at the top and have to scroll down. Same code runs perfectly in ios 4. Any suggestions how to fix it?

A: I was looking for something similar and I don't think you can do this (unless your roll your own custom photo picker).  So, I settled on using UIImagePickerControllerSourceTypePhotoLibrary which gets me close to this.  You get presented a choice of albums to go into and when you select Camera Roll, this shows you the photos scrolled all the way down to the bottom...to the latest photos taken.
Also, this link helped shed some light on the differences between UIImagePickerControllerSourceTypePhotoLibrary and UIImagePickerControllerSourceTypeSavedPhotosAlbum


text:
Q: Spark scala - Nested StructType conversion to Map I am using Spark 1.6 in scala.
I created an index in ElasticSearch with an object. The object "params" was created as a Map[String, Map[String, String]]. Example:
val params : Map[String, Map[String, String]] = ("p1" -> ("p1_detail" -> "table1"), "p2" -> (("p2_detail" -> "table2"), ("p2_filter" -> "filter2")), "p3" -> ("p3_detail" -> "table3"))

That gives me records that look like the following:
{
        "_index": "x",
        "_type": "1",
        "_id": "xxxxxxxxxxxx",
        "_score": 1,
        "_timestamp": 1506537199650,
        "_source": {
           "a": "toto",
           "b": "tata",
           "c": "description",
           "params": {
              "p1": {
                 "p1_detail": "table1"
              },
              "p2": {
                 "p2_detail": "table2",
                 "p2_filter": "filter2"
              },
              "p3": {
                 "p3_detail": "table3"
              }
           }
        }
     },

Then I am trying to read the Elasticsearch index in order to update the values.
Spark reads the index with the following schema:
|-- a: string (nullable = true)
|-- b: string (nullable = true)
|-- c: string (nullable = true)
|-- params: struct (nullable = true)
|    |-- p1: struct (nullable = true)
|    |    |-- p1_detail: string (nullable = true)
|    |-- p2: struct (nullable = true)
|    |    |-- p2_detail: string (nullable = true)
|    |    |-- p2_filter: string (nullable = true)
|    |-- p3: struct (nullable = true)
|    |    |-- p3_detail: string (nullable = true)

My problem is that the object is read as a struct. In order to manage and easily update the fields I want to have a Map as I am not very familiar with StructType.
I tried to get the object in a UDF as a Map but I have the following error:
 User class threw exception: org.apache.spark.sql.AnalysisException: cannot resolve 'UDF(params)' due to data type mismatch: argument 1 requires map<string,map<string,string>> type, however, 'params' is of struct<p1:struct<p1_detail:string>,p2:struct<p2_detail:string,p2_filter:string>,p3:struct<p3_detail:string>> type.;

UDF code snippet:
val getSubField : Map[String, Map[String, String]] => String = (params : Map[String, Map[String, String]]) => { val return_string = (params ("p1") getOrElse("p1_detail", null.asInstanceOf[String]) return_string }

My question: How can we convert this Struct to a Map? I already read saw the toMap method available in the documentation but can not find how to use it (not very familiar with implicit parameters) as I am a scala beginner.
Thanks in advance,

A: I finally solved it as follows:
def convertRowToMap[T](row: Row): Map[String, T] = {
  row.schema.fieldNames
    .filter(field => !row.isNullAt(row.fieldIndex(field)))
    .map(field => field -> row.getAs[T](field))
    .toMap
}

/* udf that converts Row to Map */
val rowToMap: Row => Map[String, Map[String, String]] = (row: Row) => {
  val mapTemp = convertRowToMap[Row](row)

  val mapToReturn = mapTemp.map { case (k, v) => k -> convertRowToMap[String](v) }

  mapToReturn
}
val udfrowToMap = udf(rowToMap)

A: You can't specify type of param as StructType object, instead specify type as Row.
//Schema of parameter
def schema:StructType = (new StructType).add("p1", (new StructType).add("p1_detail", StringType))
      .add("p2", (new StructType).add("p2_detail", StringType).add("p2_filter",StringType))
      .add("p3", (new StructType).add("p3_detail", StringType))

 //Not allowed
 val extractVal: schema => collection.Map[Nothing, Nothing] = _.getMap(0)

Solution:
// UDF example to process struct column
val extractVal: (Row) => collection.Map[Nothing, Nothing] = _.getMap(0)

// You would implement something similar
   val getSubField : Map[String, Map[String, String]] => String =
  (params : Row) =>
  {
    val p1 = params.getAs[Row]("p1")
    .........
    return null;
  }

I hope this helps !


text:
Q: Not able to store multiple records in related list using visualforce page Here i am not clear about the apex logic,
the flow is :
i have one child record Bundle__c and Product2 is parent, and i need to store multiple Product2 under Bundle__c (Product2 is located in related list under Bundle__c record)
To achieve this scenario i wrote visualforce page for multiselect product2 using checkbox and once user click on ADD Button then those all selected Products have to store under that related list of Bundle__c
here is my Page code :
<apex:page standardController="Product2" extensions="ProductSelectController">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockButtons location="TOP">
            <apex:commandButton value="Add" action="{!AddProduct}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockTable value="{!productlist}" var="prlist">
            <apex:column >
                <apex:inputCheckbox value="{!selectedCheckBox}" />
            </apex:column>
            <apex:column headerValue="Product Name">
                {!prList.Name}
            </apex:column>
            <apex:column headerValue="Description">
                {!prList.Description}
            </apex:column>
            <apex:column headerValue="Price">
                {!prList.Cost__c}
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>

Apex Class :
Public Class ProductSelectController{

public List<Product2> productlist{get;set;}
public boolean selectedCheckBox{get;set;}
//public Product2 pr{get;set;}
public Bundle__c bundle{get;set;}

public ProductSelectController(ApexPages.StandardController Controller){

    productlist = [select Id, Name, Description, Cost__c from Product2];
    bundle = new Bundle__c();
    //pr = new Product2();

}

public Void AddProduct(){
    for(Product2 p : productlist){
        if(selectedCheckBox == True){
            p.Bundle__c = bundle.Id;
            system.debug('====P====='+p.Bundle__c);
        }
    }
}
}

Can anyone please help me !!

A: Assuming that Bundle__c is the record being passed into the standard controller and that you are simply updating a field on product2 (those you selected) to populate the Bundle__c lookup, this illustrates the wrapper class in its most basic form:
class
Public Class ProductSelectController{

public Id bundleId{get;set;}

public productWrapper[] productList {
    get{
        if(productList == null){
            productList = New ProductWrapper[]{};

            for(Product2 p : [select Id, Name, Description, Cost__c, Bundle__ c from Product2])
                productList.add(New productWrapper(p,bundleId));

        }

        return productList;
    }
    set;
}

//Assuming the standard controller is on bundle
public ProductSelectController(ApexPages.StandardController Controller){
    bundleId = controller.getId();
}

public Void save(){
    Product2[] tbu = New Product2[]{};

    for(ProductWrapper p : productlist){
        if(p.isSelected == True){
            p.prod.Bundle__c = bundleId;
            system.debug('====P====='+p.prod.Bundle__c);
            tbu.add(p.prod);
        }
    }

    update tbu;
}

public class productWrapper{
    public product2 prod {get;set;}
    public boolean isSelected {get;set;}

    public productWrapper(Product2 prod, Id bundleId){
        this.prod = prod;
        isSelected = prod.Bundle__c == bundleId; //If the product already is associated with the BundleId then default to already selected
    }
}
}

Then your page would use the wrapper and its values to iterate and ultimately call the save() method
<apex:page standardController="Bundle__c" extensions="ProductSelectController">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockButtons location="TOP">
            <apex:commandButton value="Add" action="{!save}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockTable value="{!productlist}" var="prlist">
            <apex:column >
                <apex:inputCheckbox value="{!prList.isSelected}" />
            </apex:column>
            <apex:column headerValue="Product Name">
                {!prList.prod.Name}
            </apex:column>
            <apex:column headerValue="Description">
                {!prList.prod.Description}
            </apex:column>
            <apex:column headerValue="Price">
                {!prList.prod.Cost__c}
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>

I assumed you had the standardController set incorrectly since you were updating the product2 records Bundle__c lookup to be associated with the Bundle__c record. In the Example the Bundle__c is the singular record that you will be using to populated the lookup on your selected Product2 records.

A: Here is the Wrapper Class outline code. Little explanations on the concept of Wrapper class. You can think of it as the structure of the C/C++ languages.
This is how you need to declare it:- Your object relationships are not very clear. Still, I made my own assumptions while coding this. Please follow it as an example.
Public Class ProductSelectController{
public ProductSelectController(ApexPages.StandardController Controller){

public List<ProductBundleSelectedWrapper> productBundlewrap = new List<ProductBundleSelectedWrapper>();
public ProductBundleSelectedWrapper wrap = new ProductBundleSelectedWrapper();
public Product2 productrec = new Product2();
public Bundle__c Bundlerec = new Bundle__c();
public List<Product2> productlst = new List<Product2>();
public List<Product2> productlst2 = new List<Product2>();
public List<Bundle__c> bundlelst = new List<Bundle__c>([select Id, Product__c, Name, Description, Cost__c from Bundle__c WHERE Id = (Bundle__c)controller.getRecord().id]);

public Void AddProduct(){
    for (Bundle__c tmpbundle : bundlelst){
        productlst = [SELECT ProductCode, isSelected, Name, Description FROM Product2 WHERE Product__c =: (Id)tmpbundle.Product__c];

        for (Product2 tmpprod : productlst)
        {
            if (tmpprod.isSelected == true)
                productlst2.add(tmpprod);
        }
        wrap.productlst = productlst2;
        wrap.buldlerec = tmpbundle;
        ProductBundleSelectedWrapper.add(wrap);
    }
    insert ProductBundleSelectedWrapper;
}

public class ProductBundleSelectedWrapper{
    public List<Product2> productlst = new List<Product2>();
    public Boolean isSelected = false;
    public Buldle__c buldlerec = new Bundle__c();

    //Constructor
    public productSelectedWrapper()
    {
    }

}

}


text:
Q: Is there a way to run a shell script on a linux file server from a c# console application I have a directory full of DICOM on a linux file server. I have the directory mapped as a network drive and have created a c# console application for modifying the DICOM tags, modifying DICOM tags is something I must do before I can import to our database.
When I am in the server I can run the following to import everything from this directory to my database:
for x in `ls -d1 *`;
do
    dcmbase_import -U p_mfdid1 -n -l info -i "$x:spiromics:file:H:SPIROMICS";
done

I would like to know if there is a way that I can run the above code from within the c# application. For instance, is there a way to access the linux file server and execute a shell script?
Currently I have to run my c# application to change heads and then manual access the server and run the shell script. I would love to have this all encompassed in one application so that I could run it at the end of the day and have it processing and importing over night.

A: You can't run the shell script over the network share as that would run it on your local machine and you need to run it on the Linux machine.
The common method for executing code remotely is by running it with SSH or invoking with RPC. I would avoid RPC if possible because even though it's more powerful it also needs more complicated setup.
From Karl-Johan Sjögren's answer on this question, C# send a simple SSH command, I was able to find a git project for SSH calls in .NET as well as a small stub that could get you started. You would change hostnameOrIp to your Linux server, and change the command to be run to your script.
SSH.NET
using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
    client.Connect();
    client.RunCommand("etc/init.d/networking restart");
    client.Disconnect();
}


text:
Q: lightest ubunto flavor for distance learning with almost every school having distance learning and many of my friends and families looking to get either a new laptop or iPad just to use it for chrome & google classroom or MS-Teams app, I thought of doing and installfest for old laptops they have to make them faster to be used for this single use only.
I was wondering from your vast experience which flavor would do the job? I remember testing xubuntu in old days but being far from the recent developments maybe there is something else? for example lubuntu? or even lighter (chrome/firefox + Microsoft Teams app?)
Most of those old laptops run on low ram and CPU and never on SSD as you know (core 2 duo 2GB RAM or less)
I had an initiative to install regular Ubuntu on a thumbdrive and wanted to clone it for them, but flashdrives are super slow when they start using SWAP.
any recommendations is highly welcome even if it was flashdrive/external USB drive or any other crazy idea you might have :)
Thank you

A: Lubuntu 18.04 would work with these laptops, and is quite light. It would be supported till 2021. Even after that, it will be much safer to use it than Windows. You would still be able to use latest browsers with snap/flatpak.
The issue is that MS Teams is a bloatware. It alone consumes more than 1 GB of RAM. Recent versions of Chromium and Firefox also consume a lot of RAM.
However, as mentioned in the comments, you can look for lighter distros, which are not official flavors of Ubuntu.


text:
Q: how to secure rest api with query authentication I have a rest API which create by asp.net webservice, and I have an android and IOS application which call the api and show some data to the user.
what I need is to secure my API in a way that only my application can access to the data through the api and other request rejects.
I should mention that my application are not user base so there is no login and authentication and I don't want force user login !!!
According to my search, I need query authentication (query parameters) to achieve this.
What I need is how to create this kind of query parameters and how to validate them? (Performance is too important for me)
Thanks in advance

A: You can use basic authentication or any token based authentication mechanism.
So on every request to your api, get the authentication headers(authenticiation tokens in http request header) and verify if client is allowed to invoke it. If it failed then send by necessary HTTP status code. You just need to ensure that the applications that you want to allow to call your api are using those security tokens in their request headers. And you can keep those credentials or security tokens in memory or file or db as you like.

A: I am not a security expert, but as far as I know what you want is not possible. Anything you embed on the client to authenticate your application is accessible to an attacker, who can than use that information to access your API.


text:
Q: Does Snowflake variables in UDF need to be in uppercase? I created a UDF to test this point:
CREATE OR REPLACE function EDW_WEATHER.CHK_READING(p_reading VARCHAR2, P_SENSOR VARCHAR2 )
  RETURNS VARCHAR2
  LANGUAGE JAVASCRIPT
AS
$$
    if (P_SENSOR == 'A') return p_reading;
$$
;

It runs correctly:
select EDW_WEATHER.CHK_READING('A', 'B');

By simply lowercasing the variable P_SENSOR as:
CREATE OR REPLACE function EDW_WEATHER.CHK_READING(p_reading VARCHAR2, p_sensor VARCHAR2 )
  RETURNS VARCHAR2
  LANGUAGE JAVASCRIPT
AS
$$
    if (p_sensor == 'A') return p_reading;
$$
;

I get this when I run the UDF:

100132 (P0000): JavaScript execution error: Uncaught ReferenceError:
p_sensor is  not defined in CHK_READING at 'if (p_sensor == 'A')
return p_reading;' position  0

My question is whether Snowflake really require variables (used in "if" or "case" statements) to be in uppercase, or am I doing something wrong.

A: So there are two things. One is your session's handling of database object names. Which defaults to all objects are upper case by default (aka case does not matter), and in that context using double quotes, will mean "how I have the case is the intended case to use, also white space and other stuff is ok in here". This can be changed by session variables, but that leads to all sorts of troubles with views that using quotes and the case being respected an not for different sessions.
Then there is where that name convention behavior interacts/intersects with UDF code, where by case matters, and Snowflake have gone with "the objects true name is what it needs to be called in the JavaScript.
So if you are accessing passed in parameter and you do not double quote it's name (when you declare it), you will always have to refer to it SHOUTING style. But if you use the double quotes on the variable names when declaring the function (in a session where "quotes are respected") then you can have lower case variables in your javascript, which I show in the second example.
thus normally this function
CREATE OR REPLACE function EDW_WEATHER.CHK_READING(p_reading VARCHAR2, p_sensor VARCHAR2 )

the inputs are only P_READING & P_SENSOR
and here in this case
CREATE OR REPLACE function EDW_WEATHER.CHK_READING("p_reading" VARCHAR2, "p_SeNsOr" VARCHAR2 )

the input are only p_reading & p_SeNsOr
so you could change your function like this
CREATE OR REPLACE function CHK_READING("p_reading" VARCHAR2, "p_sensor" VARCHAR2 )
  RETURNS VARCHAR2
  LANGUAGE JAVASCRIPT
AS
$$
    if (p_sensor == 'A') return p_reading;
$$
;

and then happiness is true!
select CHK_READING('A', 'B');

see above how you named the function an object CHK_READING you can also call it via chk_reading because in SQL case (by default) does not matter.
So the last part: you question:

My question is whether Snowflake really require variables (used in "if" or "case" statements) to be in uppercase, or am I doing something wrong.

it is not a matter of things in IFs or CASEs, but when you use the input varaible.

A: As mentioned by the doc here:
https://docs.snowflake.com/en/developer-guide/udf/javascript/udf-javascript-introduction.html#javascript-arguments-and-returned-values

Note that an unquoted identifier must be referenced with the capitalized variable name.


text:
Q: How to refresh my data from parent component? Hi I want refresh my timestamp value from parent component.
My parentComponent.ts
public updateComponent(){
    this.timestamp = new Date();
    this.timestamp.setDate(this.timestamp.getDate() - 30);
    this.timestamp = this.timestamp.toJSON();
}

public ngOnInit() {
  this.updateComponent();
  interval(10000).subscribe(() => {
      console.error('called');
      console.error(this.timestamp);
      this.updateComponent();
  });

}

//my parent.component.html
<app-dashboard-card [refresh]="timestamp"></app-dashboard-card>

//When I catch my data
private ts: any;

@Input()
set refresh(timestamp: any) {
  console.error("TIMESTAMP CHANGE -> ", timestamp);
  this.ts = timestamp;
};

I don't know why my @Input don't catch when timestamp change.

A: Your code seems working here just using setInterval().

Suggestion: you can achieve the same without using setter here; simply get your timestamp in your child component as follows -

@Input() timestamp: any;

ngOnChanges() {
    console.log("TIMESTAMP CHANGE -> ", this.timestamp);
}

Note: Remember to check console for logs.

A: ngOnChanges() is called when the reference of object is changed in parent component
  import { Input, SimpleChanges } from "@angular/core";

  ngOnChanges(changes: SimpleChanges) {
    if (changes['refresh']) {
      //do something after value change
    }
  }


text:
Q: swift cocoa (OSX) IBAction in one window fails calling function in independent windows NSView I feel a little less than Swift asking this one but I have become exhausted going in circles on the Swift / Obj-C function calls. This is OSX (Coacoa/AppKit), not IOS where documentation is much more available. We are dealing with NSViews and controllers, not UIViews and controllers.
The problem is surely something basic I am missing, so apologies for this frustration generated question.
Below is the code in a testing prototype OSX App. It is located in the NSViewController for one of the two NSViewControllers contained in the main SplitView controller. It services testing buttons which I place via storyboard in that view. The action code is a standard "switch based on button.title" approach. The first case "Timer Window" successfully launches the independent window set up in storyboard which contains a storyboard generated view contoller.
The second case "Start Timer" calls a function in "ProgressView" which is the actual custom NSView for that new window. It fails with a "missing argument for parameter #1 in call" even though the actual function (also shown below) takes none.
What I know:

*

*The function being called works just fine when it is called from withing the the "ProgressView" class itself - I am simply trying to invoke it from a button in a separate window (storyboard requires the IBAction to be in the controller for the view where the button is located).

*"ProgressView" does appear to be the object instantiated by Storyboard since changing it to "progressView" changes the error to "unresolved identifier".

*I cannot find definitive documentation to confirm the naming conventions of storyboard instantiations so the item 2 conclusion is "an assumption".
Here is the controller code:
  var graphicsController: NSWindowController?
   @IBAction func launchTimer(sender: NSButton)
   {
      let destOp = sender.title
      switch destOp
  {
  case "Timer Window":
     if !(graphicsController != nil)
     {
        let storyboard = NSStoryboard(name: "Main", bundle: nil)
        graphicsController = storyboard?.instantiateControllerWithIdentifier("TimerGraphics") as? NSWindowController
        if graphicsController != nil { graphicsController!.showWindow(sender)            }
     }
  case "Start Timer":
     ProgressView.startTicTimer()
  default: println("Missing Button Press action for: \(destOp)")

      }
   }

Here is the function from the custom NSView class ProgressView that is the target finction to be invoked:
   func startTicTimer() {
      timer = NSTimer.scheduledTimerWithTimeInterval (0.08333333333333,     target:self, selector: "updateTimer", userInfo: nil, repeats: true)
      animateStroke(15.0)
      animatePosition(15.0)
   }

Any thoughts greatly appreciated, I have tried many things and just keep hitting the wall. That's why I suspect I'm having a huge blind spot here.

A: DUH! I am know that "ProgressView" is the class, not an instance. It was only being burned out from my frustration with trying so many things (+ cryptic error msg) that ended up with the bad assumption noted above in items 2 & 3. Apple is not going to violate their own rule of starting Cap for class, lower case for instance. I simply have no idea what the instance name is or how to find it.
So that gets me back to the basic issue which put me on this death spiral, how do I know the object name to reference the instance that the builtin storyboard logic used when instantiating ProgressView? I will repost using that question.


text:
Q: MYSQL NOT IN Query not working unless hard coded I'm fairly new to Javascript and PHP so I have no idea what I'm doing for the most part. I'm trying to make a Room Booking System.
$booking_id = '';
if(isset($_POST['edit_button_booking'])){
    $booking_id = $_POST['edit_id'];
}

echo "<script>alert('$booking_id')</script>";

$today_date = date('Y-m-d');
$room_query = "SELECT * FROM rooms";
$room_run = $conn->query($room_query);
if($room_run->num_rows>0){
    $options = mysqli_fetch_all($room_run, MYSQLI_ASSOC);
}

$start_from = 8;
$end_from = 21;
$start_to = $start_from+1;
$end_to = $end_from+1;
$from_booked = [];
$to_booked = [];
if(isset($_POST['value'])){
    $room_id = $_POST['value'];
    $specify_query = "SELECT * FROM rooms WHERE room_id = '$room_id'";
    $specify_run = $conn->query($specify_query);
    $row = mysqli_fetch_assoc($specify_run);
    $room_name = $row['room_name'];
    $disable_query = "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '$today_date' AND room_id = '$room_id' AND booking_id NOT IN (SELECT booking_id FROM booking WHERE booking_id = '$booking_id')";
    $disable = $conn->query($disable_query);
    if($disable->num_rows > 0){
        while($row = $disable->fetch_assoc()){
            $from_booked_hour = date_parse($row['booking_start'])['hour'];
            $to_booked_hour = date_parse($row['booking_end'])['hour'];
            $from_booked = array_merge($from_booked, range($from_booked_hour, $to_booked_hour-1));
            $to_booked = array_merge($to_booked, range($from_booked_hour+1, $to_booked_hour));
        }
    }
}

This is my code. What this code is supposed to do is to display the booked time slots for the room except for the chosen time slot.

And yet, it keeps on displaying both booked times when I want the 9 -12 time slot to be omitted from the time table
The alert that I used show that $booking_id has the value '000053' which is the id of the booking that I want not shown in the time table.
If I were to hard code it to $booking_id = '000053' or $booking_id = 53, it works.
$booking_id = '';
if(isset($_POST['edit_button_booking'])){
    $booking_id = $_POST['edit_id'];
}

$booking_id = 53;

echo "<script>alert('$booking_id')</script>";

$today_date = date('Y-m-d');
$room_query = "SELECT * FROM rooms";
$room_run = $conn->query($room_query);
if($room_run->num_rows>0){
    $options = mysqli_fetch_all($room_run, MYSQLI_ASSOC);
}

$start_from = 8;
$end_from = 21;
$start_to = $start_from+1;
$end_to = $end_from+1;
$from_booked = [];
$to_booked = [];
if(isset($_POST['value'])){
    $room_id = $_POST['value'];
    $specify_query = "SELECT * FROM rooms WHERE room_id = '$room_id'";
    $specify_run = $conn->query($specify_query);
    $row = mysqli_fetch_assoc($specify_run);
    $room_name = $row['room_name'];
    $disable_query = "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '$today_date' AND room_id = '$room_id' AND booking_id NOT IN (SELECT booking_id FROM booking WHERE booking_id = '$booking_id')";
    $disable = $conn->query($disable_query);
    if($disable->num_rows > 0){
        while($row = $disable->fetch_assoc()){
            $from_booked_hour = date_parse($row['booking_start'])['hour'];
            $to_booked_hour = date_parse($row['booking_end'])['hour'];
            $from_booked = array_merge($from_booked, range($from_booked_hour, $to_booked_hour-1));
            $to_booked = array_merge($to_booked, range($from_booked_hour+1, $to_booked_hour));
        }
    }
}

I don't know what is causing this issue. Any help will be appreciated.
The var_dump of both queries are as follows:
Generated SQL:
string(156) "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '2022-07-22' AND room_id = '1' AND booking_id != '53'"

Hard Coded:
string(156) "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '2022-07-22' AND room_id = '1' AND booking_id != '53'"

UPDATE:
The var_dump()'s I posted earlier were outside of the if(isset($_POST['value'])) block since I thought the variable $booking_id can be accessed in the if block as well. I tried to use var_dump() inside the if block and it turned out that the $booking_id was turning up blank.
string(154) "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '2022-07-22' AND room_id = '1' AND booking_id != ''"

This was the result of the var_dump() running inside of the if block. I don't understand why it is doing this though. My $today_date variable was defined outside of the if block as well and that's working.


text:
Q: Mixing read() and write() on Python files in Windows It appears that a write() immediately following a read() on a file opened with r+ (or r+b) permissions in Windows doesn't update the file.
Assume there is a file testfile.txt in the current directory with the following contents:
This is a test file.

I execute the following code:
with open("testfile.txt", "r+b") as fd:
    print fd.read(4)
    fd.write("----")

I would expect the code to print This and update the file contents to this:
This----a test file.

This works fine on at least Linux. However, when I run it on Windows then the message is displayed correctly, but the file isn't altered - it's like the write() is being ignored. If I call tell() on the filehandle it shows that the position has been updated (it's 4 before the write() and 8 afterwards), but no change to the file.
However, if I put an explicit fd.seek(4) just before the write() line then everything works as I'd expect.
Does anybody know the reason for this behaviour under Windows?
For reference I'm using Python 2.7.3 on Windows 7 with an NTFS partition.
EDIT
In response to comments, I tried both r+b and rb+ - the official Python docs seem to imply the former is canonical.
I put calls to fd.flush() in various places, and placing one between the read() and the write() like this:
with open("testfile.txt", "r+b") as fd:
    print fd.read(4)
    fd.flush()
    fd.write("----")

... yields the following interesting error:
IOError: [Errno 0] Error

EDIT 2
Indirectly that addition of a flush() helped because it lead me to this post describing a similar problem. If one of the commenters on it is correct, it's a bug in the underlying Windows C library.

A: Python's file operation should follow the libc convention as internally its implemented using C file IO functions.
Quoting from fopen man page or fopen page in cplusplus

For files open for appending (those which include a "+" sign), on
  which both input and output operations are allowed, the stream should
  be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between
  either a writing operation followed by a reading operation or a
  reading operation which did not reach the end-of-file followed by a
  writing operation.

SO to summarize, if you need to read a file after writing, you need to fflush the buffer and a write operation after read should be preceded by a fseek, as fd.seek(0, os.SEEK_CUR)
So just change your code snippet to
with open("test1.txt", "r+b") as fd:
    print fd.read(4)
    fd.seek(0, os.SEEK_CUR)
    fd.write("----")

The behavior is consistent with how a similar C program would behave
#include <cstdio>
int main()
{
    char  buffer[5] = {0};
    FILE *fp = fopen("D:\\Temp\\test1.txt","rb+");
    fread(buffer, sizeof(char), 4, fp);
    printf("%s\n", buffer);
    /*without fseek, file would not be updated*/
    fseek(fp, 0, SEEK_CUR);
    fwrite("----",sizeof(char), 4, fp);
    fclose(fp);
    return 0;
}

A: It appears that this due to the behaviour of the underlying Windows libraries (which personally I regard to be in error) and nothing wrong with Python. On adding a flush() call between reading and writing (which is apparently good practice) I got an IOError with a zero errno, which is the same issue as discussed in this blog post.
From that post I found this Python issue which mentions the problem and says that the seek() call is actually the best workaround, along with a flush() every time you change from reading to writing.
All that taken into account, it seems the best way to write the code above such that it successfully runs on Windows is:
with open("testfile.txt", "r+b") as fd:
    print fd.read(4)
    fd.flush()
    fd.seek(4)
    fd.write("----")

Might be something to bear in mind for anybody attempting to write portable code.

A: have you tried flushing ?
fd.flush()

it is OS-dependant, as write uses the filesystem caching mechanism

A: Is it possible that the implementation missinterpretest "r+b"? Afaik "rb+" is for reading and writing in binary.


text:
Q: pkg_resources.DistributionNotFound: grpcio not found Traceback (most recent call last):
  File "txt_img.py", line 4, in <module>
    from google.cloud import vision
  File "/home/ram/.local/lib/python2.7/site-packages/google/cloud/vision.py", line 20, in <module>
    from google.cloud.vision_v1 import enums
  File "/home/ram/.local/lib/python2.7/site-packages/google/cloud/vision_v1/__init__.py", line 22, in <module>
    from google.cloud.vision_v1.gapic import image_annotator_client as iac
  File "/home/ram/.local/lib/python2.7/site-packages/google/cloud/vision_v1/gapic/image_annotator_client.py", line 18, in <module>
    import google.api_core.gapic_v1.client_info
  File "/home/ram/.local/lib/python2.7/site-packages/google/api_core/gapic_v1/__init__.py", line 15, in <module>
    from google.api_core.gapic_v1 import client_info
  File "/home/ram/.local/lib/python2.7/site-packages/google/api_core/gapic_v1/client_info.py", line 26, in <module>
    _GRPC_VERSION = pkg_resources.get_distribution('grpcio').version
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 344, in get_distribution
    if isinstance(dist,Requirement): dist = get_provider(dist)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 223, in get_provider
    return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 725, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/usr/lib/enter code herepython2.7/dist-packages/pkg_resources.py", line 628, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: grpcio

when i am installing grpcio
pip install grpcio

then it's giving error like below:
pip can't proceed with requirement 'grpcio' due to a pre-existing build directory.
 location: /tmp/pip_build_ram/grpcio
This is likely due to a previous installation that failed.
pip is being responsible and not assuming it can delete this.
Please delete it and try again.

Storing debug log for failure in /tmp/tmpDEmkZc

i deleted "/tmp/pip_build_ram/grpcio" and tried again but not working.


text:
Q: Spring Boot SessionScoped Object not expired after logout. Autowires two different objects in different controllers I needed to auto wire logged in User Object in my controller /service classes. So i created a util Bean as
@Component
public class UtilBeans {
    @Autowired
    UserService userService;

    @Bean(name = "loggedInUser")
    @SessionScope
    public UserMaster userMaster() {
        UserMaster user;
        try {
            user = (UserMaster) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            user.setAuthorities(userService.getUserAuthorities(user.getUserId()));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("user Not logged in");

        }
        return user;
    }
}

and used in controller class as
@Autowired
    @Qualifier(value = "loggedInUser")
    UserMaster user;

In  most controllers  it works OK, but in some controllers first logged in user object doesn't change until I restart the application.
my logout configuration is as follows
.formLogin().loginPage("/loginForm").permitAll()
                .and()
                .formLogin().defaultSuccessUrl("/dashboard").and()

                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .deleteCookies("JSESSIONID").clearAuthentication(true)
                .invalidateHttpSession(true).permitAll();

Please help me where I am doing wrong. What I understand is , Session Scoped object should expire on logout, and it do changes but why not in some cases.

A: I by mistake assigned a different object of same type and same id to user in controller, changing code to remove that assignment fixed the problem.


text:
Q: Align Image with 1 line inline elements I am having a problem with my image alignment. I want my image to align with inline elements in a specific way.
This is what I have now:
                ######################
                #                    #
                #                    #
                #       image        #
                #                    #
                #                    #
inline elements ######################

but I want:
inline elements ######################
                #                    #
                #                    #
                #       image        #
                #                    #
                #                    #
                ######################

Is there anyway to do with with CSS?

A: Just assign vertical-align: top to the image's CSS.
http://codepen.io/anon/pen/zBKpmJ

A: Use below CSS for image -  position:absolute
    img{
  position:absolute;
   }

codepen-http://codepen.io/pen/

A: css float:left on the inline element. See fiddle
https://jsfiddle.net/djLqudmt/2/


text:
Q: Drag n Drop Operations across MDI Child Forms I am trying to perform a simple drag-n-drop operation starting from one button in one MDI child form to another button in a different MDI child form. For some reason however the DragDrop event never gets fired when I attempt to drag one button to the other. It may be worth noting that when I drag the button my cursor becomes the black-cancel icon.
My code:
    #region ActivatesDragDropControl
    [DllImport ("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

    private const int WM_NCACTIVATE = 0x0086;
    #endregion
    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        DoDragDrop(LocationNode, DragDropEffects.Link);
        // to deactivate
        SendMessage(Handle, WM_NCACTIVATE, 0, 0);
    }
    private void button1_DragDrop(object sender, DragEventArgs e)
    {
        //never gets here...
    }
    private void button1_DragEnter(object sender, DragEventArgs e)
    {
        // to activate
        SendMessage(Handle, WM_NCACTIVATE, 1, 0);
    }

A: OK so I played around a bit more and using DragEnter isn't enough; I had to set the DragEventArgs' Event value. In my case:
e.Effect = DragDropEffects.Link;


text:
Q: I want to change dtype from object to int df['Value'] = [-2,254.00, 3,452.00, 15,698.00, -6,258.00]

The datatype is saying object. I would like to convert them into integers, but i am getting an error

A: Use df.astype:
In [2329]: df['Value'] = df['Value'].astype(int)

In [2329]: df['Value']
Out[2329]:
0     -2
1    254
2      3
3    452
4     15
5    698
6     -6
7    258
Name: Value, dtype: int64

A: you can try the following code:
df['Value'] = df['Value'].astype(dtype='int64')

A: Use pd.to_numeric with errors='coerce'
df['Value'] = pd.to_numeric(df['Value'], errors='coerce')


text:
Q: React doesn't update states when using formsy-react I am using formsy-react to handle validation of my input fields. Problem is that I can't update states. I followed example on formsy github page and validation is working but problem is that states are incorrect. They are always one step (or few) behind and I am not sure why...
I used callback on setState function to implement some custom logic on validation and that part doesn't work properly.
I have a situation where user enters email. After user enters email I check if email is already registrated. If user is already in system, I create new input component (password type) and if not I create new "input type email" component.
Since all forms elements are required I added one more validation check that checks if new password or email component is added and if there is any data.
To update states I used Forms form API call onChange() and this part is not working for unknown reason.
Does someone knows where is the problem?
This is code I am using:
Component Input (shorted version)
changeValue(event) {

    this.setValue(event.currentTarget.value);

},
render() {

    // Set a specific className based on the validation
    // state of this component. showRequired() is true
    // when the value is empty and the required prop is
    // passed to the input. showError() is true when the
    // value typed is invalid
    const className = (this.props.className || "col-md-4" );
    const classValidationName =this.isValid() ? 'valid' : this.showError() ? ' invalid' : null;

    // An error message is returned ONLY if the component is invalid
    // or the server has returned an error message
    const errorMessage = this.getErrorMessage();

    return (

                <input
                    className={classValidationName}
                    name={this.props.name}
                    id={this.props.id}
                    type={this.props.inputType}
                    value={this.getValue() || ""}
                    onChange={this.changeValue}
                    onBlur={this.props.controlFuncOnBlur}
                    placeholder={this.props.placeholder}
                    required={this.props.required}
                    pattern={this.props.pattern}
                />
                {this.props.title}

    );
}

Container (shorted version)
handleEmailBlur(event) {
    const self = this;

    if (this.refs.email.isValid) {
        axios.get('/api/checkIsUserRegistrated', {
            params: {
                email: this.state.email
            }
        })
            .then(function (response) {
                if (self.state.userExist !== response.data[0].userExist) {
                    self.setState({
                        userExist: response.data[0].userExist,
                        confirmEmail: "",
                        password: ""

                    });
                    self.forceUpdate();
                }

            })
            .catch(function (error) {
                console.log(error);
            });
    }
}

enableButton = () => {

    this.setState({
        formValid: true
    });
}

disableButton = () => {
    this.setState({
        formValid: false
    });
}
saveCurrentValuesToStates = (getCurrentValues, isChanged) => {
    console.log(this);
    this.setState(getCurrentValues, ()=> {
        if (this.state.formValid && (this.state.password || this.state.confirmEmail)){
            this.setState({
                canSubmitForm: true
            });
        }
        else{
            this.setState({
                canSubmitForm: false
            });
        }
    });
}

 <Formsy.Form className="booker-form" ref="form"
   onChange={this.saveCurrentValuesToStates} onValid={this.enableButton} onInvalid={this.disableButton}>

                            <SingleInput
                            inputType={'email'}
                            icon={'icon-Email'}
                            id={'email'}
                            name={'email'}
                            title={'E-mail'}
                            ref="email"
                            controlFuncOnBlur={this.handleEmailBlur}
                            content={this.state.email}
                            errorMessage={'Incorect E-Mail address'}
                            required
                            validations="isEmail"
                            validationError="This is not a valid email"
                        />
                        {(this.state.userExist === '0') ?
                            <SingleInput
                                inputType={'email'}
                                icon={'icon-Email'}
                                id={'confirmEmail'}
                                name={'confirmEmail'}
                                title={'Confirm your E-mail'}
                                content={this.state.confirmEmail}
                                required
                                validations="equalsField:email"
                                validationError="Emails don't match"

                            />
                            : null}
                        {(this.state.userExist === '1') ?
                            <SingleInput
                                inputType={'password'}
                                icon={'icon-Padlock'}
                                id={'password'}
                                name={'password'}
                                title={'Enter your password'}
                                content={this.state.password}
                                required

                            />
                            : null}


text:
Q: Getting error : Invalid property x set to -100 Missing plugin? gsap.registerPlugin() I'm trying to make an animation of my cards in my Vue application with GSAP. I tried to follow a codesandbox example I found earlier but I can't make it work with my app.
Here's the link
I have everything the same as in the example except that I'm not getting an array of HTMLDivElement with this.boxes.$refs.boxes but an array of VueComponent
When I'm trying to apply the gsap transformation with
this.tl = gsap
        .timeline()
        .from(
            this.boxes.$refs.boxes,
            {duration: 1, x: -100}
        );

I get an error in my web browser :

Invalid property x set to -100 Missing plugin? gsap.registerPlugin()

After looking on many forums I can't find a solution working for me.

After some search I finally ended up with this solution, I don't really know if this is a good way to do it and since it's a school project I don't want to spend too much time on it.
gsap
    .timeline()
    .from(
        ".anime-card",
        {y: -25, opacity:0, stagger: 0.1},

    );


text:
Q: Scala generic function with parsing object I need a function like this (sorry I need null)
def foo[T](json: JsonElement): T =
json match {
 case x: JsonObject => gson.fromJson(x, classOf[T])
 case _ => null
}

Of course this is can not compile :)
Help please!
upd
there are result functions
def parseObject[T: ClassTag](jo: JsonObject, gson: Gson, name: String): Option[T] = Option(jo.get(name)).map {
  case x: JsonObject =>
    val cTag = implicitly[ClassTag[T]]
    gson.fromJson(x, cTag.runtimeClass.asInstanceOf[Class[T]])

  case _ => null.asInstanceOf[T]
}

def parseArray[T: ClassTag](jo: JsonObject, gson: Gson, name: String): java.util.List[T] = Option(jo.get(name)).map {
  case x: JsonArray =>
    val cTag = implicitly[ClassTag[java.util.List[T]]]
    gson.fromJson(x, cTag.runtimeClass.asInstanceOf[Class[java.util.List[T]]])

  case _ => Collections.emptyList[T]
}.getOrElse(Collections.emptyList[T])

They are working well :)
Thanks a lot for everyone!
p.s.
last question
Is there are some way to transform this functions to parsePrimitive[T](jo: JsonObject, name: String): Option[T] = ???
def parseInteger(jo: JsonObject, name: String): Option[Integer] = Option(jo.get(name)).map {
  case x: JsonPrimitive => x.getAsInt
  case _ => null
}

def parseString(jo: JsonObject, name: String): Option[String] = Option(jo.get(name)).map {
  case x: JsonPrimitive => x.getAsString
  case _ => null
}

def parseBoolean(jo: JsonObject, name: String): Option[java.lang.Boolean] = Option(jo.get(name)).map {
  case x: JsonPrimitive => x.getAsBoolean
  case _ => null
}

A: Try this (using Option):

import scala.reflect.ClassTag
def foo[T : ClassTag](json: JsonElement): Option[T] = json match {
  case x: JsonObject =>
    val cTag = implicitly[ClassTag[T]]
    Some(gson.fromJson(x, cTag.runtimeClass.asInstanceOf[Class[T]]))
  case _ => None
}

Note that you will need to know what T is when calling the function.
If you really do need the null, then you can append .orNull when retrieving the result.
If you really, really, really must use null, then this ought to work:
import scala.reflect.ClassTag
def foo[T <: AnyRef : ClassTag](json: JsonElement): T = json match {
  case x: JsonObject =>
    val cTag = implicitly[ClassTag[T]]
    gson.fromJson(x, cTag.runtimeClass.asInstanceOf[Class[T]])
  case _ => null.asInstanceOf[T] // Required for some odd reason.
}

A: Good Scala style discourages the use of null. Beyond that the compiler restricts what types are null-able. Many primitives cannot be null (Int, Boolean, etc.).
The compiler doesn't know if the type T is null-able or not so what you've got is not allowed. If T can be context bound to some subset of null-able types this might be possible. (But Option[T] would still be better.)


text:
Q: Damerau - Levenshtein Distance, adding a threshold I have the following implementation, but I want to add a threshold, so if the result is going to be greater than it, just stop calculating and return.
How would I go about that?
EDIT: Here is my current code, threshold is not yet used...the goal is that it is used
    public static int DamerauLevenshteinDistance(string string1, string string2, int threshold)
    {
        // Return trivial case - where they are equal
        if (string1.Equals(string2))
            return 0;

        // Return trivial case - where one is empty
        if (String.IsNullOrEmpty(string1) || String.IsNullOrEmpty(string2))
            return (string1 ?? "").Length + (string2 ?? "").Length;

        // Ensure string2 (inner cycle) is longer
        if (string1.Length > string2.Length)
        {
            var tmp = string1;
            string1 = string2;
            string2 = tmp;
        }

        // Return trivial case - where string1 is contained within string2
        if (string2.Contains(string1))
            return string2.Length - string1.Length;

        var length1 = string1.Length;
        var length2 = string2.Length;

        var d = new int[length1 + 1, length2 + 1];

        for (var i = 0; i <= d.GetUpperBound(0); i++)
            d[i, 0] = i;

        for (var i = 0; i <= d.GetUpperBound(1); i++)
            d[0, i] = i;

        for (var i = 1; i <= d.GetUpperBound(0); i++)
        {
            for (var j = 1; j <= d.GetUpperBound(1); j++)
            {
                var cost = string1[i - 1] == string2[j - 1] ? 0 : 1;

                var del = d[i - 1, j] + 1;
                var ins = d[i, j - 1] + 1;
                var sub = d[i - 1, j - 1] + cost;

                d[i, j] = Math.Min(del, Math.Min(ins, sub));

                if (i > 1 && j > 1 && string1[i - 1] == string2[j - 2] && string1[i - 2] == string2[j - 1])
                    d[i, j] = Math.Min(d[i, j], d[i - 2, j - 2] + cost);
            }
        }

        return d[d.GetUpperBound(0), d.GetUpperBound(1)];
    }
}

A: This is Regarding ur answer this: Damerau - Levenshtein Distance, adding a threshold
(sorry can't comment as I don't have 50 rep yet)
I think you have made an error here. You initialized:
var minDistance = threshold;

And ur update rule is:
if (d[i, j] < minDistance)
   minDistance = d[i, j];

Also, ur early exit criteria is:
if (minDistance > threshold)
   return int.MaxValue;

Now, observe that the if condition above will never hold true! You should rather initialize minDistance to int.MaxValue

A: Here's the most elegant way I can think of. After setting each index of d, see if it exceeds your threshold. The evaluation is constant-time, so it's a drop in the bucket compared to the theoretical N^2 complexity of the overall algorithm:
public static int DamerauLevenshteinDistance(string string1, string string2, int threshold)
{
    ...

    for (var i = 1; i <= d.GetUpperBound(0); i++)
    {
        for (var j = 1; j <= d.GetUpperBound(1); j++)
        {
            ...

            var temp = d[i,j] = Math.Min(del, Math.Min(ins, sub));

            if (i > 1 && j > 1 && string1[i - 1] == string2[j - 2] && string1[i - 2] == string2[j - 1])
                temp = d[i,j] = Math.Min(temp, d[i - 2, j - 2] + cost);

            //Does this value exceed your threshold? if so, get out now
            if(temp > threshold)
              return temp;
        }
    }

    return d[d.GetUpperBound(0), d.GetUpperBound(1)];
}

A: You also asked this as a SQL CLR UDF question so I'll answer in that specific context: you best optmiziation won't come from optimizing the Levenshtein distance, but from reducing the number of pairs you compare. Yes, a faster Levenshtein algorithm will improve things, but not nearly as much as reducing the number of comparisons from N square (with N in the millions of rows) to N*some factor. My proposal is to compare only elements who have the length difference within a tolerable delta. On your big table, you add a persisted computed column on LEN(Data) and then create an index on it with include Data:
ALTER TABLE Table ADD LenData AS LEN(Data) PERSISTED;
CREATE INDEX ndxTableLenData on Table(LenData) INCLUDE (Data);

Now you can restrict the sheer problem space by joining within an max difference on lenght (eg. say 5), if your data's LEN(Data) varies significantly:
SELECT a.Data, b.Data, dbo.Levenshtein(a.Data, b.Data)
FROM Table A
JOIN Table B ON B.DataLen BETWEEN A.DataLen - 5 AND A.DataLen+5

A: Finally got it...though it's not as beneficial as I had hoped
    public static int DamerauLevenshteinDistance(string string1, string string2, int threshold)
    {
        // Return trivial case - where they are equal
        if (string1.Equals(string2))
            return 0;

        // Return trivial case - where one is empty
        if (String.IsNullOrEmpty(string1) || String.IsNullOrEmpty(string2))
            return (string1 ?? "").Length + (string2 ?? "").Length;

        // Ensure string2 (inner cycle) is longer
        if (string1.Length > string2.Length)
        {
            var tmp = string1;
            string1 = string2;
            string2 = tmp;
        }

        // Return trivial case - where string1 is contained within string2
        if (string2.Contains(string1))
            return string2.Length - string1.Length;

        var length1 = string1.Length;
        var length2 = string2.Length;

        var d = new int[length1 + 1, length2 + 1];

        for (var i = 0; i <= d.GetUpperBound(0); i++)
            d[i, 0] = i;

        for (var i = 0; i <= d.GetUpperBound(1); i++)
            d[0, i] = i;

        for (var i = 1; i <= d.GetUpperBound(0); i++)
        {
            var im1 = i - 1;
            var im2 = i - 2;
            var minDistance = threshold;

            for (var j = 1; j <= d.GetUpperBound(1); j++)
            {
                var jm1 = j - 1;
                var jm2 = j - 2;
                var cost = string1[im1] == string2[jm1] ? 0 : 1;

                var del = d[im1, j] + 1;
                var ins = d[i, jm1] + 1;
                var sub = d[im1, jm1] + cost;

                //Math.Min is slower than native code
                //d[i, j] = Math.Min(del, Math.Min(ins, sub));
                d[i, j] = del <= ins && del <= sub ? del : ins <= sub ? ins : sub;

                if (i > 1 && j > 1 && string1[im1] == string2[jm2] && string1[im2] == string2[jm1])
                    d[i, j] = Math.Min(d[i, j], d[im2, jm2] + cost);

                if (d[i, j] < minDistance)
                    minDistance = d[i, j];
            }

            if (minDistance > threshold)
                return int.MaxValue;
        }

        return d[d.GetUpperBound(0), d.GetUpperBound(1)] > threshold
            ? int.MaxValue
            : d[d.GetUpperBound(0), d.GetUpperBound(1)];
    }


text:
Q: add namespace tag to root element asmx C# Good day.
i am hoping someone could possibly assist me. i am creating an asmx web service. i have written all the classes to send a response back in soap xml. i only have one issue currently that i cannot seem to overcome. i have done quite a bit searching and have tried several options but have not managed to make the desired changes i need.
i require that the root node has an namespace tag, but i cannot figure out how to achieve this. currently i get an output like below.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <RequestResponse xmlns="https://web.com/">
            <RequestResult>
                <ServerVersion>1.0</ServerVersion>
            </RequestResult>
        </RequestResponse>
    </soap:Body>
</soap:Envelope>

but i require the format in with the following.
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <ns:RequestResponse xmlns:ns="https://web.com/">
            <RequestResult>
                <ServerVersion>1.0</ServerVersion>
            </RequestResult>
        </ns:RequestResponse>
    </soap:Body>
</soap:Envelope>

i require <ns:RequestResponse xmlns:ns="https://web.com/"> "ns:tag"
my class looks like the below.
namespace Requester
{
    [XmlRoot(Namespace = "https://web.com/")]
    public class RequestResponse
    {

        public string ServerVersion
        {
            get;
            set;
        }
    }
}

as you can see, i have tried adding the XMLRoot and Namespace,  but the output remains the same.
i have seen on many places that it is not really required, but i have a client who insists this be in place. i have even seen this article by Scott Hanselman which seems to be exactly what i am looking for.
https://www.hanselman.com/blog/XmlRootForcePrefixPrefixfoo.aspx
any assistance would be greatly appreciated.
i have looked over a good number of pages here on Stack overflow but none have helped me achieve this change thus far. i apologies if this is a duplicate, however i cannot get the desired change


text:
Q: related to getting data in frontend from backend server part
router.get("/getuserdata",verifyuser,(req,res)=>{
 res.json({user:req.rootuser});
console.log(req.rootuser);
})

frontend part
 const callabout=async ()=>{
   try{
       const res=await fetch("http://localhost:8800/api/users/getuserdata",{
        mode:"no-cors",
         method:"GET",
         headers:{
          Accept:"appllication/json",
           "Content-Type":"application/json"
       },
         credentials:"include",

      })

    const data=await res.json();
    console.log(data);

      if(!res.status===200){
     const error=new Error(res.error);
     throw error;

     }}
     catch(err){
     console.log(err);
     navigate("/Login")
    }

     }

i want my user data in my front end after login but its not giving data.An error is occuring "unexepexted end of input" while compiling through const data = await res.json(); in frontend part.
please help me


text:
Q: Hide form action value in the URL in JSP I am creating a web application in Java. I created some JSP pages each having some form fields. All are post method type so it hides all the form fields. In each page it will call servlet and forward to next JSP page(like a step by step process.)) Welcome page is index.jsp. In the last JSP page also I am having form field which is also post method type. When I press sumbit button, it will call servlet and should forwartd to home page(That is index.jsp).
Last page action value is finish. In my servlet, I am using RequestDispatcher and forwarding to index.jsp. The the URL will be
http://localhost:8080/myproject/finish.
As it is the home page, I wanted to hide that action value. So instead of RequestDispatcher I used
response.sendRedirect("index.jsp"); And then URL becomes
http://localhost:8080/myproject/index.jsp.
This is not a big issue. But still I am asking is there anyway to hide this index.jsp in the URL? It should be like when we open the site for the first time(http://localhost:8080/myproject/).

A: I got the answer finally. Thanks to @Sayem Ahmed for his reply as comments.
I tried this only
response.sendRedirect("/myproject");