text:
Q: Trying to put all the values below and above the main diagonal equal to 0 in a matrix So my fuction to put all zeros except the main diagonal is a mess and its not doing the work.
The first function is going to subtract each entrance on a line of a matrix for (one of the main diagonal entrance * ( one of the main diagonal entrance * ( one of the main diagonal entrance / an entrance below or above the main entrance). (Sorry for my English)
def subtract_lines(m,r,x,y):
for i in range(r,r + 1):
    for j in range(0,m.shape[1]):
        m[i,j] = m[i,j] - (y * (x / y))
return m

The second function is supossed to give me a answer like this: numpy.array([[4.0,2.0,3.0],[3.0,4.0,3.0],[2.0,5.0,6.0]] = array([[ x., 0.,  0.],[ 0.,  x.,  0.],[0.,  0.,  x.]]) x = Random Number. (I hope i had this result in my code)
def all_zeros(m):
for i in range(0,m.shape[0]):
    for j in range(0,m.shape[1]):
            for l in range(0,m.shape[0]):
                for c in range(0,m.shape[1]):
                    if i == j and l != i:
                        subtract_lines(m,l,m[l,j],m[i,j])
return m

If someone can understand what I´m saying and can help me, I would be extremely grateful!

A: (I'm not entirely certain I'm interpreting your question correctly, but I don't have enough reputation to clarify as a comment so this is my best attempt at an answer.)
Numpy has some helper functions that seem like they would save you a lot of work: if m is a matrix with n rows and n columns, m.diagonal() is a matrix with 1 row and n columns representing the diagonal entries of your matrix in order. The function numpy.fill_diagonal(m, x) will fill the diagonal cells of your matrix with the value x (or the values of x in order, if x is a list, matrix, or similar data type containing the values you want to place in the diagonal).
I am not clear about the exact. purpose of subtract_lines, and it would help me to understand if you gave an example input and the desired output like you did with the other function.

A: Sorry for being late here. I'm just going to answer the question in the title: "How to set all values above and below the diagonal to zero in a matrix."
Its quite simple:
import numpy as np
arr = np.array([[1,2,3], [4, 5, 6], [7, 8, 9]])

for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        if i == j:
            # We are on a diagonal, do nothing
            continue
        else:
            arr[i,j] = 0

If you want to only set the "upper" triangle to zero, you would use this instead:
import numpy as np
arr = np.array([[1,2,3], [4, 5, 6], [7, 8, 9]])

for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        if i > j:
            # We are above the diagonal
            arr[i,j] = 0
        else:
            continue

And lastly, if you only want to set the lower diagonal to zero:
import numpy as np
arr = np.array([[1,2,3], [4, 5, 6], [7, 8, 9]])

for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        if i < j:
            # We are below the diagonal
            arr[i,j] = 0
        else:
            continue


text:
Q: Batch File wouldn't allow me to log in @echo off
set datetoday=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
set /a batchdate=%datetoday%-1
cd c:\batchreports\DAYENDREPORTS\PREDAYEND\%batchdate%

ftp 192.168.18.188
username
password
cd autoemail
send DEALS_ENTERED_TODAY_ALL_2OM_UP_20170813.xls
bye
exit

When I try to run the code line by line in cmd prompt it works properly but if I run the bat file itself, it just prompts the login screen, which means my code stops working at the line of username.. what should I do so that the code will proceed?

A: To securely get yesterdays date you can't simply subtract one from todays date if this will swap the month as Compo already pointed out.
@echo off
For /f %%Y in (
  'powershell -NoP -C "(get-date).AddDays(-1).ToString(\"yyyyMMdd\")"'
) Do Set Yesterday=%%Y
Set "Folder=c:\batchreports\DAYENDREPORTS\PREDAYEND\%yesterday%"
Pushd "%folder%"||(Echo Can't locate %folder% &Pause&Exit /B 1)

> ftpscript.ftp (
echo host 192.168.18.188
echo username
echo password
echo cd autoemail
echo send DEALS_ENTERED_TODAY_ALL_2OM_UP_%Yesterday%.xls
echo bye
)
(ftp -i -s:ftpscript.ftp 2>&1 >ftpscript.log) && (Del ftpscript.*) || (
Echo An error occured, view log:
more < ftpscript.log
pause
Exit /B 1
)
Exit /B 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove next empty row from text From text:
Text...
Target row

Text...

I need remove row with string 'Target row' and the next empty row. So I need to get:
Text...

Text...

A: $result = preg_replace('/^Target row\r?\n\r?\n/m', '', $subject);

if empty lines must really not contain anything, not even spaces/tabs. If spaces/tabs are allowed, use
$result = preg_replace('/^Target row[ \t]*\r?\n[ \t]*\r?\n/m', '', $subject);

A: You've got few "big options".
Replace characters within a text:
$req = ''; // Partial string to get matched
$length = 0; // If you had a full string not partial, use strlen here

// Now find beginning, don't forget to check with === false
$pos = strpos( $text, $req);
$end = strpos( $text, "\n", $pos+1);

// If you don't have criteria that match from start
$start = strrpos( $text, "\n", $pos-1);
// And build resulting string (indexes +/-2, do your job):
$result = substr( $text, 0, $start-1) . substr( $text, $end+2);

Match results with preg_match_all()
If you need to match more complex patter you could use preg_match_all() with flag PREG_OFFSET_CAPTURE (to get start offset) and than use the same algorithm as previous example (previous should be much more effective).
Use preg_replace
As Tim Pietzcker suggested, but this solution doesn't care about spaces in free row
$result = preg_replace('/^Target row\r?\n\s*\r?\n/m', '', $subject);

Use explode and next
$array = explode( "\n", $text);
// I would use this only when loading file with:
$array = file( 'file.txt');

while( $row = next( $array)){
  if( matches( $row)){ // Apply whatever condition you need
    $key1 = key( $array);
    next( $array); // Make sure it's not === false
    $key2 = key( $array);

    unset( $array[$key1]);
    unset( $array[$key2]);
    break;
  }
}

When loading from file with fgets
$fp = fopen( 'file.txt', 'r') or die( 'Cannot open');
while( $row = fgets( $fp)){
  if( matched( $row)){
    fgets( $fp);// Just skip line
  } else {
    // Store row
  }
}


text:
Q: I'm trying to make a card game. How would I make a deck of cards and then deal them? I am making a card game, I started by placing all the cards in an array of tuples with a number 1-52 assigned. But by using a random number generator to pick the cards it becomes difficult to remove a card from the deck because I can't specifically remove that number from my random number generator. Any help is appreciated.
 func createDeck(){

    deck.append((name: "ace1", number: 1))
    deck.append((name: "ace2", number: 2))
    deck.append((name: "ace3", number: 3))
    deck.append((name: "ace4", number: 4))
    deck.append((name: "two1", number: 5))
    deck.append((name: "two2", number: 6))
    deck.append((name: "two3", number: 7))
    deck.append((name: "two4", number: 8))
    deck.append((name: "three1", number: 9))
    deck.append((name: "three2", number: 10))
    deck.append((name: "three3", number: 11))
    deck.append((name: "three4", number: 12))
    deck.append((name: "four1", number: 13))
    deck.append((name: "four2", number: 14))
    deck.append((name: "four3", number: 15))
    deck.append((name: "four4", number: 16))
    deck.append((name: "five1", number: 17))
    deck.append((name: "five2", number: 18))
    deck.append((name: "five3", number: 19))
    deck.append((name: "five4", number: 20))
    deck.append((name: "six1", number: 21))
    deck.append((name: "six2", number: 22))
    deck.append((name: "six3", number: 23))
    deck.append((name: "six4", number: 24))
    deck.append((name: "seven1", number: 25))
    deck.append((name: "seven2", number: 26))
    deck.append((name: "seven3", number: 27))
    deck.append((name: "seven4", number: 28))
    deck.append((name: "eight1", number: 29))
    deck.append((name: "eight2", number: 30))
    deck.append((name: "eight3", number: 31))
    deck.append((name: "eight4", number: 32))
    deck.append((name: "nine1", number: 33))
    deck.append((name: "nine2", number: 34))
    deck.append((name: "nine3", number: 35))
    deck.append((name: "nine4", number: 36))
    deck.append((name: "ten1", number: 37))
    deck.append((name: "ten2", number: 38))
    deck.append((name: "ten3", number: 39))
    deck.append((name: "ten4", number: 40))
    deck.append((name: "jack1", number: 41))
    deck.append((name: "jack2", number: 42))
    deck.append((name: "jack3", number: 43))
    deck.append((name: "jack4", number: 44))
    deck.append((name: "queen1", number: 45))
    deck.append((name: "queen2", number: 46))
    deck.append((name: "queen3", number: 47))
    deck.append((name: "queen4", number: 48))
    deck.append((name: "king1", number: 49))
    deck.append((name: "king2", number: 50))
    deck.append((name: "king3", number: 51))
    deck.append((name: "king4", number: 52))

}
func randomNumber(){
    random = arc4random_uniform(52) + 0;
    print(random)
}
func deal(){

    var aces = Set<Int>(arrayLiteral:1, 2, 3,4)
    var twos = Set<Int>(arrayLiteral:5, 6, 7,8)
    var threes = Set<Int>(arrayLiteral:9, 10, 11,12)
    var fours = Set<Int>(arrayLiteral:13, 14, 15,16)
    var fives = Set<Int>(arrayLiteral:17, 18,19,20)
    var sixes = Set<Int>(arrayLiteral:21, 22, 23,24)
    var sevens = Set<Int>(arrayLiteral:25, 26, 27,28)
    var eights = Set<Int>(arrayLiteral:29, 30, 31,32)
    var nines = Set<Int>(arrayLiteral:33, 34, 35,36)
    var tens = Set<Int>(arrayLiteral:37, 38, 39,40)
    var jacks = Set<Int>(arrayLiteral:41, 42, 43,44)
    var queens = Set<Int>(arrayLiteral:45, 46, 47,48)
    var kings = Set<Int>(arrayLiteral:49, 50, 51,52)

    if aces.contains(Int(random)){
        playern1 = Int(random)
        aces.removeFirst()
    }
    if twos.contains(Int(random)){
        twos.removeFirst()

...

A: Maintain an array of cards that are still available and not already picked.  For the purpose of this discussion, I will call this the "deal array" (this must be maintained separately to the deck array!  It could start off as a mutable copy of the deck array.).
When you randomly pick/deal a card remove it from the deal array.
Your random number generator should be choosing a number between zero and the number of items left in the deal array - NOT between zero and fifty two.
(Assuming the deal array is not empty - check this before randomly choosing a card from the deal array.)
When selecting a card from the deal array use the random number as an index to the array (not as the card numbers you've created, which are not of any real use for picking cards from the deal array randomly).
(Note that I'm not including any example code here, because it's unclear to me what the purpose of some of your code is.  If I tried to post code here, the chances are that I would mis-interpret your code and therefore post incorrect code).

A: You may want to redesign how you define a card:
enum Suit: String {
    case heart, diamond, club, spade
}
enum Rank: Int {
    case _1 = 1, _2 = 2, _3 = 3, _4 = 4, _5 = 5, _6 = 6, _7 = 7, _8 = 8, _9 = 9, _10 = 10
    case jack = 11, queen = 12, king = 13
}
struct Card {
    let suit: Suit
    let rank: Rank
}

(or an alternative could be enum Card {case card(suit: Suit, rank: Rank)})
Then defining your deck:
var deck = [Card(suit: .heart, rank: ._1),
            Card(suit: .heart, rank: ._2),
            Card(suit: .heart, rank: ._3),
            Card(suit: .heart, rank: ._4),
            Card(suit: .heart, rank: ._5),
            Card(suit: .heart, rank: ._6),
            // ...
]

Then picking a card from a deck:
func pickRandomCardFromDeck() -> Card {
    return deck.remove(at: Int(arc4random_uniform(UInt32(deck.count))))
}

[edit for comment]
To check for a pair:
extension Card {
    func isPair(with card: Card) -> Bool {
        return rank == card.rank
    }
}


text:
Q: Global variable is not recognized inside a procedure in TCL script for ns-2 I am trying to run the following tcl script but getting an error in procedure thpt_rec that
ns: thpt_rec: can't read "tcps(0)": no such variable
    while executing
"$tcps(0) set bytes_"
    (procedure "thpt_rec" line 4)
    invoked from within
"thpt_rec"
But when I replace this tcps(0) with a variable named sink at all place everything works well. Kindly shed light in this issue.
set ns [new Simulator]
set tracefile [open tcpf1.tr w]
set thptfile  [open thpt.tr  w]
$ns trace-all $tracefile

proc finish {} {
global ns tracefile thptfile
$ns flush-trace
close $tracefile
close $thptfile
exit 0
}

proc thpt_rec {} {
global ns tcps(0) thptfile
set time 1.0
set bw [$tcps(0) set bytes_]
set now [$ns now]
puts $thptfile "$now [expr $bw/$time*8/1000000]"
$tcps(0) set bytes_ 0
$ns at [expr $now+$time] "thpt_rec"
}

for {set i 0} {$i < 10} {incr i} {
set n($i) [$ns node]
}

for {set i 0} {$i < 4} {incr i} {
$ns duplex-link $n($i) $n(4) 10Mb 2ms DropTail
$ns duplex-link $n(5)  $n([expr ($i+6)]) 10Mb 2ms DropTail
}

$ns duplex-link $n(4) $n(5) 0.25Mb 10ms DropTail

set tcp(0) [new Agent/TCP]
$ns attach-agent $n(0) $tcp(0)
set tcps(0) [new Agent/TCPSink]
$ns attach-agent $n(6) $tcps(0)
$ns connect $tcp(0) $tcps(0)
set ftp(0) [new Application/FTP]
$ftp(0) attach-agent $tcp(0)

$ns at 0.0 "thpt_rec"
for {set i 0} {$i < 1} {incr i} {
$ns at [expr (5.0 * $i )] "$ftp($i) start"
$ns at 140.0 "$ftp($i) stop"
}
$ns at 150.0 "finish"

$ns run

A: Replace
global ns tcps(0) thptfile

with
global ns tcps thptfile

and it should work OK.
The problem is that the tcps variable is an array, and array elements are not variables — they are just values.  So if you want to access an element of a global array in a procedure, you should declare the array variable itself as global.


text:
Q: ReactJs state change and value is not what I want I try to build a calendar app to practise.
In the state I have a current_month: 1, and  I have a function IncreaseMonth() to increase current_month but when current_month value becomes 12, I want it changed to 1.
I try to use componentWillUpdate() lifecycle method to do it, in the code below:
componentWillUpdate(prev, next) {
   if (next.current_month == 13) {
     this.setState({current_month: 1})
   }
}

But I watch tutorials about lifecycle, which tell me not to use componentWillUpdate() to set state.
Is there a better way to do this?

A: The correct way would be to move reseting month value into IncreaseMonth() method as shown below.

IncreaseMonth = () => {
  let month = 1;
  if (this.state.current_month < 12) {
    month = this.state.current_month + 1;
  }

  this.setState({
    current_month: month
  });
}

You MUST not set the state in componentWillUpdate() lifecycle event as that event is triggered to indicate that the component is going to be re-rendered, and you can decide within this method whether the component should continue with re-rendering. If this method returns true, the component will be re-rendered. For more information, refer the official documentation


text:
Q: onHover not working with scenegraph in deck.gl my code - layer
new ScenegraphLayer({
  id:"22",
  scenegraph: "glb/22.glb",
  data: dataArray.glb22,
  getPosition: d => [d.geometry.coordinates[0],
                     d.geometry.coordinates[1], 0] ,
  sizeMinPixels: 1,
  sizeMaxPixels: 10,
  getOrientation: [0, 180, 90],
  getTranslation: [0, 0, 0],
  sizeUnits: 'meters',
  onHover: this._onHover
});

onHover Code is
_onHover({x, y, object}) {
  console.log("TTTTTTTTTTTTTTTTT");
}

but not working. this code working in geojsonLayer.
how to fix my code? I want onHover working in scenegraph-layer.
thanks.

A: I think you just forgot to add pickable ability. onHover required pickable properties to be true. You can read more about that here.
Here there is an online example of ScenegraphLayer from official documentantion and here you can see the source code. Pay attention to row 116:
const layer =
    data &&
    new ScenegraphLayer({
      id: 'scenegraph-layer',
      data,
      pickable: true,
      ...
    });


text:
Q: Controlling space between sentences in Microsoft Word In Microsoft Word, if I use two spaces between sentences, the spacing becomes way more than twice the distance if I use only one space.  This happens only in a particular document, and does not occur if I copy-paste the text into a new document.  Doing regular paste and paste as plain text produces the same result.
This is with left-justified text, Times New Roman 12.  All settings in Font and Paragraph are the same between the documents.  This is in Microsoft Word 2016.  No compatibility settings are enabled.
If I only use one space between sentences, the behavior is as expected.
Here is a picture showing the issue I'm talking about.

What setting controls this behavior and how can I change my document so that the formatting matches what happens in a new document?

*

*Link to this document: Original document

*Link to new document with same text: New document

A: This document seems to have come from another operating system and another
word processor. It refers to fonts that do not exist in Windows, so Word
tries to substitute them with existing fonts, but apparently not very correctly.
I have managed to get rid of the weird formatting, but it took some manipulations.
I did as follows:

*

*Open menu File > Options > Advanced

*Under "Show document content", click Font Substitution..., which looks like:

*For "Helvetica", set "Substituted font:" to "Arial", click
Convert Permanently... and answer OK

*Click again Font Substitution...

*For "Times", set "Substituted font:" to "Times New Roman",
click Convert Permanently... and answer OK

*Open menu File > Save As, choose your folder, set "Save as type:" to
"Word 97-2003 Document (*.doc)" and save the document

*Close Word

*Open the .doc document - the spacing should now be normal.
In my testing, all the above steps were necessary and none of them
could be omitted.

A: I've struggled with this exact issue. Try this:

*

*Go to "File" tab in MS Word on far left of the screen. Scroll down and select "Options".

*A new window will open. Select "Advanced" from the menu on the left.

*Scroll to the bottom of the list of sections. You will see a section titled "Layout options for [DOC TITLE].   Look for the checkbox option titled "Balance SBCS characters and DBCS characters (4th from the top).

*Select "Okay" to exit out of the "Options" window and go back to your document.
This worked for me. Hope it works for you.


text:
Q: C# How to Access Hidden DataTable Columns That is DataSource Binded in DataGridView I having a hard time trying to access hidden columns that been hidden in DataTable which later bind and accessed in DataGridView
In Details : dtResult is a DataTable
Example Tried :
dtResult.Columns[i].ColumnMapping = MappingType.Hidden;

OR
dtResult.Columns.RemoveAt(i);

Then Store into DataSource of DataGridView :
dataGridView.DataSource = dtResult;

Accessing Hidden Columns occur error :  "Columns 'Active' Cannot be found" :
dataGridView.SelectedRows[0].Cells["active"].Value.ToString()

So Is there are way for DataGridView to get Hidden Columns that been hidden in DataTable before binding it into DataGridView ?
Please help me~ . Thank you
FYI :
I just realized
That DataSource Binding doesn't include Hidden Columns of DataTable.
Means That If DataTable.Column.Count = 10. (2 Hidden)
DataGridView.DataSource = DataTable.
DataGridView.Column.Count == 8.

So lead me to ask.
How to Bind Those Hidden Column into the DataGridView From DataTable

A: Why do you need to hide the column in the datatable ? Visability in UI is a UI concern, I would bind the the datatable to the datagridview and hide the desired columns in the datagridview.

A: I know this is old but I had the same issue today so I am posting my solution. I was using DataSet.ReadXml(Stream) to dump an xml file into a DataSet and the columns that are generated for relations were not showing up in a DataGridView. The following code loops through all of the columns in each DataTable in the DataSet and changes the ColumnMapping property to MappingType.Element. I picked MappingType.Element since the visible columns were set to that and the description fits for my situation: "The column is mapped to an XML element."
Short answer: Change the ColumnMapping from MappingType.Hidden to something that is not hidden before binding to the DataGridView.
    ...
    DataSet ds;
    ...
    foreach(DataTable dtbl in ds.Tables)
    {
        foreach(DataColumn dcol in dtbl.Columns)
        {
            if (dcol.ColumnMapping == MappingType.Hidden)
            {
                dcol.ColumnMapping = MappingType.Element;
            }
        }
    }

    DataGridView.DataSource = ds;

Then if you need to hide them in UI you can do it on the DataGridView.


text:
Q: How to plot circles in trading view with for loop using pine code I am trying to use square numbers gann square of 9 logic, for that i am trying to plot lines or circles
with the for loop
but when i am trying  getting this error  Cannot use 'plot' in local scope.
Please help me Thanks in advance

A: The function plot can't be used inside loops, however, this isn't the case for line.new or label.new, you can try using these functions instead.


text:
Q: Special UnknownHostException with machine name I get an UnknownHostException (from lookuphostbyname).
Doing this:
result = httpClient.execute(httpGet, responseHandler);

I have the internet permission and internet access.
AND: If I use the ip it works.
If I use http://www.google.de it works.
But if I use the machine name in the URL it doesn't...
How can this be? Does android/java do not handle machine names?
I also tried:
InetAddress i = InetAddress.getByName(URLName);

I don't know that I can do next...
Edit: With the fqdn it work's. But machine names dont?

A: Just to clarify a few things.
If you are using the emulator it can be considered exactly the same as using a separate device.
By this, any network requests will be treated as NOT coming from your PC.
While I believe it is possible to get into the device/emulator and add a host record, its not a path you really want to go down.
Best bet is to just use IP address or always make sure the address you are using are in a DNS that is accessible from the device/emulator (doesn't need to be a public one).
Basically think of the emulator/device as a separate computer and you will know where you need to go

A: The machine name must either be registered in a DNS that this machine can see, or it needs to be resolved in your hosts file.


text:
Q: Non-scrollable ListView inside ScrollView with different size items Non-scrollable ListView inside ScrollView with different size items. actually i tried getting no of list items and giving height = no of items* height of first item, but the issue is i have items with different height in list so last item sometimes not visible.
here is my custom listview:
public class ExpandedListView  extends ListView {

    private android.view.ViewGroup.LayoutParams params;
    private int old_count = 0;
    int limit=0;
    public ExpandedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getCount() != old_count) {
            old_count = getCount();
            params = getLayoutParams();
            int height=0;

            int h =getCount() * (old_count > 0 ? getChildAt(0).getHeight() : 0);

            int minHeight=setListViewHeightBasedOnChildren(this);
            if (h>minHeight) {
                params.height=h+8 * (getCount() - 1)+25;
                setLayoutParams(params);
            }

            super.onDraw(canvas);
        }
    }

    public static int setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return 0;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1))+100;

        listView.setLayoutParams(params);
        return params.height;
    }

}

A: i not understand your question exact what you want.
If you want to make listview scrolable with same heights and width of every listview item then use inflater.make single row and use this in array using inflater.
if your question is this then i show you the code of listview with same heighta and width of every listview item.


text:
Q: ( find Distance and display ) in Arrays Any suggestion on writing proper codes to get distance between src and dest and Display the distance to user .

    int distance = findDistance(CityNames, distances, src, dest);
        display(distance);
    }

    public static int findDistance(String[] CityNames, int[][] distances, String src, String dest) {
        // Find and return the distance between src and dest.
        return 0;
    }

    public static void display(int distance) {
        // Display the distance to user.
    }

}

A: package test; // sample of array w/o validation .

import javax.swing.JOptionPane;

class ArrayTest {
    public static void main(String[] args) {
        int distances[][] = {{0, 50, 100, 20}, {50, 0, 70, 110}, {100, 70, 0, 200}, {20, 110, 200, 0}};
        String cityNames[] = {"herndon", "fairfax", "baltimore", "centerville"};

        String departure = JOptionPane.showInputDialog("Enter departure city");
        String destination = JOptionPane.showInputDialog("Enter destination city");
        int departureIndex = findCity(departure, cityNames);
        int destinationIndex = findCity(destination, cityNames);
        display(departureIndex, destinationIndex, distances);
    }

    private static int findCity(String cityName, String[] cityNames) {

        for (int i = 0; i < cityNames.length; i++) {
            if (cityName.equalsIgnoreCase(cityNames[i]))
            {
                return i;
            }

        }
        return -1;
    }

    private static void display(int departureIndex, int destinationIndex, int[][] distances) {

        JOptionPane.showMessageDialog(null, "Distance is " + distances[departureIndex][destinationIndex]);
    }

}


text:
Q: Calling Oracle Stored Procedure from Laravel which has 2 IN and one OUT parameters
*

*Here is my Procedure:
create or replace PROCEDURE GET_CONTENT(IID IN INTEGER, key IN RAW, DATA
   OUT CLOB)
   AS
   BEGIN
   SELECT ENCRYPT_DECRYPT.DECRYPT(DATA, KEY, UTL_RAW.cast_to_raw(key))
   INTO DATA
   FROM AUDIT_TABLE
   WHERE ID = IID;
   END;

*Here is what i have been trying:
$pdo = DB::connection('oracle')->getPdo();

$sql = 'CALL GET_CONTENT(?,?,?)';
$stmt = $pdo->prepare($sql);
$lid =  11;
$key = 'MASTERKEY';
$stmt->bindParam(1, $lid, PDO::PARAM_INT, 10);
$stmt->bindParam(2, $master_key, PDO::PARAM_STR|PDO::PARAM_INT, 100);
$stmt->bindParam(3, $DataResult, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT,
200);
print "Values of bound parameters _before_ CALL:\n";
print "  1: {$lid} 2: {$key}\n";

$stmt->execute();

print "Values of bound parameters _after_ CALL:\n";
print "  1: {$lid} 2: {$key}\n";

Error: Illegal name variable/number


text:
Q: Proving iterative methods to calculate a linear system of equations converge. Given the $n\times n$ matrix
$$B=\begin{bmatrix}
\frac{1}{2}&\frac{1}{2^2}&\frac{1}{2^3}&\cdots &\frac{1}{2^n}\\
a &0&0 &\cdots&0 \\
 0 &a&0&\cdots &0\\
\vdots&\ddots &\ddots&\ddots&\vdots\\
0&\cdots&\cdots&a&0\end{bmatrix}$$
I want to prove the Gauss-Seidel or Jacobi method used to solve linear system of equations $Ax=b$ converge (in this case, for any vector $b$). I know the Jacobi iteration matrix is $D^{-1}(L+U)$ where $$D=\begin{bmatrix}1/2&0&\cdots&0
\\
0&0&\cdots&0\\
\vdots&\vdots&\ddots&\vdots\\
0&0&0&0\end{bmatrix}$$
$$L=\begin{bmatrix}0&0&\cdots&\cdots&0
\\
a&0&\cdots&\cdots&0\\
0&a&0&\cdots&0\\
\vdots&\ddots&\ddots&\ddots&\vdots\\
0&0&0&a&0\end{bmatrix}$$
$$U=\begin{bmatrix}
0&\frac{1}{2^2}&\frac{1}{2^3}&\cdots &\frac{1}{2^n}\\
0 &0&0 &\cdots&0 \\
 0 &0&0&\cdots &0\\
\vdots&\ddots &\ddots&\ddots&\vdots\\
0&\cdots&\cdots&0&0\end{bmatrix}$$
are all $n\times n$ matrices. To converge, the Jacobi iteration matrix must have a spectral radius of $|\rho|<1$. The problem is that $D$ is not invertible, so I can't calculate this matrix. The same happens with the Gauss-Seidel iteration matrix: $(D+L)^{-1}U$. What can I do to avoid that problem?


text:
Q: Как обновлять tableView в MVP Практикуюсь в написании проекта с использованием MVP. Есть задача - обновить таблицу после того, как новый элемент был добавлен в модель.
Метод внутри DataStorageObserver, который обновляет модель:
func addContact(contact: Contact) {
  DataStorage.sharedInstance.contactList.append(contact)
  NSNotificationCenter.defaultCenter().postNotificationName(Constants.Identifiers.sharedInstance.contactListUpdateIdentifier, object: nil)
}

View реализует методы протокола
protocol ContactListViewProtocol: class {
  func updateData()
}

Сам метод обновления, который внутри View (роль которой играет UITableViewController)
func updateData() {
  self.tableView.reloadData()
}

Внутри пресентера есть метод:
required init(view: ContactListViewProtocol) {
  self.view = view
  NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ContactListViewProtocol.updateData), name: Constants.Identifiers.sharedInstance.contactListUpdateIdentifier, object: nil)
}

Xcode подсказывает о том, что последний required init содержит ошибку

Argument of '#selector' refers to a method that is not exposed to
  Objective-C

Если принять подсказку от Xcode, то он предлагает подставить к методу в ContactListPresenterProtocol метку @objc, который (метод) никак не относится к логике обновления (полагаю, что косяк ide). Как лучше следует реализовать обновление? Где следует проставить @objc? Стоит ли?

A: Селекторы, это часть ОбжС и могут использоваться только с методами, которые существуют в Obj-C runtime. Нельзя вызвать селектором метод swift'а.
Если ваш класс наследован от NSObject, то все его публичные методы видны в обжС автоматически. Поскольку ваш класс не наследован от NSObject, вам надо использовать аттрибут @objc, чтобы обозначить, что вы хотите, чтобы этот метод был доступен для вызова используя selector.
#selector() это новый синтаксис доступный в Swift 2.2. Он позвоняет компилятору проверить, что селектор, который вы хотите вызвать существует. Старый синтаксис будет удален в Swift 3.0

A: Ошибка у вас в том, что вы вызываете updateData на self, а метод у вас в классе view
NSNotificationCenter.defaultCenter().addObserver(self.view,selector: #selector(ContactListViewProtocol.updateData), name: Constants.Identifiers.sharedInstance.contactListUpdateIdentifier, object: nil)


text:
Q: Can multiple files be moved in as a batch I want to move multiple files from one directoy to anoher. I use 'My.Computer.FileSystem.MoveFile' and that works fine but it handles one file at a time. So, for every already existing file in that directory I get a warning (ie. 'File already exists') instead of one warning for the batch. Is it posible to get one warning for all the moved files?
       For i = .Items.Count - 1 To 0 Step -1

                Dim map = .Items.Item(i).SubItems(COL_MAP).Text
                Dim bestandHernoemd = .Items.Item(i).SubItems(COL_HERNOEMD).Text
                Dim bestandOrigineel = .Items.Item(i).SubItems(COL_ORIGINEEL).Text

                    Try

                        My.Computer.FileSystem.MoveFile(map & bestandOrigineel, My.Settings.OPTIE_OvernemenStandaardMapNaam & bestandHernoemd, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException)

                        .Items.RemoveAt(i)

                    Catch ex As Exception

                        foutLijst.Add(bestandOrigineel & ": " & ex.Message)

                    End Try
        Next

A: And if you want to copy files recursively ( all folders, subfolders, files or subfiles ) from one source to destination, you can use the below sub procedure. No Warning applied and shall overwrite the destination.
Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
   Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
        'If the destination folder doesn't exist then create it'
      If Not System.IO.Directory.Exists(destinationPath) Then
            'Obs, folder doesn't exist, create one please :)'
         System.IO.Directory.CreateDirectory(destinationPath)
      End If
   Dim fileSystemInfo As System.IO.FileSystemInfo
       For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
         Dim destinationFileName As String = System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)
            'Now check whether its a file or a folder and take action accordingly
            If TypeOf fileSystemInfo Is System.IO.FileInfo Then
              System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
            Else
              ' Recursively call the method to copy all the nested folders
              CopyDirectory(fileSystemInfo.FullName, destinationFileName)
            End If
       Next
End Sub


text:
Q: How can I put an Anchor in React.js next to React-router-dom? or there is a better way to put anchors in react.js I have a spa that consists of a homepage, categories, about us and contact us.
They all take you to a different component except categories that should take me to a part of the homepage.
Is there a way how to do it with React-router or is there another way
to do it?

A: It is hard to give feedback without seeing your code.
But if I understood correctly, you want to navigate between the different components using React-Router.
You can import the Router, Switch and Route from React-Router and then in your toplevel-container component, you would create the different  for each component, making the URL change based on each component, e.g. /about-us, /contact-us, etc.
If you want your categories to be part of your homepage, then you could create another  inside Homepage component, where you want it displayed, if it's only rendered at a specific URL. If you want it displayed at all times, then make the link go to the /homepage URL, same as for the regular homepage component.


text:
Q: EGit does not commit I had a Scala project, synchronized with GitHub. Then I had to reinstall my OS. I installed Eclipse and EGit, then imported the project from the remote location.
Now, when I make changes to the project, commit does nothing. It does not open the dialog which lets me enter a message and select files to commit. The files are still displayed as changed in the package explorer. I read somewhere that EGit logs errors to stdout, but when I start Eclipse from the command line, I see no errors logged.
If I try to push, I get asked for the passphrase for my ssh keys, and there is a window with a progress bar, but then the content of the remote repository does not change.
I am quite new to Git and don't know where to go further to diagnose the problem. What I did was to get into the Eclipse preferences and restore the defaults on preferences windows in the Git group. This didn't help.
One thing which I noticed is that the project itself is in the git directory, so when I make changes to the code and save, they get written there, not under the workspace directory of Eclipse. I don't know if this is relevant (maybe it can't write the changes to the local repository because there is no local repository copy to be updated?), but I didn't see a setting to change this location when I imported the project.
What can I do to troubleshoot this problem?


text:
Q: merge based on a character column in R I am trying to merge 2 dataframes which have a column (one has more rows than the other) in common, keeping the row order the same, having seen on this website the different SQL joins that can be performed with the merge function. However, it doesn't merge row names into a single one (the columns are merged but I get many duplicates in the row names, as you can see by the output I get - see below)... how could I proceed ?
 bilans_18_19 <- merge(bilan_melia_2018, bilan_melia_2019, by = "bilan_consolide")

Here is the structure of my datasets :
structure(list(bilan_consolide = c("NON-CURRENT ASSETS", "Goodwill",
"Other intangible assets", "Property Plant and Equipment", "Investment property",
"Investments measured using the equity method"), `31/12/2018` = c("",
"67 999", "107 588", "1 856 801", "149 437", "197 817"), `31/12/2017` = c("",
"60 714", "102 194", "1 682 040", "135 900", "229 644")), row.names = 99:104, class =
"data.frame")

structure(list(bilan_consolide = c("NON-CURRENT ASSETS", "Goodwill",
"Other intangible assets", "Property Plant and Equipment", "Right of use",
"Investment property"), `31/12/2019` = c("", "72 267", "73 408",
"1 923 267", "1 251 255", "116 267"), `31/12/2018` = c("", "67 999",
"76 372", "1 851 194", "1 064 130", "149 437"), `01/01/2018` = c("",
"60 714", "67 660", "1 676 072", "1 172 344", "135 900")), row.names = 98:103, class =
"data.frame")

And the structure of the output I get after merging them :
structure(list(bilan_consolide = c("Bank loans", "Bank loans",
"Bank loans", "Bank loans", "Bonds and other negotiable securities",
"Bonds and other negotiable securities"), `31/12/2018.x` = c("719 949",
"719 949", "115 066", "115 066", "33 835", "33 835"), `31/12/2017` = c("644 515",
"644 515", "209 482", "209 482", "", ""), `31/12/2019` = c("786 923",
"100 343", "786 923", "100 343", "33 951", "172"), `31/12/2018.y` = c("719 949",
"115 066", "719 949", "115 066", "33 835", "51 526"), `01/01/2018` = c("644 515",
"209 482", "644 515", "209 482", "", "71 610")), row.names = c(NA,
6L), class = "data.frame")

I know this code to suppress identical columns, do you know how I could replicate it for identical rows in one column ?
library(digest)
non_duplicates <- df[!duplicated(lapply(df, digest))]

duplicates <- df[duplicated(lapply(df, digest))]

for(i in 1:ncol(non_duplicates)){
  for(j in 1:ncol(duplicates)){
    if(FALSE %in% paste0(non_duplicates[,i] == duplicates[,j])) NULL
    else names(non_duplicates)[i] <- paste(names(non_duplicates[i]),
names(duplicates[j]), sep = "+")
  }
}
DF <- non_duplicates

Thanks in advance !
EDIT : i found a way out, but still would appreciate a code for a loop removing duplicate rows based on the value in one column (for instance here, in the names in "bilan_consolide"). Here is the code that works :
 library(dplyr)
 test_1 = bilan_melia_2019[,(1:3)] %>%
   full_join(bilan_melia_2018[,c(1,3)], by = "bilan_consolide")

And the structure of test_1, which is the desired one :
structure(list(bilan_consolide = c("NON-CURRENT ASSETS",
"Goodwill",
"Other intangible assets", "Property Plant and Equipment", "Right
of use",
"Investment property"), `31/12/2019` = c("", "72 267", "73 408",
"1 923 267", "1 251 255", "116 267"), `31/12/2018` = c("", "67
999",
"76 372", "1 851 194", "1 064 130", "149 437"), `31/12/2017` =
c("",
"60 714", "102 194", "1 682 040", NA, "135 900")), row.names =
c(NA,
6L), class = "data.frame")


text:
Q: Connect an iPad Pro to an older Macbook Pro using a generic USB-C to USB-A cable The older Macbook Pro I'm using doesn't have USB-C ports. The cable that came with the iPad Pro I'm using came with a USB-C to USB-C cable. I tried to use a USB-C to USB-A cable from a Huawei phone to connect the iPad and the Macbook, but there was no connection whatsoever.
Does it mean I'll have to get hold of a very specific USB-C to USB-A cable, such as a "Belkin USB-A to USB-C Cable (USB 3.1)" (cf. https://support.apple.com/en-us/HT209186#computer)?

A: No, there's no need to use that specific cable. Any standards-compliant USB-C to USB-A cable should work.


text:
Q: error: could not create '/usr/local/lib/python2.7/dist-packages/sklearn': Permission denied I'm trying to install scikit learn following by
http://scikit-learn.org/stable/install.html
but at the end getting this error
creating /usr/local/lib/python2.7/dist-packages/sklearn

error: could not create '/usr/local/lib/python2.7/dist-packages/sklearn': Permission denied

----------------------------------------
  Can't roll back scikit-learn; was not uninstalled
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_tauqeer/scikit-learn/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-i5vTnt-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_tauqeer/scikit-learn
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    load_entry_point('pip==1.5.4', 'console_scripts', 'pip')()
  File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 235, in main
    return command.main(cmd_args)
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 161, in main
    text = '\n'.join(complete_log)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 48: ordinal not in range(128)

I have also tried pip install scikit-learn and it shows
Requirement already satisfied (use --upgrade to upgrade): scikit-learn in /usr/lib/python2.7/dist-packages
Cleaning up...

I have also tried it by using
sudo apt-get install scikit-learn

by trying sudo I'm getting this

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package scikit-learn

A: Make sure that you have installed dependencies. Installing from source requires you to have installed the scikit-learn runtime dependencies
You can install them using
sudo apt-get install build-essential python-dev python-setuptools \
                     python-numpy python-scipy \
                     libatlas-dev libatlas3gf-base

Then use below command to install
pip install --user --install-option="--prefix=" -u scikit-learn

Then you will not get any error.


text:
Q: Где находить соглашения по codestyle В различных ЯП есть соглашения по код стайлу
например в названии переменной:
   _apiBase = 'https://swapi.dev/api'
вместо:
   apiBase = 'https://swapi.dev/api'
(нижнее подчёркивание)
Или в redux дополнительные данные передаются с именем payloads
И это касается не только имен переменных, но иногда и архитектуры проекта, и многое другое
Так вот вопрос в том, где можно ознакомиться со всем этими соглашениями?
Чтобы понимать почему имя переменной с нижнего подчеркивания, почему payloads, и тд и тп.

A: Насколько я понимаю, по крайней мере в JavaScript — такое соглашение является средним арифметическим от целого ряда традиций в разных обществах разработчиков. Некоторые традиции кодифицированы. Например, популярные стилистические руководства:

*

*https://github.com/airbnb/javascript

*https://github.com/airbnb/javascript/tree/master/react

*https://google.github.io/styleguide/jsguide.html

*https://github.com/rwaldron/idiomatic.js

*https://standardjs.com/
Проверять код на соответствие популярным соглашениям можно при помощи "линтеров". Иногда в руководствах к ним также перечисляются распространённые практики:
https://github.com/sorrycc/awesome-javascript#qa-tools
Одним из самых популярных сейчас линтеров является ESLint (https://github.com/eslint/eslint). В его документации описываются некоторые правила, ряд из них помечен как рекомендуемые разработчиками линтера. Это тоже может быть полезным чтением: https://eslint.org/docs/rules/


text:
Q: neo4j - Create relationships between all nodes in database (Out of memory) I have a neo4j database with ~260000 (EDIT: Incorrect by order of magnitude previously, missing 0) nodes of genes, something along the lines of:

*

*example_nodes: sourceId, targetId

*with an index on both sourceId and targetId
I am trying to build the relationships between all the nodes but am constantly running into OOM issues. I've increased my JVM heap size to -Xmx4096m and dbms.memory.pagecache.size=16g on a system with 16G of RAM.
I am assuming I need to optimize my query because it simply cannot complete in any of its current forms. However, I have tried the following three to no avail:
MATCH (start:example_nodes),(end:example_nodes) WHERE start.targetId = end.sourceId CREATE (start)-[r:CONNECT]->(end) RETURN r

(on a subset of the 5000 nodes, this query above completes in only a matter of seconds. It does of course warn: This query builds a cartesian product between disconnected patterns.)
MATCH (start:example_nodes) WITH start MATCH (end:example_nodes) WHERE start.targetId = end.sourceId CREATE (start)-[r:CONNECT]->(end) RETURN r
OPTIONAL MATCH (start:example_nodes) WITH start MATCH (end:example_nodes) WHERE start.targetId = end.sourceId CREATE (start)-[r:CONNECT]->(end) RETURN r
Any ideas how this query could be optimized to succeed would be much appreciated.
--
Edit
In a lot of ways I feel that while the apoc libary does indeed solve the memory issues, the function could be optimized if it were to run along the lines of this incredibly simple pseudocode:
for each start_gene
create relationship to end_gene where start_gene.targetId = end_gene.source_id
move on to next once relationship has been created

But I am unsure how to achieve this in cypher.

A: You can use  apoc library for batching.
call apoc.periodic.commit("
MATCH (start:example_nodes),(end:example_nodes) WHERE not (start)-[:CONNECT]->(end) and id(start) > id(end) AND start.targetId =
end.sourceId
with start,end limit {limit}
CREATE (start)-[:CONNECT]->(end)
RETURN count(*)
",{limit:5000})


text:
Q: Apache loading time in microseconds - difference between header and log I recently followed this guide to obtain performance measurement of siteload on a web server.

To log the time it takes for Apache to process a request add this to your apache configuration file:
LogFormat "%h %D %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

%D means you'll see the time it took Apache to process the request in the access log. The time is measured in microseconds.
To make it even easier to debug page load times, add this to your configuration file:
Header set X-Request-Received: %t
Header set X-Request-Processing-Time: %D

Remember to enable mod_headers first by executing a2enmod headers.
  Now you should see these headers in the response:
X-Request-Received t=1286995673038485
X-Request-Processing-Time D=251

I used exactly the code above (with header defined in .htaccess) but get for example "525151" in the log and "262" in the header for the same request. In general there seems to be orders of magnitude in difference between the numbers
192.0.2.1 525151 - - [21/Aug/2011:14:19:53 +0200] "GET /images/site/slide-1.png HTTP/1.1" 262 423285 "http://example.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1"

vs.
X-Request-Processing-Time:D=262
X-Request-Received:t=1313929193502879

How can I fix this?

A: Can you verify that your LogFormat name 'combined' matches what your CustomLog variable is using.  I tested this on OS X and aside from the minor difference you'd expect between reading the variable when writing back the headers and when logging (after sending all the data back to the client) they are very close:
/etc/apache2# grep LogF httpd.conf
    LogFormat "%h %l %u %t \"%r\" %>s %b %t %D" common

/etc/apache2# grep CustomL httpd.conf
    # a CustomLog directive (see below).
    CustomLog "/private/var/log/apache2/access_log" common

# wget -qqO /dev/null -S http://localhost/
...
  X-Request-Received: t=1314588821970347
  X-Request-Processing-Time: D=336

/private/var/log/apache2# tail access_log
::1 - - [28/Aug/2011:20:33:41 -0700] "GET / HTTP/1.0" 200 44 [28/Aug/2011:20:33:41 -0700] 587

A: I think your best bet might be to choose a 'proper' name for your custom LogFormat, rather than reuse/change the combined log format.
All else aside (and as suggested by @polynomial), it seems as though there is a gap between the config you show, and the output you show.
If only to make troubleshooting less ambiguous (currently, you don't know if the default combined (LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined) or your version is being used).
So I would first do something like:
LogFormat "%h %D %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" perf-combined
And then use perf-combined where it is needed.
Looking at the fairly wide differences between Header %D and AccessLog %D values in @polynomial's example, I would also wonder whether the two are actually representing two different points in the request processing:

*

*since the header value of %D is lower in all examples on this page, it might show the time it took to form the response headers, but not necessarily body

*the AccessLog value of %D might be the time to send the full response.

That's a complete guess though.

A: [This is a very old question, but worthy of a better answer for others who arrive here]
The HTTP header is necessarily generated before the content is delivered to the end user, so it excludes network delays.  The access_log entry on the other hand is written after the whole of the content is delivered to the end user, possibly over a slow network link, and it includes the time taken for that delivery.
Which figure is more useful to you depends on what you're trying to find out.  For your image URL, you're probably looking at end user performance, and network delays are probably most of the answer.
If you're debugging performance of dynamically generated content, you probably want to log the time excluding network delays.  LogFormat will let you log the content of a header with %{X-Request-Processing-Time}i - haven't tried it, but I expect that it'll work.


text:
Q: Get ratios with time shift in Google Cloud Monitoring I'm running a query which compares data to that from 7 days previously.  The query only shows if there is a difference.  It doesn't reflect if the difference is an increase or a decrease.
What I'm looking for is a centre 0 line with a line graph showing if the current data is an increase or a decrease on last week's data, (ideally) as a percentage.
fetch generic_node
| metric 'custom.googleapis.com/myCustomMetric'
| group_by 4h, [row_count: row_count()]
| {value [v_now: val()] ; time_shift 1w}
| join | div

A: What about:
fetch generic_node
| metric 'custom.googleapis.com/myCustomMetric'
| group_by [], [row_count: row_count()]
| {value [v_now: val()] ; time_shift 1w}
| join | div

Or
fetch generic_node
| metric 'custom.googleapis.com/myCustomMetric'
| group_by [], mean(val())
| {
    ident
  ;
    time_shift 1w
  }
| join | div

Docs:

*

*https://cloud.google.com/monitoring/mql/examples#qlx-ratio-ratio

*https://cloud.google.com/monitoring/mql/examples#qlx-union-over-time

A: Simply change the last table operation to sub:
fetch generic_node
| metric 'custom.googleapis.com/myCustomMetric'
| group_by 4h, [row_count: row_count()]
| {value [v_now: val()] ; time_shift 1w}
| join | sub

Note that after the join table operation, you get a time series table with two value columns - the first column for current data and the second for last week's data. A following arithmetic function(textual name for an arithmetic operator) acts as a table operation shortcut for generating a single value column by performing that arithmetic function on the two value columns.
div here means
| value div(val(0), val(1))

That's why you get a ratio. And sub means
| value sub(val(0), val(1))

where you can get the difference.
https://cloud.google.com/monitoring/mql/reference?hl=en#div-func
https://cloud.google.com/monitoring/mql/reference?hl=en#sub-func


text:
Q: Extra space after cross reference When I make a cross reference with \ref inside the paragraph, resultant chapter includes extra vertical space after the reference line.

When I make a \ref at the end of the paragraph, space between that paragraph and next paragraph becomes more than normal. So adding a cross reference adds extra vertical space in any case.

When I add multiple cross references in a paragraph, this makes this vertical space bigger. For example 4 reference makes that space 4 times bigger.

What would be the cause for this extra vertical space ?
You can find my example from following link https://www.overleaf.com/read/mvfqcpjxbcwx

A: the class file has
\def\thechapter{\vspace*{10pt} \arabic{chapter}

which makes no sense and forced 10pt space on the line after any line that references a chapter number (including tables as they use the form chapter.table.
Just delete the \vspace*{10pt}


text:
Q: Output from nested child to parent to grand-parent component in Angular Hi angular community !
My issue is that i am tried to fired the child output to say the gran parent that the child is open or close but the parent could also fired the child and output it same way, it a bit like that post plus the gran parent How to use @output to fire a boolean from child to parent
PS: Note that the child could be fired/hide from the parent and the gran parent..thanks for help and if it's not clear don't hesitate to ask me for details..
gran parent.html:

<my-daydetail [showMePartially]="showVar"(close)="isHidden = true" (open)="isHidden = false"></my-daydetail>

<app-pie-chart [minifiedMe]="showVar" ></app-pie-chart>

<app-fonctionnaly [minifiedMe]="showVar"  ></app-fonctionnaly>

parent.html:

  Informations sur le fonctionnement

Taux de fonctionnement sur la période

<app-my-verticalchart [showMePartially2]="showVar" (closed)="isHiddenn = true" (opened)="isHiddenn = false"></app-my-verticalchart>

parent.ts
@Input() showMePartially: boolean;
@Input() showMePartially2: boolean;
@Output() open: EventEmitter<any> = new EventEmitter();
@Output() close: EventEmitter<any> = new EventEmitter();
@Output() opened: EventEmitter<any> = new EventEmitter();
@Output() closed: EventEmitter<any> = new EventEmitter();

child.html

     <chart [options]="options" (load)="saveInstance($event.context)">

      </chart>

child.ts
 @Input() showMePartially2: boolean;


text:
Q: "gulp sass" command runs but nothing happens This is my gulpfile.js file;
'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
    return gulp.src('./sass/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./css'));
});

gulp.task('sass:watch', function () {
    gulp.watch('./sass/*.scss', ['sass']);
});

You can see my folders here:

I write some code in my main scss file and then run gulp sass command in the terminal. It looks like it works but nothing changes.

A: For an explanation of partials, see partials and imports or sass language guide:

You can create partial Sass files that contain little snippets of CSS that you can include in other Sass files. This is a great way to modularize your CSS and help keep things easier to maintain. A partial is simply a Sass file named with a leading underscore. You might name it something like _partial.scss. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @import directive.

And sass partial tutorial.  In your case, remove the underscore before the main.scss filename and it will work as you expect.  Into your main.scss you will import other partial files (with leading underscores).

A: i dont think you need the './' in your src directory or destination directory,  should look like this.
gulp.task('sass', function () {
return gulp.src('sass/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('css'));
});


text:
Q: XML Namespace exception I have searched on stackoverflow for similar problems but I could not understand the reason of exception in my file. I have a DTO of customer which has following customer-servlet.xml
    <?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-2.5.xsd
         http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/util/ http://www.springframework.org/schema/util/spring-util.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.utd.controller" />
    <bean id="jspViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties"></bean>
    <bean id="dataSource"
          class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
          p:password="${jdbc.password}"></bean>
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <bean id="customerDao" class="com.utd.dao.CustomerDaoImpl"></bean>
    <bean id="customerManager" class="com.utd.service.CustomerManagerImpl"></bean>
    <tx:annotation-driven />
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
</beans>

I am getting following exception in tomcat logs:
27-Nov-2018 00:48:13.919 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
27-Nov-2018 00:48:14.378 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
 org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 55 in XML document from ServletContext resource [/WEB-INF/customer-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 55; columnNumber: 29; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4643)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5109)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)

Can you help me to understand why I am getting this exception and how can I resolve it?

A: Change http://www.springframework.org/schema/mvc/spring-mvc.xsd to http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd by specifying version and it should work.
for tx and other schema also change like this.
Refer this thread


text:
Q: How to deallocate memory I have a void function which I call in the main and I want it to use a new value for pi each time is called, and not adding them. I thing I should deallocate the memory for the array of type Dir, but I can't figure it out. The implementation is as follows:
void throwSeries(int n)
{
   double pi;
   double faults;
   double numCicle;
   Dir c[n];

   int count = 0;
   for (int i = 0; i < n; i++)
   {
       c[i] = someFun();   // Returns type Dir
       if (below(c[i]))
       {
           numCicle++;
       }
   }
   pi = 4 * (numCicle / (double) n);
   faults = ((pi - M_PI) / M_PI) * 100;

   cout << setw(15) << setfill(' ') << n;
   cout << fixed << setprecision(5);
   cout<< setw(15)<< setfill(' ')  << pi << setw(15)<< setfill(' ') ;

   cout << fixed << setprecision(1);
   cout << faults << endl;
}

int main()
{
   system("CLS");
   srand(time(0));

   cout << setw(15) << "n" << setw(15) << "pi" << setw(15) << "faults" << endl;
   cout << setw(15) << setfill('-') << "|"<< setw(15) << setfill('-') << "|";
   cout << "--------------" << endl;

   int n = 0;
   for (int i = 0; i < 100; i++)
   {
       n += 100;
       throwSeries(n);
   }

   return 0;
}

A print out example is as follows:
              n             pi     Rel. fault
--------------|--------------|--------------
            100        3.12000           -0.7
            200        4.66000           48.3
            300        6.28000           99.9
            400        7.80000          148.3
            500        9.40000          199.2
            600       10.76000          242.5

And the values of pi shouldn't be added in each iteration.

A: You have to initialize numCicle before adding something to that.
In other words,
   double numCicle;

should be
   double numCicle = 0;


text:
Q: Parsing JSON Object - Angularjs + PHP I'm working on some CRUD operations for an Angular app that communicates with a PHP API on the server. I'm very new to PHP so I'm have trouble parsing what I send to the delete.php when I want to delete an entry in the database. When I send the record's id in the Data properties of the request it brings the name with the value, so Data contains 'id=1', for example.
On the PHP end I went off an example that used $_Post['id'] to get the condition for doing the deleting but from what I can tell that doesn't work because of the fact I'm sending a file that doesn't match that name. I know there are ways to encode to JSON or otherwise get the value on the PHP end but I tried it and whatever mess I made of it it deletes the entire table rather than the entry I want to specify..!
How should I go about collecting the data and parsing it so that it can fit into the delete() function?
In the App.js:
    $http({
       method: 'POST',
       url: 'http://localhost:8080/sns/delete.php',
       data: {id: user.id}
    }).success(function(response){
        if(response.status == 'OK'){
                var index = $scope.users.indexOf(user);
                $scope.users.splice(index,1);
        }
    });

delete.php:
<?php

include 'DB.php';

$db = new DB();
$tblName = 'members';
            if(!empty($_POST['id'])){
                $condition = $_POST['id'];
                $delete = $db->delete($tblName,$condition);
                if($delete){
                    $data['status'] = 'OK';
                    $data['msg'] = 'User data has been deleted successfully.';
                }else{
                    $data['status'] = 'ERR';
                    $data['msg'] = 'Some problem occurred, please try again.';
                }
            }else{
                $data['status'] = 'ERR';
                $data['msg'] = 'POST id was, please try again.';
            }
            echo json_encode($data);
            exit;

A: try this and in then you should be able to call $_POST["id"] in your PHP script.

this should work for other request without any modification except the url and the data fields.

$http({
   method: 'POST',
   url: 'http://localhost:8080/sns/delete.php',
   data: {id: user.id},
   headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
   },
   transformRequest: function (data) {
       transformedData="";
       keys=Object.keys(data);values=Object.values(data);
       for (i in keys)
            transformedData+=keys[i]+"="+values[i]+"&";
       return transformedData;
 }
}).success(function(response){
    if(response.status == 'OK'){
            var index = $scope.users.indexOf(user);
            $scope.users.splice(index,1);
    }
});


text:
Q: BPEL Add-on I´m not sure if this is the right place to ask, however.....
I need help from someone who has experience in Modeling BPEL Diagrams. I´m thinking of writing an Add-on for a BPEL Modeling tool. I want to write some Add-on, which really is useful to the Business Analysts.  I´m playing around with the idea of simulating and testing the BPEL Diagrams. Is there something more useful.....what do you think of the idea to transform UML to BPEL (bottom up approach)....please give me some feedback

A: There are some opensource Graphical BPEL Editors like Eclipse BPEL Editor, it is better if you can improve and contribute to these tools rather than starting from the scratch.

A: Graphical modeling: good. WS-BPEL is XML, which is painstaking to write by hand at the best of times.  There is no standard graphical notation, though.
Simulation: I'm all in favor of simulation, but simulating what?  Performance?  Functionality?


text:
Q: How to create new VM using the existing VHD in the Azure Blob storage? I have taken a backup of my azure VM VHD to blob storage using copy blob feature some time back.Now the VM is not present.Now i want to create the new VM using the Backup VHD in the another storage account using Power shell.
How can i do that using powershell?

A: Before you can create a virtual machine you need to create a 'disk' over the blob copy.
This can be done using the Add-AzureDisk
Then you can create a Virtual Machine over an existing disk using New-AzureVMConfig and New-AzureVM, example of this has been published here  -
$vmI1 = New-AzureVMConfig -Name $machineName -InstanceSize Small -AvailabilitySetName 'RDGW' -DiskName 'MY-OS-Disk-Name' |
Add-AzureDataDisk -Import 'My-Data-Disk-0'  -LUN 0 |
Add-AzureDataDisk -Import 'My-Data-Disk-1' -LUN 1 |
Add-AzureEndpoint -Protocol tcp -LocalPort 443 -PublicPort 443 -Name 'HTTPs' |
Set-AzureSubnet $_subnetInternal, $_subnetDmz, $_subnetProtected

This creates the VM configuration which is then passed to New-AzureVM

A: BTW: it's possible to create VM from VHD blob using web interface.
On Virtual Machines tab you can switch to sub tab Images and create new image using vhd from blob.
Then it's possible to add new VM using existent vm image.

A: Using the Azure Portal, after uploading your blob as a "page blob", click All Services and search for Image. Click +Add then define your image, select the blob, and you're off!


text:
Q: Classifier which minimizes inaccuracy I recently interviewed for a machine learning job which involved very mathematically rigorous questions. This is one of them, which I'm still very confused about.
Question: Given a data generating distribution $\mathbb{P}(x,y)$ and a classifier $f(x)$, where $x$ is the observation and $y$ is the label, prove that the inaccuracy given by:
$$\mathbb{E}[\mathbb{1}(f(x) \neq y)]$$
is minimized by the classifier:
$$f^*(x) = \text{sign}\big(\mathbb{P}(y|x) - \frac{1}{2}\big)$$
where $\mathbb{1}(a \neq b)$ is $1$ when $a \neq b$ and $0$ otherwise, and $\text{sign}(a)$ gives the arithmetic sign of $a$, that is $+1$ or $-1$.

Now I have multiple concerns about this question which really confuse me:

*

*What is the meaning of this statement? What does it say on an intuitive level?

*What information does it give us about the classifier? Can this information be used to design a "practically good" classifier for the problem which can be learned from data?

*What is the use of this result? How does it relate to, say, designing a logistic regression classifier? I ask about logistic regression because there also we threshold our predicted probability at $0.5$.

A: To archive optimal accuracy (minimal inaccuracy) you would assign a label A to x whenever P(y|x) > 0.5 and label B whenever P(y|x) < 0.5.
In other words, P(y|x) together with threshold 0.5 is the optimal Bayes classifier.
This is equivalent to assign labels based on the sign P(y|x) - 0.5, as you simply project the probabilities of P(y|x) in [0, 1] to the interval [-0.5, +0.5]. The decision boundary in probability space, 0.5, becomes 0 in the projected space and thus you can check whether a sample lies on either side of the decision boundary by checking the sign of P(y|x) - 0.5.
I'm sure you can formulate this a lot more mathematically, but this is the intuition.


text:
Q: Python: When using compile() - how do I create find the classname & create it? I have an issue where I need to instantiate a class, but I'm not sure what the most optimal way to go about this is.
Imagine the following code:
# loadstuff.py

class LoadSomething:
    def load(self, filename):
        compiled = compile(open(filename).read(), filename, 'exec')

        # The part I am stuck on
        # How do I get the class name, and how do I instantiate it?
        # This is assuming the file name is the same as the class name, only starting with capital letter, and minus file extension
        module = compiled.  # instantiate class 'Printstuff'

        return module

loader = LoadSomething()
module = loader.load("printstuff.py")
module.printSomething()  # Should print "Something!"

# printstuff.py

class Printstuff:
    def printSomething(self):
        print("Something!")

I think the code (and thus the question) speaks mostly for itself, how do I return and instantiate a new class with compile(..) so that I can call its methods?

A: There is no need to manually compile. Use importlib.import_module() to dynamically import the module.
You can then use inspect.getmembers() together with the inspect.isclass() predicate to find all classes, including any that might match the module name:
import importlib
import inspect

class LoadSomething:
    def load(self, modulename):
        module = importlib.import_module(modulename)
        modname = modulename.rpartition('.')[-1]  # support packages too
        for clsname, cls in inspect.getmembers(module, inspect.isclass):
            if clsname == modname.title():
                return cls()

This returns an instance of the first class that has the same name as the module, titlecased.

A: The fundamental problem is that the code object (the thing you've used compile() to produce) can contain any Python code — e.g. it could define multiple classes.  As a result, you're going to have to specify how the file you're loading is supposed to indicate which class to use.
One option, for instance, would be to require it to define a class with a well-known name.  For instance:
codeobj = compile(open(filename).read(), filename, 'exec')
globs = {}
locs = {}
exec(codeobj, globs, locs)
cls = globs['Foobar']
obj = cls()

You could simplify this quite a bit by using execfile() instead of compile() and exec():
globals = {}
locals = {}
execfile(filename, globs, locs)
cls = globs['Foobar']
obj = cls()

It's quite easy to come up with more complex schemes as well.
FWIW, the reason to do this rather than use imp, importlib or __import__ is that the import-based options use the module system.  If this is for loading a plug-in, you probably don't want that, so execfile() et al are more appropriate.


text:
Q: Is there a difference running Ruby on Rails on Ubuntu locally vs Ubuntu on Virtual Machine? More or less - as in the topic. I'm planning to format my PC, currently I have dual-boot with Win 7/Ubuntu 16.04. For my daily job I'm working mainly with Windows software but have quite a lot of irregular breaks that I can spend on programming. To do it though, I have to save all the progress and restart the PC every time in order to boot Ubuntu which is a bit of a pain in the ass for me.
I would like to install Windows 10 with Ubuntu on virtual box. Is there any difference in how does Ubuntu behave on VM and locally? I would like to be sure that I won't have a problem with running PostgreSQL, connecting with github or deploying apps to servers. Is anyone using a similar combo?

A: There is no functional difference between running your environment on your PCs hardware, or as a virtual machine.
Your VM will have less CPU power and have less memory, but on modern computers that shouldnt be an issue.  As long as you set up the networking properly, you should have the same access to any networks your host PC has.


text:
Q: Coredata chained Relationship What is the best way to update or add data if relationships are chained.
I have my coredata designed like this:

I have 3 Entities

1) User To_Many Category
2) Category To_Many Item
3) Item To_One Category

User is required before adding a Category, and Category is required before adding an Item

A: Simple. Just set the to-one relationship, the corresponding inverse relationship will be set automatically by Core Data.
newItem.category = category
category.user = user

According to best practice, I am renaming the clumsy attribute names    itemCategory, categoryUser, categoryInUser to simply category, user,  categories respectively.


text:
Q: Find the area between functions $x^3=2y^2;x=0;y=-2$
Take the element of area parallel to the y axis:
  $$x^3=2y^2;x=0;y=-2$$

First, I isolated in terms of $y$,
$$y= \pm \sqrt{x^3\over2}
\\ = \pm{\sqrt2\over 2}x^{3 \over 2}$$
Since bounded by $y=-2$, consider the negative portion:
$$= -{\sqrt2\over 2}x^{3 \over 2}$$
and let
$$f(x)= -{\sqrt2\over 2}x^{3 \over 2}$$
$$g(x) = -2$$
since $f(x)$ and $g(x)$ intersect at $x=2$ and bound by $x=0$
So,
$$ \int_0^2 [-g(x) -f(x)]dx
\\ = \int_0^2 (2 + {\sqrt2\over 2}x^{3 \over 2} ) dx
\\ = 2x + {\sqrt2\over 5}x^{5 \over 2}\Bigg]^2_0
\\ = 4 + {\sqrt2\over 5}2^{5 \over 2}$$
However the answer i supposed to be $12\over 5$
And I do not understand what the question means by "The element of area parallel to y axis"

A: The area should be
$$\int^2_0[f(x)-g(x)]dx$$ as $f(x)\ge g(x)$ in the given interval.
So,$$\sqrt2\cdot2^{5/2} = 2^{1/2}2^{5/2} = 2^{3} = 8 \implies 4- \frac{8}{5} = \frac{12}{5}$$

A: $f(x)=-\frac{\sqrt2}{2}x^{\frac{3}{2}}$
When intersected with $g(x)=-2$ you get the point $x=2$ as you showed.
So the area between $x=0$ , $y=-2$ and $f(x)$ is the area of $x=0$, $y=2$ and $-f(x)$.
This area is the same as the area of $x=0$ , $x=2$ and $y=2$ minus the area of $-f(x)$ between $0$ and $2$.
So $A=4-\int{f(x)dx}=4-\frac{8}{5}=\frac{12}{5}$


text:
Q: GWT: Linkers and Codesplitting In GWT-land, what is the relationship between "linkers" and DFN code splitting? Why does a linker need to support codesplitting, and why do some linkers not support it? How do you choose which linker your app should use and what factors go into that decision?

A: The primary linker (there also are secondary linkers, but they're not involved here) is responsible for creating the *.js or *.html files that host the compiled JS code, and of course how to bootstrap/load them into the browser.
Once you know that, it becomes obvious that they have to explicitly support code-splitting.
For instance, the xs (cross-site) linker wraps the whole script in an anonymous function so it doesn't "pollute the global scope" (technique also known as the module pattern). It cannot then dynamically inject some other script into the page that would have access to its internals. The sso (single-script) linker has the same limitation.
The std (iframe) linker loads your app in a dynamically created iframe which serves as the sandbox: the iframe's global scope is not the host page's global scope. It can then dynamically inject a script inside the iframe that would have access to everything that's already there (the iframe's global scope).
But actually, you don't have to choose which linker your app should use: stick with the xsiframe (which you have to activate explicitly however, for the time being that is). It combines the cross-site friendliness of the xs linker with the iframe sandboxing of the std linker.
You can expect all other linkers (except maybe the sso one) to be deprecated in future GWT releases, and eventually be removed altogether; and the std linker to be replaced by the xsiframe linker as the default linker.


text:
Q: Invalid Command $n(0) in Tcl NS2 for {set i 0} {$i < $num_nodes} {incr i} {
    set a($i) [new Agent/MessagePassing/Flooding]
    $n($i) attach  $a($i) $MESSAGE_PORT
    $a($i) set messages_seen {}
}
set Consumer n(0)
set Producer n(5)
$ns attach $a(1) $consumer
$ns attach $n(5) $producer
$ns connect $consumer $producer

where a comes from the agent node.Please tell me anyone why this gives error in agent a(0) in this line:
$ns attach $a(1) $consumer


text:
Q: Why I am having error like this? I use datatables jquery plugin I am using for css
and for datatables
Please help me in my problem I want to implement table sorting. Thanks!
I am having error like this.

Full Code:
    <!DOCTYPE HTML>

    <meta charset="utf-8">

    <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">

    <link href="https://github.com/DataTables/DataTables/blob/master/media/css/jquery.dataTables.css" rel="stylesheet" type="text/css">

A: https://github.com/DataTables/DataTables/blob/master/media/js/jquery.dataTables.js is an HTML document not a JavaScript file.
Github repositories are not CDNs. You need to check the code out (or follow the download link from the project homepage) and host it somewhere.


text:
Q: Move focus from Taskpane to Sheet with Excel Javascript API I am working on an Excel Add in using Excel Javascript API.
https://learn.microsoft.com/en-us/office/dev/add-ins/reference/overview/excel-add-ins-reference-overview
Is there a way to switch focus from taskpane to the sheet? Now if user clicks on an element on the taskpane she cannot use the the arrow keys to navigate the excel sheet until she has clicked the sheet area again with the mouse.
Use case
It would be nice to have a button on the taskpane that would paste text to a certain range on the sheet and would also move the focus to the sheet, so the user could start navigating with arrow keys immediately after pressing the button.
Pasting the text to the range and setting the selection are working fine, but I cannot find a way to move focus from the taskpane to the sheet with JS API.
Any help is very much appreciated,
Thank you!

A: The best what you could do is to try to Set the active worksheet:
await Excel.run(async (context) => {
    let sheet = context.workbook.worksheets.getItem("Sample");
    sheet.activate();
    sheet.load("name");

    await context.sync();
    console.log(`The active worksheet is "${sheet.name}"`);
});

If this isn't what you are looking for, I'd suggest you to file a feature request here: https://aka.ms/M365dev-suggestions .


text:
Q: Object oriented design: when to make an abstract class Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.

A: There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)

A: For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
    public abstract List<SoldProduct> FetchData();
    public bool UploadData(List<SoldProduct> productsSold)
    {
        // here you can do code to save data in common destination
    }
}

public class ExcelImporter : AbstractImporter
{
  public override List<SoldProduct> FetchData()
  {
  // here do code to get data from excel

  }
}

public class XMLImporter : AbstractImporter
{
  public override List<SoldProduct> FetchData()
  {
  // here do code to get data from XML

  }
}

public class AccessDataImporter : AbstractImporter
{
  public override List<SoldProduct> FetchData()
  {
  // here do code to get data from Access database

  }
}

and calling can be like this
    static class Program
    {

          static void Main()
          {
             List<SoldProduct> lstProducts;
             ExcelImporter excelImp = new ExcelImporter();
             lstProducts = excelImp.FetchData();
             excelImp.UploadData(lstProducts);

             XMLImporter xmlImp = new XMLImporter ();
             lstProducts = xmlImp.FetchData();
             xmlImp.UploadData(lstProducts);

             AccessDataImporterxmlImp accImp = new AccessDataImporter();
             lstProducts = accImp .FetchData();
             accImp.UploadData(lstProducts);

          }
    }

So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.

A: In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post

A: As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.

A: Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."

A: This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.

A: The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.

A: Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably.  While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method.  Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }

[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations.  Unfortunately, I know of no plans to add any such functionality.


text:
Q: pointer vs double pointer for Linked List and Binary Tree
*

*For single linklist
1.1. This is what I saw from a tutorial, I only wrote the important part.
sortedInsert(Node **root, int key){};
int main(){
    Node *root = &a;
    sortedInsert(&root, 4);
}

1.2. However I just used pointer rather than double pointer, and everything works fine, I can insert the key successfully.
sortedInsert(Node *root, int key){};
int main(){
    Node *root = &a;
    sortedInsert(root, 4);
}

*For binary Tree
2.1. From tutorial(double pointer)
    void insert_Tree(Tree **root, int key){
    }

    int main(){
        Tree *root = NULL;
        insert_Tree(&root, 10);
    }

2.2. what I did is below, and I failed to insert the key, when I checked the node after insertion, the node is still null.(single pointer)
    void insert_Tree(Tree *root, int key){
        if(root == NULL){
        root = (Tree *)malloc(sizeof(Tree));
        root->val = key;
        root->left = NULL;
        root->right = NULL;
        cout<<"insert data "<<key<<endl;
    }else if(key< root->val){
        insert_Tree(root->left, key);
        cout<<"go left"<<endl;
    }else{
        insert_Tree(root->right, key);
        cout<<"go right"<<endl;
    }
    }
    int main(){
        Tree *root = NULL;
        insert_Tree(root, 10);
    }

I have a few questions
1).  which is right, 1.1/2.1 double pointer or 1.2/2.2 single pointer? Please explain in detail, it could be better if you can show an example, I think both of them are right.
2). Why did I insert key successfully in the linkedlist with single pointer, however I failed in the tree insertion with single pointer?
Thanks very much, I appreciate everyone's help.

A: I suspect you were lucky with your linked list test. Try inserting something at the head of the list.
To expand on that...
main() has a pointer to the head of the list which it passes by value into your version of sortedInsert(). If sortedInsert() inserts into the middle or end of the list then no problem, the head is not changed and when it returns to main() the head is the same. However, if your version of sortedInsert() has to insert a new head, fine it can do that, but how does it return the information about the new head back to main()? It can't, when it returns to main() main will still be pointing at the old head.
Passing a pointer to main()'s copy of the head pointer allows sortedInsert() to change its value if it has to.

A: both your approaches are correct.But where you used a single pointer ,your head pointer isn't being updated.All you need to do is return the new head by writing 'return head;' at the end of your function,


text:
Q: Library for build objects from key/value pairs After writing another boilerplate builder for a class from IDictionary<string, string> I'm looking for some library that does it in declarative style.  Here is an example of what I want.  Could you suggest any libs that allow to do this?
class Person
{
    string Name;
    int Age;
}

class PersonBuilder
{
    public Person Build(IDictionary<string, string> values)
    {
        // MagicBuilder is what I'm looking for
        var magicBuilder = new MagicBuilder<Person>();
        // MagicBuilder.AddRequiredField<Type>(key, field)
        magicBuilder.AddRequiredField<string>("name", p => p.Name);
        // MagicBuilder.AddOptionalField<Type>(key, field, defaultValue)
        magicBuilder.AddOptionalField<int>("age", p => p.Age, 0);
        return magicBuilder.Build(values);
    }
}


text:
Q: Cannot access mongo-express started on Docker I went through all the possible articles about this problem on StackOverflow and Github and none of the solutions works, that's why I decided to post another question.
I've setup mongo with mongo-express on docker-compose and when I run it everything seems good except that when I try it through web browser it says ERR_EMPTY_RESPONSE
Docker-compose:
version: '3.1'
services:
  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    depends_on:
      - "mongo"
    ports:
      - "8081:8081"
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_SERVER: mongo

Logs from docker mongo-express:
Welcome to mongo-express
------------------------

(node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Mongo Express server listening at http://0.0.0.0:8081
Server is open to allow connections from anyone (0.0.0.0)
basicAuth credentials are "admin:pass", it is recommended you change this in your config.js!

Docker ps:
CONTAINER ID   IMAGE           COMMAND                  CREATED              STATUS              PORTS                      NAMES
a97ae1a348c6   mongo-express   "tini -- /docker-ent…"   About a minute ago   Up About a minute   0.0.0.0:8081->8081/tcp     docker-compose-mongo-express-1
d645863a90de   mongo           "docker-entrypoint.s…"   2 hours ago          Up About a minute   0.0.0.0:27017->27017/tcp   docker-compose-mongo-1

I tried also as it was suggested on other posts to run mongo-express on 0.54.0 image version. Below is the result:
Mongo Express server listening at http://0.0.0.0:8081
Server is open to allow connections from anyone (0.0.0.0)
basicAuth credentials are "admin:pass", it is recommended you change this in your config.js!
Database connected
Admin Database connected
unable to list databases
Error [MongoError]: Unsupported OP_QUERY command: listDatabases. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal
    at Function.MongoError.create (/node_modules/mongodb-core/lib/error.js:31:11)
    at /node_modules/mongodb-core/lib/connection/pool.js:483:72
    at authenticateStragglers (/node_modules/mongodb-core/lib/connection/pool.js:429:16)
    at Connection.messageHandler (/node_modules/mongodb-core/lib/connection/pool.js:463:5)
    at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:319:22)
    at Socket.emit (events.js:314:20)
    at addChunk (_stream_readable.js:297:12)
    at readableAddChunk (_stream_readable.js:272:9)
    at Socket.Readable.push (_stream_readable.js:213:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
  ok: 0,
  errmsg: 'Unsupported OP_QUERY command: listDatabases. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal',
  code: 352,
  codeName: 'UnsupportedOpQueryCommand'
}

All looks good, except of I can't access mongo-express from outside docker container.
Do you have any other ideas what might be wrong?

A: I suggest you

*

*Add tags :latst (:wanted_version) to your docker images

*Add a wait for script https://github.com/eficode/wait-for

*Add a netword that contains both containers together