text:
Q: MATLAB find a row of chars in a matrix There is a char matrix. Each row is a word. All the words/rows have the same length.
Is there anyway to find a target word in this matrix using find() function?
Say M=[o k a y; g o o d; h a v e]; A target word W='have'; Is there any function to search W in M and return the row index?
When I try index = find(isequal(W,M)) and index = find(isequal(W,M(:,:))), they both return empty array.
I know that I can use linear search, i.e. to compare row by row, just wonder if there is a built-in function to solve this problem. Thanks!

A: You need to compare M with a string. I am assuming M contains of individual characters as follows:
M=['o' 'k' 'a' 'y'; 'g' 'o' 'o' 'd'; 'h' 'a' 'v' 'e']

and W='have'
So in order to compare each row of M with W, you need to use strcmp. For that, you need M to be a cell array. You can convert each row of M into a cell array by using mat2cell.
equalRows=strcmp(W, mat2cell(M,ones(1,size(M,1)),size(M,2)));

% Answer

equalRows =

 0
 0
 1

Use find command on the above output to get the indices.

A: Another approach would be to use ismember.  Assuming that M is a character array like you have defined, you would thus do:
W = 'have';
[~,idx] = ismember(M, W, 'rows');

The first input is the character array defined, the second input is the string we are searching for, and we choose 'rows' as the flag as we want to search on a row basis.  Each word is defined in one row.  The first output is true/false that is of the same size as M that tells you whether or not we have found the word indexed by that row in M is a match to the one you're searching for.  Because we only want to know where that word is, we can suppress that first output. idx tells you which row the word was found.
When we call this function, we get:
idx =

3

This means that the third row contains the word you're looking for.  However, if you're dead set on using find, consider using ismember in conjunction with find:
W = 'have';
idx = find(ismember(M, W, 'rows'));

idx =

3

However, the advantage with the above approach is that it will find all locations that match the particular word you're looking for.


text:
Q: Python OpenCV - Update camera index of live webcam view I am viewing a webcam camera live feed. I would like to incorporate this into a Tkinter GUI and have a dropdown selection that allows one to change the camera index, and therefore the webcam being used, on the fly.
How can this be achieved?
Example code:
import cv2

def show_webcam(mirror=False):
    cam = cv2.VideoCapture(0)
    while True:
        ret_val, img = cam.read()
        if mirror:
            img = cv2.flip(img, 1)
        cv2.imshow('my webcam', img)
        if cv2.waitKey(1) == 27:
            break  # esc to quit
    cv2.destroyAllWindows()

def main():
    show_webcam(mirror=True)

if __name__ == '__main__':
    main()

A: To change camera at run time all you need to change is the index you pass in
cv2.VideoCapture(index).
Find out how many camera you will be using for your app and for 3 cameras, you can change it through changing index to 0 or 1 or 2.
Add one more parameter as index
show_webcam(mirror=True, index)
in function side you can use this
def show_webcam(mirror=False,index):
    cam = cv2.VideoCapture(index)
    while True:
        ret_val, img = cam.read()
        if mirror:
            img = cv2.flip(img, 1)
        cv2.imshow('my webcam', img)
        if cv2.waitKey(1) == 27:
            break  # esc to quit
    cv2.destroyAllWindows()

redpajama_set_name: RedPajamaStackExchange


text:
Q: XML Parsing Error I am consuming a web service as its output is an XML string. I am parsing it into a document and getting each child node value one by one and inserting into my SQLlite table as shown below:
public void DownloadAndInsertProblemAndReasonCode(String serverIPAddress,
            String deviceId) {
        String SOAP_ACTION = "http://VisionEPODWebService/GetProblemAndReasonCodesNew";
        String OPERATION_NAME = "GetProblemAndReasonCodesNew";
        String WSDL_TARGET_NAMESPACE = "http://VisionEPODWebService/";
        String SOAP_ADDRESS = "";

        SOAP_ADDRESS = "http://" + serverIPAddress
                + "/VisionEPODWebService/SystemData.asmx";
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                OPERATION_NAME);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER10);
        request.addProperty("deviceID", deviceId);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
        try {
            httpTransport.call(SOAP_ACTION, envelope);
            Object response = envelope.getResponse();
            DocumentBuilderFactory docBuilberFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docBuilberFactory.newDocumentBuilder();
            InputSource inputSource = new InputSource();
            inputSource
                    .setCharacterStream(new StringReader(response.toString()));
            Document doc = docBuilder.parse(inputSource);
            NodeList nodesProblemCode = doc
                    .getElementsByTagName("tblProblemCode");
            ContentValues initialProblemCodeValues = new ContentValues();
            dbAdapter = new DatabaseAdapter(this.context);
            dbAdapter.open();
            dbAdapter.BeginTransaction();
            dbAdapter.DeleteRecord("tblProblemCode", "", "");

            for (int i = 0; i < nodesProblemCode.getLength(); i++) {
                Element element = (Element) nodesProblemCode.item(i);

                NodeList PKProblemCode = element
                        .getElementsByTagName("PKProblemCode");
                Element line = (Element) PKProblemCode.item(0);
                initialProblemCodeValues.put("PKProblemCode",
                        getCharacterDataFromElement(line).toString());

                NodeList ProblemCode = element
                        .getElementsByTagName("ProblemCode");
                line = (Element) ProblemCode.item(0);
                initialProblemCodeValues.put("ProblemCode",
                        getCharacterDataFromElement(line));

                NodeList ProblemCodeDescription = element
                        .getElementsByTagName("ProblemCodeDescription");
                line = (Element) ProblemCodeDescription.item(0);
                initialProblemCodeValues.put("ProblemCodeDescription",
                        getCharacterDataFromElement(line).toString());

                NodeList VWReturn = element.getElementsByTagName("VWReturn");
                line = (Element) VWReturn.item(0);
                initialProblemCodeValues.put("VWReturn",
                        getCharacterDataFromElement(line).toString());

                dbAdapter.InsertRecord("tblProblemCode", "",
                        initialProblemCodeValues);
            }

            NodeList nodesReasonCode = doc
                    .getElementsByTagName("tblReasonCode");
            ContentValues initialReasonCodeValues = new ContentValues();
            dbAdapter.DeleteRecord("tblReasonCode", "", "");
            for (int i = 0; i < nodesReasonCode.getLength(); i++) {
                Element element = (Element) nodesReasonCode.item(i);

                NodeList PKReasonCode = element
                        .getElementsByTagName("PKReasonCode");
                Element line = (Element) PKReasonCode.item(0);
                initialReasonCodeValues.put("PKReasonCode",
                        getCharacterDataFromElement(line).toString());

                NodeList ReasonDescription = element
                        .getElementsByTagName("ReasonDescription");
                line = (Element) ReasonDescription.item(0);
                initialReasonCodeValues.put("ReasonDescription",
                        getCharacterDataFromElement(line));

                dbAdapter.InsertRecord("tblReasonCode", "",
                        initialReasonCodeValues);
            }
            dbAdapter.SetSucessfulTransaction();
            dbAdapter.EndTransaction();
            dbAdapter.close();
        }

        catch (Exception exception) {
            exception.toString();
        }

    }

public static String getCharacterDataFromElement(Element e) {

        Node child = e.getFirstChild();
        if (child instanceof CharacterData) {
            CharacterData cd = (CharacterData) child;
            return cd.getData();
        }
        return "?";
    }

The problem is that after some time the XML string will not have some of child node. For example
"ProblemCode" child node.....at that time the code shows error.
How can I check whether there exists an element in the document, or whether values exist or not for the element?

A: I think you need to check if the child node exists: specifically for your problem node:
NodeList NL = element.getElementsByTagName("PKProblemCode");
if ((NL==null)||(NL.getLength()==0)) {
  //No such node so use a default instead
} else
  Element line = (Element) PKProblemCode.item(0);


text:
Q: SQL Server 2008 Express Management Studio connects to database from LAN but using same connection string vb.net application fails to connect I developed an application using vb.net that connects to SQL Server Express 2008 R2 database (Hospital) through LAN, from a client PC.
SQL Server 2008 Express Management Studio successfully connects to the database (Hospital), but using the same connection string, my vb.net application fails to connect.
My connection string is:
"Data Source=TCP:192.168.1.1\SQLEXPRESS;Initial Catalog=Hospital;Persist Security Info=True;User ID=XXXX;Password=1111"

What is the problem? Can anybody help me to solve that?

A: First create a ODBC connection.
Then follow this connection string:
Data Source="SERVERNAME";Initial Catalog="DATABASE NAME";User ID="USERNAME";Password="PASSWORD";
IT should Work


text:
Q: Why do many animals die at the same time when lighting hits surroundings? I have been reading about many cases in history of lighting striking and killing dozens even hundreds of animals, to be more specific quadruples, at the same time. Apparently this doesn't happen with small animals, only with animals that have a significant separation between their legs. Why does this happen.
Here is an article reporting one of the cases and it has an explanation that I didn't understand. https://www.google.com.co/amp/s/motherboard.vice.com/amp/en_us/article/78kewb/a-very-simple-explanation-for-how-lightning-killed-323-reindeer-at-once

A:
because it said that a squirrel could survive, and said something about the distance of the legs, that part is very unclear to me

Every electric conductor has a property called "resistance."  You may have heard that "electricity always follows the path of least resistance."  That's almost true, but really, its only most of the current that follows the path of least resistance.
When there's more than one path for current to follow, the fraction of current that follows each path is inversely proportional to the resistance of the path.  The path with less resistance gets more current and vice versa.
The resistance of an overhead power line is extremely low compared to the resistance of the body of a squirrel.  -Especially if you compare it to the resistance of a squirrel's dry skin.  When a squirrel walks along a line that is carrying current on a dry, sunny day; virtually all of the current will stay in the line, and only a tiny, tiny amount will go through the squirrel's body.
You can ignore the part about the squirrel touching the tree and the power line at the same time.  That's a case where the squirrel's body would be the only path for current to flow.  That is unlike what happened to the caribou.
What happened to the caribou was that lightning sent a huge amount of current (could have been as much as 100,000 Amperes at the point of the strike) travelling along the surface of the ground.  The caribou were wet.  And the resistance of the path through their wet skin and their bodies probably was not very different from the resistance of the ground that they were standing on.  Therefore, a significant amount of current took the detour, up one leg, through the animal's heart, and down another leg instead of staying in the ground.
Like I said, a big lightning bolt can carry more than a hundred thousand Amperes.  It only takes a few hundredths of an Ampere to put an unlucky mammal's heart into fibrillation.

P.S., Sqirrels in front of my house usually walk on the telephone wires and TV cable which are closer to the ground than the power lines.  Those wires are low voltage, carry very little current, and they're insulated (i.e., covered in very high-resistance material).

A: I wouldn't be surprised if it has something to do with "ground step potential".  When a high voltage source, e.g a downed transmission line, touches the ground, the voltage does not go from the high potential to zero (ground) over an infinitely small distance, but over a measurable distance.  This is in addition to the factors that james large mentions.
One reference I found states the voltage drops by half every 2.5-3 feet away from the energized source.  So a human, or a deer, with their feet spread 3-4 feet radially from the source would see a significant potential difference between their feet, leading to a large current flowing through the body as james large details.  A smaller animal would experience a much smaller potential difference and less current, and in the extreme case of a squirrel or bird on a power line, there should be no real potential difference between limbs, and thus no current.  Also if the potential difference is low enough, it's not enough to cause significant current to flow due to the resistance of dry skin.
As a side note, don't go close to a downed power line for this reason.
Here's a DOE report on an incident that describes some of the details.  Here's some info on human electrical resistances.


text:
Q: Why is my data being interpreted as a readable stream instead of a json object? I'm building a simple REST API in Kotlin and front-end with React. I'm pretty new to Kotlin and Spring, but I've managed to get a simple service working with Postman. I'm able to return all objects in an SQL table using JpaRepository interface. When I make the call through Postman, my output is as expected (looks like a normal Json object).
However, when I make the call through a standard react fetch the body is produced as a ReadableStream {locked: false}. I did some research on readable streams and they appear to mostly be for images. I tried body.getReader() from https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams, but that did not work either.
Here is my Kotlin code:
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/catalog")
class ArtworkController (
    private val artworkService: ArtworkService
        ) {

    @CrossOrigin
    @GetMapping("")
    @ResponseBody
    fun getData(): MutableList<Artwork> {
//        println(artworkService.getArt().javaClass.kotlin)
        return artworkService.getArt()
    }

}

@Service
class ArtworkService(
    private val artworkRepository: ArtworkRepository
){

    fun getArt(): MutableList<Artwork> {
        return artworkRepository.findAll()
    }
}

These are in separate files - just joined them here for brevity.
Any help would be greatly appreciated!

A: It turns out I was immediately returning a promise and had to set up an async function to handle the request.
  const { isLoading, error, data } = useQuery("repoData",
  async () => {
    const data = await fetch("https://url_here")
    .then(function(response) {
      return response.json()
    }

  )
  setData(data)
  }

For context, this request is wrapped in react-query but works without it as well.


text:
Q: Correct way to insert a view with Backbone.js I have a simple backbone.js app. I want to render a view into the DOM of the HTML page, this view is a detail view for a model. My HTML page already has the DIV element that I want to render the view into. If I try to render my view like this:
detailView = new RulesPanelView({model : @model})
$("#detail").html(detailView.render().el)

It fails and I get [Object HTMLDivElement] inserted into the DOM, not my rendered HTML.
This is the only way I can get it to work and it seems like a hack:
$("#detail").html('')
detailView = new RulesPanelView({model : @model})
$("#detail").append(detailView.render().el)

Having to empty the HTML of the DIV before rendering so I don't get multiple views rendered inside #detail which is what would happend with append.
Also aren't I creating way too many views this way, just seems cleaner to replace the HTML as in the first code segment?
What is the correct way to render this view?

A: What you want is to pass the already inserted DOM node to the view as a 'el' option to the constructor:
new RulesPanelView({el: $("#detail")});

This way, it won't render again. You still need to make sure your view's 'render' method will be able to render a correct view from an updated model, though.
The backbone documentation mentions this  as a good way to avoid rendering too much stuff at once.

A: I actually append in the render method of the view. This doesn't work if you want to re-render when models change - but for that I've added a refresh method that render actually calls before appending. I then bind the refresh to the model change (if I need that). So in my View, I do this:
render: function(){
    var markup = this.refresh();
    $(markup).appendTo('#some-selector');
    return this;
},
refresh: function(){
    return $(this.el).html($.mustache(this.template, this.model.toJSON()));
},

Not sure if that's the "best", but I think it works pretty well. I've also seen where you have a collection bound to a view that loops through all of the models and renders "sub-views" of the collection view - this provides a nicer programmatic approach than hard-coding where you're going to append.


text:
Q: mssql_fetch_array not returning false? I've got a php script that is supposed to generate images based on an MS SQL database (specifically, greetings cards for our first-year students). For some reason, after it runs out of rows in the result resource, mssql_fetch_array() goes back to the start of the result rather than returning false. Can anyone tell me why this could be?
The actual messages are in .txt files on the server, due to MS SQL Server's habit of mangling the punctuation. Database fields are id | fname | sname | tutgrp | house.
Relevant portion of code:
    $dbConn = mssql_connect($dbHost, $dbUser, $dbPass) or die("Connection to database failed");
mssql_select_db($dbData, $dbConn) or die("Unable to select database");

$query = "SELECT * FROM newIntakeTest;";
$result = mssql_query($query, $dbConn) or die("Unable to query");

while(False !== ($row = mssql_fetch_assoc($result)))
{
    array_walk($row, 'trim_value');
    echo $row["sname"].", ".$row["fname"]."... ";
    $image = imagecreatefrompng("res/".$row["house"].".png");
    $black = imagecolorallocate($image,0,0,0);
    //tutor msg
    imagettftext($image, 35, 0, 57, 86, $black, $fontBold, "Message from your Tutor:");
    $fn = "in/".$row["tutgrp"].".txt";
    $fh = fopen($fn,'r');
    $tutormsg = fread($fh,filesize($fn));
    fclose($fh);
    imagettftext($image, 35, 0, 57, 139, $black, $fontStd, wrap(35,0,$fontStd,$tutormsg,1640));

    //HoH msg
    imagettftext($image, 35, 0, 57, 1399, $black, $fontBold, "A message from ".$heads[$row["house"]].", Head of ".$row["house"]." house:");
    $fn = "in/".$row["house"].".txt";
    $fh = fopen($fn,'r');
    $headmsg = fread($fh,filesize($fn));
    fclose($fh);
    imagettftext($image, 35, 0, 57, 1455, $black, $fontStd, wrap(35,0,$fontStd,$headmsg,1640));

    printaligned($image, "To: ".$row["fname"]." ".$row["sname"], $fontStd, 70, 450, $black);
    printaligned($image, "From: ".substr($row["house"],0,1)."-".$row["tutgrp"], $fontStd, 70, 1985, $black);
    printaligned($image, $row["house"]." House", $fontStd, 70, 2130, $black);

    imagepng($image,"out/".$row["id"]."_".$row["sname"]."_".$row["fname"].".png");
    echo "done.<br />";
    imagedestroy($image);

}

A: Change your while to:
while($row = mssql_fetch_assoc($result))

You are using False, not false - that will cause a problem.

A: I believe the typical convention is just
while($row = mssql_fetch_assoc($result))


text:
Q: I am having a hard time understanding this question. Use the graph of $f(x)$ and $g(x)$ to answer the following.
a. $(1)$
b. $(−7)$
c. $(7) − (4)$
d. $((−5))$
e. Find the $x$-value(s) that satisfy $() = 6.$
f. State the domain of $f(x)$ in interval notation.
g. State the range of $g(x)$ in interval notation.
Tne graph of $f(x)$ and $g(x)$

A: From the graph, we have: $$g(1)=4 \land f(-7)=-4 \land f(7)-g(4)=1 \land f(g(-5))=f(4)=6$$
Also, we have $$f(x)=6 \leftrightarrow x=4\lor x=9$$
And range of $g(x)$ is $2\leq y\leq 7$.


text:
Q: A not Euclidean PID by prof. Wilson Let $\omega=\frac{1+\sqrt{-19}}{2}$ and let $R=\mathbb{Z}[\omega]$. I have to prove that $R$ is a PID. To prove this fact, let I be an ideal of R and choose a non-zero $b \in I$ such that its complex norm $|b|$ is the least possible. Then let $a \in I \setminus\{b\}$. I have to prove that there exist $p,q \in \mathbb{Z}[\omega]$ such that $|ap−bq|<|b|$.
Since we may replace $a$ by any element $a'=a−bq$, we may subtract any desired element of $R$ from $\frac{a}{b}$.
1) In particular, we can assume that the imaginary part $y$ of $\frac{a}{b}=x+iy$ lies in $[-\frac{\sqrt{-19}}{4};\frac{\sqrt{-19}}{4}]$. How can I obtain this particular interval? Can I choose another interval?
2) Now if the imaginary part of $\frac{a}{b}$ lies strictly between $\pm \frac{\sqrt{3}}{2}$ then $\frac{a}{b}$ lies at distance less than 1 from some ordinary integer, and we are done. Why I obtain the numbers $\pm \frac{\sqrt{3}}{2}$? May I take another couple of particular numbers? Moreover, how can I proof that $\frac{a}{b}$ lies at distance less than 1 from some ordinary integer?
3) We may assume that the imaginary part of $\frac{a}{b}$ lies between $\frac{\sqrt{3}}{2}$ and $\frac{\sqrt{19}}{4}$ (or the negative of this, where the argument is the same). Hence the imaginary part of $\frac{2a}{b}-\omega$ lies between $\sqrt{3}-\frac{\sqrt{19}}{2}$.
Being $\frac{\sqrt{19}}{2}-\sqrt{3}>0$, the imaginary part of $\frac{2a}{b}-\omega$ is sufficiently small that the complex number lies at a distance less than 1 from some ordinary integer. Why this imaginary part is small so that $\frac{2a}{b}-\omega$ has distance less 1 from some ordinary integer?
Thus in both cases we have found elements $p,q \in R$ such that $|ap − bq| < |b|$ (in fact with $p = 1$ and $q=n \in \mathbb{Z}$ or $p = 2$ and $q=\omega$). This contradicts the assumption that $I \ne bR$.
Please, can you answer to the questions 1), 2) and 3)?


text:
Q: Popup User Authentication Window in android webview i want to access a private protected url in Webview. when i brows that url in browser then a popup window with user name and password fields displayed but when i place that url in android WebView then that popup not appeared please help me regarding this problem.
Here is my MainActivity.java
package com.code.developers.afghannews;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
WebView wb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    wb = (WebView) findViewById(R.id.Hello_World);
    wb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wb.getSettings().setJavaScriptEnabled(true);
    wb.getSettings().setDomStorageEnabled(true);
    wb.getSettings().setBuiltInZoomControls(true);
    wb.getSettings().setSupportZoom(true);
    wb.getSettings().setSupportMultipleWindows(true);
    final Context myApp = this;
    wb.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
            new AlertDialog.Builder(myApp)
                    .setTitle("javaScript dialog")
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok,
                            new AlertDialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    result.confirm();
                                }
                            })
                    .setCancelable(false)
                    .create()
                    .show();

            return true;
        }

        ;
    });

    wb.loadUrl("http://192.168.1.6/video.cgi");
}
}

and xml is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">

<WebView android:id="@+id/Hello_World"
    android:layout_width="match_parent"
    android:layout_height="500dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="10dp"/>
</RelativeLayout>


text:
Q: How to deploy an application to cloud run in google cloud? I created a docker image by Dockerfile
    FROM golang:1.15-buster as builder

    WORKDIR /app

    COPY . .
    COPY ../../../common/library/golang /app

    RUN go build -o server

    FROM debian:buster-slim
    RUN set -x && apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
        ca-certificates && \
        rm -rf /var/lib/apt/lists/*

    COPY --from=builder /app/server /server

    CMD ["/server"]

Build it with docker build in local
    $ docker build -t asia.gcr.io/my-project/my-service .

Push it to google container registry
    $ docker push asia.gcr.io/my-project/my-service

Deploy it to cloud run by command
    $ gcloud run deploy my-service --image asia.gcr.io/my-project/my-service

    Please choose a target platform:
     [1] Cloud Run (fully managed)
     [2] Cloud Run for Anthos deployed on Google Cloud
     [3] Cloud Run for Anthos deployed on VMware
     [4] cancel
    Please enter your numeric choice:  1

    To specify the platform yourself, pass `--platform managed`. Or, to make this the default target platform, run `gcloud config set run/platform managed`.

    Allow unauthenticated invocations to [my-service] (y/N)?  N

    Deploying container to Cloud Run service [my-service] in project [my-project] region [asia-northeast1]
    ⠹ Deploying new service... Invalid ENTRYPOINT. [name: "asia.gcr.io/my-project/my-service@sha256:
    23e3e62e4a2d9c5fb098d01a1e9eb85872c552dd31701ba8525fce692f924d50"
    error: "Command \"/server\": invalid
     mode \"-rw-r--r--\" for /server"
    X Deploying new service... Invalid ENTRYPOINT. [name: "asia.gcr.io/my-project/my-service@sha256:
    23e3e62e4a2d9c5fb098d01a1e9eb85872c552dd31701ba8525fce692f924d50"
    error: "Command \"/server\": invalid52dd31701ba8525fce692f924d50"
     mode \"-rw-r--r--\" for /server"
    ]. mode \"-rw-r--r--\" for /server"
    ].
      . Routing traffic...

    Deployment failed
    ERROR: (gcloud.run.deploy) Invalid ENTRYPOINT. [name: "asia.gcr.io/my-project/my-service@sha256:23e3e62e4a2d9c5fb098d01a1e9eb85872c552dd31701ba8525fce692f924d50"
    error: "Command \"/server\": invalid mode \"-rw-r--r--\" for /server"
].

Why it's Invalid ENTRYPOINT? Is it necessary to change mode of execute file? Or other reason?


text:
Q: Get offset minutes from IANA (TZDB) time zone I have a table T1 with Id, Name and TimeZone as columns. The TimeZone column has IANA (TZDB) format like America/Chicago
I'm getting the data from T1 like
response = T1.Where(t => t.Id == 9).Select(rez => new
           {
              RezName = rez .Name,
              Offset = ...
           });

Inside Offset I need to get the current offset in minutes (like -300 for America/Chicago that has offset -05).
Is there a way to get the offset minutes inside the LINQ query or only by iterating after the select and calculate the local time for each element?

A: As you originally tagged your question with nodatime, here is how you can leverage NodaTime for this:
using NodaTime;

...
Instant now = SystemClock.Instance.GetCurrentInstant();
response = T1.Where(t => t.Id == 9)
   .Select(rez => new
   {
      RezName = rez.Name,
      TimeZone = rez.TimeZone
   })
   .AsEnumerable()
   .Select(x => new
   {
      RezName = x.RezName,
      Offset = (int) DateTimeZoneProviders.Tzdb[x.TimeZone]
                         .GetUtcOffset(now).ToTimeSpan().TotalMinutes
   });

If you are leveraging .NET on Linux or macOS, or if you are using .NET 6 or higher on Windows, you can do this without Noda Time:
DateTimeOffset now = DateTimeOffset.UtcNow;
Instant now = SystemClock.Instance.GetCurrentInstant();
response = T1.Where(t => t.Id == 9)
   .Select(rez => new
   {
      RezName = rez.Name,
      TimeZone = rez.TimeZone
   })
   .AsEnumerable()
   .Select(x => new
   {
      RezName = x.RezName,
      Offset = (int) TimeZoneInfo.FindSystemTimeZoneById(x.TimeZone)
                         .GetUtcOffset(now).TotalMinutes
   });

Yet another alternative would be to use `TZConvert.GetTimeZoneInfo from TimeZoneConverter with similar code to the second example.
Keep in mind, that all of these return the current offset from UTC (as minutes, with positive values being East of GMT).  For America/Chicago, that's presently -300 because daylight saving time is in effect.  When daylight time ends, it will return -360.
Note that in the above examples, the time zone code must occur after the query materializes, as it would be impossible for a LINQ provider like EF to translate it to a SQL query.


text:
Q: The button element lost its features when in my webpage I have a problem with my button. I put a button into the header like this:

SOME TEXT....

  <button type='button' class='HH' id='tg'>Click me</button>

and CSS:
* {
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}
header {
  display: flex;
  align-items: center;
  background: #2b1c1c;
  padding: 8px;
}
.HH {
  background: red;
  width: 70px;
  position: absolute;
  right: 3px;
}

JS:
const tg = document.getElementById("tg")
const nav = document.querySelector('nav')

tg.addEventListener('click', () => {
  if (nav.style.diplay === 'none') {
    nav.style.display = 'block';
  } else {
    nav.style.display = 'none';
  }
})

but button's features disappears(Like I can't click it.)
What is the problem?

A: In your code you are using
const nav = document.querySelector('nav')

But in HTML (at least this one) you don't have a nav defined so the code doesn't work. So I changed the code from nav to h1 to hide this element only.
It's not the cleanest code but it gives you something to start working with it.

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}
* {
  margin: 0;
  padding: 0;
}

html, body {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}

header {
  display: flex;
  align-items: center;
  background: #2b1c1c;
  padding: 8px;
}

.HH {
  background: red;
  width: 70px;
  position: absolute;
  right: 3px;
}

SOME TEXT....

  <button type='button' onclick="toggle_visibility('testing');" class='HH' id='tg'>Click me</button>

A: Firstly you misspelled "display" as diplay in your "if" statement.
Secondly, I think the "if" statement may not see "nav.style.display" as a +ve value. Hence, it moves to the else to set display to "none" of which, your button element is inside your nav element. Thus, you button disappears with your nav.

SOME TEXT....

  <button type='button' class='HH' id='tg'>Click me</button>

item1

item2

item3

const tg = document.getElementById("tg");
const nav = document.querySelector("nav");
nav.style.display = "none";

tg.addEventListener("click", () => {
  if (nav.style.display === 'none') {
    nav.style.display = "block";
  } else {
    nav.style.display = "none";
  }
});

You may try this.
And try to remove your button from inside your nav


text:
Q: How should I encrypt my data in a PHP application? I was trying to use the Paypal PHP SDK and I noticed a warning that says I should encrypt my API username and password for use in production environments. I do agree on this statement, but I'm wondering how I should go about doing that. I currently have no clue.
Here's what the warning says, just for the record:

Do not embed plaintext credentials in your application code. Doing so
  is insecure and against best practices. Your API credentials must be
  handled securely. Please consider encrypting them for use in any
  production environment, and ensure that only authorized individuals
  may view or modify them.

Thanks in advance.

A: Generally, you can store credentials like this in a file outside of the web root.  This limits risk, but doesn't get rid of it entirely.
If they can see your code (or even worse, edit it), then they can get your credentials anyway.  Encrypting it means you need your encryption key somewhere that would be just as visible as the username/password itself.

A: First, set an encryption key:
$key = 'yourpasswordhere';
$string = ' confidential information here '; // note the spaces

Encrypt it on DB entry or from another file and only store the encrypted string in the file itself:
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
var_dump($encrypted); // "ey7zu5zBqJB0rGtIn5UB1xG03efyCp+KSNR4/GAv14w="

Decrypt it later:
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
var_dump($decrypted); // " confidential information here "


text:
Q: Bash command to exit from TL1 terminal I have a bash script that telnets to a system's TL1 terminal and executes a command but how do I exit out of the TL1 terminal?
I've tried quit and exit and it doesn't work. Normally, I would press CTRL+C if I had logged in manually to the TL1 term and this would work; but how would I automate this process?
    #!/bin/bash
    (
       echo "ACT-USER::ROOT:D::ROOT;"
       echo "^C"
       echo "quit"
       echo "exit"
    ) | telnet 192.168.1.1

    echo "done"
    exit

A: Not sure if the answer is still relevant, and it could be system specific as well, but I use

echo "logoff;"

command in my case and it works because it is supported on my terminals. If it also doesn't work, you need need to look into your device documentation for related command to logout,

A: expect, a tool to script interactive programs that's part of most Linux distributions may help. Some fiddling will be required, but basically it goes like this:
#!/usr/bin/expect -f
spawn telnet 192.168.1.1
send "ACT-USER::ROOT:D::ROOT;\r"
send \003

Which will start telnet to the host and send your command string followed by control-c. expect has many more possibilities (especially the fact that it can react to what the other side replies, the possibility to limit the script runtime, etc), and there are literally hundreds of good references on the internet, but this should get you started.


text:
Q: LAN Connection in a PWA Please how could  i possibly connect devices in a LAN to my PWA that works without internet?
The source code is on github and the app is coded in angular, is deployed and has service workers with functionalities to work without internet
But when there is no internet each app on each computer works indpendently
What I am trying to achieve is something similar to when i do ng serve --host 192.168.X.X
All the computers connected to the LAN can acces the app (the same instance of the app)
Any help would be appreciated
Thanks


text:
Q:  element as a child element from  I don't get it. What does this XSD mean exactly?:
<element name="X509Data" type="ds:X509DataType"/>
<complexType name="X509DataType">
    <sequence maxOccurs="unbounded">
        <choice>
            <element name="X509IssuerSerial" type="ds:X509IssuerSerialType"/>
            <element name="X509SKI" type="base64Binary"/>
            <element name="X509SubjectName" type="string"/>
            <element name="X509Certificate" type="base64Binary"/>
            <element name="X509CRL" type="base64Binary"/>
            <any namespace="##other" processContents="lax"/>
        </choice>
    </sequence>
</complexType>

I understand it in that way:

*

*All elements below the <sequence> element can occur as often as required, but at least once (because the attribut minOccurs is not set and the value of minOccurs is 1 by default).

*But just one element below the <choice> element can occur exactly once (because no minOccurs or maxOccurs is set).
However, since the <choice> element is under the <sequence> element, can the other listed elements still occur? Then why didn't you define everything under the <sequence> element instead of defining another <choice> element?
This a part of my XML document:
<X509Data>
    <X509IssuerSerial>
        <X509IssuerName>E=forename.surname@provider.com, CN=Forename Surname, OU=Management, O=Company, L=City, ST=State, C=CO</X509IssuerName>
        <X509SerialNumber>13894744055819454397</X509SerialNumber>
    </X509IssuerSerial>
    <X509Certificate>MIIEEjCCAvqgAwIBAgIJAMDUDBnsFse9MA0GCSqGSIb3DQEBCwUAMIGdMQswCQYD
    VQQGEwJERTEQMA4GA1UECAwHU2FjaHNlbjEQMA4GA1UEBwwHTGVpcHppZzERMA8G
    A1UECgwIQ29tcHVkb2MxEzARBgNVBAsMCk1hbmFnZW1lbnQxFTATBgNVBAMMDFN0
    ZXZlIE1hcnRpbjErMCkGCSqGSIb3DQEJARYcc3RldmUubWFydGluMTk5MEBvdXRs
    b29rLmNvbTAeFw0yMDAxMDcxNTQzMThaFw0yMTAxMDYxNTQzMThaMIGdMQswCQYD
    VQQGEwJERTEQMA4GA1UECAwHU2FjaHNlbjEQMA4GA1UEBwwHTGVpcHppZzERMA8G
    A1UECgwIQ29tcHVkb2MxEzARBgNVBAsMCk1hbmFnZW1lbnQxFTATBgNVBAMMDFN0
    ZXZlIE1hcnRpbjErMCkGCSqGSIb3DQEJARYcc3RldmUubWFydGluMTk5MEBvdXRs
    b29rLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOoYJi1AUDma
    w07WuR+ivHX+Kr3yf0F/d9SrEzHovmmxYyac7C4DheGglJ2H9A3u2x5osu4fG/1f
    JhEhMqhhLGBfLtUrB6v2CWh6FOz06sz/W8NaIRCo81eOJVJDqwiejk24q6JnjP37
    NZ7TQ0/7oeEU5VhKrgTWo0jUoCe6xqOSvuVlr1Er4Jh0zwVumWuj63UJsjXMgqC8
    R3Qomf2ZIgO0HTGOiXA5NXA4Hzsp2lyxn7/9UExzh6L5v+bQSFvCN12TRQeVLoR4
    xog9SOI1yiP3XzhZVbKVHOnXbuzxuuKjPOm7GjKELQoNaSIkwkZybKzXDZfyk3IM
    Vb8i86rg3xkCAwEAAaNTMFEwHQYDVR0OBBYEFFSiMmL2coCYAD82W8WQ9v4VDxc2
    MB8GA1UdIwQYMBaAFFSiMmL2coCYAD82W8WQ9v4VDxc2MA8GA1UdEwEB/wQFMAMB
    Af8wDQYJKoZIhvcNAQELBQADggEBAEwohR0qXn1yqt3wtRPzCzKbv7X+GUlNKZ21
    Rdc6GdwuyWI08gWh0g0EQ1MesYEv9PZbrwDQs+iOA8f9E5LVTJ0LRgug9DpxDagg
    JnQEKYQUhA3E4HBrNe3PH1h22+UD3AVbZ86LzkZdu5RooJQlJsLbJzWCUpjW/3zl
    M6z+1SHEre6GIRN8lPMOreZxVGgUlCSE6Y3qk2e/8WNeMCjQ9gpC3CEwTmL6law/
    7EgVcud3DI7MQg0ebRPtCSLROYokyThJROHlv7DGEdaEPrdk8dzq77ncxzac8amq
    B0V/qDtp5qD0N5KJT6P4JuOcVz3YFkROn2wjQ2RfhCr1ZMMbAUc=</X509Certificate>
</X509Data>

and it's valid, why? <X509IssuerSerial> and <X509Certificate>occurs both.


text:
Q: Sorting individual columns of an array Given an input
array = [
[1,2,-1,-1,2],
[3,-1,-1,-1,-1],
[-1,-1,-1,3,2]
]

I want to transform it into this:
new_array = [
[-1,-1,-1,-1,-1],
[1,-1,-1,-1,2],
[3,2,-1,3,2]
]

That is, for each column, I want elements to stay in their relative places, but move any -1 to the "top" of the column.
I know thanks to a previous question that i can use a something along the lines of sorted(array, key=lambda x: x==-1) to sort all the -1 values to the top. I could also use sorted(array, key = lambda x: x[i]) to sort the array based on column i. However, even combining these doesn't do what I would like it to do, as I'd like to sort each column separately based on the -1 key above. I've tried playing around with some different lambda functions, but this is the first time I've seen them so I'm not really sure how they work yet. Any pointers would be appreciated.

A: you can use numpy
import numpy as np

array = [
[1,2,-1,-1,2],
[3,-1,-1,-1,-1],
[-1,-1,-1,3,2]]

np_array = np.array(array)
sorted_np_array = np.sort(np_array, axis=0)

sorted_array = sorted_np_array.tolist()

A: array = [
[1,2,-1,-1,2],
[3,-1,-1,-1,-1],
[-1,-1,-1,3,2]
]

list(zip(*[sorted(i) for i in list(zip(*array))]))

Here you go a single line list comprehension for your question


text:
Q: Getting forbidden error if I include csrf Spring security config for all non GET requests I created a Course API and wanted to authorize "ADMIN" and "USER" role users for GET request and only "ADMIN" role users for all other requests.
So keeping this requirement on my mind I wrote the below code.
@EnableWebSecurity(debug = true)
public class SpringSecurityConfiguration {

    @Autowired
    MyUserDetailsService userDetailsService;

    @Autowired
    CustAuthenticationProvider authenticationProvider;

    @Autowired
    CustomHeaderAuthFilter customAuthFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.authorizeRequests()
        .antMatchers(HttpMethod.GET,"/topics*").hasAnyRole("USER","ADMIN")
        .antMatchers(HttpMethod.POST,"/topics*").hasRole("ADMIN")
        .antMatchers(HttpMethod.PUT,"/topics*").hasRole("ADMIN")
        .antMatchers(HttpMethod.DELETE,"/topics*").hasRole("ADMIN")
        .antMatchers(HttpMethod.GET,"/hellos*").hasRole("ADMIN")
        .and()
        .formLogin().and().httpBasic();

        return http.build();

    }

    @Autowired
    public void authenticationManager(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("student").password("Student@1997").authorities("ROLE_USER")
        .and()
        .withUser("faculty").password("Faculty@1997").authorities("ROLE_ADMIN").and()
        .passwordEncoder(NoOpPasswordEncoder.getInstance());

    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {

        return NoOpPasswordEncoder.getInstance();
    }
}

But I was getting forbidden error when I was logging in with "ROLE_ADMIN" too. Then I disabled csrf with the below code
http
 .csrf().disable();

Then It started working as expected. But I know removing csrf is not safe. So anyone can you please explain why I was not being authenticated if I add csrf and how to get around with this problem.


text:
Q: including bootstrap.min.js breaks dropdown I have a navbar-collapse.
If I use the code shown below, dropdowns stop working. (Clicking a dropdown item does nothing.)
    <!-- Le styles -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/bootstrap-responsive.min.css" rel="stylesheet">
    <style>
        body { padding-top: 60px; /* 60px to make the container go all the way
            to the bottom of the topbar */ }
    </style>
    <!-- Le javascripts -->
    <script type="text/javascript" src='/js/jquery-1.9.1.min.js'></script>
    <script type="text/javascript" src='/js/jquery.cookie.js'></script>
    <script type="text/javascript" src='/js/bootstrap.min.js'></script>

removing the ref to bootstrap.min.js makes dropdowns work correctly. I'm confused. Am I not supposed to include both .js and .css?
(I tried including jQuery before the css files. Same result.)
(I also tried including javascript before css. Same result.)
All bootstrap files were downloaded straight from the bootstrap website.

A: The reference to the bootstrap.js file is important since the drop down function is included in it . On line 637 in bootstrap.js the drop-down definition is defined . like :
  var toggle = '[data-toggle=dropdown]'
, Dropdown = function (element) {
    var $el = $(element).on('click.dropdown.data-api', this.toggle)
    $('html').on('click.dropdown.data-api', function () {
      $el.parent().removeClass('open')
    })
  }

The same way its defined in the bootstrap.min.js which is minified version of bootstrap.js . Removing the reference to the bootstrap.js file will not make the dropdown function to work .
Also I will advise you to use the javascripts in footer .. like
<script type="text/javascript" src='/js/jquery-1.9.1.min.js'></script>
<script type="text/javascript" src='/js/bootstrap.min.js'></script>
<script type="text/javascript" src='/js/jquery.cookie.js'></script>


text:
Q: How to use pandas for comparisons only of a part of a variable? I need to compare codes in two dataframes. I'm using Python 3 and pandas
In the first base the codes always have 18 digits:
dividas_dep = pd.read_csv("dividas_deputados_ajustado_csv.csv",sep=';',encoding = 'latin_1')

dividas_dep.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 106 entries, 0 to 105
Data columns (total 10 columns):
CPF_Deputado                  106 non-null object
CPF_limpo                     106 non-null int64
Nome_Deputado                 106 non-null object
Vinculo                       106 non-null object
CNPJ_Devedor                  106 non-null object
CNPJ_limpo                    106 non-null int64
Nome_Devedor                  106 non-null object
Valores_situacao_Irregular    65 non-null object
Valores_situacao_Regular      52 non-null object
Total_Devido                  106 non-null object
dtypes: int64(2), object(8)
memory usage: 8.4+ KB

The column to compare in this first base ("CNPJ_Devedor") has these examples: 17.080.201/0001-49, 76.205.723/0001-99, 04.885.828/0001-25...
And in the second base, the codes always have 10 digits:
funrural = pd.read_excel('DEVEDORES FUNRURAL ATUALIZADO PGFN.xlsx')

funrural.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8130 entries, 0 to 8129
Data columns (total 14 columns):
PSFN_PGFN               8129 non-null object
Regiao                  8129 non-null object
CNPJ_CEI_Tipo           8129 non-null object
CNPJ_Raiz               8129 non-null object
Razao_Social            8130 non-null object
Valor_principal         8130 non-null float64
Valor_TR_IPC_Poup       8130 non-null float64
Valor_Juros             8130 non-null float64
Valor_SELIC             8130 non-null float64
Valor_Encargo           8130 non-null float64
Valor_Multa_Oficio      8130 non-null float64
Valor_Selic_M_Oficio    8130 non-null float64
Vl_Multa_Mora           8130 non-null float64
Vl_Tot_Credito          8130 non-null float64
dtypes: float64(9), object(5)
memory usage: 889.3+ KB

The column to compare in this second base ("CNPJ_Raiz") has these examples: 04.244.173, 05.006.407, 03.632.132...
The codes "CNPJ_Devedor" and "CNPJ_Raiz" are related in tax legislation, but I can not make a simple merge like this:
compara1 = pd.merge(dividas_dep, funrural, left_on='CNPJ_Devedor', right_on='CNPJ_Raiz')

What I need to do is compare only the first 10 digits of "CNPJ_Devedor" with the code "CNPJ_Raiz" (example, in "17.080.201/0001-49" use only "17.080.201")
Is there any way to do this in Python? Or should I edit the original dataframe file, dividas_dep (dividas_deputados_ajustado_csv.csv), to create a new column with only the first 10 digits?

A: You can compare the slice of the first 10 string elements with .str.slice(None, 10):
dividas_dep["CNPJ_Devedor"].str.slice(None, 10) == funrural["CNPJ_Raiz"]

Example:
>>> dividas_dep = pd.DataFrame({"CNPJ_Devedor": ['17.080.201/0001-49', '76.205.723/0001-99', '04.885.828/0001-25']})
>>> funrural = pd.DataFrame({"CNPJ_Raiz": ['17.080.201', '04.244.173', '05.006.407']})
>>> dividas_dep["CNPJ_Devedor"].str.slice(None, 10) == funrural["CNPJ_Raiz"]
0     True
1    False
2    False
dtype: bool

You can use the result to create a new dataframe:
res = dividas_dep["CNPJ_Devedor"].str.slice(None, 10) == funrural["CNPJ_Raiz"]
funrural[res]


text:
Q: stored procedure remote call not working i have stored procedure sp_1  in server_A .i am calling this SP from Server_B
the code is:exec Server_A.MyDb.dbo.SP_1 in the body of sp i have complicted logic in the final step I insert result to Table_A.
running sp take 10 minute and return 'command complete successfully' but tabe_A is Empty (must be filled).
i try to execute the body of script it work properly .and tble Fill as expect.
i do'nt know what is wrong...?
i try to execute sp_1 from Another server 'server_c' server_d it work fine.
 problem is with server_B

A: i found the anwser the problem is with Remote Query Timeout set to 600 sec


text:
Q: how to manipulate data from text to CSV I have text file data.txt like this:

Name male  female
bayu 1 0
jonson 1 0
anna 0 1

i have try to convert this file using pandas python
import pandas as pd
df = pd.read_fwf('data.txt')
df.to_csv('data.csv')

I want to get results data.csv like this:

Gender name
bayu male
jonson male
Anna  Female

what should i do?

A: import numpy as np
df['Gender'] = np.where(df['male'].eq(1), 'male', 'female')
df = df.drop(columns={'male', 'female'})
df.to_csv('data.csv', index=False)

    Name    Gender
0   bayu    male
1   jonson  male
2   anna    female

A: You can use idxmax() before to save to csv:
df['Gender'] = df[['male', 'female']].idxmax(axis=1)
df = df.drop(columns=['male', 'female'])

A: Simply can be done with replace and rename ..
DataFrame:
>>> df
    Name  female  male
0   bayu       0     1
1  jason       0     1
2   anna       1     0

Result:
>>> df.replace({ 0: "male", 1: "Female"}).drop(columns={'male'}).rename(columns={'female': 'Gender'})
    Name  Gender
0   bayu    male
1  jason    male
2   anna  Female

saving dataframe to csv..
>>> df = df.replace({ 0: "male", 1: "Female"}).drop(columns {'male'}).rename(columns={'female': 'Gender'})
>>> df.to_csv('data.csv', index=False)

Your CSV will be looks like below with comma delimited ..
$ cat data.csv
Name,Gender
bayu,male
jason,male
anna,Female

Or, Just with idxmax and df.assign  to assign back the values to nw columns altogether.
>>> df.assign(Gender = df[['male','female']].idxmax(axis=1)).drop(columns={'male', 'female'})
    Name  Gender
0   bayu    male
1  jason    male
2   anna  female

2) Another way around creating a function and then using apply method.
 def setval(col):
   col = str(col)
   if col.startswith('0'):
     return  'Male'
   if col.startswith('1'):
     return  'Female'

>>> df.assign(Gender = df[ 'female'].apply(setval)).drop({"female", "male"}, axis=1)
    Name  Gender
0   bayu    Male
1  jason    Male
2   anna  Female

3) Just for the sake of posterity ..
You can create a dict and then map the dict against one of the column assign the new values to a new column with df.assignfurther dropping the un-desired columns.
Here, yo can use either map or replace method at your ease ..
>>> newVal = {0:'Male', 1: 'Female'}   # dictionary paired with key, values

a) in the below example axis=1 represents the column which is newer method.
>>> df.assign(Gender=df.female.map(newVal)).drop({'male', 'female'},axis=1)
    Name  Gender
0   bayu    Male
1  jason    Male
2   anna  Female

b) while in the below example we are explicitly mentioning it to be applied on the column which is old method.
>>> df.assign(Gender=df.female.map(newVal)).drop(columns={'male', 'female'})
    Name  Gender
0   bayu    Male
1  jason    Male
2   anna  Female

With .replace
>>> df.assign(Gender=df.female.replace(newVal)).drop({'male', 'female'},axis=1)
    Name  Gender
0   bayu    Male
1  jason    Male
2   anna  Female


text:
Q: Very simple DNS server I have a linux server has an ad-hoc wireless network for clients to connect to. Once connected I want users to always be redirected to it's own web server no matter what URL they type in. The large solution would be to set up a full DNS server (with BIND or equivalent) but that seems like overkill. All I need is a simple program that will listen for any DNS request and always respond with the same IP address.
I looked around for one but couldn't seem to find one. It would preferably be written in C or Perl as I don't really want to install any other scripting languages.

A: I would suggest using dnsmasq. It's more full-featured than you absolutely need, but it's very well-written, small, and easy to install, and the only configuration you would need to give it is --address='/#/1.2.3.4' to tell it to answer all queries (that don't match some other rule) with the address 1.2.3.4. dnsmasq is well-known and maintained and probably a more robust server than Net::DNS::Nameserver.

A: I've used fakedns.py when reversing malware.  It may be too limited for your situation.

A: As I answered in the other related question, I wrote a basic DNS server in C++ for a job interview under BSD license.
I think the code was pretty clean, though I didn't made unit tests :-(
I tested it with dig, and it took about a week understanding DNS protocol + implementing + documentation.
If anyone would want to extend it, I guess it would not be very difficult.
Because I think it only supported inverse queries, as that was asked in the exercise.
The code could be found here:
http://code.google.com/p/dns-server/
It was migrated to: https://github.com/tomasorti/dns-server

A: Use Net::DNS::Nameserver and write your own reply handler.
For C, look at:

*

*How to Build a custom simple DNS server in C/C++

*Create custom DNS name server in C


text:
Q: Thread start in Form1() crashing program on Windows Server 2008 Hey guys, I'm getting a really strange error. I have a program that needs to run a thread on startup, and for some reason when I do myThread.Start() in Form1()  it will crash with "program is not working" (But only on Windows Server, not on my local machine!). However,  if I put the same code under button1_Start() it works no problem. What gives?
Any ideas?
Thank you.
EDIT
A little extra information: In my thread I have a line of code that uses invoke
Invoke(new Action(() => richTextBox1.AppendText(string.Format("Updating {0}..\n", DateTime.Now))));

And for some reason the crashing goes away after I make the thread sleep for 2 seconds before it starts executing. Am I using the right method to execute code on the app startup?

A: Note, this is a guess, you haven't given nearly enough information in your question to give you any definitive answers.
I doubt it has anything to do with Windows Server 2008, but probably more with the fact that the server has more CPU cores and/or a faster processor than your development machine.
If you, in the thread tries to either access the form through a variable, or you try to invoke back to the thread that owns the form, you will crash on a fast computer.
Why?
In the first case, the variable has not yet been set. The following code:
var fm = new Form1();

here, fm will not be set before the constructor has returned. If your thread has already tried to access the form through fm, that variable is null.
In the second case, the constructor is not responsible for showing the form, that happens afterwards. Many controls postpone actually allocating a handle until they are asked to draw themselves, and thus if the thread tries to do stuff to a control before that, it will crash.
You should instead start your thread from Form_Load.

A: In our company we had the same symptom on an application that spawned a bitmap async loading that used COM - only on W2008.
The problem turned out to be:

*

*we used a COM object from that thread (which was STA)

*only on W2008 initialization of the object could not complete in time

*thread started working before the COM was ready and getting error

I don't know why only on W2008, but our hack was to move the start of the thread from the constructor to the actual point where the thread work was needed.


text:
Q: JMS serializers error when property does not exist I am creating a symfony2 project and using the JMS serializer bundle to serialize my object for database storage (I know this is not the best way).
But now my problem is,
when I change a property of my object and deserialize the Json string the JMS serializer ignores non existing properties instead of throwing an error, which is actually great. Yet I would like to log such an event.
Below is an example to illustrate my question
Json string from my database:
$dataToBeDeserialized = {"title":"testing123","text":"Lorem Ipsum"}

TestClass:
/**
 * @Type("string")
 */
protected title;

/**
 * @Type("string")
 */
protected text;

Deserialize method:
$this->serializer = SerializerBuilder::create()->build();
$this->serializer->deserialize($dataToBeDeserialized, 'TestClass', 'json');

This results in:
TestClass {
  title: "testing123",
  text: "Lorem Ipsum"}

But when I change my Testclass and rename (or remove) title to, let's say, "title2", The deserializer ignores the "title" attribute in the Json string.
and that results in:
  TestClass {
  title2: "",
  text: "Lorem Ipsum"}

Well no problem there. The data in the database is wrong. But I would like to log that problem. How should I do this? I don't want to mess in the code of the JMS serializer if possible (since I cannot update it anymore). And looking for empty properties in my TestClass isn't the best way either, since they can be null.

A: The JMS Serializer allows to be configured with handlers and event listeners, in your case I think a event listener would suffice as you will just be waiting for the occurence of a certain situation (an unmatched attribute).
At that point you simply want to write it to log, so the course would be the following:

*

*Create a listener class which implements JMS\Serializer\EventDispatcher\EventSubscriberInterface

*Make the listener write a log line when your condition is met.

*Subscribe this listener to an event.

I will write a more detailed description when I get home from work this evening but I thought maybe this can help you along already.
Check out the docs for more details:
http://jmsyst.com/bundles/JMSSerializerBundle/master/configuration#event-dispatcher
And the default subscribers might give you a clue:
https://github.com/schmittjoh/serializer/tree/master/src/JMS/Serializer/EventDispatcher/Subscriber


text:
Q: Устройства в сети пропадают
R1 - 192.168.1.1 dhcp
R2 - 192.168.1.2 static
pc1(r2) - 192.168.1.5 static

команда из pc1 подключенного от r2
sudo arp-scan -I wlp4s0 -l

не всегда выдаёт список подключенных устройств. Иногда только
Interface: wlp4s0, datalink type: EN10MB (Ethernet)
Starting arp-scan 1.8.1 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
192.168.1.2 10:62:eb:75:3a:46   (Unknown)

1 packets received by filter, 0 packets dropped by kernel
Ending arp-scan 1.8.1: 256 hosts scanned in 1.378 seconds (185.78 hosts/sec). 1 responded

R1 и R2 подключены кабелем через свитч. За R2 всё работает нормально, периодически отсутствует пинг между R1 и R2. Однако интернет через него по 3G работает нормально для PC1. Компьютеры подключенные промежуточно через свитч не пингуются из R2 не смотря на то что в настройках стоит статический адрес.
Что не так, и как это можно исправить?
R1 - Sagemcom 2804v2, R2 - dir-825ac
UPD 1:
после перезагрузки роутера ситуация нормализовалась, однако хотелось бы знать первопричину.
UPD 2:
sudo arp-scan -I wlp4s0 -l
192.168.1.1 xx:xx:xx:xx:xx:xx   SAGEMCOM
192.168.1.3 xx:xx:xx:xx:xx:xx   CADMUS COMPUTER SYSTEMS
...
ping 192.168.1.3
PING 192.168.1.3 (192.168.1.3) 56(84) bytes of data.
^C
--- 192.168.1.3 ping statistics ---
133 packets transmitted, 0 received, 100% packet loss, time 135166ms

при этом 192.168.1.3 пингуется с других машин за R2
Информация о R2:

Модель:DIR-825ACG1
Аппаратная ревизия:G1A
Версия ПО:3.0.2

резервная копия dir-825ac


text:
Q: How to get selected row value on the next page using jquery? I want to get selected row id on the next page. I want when i click on button then selected row id show in next page. Remember next window tab will open.
Here is my jquery function.Its getting ID in value var when i click on row  but i don't know ho to get this id on next page. But i want that, first i select row then i click on button then id show on next tab window. Thanks

And here is my jQUERY function :
$("#maintable tr").click(function(){
//alert($(this).hasClass("selected"));
if ($(this).hasClass("selected")){
    $(this).removeClass("selected");
    var value=$(this).find('td:first').html();
     alert(value);
}else{
    $(this).addClass("selected").siblings().removeClass("selected");
}
});

A: In a comment you say:

I try this window.open('http://localhost/new/old.php') this will move to next page

In that case you'd simply add value as a query string parameter.  For example:
window.open('http://localhost/new/old.php?id=' + value);

If value might contain more complex character data, you may want to URL-encode it:
window.open('http://localhost/new/old.php?id=' + encodeURIComponent(value));

A: The main way to get the information to the next page is through the url
You can set the id as a query string so when the button is clicked to take them to the next page the id will be passed with the url. Then you can use
<script>
        $.extend({
            getUrlVars: function(){
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for(var i = 0; i < hashes.length; i++){
                    hash = hashes[i].split('=');
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
                return vars;
            },
            getUrlVar: function(name){
                return $.getUrlVars()[name];
            }
        });
        var ID = $.getUrlVar('id');

Then you can display or manipulate the value how you see fit.


text:
Q: How large would and asteroid need to be to cause damaging earthquakes? Reading this acticle www.mirror.co.uk/news/weird-news/huge-asteroid-could-cause-earthquakes-7019482 I was surprised at the claim that a 2.4km wide asteroid could cause earthquakes on earth by way of a near-miss. Of course, I have no questions regarding what would happen if it was actually a hit ...
The first line states "[...] so big some claim its gravitational pull could cause earthquakes and volcanoes on Earth [...]"
Is this claim based on any actual data or just lies "for the views" ?
If this claim is true I would expect mountains, which I assume are generally larger than this asteroid in volume and mass, to have a visible effect on the landscape through the same "gravitational pull".
This claim seems even more surprising considering that $g = GM/r^2$ implies that strength of the "gravitational pull" decreases with the inverse of the square of the distance. If that asteroid can cause earthquakes, why don't mountains bend trees and pull houses ?


text:
Q: Bromwich integral of $1/s^k$ with k real (non integer) and $1Is there a simple way to compute the inverse laplace transform of $1/s^k$ with k non integer using Bromwich integral (basically without using the known laplace transform of $t^n$)?

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
&\int_{0}^{-\infty}{\expo{st} \over \pars{-s}^{k}\expo{\ic\pi k}}
\,{\dd s \over 2\pi\ic}
+
\int_{-\infty}^{0}{\expo{st} \over \pars{-s}^{k}\expo{-\ic\pi k}}
\,{\dd s \over 2\pi\ic}
\\[3mm]&=
-\expo{-\ic\pi k}\int_{0}^{\infty}{\expo{-st} \over s^{k}}\,{\dd s \over 2\pi\ic}
+
\expo{\ic\pi k}\int_{0}^{\infty}{\expo{-st} \over s^{k}}\,{\dd s \over 2\pi\ic}
={\sin\pars{\pi k} \over \pi}\int_{0}^{\infty}s^{-k}\expo{-st}\,\dd s
\\[3mm]&=
{\sin\pars{\pi k} \over \pi}\,t^{k - 1}\int_{0}^{\infty}s^{-k}\expo{-s}\,\dd s
={\sin\pars{\pi k} \over \pi}\,t^{k - 1}\Gamma\pars{1 - k}
={\sin\pars{\pi k} \over \pi}\,t^{k - 1}\,{\pi \over \Gamma\pars{k}\sin\pars{\pi k}}
\\[3mm]&=\color{#000}{\large{t^{k - 1} \over \Gamma\pars{k}}}
\end{align}


text:
Q: What's the difference between Architectural Patterns and Architectural Styles? In Software Architecture - Foundations, Theory and Practice, I can find definitions for both. The problem is that I don't get what each one of them means in plain English:
Architectural Pattern

An Architectural Pattern is a named collection of architectural design decisions that are applicable to a recurring design problem parameterized to account for different software development contexts in which that problem appears.

Architectural Style

An Architectural Style is a named collection of architectural design decisions that (1) are applicable in a given development context, (2) constrain architectural design decisions that are specific to a particular system within that context, and (3) elicit beneficial qualities in each resulting system.

What does each one mean and what are the differences between them?

A: In very simple words:

*

*An architectural style
Is a concept, theory (and how it's implemented it is up to you). It can also apply to outside of the software world.
In example: REST (Representational State Transfer) is an architectural style built on certain principles using the current "Web" fundamentals.

*An architectural patterns
Describes a solution at the software system (or module) level. In other words how it interacts each other e.g. view with model, and model with controller.

*A design patterns
Is a solution at the core level, it talks about classes, functions and how actually the logic flows.

A: An Architectural Pattern is a way of solving a recurring architectural problem. MVC, for instance, solves the problem of separating the UI from the model. Sensor-Controller-Actuator, is a pattern that will help you with the problem of actuating in face of several input senses.
An Architectural Style, on the other hand, is just a name given to a recurrent architectural design. Contrary to a pattern, it doesn't exist to "solve" a problem.
Pipe&filter doesn't solve any specific problem, it's just a way of organizing your code. Client/server, Main program & subroutine and Abstract Data Types / OO, the same.
Also, a single architecture can contain several architectural styles, and each architectural style can make use of several architectural patterns.

A: In my view, patterns and architectural styles are complementary mechanisms for encapsulating design expertise.  An architectural style provides a collection of building block design elements, rules and constraints for composing the building blocks, and tools for analyzing and manipulating designs created in the style.
Styles generally provide guidance and analysis for building a broad class of architectures in a specific domain whereas patterns focus on solving smaller, more specific problems within a given style (or perhaps multiple styles).

A: Architectural Styles
Architectural styles are names which represent the broader organizations of your applications subsystems and depict the idea of the overall outline of the it. Examples are, SOA, Client/Server, Message Bus etc.
Architectural Patterns
Architectural patterns are names of the reusable solutions to the general architectural problems which give an idea of how the inner parts are implemented to solve them. Examples are, 2-Tier, 3-Tier, N-Tier, MVC, REST etc.
One style can use multiple patterns to solve multiple problems. For example, a Client/Server style can use an N-Tier pattern or(and) an MVC pattern for separating its business logic, presentation logic and data logic for introducing modularity which solves modifiability and maintainability problems.

A: Architectural design patterns are more domain specific where are architectural styles are more generic and usable in wide range of applications. Because of this architectural patterns requires more domain knowledge.

A: Architectural Style  style refers to a set of guidelines or principles for designing and building software systems.

Category
Architecture styles

Communication
SOA, ROA, Message Bus

Deployment
Client/Server

Domain
Domain Driven Design,Monolithic, Mocroservice

Structure
Component-Based, Object-Oriented, Layered, Plug-ins

Other
REST, Peer-to-peer, Cloud computing, Internet of Things, Blockchain...

An Architectural Pattern is a specific, reusable solution to a common problem or design issue in software architecture.

*

*For example: 3-tier, N-tier, MVC, Model View ViewModel, Publish-subscribe,Sensor-controller-actuator...

An architectural style is a blueprint of the system's overall structure, while an architectural pattern is a blueprint of a specific part of the system
A Design pattern is a general reusable solution to a commonly occurring problem in object-oriented software design. It provide a blueprint for how to solve a specific problem or design issue at the level of individual classes and objects, rather than the overall structure of a system.

*

*For example: Factory, Singleton, Prototype.

Real-life example: Temple architecture styles would be same but inner design could be different:

A: Frankly, I have always considered both these terms to be synonymous! And layman (relatively speaking) literature definitely treats them as such.
Refer MSDN or Wikipedia
However, your question intrigued me a bit so I did a bit more digging and frankly...I couldn't find much except for a reference to A Practical Guide to Enterprise Architecture (The Coad Series), from which i quote:

An architectural style (Base et al. 1997) and an architectural pattern (Buschmann et al. 1996) are essentially synonymous.

Based on some more googling, this is what I think might be one possible way to differentiate the two:

*

*An architectural style is a conceptual way of how the system will be created / will work.

*An architectural pattern describes a solution for implementing a style at the level of subsystems or modules and their relationships.

How an architectural pattern will differ from a Design pattern i.e. Adapter, observer is basically by the level of Granularity at which they are applied (I know this isn't part of the question but it's related, I think...)

A: For Architectural Patterns think specific ways to style your code as described by the GoF like; Adapter, Strategy, Builder, Mediator, etc
For Architectural Style think overall system; I.E., using MVC for presentation, DDD to model the business layer, WCF (if you're into .NET) for Interop, SOA for integration, etc.

A: Architectural Patterns – define a general set of element types and their
interactions. Examples of Architectural Patterns include Pipes and Filters,
Model–View–Controller, and Reflection.
Architectural Style – the term was coined by Garlan and Shaw, it is an
idiomatic pattern of system organization. For example, a client–server system
is an architectural style.
p.s : Many of the original architectural styles have been
reformulated as patterns.

A: Architecture style describes a system of many components. There is only one application architecture and you have to apply the one architectural style like Microservices, SOA, and event-driven architecture everywhere.
Architecture patterns describe something inside a single component and do not try to apply the same architectural patterns like CQRS or DDD everywhere.

A: Architectural styles tell us, in very broad strokes, how to organize our code. It's the highest level of granularity and it specifies layers, high-level modules of the application and how those modules and layers interact with each other, the relations between them. Examples of Architectural Styles: Component-based, SOA
Architectural Patterns have an extensive impact on the code base, most often impacting the whole application either horizontally (ie. how to structure the code inside a layer) or vertically (ie. how a request is processed from the outer layers into the inner layers and back). Examples of Architectural Patterns: Model-View-Controller, Model-View-ViewModel

A: Architecture pattern: context + problem -> solution
Architecture style: solution part of architecture pattern
So architecture style is analogous to the solution part of the architecture pattern. It's often used in books dealing with architecture documentation where the focus is on the solution and not how the context and problem came about.


text:
Q: Is PoE without LAN input possible? I have an access point which requires PoE input, however that access point can also work as a WiFi extender which means it doesn't need any LAN input, it just needs the power input.
Can I use a generic PoE injector, let's say like this one

and just plug the PoE output cable, without plugging any LAN input cable? Or does the whole PoE mechanism requires LAN input too?
Is this an equipment specific behavior?


text:
Q: Search content fail when tag contains '&' I am working on portal community and created link with tag for user to search.All of them success instead for tag named 'Debit & Credit'.I suspected it is due to '&' because when I remove '&' it works.I tried to replace '&' with the %26 and & as below but none of them works.

<apex:outputLink value="/apex/MyPortal_Category_Vf?Tags=%22Financial Management%22,%22Debit & Credit%22">Debit & Credit</apex:outputLink>
 //Fail

<apex:outputLink value="/apex/MyPortal_Category_Vf?Tags=%22Financial Management%22,%22Debit & Credit%22">Debits & Credit</apex:outputLink>
// Fail

<apex:outputLink value="/apex/MyPortal_Category_Vf?Tags=%22Financial Management%22,%22Debit%20%26%20Credit%22"> //Fail

The success page will look like this:

The fail page is look like this :

I tried to capture in debug log as below but nothing.No exception has been thrown.
36.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,NONE;VALIDATION,INFO;VISUALFORCE,NONE;WORKFLOW,INFO
06:12:49.0 (461069)|USER_INFO|[EXTERNAL]|005260000016xsE|portaluser@myportal.com|Greenwich Mean Time|GMT+01:00
06:12:49.0 (500985)|EXECUTION_STARTED
06:12:49.0 (506009)|CODE_UNIT_STARTED|[EXTERNAL]|066260000004gCG|VF: /apex/MyPortal_Category_Vf
06:12:49.53 (53007801)|CUMULATIVE_LIMIT_USAGE
06:12:49.53 (53007801)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

06:12:49.53 (53007801)|CUMULATIVE_LIMIT_USAGE_END

06:12:49.0 (53060382)|CODE_UNIT_FINISHED|VF: /apex/MyPortal_Category_Vf
06:12:49.0 (54259004)|EXECUTION_FINISHED

Is there any way to include '&' in tag?


text:
Q: Should all machines which run mongo instances (mongod or mongos) in a Mongo DB cluster have unique hostnames (also at OS level)? I have been using Mongo DB Cluster for some data analysis (Mongo DB version 2.4.5) and while inserting some data into the cluster, I found an error which is the same as mentioned in the bug : https://jira.mongodb.org/browse/SERVER-10578
My configuration is as follows:
1) Node1 - mongoconfig server, mongod shard
2) Node2 - mongoconfig server, mongod shard
3) Node3 - mongoconfig server, mongos
4) Node4 - mongos
I changed the OS hostnames of all the machines and made sure that hostnames specified in the DNS server and OS hostnames are the same. After that, the problem got solved.
But now I have a requirement that I need to add mongos instances (nodes/machines) on the fly which will have different IP addresses but the same hostname (both at the OS level and in DNS entries). I will still continue to have unique hostnames (both at OS level and in DNS entries) for all the mongo config servers and mongo shard servers.
Will that work correctly or will I run across the same problem as mentioned in the bug?
Does the requirement of unique hostnames at OS level hold true even for mongos instances or is it just for shards?


text:
Q: using similarity of triangles, how it implements the persepctive projection I am doing revision on graphics module, but im unsure how to answer the following question.
Can someone please help me with this? thanks
revision question


text:
Q: Disable Warning Sign Is there any way to stop this warning sign from popping up in Microsoft Access 2007-2013 via VBA method? I have tried (DoCmd.SetWarnings False) and (Application.DisplayAlerts = false)
Apparently Both of the method didn't work out at all.
Any Help will be greatly appreciated.

A: Check out CopyFile Method and consider using the overwrite argument to pass to the function to tell it that if the file exist, then overwrite it and do not prompt.

Visual Basic for Applications Reference
CopyFile Method
Syntax
object.CopyFile source, destination[, overwrite]
The CopyFile method syntax has these parts:

*

*Part: overwrite

*

*Description: Optional. Boolean value that indicates if existing files are to be overwritten. If True, files are
  overwritten; if False, they are not. The default is True. Note
  that CopyFile will fail if destination has the read-only attribute
  set, regardless of the value of overwrite.

  Remarks
Wildcard characters can only be used in the last path component of the
  source argument. For example, you can use:
FileSystemObject.CopyFile "c:\mydocuments\letters\*.doc", "c:\tempfolder\"

But you can't use:
FileSystemObject.CopyFile "c:\mydocuments\*\R1???97.xls", "c:\tempfolder"

If source contains wildcard characters or destination ends with a path
  separator (), it is assumed that destination is an existing folder in
  which to copy matching files. Otherwise, destination is assumed to be
  the name of a file to create. In either case, three things can happen
  when an individual file is copied.

*

*If destination does not exist, source gets copied. This is the usual    case.

*If destination is an existing file, an error occurs if overwrite is    False. Otherwise, an attempt is made to copy source over the existing    file.

*If destination is a directory, an error occurs.

  An error also occurs if a source using wildcard characters doesn't
  match any files. The CopyFile method stops on the first error it
  encounters. No attempt is made to roll back or undo any changes made
  before an error occurs.

Source


text:
Q: Bayesian probability with uncertain quality of evidence Suppose a Bayesian updater receives one of a finite number of signals. The device that gives him the signal is of uncertain quality. If it is high-quality the signal is always a perfect signal about some underlying variable he is interested in. If it is low-quality it is noise.
After seeing the signal he updates his beliefs about the underlying variable and the quality of the evidence device, right? But I am not sure how to model it.
I have tried looking at it 2 ways with very different answers.
a) He uses his updated belief about the quality of the device to form a posterior about the underlying variable, and his updated belief about the underlying variable to form a posterior about the quality of the device. This gives a system of equations with unique solutions for each one.
b) He forms a joint probability distribution over the two variables and updates it.
The former gives some weird results, such as if his prior beliefs about the distribution of signals from a high-quality and low-quality device, he updates his belief about the quality of the expert upwards, regardless of the signal.
The latter seems like it is imposing an independence assumption that is not true.

A: My advice is to think about the relations between variables. Everything else follows from that.
One model for an unreliable sensor is: P(M | V, R) P(V) P(R) where M is the measurement, V is the variable you are trying to measure, and R is the reliability of the sensor. These variables could be discrete or continuous, with P(M | V, R) being whatever makes sense for the problem at hand.
Operations on such a model could include computing P(V | M), P(R | M), and P(V, R | M). Which of these is useful to you depends on the problem you are trying to solve.
I worked with models of unreliable sensors in Chapter 6 of my dissertation [1]. On looking at it again, it seems like Sections 6.3 and later are most relevant to you.
[1] http://riso.sourceforge.net/docs/dodier-dissertation.pdf


text:
Q: Push notifications using Grease/TamperMonkey userscripts? I would like to push notifications or updates out through my userscript. It's coded in Javascript, like all userscripts.
The only thing I have thought about, is getting a server which would host my file. Then the userscript would check if that file has been changed, and if it has, then display the new message. Basically allowing me to push out messages.
Is there a way to do that? Push notifications or updates without using a server, because that would be too much. I use http://userscripts.org/ for hosting my userscripts, but I haven't been able to find any way of pushing out notifications.


text:
Q: Bootstrap navbar and php include function I'm working with bootstrap navbar and everything is fine, but when I call include function on php to call the navbar I see a gap between top of the page and navbar. What happend?
This is the index.php
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/bootstrap.css" rel="stylesheet">

<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">

This is navbar.php:

      <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

  </button>
  Project name

Home

About

Contact

When I call in the index.php:
<?php include('navbar.php'); ?>

There is a space in between navbar and top page. If I paste the navbar code in the index.php everything goes fine.


text:
Q: Create Login/User using stored procedure from Azure SQL Database's non master database What I need is to create stored procedure inside non master database that will create login and user based on data in database.
It works in SQL Server, but is it possible to do it in Azure SQL Database?

A: No, it's impossible.
In SQL Database, you must be connected to the master database to create a login.
Please reference: SQL Database Logins.
That means even you have create the stored procedure inside non master database, when you execute it, you may get the error like:

Hope this helps


text:
Q: equivalent of MySQL's hex(aes_encrypt) In mySql I do, hex(AES_ENCRYPT('mytext','mykeystring')). This gives me a string with characters, rather than some unreadable things.
How can I do something like this in php? Is there a built in function that'll let me do this? Just like mySql has hex and aes_encrypt with a password/salt.
I'm not looking for exact aes encryption in php. Anything that returns a string of alphabets and numbers and that isnt easy to crack will do (has salt)

A: The PHP equivalent is:
// MySQL's AES_ENCRYPT uses Rijndael 128 with ECB mode
$enc_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_ECB);
// HEX() equivalent
echo bin2hex($enc_text);

Note that ECB block mode ain't great, and it's better to use CFB. My previous answer discusses this in more detail.

A: Use the hash function http://php.net/manual/en/function.hash.php). The hash_algos() function returns an array of available algorithms. (http://www.php.net/manual/en/function.hash-algos.php)


text:
Q: SSH Tunneling Through a Firewall to a Cluster I work at a university but I often work remotely. There is a cluster computer at the university that I need to be able to interact with, but its behind a firewall. Let's call the firewall F and the cluster C.
In the past, in similar situations, I would just ssh to F and then ssh from F to C. This works fine, and I can connect doing so. The problem is, unlike other firewalls I've dealt with in the past, F does not have anything installed besides ssh. I need to be able to get files to and from C, and I can't do so through F without scp.
My university offers an sslvpn for this situation, but for reasons that I and the technical staff cannot figure out why I cannot ssh into local computers when on the sslvpn. For example, although from an external network I can ssh into F and then to C, I cannot ssh into F OR C (or any other computer on the network) when connected to the sslvpn. The connection just times out.
I've thought that ssh tunneling might be the solution - tunnel my traffic through F to C (as I understand it). Then I can scp to C or from C and the packets will just be tunneled through F. However, I'm having trouble setting this up, and no guides I've found online have been helpful. I want to be able to have an interactive shell on C which is tunneled through F.
I've tried:
~  ᐅ ssh -f -R 3000:me@firewall_here:5222 me@cluster_here -N
~  ᐅ ssh -f -L 3000:me@firewall_here:5222 me@cluster_here -N

I've also tried following this guide: http://www.revsys.com/writings/quicktips/ssh-tunnel.html
and this guide:
With either of those commands, the connection times out when trying to connect to m3@cluster_here just as if I was on the sslvpn. I have no idea how to fix this. Any help appreciated - and can run any commands for more useful information.

A: Not exactly the answer you asked for, but you should be able to transfer files through an SSH connection:
sending
ssh user1@firewall "ssh user2@cluster \"cat > remote_file\" "  < local_file

fetching
ssh user1@firewall "ssh user2@cluster \"cat remote_file\" "  > local_file

EDIT:
There are also terminal based file transfer tools like "zmodem"

A: Read about Reverse SSH. Maybe this will help you. I use it to connect to remote storages behind NAT.


text:
Q: Spot start and end index of values outside specified bounds? I have 3 arrays of size n :
let values = [5, 5, 5, 6, 7, 6, 5, 4, 3, 3, 4, 5, 5];
let min_arr = [3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3];
let max_arr = [7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7];
let n = values.length;

I am trying to spot the indexes of the start and end of the "zones" where min_arr[i] > values[i] or max_arr[i] < values[i].
In the previous arrays the first zone : values[4] = 7 > 6 = max_arr[4] and !(values[5] = 6 > 6 = max_arr[5]) thus start = 4 and end = 5.
In the previous arrays the second zone : values[8] = 3 < 4 = min_arr[8] and values[9] = 3 < 4 = min_arr[9] but !(values[10] = 4 < 3 = min_arr[10]) thus start = 8 and end = 10.
In the previous arrays the expected output would be : [[4, 5], [8, 10]].
Nb: It does not matter if the last end index is greater than n.
Here is my code so far :
let temp = values
  .map((e, i) => min_arr[i] > e || max_arr[i] < e ? i : undefined)
  .filter((e) => e);
console.log(temp);

Output
[4, 8, 9]

My logic here is to first get all the indexes where the value is not in the bounds before removing consecutive values and adding the end value.
let res = [];
let start = temp[0];
for (let i = 0; i < temp.length; i++) {
  if (i + 1 == temp.length) {
    res.push([start, temp[i] + 1]);
    break;
  }
  if (temp[i] + 1 != temp[i + 1]) {
    res.push([start, temp[i] + 1]);
    start = temp[i + 1];
  }
}
console.log(res);

Output
[[4, 5], [8, 10]]

As a beginner in JavaScript, I find this method crude and I believe that the whole process can be done in a declarative way. How should I proceed ?
Please don't hesitate to edit this question if it lacks clarity.

A: Here are not so crude methods, probably they are in declarative way, also with handling some corner-cases. Corner cases i mean in result you are expencting arrays with 2 elements, open index and close index. So if the last element in array is out of bound - still an array with 2 elements will be returned. And at this point im curious about the correct output, probably you have to clarify it a bit. I assumed that indexes shoult be "first index of item that is out of bounds" and "last index of item that is out of bounds", not the "last index + 1"

let values = [5, 5, 5, 6, 7, 6, 5, 4, 3, 3, 4, 5, 5];
let min_arr = [3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3];
let max_arr = [7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7];

function getZones(values, predicateFn) {
  const reduced = values.reduce(
    (acc, curr, i) => {
      const isMet = predicateFn(curr, i);

      if (isMet) {
        if (acc._zone) acc._zone[1] = i;
        else acc._zone = [i];
      } else if (acc._zone) {
        // -1 due to current index is ok, previous was not.
        acc._zone[1] = i - 1;
        acc.result.push(acc._zone);
        acc._zone = undefined;
      }
      return acc;
    },
    {
      _zone: undefined,
      result: []
    }
  );

  // Case when zone was opened and not closed.
  // Happens for last item only.
  const { _zone, result } = reduced;
  if (_zone) {
    if (_zone.length === 1) {
      _zone[1] = _zone[0];
    }
    result.push(_zone);
  }

  return result;
}

const res = getZones(values, (curr, i) => curr < min_arr[i] || curr > max_arr[i]);
console.log(JSON.stringify(res));

Test set i checked with:
const testSets = [
  {
    // Original set
    values: [5, 5, 5, 6, 7, 6, 5, 4, 3, 3, 4, 5, 5],
    min_arr: [3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3],
    max_arr: [7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7]
    // [[4,4],[8,9]]
  },
  {
    // with starting and ending outs
    values: [2, 5, 5, 6, 7, 6, 5, 4, 3, 3, 4, 5, 10],
    min_arr: [3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3],
    max_arr: [7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7]
    // [[0,0],[4,4],[8,9],[12,12]]
  },
  {
    // with starting and ending "wave"
    values: [2, 8, 2, 6, 7, 6, 5, 4, 3, 3, 4, 2, 2, 10],
    min_arr: [3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3],
    max_arr: [7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7]
    // [[0,2],[4,4],[8,9],[11,13]]
  },
  {
    // Completely out of bounds
    values: [2, 2, 2, 2, 2, 2, 2, 8, 8, 8, 8, 8, 8, 8],
    min_arr: [3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3],
    max_arr: [7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7]
    // [[0,13]]
  }
];

Also, here is a codesandbox so you can check the correct output and behavior.

A: Your method will work only for 2 consecutive values , try an example with more  consecutive values like [[2, 7], [8, 11]] and check your method .
The solution can be the next:
let values = [5, 5, 5, 6, 7, 6, 5, 4, 3, 3, 4, 5, 5];
let min_arr = [3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3];
let max_arr = [7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7];

const result = values
  .map((num, i) => (min_arr[i] > num || max_arr[i] < num ? i : undefined))
  .reduce((previousValue, currentValue, currentIndex, array) => {
    if ((currentValue || currentValue === 0) && !array[currentIndex - 1]) {
      const findNextSibling = array.slice(currentIndex).findIndex(i => !i);
      const finalConsecutiveValue =
        findNextSibling === -1 || findNextSibling === 0
          ? 1
          : findNextSibling + currentIndex;

      previousValue.push([currentValue, finalConsecutiveValue]);
    }

    return previousValue;
  }, []);

    console.log('result', result);


text:
Q: Wordpress how do I echo SUM from a column of a MySQL table by user id AND type_operation I have account funds table in wordpress database. Structure like this;
Id           user_id         fund_user        type_operation
-----------------------------------------------------------
1             1379               100              admin_op
2             1565               500              admin_op
3             1379              -50               pay
4             1379               200              admin_op
5             1616              -150              pay

And in my Wordpress page, I want to display the following:
Loggedin user's only admin_op in type_operation, GET TOTAL only positive fund_user values.
I have this;
global $wpdb;
$result_good = $wpdb->get_results("Select sum(fund_user) as good_points from wp_ywf_user_fund_log where type_operation='admin_op'");

        $haha= "Total Points for Good =".$result_good['good_points'];
        echo $haha;
        return $haha;

but that result none and i cant edit that for my specific query.
How can i get and echo in that table, for current user, specific type_operation's Total of fund_user's value?
Thanks for all replies.

A: If it's no extricly neccesary perform an operation in a sql statement I would prefere perfom it over an Array of admin_op data, like :  op_sum = get_results( Select fund_user FROM table WHERE type_operation = admin_op ); then var = array_sum(op_sum);


text:
Q: not exist weight property for widget in eclipse I'm trying set value for weight property in eclipse mars and android 20
but it was not in properties window, and while get xml coding page it was not there. how to get weight property?

A: this is my layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="sajjad.sadeghi.test.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="128dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="55dp"
        android:layout_marginTop="29dp"
        android:text="Distance" />

    <Button
        android:id="@+id/button2"
        android:layout_width="128dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:text="Volume" />

    <Button
        android:id="@+id/button3"
        android:layout_width="128dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:text="Speed" />

    <Button
        android:id="@+id/button4"
        android:layout_width="128dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button3"
        android:layout_centerHorizontal="true"
        android:text="Temprature" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button4"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="94dp"
        android:text="Design by android team "
        android:textSize="24sp" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="2015"
        android:textSize="24sp" />

</RelativeLayout>

A: android:layout_gravity is a attribute of LinearLayout,so you can't use it in RelativeLayout.


text:
Q: Facebook accountkit integration in Signup page I have successfully integrated Facebook account kit. Now I want to use it within my signup page. As Facebook account kit provide a different page for writing a phone number and another for verify otp. But I want to take phone number from signup page and directly go to verification page (enter otp page).
I have gone through the documentation
I have followed all steps and successfully created a simple demo as per the doc.
Please let me know if you required any code. Please suggest any links or tutorial for the same


text:
Q: Канал pipe между двумя консолями Здравствуйте. Нужно что-то типо клиент сервер. Сама программа аналог утилиты dir. При запуске создает две консоли. Задача клиента передать путь до папки серверу через канал pipe. Сервер обрабатывают саму программу и передает обратно результат её выполнения. Помогите с этим pipe.
Сама программа сервера:
#include <stdio.h>
#include "dirent.h"
#include <iostream>

int main(int argc, char* argv[])
{
  DIR *dir;
  struct dirent *entry;
  if (argc > 1){
      dir = opendir(argv[1]);
  }
  if (!dir) {
      perror("diropen");
      return 1;
  };

  while ((entry = readdir(dir)) != NULL)
  {
      printf("%s\n", entry->d_name);
  };

  closedir(dir);
  std::cin.get();
  return 0;
};

Разобрался, только теперь одна проблема.
Эта функция которая передает данные клиенту:
while ((entry = readdir(dir)) != NULL)
{
    if (!WriteFile(hNamedPipe, entry->d_name, strlen(szBuf) + 1, &cbWritten, NULL));
}; `

Эта принимает:
if (ReadFile(hNamedPipe, szBuf, 512, &cbRead, NULL));
Итог то что клиент видит только первую строку которую передал сервер. Потому что он не зациклен, а я не знаю сколько строк придет чтобы через for сделать. А через while не знаю как. Есть что то типо "пока сервер передает, принимай"?

A: Обманите цикл while, указав в его условии true, так как операция чтения канала (pipe) является блокируемой (если входных данных нет, программа не выполняется), с вами не случится зацикливание кода.

A: Решилась проблема давно, решил ответить сам на свой вопрос, может пригодится кому нибудь. Пошел по пути который дал @avp. А т.е отправил символ который не может встретиться в папке ("|").
Получилось после всей отправки данных на сервере:
if (!WriteFile(hNamedPipe, "|", strlen(szBuf) + 1, &cbWritten, NULL));

На клиенте:
if (strcmp(szBuf, "|") != 0)
{
    //если не пришел этот символ
}
else
{
    break; //выход из цикла while (чтения данных)
}