text:
Q: How to stop elements in list from changing? I'm not really sure what is going on here. But the elements in my list keep changing.
table._row_gen is a generator instance, and it creates the rows for my table. Source is here.
It returns a dict; I can also get the dict directly from table._row_gen.stats.
def test_append(self):
        start_stats = {'step':250,'offset':13,'inc':113,'danger':0,'input':None}
        gen = StatGenerator(start_stats)
        table = PathTable(gen)

        stats_list = []

        for i in xrange(50):
            stats_list.append(table._row_gen.stats)
            print stats_list[i]
            table._row_gen.next()

        assert stats_list[0]['step'] == 250

This should build a list of rows to stats_list.
The print works fine and displays the correct output:
{'danger': 0, 'input': None, 'step': 250, 'inc': 113, 'offset': 13}
{'enc': False, 'danger': 113, 'rnd': 216, 'step': 252, 'limit': 55552, 'offset': 13, 'inpu
{'enc': False, 'danger': 226, 'rnd': 163, 'step': 254, 'limit': 41984, 'offset': 13, 'inpu
{'enc': False, 'danger': 339, 'rnd': 151, 'step': 0, 'limit': 38912, 'offset': 26, 'input'
{'enc': False, 'danger': 452, 'rnd': 212, 'step': 2, 'limit': 54528, 'offset': 26, 'input'
{'enc': False, 'danger': 565, 'rnd': 64, 'step': 4, 'limit': 16640, 'offset': 26, 'input'

But the list is malformed, and the assert fails:
>           assert stats_list[0]['step'] == 250
E           assert 94 == 250

test_int_path_table.py:47: AssertionError

After the loop:
print stats_list[0]
{'enc': True, 'danger': 5650, 'rnd': 6, 'step': 94, 'limit': 1792, 'offset': 26, 'input':

94 should the last row. Yet all of the rows are reporting to be the same:
print stats_list[0] is stats_list[48]
True

I don't really understand why this is happening, and I would like the list to be correct (like the print output).

A: The simple solution is to make a copy. For this, you can do
def test_append(self):
        start_stats = {'step':250,'offset':13,'inc':113,'danger':0,'input':None}
        gen = StatGenerator(start_stats)
        table = PathTable(gen)

        stats_list = []

        for i in xrange(50):
            stats_list.append(table._row_gen.stats.copy()) # <=== the copy call makes a new copy and solves your problem.
            print stats_list[i]
            table._row_gen.next()

        assert stats_list[0]['step'] == 250

Also, the next call at the end of the for block is extraneous. It can be combined using
def test_append(self):
        start_stats = {'step':250,'offset':13,'inc':113,'danger':0,'input':None}
        gen = StatGenerator(start_stats)
        table = PathTable(gen)

        stats_list = []

        for i in xrange(50):
            stats_list.append(next(table._row_gen).copy())
            print stats_list[i]

        assert stats_list[0]['step'] == 250

If you're in control of the pastebin code, the stats property should return a defensive copy.
    @property
    def stats(self):
            return self._stats.copy()

and the next method should return a defensive copy too.
    def next(self):
            ''' Generates and returns stats. '''
            row = self._stats
            row['step'] = self._genStepId(self._stats['step'])
            row['offset'] = self._genOffset(self._stats['offset'], self._stats['step'])
            row['danger'] = self._genDanger(self._stats['danger'], self.stats['inc'])
            row['rnd'] = self._genRnd(self.rnlut[self._stats['step']], self._stats['offset'])
            row['limit'] = self._genDangerLimit(self._stats['rnd'])
            row['enc'] = self._genEnc(self._stats['danger'], self._stats['limit'])

            return self.stats

If you do the above two blocks, the copy in the first two is no longer necessary.


text:
Q: Type inference with Generics in Swift I have this code
func getMeGoodies<T>(String:goodieName, callback:(goodie:T) -> ()) {
   var goodie:T = //get it from the jug
   callback(goodie)
}

And somewhere I want to call this
self.getMeGoodies("chocolatechip", callback: { (goodie) -> () in
            println("eat the \(goodie)")
        })

I am getting an error at the string "chocolatechip" saying it can't convert (blah blah). I believe it is not able to figure it out what T is because it works when I return the goodie from the function and assign it to a variable when calling it (or simply do a casting)
var chocolateChip:Goodie =  self.getMeGoodies("chocolatechip", callback: { (goodie) -> () in
            println("eat the \(goodie)")
        })

or
self.getMeGoodies("chocolatechip", callback: { (goodie) -> () in
            println("eat the \(goodie)")
        }) as Goodie

Is there any way I can let swift know what type it is without the sorta hacky way of doing it.

A: If you add a type annotation to the closure parameter then
the compiler can infer the generic type T:
self.getMeGoodies("chocolatechip", callback: { (goodie : Goodie) -> () in
    println("eat the \(goodie)")
})

Another method is to pass the type as an argument to the method:
func getMeGoodies<T>(type : T.Type, goodieName : String, callback:(goodie:T) -> ()) {
    var goodie:T = 0 //get it from the jug
    callback(goodie: goodie)
}

self.getMeGoodies(Goodie.self, goodieName: "chocolatechip", callback: { (goodie)  in
    println("eat the \(goodie)")
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pin app terminated abnormally due to signal 6 I am trying to use Pin tool and loopprof to instruments my cluster using MPI, but pin terminated  abnormally due to signal 6 with this error:
A: Source/pin/pin/image.cpp: IMG_Type: 374: The img passed to IMG_Type() is stale
####################################################
## STACK TRACE
####################################################
addr2line -C -f -e "loopprof" 0x2b5b678a02c9 0x2b5b678a10b6
??
??:0
??
??:0
??
??:0
??
??:0
??
??:0
??
??:0
??
??:0
Pin 2.14
Copyright (c) 2003-2015, Intel Corporation. All rights reserved.
@CHARM-VERSION: $Rev: 71293 $
@CHARM-BUILDER: BUILDER
@CHARM-COMPILER: gcc 4.4.7
@CHARM-TARGET: ia32e
@CHARM-CFLAGS:  __OPTIMIZE__=1  __NO_INLINE__=__NO_INLINE__
Pin app terminated abnormally due to signal 6.

Can anybody help me to fix this error??


text:
Q: Modify username in ssh When ssh into my home router, I use the admin credentials provided by my isp. How do I list all users along with their details (group/privilege) and as the superuser how do I modify their (and my) username?

A: Username is nothing more than two things:

*

*a record in /etc/passwd file

*a record in /etc/shadow file (if your system uses it)

When talking about routers, most of them do not use /etc/shadow, so to rename a user you have to change it in the file /etc/passwd and here you go. Use sed for it.
Changing root username doesn't look like a good idea - there could be software with hardcoded root username, for sure.


text:
Q: How can I get two UL's in table-cell-formatted DIV's to be flush against the top?

jQuery(function() {
  jQuery(".collection").sortable({});

  jQuery('li', jQuery('.collection')).draggable({
    'connectToSortable': '.collection',
    'cancel': 'a.ui-icon',
    'revert': 'invalid',
    'containment': 'document',
    'cursor': 'move'
  });
});
body {
  background-color: silver;
  font-family: Verdana, Georgia;
}

div.main {
  margin-left: auto;
  margin-right: auto;
  width: 740px;
}

div.table {
  display: table;
  width: 740px;
}

div.td {
  display: table-cell;
  margin-top: 0;
  width: 50%;
}

div.tr {
  display: table-row;
}

ul.collection {
  background-color: white;
  list-style: none;
  padding-left: 0;
  min-height: 100px;
  padding-left: 0;
  width: 200px;
}

ul.collection>li {}

ul#selection {
  right: 0;
}

ul#source {}

<!DOCTYPE html>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" type="text/css" href="/stylesheets/page.css" />

Everything

Nonfiction

Fiction

Poetry

This script is intended to make LI's draggable between two UL's. When this runs, the populated UL in the left table-cell-styled DIV is not flush up against the top of the table-styled DIV; it appears that its top is loosely (or exactly) aligned with the bottom of the empty table-cell to the right. The initial image, with a different background, is as follows:

If both UL's have at least one LI, then they are aligned flush towards the top as desired. If the last LI is dragged over, there can be a flicker effect. The desired flush appearance is:

I'd like to set things so that both UL's are at the top of what should be their simulated table-cell's whether they are populated or empty.

A: Vertically align the table-cells by using vertical-align: top on the div.td element. This will tell the table-cell to stick to the top.
See demo below:

jQuery(function() {
  jQuery(".collection").sortable({});

  jQuery('li', jQuery('.collection')).draggable({
    'connectToSortable': '.collection',
    'cancel': 'a.ui-icon',
    'revert': 'invalid',
    'containment': 'document',
    'cursor': 'move'
  });
});
body {
  background-color: silver;
  font-family: Verdana, Georgia;
}

div.main {
  margin-left: auto;
  margin-right: auto;
  width: 740px;
}

div.table {
  display: table;
  width: 740px;
}

div.td {
  display: table-cell;
  margin-top: 0;
  width: 50%;
  vertical-align: top;
}

div.tr {
  display: table-row;
}

ul.collection {
  background-color: white;
  list-style: none;
  padding-left: 0;
  min-height: 100px;
  padding-left: 0;
  width: 200px;
}

ul.collection>li {}

ul#selection {
  right: 0;
}

ul#source {}

<!DOCTYPE html>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" type="text/css" href="/stylesheets/page.css" />

Everything

Nonfiction

Fiction

Poetry


text:
Q: Using Get-Random after using Where-Object creates a null valued expression I'm trying to create a 10 character password that includes a mix of numbers, letters (uppercase and lowercase), and symbols.
Below is the script I am using in the function:
Function Get-TempPassword {

$TempPassword = $null

$ascii = $NULL;For ($a = 33;$a –le 126;$a++) {$ascii +=, ([char][byte]$a | Where-Object {$_ -notin "'",'`','|','_',"`;",'"',','})}

Do {$TempPassword += $ascii | Get-Random; $loop++}

Until ($loop -eq 11)

return $TempPassword

}
If I remove the following section:

| Where-Object {$_ -notin "'",'`','|','_',";",'"',','}

The creation of the password works fine albeit including the symbols I don't want included.
Having the Where-Object function causes the Get-Random function to only use the first 5 characters in the array, and therefore I don't get letters of any case type, or numbers, or any of the other symbols.
I've found that if I use $ascii[26] (being the 25th character in the array) I get a null value, however I would think this would allow any character up to this character to be used, or none at all, not just the first 5. The 25th character just so happens to be a ; (ascii value number 59). I tried adding the symbol to the Where-Object exclusion, and it was removed from the array, but the 25th character still showed as a null value.
I performed a reverse lookup of the ascii value [int[]][char[]] of each character either side of where the ; symbol would appear and it returned values 58 and 60, leading me to believe it was value 59 that was offending, but the symbol at this point should have been excluded.
Adding characters to the 'where-object' exclusion list should be removing them from the array, and it appears to, however running $ascii.Count shows 49 characters, regardless of whether I add or remove characters to the Where-Object exclusion list.
I have looked for information on the web and can't seem to find any, although it may be the search terms I'm using, as it's a bit of a complex case that not many would be reporting on.
Any help is appreciated.

A: Short version (best method for me):
$possible=36..38 + 40..43 + 45..58 + 60..94 + 97..123 + 125..126 + 33
(get-random -count 10 -input $possible | % {[char]$_}) -join ''

A: I didn't write this and i can't remember where i got it but i have built this into any scripts to create random secure Windows passwords, you can specify the length of the password returned by the param [int]$PasswordLength ( i have already set it to 10 ).
function New-SWRandomPassword {
    [CmdletBinding(DefaultParameterSetName='FixedLength',ConfirmImpact='None')]
    [OutputType([String])]
    Param
    (
        # Specifies minimum password length
        [Parameter(Mandatory=$false,
                   ParameterSetName='RandomLength')]
        [ValidateScript({$_ -gt 0})]
        [Alias('Min')]
        [int]$MinPasswordLength = 8,

        # Specifies maximum password length
        [Parameter(Mandatory=$false,
                   ParameterSetName='RandomLength')]
        [ValidateScript({
                if($_ -ge $MinPasswordLength){$true}
                else{Throw 'Max value cannot be lesser than min value.'}})]
        [Alias('Max')]
        [int]$MaxPasswordLength = 11,

        # Specifies a fixed password length
        [Parameter(Mandatory=$false,
                   ParameterSetName='FixedLength')]
        [ValidateRange(1,2147483647)]
        [int]$PasswordLength = 10,

        # Specifies an array of strings containing charactergroups from which the password will be generated.
        # At least one char from each group (string) will be used.
        [String[]]$InputStrings = @('abcdefghijkmnpqrstuvwxyz', 'ABCEFGHJKLMNPQRSTUVWXYZ', '23456789', '!"#%&'),

        # Specifies a string containing a character group from which the first character in the password will be generated.
        # Useful for systems which requires first char in password to be alphabetic.
        [String] $FirstChar,

        # Specifies number of passwords to generate.
        [ValidateRange(1,2147483647)]
        [int]$Count = 1
    )
    Begin {
        Function Get-Seed{
            # Generate a seed for randomization
            $RandomBytes = New-Object -TypeName 'System.Byte[]' 4
            $Random = New-Object -TypeName 'System.Security.Cryptography.RNGCryptoServiceProvider'
            $Random.GetBytes($RandomBytes)
            [BitConverter]::ToUInt32($RandomBytes, 0)
        }
    }
    Process {
        For($iteration = 1;$iteration -le $Count; $iteration++){
            $Password = @{}
            # Create char arrays containing groups of possible chars
            [char[][]]$CharGroups = $InputStrings

            # Create char array containing all chars
            $AllChars = $CharGroups | ForEach-Object {[Char[]]$_}

            # Set password length
            if($PSCmdlet.ParameterSetName -eq 'RandomLength')
            {
                if($MinPasswordLength -eq $MaxPasswordLength) {
                    # If password length is set, use set length
                    $PasswordLength = $MinPasswordLength
                }
                else {
                    # Otherwise randomize password length
                    $PasswordLength = ((Get-Seed) % ($MaxPasswordLength + 1 - $MinPasswordLength)) + $MinPasswordLength
                }
            }

            # If FirstChar is defined, randomize first char in password from that string.
            if($PSBoundParameters.ContainsKey('FirstChar')){
                $Password.Add(0,$FirstChar[((Get-Seed) % $FirstChar.Length)])
            }
            # Randomize one char from each group
            Foreach($Group in $CharGroups) {
                if($Password.Count -lt $PasswordLength) {
                    $Index = Get-Seed
                    While ($Password.ContainsKey($Index)){
                        $Index = Get-Seed
                    }
                    $Password.Add($Index,$Group[((Get-Seed) % $Group.Count)])
                }
            }

            # Fill out with chars from $AllChars
            for($i=$Password.Count;$i -lt $PasswordLength;$i++) {
                $Index = Get-Seed
                While ($Password.ContainsKey($Index)){
                    $Index = Get-Seed
                }
                $Password.Add($Index,$AllChars[((Get-Seed) % $AllChars.Count)])
            }
            Return $(-join ($Password.GetEnumerator() | Sort-Object -Property Name | Select-Object -ExpandProperty Value))
        }
    }
}

New-SWRandomPassword

EDIT:::
https://gallery.technet.microsoft.com/scriptcenter/Generate-a-random-and-5c879ed5
The script can be found here.

A: try Something like this :
Function random-password ($length = 10)
{
  $possible=36..38 + 40..43 + 45..58 + 60..94 + 97..123 + 125..126  + 33

  $password = get-random -count $length -input $possible |
            % -begin { $aa = $null } -process {$aa += [char]$_} -end {$aa}

  return $password
}

random-password

A: Using the following script seems to have worked exactly how I want.
I removed the comma (,) from after += on this line:
$ascii = $NULL;For ($a = 33;$a –le 126;$a++) {$ascii +=, ([char][byte]$a | Where-Object {$_ -notin "'",'`','|','_',";",'"',','})}
I created a blank array before the array is added to:
$ascii = @()
The full code block is below:
Function Get-TempPassword {

    $TempPassword = $null

    $ascii = @()
    For ($a = 33;$a –le 126; $a++) { $ascii += ([char][byte]$a | Where-Object { $_ -notin "'",'`','|','_',";",'"',',' }) }

    Do {$TempPassword += $ascii | Get-Random; $loop++}

    Until ($loop -eq 11)

    return $TempPassword
}

A: I have rectified my others propositions, but i propose an other method :)
Function random-password2 ($length = 10)
{

$Assembly = Add-Type -AssemblyName System.Web
$password = [System.Web.Security.Membership]::GeneratePassword(50, 2)

$possible=36..38 + 40..43 + 45..58 + 60..94 + 97..123 + 125..126 + 33
$newchar=[char](get-random -count 1 -input $possible)
$password=$password -replace "[`'|_;,]",  $newchar
$password.Substring(0, $length)

}

random-password2

A: Recursive method :
Function random-password ($length = 10)
{

$Assembly = Add-Type -AssemblyName System.Web
$password = [System.Web.Security.Membership]::GeneratePassword($length, 2)

$desablechar = "[``'|_;,`"]"

  if ($password -match $desablechar )
  {
    random-password $length
  }
  else
  {
    $password
  }
}

random-password


text:
Q: Cannot set constraints for image view First I'd like to stress that I've spent quite some time looking for an ansswer and maybe I haven't found one simply because I'm not really understanding how it's working.
I'm setting up a UI, but can't manage to move an imageview by modifying its constraints. Basically my problem is that modifying constraints doesn't seem to modify the image's position.
Here's my layout:
    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="geoensea.ensea.com.geoensea.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="80dp"
        android:layout_height="41dp"
        android:layout_marginBottom="60dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/button_send"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="326dp"
        android:layout_height="320dp"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:contentDescription="@string/map_rdc"
        android:src="@drawable/ic_two_men"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.541" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="165dp"
        android:layout_height="74dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/title"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

my main activity
    package geoensea.ensea.com.geoensea;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    LinearLayout mLinearLayout;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Image

            // Create a LinearLayout in which to add the ImageView
            mLinearLayout = new LinearLayout(this);

            // Instantiate an ImageView and define its properties
            ImageView i = new ImageView(this);
            i.setImageResource(R.drawable.ic_two_men);

            // set the ImageView bounds to match the Drawable's dimensions
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new Gallery.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            // Add the ImageView to the layout and set the layout as the content view
            mLinearLayout.addView(i);
            setContentView(mLinearLayout);

        //Button new activity

    }
}

The image is always in the left top corner of the layout:
Here is an image of the problem

A: You didn't actually said what is the problem but I see that your ImageView has horizontal bias declared. It wont work without start and end constraint specified.
<ImageView
    android:id="@+id/imageView"
    android:layout_width="326dp"
    android:layout_height="320dp"
    android:contentDescription="@string/map_rdc"
    android:src="@drawable/ic_two_men"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5" />

To clarify this code: You've specified start and end constraint for your view and also set it's width to given value. In such situation there are side margins (between scren edge and edge of your view). Android has to calculate them and it's doing this using vertical bias parameter (dafault set to 0.5). Horizontal bias is just ratio of left and right margin (0.5: margins are equal, 0: left margin is equal to 0, 1: right margin is equal to 0).
EDIT:
What did you want to get using this code in your onCreate method? Just do simple:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ID_OF_THE_XML_YOU'VE_PASTED);
}

Do you know that you didnt actually use your xml file? Everything you've seen on the screen was generated dynamically in your onCreate method!
Just to be 100% sure you understand everything. Your xml file (this one we've been discussing all the time) has it's name... eg activity_main.xml. In such case type:
setContentView(R.layout.activity_main)


text:
Q: Multiple clickable items in ListView inside android widget I'm trying to make ListView in a widget where there are multiple clickable items in each row. For example, if each row has data containing a link, one button in the row to open the link and another to share the link.
Sample code:
Widget layout
<LinearLayout...>

<TextView../>
<ListView with id="list_view" />

</LinearLayout>

Each list row in the ListView has:
<LinearLayout with id="listRowParent">

<TextView../>
<Button with id="openBtn"/>
<Button with id="shareBtn"/>

</LinearLayout>

I'm able to set onClick of each row using
remoteViews.setPendingIntentTemplate(R.id.list_view,
                    *<PendingIntent>*); //in onUpdate

and remoteView.setOnClickFillInIntent(R.id.openBtn, *fillIntent*); // in adapter
which works fine, but I can't have setPendingIntentTemplate for a list row button by doing remoteViews.setPendingIntentTemplate(R.id.shareBtn,
                        );
since nothing happens on clicking the button if I do this.
Question:
Is what I'm attempting possible? If yes, help is greatly appreciated :)

A: My bad. I should be using
remoteViews.setPendingIntentTemplate(R.id.list_view,
                    *<PendingIntent>*);

for both the buttons, but I was trying to use the button's ID directly in the second. Got fixed.


text:
Q: How to generate dataset for multi output keras model I followed the code examples for structured data classification at keras.io to build a model for classifying a rather simple model similar to the one in the example.
I wanted to extend the model to handle a second output, but I cannot use this model to train. The dataset is generated like it is done in the example (but with two results):
res1 = dataframe.pop("result1")
res2 = dataframe.pop("result2")
ds = tf.data.Dataset.from_tensor_slices((dict(dataframe),(res1,res2)))

The model is also similar to the example but using a two-dimensional output:
x = layers.Dense(32, activation="relu")(all_features)
x = layers.Dropout(0.5)(x)
output = layers.Dense(2, activation="sigmoid")(x)
model = keras.Model(all_inputs, output)
model.compile("adam", "binary_crossentropy", metrics=["accuracy"])

It compiles, but when i try to run fit...
model.fit(train_ds,epochs=30)

I get an error message:
ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1))

How can I prepare the dataset to meet the shape constraints?

A: I believe you should use the zip() function:
ds = tf.data.Dataset.from_tensor_slices((dict(dataframe),zip(res1,res2)))

This way, you are telling from_tensor_slices() to zip labels into a new array of shape (N, 2) instead of concatenating two vectors of shape (N, 1) into (2N, 1).


text:
Q: How do you handle laptop/mobile users of Exchange 2003? We are running Exchange 2003 Standard. While IMAP or OWA access is easy to provide for people who are never on site, we have difficulty administering access for those staff who have a laptop, and for example, work at home or on the road two days a week.
Is it possible to set up their Outlook client to connect directly to the Exchange when they are on-site, and swith co IMAP when they are off-site? How do you handle this kind of scenario?
I know Ex/Outlook 2K7 have provisions for this (using ActiveSync I think), but I was wondering what the best way to handle this using Ex2K3 was? Currently our only option is to limit them to OWA or to give them VPN access, neither of which are preferable.
Thanks
Matt

A: What you're looking for is "RPC over HTTP". We did this with Exchange 2003, and it worked well. The one caveat we ran into won't be problem for you, it seems you have to have unrestricted access to the Exchange servers to set it up; this was a problem for home desktop users but for a mobile workforce that's in the office at least once a week isn't a problem. That'll allow them to use the same access method (RPC over HTTP) both at home and in the office.
http://support.microsoft.com/kb/833401

A: Our "resolution" to this dilemma ... (Exch 2003, Outlook 2003):
1- ActiveSync is widely used here.  We have a bunch of iPhone users (including myself), and a number of other smartphones.
2- For company laptops we setup Outlook in "cached mode", and it connects to Exchange when the PC is connected to the network via VPN.  When not connected, they can still work in offline mode.
3- We do not allow home (i.e. non-company) PCs to connect to the network or to connect Outlook to Exchange.  If we haven't given you a laptop, then OWA or ActiveSync have to do. We don't want someone's mail in a PST/OST on a computer that we don't own.
4-  We tried to setup RPC over HTTP two years ago and failed.  We haven't tried since the "Outlook Anywhere" concept arrived.  We are going to look again this summer.  For security reasons, it won't be activated unless we can restrict the connection to domain computers.
To respond to your questions:

*

*You could open IMAP to the Exchange server from the internet, and have an Exchange account and an IMAP account configured in Outlook.  I would not do that .. the client configuration will be difficult to manage, the users will struggle, and although I don't know for sure it smells insecure.

*If you don't want VPN and must have Outlook then setup RPC over HTTP.  Those who use it love it, and apparently it is quite secure.  We never got it working, but we have an ISA proxy gateway, which was "best practice" when we implemented but has since fallen from favor.

*If possible, I would not allow non-company computers access to the network or to Exchange via Outlook, for the reason I noted above.

A: Another vote for Outlook Anywhere. Set up Outlook to work in cached mode and Outlook will seamlessly work when on the LAN and when on the road connecting through the Internet. If you're using SBS just run the Internet connection wizard to enable it. If you're using pukka Exchange 2003 it can be a bugger to set up. See http://www.ratsauce.co.uk/notablog/SettingupOutlookRPC.asp for my walkthrough.
JR

A: We use an SSL-VPN product from Sonicwall to provide VPN access to the LAN and then run the standard Outlook client.

A: I would give them Outlook Cached mode for when they are out of the office.

*

*VPN will be the primay way to dial in and they get full outlook functions.  Just tell them it will be slower.

*Put an internet short cut on their desktop for OWA, tell them if the VPN is not working, or Outlook is just too slow, then use the OWA link.
I have a place setup that doesn't even do number 1, they know when not in the office they are on OWA or a mobile device if they have been issued one.


text:
Q: Copy/publish images linked from the html files to another server and update the HTML files referencing them I am publishing content from a Drupal CMS to static HTML pages on another domain, hosted on a second server. Building the HTML files was simple (using PHP/MySQL to write the files).
I have a list of images referenced in my HTML, all of which exist below the /userfiles/ directory.
cat *.html | grep -oE [^\'\"]+userfiles[\/.*]*/[^\'\"] | sort | uniq

Which produces a list of files
http://my.server.com/userfiles/Another%20User1.jpg
http://my.server.com/userfiles/image/image%201.jpg
...

My next step is to copy these images across to the second server and translate the  tags in the html files.

I understand that sed is probably the tool I would need. E.g.:
sed 's/[^"]\+userfiles[\/image]\?\/\([^"]\+\)/\/images\/\1/g'

Should change http://my.server.com/userfiles/Another%20User1.jpg to /images/Another%20User1.jpg, but I cannot work out exactly how I would use the script. I.e. can I use it to update the files in place or do I need to juggle temporary files, etc. Then how can I ensure that the files are moved to the correct location on the second server

A: It's possible to use sed to change the file in-place using the -i option.
For your use it's up to you if it's easier/better to create a new file with the changes from the old, then copy to the 2nd domain using scp (or something similar).  Or it may be easier to copy the file first, then modify it once it's on the remote server (less management of new filenames this way).


text:
Q: Unsupported operand type in sum function of array I am a beginner in python and i am here confused why sum function isn't working on adding array elements here is the code below `from future
inc = 0
array = []
i=0
while True:
rating=input("Enter your rate between (1 to 5) ")
inc += 1
array.insert(inc,rating)
length = len(array)
print('total number of rating:',length)
ans = sum(array)
average = ans/length
print('avrage ratiing',round(average, 1))
while i<length:
     print(array)
     break`

please help
here is the traceback

A: Add int casting
rating = int(input("Enter your rate between (1 to 5) "))

When you get an input from the user, you get it as type of str.
In order to increment this number, you can cast it to int and than you can apply math operations.
In Addition:
You can add a functionality that checks that the user actually inserted a number by:
def get_number():
  try:
   return int(input("Enter your rate between (1 to 5) "))
  except ValueError:
   raise ValueError("That's not an integer, please insert an integer")

And than:
rating = get_number()

EDIT:
Notice that if you want to get input like '3.7' you should use float casting.
return float(input("Enter your rate between (1 to 5) "))

A: The sum function is, effectively, defined like so
def sum(iterable, start=0):
    total = start
    for item in iterable:
        total += item
    return total

Currently, your array is a list of strings, because that is what is returned by input, so the sum function tries to add a string item to an integer total giving the error
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The trick is to cast the string to an int
rating = int(input("Enter your rate between (1 to 5) "))


text:
Q: Change elements of beamer table step-by-step I have seen questions about how to add elements to a table in beamer step-by-step, but I am interested in changing existing elements of a table step-by-step. Here is a simple example:
\begin{frame}
\frametitle{Example}
\begin{table}
\centering
\begin{tabular}{c c c}
\toprule
H1 & H2 & H3\\
\midrule
1 & ? & 3 \\
2 & 4 & ?\\
\bottomrule
\end{tabular}
\end{table}
\end{frame}

For example, I would like the ? in the first row after the header to first appear as is, but then when I press the arrow to go to the next slide, it is in a \framebox{}, or has color, something like that.
Is there a way to do this with \onslide{}?
Thanks!

A: You can use \only. For example:
1 & \only<1>{?}\only<2>{somethingelse} & 3

The parameter in <> specify when it will be displayed. You can also use ranges:

*

*\only<1-3>{abc}: Display abc for the first 3 steps

*\only<2->{abc}: Display nothing on the first step, then display abc for each following step

A: like this?
\documentclass{beamer}

\usepackage{booktabs}
\usepackage{colortbl}

\begin{document}
\begin{frame}
\frametitle{Example}
\begin{table}
\centering
\begin{tabular}{c c c}
\toprule
H1 & H2 & H3\\
\midrule
1 & \only<2>{\cellcolor{blue!50}}? & 3 \\
2 & 4 & ?\\
\bottomrule
\end{tabular}
\end{table}
\end{frame}
\end{document}


text:
Q: The function should return a char from a list of binary, but I get "invalid literal for int() with base 2" def binToChar(b):

    a=','.join([str(i) for i in b])
    a = int(a, 2)
    if a < 26:
        return chr(ord('A')+a)
    elif a < 52:
        return chr(ord('a')+a-26)
    elif a < 62:
        return chr(ord('0')+a -52)
    else:
        if a == 62 :
            return "+"
        if a == 63:
            return "/"

print(binToChar([1,0,1,0,1,0]))

Traceback (most recent call last):
File "C:/Users/PycharmProjects/assignment1/venv/tester.py", line 46, in
print(binToChar([1,0,1,0,1,0]))
File "C:/Users/PycharmProjects/assignment1/venv/tester.py", line 23, in binToChar
a = int(a, 2)
ValueError: invalid literal for int() with base 2: '1,0,1,0,1,0'

A: The message tells you exactly what is wrong: "1,0,1,0,1,0" is not a valid number in base 2.  You want "101010" instead.
To do that, change
a=','.join([str(i) for i in b])

to
a=''.join([str(i) for i in b])


text:
Q: Dynamic import vue file in typescript recursive I tried to dynamically import a single file vue component in itself in typescript and got an error:
/Users/lilei/Desktop/designer-web/node_modules/fork-ts-checker-webpack-plugin/lib/service.js:22
        throw error;
        ^

RangeError: Maximum call stack size exceeded
    at getSymbolLinks (/Users/lilei/Desktop/designer-web/node_modules/typescript/lib/typescript.js:31794:32)
    at getDeclaredTypeOfTypeAlias (/Users/lilei/Desktop/designer-web/node_modules/typescript/lib/typescript.js:36457:25)

...

myComp.vue
<template>

    <my-comp v-if="someCondition"></my-comp>

</template>

I think there are some recursive tasks performed while TypeScript compiling and thrown an error. But I make sure the component won't nested itself infinity by controlling the someCondition in my logic. How to dynamic import .vue file recursively in TypeScript?
vue doc

A: You are including myComp inside myComp and you end up with an infinite recursion. (you end up with a StackOverlow ;).
One way to fix this is to name your component and use use the given name. There is no need to import your component again. Something like this.
 <template>

   <my-comp v-if="someCondition"></my-comp>

 </template>

And you should probably change Vue.extend to Vue.component.

A: Register the component to global and use it with the name.

A: I believe it was an issue with TypeScript, which has now been fixed.
Try updating if you're experiencing the issue.


text:
Q: R plot, use line thickness to convey relative importance of information I have 5 lines that represent different trajectories that vary in their likelihood. I'd like to change the relative thickness of the lines to convey the information about their likelihood. The likelihoods add up to 100% and I'd like the thickness of the lines to reflect that, here is some dummy data
attempt<-matrix(0,ncol=6,nrow=5, dimnames=list(c("Intermediate A",
    "Worst Case", "Intermediate B", "Best Case","Intermediate C"),
    c("likelihood",c(1:5))))

attempt[,1]<-c(0.2,0.10,0.30,0.25,0.15)
attempt[,2]<-c(rep(0,nrow(attempt)))
attempt[,3]<-c(0.1,0.2,0.15,0.06,0.15)
attempt[,4]<-c(0.2,0.4,0.2,0.10,0.3)
attempt[,5]<-c(0.3,0.6,0.25,0.18,0.4)
attempt[,6]<-c(0.4,0.8,0.3,0.21,0.5)

#want to plot these as lines that have varying thickness according to the
#likelihood in column 1

plot(0,0, xlim=c(1,5), ylim=c(0,1), xlab="years", ylab="probability of
extinction")
  lines(attempt[1,2:6], col="blue")
  lines(attempt[2,2:6], col="red")
  lines(attempt[3,2:6], col="brown")
  lines(attempt[4,2:6], col="green")
  lines(attempt[5,2:6], col="purple")

Most posts I've found point to overlapping lines (frequency) or varying the thickness of a single line over a different portion of the data, I want the reader to be able to judge which line is most likely (following the likelihood values in column 1) by the relative thickness of the lines.

A: plot(0,0, xlim=c(1,5), ylim=c(0,1), xlab="years", ylab="probability of
extinction")

lwd_mult <- 100

lines(attempt[1,2:6], col="blue", lwd=attempt[1, 1] * lwd_mult)
lines(attempt[2,2:6], col="red", lwd=attempt[2, 1] * lwd_mult)
lines(attempt[3,2:6], col="brown", lwd=attempt[3, 1] * lwd_mult)
lines(attempt[4,2:6], col="green", lwd=attempt[4, 1] * lwd_mult)
lines(attempt[5,2:6], col="purple", lwd=attempt[5, 1] * lwd_mult)

The lwd argument sets the relative thickness of the line and the lwd_mult parameter is used to visually scale the thickness.

A: Another option using tidyverse
library(tidyverse)

as.data.frame(attempt) %>%
  rownames_to_column()%>%
  gather(num, val, -likelihood, -rowname) %>%
  ggplot(aes(x = num, y = val, group = rowname, color = rowname, size = likelihood))+
  geom_line()

Created on 2018-08-16 by the reprex
package (v0.2.0).
First, we convert to a dataframe, next we change the row names to a column, then we gather the data into long format, lastly we plot the data. In aes we can tell ggplot that we want the color to be based on the row names and the size of the line to be based on the likelihood.


text:
Q: How to set the real time factor on gazebo to 1? I got a question regarding the timing in Gazebo and ROS.
I have a car robot (with velodyne vlp16 LiDAR) which uses Gazebo plugins and some ROS packages. I'm aiming to detect the position of obstacle by moving the car and i would like to synchronize ros and Gazebo namely simulation time and real time on Gazebo. I have read ros time is the same as simulation time when the use_sim_time parameter is enabled. Unfortunately it doesn't work. I also try to set it directly using the parameter <real_time_factor>1</real_time_factor> on my sdf.file but it doesn't work. By running Gazebo and ros i always have in Gazebo real time factor equal to 0,71. I guess it muss be normally equal to 1.
Any idee how to solve this Problem please?

A: The gazebo real time factor isn't just a property you can set and have it work. It's purpose it to tell you how fast the sim time is running relative to real time. The reason it doesn't get above .71 is because it can't keep up computationally. A known problem, especially with older versions of gazebo, is that it isn't super efficient.


text:
Q: Get current connections to MongoDB in Node.JS How do I get the current amount of connections to my MongoDB collection?

A: Run this query:
db.serverStatus().connections

Should return a response containing the current, available, and total created connections.
More info in the official documentation: https://docs.mongodb.com/manual/reference/command/serverStatus/#connections


text:
Q: how to override a one line with the other line using JCL Below is my query:

In the first picture the 0 is present in the first line, that zero needs to be added in the second line as shown in the second picture

A: Interactively using ISPF Edit place a M on line 000001 and an O on line 000002.   Although, its not in JCL.
Are you looking for a utility that can be run as a step in a batch job to do this automatically ?
IEBUPDTE is described here to do what you are describing in batch.  Unfortunately, given the lack of detail in the original post I can't really craft an example.


text:
Q: Tenant does not have a SPO license when updating user I've been using Microsoft Graph API to create users in Azure Active Directory, but when I try to update skills or schools I get error:
 PATCH https://graph.microsoft.com/v1.0/me
     {
        "skills": ["skills-value"]
     }

{
    "error": {
        "code": "BadRequest",
        "message": "Tenant does not have a SPO license.",
        "innerError": {
            "request-id": "804948b5-f087-4be8-bdf0-ab49dccf7efc",
            "date": "2018-04-14T17:55:52"
        }
    }
}

Also when I try to update for example businessPhones it's work fine, I get no errors.
 PATCH https://graph.microsoft.com/v1.0/me
{
    "businessPhones": ["businessPhones-value"],
}

HTTP/1.1 204 No Content

Any idea?

A: The Microsoft Graph is a front-end which intelligently wraps a suite of Microsoft and Office 365 APIs into a single endpoint. This includes free and paid services, and ultimately to access certain APIs you will need to have a subscription for the services which host the underlying API.
In this case, you are seeing that the skills attribute on the user is stored in SharePoint Online, and if you do not have a SharePoint license, you will not be able to use that property.
If you are simply looking for a way around this, you might look into storing and retrieving your skill information using Add custom data to resources using extensions which is stored in Azure AD and should be totally free to access.


text:
Q: Zillow scraper: Why I can't scrape full listing from Zillow search I am trying to explore zillow housing data for analysis. but I found the data I scraped from Zillow would be much less then listing.
there is one exmaple:
I try to pull house-for-sale listing on 35216:
https://www.zillow.com/birmingham-al-35216/?searchQueryState=%7B%22usersSearchTerm%22%3A%2235216%22%2C%22mapBounds%22%3A%7B%22west%22%3A-86.93997505787829%2C%22east%22%3A-86.62926796559313%2C%22south%22%3A33.33562772711966%2C%22north%22%3A33.51819716059094%7D%2C%22regionSelection%22%3A%5B%7B%22regionId%22%3A73386%2C%22regionType%22%3A7%7D%5D%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22ah%22%3A%7B%22value%22%3Atrue%7D%2C%22sort%22%3A%7B%22value%22%3A%22globalrelevanceex%22%7D%7D%2C%22isListVisible%22%3Atrue%2C%22mapZoom%22%3A13%2C%22pagination%22%3A%7B%7D%7D
we can see there are 76 records. and if I use google chrome extension: Zillow-to-excel , all 76 houses in listing can be scraped.
https://chrome.google.com/webstore/detail/zillow-to-excel/aecdekdgjlncaadbdiciepplaobhcjgi/related
But when I use Python with request to scrape zillow data, only 18-20 records could be scraped.
here is my code:
import requests
import json
from bs4 import BeautifulSoup as soup
import pandas as pd
import numpy as np

cnt=0
stop_check=0
ele=[]
url='https://www.zillow.com/birmingham-al-35216/'
headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6',
    'upgrade-insecure-requests': '1',
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
for i in range(1,2):
    params = {
    'searchQueryState':'{"pagination":{"currentPage":'+str(i)+'},"usersSearchTerm":"35216","mapBounds":{"west":-86.83314614582643,"east":-86.73781685417354,"south":33.32843303639682,"north":33.511017584543204},"regionSelection":[{"regionId":73386,"regionType":7}],"isMapVisible":true,"filterState":{"sort":{"value":"globalrelevanceex"},"ah":{"value":true}},"isListVisible":true,"mapZoom":13}'
    }
    page=requests.get(url, headers=headers,params=params,timeout=2)
    sp=soup(page.content, 'lxml')
    lst=sp.find_all('address',{'class':'list-card-addr'})
    ele.extend(lst)
    print(i, len(lst))
    if len(lst)==0:
        stop_check+=1
    if stop_check>=3:
        print('stop on three empty')

Headers and params comes from web using chrome develop tool. I also tried other search and found I only can scrape first 9-11 records on each pages.
I know there is a zillow API but it could be used for a general search like all houses in a zipcode. So I want to try web-scraping.
May I have some suggestions how to fix my code?
Thanks a lot!

A: You can try that
import requests
import json

url = 'https://www.zillow.com/search/GetSearchPageState.htm'

headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9',
    'upgrade-insecure-requests': '1',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}

houses = []
for page in range(1, 3):
    params = {
        "searchQueryState": json.dumps({
            "pagination": {"currentPage": page},
            "usersSearchTerm": "35216",
            "mapBounds": {
                "west": -86.97413567189196,
                "east": -86.57244804982165,
                "south": 33.346263857015515,
                "north": 33.48754107532057
            },
            "mapZoom": 12,
            "regionSelection": [
                {
                    "regionId": 73386, "regionType": 7
                }
            ],
            "isMapVisible": True,
            "filterState": {
                "isAllHomes": {
                    "value": True
                },
                "sortSelection": {
                    "value": "globalrelevanceex"
                }
            },
            "isListVisible": True
        }),
        "wants": json.dumps(
            {
                "cat1": ["listResults", "mapResults"],
                "cat2": ["total"]
            }
        ),
        "requestId": 3
    }

    # send request
    page = requests.get(url, headers=headers, params=params)

    # get json data
    json_data = page.json()

    # loop via data
    for house in json_data['cat1']['searchResults']['listResults']:
        houses.append(house)

# show data
print('Total houses - {}'.format(len(houses)))

# show info in houses
for house in houses:
    if 'brokerName' in house.keys():
        print('{}: {}'.format(house['brokerName'], house['price']))
    else:
        print('No broker: {}'.format(house['price']))

Total houses - 76
RealtySouth-MB-Crestline: $424,900
eXp Realty, LLC Central: $259,900
ARC Realty Mountain Brook: $849,000
Ray & Poynor Properties: $499,900
Hinge Realty: $1,550,000
...

P.S. do not forget to mark answer as correct if I help you :)


text:
Q: Recurrence relation complexity I just learned about recurrences and I just can't solve this problem. I have this recurrence relation:
$T(n)=k * T(n / k)$
$T(0)=1$,
where k is a constant number.
I tried drawing a recurrence tree or replacing for lower n-s but no success. I hope you can help me with an idea!

A: $$\begin{align}
T(n) &= k~T(k~n) \\
     &= k^2~T(k^2~n) \\
     &= k^3~T(k^3~n) \\
     & \vdots \\
     &= k^z~T(k^z~n) \\
\end{align}$$
So which $z$ to choose?  Let's make the base case be $T(1) = c$, so
$$k^z~n = 1$$
$$\log(k^z~n) = \log(1)$$
$$z~\log(k) + \log(n) = 0$$
$$z = -\frac{\log(n)}{\log(k)}$$
$$z = \log_k(n^{-1})$$
So we have
$$\begin{align}
T(n) &= k^{\log_k(n^{-1})} T(k^{\log_k(n^{-1})} ~ n) \\
     &= n^{-1} T(1) \\
     &= \frac{c}{n}
\end{align}$$
So as you can see, $T(n) = k~T(k~n)$ doesn't actually depend on $k$ at all.  Any $T$ that has this property for one $k$ will have it for any other $k$ (for $0 < k < 1$ anyway).
Unfortunately, since $T(n)$ is monotonically decreasing (as opposed to asymptotically increasing), this isn't a good problem to learn complexity with.

A: I assume that
only integer parameters are used,
so the correct recurrence is
$T(n)=k * T(\lfloor n / k \rfloor)
$.
Correcting DanielV's answer,
since
$\lfloor \lfloor n/k \rfloor /k \rfloor
=\lfloor n/k^2 \rfloor
$,
by induction
$T(n)=k^m * T(\lfloor n / k^m \rfloor)
$
for
$k^m \le n
$.
If $m$ is the smallest value
such that
$k^m > n$
(this is
$m > \log(n)/\log(k)$
or
$m = \lceil \log(n+1)/\log(k) \rceil$
),
then,
since
$T(0) = 1$,
$T(n)
=k^m
$.
Since
$\log(n+1)/\log(k)
\le m
<1+\log(n+1)/\log(k)
$,
$n+1
\le k^m
< k(n+1)
$.
Therefore
$n+1
\le T(n)
< k(n+1)
$,
so
$T(n)
=\Theta(n)
$.
Notice that,
for the upper bound of
$T(n)
= O(n)
$,
the constant hidden by the
$O(n)$
depends on $k$.
Since this does not depend on $n$,
this is OK.


text:
Q: Why is my node express route not found? I am trying to add a route to '/signup' in my node express app. The GET to '/' is working, but '/signup' gives a 404 not found.
index.js and signup.js are both in the root folder.
signup.hbs and index.hbs are both in my views folder.
index.js:
const express = require('express');
const engines = require('consolidate');
var signup = require('./signup');

const app = express();
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');

app.get('/', (req, res) => {
    res.render('index');
});

app.use('/signup', signup);

signup.js
var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
    res.render('signup', {text:"Send some text to template here"});
});

module.exports = router;

link in index.hbs (results in 404 not found):
Sign up

A: Modules in node.js are singletons by default, therefore loading a module more than once is unnecessary.
If you want to consider index.js as the file that will load express.js, consider exporting the express variable you have defined and importing index.js in signup.js.
index.js
const express = require('express');
const app = express();
...
module.exports{
    app
}

signup.js
const index = require('./index');
...
const router = index.app.Router();

Also, seems like your use of app.use is kinda off. You should provide a router, an express app or make your own middleware, while you are just sending a module (signup.js). You can read more about it here: https://expressjs.com/en/4x/api.html#middleware-callback-function-examples

A: var express = require('express');
var router = express.Router();

 router.post('/', function (req, res) {
   res.render('signup', {OCR:"OCR TEXT"});
 });

module.exports = router;

Server is not finding appropriate method call so it is sending your 404 page .
you have to use POST method on your route , If you are sending some data to server


text:
Q: Learning multivariable/vector calculus through guided discovery I am asking this question as a question similar to what has been asked previously for other topics as well as math in general. But I'd like to ask for text references specifically in the domain of multivariable/vector calculus.
So my question shares a similar spirit to other questions such as
Learning through guided discovery https://mathoverflow.net/questions/119621/learning-through-guided-discovery
Big list of guided discovery textbooks
Big list of "guided discovery" books
Are there any books that take a 'theorems as problems' approach?
https://mathoverflow.net/questions/12709/are-there-any-books-that-take-a-theorems-as-problems-approach
The discussions and responses on all those discussions are great, but they did not talk about anything for multivariable calculus.
I would greatly appreciate it if anyone could share any books they know that would fulfill some of the characteristics of a guided discovery text. Just to give a clearer sense of what kind of book I'm looking out for, the books
Excursions in Calculus
http://www.amazon.com/Excursions-Calculus-Continuous-Mathematical-Expositions/dp/0883853175
and
Excursions in Classical Analysis
www.maa.org/press/maa-reviews/excursions-in-classical-analysis
are great books which I've been looking for in the topic of single variable calculus, and have found them. I just hope that there exists something similar in multivariable calculus.
To start off the sharing and listing, I thought I would say that the book
Div, Curl and All That
www.amazon.com/Div-Grad-Curl-All-That/dp/0393925161
to be a possible candidate, but from what I've seen from it so far, it looks like it does not have the same level of mathematical rigor as what the other two textbooks have (for the topic single variable calculus that they address).
Thank you very much!

*

*I wanted to post up the links completely for all the other references, but I couldn't because my reputation isn't high enough. So pardon the incomplete links :p


text:
Q: For Each Loop using a second database table model in MVC view I have a cshtml view linked to a controller for a model for one table in my database, but I need to do a for each loop that references a second model for a second table. Since setting 2 models at the top of the page is not possible foreach (var row in model) wont work.
what I need is something like this
@model MVCapp.Models.COOKIE
@using MVCapp.Models;

@{
  ViewBag.Title = "Update";
  ;

  foreach (var row in IEnumerable<MVCapp.Models.COOKIE_JARS)
  {
     some code
  }
}

Update

Although that is not aloud because I'm using a type like a variable. So what I am asking is if there is a way to set type:IEnumerable<MVCapp.Models.COOKIE_JARS to a variable or a second model, Or if there is a completely alternative method to achieve this looping through a second database table that I am trying to attempt.

A: The best way to do this is to create a ViewModel, a class that will contain the information of both your models.
You view must never made any logic or get information from your database, this is the goal of the Controller.
So, the idea is that your controller will make the queries, and add the data into your ViewModel object that will then be sent to the View.
Example :
Your ViewModel:
public class CookieEatersViewModel
{
    public IEnumerable<Cookie> Cookies {get; set;}
    public IEnumerable<Monster> Monsters {get; set;}
}

Your View:
@model MVCApp.ViewModels.CookieEatersViewModel

Update

Use the informations from your ViewModel here

Your controller:
public ActionResult Index()
{
    CookieEatersViewModel cevm = new CookieEatersViewModel();
    cevm.Cookies = repo.GetCookies();
    cevm.Monsters = repo.GetMonsters();

    return View(vm);
}


text:
Q: How do I tell what my odbc driver connection information is? I am using the r package RODBC. I am wanting to connect to some tables that I made for my grad school program. I know the server number. I am wondering how I tell what my driver and actual database name. The schema that I am connecting to is IS521FA1B12 so I am wondering if that is it (select * from IS521FA1B12.tablename).
This is the code that R is wanting to me to use I think.
dbhandle <- odbcDriverConnect('driver={SQL Server};server=mysqlhost;database=mydbname;trusted_connection=true')


text:
Q: Suggestions for proximity analysis For a GIS assignment I have used raster analysis map overlays in ArcMap to find areas where, if legalised, cannabis dispensaries would be able to be located in London.
I have identified several small areas which are further than 1000ft from schools, nurseries, parks and playgrounds etc.
At present, many of the 'legal' locations seem to be near train stations, notably Paddington, Charing Cross and London Bridge - is there a way of quantifying this relationship?

A: Assuming that the train stations are point data, so you are trying to find a relationship between points and polygons.

*

*Near tool - works with points, lines, or polygons.  Can compare point/point, point/line, point/polygon, line/line, line/polygon, polygon/polygon.  This tool will add attributes to your feature class.  Here is the documentation, which covers everything you need to use the tool:  http://desktop.arcgis.com/en/arcmap/latest/tools/analysis-toolbox/near.htm

*If you do not want to modify your input data, use "Generate Near Table".  This works the same way as the near tool, but creates a stand alone table instead of adding attributes to your input data.  This tool also allows you to calculate distances from more than one feature class (i.e. distance to train stations and distance to atms).  Here is the documentation:  http://desktop.arcgis.com/en/arcmap/latest/tools/analysis-toolbox/generate-near-table.htm


text:
Q: how to change style of bootstrap tagsinput I have an input field with bootstrap tagsinput, the problem is when the tag is activated I don't have the box of the tag.
For example I have this :

And I want something like this :

showing that the tag python and java is activated with creating a little box.
I am using this style for my example :
 <style>

.bootstrap-tagsinput {
  background-color: #fff;
  border: 1px solid #ccc;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  display: inline-block;
  padding: 4px 6px;
  color: #555;
  vertical-align: middle;
  border-radius: 4px;
  max-width: 100%;
  line-height: 22px;
  cursor: text;
}
.bootstrap-tagsinput input {
  border: none;
  box-shadow: none;
  outline: none;
  background-color: transparent;
  padding: 0 6px;
  margin: 0;
  width: auto;
  max-width: inherit;
}
.bootstrap-tagsinput.form-control input::-moz-placeholder {
  color: rgb(170, 36, 36);
  opacity: 1;
}
.bootstrap-tagsinput.form-control input:-ms-input-placeholder {
  color: #777;
}
.bootstrap-tagsinput.form-control input::-webkit-input-placeholder {
  color: #777;
}
.bootstrap-tagsinput input:focus {
  border: none;
  box-shadow: none;
}
.bootstrap-tagsinput .tag {
  margin-right: 2px;
  color: black;
}
.bootstrap-tagsinput .tag [data-role="remove"] {
  margin-left: 8px;
  cursor: pointer;
}
.bootstrap-tagsinput .tag [data-role="remove"]:after {
  content: "x";
  padding: 0px 2px;
}
.bootstrap-tagsinput .tag [data-role="remove"]:hover {
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
}
.bootstrap-tagsinput .tag [data-role="remove"]:hover:active {
  box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}

</style>

A: I solved my problem by adding this :
.bootstrap-tagsinput .tag {
  background: gray;
  border: 1px solid black;
  padding: 0 6px;
  margin-right: 2px;
  color: white;
  border-radius: 4px;
}


text:
Q: Calling pointer to Array in C library from swift closure I find information that comes close, but doesn't quick go far enough in answering this question and am just hitting my head against the wall.
I have a C-based library that calling in Objective-C goes like this:
[access execute:@"string" completion:^(NSArray* results) {
            [self process:results];
            [access disconnect];
        }];

I'm after the contents of results, which is a variable multi-dimensional (array of arrays) chunk of data that can't be predicted ahead of time.
I have tried several things, including
access.execute("string") { (sqlArray:NSArray) -> Void in
            NSLog("something")
       }

but get a set of errors:

*

*Anonymous closure arguments cannot be used inside a closure that has explicit arguments

*Cannot convert value of type '(NSArray) -> Void' to expected argument type '(([AnyObject]!) -> Void)!'

I think I need an inout in there as well since I need the contents of the NSArray*. What am I missing? The bridging-header is set up and another call that only passes a Bool works great.
Thanks!


text:
Q: how to avoid concatenation in combo box I'm trying to design a simple windows form application.Where if I select a combobox which represents countries. then again if i select any country then in another combobox states of that country will come.Finally if we select one state then corresponding cities will come in another combobox.First time if I do my operation it is working fine .. But second time if I'm doing any modification then it is concatenating..
here is my code-
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedItem.ToString() == "INDIA")
    {
        string[] Country = { "Andhra Pradesh",
       "Karnataka","Maharashtra"};
        comboBox2.Items.AddRange(Country);
    }
    else if (comboBox1.SelectedItem.ToString() == "USA")
    {
        comboBox2.Items.AddRange(new string[] { "Alabama",
        "Alaska", "Arizona"});
    }
    else if (comboBox1.SelectedItem.ToString() == "CHAINA")
    {
        comboBox2.Items.AddRange(new string[] { "Beijing Municipality",
        "Tianjin Municipality", "Hebei Province"});
    }
}

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox2.SelectedItem.ToString() == "Andhra Pradesh")
    {
        comboBox3.Items.AddRange(new string[] { "Adilabad","Anantapur","Chittoor","Kakinada","Guntur","Hyderabad",            "Khammam","Kurnool","Medak","Nizamabad","Visakhapatnam","Warangal","Eluru"});
    }
    else if (comboBox2.SelectedItem.ToString() == "Karnataka")
    {
        comboBox3.Items.AddRange(new string[] { "Bengaluru Urban", "Bengaluru Rural", "Chikkaballapur", "Kolar", "Mysuru" });
    }
    else if (comboBox2.SelectedItem.ToString() == "Maharashtra")
    {
        comboBox3.Items.AddRange(new string[] { "Mumbai", "Pune", "Nagpur", "Thane", "Nashik" });
    }
    else if (comboBox2.SelectedItem.ToString() == "Alabama")
    {
        comboBox3.Items.AddRange(new string[] { "Margaret","Helena","Southside","Mountain Brook","Vestavia Hills"});
    }
    else if (comboBox2.SelectedItem.ToString() == "Alaska")
    {
        comboBox3.Items.AddRange(new string[] { "Anchorage", "Fairbanks", "Juneau", "Sitka", "Ketchikan" });
    }
    else if (comboBox2.SelectedItem.ToString() == "Arizona")
    {
        comboBox3.Items.AddRange(new string[] { "Apache Junction", "Avondale", "Benson", "Buckeye", "Bullhead City" });
    }
    else if (comboBox2.SelectedItem.ToString() == "Beijing Municipality")
    {
        comboBox3.Items.AddRange(new string[] { "Dongcheng", "Xicheng", "Chaoyang", "Fengtai ", "Miyun " });
    }
    else if (comboBox2.SelectedItem.ToString() == "Tianjin Municipality")
    {
        comboBox3.Items.AddRange(new string[] { "Heping", "Hedong", "Xiqing", "Nankai", "Beichen" });
    }
    else if (comboBox2.SelectedItem.ToString() == "Hebei Province")
    {
        comboBox3.Items.AddRange(new string[] { "Baoding", "Bazhou", "Chengde", "Handan", "Langfang" });
    }
}

Please suggest me guys what should I modify in my code ?

A: Since each time you select something from combobox1 (countries) or combobox2 (states) you want to "start over," you must first clear those secondary comboboxes on the appropriate events, such as:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    combobox2.Items.Clear();
    combobox3.Items.Clear();
    . . .
}

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    combobox3.Items.Clear();
    . . .
}

Also, it would be better to give your controls meaningful names. Rather than letting their keep their default generic names, give them names such as comboboxCountries, comboboxStates, comboBoxCities. This will make debugging easier.
Finally, it would be better to keep the list of places (countries, states and provinces, cities/towns) in a database or at least in some sort of separately maintained list. Putting them all willy-nilly in labyrinthine if blocks will end up making you go cross-eyed.


text:
Q: Google Sheets - Matching Company Names I have 2 databases, both have names of companies, but in different formats.  I have been able to do exact matching using vlookup. I want to extract companies that were written differently, but they are actually the same company and extract the data.
Below is a small part of the databases I have
Database 1

Column A
1-800-Flowers.com Inc
Abbott Laboratories (Abbott)
21st Century Fox America Inc (formerly News America Inc)

Column B
1234(data I need to grab)
4567
8910

Database 2

Column C
1-800 CONTACTS INC
1-800-FLOWERS.COM
ABBOTT LABORATORIES
TWENTY-FIRST CENTURY FOX INC

Column D
ABCD(DataI can ignore as the company doesn't exist in database 1)
EFGH (Data I need as it matches from Database 1)
IJK
LMNO

As you can see from the above databases, Database 1 matches Database 2's in similar words like
21st Century Fox America Inc vs Twenty-first Century Fox Inc
In my database 1, I have about 4000+ values, while in database 2, I have 10,000 values. Is there a code to compare similar words between both databases and extract the data I need from columns B and D?
I have tried query, but it doesn't work the way I wanted it to. This is my shareable link.
Currently, What I have done is to extract the words which are similar using REGEXTRACT to find a match between the strings like Century Fox in 21st Century Fox and Twenty-First Century Fox and attempted to match both data sets using query. However my query result comes up with NA when I write it like this
=query(E:E,"Select E where E contains '"&L2&"'",0 )

L2 being the cell that contains the string Century Fox

A: L2:
=ARRAYFORMULA(INDEX($E$2:$E$68,MATCH(MAX(ARRAY_CONSTRAIN(MMULT(LEN(IFERROR(VLOOKUP(SPLIT($E$2:$E$68," "),transpose(SPLIT(A2," ")),1,0))),ROW(A$1:A$7)^0),ROW(E68),7)),ARRAY_CONSTRAIN(MMULT(LEN(IFERROR(VLOOKUP(SPLIT($E$2:$E$68," "),transpose(SPLIT(A2," ")),1,0))),ROW(A$1:A$7)^0),ROW(E68),7),0)))
M2:
=ARRAYFORMULA(INDEX($E$2:$F$68,MATCH(MAX(ARRAY_CONSTRAIN(MMULT(LEN(IFERROR(VLOOKUP(SPLIT($E$2:$E$68," "),transpose(SPLIT(A2," ")),1,0))),ROW(A$1:A$7)^0),ROW(E68),7)),ARRAY_CONSTRAIN(MMULT(LEN(IFERROR(VLOOKUP(SPLIT($E$2:$E$68," "),transpose(SPLIT(A2," ")),1,0))),ROW(A$1:A$7)^0),ROW(E68),7),0),2))
N2:
=ARRAYFORMULA(TEXT(MAX(ARRAY_CONSTRAIN(MMULT(LEN(IFERROR(VLOOKUP(SPLIT($E$2:$E$68," "),transpose(SPLIT(A2," ")),1,0))),ROW(A$1:A$7)^0),ROW(E68),7))/LEN(A2),"0%"))
Drag fill down.
Notes:

*

*Formula is resource intensive. Apps Script might be a better choice.

*For the given sample, This formula works with a reasonable degree of precision.

*7 is the maximum number of  words per cell found in all of Column E( or Column C of database 2). This is hardcoded in the above formula. This should be found using a helper column. Z2:COUNTA (SPLIT(A2," ")) Drag fill down. And AA2: =MAX(Z2:Z)

*N column gives the degree of confidence in the VLOOKUP produced result. Preferably, Anything below 45% should be rechecked manually.

*How it works: All of E column (db2) is split by words and each of the word is looked upon in each entry of A column(db1). If a group of words are matched for multiple entries in E column, then the maximum of the length of matched words is taken and given as the possible match. A letter approach instead of a word approach may give better precision, but seems unnecessary in the given sample.


text:
Q: changing activities with a login screen if login is correct I have my main activity launch one view vs another view depending if a user is logged in or not. It checks if a user is logged in or not based on if some shared preferences are entered.
In my main I determine which view is shown with this code:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //check if user is logged in
        SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
        String prefName = myPrefs.getString("userName", null);
        String userID = myPrefs.getString("userID", null);

        if(prefName == null && userID == null ){

            setContentView(R.layout.activity_login);

        }

        else{
            setContentView(R.layout.activity_main);
        }

If I go to the login view the user enters their details and if their login is succesful I would like to go back to change activities to the normal R.layout.activity_main which I am having trouble figuring out how to do at the end of my async task:
public class ReadLogInJSON extends AsyncTask
<String, Void, String> {

    Context c;

    public ReadLogInJSON(Context context)
    {
         c = context;
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPostExecute(String result){

        //decode json here
        try{

            JSONObject json = new JSONObject(result);
            String status = json.getString("status");

            if(status.equals("no")){
                //toast logIN failed

                String message = "Log In Failed";
                Toast.makeText(c,  message, Toast.LENGTH_SHORT).show();

            }

            else{
                //get userName
                String userName = json.getString("userName");

                //get user ID
                String userID = json.getString("userID");

                //set preferences
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("userName",userName);
                editor.putString("userID",userID);
                editor.commit();

                //launch normal activity
                Intent i = new Intent(c, MainActivity.class);
                i.setClass(c, MainActivity.class);
                startActivity(i);

            }

        }
        catch(Exception e){

        }

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

A: I think your architecture should separate the log-in functionality from the welcome functionality by separating activities i.e. Login activity + Welcome activity. Before you decide which one to use create a Splash activity and check the persistent data SharedPreferences. This way you separate the modules and call each one as needed.


text:
Q: Sending a reply email using exchange web services - how to deal with the changeKey property For my code, I retrieve an unread message from exchange, do some processing based on that message, and then reply to the message with the results of the processing I did.
The problem that I'm having is that when I attempt to reply to the email I'm getting the below error on calling responseMessage.send() or responseMessage.sendAndSave():
The current ChangeKey is required for this operation.

Below is the code that I am running that is triggering this error:
public void replyToEmail(EmailMessage _emailMessage, String _reply)
    {

        String serviceManager = emailServerAddress = ConfigurationSettings.AppSettings["serviceManagerEmail"].Trim();
        ResponseMessage responseMessage = _emailMessage.CreateReply(true);
        responseMessage.BodyPrefix = _reply;

        String changekey = _emailMessage.Id.ChangeKey;

        if (!serviceManager.Equals(""))
        {
            responseMessage.CcRecipients.Add(new EmailAddress(serviceManager));
        }

        responseMessage.Send();
    }

I'm able to check the _emailMessage changeKey value via _emailMessage.id.Changekey and there is a value there, I would have expected that to be assigned to the responseMessage when _emailMessage.createReply() was call.  I'm unable to find a way to manually assign it.
I've been unable to find any references to this issue during searching, I was hoping someone

A: I ran into this problem with .Forward, after setting the message IsRead = true and saving that update back to the server. That changes the ChangeKey, so it's no longer valid.
Try doing _emailMessage.Load() to get the message from the server again, and the new ChangeKey.


text:
Q: A property set as private or without private keyword. What is the difference? I am setting the property of a class like that
public string Name { get; set; }

But i can also set the property like that
public string Name { get; private set; }

I want to know the difference between these? and what scope they have?

A: It means you cannot set this property from class instance. Only member of same class can set it. Hence for outsiders this property becomes read-only property.
class Foo
{
    public string Name1 { get; set; }

    public string Name2 { get; private set; }

    public string Name3 { get { return Name2; } set { Name2 = value; }
}

Then
Foo f = new Foo();

f.Name1 = ""; // No Error

f.Name2 = ""; // Error.

f.Name3 = ""; // No Error

Name3 will set value in Name2 but setting value in Name2 directly is not possible.

and what scope they have?

Since Name1 and Name3 property are public so they and their get and set methods are available everywhere.
Name3 is also public but its set is private so property and get method will be available everywhere. Set method scope is limited to class only (private access modifier has scope inside entity where it is defined).

A: For the case public string Name { get; private set; }
Using private set means that the property is ReadOnly from the outside. Its useful when  you have a read only property and don't want to explicitly declare the backing variable.
public string Name { get; private set; } it  is same as :
private string _Name;
public string Name
{
    get { return _Name; }
    private set { _Name = value; }
}

A: The first one will have Set and Get methods available out of your class. The second one will have a Get method available out of your class but the Set method will only be available within your class. This usually denotes read only behaviour.


text:
Q: Cannot do http-post in mongodb shell I am trying to use a shell script to save data to mongodb then send the same to elasticsearch for analysis.
Below is a psudo code in the shell script that illustrate the issue.
mongo $mongo_conn --eval "

// other javascritp code
db.collection.insertOne(insertData);
http_post_to_elasticsearch(url,insertData);

function http_post_to_elasticsearch(url,insertData){
    // which http_post() method can work here?
    // both fetch and xhr are undefined
    // tried installing npm install -g xmlhttprequest but 'require' is also undefined
}

Below are the functions that have tried but seem not to be supported
async function http_post(url = '', data = {}) {
    print('starting http_post()')
    // Default options are marked with *
    const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify(data) // body data type must match "Content-Type" header
    });
    return response.json(); // parses JSON response into native JavaScript objects
}

async function xhr_post(url = '', data = {}) {
    const xhr = require('xmlhttprequest').XMLHttpRequest;
    // const xhr = new XMLHttpRequest();
    // listen for `load` event
    xhr.onload = async () => {
        // print JSON response
        if (xhr.status >= 200 && xhr.status < 300) {
            // parse JSON
            const response = JSON.parse(xhr.responseText);
            printjson(response);
            // return response;
        }

    };

    // create a JSON object
    const json = data;

    // open request
    xhr.open('POST', url);

    // set `Content-Type` header
    xhr.setRequestHeader('Content-Type', 'application/json');

    // send rquest with JSON payload
    xhr.send(JSON.stringify(json));
}

A: mongo shell does not provide a browser nor a nodejs-compatible runtime.
You can look through the  server js tests to see if there is anything there that resembles an http client.
See also ReferenceError: require is not defined in MongoDB shell.


text:
Q: Possible to have multiple keys for a value in a Map? If not then how to do this? I'm trying to figure out if there is a way to have multiple keys for a value in a Map in javaScript. The documentation on Mozilla doesn't seem to suggest it so I'm not sure. An example is that I'm getting input from the user in the form of a string, and I want to match that string to the matching object with the same name. alexander is the name of one of these objects. However, I also want "alex" or maybe "ali" to be acceptable inputs. In the current form below, only "alexander" will match the alexander object. If it is not possible to do this with maps, I'd like to know what's a good way I can match user string input with object names that doesn't involve using a bunch of if statements (there may be some names that have dozens of nicknames).
var john = {
  age: 20
  wt: 185
  favFood: pizza
};

// alexander, wesley etc. all have the same fields, just different values

// Map (used to validate user input)
const personByKey = new Map([
  ["john", john],
  ["alexander", alexander] // I also want "alex" to be acceptable for alexander obj
  ["wesley", wesley]
]);

A: I suppose you want
const personByKey = new Map([
  ["john", john],
  ["alexander", alexander],
  ["alex", alexander],
  ["wesley", wesley]
]);

A: I think you'll need a master lookup dictionary with all of the possible nicknames that map to the key to use in the personByKey map.
let nicknameMap = {
  "alex": "alexander",
  "al": "alexander",
  "alexander": "alexander",
  "john": "john",
  "j-dog": "john"
   "al": "alexander",
}

var person = personByKey[nicknameMap["al"]];


text:
Q: Not able to receive mails in my mailbox I've configured Google apps (Google services) to my domain for access mails some thing like mail.mysite.com. I've configured successfully all the accounts include admin and users also.
But here the surprising thing is I cant able to receive any mails when i sent mails to admin@mysite.com. But I can able to send mails from the same account (admin@mysite.com)to any other email ids.
Anybody knows the reason? I'm working on the same thing from the week.

A: Contacting google's staff would be a smarter idea.

A: Check to see if:

*

*You are forwarding mail to
admin@mysite.com to someone else.
You may have done this while you
were setting up.

*You have a filter rule that does
something with mail sent to
admin@mysite.com
There is an option in Google Apps mail that lets you direct mail addressed to a nonexistent user to a catchall address. Try setting that up to see if mail to admin@mysite.com is being redirected for some reason.


text:
Q: Reverse Numeric Matrix by Row Using Rcpp, for a package that I am writing in R, I am trying to reverse a NumericMatrix, so that the last row now would become the first, and the first row would become the last, in other words, the relative row indexes would go from 1, 2, 3, ... n to n, n-1, n-2, .... 1
So, if I declare the following function:
NumericMatrix reverseByRow(NumericMatrix in){
  int r = in.nrow();
  NumericMatrix nw(r,in.ncol());
  for(int i = 0; i < r; i++){
    nw.row(i) = in.row(r-i-1);
  }
  return nw;
}

And I have an 'N x M' Numeric matrix called 'mid', which I am trying to reverse by row, via the following:
        cout << "Reversing1: " << mid(0,0) << endl;
        cout << "Reversing2: "<< mid(1,0) << endl;
        mid = reverseByRow(mid);
        cout << "Reversed1: " << mid(0,0) << endl;
        cout << "Reversed2: " << mid(1,0) << endl;

Why am I getting the following output, suggesting that nothing has changed...???
Reversing1: 2806
Reversing2: 7
Reversed1: 2806
Reversed2: 7

Surely I am missing something very obvious... ???

A: Here is a 'fixed' version with a suitable variable name:
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix reverseByRow(NumericMatrix inmat) {
  int r = inmat.nrow();
  NumericMatrix nw(r,inmat.ncol());
  for(int i = 0; i < r; i++){
    nw.row(i) = inmat.row(r-i-1);
  }
  return nw;
}

/*** R
M <- matrix(1:9, 3, 3)
M
reverseByRow(M)
*/

which works as expected:
R> sourceCpp("/tmp/nicholas.cpp")

R> M <- matrix(1:9, 3, 3)

R> M
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

R> reverseByRow(M)
     [,1] [,2] [,3]
[1,]    3    6    9
[2,]    2    5    8
[3,]    1    4    7
R>


text:
Q: Pine Script - 3 Take profits, 1 SL and 1 Trailing Stop Calculated by Price I have read a dozen posts and tried many things in TV, but I can't seem to understand how PineScript works regarding strategy exits. I have an indicator-calculated-Price for each Level I want to use as an Exit (1 stoploss, 3 take profits and a trailing stop )
here is an example of the first 4 levels:
if (strategy.position_size > 0)

strategy.exit( "SL" ,from_entry="Long" ,qty_percent = 100 , stop= STOP )

strategy.exit( "tp1" , from_entry="Long", qty_percent=10, limit= k_vol_upper  )

strategy.exit( "tp2" , from_entry="Long", qty_percent=50, limit= AF_midLevel  )

strategy.exit( "tp3" , from_entry="Long", qty_percent=50, limit=a_AF_level4   )

the problem is the take profit levels don't work, only the stoploss, that's unless I change the "stop" order from "exit" to "close", and put an event instead of a level, like so:
strategy.close( "SL" ,from_entry="Long" , qty_percent = 100, when= xxx  )

in which case I get closed out late... the price has gone trough the SL level and closed there, but at least it gets the TakeProfit levels to work, with the "stop=" they just don't, well sort off, exits seem the be executed only on closes above the levels, I see levels broken by wicks every where not executed by the strategy, entries and exits, only on closes.
The las thing is the Trailing stop, which should follow a Bollinger band once the price has reached tp2
Anyways, I believe the logics should be simple enough and once you've seen it, its a done deal, I wish there was a YouTube video explaining this but I've looked for it.