text:
Q: CURL request to kafka-rest I have executed HTTP POST on kafka-rest using curl call. one request is successful but another request (with different json) is returned 422 error ({"error_code":422,"message":"Unrecognized field: receiver"}).
Working request
    curl -X POST -H "Content-Type: application/vnd.kafka.json.v2+json" -H "Accept: application/vnd.kafka.v2+json" --data '{"records":[{"value":{"foo":"bar"}}]}' "http://localhost:8082/topics/jsontest"

Outout
{"offsets":[{"partition":0,"offset":0,"error_code":null,"error":null}],"key_schema_id":null,"value_schema_id":null}

Not working request
 curl -X POST -H "Content-Type: application/vnd.kafka.json.v2+json" -H "Accept: application/vnd.kafka.v2+json" --data @alert-request.json "http://localhost:8082/topics/jsontest"

Output
{"error_code":422,"message":"Unrecognized field: receiver"}

alert-request.json
{
  "receiver": "email-logs",
  "status": "firing",
  "alerts": [
    {
      "status": "firing",
      "labels": {
        "alertname": "CPUUsageAbove20%",
        "instance": "node-exporter:9100",
        "job": "node-exporter",
        "monitor": "my-project",
        "severity": "warn",
        "team": "raptors"
      },
      "annotations": {
        "dashboard": "www.prometheus.io",
        "description": "CPU usage on node-exporter:9100 has reached 60"
      },
      "startsAt": "2020-04-30T08:03:17.309164516Z",
      "endsAt": "0001-01-01T00:00:00Z",
      "generatorURL": "http://0ab6d9955c65:9090/graph?g0.expr=60+%3E+job%3Anode_cpu_seconds%3Ausage+%3E+20\u0026g0.tab=1",
      "fingerprint": "9c558a8c20c2ba08"
    }
  ],
  "groupLabels": {
    "alertname": "CPUUsageAbove20%",
    "team": "raptors"
  },
  "commonLabels": {
    "alertname": "CPUUsageAbove20%",
    "instance": "node-exporter:9100",
    "job": "node-exporter",
    "monitor": "my-project",
    "severity": "warn",
    "team": "raptors"
  },
  "commonAnnotations": {
    "dashboard": "www.prometheus.io",
    "description": "CPU usage on node-exporter:9100 has reached 60"
  },
  "externalURL": "http://5493399b56dc:9093",
  "version": "4",
  "groupKey": "{}/{team=~\"^(?:(raptors|leafs))$\"}:{alertname=\"CPUUsageAbove20%\", team=\"raptors\"}"
}

I need to write above json to kafka using kafka-rest, and i use curl call to perform HTTP post on kafka-rest but it's returning error. how to successfully write to kafka using kafka-rest (using curl)?.

A: The error code in the response as "error_code":422 means that the request payload is incorrect.
According the API spec of kafka-rest, the one of the valid request payload structure is
{
  "records": [
    {
      "key": "recordKey",
      "value": "recordValue"
    }
  ]
}

So your alert-request.json file should be modified with the contents under the value field inside records
{
  "records": [
    {
      "key": "recordKey",
      "value": {
        "receiver": "email-logs",
        "status": "firing",
        "alerts": [
          {
            "status": "firing",
            "labels": {
              "alertname": "CPUUsageAbove20%",
              "instance": "node-exporter:9100",
              "job": "node-exporter",
              "monitor": "my-project",
              "severity": "warn",
              "team": "raptors"
            },
            "annotations": {
              "dashboard": "www.prometheus.io",
              "description": "CPU usage on node-exporter:9100 has reached 60"
            },
            "startsAt": "2020-04-30T08:03:17.309164516Z",
            "endsAt": "0001-01-01T00:00:00Z",
            "generatorURL": "http://0ab6d9955c65:9090/graph?g0.expr=60+%3E+job%3Anode_cpu_seconds%3Ausage+%3E+20\u0026g0.tab=1",
            "fingerprint": "9c558a8c20c2ba08"
          }
        ],
        "groupLabels": {
          "alertname": "CPUUsageAbove20%",
          "team": "raptors"
        },
        "commonLabels": {
          "alertname": "CPUUsageAbove20%",
          "instance": "node-exporter:9100",
          "job": "node-exporter",
          "monitor": "my-project",
          "severity": "warn",
          "team": "raptors"
        },
        "commonAnnotations": {
          "dashboard": "www.prometheus.io",
          "description": "CPU usage on node-exporter:9100 has reached 60"
        },
        "externalURL": "http://5493399b56dc:9093",
        "version": "4",
        "groupKey": "{}/{team=~\"^(?:(raptors|leafs))$\"}:{alertname=\"CPUUsageAbove20%\", team=\"raptors\"}"
      }
    }
  ]
}

Do note that the key field is optional and you can provide any unique key that suits your use-case.


text:
Q: Receive data from an api and display it on html I try to do a call API and i would like to show a number of my datas.
My data arrives in tabular.
Currently i have a [objet : Objet]
console.log(this.data) =
1: {products_id: 6128961, products_date_added: "2016-10-04T00:00:00+02:00"}
2: {products_id: 6129048, products_date_added: "2016-10-05T00:00:00+02:00"}
Children component.html :
        <mat-icon>
{{datas.length}}
</mat-icon>

Chiledren component.ts
@Input() counterDatasObservable: Observable<any>;
  data = [];

  constructor() {}

  ngOnInit() {
    this.counterDatasObservable.subscribe( datas => {
      this.data = datas;
      console.log(this.data);
      console.log('jesuis là');

    });

Parent component.html:
        <app-counter [counterDatasObservable]="dataMlsService.getProducts('EnCours', 'Location')"></app-counter>

My solution is here :
<mat-icon *ngIf='data'>{{data.length}}</mat-icon>

A: Children component does not know about datas, in html you should use data and not datas variable
something like
<mat-icon>
{{data.length}}
</mat-icon>

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql index cardinality I have x row count, but all index cardinarlities are much greater than x, how is this possible?  If I understand correctly, index cardinality is the number of unique rows of that index.

A: From SHOW INDEX:

Cardinality
  An estimate of the number of unique values in the index. This is updated by running ANALYZE TABLE or myisamchk -a. Cardinality is counted based on statistics stored as integers, so the value is not necessarily exact even for small tables.

A: cardinality is not the number of distinct values of an index.
rather it is the count of noded in the Btree of the index.
for exampls you created a btree with numbers 1 to 10, you got some 5 nodes and 5 leaves.
then your index cardinality can never be more than 5(nodes count)
YES, cardinality can be more than number of rows. This happens when you have index on more than one column. In this case it tries to build a tree with the combination of attributes in the composite index and cadinality will be more than number of rows
Hope U understood...
Regards,
UDAY.


text:
Q: Преобразование изображения cv::Mat в point cloud. Работаю с библиотекой opencv, pcl c++ linux Вот мой код, в котором я пытаюсь преобразовать стерео изображение в облако точек. Но конечный результат неверен. Точнее координаты, по которым я выстраиваю конечный результат - cv::Mat coords(3, image.cols * image.rows, CV_64FC1);. Подскажите, пожалуйста, что я делаю не так?
#include <iostream>
#include <thread>

#include "imageset.h"
#include "fileloader.h"
#include "consumer.h"

#include <opencv2/highgui.hpp>

#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>

#include <pcl/PCLHeader.h>
#include <pcl/pcl_macros.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/statistical_outlier_removal.h>

#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;
namespace fs = boost::filesystem;
using namespace pcl;

void draw_cloud(const std::string &text, const pcl::PointCloud<pcl::PointXYZRGB>::Ptr &cloud)
{
    pcl::visualization::CloudViewer viewer(text);
    viewer.showCloud(cloud);
    while (!viewer.wasStopped())
    {
    }
}

pcl::PointCloud<pcl::PointXYZRGB>::Ptr MatToPoinXYZ(cv::Mat depthMat)
{
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr ptCloud (new pcl::PointCloud<pcl::PointXYZRGB>);

// calibration parameters
    float const fx_d = 5.9421434211923247e+02;
    float const fy_d = 5.9104053696870778e+02;
    float const cx_d = 3.3930780975300314e+02;
    float const cy_d = 2.4273913761751615e+02;

    unsigned char* p = depthMat.data;
    for (int i = 0; i<depthMat.rows; i++)
    {
    for (int j = 0; j < depthMat.cols; j++)
    {
        float z = static_cast<float>(*p);
        pcl::PointXYZRGB point;
        point.z = 0.001 * z;
        point.x = point.z*(j - cx_d)  / fx_d;
        point.y = point.z *(cy_d - i) / fy_d;
        ptCloud->points.push_back(point);
        ++p;
    }
    }
    ptCloud->width = (int)depthMat.cols;
    ptCloud->height = (int)depthMat.rows;

    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZRGB>);
    std::cerr << "Cloud before SOR filtering: " << ptCloud->width * ptCloud->height << " data points" << std::endl;
    // Create the filtering object
    pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;
    sor.setInputCloud(ptCloud);
    sor.setMeanK(50);
    sor.setStddevMulThresh(1.0);
    sor.filter(*cloud_filtered);
    std::cerr << "Cloud after SOR filtering: " << cloud_filtered->width * cloud_filtered->height << " data points " << std::endl;
    copyPointCloud(*cloud_filtered, *ptCloud);

    return ptCloud;

}

int main(int argc, char* argv[])
{
    cv::Mat image = cv::imread("/home/madina/projects/testOpenCV/images/2.jpg");
    cv::resize(image, image, cv::Size(640, 480));
    cv::imshow("initial", image);

    cv::Mat coords(3, image.cols * image.rows, CV_64FC1);
    for (int col = 0; col < coords.cols; ++col)
    {
    coords.at<double>(0, col) = col % image.cols;
    coords.at<double>(1, col) = col / image.cols;
    coords.at<double>(2, col) = 10;
    }

    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud = MatToPoinXYZ(image);
    //pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud = img_to_cloud(image, coords);
    draw_cloud("points", cloud);

    //cloud_to_img(cloud, coords, image);
    //cv::imshow("returned", image);

    cv::waitKey();
    return 0;

}


text:
Q: Saving Hebrew text to NSUserDefaults return strange encoding I'm saving Hebrew text to NAMutableArray, then I save it to NSUserDefalts, this way:
numOfWallPosts++;
        NSString *tempKeyToStore = [NSString stringWithFormat:@"wall_post_%d", numOfWallPosts]; // wall_post_%d

        NSMutableArray *tempArray = [[NSMutableArray alloc] init];

        [tempArray addObject:currentOwner];
        [tempArray addObject:currentTitle];
        [tempArray addObject:currentText];
        [tempArray addObject:currentDate];
        [tempArray addObject:currentTime];
        [tempArray addObject:currentImageURL];
        [tempArray addObject:currentWallID];

        [self.sharedPrefs setObject:tempArray forKey:tempKeyToStore];
        [self.sharedPrefs synchronize];

When I want to get the Hebrew text back I get text like this:
Wall messages: (
    "\U05de\U05e2\U05e8\U05db\U05ea",
    "\U05ea\U05e8\U05d2\U05d9\U05dc \U05e4\U05d9\U05e7\U05d5\U05d3 \U05d4\U05e2\U05d5\U05e8\U05e3",
    "\U05d0\U05d6\U05e2\U05e7\U05ea \U05ea\U05e8\U05d2\U05d5\U05dc \U05d1\U05e9\U05e2\U05d4 19:05",
    "27/05/13",
    "13:16",
    "http://blabla......",
    9
)

I tried to format the text in UTF8String, and with NSUTF8StringEncoding and I still get the text this way.
Can I save the text in proper way or encode it back to proper Hebrew?
EDIT:
This is so strange, although the text saved strange, I pull it back and I get the text correctly.
But when I save them to NSUserDefaults, it show me this strange encoding.
NSString *tempKeyToStore = [NSString stringWithFormat:@"wall_post_%d", indexPath.row];
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    NSLog(@"\n\nWall messages: %@", [self.sharedPrefs objectForKey:tempKeyToStore]);

    tempArray = [self.sharedPrefs objectForKey:tempKeyToStore];
    NSString *tempOwner = [tempArray objectAtIndex:0];
    NSLog(@"\n\nOWNER: %@", tempOwner);

A: Try doing something like this:
NSString *someObject = //your object that needs decode
        NSString *decodedObject = [NSString
            stringWithCString:[someObject cStringUsingEncoding:NSUTF8StringEncoding]
            encoding:NSNonLossyASCIIStringEncoding];
        NSLog(@"decodedObject = %@", decodedObject);

Edit: There's probably something wrong in your code someplace else because this:
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    [tempArray addObject:@"בדיקה"];

    [[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:@"test"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSMutableArray *test2=[[NSUserDefaults standardUserDefaults] objectForKey:@"test"];
    NSLog(@"test2: %@",[test2 objectAtIndex:0]);

works fine.

A: If you use NSLog(@"%@", ...) to print the description of an array or dictionary, all non-ASCII characters are printed using a \Unnnn escape sequence:
NSArray *a = [NSArray arrayWithObject:@"מערכת"];
NSLog(@"%@", a);

Output:

(
   "\U05de\U05e2\U05e8\U05db\U05ea"
)

(The reason is that the description method of NSArray and NSDictionary
uses the Old-Style ASCII Property Lists format,
which, as the name indicates, allows only ASCII characters.)
If you print the description of a string, all characters are properly displayed:
NSLog(@"%@", [a objectAtIndex:0]);

Output:

מערכת

So this is only a display issue.

A: Well, can you post the code behind sharedPrefs?
When i tried to save a simple hebrew to userdefault it worked just fine.
NSString *tempKeyToStore = @"KEY";

NSMutableArray *tempArray = [[NSMutableArray alloc] init];

[tempArray addObject:@"שלום שלום"];

[[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:tempKeyToStore];
[[NSUserDefaults standardUserDefaults] synchronize];

Read it later -
//
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSMutableArray *tempArray = [defaults objectForKey:@"KEY"];

for (NSString* str in tempArray)
{
    NSLog(@"%@", str);
}

Hope i helped..


text:
Q: Nice proof of the Jordan curve theorem? As a student, I was taught that the Jordan curve theorem is a great example of an intuitively clear statement which has no simple proof.
What is the simplest known proof today?
Is there an intuitive reason why a very simple proof is not possible?

A: You should compare with: "Geometric Topology in Dimensions 2 and 3", Moise, Edwin E. (1977). Springer-Verlag and tell

A: There's a short proof (less than three pages) that uses Brouwer's fixed point theorem, available here:
The Jordan Curve Theorem via the Brouwer Fixed Point Theorem
The goal of the proof is to take Moise's "intuitive" proof and make it simpler/shorter.  Not sure whether you'd consider it "nice," though.

A: It depends on what you mean by "simple". If you know homology, the proof is not very hard (less than 1 page), see for example, section 2.B ("Classical Applications") of Hatcher's book "Algebraic Topology".

A: There is a proof of the Jordan Curve Theorem in my book Topology and Groupoids  which also derives results on the Phragmen-Brouwer Property. Also published as
`Groupoids, the Phragmen-Brouwer property and the Jordan curve theorem', J. Homotopy and Related Structures 1 (2006) 175-183.
The van Kampen Theorem for the fundamental groupoid on a set of base points is used to prove that if $X$ is pathconnected and the union of open path connected sets $U,V$ whose intersection has $n$ path components, then the fundamental group of $X$ contains the free group on $n-1$ generators as a retract.
May 30: The question asks why there is not a simple proof. Perhaps the following Figure  9.10 from the above book will explain why a proof is not expected to be so so easy; how do you decide whether a point in the middle is inside or outside?

Feb 9, 2016: A small correction is needed, and this is given in this paper  jointly with Omar Antolin-Camarena.
October 26, 2016 Related issues on many base points are discussed in this paper.

A: Several proofs are here:
http://www.maths.ed.ac.uk/~aar/jordan/index.htm
Among them, Tverberg's (1980) could (and should) be mentioned.
But, after reading (and reading)
http://www.math.sunysb.edu/~bishop/classes/math401.F09/HalesDefense.pdf ,
I really like Jordan's proof itself.

A: Carsten Thomassen's proof is relatively simple:
Carsten Thomassen, The Jordan-Schönflies theorem and the classification of surfaces. Amer. Math. Monthly 99 (1992), no. 2, 116-130.
By the way, the Jordan Curve Theorem has a formal proof (one that can be checked by a computer):
Thomas C. Hales, The Jordan curve theorem, formally and informally. Amer. Math. Monthly 114 (2007), no. 10, 882-894.
Hales bases the formal proof on Thomassen's.
The following is a survey on the older papers on the subject:
H. Guggenheimer, The Jordan curve theorem and an unpublished manuscript by Max Dehn. Archive for History of Exact Sciences 17 (1977), 193-200.

A: An elementary proof by means of nonstandard analysis (by reduction to the case of polygons) and elementary combinatorics is given in Kanovei & Reeken, A nonstandard proof of the Jordan curve theorem, RAE 1999, 24, 161--170

A: There's a remarkable elementary proof of the Jordan separation theorem, using only the fundamental group, due to Doyle. The proof is expounded in detail in Armstrong's book Basic Topology, Section 5.6.
I think this approach could be extended to prove that there are two complementary components. If there were more, then by an application of Van Kampen's theorem, one could conclude that the fundamental group is a free group of rank $>1$, which would give a contradiction as in Doyle's argument.

A: I'm sure there was a simple proof of the Jordan Curve Theorem as one of Kevin Brown's math articles, at http://www.mathpages.com.
As I recall, it was based on counting curve crossings over each of a sequence of concentric narrow annuli, the outmost of which entirely encloses the curve.
But as I can't now find it on Kevin's site, and there is a host of other fascinating articles there which will doubtless divert your attention for quite some time, I fear this reply probably isn't one of my more helpful ones!

A: A nice and simple proof using $\mod 2$ intersection theory is given in the book Differential Topology by Guillemin,Pollack.


text:
Q: Firebase read/ save Data to use it as a list | Swift/Firebase Hello I have The Following Problem,
I want to save my data to my realtime Database so, that I can use it as a list.

so know I am trying to save the PartyId (yellow) with a uuid (red), but this is not really working, because I need the uuid to use it on swift.
So are there probably any other ways to save or read the data.
Thanks in advance.

A: If you only need to store the data in an array, you need to add the index of the element as a key, and the PartyId as the value.

This make the "Array" element to be able to be treated as an array when you retrieve the data.
Just to be mentioned, if you need to make some queries when you retrieve the data (for example, how many users assist to a specific party) consider to flatten your structure data like this:

With this you can be able to query, for example, all the users that have a specific partyId. For more information, you can check the documentation to create good data structures


text:
Q: Proving independence of random variables
If $X$ and $Y$ are independent exponential random variables with parameter $\lambda$ and $\mu$. Let $Z=\min(X,Y)$, prove that $Z$ and $\mathbf 1_{\{X<Y\}}$ are independent.

I don't know, how to begin, to show is
$$\Pr(Z\in A, \mathbf 1_{\{X<Y\}}\in B)=\Pr(Z\in A)\Pr(\mathbf 1_{\{X<Y\}}\in B)$$
for any Borel $A,B$
but this doesn't seem very useful, or do I have to find first the distribution function of $Z$, can you help please.
EDIT: maybe the parameters are not significant for this part of the exercise, there are also other questions, where the parameters must be used. I tried also;
$\Pr(Z\in A, \mathbf 1_{\{X<Y\}}\in B)$
$=\Pr([Z\in A, \mathbf 1_{\{X<Y\}}\in B]\mathbf 1_{\{X<Y\}})+\Pr([Z\in A, \mathbf 1_{\{X<Y\}}\in B]\mathbf 1_{\{X>Y\}})$
$=\Pr(X\in A, 1\in B)+\Pr(Y\in A, 0\in B)\overset!=\Pr(X\in A)\Pr(1\in B)+\Pr(Y\in A)\Pr(0\in B)$
$=\Pr(Z\in A)\Pr(\mathbf 1_{\{X<Y\}}\in B)$
the second last step (!) is allowed since, $1$ and $0$ are constant random variables and therefore independent of $X$ and $Y$ ?

A: Consider independent Poisson processes $N_t$, $M_t$ with rates $\lambda$, $\mu$, such that $X$ is the time until the first occurrence of $N_t$ and $Y$ is the time until the first occurrence of $M_t$.  Then $N_t + M_t$ is a Poisson process  with rate $\lambda + \mu$, and $Z$ is the time until its first occurrence.  One way to
realize this is to start with a Poisson process of rate $\lambda + \mu$, and assign each occurrence (independently) to process $N_t$ with probability $\lambda/(\lambda + \mu)$, otherwise to $M_t$.  Then $X<Y$ is the event that the first occurrence is assigned to $N_t$, and by construction that is independent
of $Z$.

A: Maybe an easier answer is to follow the initial approach and forget about the exponential law because it doesn't matter. Intuitively, just knowing the maximum of the two iid rv tells you nothing about which of the two is larger than the other. Formally, you are supposed to show
\begin{align*}
\mathbb{P}[Z\in A,\mathbf{1}_{X<Y} \in B] &=\mathbb{P}[Z\in A] \mathbb{P}[\mathbf{1}_{X<Y} \in B]
\end{align*}
for all $A,B \in \mathcal{B}(R)$. Borel sets are not as bad as Lebesgue sets, but still, they are very complicated, so showing something for all Borel sets seems hard. Until you realize that there are not so many values that $\mathbf{1}_{X<Y}$ can take. If $B$ contains neither 0 nor 1, the equality should be obvious to you (is it?). By symmetry, you only have to consider $B$ such that $0\in B$ and $1\notin B$. Then you have
\begin{align}
\mathbb{P}[Z\in A,\mathbf{1}_{X<Y}\in B]&=\mathbb{P}[Z\in A,X<Y].
\end{align}
Can you finish it?
Hints: Use iid and the continuity of the law to find:
1) $\mathbb{P}[X<Y]=?$.
2) $\mathbb{P}[Z\in A,X<Y]=\mathbb{P}[Z\in A,Y<X]$
Finish it off with $\mathbb{P}[Z\in A]=\mathbb{P}[Z\in A,X<Y]+\mathbb{P}[Z\in A,Y<X]$.


text:
Q: Auto-update Ubuntu IP address in python script I am using python3 , flask server on ubuntu virtual machine. The server is working fine. It uploads a browsed video and print **found file when the browsed video file is in appropriate extension.
The problem is, every time when I restart my ubuntu virtual machine the IP address is changed and I have to update it manually in python script app.run(host= '192.168.1.101', debug=True).
Please tell me how to automatically update it.
Any help would be appreciated.
Thanks in advance.
Here is the code.
import os
from flask import Flask, request, redirect, url_for, send_from_directory, jsonify
from werkzeug import secure_filename

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'mp4'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
  # this has changed from the original example because the original did not work for me
    return filename[-3:].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    print("Printing the request {}".format(request.headers))
    print("Printing the request {}".format(request))
    print("Printing the request {}".format(request.data))
    print("Printing the request {}".format(request.form))
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            print('**found file', file.filename)
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            # for browser, add 'redirect' function on top of 'url_for'
            return jsonify({"success" : url_for('uploaded_file',
                                    filename=filename)})
    return '''
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form action="" method=post enctype=multipart/form-data>

<input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(host= '192.168.1.101', debug=True)

A: you will have to either parse the "ip address" or "ifconfig" command, or use
import socket
socket.gethostbyname(socket.gethostname())

cfr. Finding local IP addresses using Python's stdlib


text:
Q: Can one modify the templates created by artisan migrate command? I've created a base class for my migrations. At the moment I run the artisan migrate command and it creates a new migration that extends the Migrations file, however I want to include my BaseMigration and extend it from there. I've been making this changes manualy but I feel like I'm repeating myself unnecessarily.
Any advice on how to have new migrations automatically extend and load my base migration?

A: I don't think you can, because Laravel takes migrations from the vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs folder and you cannot change that, but you have some options:
1) Create your own artisan command migrate:makemyown.
2) Use Jeffrey Way's Laravel Generators. They let you create your migrations by doing:
php artisan generate:migration create_posts_table --fields="title:string, description:text"

If you just have some fields you need to start with and not something more specific than that, it works really fine.
3) Edit Laravel stubs, but the problem is that as soon as you composer update they might get overwritten by Composer.

A: I believe that there is no way to override this (for now) but I think that you can create your custom command which will use Laravel logic. This was created for Laravel 5.
First you have to create Generator command app/Console/Commands/Generator.php:
<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;

class Generator extends Command
{

  /**
   * Command name
   *
   * @var string
   */
  protected $name = 'generate';

  /**
   * Command description
   *
   * @var string
   */
  protected $description = 'Custom object generator';

  /**
   * An array with all available generator classes
   *
   * @var array
   */
  protected $types = ['request', 'model', 'middleware'];

  /**
   * Execute command
   *
   * @return mixed
   */
  public function handle()
  {
      $type = $this->argument('type');
      if (!in_array($type, $this->types)) {
          return $this->error('Type must be one of: '.implode(', ', $this->types));
      }

      // Create new instance
      $generatorClass = 'App\Console\Commands\Generators\\'.ucfirst($type);
      $generator = new $generatorClass(new Filesystem());

      // Each generator has "fire" method
      $this->comment($generator->setClassName($this->argument('name'))->fire());
  }

  /**
   * @return array
   */
  public function getArguments()
  {
      return [
          ['type', InputArgument::REQUIRED, 'Type of class to generate: '.implode(', ', $this->types)],
          ['name', InputArgument::REQUIRED, 'Name of class to generate'],
      ];
  }

}

Then you have to create an abstract class for all of your Generators classes app/Console/Commands/Generators/Generator.php:
<?php namespace App\Console\Commands\Generators;

use Illuminate\Console\GeneratorCommand;

abstract class Generator extends GeneratorCommand
{
  // Directory name with whole application (by default app)
  const APP_PATH = 'app';

  /*
   * Name and description of command wont be used
   * Generators Commands are not loaded via Kernel
   * Name and description property has been put just to avoid Exception thrown by Symfony Command class
   */
  protected $name = 'fake';
  protected $description = 'fake';

  /**
   * Class name to generate
   *
   * @var string
   */
  protected $className;

  /**
   * Returns class name to generate
   *
   * @return string
   */
  protected function getNameInput()
  {
      return $this->className;
  }

  /**
   * Returns path under which class should be generated
   *
   * @param string $name
   * @return string
   */
  protected function getPath($name)
  {
      $name = str_replace($this->getAppNamespace(), '', $name);

      return self::APP_PATH.'/'.str_replace('\\', '/', $name).'.php';
  }

  /**
   * Sets class name to generate
   *
   * @param string $name
   * @return $this
   */
  public function setClassName($name)
  {
      $this->className = $name;
      return $this;
  }

  /**
   * Execute command
   *
   * @return string
   */
  public function fire()
  {
      $name = $this->parseName($this->getNameInput());

      if ($this->files->exists($path = $this->getPath($name)))
      {
          return $this->type.' already exists!';
      }

      $this->makeDirectory($path);

      $this->files->put($path, $this->buildClass($name));

      return $this->type.' '.$this->className.' created successfully.';
  }

}

At the end you can create your first Generator class! app/Console/Commands/Generators/Request.php
<?php namespace App\Console\Commands\Generators;

class Request extends Generator
{

  /**
   * Class type to generate
   *
   * @var string
   */
  protected $type = 'Request';

  /**
   * Returns default namespace for objects being generated
   *
   * @param string $rootNamespace
   * @return string
   */
  protected function getDefaultNamespace($rootNamespace)
  {
      return $rootNamespace.'\Http\Requests';
  }

  /**
   * Returns path to custom stub
   *
   * @return string
   */
  public function getStub()
  {
      return base_path('resources').'/stubs/request.stub';
  }

}

Dont forget to add your generate command to Kernel app/Console/Kernel.php:
<?php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

  /**
   * The Artisan commands provided by your application.
   *
   * @var array
   */
  protected $commands = [
    ...
    'App\Console\Commands\Generator',
    ...
  ];

Put your stubs under resources/stubs directory. Let's create first one for Request Generator resources/stubs/request.stub:
<?php namespace {{namespace}};

class {{class}} extends Request
{

  /**
   * @return bool
   */
  public function authorize()
  {
    // CUSTOM LOGIC

    return false;
  }

  /**
   * @return array
   */
  public function rules()
  {
    $rules = [];

    // CUSTOM LOGIC

    return $rules;
  }

}

Then call with php artisan generate request MyRequest.
You can create your custom Model, Middleware, Controller etc. generators, it's very simple - you have to create new generator class under app/Commands/Console/Generators - take a look at Request.php generator to see how it works!

A: It's doable in a fairly logical way, at least in Laravel 5
Subclass MigrationCreator and override getStubPath(), just copying the function over from the original class (it will use your subclass's __DIR__)
<?php

namespace App\Database;

use Illuminate\Database\Migrations\MigrationCreator;

class AppMigrationCreator extends MigrationCreator
{
    public function getStubPath()
    {
        return __DIR__.'/stubs';
    }
}

Write a service provider to override migration.creator with your own subclass (it must be a deferred service provider, because you cannot override a deferred binding with an eager one):
<?php

namespace App\Database;

use Illuminate\Support\ServiceProvider;

class AppMigrationServiceProvider extends ServiceProvider
{
    protected $defer = true;

    public function register()
    {
        $this->app->singleton('migration.creator', function ($app) {
            return new AppMigrationCreator($app['files']);
        });
    }

    public function provides()
    {
        return ['migration.creator'];
    }
}

Add your service provider to config/app.php after the default ones.
Finally, copy vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs alongside your MigrationCreator subclass (in this example it would become app/Database/stubs) and edit the templates to your needs.
Keep the DummyClass and DummyTable names, as they are replaced with str_replace() to create the actual migrations files.

A: Since Laravel 7 you can publish stubs using php artisan stub:publish.

The published stubs will be located within a stubs directory in the root of your application. Any changes you make to these stubs will be reflected when you generate their corresponding classes using Artisan make commands.

A: For Laravel 5 you'd edit one of the .stub files in:
vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs

There's no reason why you can't edit those files.
Search in vendor/laravel/framework/src/ for .stub files to find all of the other stubs (templates) artisan uses.


text:
Q: php dynamic select option set to default value after you come back to page (reset select option after form submite) <select id = "test" name = "test">
<option value = "">default option </option>

<?php

$conn = mysqli_connect('localhost', 'root', '');

            $result = mysqli_query($conn, 'SELECT id,name FROM center');
            while ($row = mysqli_fetch_assoc($result))
            {
              $selected = (isset($_POST['list']) && $_POST['list'] ==  $row['id']) ? 'selected' : '';
              echo "<option value='$row[id]' $selected >$row[name]</option>";
            }
            ?>
</select>

<?php
if(isset($_POST['test']))
{

// unhide and display a bunch of stuff
}

Hi all, so my issue is that once the user submits the form. Leave the page and come back. The selected option in the while loop is still selected, however isset($_POST['test']) is no longer register so the code below no longer shows. So it just shows that one option, and the default option. (nothing to do or select cause isset(post) no longer set when they come to the page
The issue is that since the isset is no longer set the user can't do anything. even when page refresh. All they have is one select box option. But if the user select the same option before it would've generated the code in the if isset(post['test'])
I want it so that once the form has been submitted to reset the first select option to it's default option or show the second half when the user comes back to the page and the dynamic select option is still save
I apologize because my laptop is still broken and I can't copy and paste my code so I wrote some code and wrote a part of someone else code. I am trying to get my laptop fix as soon as possible but with the current situation I am having trouble getting it repair quickly


text:
Q: How do they tell what environment variable name is in windows' System variables I am sorry if this question is silly.
 I have no problems with setting environment variables, but I am curious to know the answer.
I searched Google but I didn't find information.
For example they tell set the variable name for Java to JAVA_HOME, and for apache tomcat set the variable name to CATALINA_HOME
How do they know it is JAVA_HOME and CATALINA_HOME?
Is there a way to know that myself?

A: "They" wrote code that reads environment variables with those names.
Therefore, "they" can tell you to set those names.


text:
Q: Saving time as timestamp in database with PHP From the front-end I am taking a time string by three separate input fields: hour, minute and mode (for am/pm). Then in the back-end I am concatenating all these three inputs to make up something like this: 12:05pm
The DB column in which I want to store this time is in timestamp format. If I insert this string, mysql force converts it to 0000-00-00 00:00:00. How can I insert the time?

A: Get the date and and concatenate the time with date and conver it into strtotime like below
$timestamp = '02:01pm';
$currentDateTime = date('Y-m-d');
$newDate= date('Y-m-d H:i:s',strtotime($currentDateTime." ".$timestamp));
echo $newDate;


text:
Q: Apache camel, how to move message from SOAP to JMS I'm learning Apache Camel framework, and try to build simple route where message is received from SOAP endpoint and is put into JMS queue (ActiveMQ).
I have the following route
<route id="cxfToJMSRoute">
    <from uri="cxf:bean:endpoint" />
    <log message="test" />
    <wireTap uri="direct:logInfo" />
    <to uri="activemq:queue:api" />
</route>

And the endpoint and queue are defined as follows
<cxf:cxfEndpoint id="endpoint" address="http://localhost:1010/hello"
        serviceClass="net.webservicex.GlobalWeatherSoap" wsdlURL="META-INF/globalweather.wsdl" />

<bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
    <property name="brokerURL" value="tcp://127.0.0.1:61616"/>
</bean>

However, when I call the endpoint, the other service reading the message queue throws following error
org.apache.camel.RuntimeCamelException: Failed to extract body due to: javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: Forbidden class org.apache.cxf.message.MessageContentsList! This class is not trusted to be serialized as ObjectMessage payload. Please take a look at http://activemq.apache.org/objectmessage.html for more information on how to configure trusted classes.. Message: ActiveMQObjectMessage {commandId = 8, responseRequired = true, messageId = ID:IT-L-R90HKRNH-64004-1511880368329-1:1:2:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:IT-L-R90HKRNH-64004-1511880368329-1:1:2:1, destination = queue://api, transactionId = null, expiration = 1511880389430, timestamp = 1511880369430, arrival = 0, brokerInTime = 1511880369434, brokerOutTime = 1511880369495, correlationId = Camel-ID-IT-L-R90HKRNH-1511880338904-0-3, replyTo = temp-queue://ID:IT-L-R90HKRNH-64004-1511880368329-1:1:1, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@663a8b1b, marshalledProperties = org.apache.activemq.util.ByteSequence@504b2d9b, dataStructure = null, redeliveryCounter = 0, size = 1640, properties = {SOAPAction=http://www.webserviceX.NET/GetCitiesByCountry, CamelHttpCharacterEncoding=UTF-8, User_HYPHEN_Agent=Apache-HttpClient/4.1.1 (java 1.5), Host=127.0.0.1:1010, operationName=GetCitiesByCountry, operationNamespace=http://www.webserviceX.NET, breadcrumbId=ID-IT-L-R90HKRNH-1511880338904-0-1, Content_HYPHEN_Type=text/xml;charset=UTF-8, CamelHttpMethod=POST, accept_HYPHEN_encoding=gzip,deflate, connection=keep-alive, CamelHttpUri=/hello, CamelHttpPath=}, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false}
        at org.apache.camel.component.jms.JmsBinding.extractBodyFromJms(JmsBinding.java:160) ~[camel-jms-2.16.3.jar!/:2.16.3]
        at org.apache.camel.component.jms.JmsMessage.createBody(JmsMessage.java:236) ~[camel-jms-2.16.3.jar!/:2.16.3]
        at org.apache.camel.impl.MessageSupport.getBody(MessageSupport.java:54) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.builder.ExpressionBuilder$35.evaluate(ExpressionBuilder.java:905) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.support.ExpressionAdapter.evaluate(ExpressionAdapter.java:36) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.builder.ExpressionBuilder$76.evaluate(ExpressionBuilder.java:1836) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.support.ExpressionAdapter.evaluate(ExpressionAdapter.java:36) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.processor.LogProcessor.process(LogProcessor.java:64) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:548) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:138) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:101) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:97) ~[camel-core-2.20.1.jar!/:2.20.1]
        at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.java:112) ~[camel-jms-2.16.3.jar!/:2.16.3]
        at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:719) ~[spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:679) ~[spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:649) ~[spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:317) [spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:255) [spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1166) [spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1158) [spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1055) [spring-jms-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_92]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_92]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92]
Caused by: javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: Forbidden class org.apache.cxf.message.MessageContentsList! This class is not trusted to be serialized as ObjectMessage payload. Please take a look at http://activemq.apache.org/objectmessage.html for more information on how to configure trusted classes.
        at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36) ~[activemq-client-5.14.5.jar!/:5.14.5]
        at org.apache.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:208) ~[activemq-client-5.14.5.jar!/:5.14.5]
        at org.apache.camel.component.jms.JmsBinding.extractBodyFromJms(JmsBinding.java:135) ~[camel-jms-2.16.3.jar!/:2.16.3]
        ... 25 common frames omitted
Caused by: java.lang.ClassNotFoundException: Forbidden class org.apache.cxf.message.MessageContentsList! This class is not trusted to be serialized as ObjectMessage payload. Please take a look at http://activemq.apache.org/objectmessage.html for more information on how to configure trusted classes.
        at org.apache.activemq.util.ClassLoadingAwareObjectInputStream.checkSecurity(ClassLoadingAwareObjectInputStream.java:112) ~[activemq-client-5.14.5.jar!/:5.14.5]
        at org.apache.activemq.util.ClassLoadingAwareObjectInputStream.resolveClass(ClassLoadingAwareObjectInputStream.java:57) ~[activemq-client-5.14.5.jar!/:5.14.5]
        at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1620) ~[na:1.8.0_92]
        at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1521) ~[na:1.8.0_92]
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1781) ~[na:1.8.0_92]
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353) ~[na:1.8.0_92]
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373) ~[na:1.8.0_92]
        at org.apache.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:206) ~[activemq-client-5.14.5.jar!/:5.14.5]
        ... 26 common frames omitted

So do I have to convert the message to POJO myself before the JMS? I'm completely new to Camel, but I got the impression Camel should handle type conversions automatically.

A: You dont want to send Java objects to a JMS broker, so instead you can convert the message to be text based via by adding
<convertBodyTo type="String"/>
<to uri="activemq:queue:api" />

Before sending to the JMS broker.
You may need to add camel-jaxb on the classpath to allow Camel to automatic convert your POJO class to text as XML. Or you can configure your SOAP endpoint to not use POJO type and just raw XML, then Camel can send that raw XML directly to JMS as text based.


text:
Q: T-SQL String manipulation in my DB I have a column given paths like :

*

*\myserver\mydir1\dir2\Atest.txt

*\myserver\mydir1\dir2\Btest.txt

At the end I should update a column with the first character after the last "\" delimiter , therefore "A" and "B" in this example.
How can I get this?
Thanks a lot
Largo

A: select substring(YourColumn, len(YourColumn)-charindex('\', reverse(YourColumn))+2, 1)
from YourTable

You have not specified what DBMS you are using. To make this work you need to have these functions available or something similar.

*

*substring

*len

*charindex

*reverse


text:
Q: Encapsulating alarm creation code in a different class than the Activity I'm creating my first Android Notifications app, so I'm very much a beginner. I have a class, Notification.java, that asks the user for the time and date. Using these data, it creates an alarm that is triggered at the specified date and time.
Here is my code for Notification.java
public class Notification extends Activity {

private PendingIntent pendingIntent;
private SetAlarm alarm;
private Date date;
private Time time;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm);

    findViewById(R.id.setTime).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setAlarmTime();
        }
    });

    findViewById(R.id.setDate).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setAlarmDate();
        }
    });

    findViewById(R.id.checkBox).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            createAlarm();
        }
    });
}

private void setAlarmTime() {

}

private void setAlarmDate() {

}

private void createAlarm() {
    alarm = new SetAlarm();
}

}
The createAlarm() method is supposed to actually create the alarm using the information that the user has provided (i.e. time and date). However, I understand that I need the following code block to create the alarm?
 private void setTheAlarm() {
    Intent alarmIntent = new Intent(SetAlarm.this, AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(SetAlarm.this, 0, alarmIntent, 0);

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval;

    /* Set the alarm to the date specified by user */

    /* Repeating on every x minutes interval */
}

However, the Notification.java is where I am extending 'Activity'. It is also where I have the 'pendingIntent; code.
So essentially, how can I move the alarm creation code into a separate class when the code dealing with the Activity is in an entirely different class?
Thanks for the help. I hope my question is clear enough.

A: Not exactly clear if that is what you want, but if I understand you correct, you need the alarmManager inside an extra class to reach it from everywhere? You could make a static one like this:
public class MyAlarmManager{

private static AlarmManager mAlarmManager;
private static PendingIntent mPendingIntent;

//start alarm
public static void setAlarm(Context context, int alarmId, long alarmTime) {

   if (mAlarmManager== null) {
    mAlarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   }

Intent startAlarmIntent = new Intent(context, YouReceiver.class);

   if(mPendingIntent==null){

    mPendingIntent = PendingIntent.getBroadcast(context, alarmId,
startAlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

   }

//check the version because of doze mode since MM
   if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                     mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
alarmTime, mPendingIntent);

   } else {
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, mPendingIntent);

   }

}

//stop alarm
public static void stopAlarm(Context context, int id) {

 if (mAlarmManager == null) {
    mAlarmManager = (AlarmManager)  context.getSystemService(Context.ALARM_SERVICE);
    }

  Intent stopAlarmIntent = new Intent(context, YourReceiver.class);

    if(mPendingIntent==null){
    mPendingIntent= PendingIntent.getBroadcast(context, id, stopAlarmIntent, 0);
    }

  mAlarmManager.cancel(mPendingIntent);
  mPendingIntent.cancel();

  }
}

Then you can call it like:
 MyAlarmManager.setAlarm(this, id, interval);

and stop it:
 MyAlarmManager.stopAlarm(this, id);

You can do this from every class by passing the context and the identical id . The alarm id must be the same as you passed by starting the alarm, otherwise it will not work. Notice that above MarshMallow, there are some changes for AlarmManager and it´s possible that it does not work in every case. If your app get´s killed or goes into idle mode, the alarm won´t be triggered in every circumstance. To handle doze mode, see this:https://developer.android.com/training/monitoring-device-state/doze-standby.html
And be aware of any third party app and battery managers, that could kill your app. Also, Huawei devices have their own battery management besides the doze mode.
If this is not what you wanted, come back. Can´t guarantee that there is no error because I have overseen something, it´s from scratch.


text:
Q: Compile native C code with android libraries I have a native C code to android (I'm not using JNI, it's pure C) and I want to print log messages on LogCat.
Without using #include<android/log.h> I was able to compile with arm-linux-gnueabi-gcc -static -o Matrix MatrixMultiplication.c and it worked very well, but now i need to send to LogCat some messages with #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "NativeC", __VA_ARGS__). I tried to import the library but it didn't work and this: http://betelco.blogspot.com.br/2010/01/buildingdebugging-android-native-c.html . I'm using  android-ndk-r8b
How can i do this?
thanks

A: For better compatibility with Android features, instead of directly invoking the compiler and linker, you should use the same structure as for a jni project, but use
include $(BUILD_EXECUTABLE)

in the Android.mk instead of one of the library build choices.
Be aware that building and invoking executable is not officially supported, though it works at present.


text:
Q: KIBANA - WAZUH pattern index I have a project to install wazuh as FIM on linux, AIX and windows.
I managed to install Manager and all agents on all systems and I can see all three connected on the Kibana web as agents.
I created test file on the linux agent and I can find it also on web interface, so servers are connected.
Here is test file found in wazuh inventory tab
But, I am not recieving any logs if I modify this test file.
This is my settings in ossec.conf under syscheck on agent server>
<directories>/var/ossec/etc/test</directories>
<directories report_changes="yes" check_all="yes" realtime="yes">/var/ossec/etc/test</directories>

And now I ma also strugling to understand meanings of index patterns, index templates and fields.
I dont understand what they are and why we need to set it.
My settings on manager server - /usr/share/kibana/data/wazuh/config/wazuh.yml
alerts.sample.prefix: 'wazuh-alerts-*'
pattern: 'wazuh-alerts-*'

On the kibana web I also have this error when I am trying to check ,,events,, -the are no logs in the events.
Error: The field "timestamp" associated with this object no longer exists in the index pattern. Please use another field.
    at FieldParamType.config.write.write (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:627309)
    at http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:455052
    at Array.forEach (<anonymous>)
    at writeParams (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:455018)
    at AggConfig.write (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:355081)
    at AggConfig.toDsl (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:355960)
    at http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:190748
    at Array.forEach (<anonymous>)
    at agg_configs_AggConfigs.toDsl (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:189329)
    at http://MYIP:5601/42959/bundles/plugin/wazuh/4.2.5-4206-1/wazuh.chunk.6.js:55:1397640

Thank you.

A: About FIM:
here you can find the FIM documentation in case you don't have it:
https://documentation.wazuh.com/current/user-manual/capabilities/file-integrity/fim-configuration.html
https://documentation.wazuh.com/current/user-manual/reference/ossec-conf/syscheck.html.
The first requirement for this to work would be to ensure a FIM alert is triggered, could you check the alerts.json file on your manager? It is usually located under /var/ossec/logs/alerts/alerts.json  In order to test this fully I would run "tail -f /var/ossec/logs/alerts/alerts.json" and  make a change in yout directory , if no alerts is generated, then we will need to check the agent configuration.
About indexing:
Here you can find some documentation:
https://www.elastic.co/guide/en/elasticsearch/reference/current/index-templates.html
https://www.elastic.co/guide/en/kibana/current/managing-index-patterns.html#scripted-fields
https://documentation.wazuh.com/current/user-manual/kibana-app/reference/elasticsearch.html
Regarding your error, The best way to solve this is to delete the index. To do this:
got to  Kibana -> Stack management -> index patterns and there delete  wazuh-alerts-*.
Then if you enter to Wazuh App the health check will create it again or you can follow this to create your index:
Go to kibana -> stack management -> index pattern and select Create index pattern.
Hope this information helps you.
Regards.

A: thank you for your answer.
I managed to step over this issue, but I hit another error.
When I check tail -f /var/ossec/logs/alerts/alerts.json I got never ending updating, thousands lines with errors like.

{"timestamp":"2022-01-31T12:40:08.458+0100","rule":{"level":5,"description":"Systemd: Service has entered a failed state, and likely has not started.","id":"40703","firedtimes":7420,"mail":false,"groups":["local","systemd"],"gpg13":["4.3"],"gdpr":["IV_35.7.d"]},"agent":{"id":"003","name":"MYAGENTSERVERNAME","ip":"X.X.X.X"},"manager":{"name":"MYMANAGERSERVERNAME"},"id":"1643629208.66501653","full_log":"Jan 31 12:40:07 MYAGENTSERVERNAME systemd: Unit rbro-cbs-adapter-int.service entered failed state.","predecoder":{"program_name":"systemd","timestamp":"Jan 31 12:40:07","hostname":"MYAGENTSERVERNAME"},"decoder":{"name":"systemd"},"location":"/var/log/messages"}

But, I can also find alert if I change monitored file. (file> wazuhtest)

{"timestamp":"2022-01-31T12:45:59.874+0100","rule":{"level":7,"description":"Integrity checksum changed.","id":"550","mitre":{"id":["T1492"],"tactic":["Impact"],"technique":["Stored Data Manipulation"]},"firedtimes":1,"mail":false,"groups":["ossec","syscheck","syscheck_entry_modified","syscheck_file"],"pci_dss":["11.5"],"gpg13":["4.11"],"gdpr":["II_5.1.f"],"hipaa":["164.312.c.1","164.312.c.2"],"nist_800_53":["SI.7"],"tsc":["PI1.4","PI1.5","CC6.1","CC6.8","CC7.2","CC7.3"]},"agent":{"id":"003","name":"MYAGENTSERVERNAME","ip":"x.x.xx.x"},"manager":{"name":"MYMANAGERSERVERNAME"},"id":"1643629559.67086751","full_log":"File '/var/ossec/etc/wazuhtest' modified\nMode: realtime\nChanged attributes: size,mtime,inode,md5,sha1,sha256\nSize changed from '61' to '66'\nOld modification time was: '1643618571', now it is '1643629559'\nOld inode was: '786558', now it is '786559'\nOld md5sum was: '2dd5fe4d08e7c58dfdba76e55430ba57'\nNew md5sum is : 'd8b218e9ea8e2da8e8ade8498d06cba8'\nOld sha1sum was: 'ca9bac5a2d8e6df4aa9772b8485945a9f004a2e3'\nNew sha1sum is : 'bd8b8b5c20abfe08841aa4f5aaa1e72f54a46d31'\nOld sha256sum was: '589e6f3d691a563e5111e0362de0ae454aea52b7f63014cafbe07825a1681320'\nNew sha256sum is : '7f26a582157830b1a725a059743e6d4d9253e5f98c52d33863bc7c00cca827c7'\n","syscheck":{"path":"/var/ossec/etc/wazuhtest","mode":"realtime","size_before":"61","size_after":"66","perm_after":"rw-r-----","uid_after":"0","gid_after":"0","md5_before":"2dd5fe4d08e7c58dfdba76e55430ba57","md5_after":"d8b218e9ea8e2da8e8ade8498d06cba8","sha1_before":"ca9bac5a2d8e6df4aa9772b8485945a9f004a2e3","sha1_after":"bd8b8b5c20abfe08841aa4f5aaa1e72f54a46d31","sha256_before":"589e6f3d691a563e5111e0362de0ae454aea52b7f63014cafbe07825a1681320","sha256_after":"7f26a582157830b1a725a059743e6d4d9253e5f98c52d33863bc7c00cca827c7","uname_after":"root","gname_after":"root","mtime_before":"2022-01-31T09:42:51","mtime_after":"2022-01-31T12:45:59","inode_before":786558,"inode_after":786559,"diff":"1c1\n< dadadadadad\n---\n> dfsdfdadadadadad\n","changed_attributes":["size","mtime","inode","md5","sha1","sha256"],"event":"modified"},"decoder":{"name":"syscheck_integrity_changed"},"location":"syscheck"}
{"timestamp":"2022-01-31T12:46:08.452+0100","rule":{"level":3,"description":"Log file rotated.","id":"591","firedtimes":5,"mail":false,"groups":["ossec"],"pci_dss":["10.5.2","10.5.5"],"gpg13":["10.1"],"gdpr":["II_5.1.f","IV_35.7.d"],"hipaa":["164.312.b"],"nist_800_53":["AU.9"],"tsc":["CC6.1","CC7.2","CC7.3","PI1.4","PI1.5","CC7.1","CC8.1"]},"agent":{"id":"003","name":"MYAGENTSERVERNAME","ip":"x.x.xx.x"},"manager":{"name":"MYMANAGERSERVERNAME"},"id":"1643629568.67099280","full_log":"ossec: File rotated (inode changed): '/var/ossec/etc/wazuhtest'.","decoder":{"name":"ossec"},"location":"wazuh-logcollector"}

Also I can see this alert in messages logs on the manager server>

Jan 31 12:46:10 MYMANAGERSERVERNAME filebeat[186670]: 2022-01-31T12:46:10.379+0100#011WARN#011[elasticsearch]#011elasticsearch/client.go:405#011Cannot index event publisher.Event{Content:beat.Event{Timestamp:time.Time{wall:0xc07610e0563729bf, ext:10888984451164, loc:(*time.Location)(0x55958e3622a0)}, Meta:{"pipeline":"filebeat-7.14.0-wazuh-alerts-pipeline"}, Fields:{"agent":{"ephemeral_id":"dd9ff0c5-d5a9-4a0e-b1b3-0e9d7e8997ad","hostname":"MYMANAGERSERVERNAME","id":"03fb57ca-9940-4886-9e6e-a3b3e635cd35","name":"MYMANAGERSERVERNAME","type":"filebeat","version":"7.14.0"},"ecs":{"version":"1.10.0"},"event":{"dataset":"wazuh.alerts","module":"wazuh"},"fields":{"index_prefix":"wazuh-alerts-4.x-"},"fileset":{"name":"alerts"},"host":{"name":"MYMANAGERSERVERNAME"},"input":{"type":"log"},"log":{"file":{"path":"/var/ossec/logs/alerts/alerts.json"},"offset":127261462},"message":"{"timestamp":"2022-01-31T12:46:08.452+0100","rule":{"level":3,"description":"Log file rotated.","id":"591","firedtimes":5,"mail":false,"groups":["ossec"],"pci_dss":["10.5.2","10.5.5"],"gpg13":["10.1"],"gdpr":["II_5.1.f","IV_35.7.d"],"hipaa":["164.312.b"],"nist_800_53":["AU.9"],"tsc":["CC6.1","CC7.2","CC7.3","PI1.4","PI1.5","CC7.1","CC8.1"]},"agent":{"id":"003","name":"xlcppt36","ip":"10.74.96.34"},"manager":{"name":"MYMANAGERSERVERNAME"},"id":"1643629568.67099280","full_log":"ossec: File rotated (inode changed): '/var/ossec/etc/wazuhtest'.","decoder":{"name":"ossec"},"location":"wazuh-logcollector"}","service":{"type":"wazuh"}}, Private:file.State{Id:"native::706-64776", PrevId:"", Finished:false, Fileinfo:(*os.fileStat)(0xc00095ea90), Source:"/var/ossec/logs/alerts/alerts.json", Offset:127262058, Timestamp:time.Time{wall:0xc076063e1f1b1286, ext:133605185, loc:(*time.Location)(0x55958e3622a0)}, TTL:-1, Type:"log", Meta:map[string]string(nil), FileStateOS:file.StateOS{Inode:0x2c2, Device:0xfd08}, IdentifierName:"native"}, TimeSeries:false}, Flags:0x1, Cache:publisher.EventCache{m:common.MapStr(nil)}} (status=400): {"type":"illegal_argument_exception","reason":"data_stream [<wazuh-alerts-4.x-{2022.01.31||/d{yyyy.MM.dd|UTC}}>] must not contain the following characters [ , ", *, \, <, |, ,, >, /, ?]"}

Here is output form apps check.
curl "http://localhost:9200"
{

  "version" : {
    "number" : "7.14.2",
    "build_flavor" : "default",
    "build_type" : "rpm",
    "build_hash" : "6bc13727ce758c0e943c3c21653b3da82f627f75",
    "build_date" : "2021-09-15T10:18:09.722761972Z",
    "build_snapshot" : false,
    "lucene_version" : "8.9.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

filebeat test output

elasticsearch: http://127.0.0.1:9200...
parse url... OK
connection...
parse host... OK
dns lookup... OK
addresses: 127.0.0.1
dial up... OK
TLS... WARN secure connection disabled
talk to server... OK
version: 7.14.2

So .. I can see alerts coming from Agent, but Its not reaching Kibana yet. On the kibana web I can see agent active and connected.


text:
Q: Auto-registration of generic classes I'm trying to inject a generic class with Simple Injector.
However, it fails with

SimpleInjector.ActivationException: No registration for type ... could be found

Here's the code to reproduce it:
using System;

namespace ErrorReproduction
{
    public class GenericClass<T>
    {
        public T Value { get; set; }
    }

    public interface IGenericInterface<T>
    {
        void DoSomething(T value);
    }

    public class NonGenericService : IGenericInterface<string>
    {
        public void DoSomething(string value) =>
            Console.WriteLine($"NonGeneric DoSomething (string): {value}");
    }

    public class GenericService<T> : IGenericInterface<GenericClass<T>>
    {
        public virtual void DoSomething(GenericClass<T> v) =>
            Console.WriteLine(
                $"Generic DoSomething {v.Value.GetType().Name}: {v.Value}");
    }

    /*
    public class StringService : GenericService<string>
    {
    }
    */

    public static class Test
    {
        public static void Main(string[] args)
        {
            var container = new SimpleInjector.Container();
            container.RegisterSingleton(
                typeof(IGenericInterface<>),
                typeof(IGenericInterface<>).Assembly);

            // works
            container.GetInstance<IGenericInterface<string>>()
                .DoSomething("non-generic-test");

            // breaks without StringService (No registration for type
            // IGenericInterface<GenericClass<string>>)
            container.GetInstance<IGenericInterface<GenericClass<string>>>()
                .DoSomething(
                    new GenericClass<string> {Value = "di-generic-test"});
        }
    }
}

If I comment-in the StringService above, it works. However, without it I receive the following exception:

Unhandled exception. SimpleInjector.ActivationException: No registration for type IGenericInterface<GenericClass<string>> could be found. at ErrorReproduction.Test.Main(String[] args) in ErrorReproduction/Test.cs:line 45

If I create a specific implementation that itself is not generic anymore, DI works.
However, even without the specific one, the GenericService<T>, which is not abstract, is enough and should be injectable.
I'd like to not have to create a specific class for each case of GenericService<T> that we will have. They would just be empty like the above StringService, fully relying on the implementation of the generic service.
Is there a way to get the DI working for a case like this?
Edit:
Turned out my use case is not exactly what I described above. However, the comments and answer provided got me on the right track.
In the end, this is what worked for me:
container.RegisterSingleton(typeof(IMapper<,>), typeof(IMapper<,>).Assembly);
container.RegisterConditional(typeof(IMapper<,>),
    typeof(SimpleTimedValueProxyMapper<>),
    Lifestyle.Singleton,
    ctx => !ctx.Handled);
container.RegisterConditional(typeof(IMapper<,>),
    typeof(TimedValueProxyMapper<,>),
    Lifestyle.Singleton,
    ctx => !ctx.Handled);

Which, given the classes in the first example, would probably resolve to this (have not tested it):
container.RegisterSingleton(typeof(IGenericInterface<>), typeof(IGenericInterface<>).Assembly);
container.RegisterConditional(typeof(IGenericInterface<>),
    typeof(GenericService<>),
    Lifestyle.Singleton,
    ctx => !ctx.Handled);

A: The XML documentation of RegisterXXX(Type, Assembly[]) states the following (emphasis mine):

Registers all concrete, non-generic, public and internal types in the given set
of assemblies

In other words, by default, only non-generic types are registered; your GenericService<T> is skipped in this auto-registration process.
This is by design, and done so because generic types often need special handling. That's because they can easily overlap and their order of registration might be important.
So to fix this, you can do the following:
container.RegisterSingleton(
    typeof(IGenericInterface<>),
    typeof(IGenericInterface<>).Assembly);

container.RegisterSingleton(
    typeof(IGenericInterface<>), typeof(GenericService<>));

When there are many generic types, and they don't overlap with one another, you can instruct Simple Injector to also include generic type definitions in the registration. This can be done as follows:
container.Register(
    typeof(IGenericInterface<>),
    container.GetTypesToRegister(
        typeof(IGenericInterface<>),
        new[] { typeof(IGenericInterface<>).Assembly },
        new TypesToRegisterOptions { IncludeGenericTypeDefinitions = true }));


text:
Q: How do i eliminate a value from dropdown if it is auto populated My jsp dropdown list looks like
    <select name="dropdown1"
            name="authority_name">
            <option value="DEFAULT_VALUE"> <c:out value="${user[1]}" /></option>
            <option value="ROLE_USER">USER</option>
            <option value="ROLE_INSTRUCTOR">INSTRUCTOR</option>
            <option value="ROLE_ADMIN">ADMINISTRATOR /></option>
        </select>

Now, if i have the default value populated as USER i would like to eliminate it from the drop down list and only display the other 2 options along with default value. Is there any way i can do this?

A: If you want to remove options of USER, but keep all other options including INSTRUCTOR and ADMINISTRATOR, you can use a jstl if statement to only render the default option if the variable is not USER.
Something like this would work:
<select name="dropdown1"
        name="authority_name">
    <c:if test=${user[1] != 'USER'}><option value="DEFAULT_VALUE"><c:out value="${user[1]}" /></option></c:if>
    <option value="ROLE_USER">USER</option>
    <option value="ROLE_INSTRUCTOR">INSTRUCTOR</option>
    <option value="ROLE_ADMIN">ADMINISTRATOR /></option>
</select>

Hope that helps.


text:
Q: How to use sed to get the required output? This is my string:
<InstalledVersion Name="xyz" version="5" identifier="6.3.0.00.267" supportData="A002-IBY03" supportRelease="6.3" versionCode="xyz/abc/267"></InstalledVersion>

What i want output from this is as 203. The last character of A002 and last two character of IBY03. Thus the output being 203.
I am using sed 's/.*supportData="A\([0-9]\+[-][A-Z]\+[0-9]\+\)".*/\1/' | cut -c3,8,9'.
This gives me the correct output but I was wondering if I can directly do it through sed .
Any help  would be appreciated.
Thanks

A: You can use this sed command:
s='<InstalledVersion Name="xyz" version="5" identifier="6.3.0.00.267" supportData="A002-IBY03" supportRelease="6.3" versionCode="xyz/abc/267">'

sed -E 's/.*supportData="[^"]*([0-9])-[^"]*([0-9]{2})".*/\1\2/' <<< "$s"

Output:
203

A: Try this:
$ var='supportData="A002-IBY03"'
$ sed -r 's/.*([0-9])-.*([0-9][0-9])"/\1\2/' <<<$var
203

A: You can use something like this:
$ echo '<InstalledVersion Name="xyz" version="5" identifier="6.3.0.00.101" supportData="A002-IBY03" supportRelease="6.3" versionCode="xyz/abc/267">' | sed -r 's/^.*supportData=".{3}([0-9])-.{3}([0-9]{2}).*$/\1\2/'
203
$


text:
Q: C# Get max difference from 7 integers I have problem with getting the difference between the lowest and highest entered integer. This is my code so far, but I don't understand why I keep getting error messages.
using System;

class Program
{
    public static int array(int[] numbers)
    {
        int minint = array(numbers);
        int maxint = array(numbers);
        foreach (int value in array(numb)
        {
            if (value < minint) minint = value;
            if (value > maxint) maxint = value;
        }

        return maxint - minint;
    }
    static void Main(string[] args)
    {
        int[] numbers = new int[7];
        for (int i = 0; i < 7; i++)
        {
            Console.Write("Enter number {0}:  ", i + 1);
            numbers[i] = Convert.ToInt32(Console.ReadLine());
        }
        Console.WriteLine("Difference between min and max is: {0} ", array(numbers));
        Console.ReadLine();
    }
}

A: i'd go with the existing methods Min() and Max()
public static int array(int[] numbers)
{
    return numbers.Max() - numbers.Min();
}

otherwise your array method should look like this
public static int array(int[] numbers)
{
    int minint = numbers[0];
    int maxint = numbers[0];
    foreach (int value in numbers)
    {
        if (value < minint) minint = value;
        if (value > maxint) maxint = value;
    }
    return maxint - minint;
}

usually the difference is ment to be a positive value - so you should take the absolute value Math.Abs() or item = item < 0 ? -item : item; in case of negative numbers within your array


text:
Q: Using SELECT within SELECT in mysql query It is common to use SELECT within SELECT to reduce the number of queries; but as I examined this leads to slow query (which is obviously harmful for mysql performance). I had a simple query as
SELECT something
 FROM posts
 WHERE id IN (
  SELECT tag_map.id
  FROM tag_map
  INNER JOIN tags
  ON tags.tag_id=tag_map.tag_id
  WHERE tag IN ('tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6')
  )

This leads to slow queries of "query time 3-4s; lock time about 0.000090s; with about 200 rows examined".
If I split the SELECT queries, each of them will be quite fast; but this will increase the number of queries which is not good at high concurrency.
Is it the usual situation, or something is wrong with my coding?

A: You could improve it by using the following:
SELECT something
FROM posts
INNER JOIN tag_map ON tag_map.id = posts.id
INNER JOIN tags
ON tags.tag_id=tag_map.tag_id
WHERE <tablename>.tag IN ('tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6')

Just make sure you only select what you need and do not use *; also state in which table you have the tag column so you can substitute <tablename>

A: In MySQL, doing a subquery like this is a "correlated query". This means that the results of the outer SELECT depend on the result of the inner SELECT. The outcome is that your inner query is executed once per row, which is very slow.
You should refactor this query; whether you join twice or use two queries is mostly irrelevant. Joining twice would give you:
SELECT something
FROM posts
INNER JOIN tag_map ON tag_map.id = posts.id
INNER JOIN tags ON tags.tag_id = tag_map.tag_id
WHERE tags.tag IN ('tag1', ...)

For more information, see the MySQL manual on converting subqueries to JOINs.
Tip: EXPLAIN SELECT will show you how the optimizer plans on handling your query. If you see DEPENDENT SUBQUERY you should refactor, these are mega-slow.

A: Join does filtering of results. First join will keep results having 1st ON condition satisfied and then 2nd condition gives final result on 2nd ON condition.
SELECT something
FROM posts
INNER JOIN tag_map ON tag_map.id = posts.id
INNER JOIN tags ON tags.tag_id = tag_map.tag_id AND tags.tag IN ('tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6');

You can see these discussions on stack overflow :
question1
question2
Join helps to decrease time complexity and increases stability of server.
Information for converting sub queries to joins:
link1
link2
link3


text:
Q: C# Main Form Reference Exception i made an UserControl and wanted to add the MainForm Reference
  public partial class ConsolePage : UserControl
{
    public synForm mainForm = new synForm();

    public ConsolePage(synForm parentForm)
    {
        mainForm = parentForm();
        InitializeComponent();
    }

so, the thing is that as Long i create my UserControl in c# code (doesnt matter where) it works perfectly but when i try to add him from my Designer from Toolbox then im getting an exception.
I know, that i should call them like this
MyControl whatever = new MyControl(this);

and i know that i should correct that in my Form.Designer if i want to add myControl from Toolbox!
Dont hate me im new in programming and spelling :D
EDIT : <<<<<<<
Forgot to put what error i got :

System.ComponentModel.Design.Serialization.DesignerSerializationManager.CreateInstance(Type type, ICollection arguments, String name, Boolean addToContainer)

System.ComponentModel.Design.Serialization.DesignerSerializationManager.System.ComponentModel.Design.Serialization.IDesignerSerializationManager.CreateInstance(Type type, ICollection arguments, String name, Boolean addToContainer)

System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeInstance(IDesignerSerializationManager manager, Type type, Object[] parameters, String name, Boolean addToContainer)

System.ComponentModel.Design.Serialization.ComponentCodeDomSerializer.DeserializeInstance(IDesignerSerializationManager manager, Type type, Object[] parameters, String name, Boolean addToContainer)

System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)

System.ComponentModel.Design.Serialization.CodeDomSerializer.DeserializeStatementToInstance(IDesignerSerializationManager manager, CodeStatement statement)
 System.ComponentModel.Design.Serialization.CodeDomSerializer.Deserialize(IDesignerSerializationManager manager, Object codeObject)
bei System.Windows.Forms.Design.ControlCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, Object codeObject)

System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.DeserializeName(IDesignerSerializationManager manager, String name, CodeStatementCollection statements)

A: Without knowing the error message (you provided only the stack trace) and content of parentForm() it is not that easy to say. But it seems parentForm() is doning something that is not possible in the designer.
So you could try to not execute parentForm() in design mode by checking DesignMode (https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.component.designmode?redirectedfrom=MSDN&view=netframework-4.7.2#System_ComponentModel_Component_DesignMode).
public ConsolePage()
    {
        if (!DesignMode)
        {
            mainForm = parentForm();
        }
        InitializeComponent();
    }


text:
Q: Include file in bdist_wheel but not sdist Many people have complained about setuptools not including things mentioned in package_data when making an sdist. (See here and here and here.) However, it appears that this was changed at some point, so that items mentioned in package_data are included not only in bdist_wheels but in sdists also. My problem is that I want the old behavior; I want a file (namely, a compiled executable) to be included in the bdist_wheel, but not the sdist. How do I do that now?

A: Disclaimer
Although it's technically possible, beware that when the source dist doesn't contain the file and wheel does, you will end up in having different installations of the same package for the same metadata, which is a bad behaviour. In the example below,
$ pip install spam --only-binary=spam  # force installation from wheel

will install file.txt:
$ pip show -f spam | grep file.txt
  spam/file.txt

while
$ pip install spam --no-binary=spam  # force installation from source dist

will not. This is a definite source for introducing new errors and no user will ever say thanks to you for this decision.

If you are really sure this is what you need: you can exclude the file in MANIFEST.in. Example:
project
├── spam
│   ├── __init__.py
│   └── file.txt
├── MANIFEST.in
└── setup.py

MANIFEST.in
exclude spam/file.txt

setup.py
from setuptools import setup

setup(
    name='spam',
    version='0.1',
    packages=['spam'],
    package_data={'spam': ['file.txt']},
)

Building wheel:
$ python setup.py bdist_wheel >/dev/null 2>&1 && unzip -l dist/spam-*.whl | grep file.txt
    0  04-17-2019 21:25   spam/file.txt

Building source dist:
$ python setup.py sdist --formats=zip >/dev/null 2>&1 && unzip -l dist/spam-*.zip | grep file.txt
<empty>


text:
Q: Copying React State object; modifying copied object changes state object I am trying to copy a state object:
@boundMethod
private _onClickDeleteAttachment(attachmentName: string): void {
    console.log("_onClickDeleteAttachment | this.state.requestApproval[strings.Attachments]: ", this.state.requestApproval[strings.Attachments]);

    let requestApprovalClone = {... this.state.requestApproval}

    if (requestApprovalClone === this.state.requestApproval) {
        console.log("they are ===");
    }
    else {
        console.log(" they are not ===");
    }

    _.remove(requestApprovalClone[strings.Attachments], (attachment: any) => {
        return attachment.FileName === attachmentName;
    })

    console.log("_onClickDeleteAttachment | this.state.requestApproval[strings.Attachments]: ", this.state.requestApproval[strings.Attachments]);
    console.log("_onClickDeleteAttachment | requestApprovalClone[strings.Attachments]: ", requestApprovalClone[strings.Attachments]);
}

The state object is being altered too.  From what I have read, I shouldn't mutate a state object but only change it with setState.
How can I correct this?

A: You are getting that behavior, because the
let requestApprovalClone = {... this.state.requestApproval}
is only shallow copying the data, your attachments property has some nested objects and it keeps the same reference and therefore when changing it, the cloned object gets altered and the state too.
To avoid that, you can perform another copy of your attachments property like this :
let attachments = [...requestApprovalClone[strings.Attachments]];
_.remove(attachments, function (attachment)  {
  return attachment.FileName === attachmentName;
});

Changing the attachments variable content won't afftect the state anymore.
you can read more about that behavior here

A: It has to to with the way that JS handles their const references.
For those who feel adventerous:
let requestApprovalClone = JSON.parse(JSON.stringify(this.state.requestApproval));

// modify requestApprovalClone ...

this.setState({
  requestApproval:requestApprovalClone
})

It would be interesting if Object.assign({},this.state.requestApproval); is faster than the whole JSON stringify/parse stuff or vice versa

A: You can have something like:
let requestApprovalClone = Object.assign({},this.state.requestApproval);

requestApprovalClone.strings.Attachments = requestApprovalClone.strings.Attachments.slice(); // will create a shallow copy of this array as well

_.remove(requestApprovalClone[strings.Attachments], (attachment: any) => {
        return attachment.FileName === attachmentName;
    })

this.setState({
  requestApproval:requestApprovalClone
})// If you want to update that in state back


text:
Q: Windows 7 finding location of installed program Usually on Windows XP, if I wanted to know the location of an installed program, I would just click 'Properties' and it would show where the executable is located.
On Windows 7, I do the same thing and I get this:

How can I find out where programs are located based on the shortcut?
I did however notice that for some programs it does show a shortcut under the 'Target', but not in the case with iTunes for example.

A: I had a similar issue and was able to use Task Manager (Ctrl-Alt-Delete → Start Task Manager) to find the application (after openingit) in  the Applications tab.
Right-click on the desired application to bring up the menu and choose Go To Process. This shows which process is associated with the app in the Processes tab.
Then, right-click on the process to bring up the menu and choose either Properties or Open File Location to find out more.

A: For those looking to do this in PowerShell without using a module:
$lnk = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Adobe\Adobe Acrobat X Pro.lnk"
$WindowsInstaller = New-Object -ComObject WindowsInstaller.Installer
$ShortcutTarget = $WindowsInstaller.GetType().InvokeMember("ShortcutTarget","GetProperty",$null,$WindowsInstaller,$lnk)
$StringData1 = $ShortcutTarget.GetType().InvokeMember("StringData","GetProperty",$null,$ShortcutTarget,1)
$StringData3 = $ShortcutTarget.GetType().InvokeMember("StringData","GetProperty",$null,$ShortcutTarget,3)
$WindowsInstaller.GetType().InvokeMember("ComponentPath","GetProperty",$null,$WindowsInstaller,@($StringData1,$StringData3))

A: What you are seeing are special shortcuts called Advertised Shortcuts.  The shortcuts actually link to msiexec.exe which is the Windows Installer executable.  Advertised shortcuts allow installer authors to install only portions of their application and then install additional pieces when they are accessed via the advertised shortcut.  Windows Installer also automatically checks the integrity of all of the installed files each time the application is run so you can be sure the application is valid when it is run.
Here is a Stack Overflow question with a bit more info on advertised shortcuts.
Finding the executable the shortcut eventually runs is not a simple task and would involve some digging through the registry.  Hugh's suggestion is likely much simpler.

A: Try either of the below (from Tek-Tips Forums):
VbScript
' GetRealTarget.vbs
' This version needs to be run under wscript engine rather than cscript

' Pass the full path to an MSI "Advertised Shortcut" lnk file (including the extension) as a parameter
' e.g. assuming that we have a default install of Office 2003 for All Users:
' GetRealTarget "C:\Documents and Settings\All Users\Start Menu\Programs\Microsoft Office\Microsoft Office Excel 2003.lnk"
' Displays fully resolved target for the MSI shortcut

Option Explicit
Dim MSITarget

On Error Resume Next ' just some simple error handling for purposes of this example
If wscript.arguments.count = 1 Then ' did actually pass an MSI advertised shortcut? Or, at least, a parameter that could be such a thing?
   With CreateObject("WindowsInstaller.Installer")
      Set MSITarget = .ShortcutTarget(wscript.arguments(0))
      If Err = 0 then
         MsgBox .ComponentPath(MSITarget.StringData(1), MSITarget.StringData(3))
      Else
         MsgBox wscript.arguments(0) & vbcrlf & "is not a legitimate MSI shortcut file or could not be found"
      End If
   End With
End If
On Error Goto 0

PowerShell (with the install of this Windows Installer Module)
get-msiproductinfo | where { $_.ProductState -match "Installed" } | fl AdvertisedProductName, InstallLocation

A: Open regedit and search the program name. It will take few "search again" (F3) but eventually you´ll find the folder.
In my case, it was under HKEY_CLASSES_ROOT\Applications\<name of app>\shell\open\command

A: I have wondered the same thing for some shortcuts under win XP. I tried Cygwin's readshortcut but it didn't tell me the real target:
$ readshortcut.exe -fa "Microsoft Word.lnk"
Target: /cygdrive/c/WINDOWS/Installer/{00000409-78E1-11D2-B60F-006097C998E7}/wordicon.exe
Working Directory:
Arguments:
Show Command: Normal
Icon Library: /cygdrive/c/WINDOWS/Installer/{00000409-78E1-11D2-B60F-006097C998E7}/wordicon.exe
Icon Library Offset: 0
Description: Create and edit text and graphics in letters, reports, Web pages, or e-mail messages by using Microsoft Word.

So they're obviously something to do with Windows Installer. To find the executable, you can  always just run it and use Process Explorer to get the path - in my case, C:\Program Files\Microsoft Office2K\Office\WINWORD.EXE.

A: If you have User Account Control active, then when UAC box comes up asking
to Allow, Cancel, you often see another (overlooked by many) dropdown arrow under it with the title "Details". If you click on Details you should see
the actual location of the target.
P.S. if I recall this issue goes way back past windows 7, even past XP, to win 98 where right clicking the shortcut, selecting properties, often wouldn't show the target. Then we had to start the app, open task manager, right click app in list, select go to process, right click process, select open file location (or sometimes properties). Now UAC makes for less steps.

A: A trick that may work is this: Startup CMD and run:
dir C:\iTunes /s /b
It would report any file or directory named exactly "iTunes" (not case sensitive). If you have more than one fixed drive, it may be needed to repeat for that drive as well.
Or, you can create a file in the "unknown folder" (here: iTunes), then look for that file on disk:
dir C:\*testfilenumber1* /s /b

A: The simplest way to find out the place of an executable:

*

*Find the program on Start menu and move it to the desktop using right mouse button. This creates a link.

*Put pointer over link and click right mouse. Select "Properties"

*On that screen you have the full path to the executable. Copy to buffer and paste whenever you need.


text:
Q: Sencha touch 2 failed to load bootstrap.json My app and all the Sencha touch 2 example apps work perfectly (opening via desktop browser) when I host them on local IIS server, but when I copy the same code to an IIS instance running on Windows Server machine, I get this error on opening both touch examples as well as my app:-
GET http://servername/touch-2.3.1/examples/map/bootstrap.json 404 (Not Found)

This happens with all apps and the same code is running without errors on my local machine. Am I missing any configuration?

A: Solved! I had not added json MIME type to the IIS server (as was specified in the tutorial). Still keeping the question if someone else makes the same mistake. Here is the stackoverflow answer to enable json mime type in IIS.


text:
Q: Нахождение главного потока Здравствуйте. Ситуация такая. Есть некое приложение. У приложения много потоков, в одном из потоков висит окно приложения с известным названием класса и window name. Как нам его найти? :)
A: Попробуйте FindWindowEx:
HWND WINAPI FindWindowEx(
  __in_opt  HWND hwndParent,
  __in_opt  HWND hwndChildAfter,
  __in_opt  LPCTSTR lpszClass,
  __in_opt  LPCTSTR lpszWindow
);

UPD: Найти поток, в котором было создано то или иное окно, можно используя метод GetWindowThreadProcessId:
DWORD WINAPI GetWindowThreadProcessId(
  __in       HWND hWnd,
  __out_opt  LPDWORD lpdwProcessId
);


text:
Q: Ubuntu 13.04 weird partition shown in Gparted My Ubuntu is a bit slow to boot so I started to look at partitions and with Gparted I have found a weird format partition. Here is a picture!

Here is a picture of the Gparted partitions !

explanations:
Ubuntu is inside dev/sda3 partition and the strange 3gb partition is inside the Linux partition so I am wondering what it could be and if I can erase it safely.
What about the unallocated spaces? Why are they there and could they slow down my system?
thanks a lot
EDIT: I have found this thread where they suggest defragmenting with windows but since it is a partition inside the ubuntu partition I am wondering if it will do any good:
http://gparted-forum.surf4.info/viewtopic.php?id=13447

A: Your /dev/sda3 is an extended partition, which is just a placeholder for the logical partitions inside it. Extended partitions don't really "belong" to any given OS, although it's possible to create an extended partition and then populate it with logical partitions that belong to just one OS. That's not the case on your disk, though.
I disagree with the suggestion by Alaa that you can safely delete /dev/sda5. As an NTFS partition, /dev/sda5 is almost certainly a Windows partition, so its non-use by Linux is irrelevant. Instead, I recommend you evaluate its utility, or lack thereof, from Windows. You might be better to ask about it on a Windows forum -- but be aware that many Windows users are clueless about Linux and about the needs of a multi-boot computer; they may offer bad advice based on this poor understanding of such issues.


text:
Q: apollo boost mutations no response I am just fairly new in React and especially in GraphQL so right now, it's my first time using React-Apollo and I am using Apollo Boost.
I am having an error (or lack thereof) when I used React-apollo's Mutation inside my render function. Here are snippets of my code (forgive the bad practices I made in this code, I will fix them once I fix the mutations):
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ApolloProvider } from "react-apollo";
import { ApolloClient, HttpLink, InMemoryCache } from "apollo-boost";
import registerServiceWorker from './registerServiceWorker';

const client = new ApolloClient({
  link: new HttpLink({
  uri: 'http://localhost:3000/graphql',
}),
  onError: ({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
      console.log(graphQLErrors);
    }
  },
  cache: new InMemoryCache()
});

const AppWithProvider = () => (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

ReactDOM.render(<AppWithProvider />, document.getElementById('root'));
registerServiceWorker();

BOOK_CART
 const BOOK_CART = gql `mutation booking($rDateStart: Date!, $rDateEnd: Date!, $grade: Int!, $section: String!, $userId: ID!, $cartlabId: ID!){
       bookCart(rDateStart: $rDateStart, rDateEnd: $rDateEnd, grade: $grade, section: $section, userId: $userId, cartlabId: $cartlabId){
        id
        rDateStart
        rDateEnd
        }
      }
    `;

ReserveCartsForm Class
class ReserveCartsForm extends React.Component {
constructor(props) {
    super(props);
      this.state = {
      userId: 1,
      classroom: '',
      subject: '',
      cart: '',
      timezone: '',
      reservationTime: '',
      endTime: '',
      open: false,
      date: '',
      fromDt: '',
      toDt: '',
      created: new Date().toISOString(),
      status: 'reserved'
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleOnChange = this.handleOnChange.bind(this);
  }
  handleOnChange = (key, e) => {
    this.setState({ [key]: e.target.value });
  };

Render
render() {
const { classes } = this.props;
const { userId, fromDt, toDt, classroom, cart, timezone, reservationTime, laboratory } = this.state;

const fromDateTime = this.state.fromDt = Moment(this.state.date + " " + this.state.reservationTime).toISOString();

const toDateTime = () => {
  this.state.endTime = Moment.utc(+Moment.utc(this.state.reservationTime, 'hh:mm A').add(40, 'm')).format('HH:mm');
  return this.state.toDt = Moment(this.state.date + " " + this.state.endTime).toISOString();
}
return

    <Typography variant="title" className={classes.heading} component="h3" color="primary">
      Make New Reservation
    </Typography>

    <Grid container spacing={24}>
      <Grid item xs={8} sm={7} md={6} lg={4} xl={3} className={classes.grid}>
        <Card className={classes.card}>
          <CardContent>

              <Typography variant="headline" component="h1" color="inherit" className={classes.title}>
                Carts Reservation Form
              </Typography>

              <Mutation mutation={BOOK_CART}>
                {bookCart =>

                <FormGroup row={true} className={classes.formGroup}>
                  <form onSubmit={e => {
                    e.preventDefault(); console.log(this.state); bookCart({ variables: { rDateStart: fromDt, rDateEnd: toDt, grade: classroom.substring(1), section: classroom.substring(1, 1), userId: userId, cartlabId: cart } }); }}>
                    <FormControl className={classes.formControl}>
                      <InputLabel htmlFor="carts">
                        Choose Cart
                      </InputLabel>
                      <Select value={cart} labelstyle={classes.select} onChange={this.handleChange} inputProps={{ name: "cart", id: "carts" }}>
                        <MenuItem value="">
                          None
                        </MenuItem>
                        <MenuItem value={1}>iPad Carts</MenuItem>
                        <MenuItem value={2}>MacBook Carts</MenuItem>
                        <MenuItem value={3}>MacBook Air Carts</MenuItem>
                      </Select>
                    </FormControl>
                    <form className={classes.formControl} noValidate>
                      <TextField id="date" label="Date" type="date" className={classes.textField} InputLabelProps={{ shrink: true }} onChange={e => this.handleOnChange("date", e)} />
                    </form>
                    <FormControl className={classes.formControl}>
                      <InputLabel htmlFor="timezone">
                        Choose Timezone
                      </InputLabel>
                      <Select value={timezone} labelstyle={classes.select} onChange={this.handleChange} inputProps={{ name: "timezone", id: "timezone" }}>
                        <MenuItem value="">
                          None
                        </MenuItem>
                        <MenuItem value={"P"}>
                          Pre School (40 mins.)
                        </MenuItem>
                        <MenuItem value={"G"}>
                          Grade School (50 mins.)
                        </MenuItem>
                        <MenuItem value={"H"}>
                          High School (60 mins.)
                        </MenuItem>
                      </Select>
                    </FormControl>
                    <FormControl className={classes.formControl}>

                      <FormControl className={classes.container}>
                        <InputLabel htmlFor="endTime">
                          Time of Borrowing
                        </InputLabel>
                        <Select value={reservationTime} labelstyle={classes.select} onChange={this.handleChange} inputProps={{ name: "reservationTime", id: "endTime" }}>
                          <MenuItem value={`7:40`}>Period 1</MenuItem>
                          <MenuItem value={`8:20`}>Period 2</MenuItem>
                          <MenuItem value={`9:00`}>Period 3</MenuItem>
                          <MenuItem value={`9:40`}>Period 4</MenuItem>
                          <MenuItem value={`10:20`}>Period 5</MenuItem>
                          <MenuItem value={`11:00`}>Period 6</MenuItem>
                          <MenuItem value={`11:40`}>Period 7</MenuItem>
                        </Select>
                        <FormHelperText id="name-helper-text">
                          The time the reservation ends.
                        </FormHelperText>
                      </FormControl>
                    </FormControl>
                    <FormControl className={classes.formControl}>
                      <InputLabel htmlFor="age-simple">
                        Subject
                      </InputLabel>
                      <Input id="age-simple" placeholder="Subject" onChange={e => this.handleOnChange("subject", e)} />
                      <FormHelperText id="name-helper-text">
                        The subject the carts will be used in
                      </FormHelperText>
                    </FormControl>
                    <FormControl className={classes.formControl}>
                      <TextField id="classroom" label="Classroom" className={classes.textField} value={laboratory} onChange={e => this.handleOnChange("classroom", e)} />
                      <FormHelperText id="name-helper-text">
                        Where the carts will be used
                      </FormHelperText>
                    </FormControl>
                    <FormControl className={classes.container} disabled>
                      <Input id="fromDt" className={classes.textField} value={fromDateTime} onChange={e => this.handleOnChange("fromDt", e)} />
                    </FormControl>

                    <FormControl className={classes.container} disabled>
                      <Input id="toDt" className={classes.textField} value={toDateTime()} onChange={e => this.handleOnChange("toDt", e)} />
                    </FormControl>
                    <Button variant="raised" color="primary" type="submit">
                      Reserve
                    </Button>
                    </form>
                  </FormGroup>

}
              </Mutation>

          </CardContent>
          <CardActions>
            <Dialog open={this.state.open} onClose={this.handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description">
              <DialogTitle id="alert-dialog-title">
                {"Cart reserved"}
              </DialogTitle>
              <DialogContent>
                <DialogContentText id="alert-dialog-description">
                  You have reserved a cart. Click to confirm.
                </DialogContentText>
              </DialogContent>
              <DialogActions>
                <Button onClick={this.handleClickClose} color="primary">
                  Back
                </Button>
                <Button onClick={(this.props.onSubmit, this.handleClickClose)} color="primary" autoFocus>
                  Confirm
                </Button>
              </DialogActions>
            </Dialog>
          </CardActions>

        </Card>
      </Grid>
    </Grid>

;
        }
  }

    ReserveCartsForm.propTypes = {
      classes: PropTypes.object.isRequired
    };

    export default withStyles(styles)(ReserveCartsForm);

I tried looking for examples such as React Apollo 2.1 Mutations documentation here and this question, too from here. So these were the few examples on where my code came from for the mutations.
Any suggestions would be very helpful and appreciated.