text:
Q: Sampling random sets of integers with bounded range How can we randomly sample a set $S$ of $k$ integers from the range $[1, n]$ such that:

*

*The set satisfies $\max(S) - \min(S) \leq w$.

*Each integer in $[1, n]$ has an equal chance of being in the set. If this is not possible, it should be as close as possible (minimizing the variance of probability).

*1 and 2 permitting, the method is as uniformly random as possible. That is, the maximum entropy distribution under constraints 1 and 2.
We have $k < w$.
Are there any efficient methods? Methods that have some bias but get close?


text:
Q: Better ways of building Microservices in Nodejs I'm into a very big project where we have already built some 50 to 70 Microservices in Nodejs. All these services imports some 5 to 10 core common modules. At this stage if there is any single line of change in common core module, we have to update,  build and deploy all the artifacts.  Is there any better way to handle this?
Thanks.

A: I agree with @skjagini core modules should be stable, they should truely be core. In general I advocate for sharing as little as possible between your microservices, they should be independently developed and deployable. They should not require deployment synchronisation where you need to co-ordinate deployments of all your microservices least you break something. If that is the issue you are finding you have yourself a distributed monolith not a microservice architecture.
I cant see any easy resolution to the issue you post. If common code does change then naturally any deployable unit that uses that common code needs to be rebuilt and redeployed. The only exception to this would be if the change is not required by a particular deployable, and in this case it probably means your modules are doing too much and don't have a clear purpose or are too large.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does $A(u)\left(\frac{\partial u}{\partial x^i},\frac{\partial u}{\partial x^j}\right)$ mean, exactly? Motivation: In the theory of harmonic maps between manifold, we often see the characterization
$$
\Delta_g u = -g^{ij}A(u)\left(\frac{\partial u}{\partial x^i},\frac{\partial u}{\partial x^j}\right)
$$
when we are working in the extrinsic viewpoint.

Question: Let $M,N$ be two Riemannian manifolds, $u:M\to N$ be a smooth map. Let $A$ denotes the second fundamental form of $N$, viewing as an embedded submanifold of $\Bbb R^k$. How is the expression
  $$
A(u)\left(\frac{\partial u}{\partial x^i},\frac{\partial u}{\partial x^j}\right)
$$
  rigorously defined?

First of all, $u$ need not be injective, so there can be a point $y\in N$ such that $u(x_1)=u(x_2)=y$. Doesn't this means that $\frac{\partial u}{\partial x^i}(y)$ is really not a vector field on $N$?
I think this non-uniqueness can be fixed for $x$ such that $du(x)$ is of full rank, so that $u$ is locally an embedding there. When $du(x)$ degenerates, however, I don't know how to make sense of it.

A: You are correct that $\partial u/\partial x_i$ is not a vector field on $N$. It is a section of $u^*TN$, i.e. associating to each point $x \in M$ a vector $\partial u/\partial x_i \in T_{u(x)} N$. So we take the second fundamental form $A$ of $N$, which is a section of $S^2(T^*N) \otimes T^{\perp} N$, and we pull it back to form $u^*A$, which you denote $A(u)$, a section of $S^2(u^* T^*N) \otimes u^* T^{\perp} N$. Then we plug in two sections $\partial u/\partial x_i, \partial u/\partial x_j$ of $u^* TN$.

A: I do not really follow the question. Since everything is local, the map $u$ can be effectively replaced by its derivative $D u$, which is a matrix of dimension $\dim(N)\times \dim(M)$. The map may be bad and the matrix may send different elements to the same element - but the image of the map itself is well defined. Once defined, the second fundamental form on $N$ gives a symmetric bilinear form on $T^{*}(N)$ at $u_{x}$. This is well-defined and you may write it out in matrix form if you like. The evaluation then is just matrix multiplication.


text:
Q: Search in a list of files I have a huge list of C source and header files, actually an autogenerated "cscope.files" file.
Is there a way to search for a string(not a C symbol) in all those files?
The files are distributed in a huge networked filesystem and I do not want to grep recursively in the root of that system.
I use Red Hat Enterprise Linux and gvim(+cscope) for my development. Any vim or python(2.3) or shell solution is OK.

A: find . -name '*.c'|xargs grep "some string"


text:
Q: Sequencing a series of functions with promises in Ember js I wasn't sure how to title this question.
What I am looking to do is grab a large array of movies, filter out only those that have reviews, then sort the reviews by date desc, then trim the list to grab only the latest 11 before setting the first entry to be featured and returning to the model then. With these numerous calls though, I notice some data being jumbled out of order and I believe it's due to all the calls running simultaneously. How can I use promises to structure this to wait for the previous step to complete before proceeding?
getLatestReviews(num) {
    const movieList = this.getMovies();
    const reviewList = movieList.filterBy('review');
    const indexList = this.sortReviewsByDate(reviewList);
    const latestList = this.getSetAmountOfMovies(num, reviewList);
    return this.setFirstReviewToFeatured(latestList);
},

sortReviewsByDate(arr, dir) {
    dir = dir || 'desc';

    return arr.sort(function(a,b) {
        if (dir === 'desc') {
            return a.review.date < b.review.date;
        } else {
            return a.review.date > b.review.date;
        }
    });
},
getSetAmountOfMovies(num, arr) {
    const movieList = arr ? null : this.getMovies();
    const trimmedList = arr ? arr.slice(0, num) : movieList.slice(0, num);
    return trimmedList;
},
setFirstReviewToFeatured(arr) {
    arr[0].isFeatured = true;
    return arr;
},

What I'm experience is once I exceed 10 reviews the ordering starts getting out of whack and I believe it's due to the functions not running in a sequence. But I'm not sure how to use promises to ensure one step is complete before running the next.

A: You should use promise chain to avoid asynchronous problems :
getLatestReviews(num) {
    return this.getMovies().then(function(movieList) {
       return movieList.filterBy('review');
    }).then(function(reviewList) {
       return //...
    });
},


text:
Q: Displaying textblock properly on a pivotitem I'm having a hard time trying to display how my textblock look like in the pivotitem. How do i make it look like the default one where u will get when u create a pivot project?
Thanks! :)
private void LoadFromLocalStorage()
{
    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        string[] fileNames = store.GetFileNames();

        foreach (string s in fileNames)
        {

            TextBlock txt = new TextBlock() { Text = s };
            container.Children.Add(txt);

            //PivotItem pitem = new PivotItem(); //create pivotitem
            //pitem.Content =  //set pivotitem content
            //MyPivot.Items.Add(pitem);//Add pivotitem to your pivot

        }
    }
}

XAML
 <controls:Pivot Title="MY APPLICATION">
            <!--Pivot item one-->
            <controls:PivotItem Header="item1">

                    <StackPanel x:Name="container"></StackPanel>
            </controls:PivotItem>

A: Edit the HeaderTemplate of the Pivot. Here's the default template:
<DataTemplate x:Key="DataTemplate1">
            <Grid>
                <TextBlock TextWrapping="Wrap" Text="{Binding}" d:LayoutOverrides="Width, Height"/>
            </Grid>
        </DataTemplate>

use like
<controls:Pivot Title="MY APPLICATION" HeaderTemplate="{StaticResource DataTemplate1}">

edit: if you're trying to display your items in the PivotItem, you should use a ListBox.
Add this to the top of the Page XAML.
 <phone:PhoneApplicationPage.Resources>
            <DataTemplate x:Key="DataTemplate1">
                <Grid>
                    <TextBlock Margin="0,0,1,0" Text="{Binding}" TextWrapping="Wrap" d:LayoutOverrides="Width, Height" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                </Grid>
            </DataTemplate>
        </phone:PhoneApplicationPage.Resources>

Inside your PivotItem, add a listbox:
<ListBox x:Name="lbFiles" HorizontalContentAlignment="Stretch" ItemTemplate="{StaticResource DataTemplate1}">

                </ListBox>

Then, change your function for getting filenames:
private void LoadFromLocalStorage()
{
    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        string[] fileNames = store.GetFileNames();
        var files = new ObservableCollection<string>();

        foreach (string s in fileNames)
        {
            files.Add(s);
        }
        lbFiles.ItemsSource = files;
    }
}

Here, the listbox 'ItemSource' is set to the list of filenames.
If this isn't familiar to you, you should go through some WP7 tutorials. It is pretty basic.
http://create.msdn.com/en-us/education/quickstarts


text:
Q: How to backup Windows 10 start menu layout? I have 3 Windows 10 devices and I wanna backup and import start menu layout on each device as Windows 10 isn't supporting layout syncing.
Most of the solutions I've found are for Windows 8 only.
One site showed me a way to export the layout by using this command:
Export-StartLayout -Path C:\StartLayout.XML

but nothing about how to import it!
I tried steps mentioned in this article and both of them shows me this error
Export-StartLayout : A parameter cannot be found that matches parameter name 'as'
At line:1 char:20
+ export-startlayout -as bin -path c: \customstartscreenlayout.bin ?ver ...
+                    ~~~
+ CategoryInfo          : InvalidArgument: (:) [Export-StartLayout], ParameterBindingException

+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.Windows.StartLayout.Commands.ExportStartLayoutCommand

This is a screenshot for everything I've tried .. https://goo.gl/Dya6ey

A: This works for me:
Export-StartLayout -path "$env:UserProfile\Desktop\StartBackup.bin" –verbose

Import-StartLayout -LayoutPath "$env:UserProfile\Desktop\StartBackup.bin" -mountpath "$env:systemdrive\"

But please note that it only applies to the default profile.

A: Apparently the As parametered is only available in Windows 8.1 and 2012 R2.
Try without it, just name the file .bin.
Export-StartLayout -Path C:\StartLayout.BIN

A: From this link: https://www.tenforums.com/tutorials/3088-backup-restore-start-layout-windows-10-a.html

*

*Back up registry key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CloudStore\Store\Cache\DefaultAccount

*Back up file %LocalAppData%\Microsoft\Windows\Shell\DefaultLayouts.xml

To restore:

*

*(Mess with registry at your own risk) Delete registry key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CloudStore\Store\Cache\DefaultAccount   (you cannot omit this step)

*Merge registry key backed up in steps above.

*Restore DefaultLayouts.xml file backed up in above steps, overwriting current %LocalAppData%\Microsoft\Windows\Shell\DefaultLayouts.xml

*Sign out of Windows and sign back in again.


text:
Q: How to bring back a removed display group in corona? I used this call in my code
display.remove(GroupName)
and it worked successfully, but how do I bring back the objects in the display object?
is there a command that will allow me to re-display the group?

A: Of course you cant bring back something that you removed as it will be void. You can hide it if you want to have it back. You can use this instead:
GroupName.isVisible = false


text:
Q: Multiple conditions in mySQL I want to filter the products on the basis of price, brand, and category. But none of them is required. So the user can filter the products on the basis of only price or price and brand. How to write this in mySQL using queries only. I have searched a lot but found the solution with the help of Stored Procedures.
If I write this query select * from product where brandid = 1 AND price = 10 and categoryid = 5. it will fetch 2 products which satisfy the where clause.
But if user doesn't want to filter the product on the basis of brand (lets say), then what will b the query? select * from product where brandid = null AND price = 10 and categoryid = 5... this will not work as I dont want to search products with brandid null. What I want is to remove that particular clause from where condition. So what my expected query is select * from product where price = 10 and categoryid = 5

A: Construct the query incrementally. Here it is in Ruby (since you didn't tag a programming language), but the logic is quite language-independent.
query = "SELECT * FROM products"
filters = []
params = []

if price_min
  filters << "price >= ?"
  params << price_min
end

if price_max
  filters << "price <= ?"
  params << price_max
end

if brand
  filters << "brand = ?"
  params << brand
end

# ...

unless filters.empty?
  query += " WHERE " + filters.join(' AND ')
end


text:
Q: Eclipse JNI failed to load Hi guys i startet eclispe this morning and everything works but a few hours later I get the following message "Failed to load the JNI shared library "C:Windows\system32..\jre\bin\client\jvm.dll". I can't find this file. I set JAVA_HOME and the Path component again and nothings works.

A: Check your pairing of the eclipse and java i.e
32-bit OS - 32-bit JDK - 32-bit Eclipse (32-bit only)

64-bit OS - 32-bit JDK - 32-bit Eclipse

64-bit OS - 64-bit JDK - 64bit Eclipse (64-bit only)

Check this link Eclipse reported "Failed to load JNI shared library"


text:
Q: How to disable certain check_boxes when using Formtastic's :as => :check_boxes <%= semantic_form_for [:admin, @admin] do |f| %>
    <%= f.inputs do %>
        <%= f.input :name %>
        <%= f.input :email, :as => :email %>
        <%= f.input :password, :as => :password %>
        <%= f.input :password_confirmation, :as => :password %>
        <%= f.input :admin_roles, :as => :check_boxes, :required => true, :disabled => [1] %>
    <% end %>
    <%= f.actions %>
<% end %>

-
<%= f.input :admin_roles, :as => :check_boxes, :required => true, :disabled => [1] %>

Passing an array to the above code disables the checkbox with id=1, which is nice. But I want to check the model of each checkbox, too see if it has a specific value, so I can disable it or not.
do_not_disable_checkbox if admin_role.do_not_show_me_boolean_field

Do I need to iterate each of my :admin_roles and output a checkbox for each? Or can I do it in one line like above? I'm new to rails and ruby, and I can't wrap my head around it and hoping for some help to put me in the right direction.


text:
Q: Time stamp conversion and deltatime with a decimal error We are working with a timestamp column in a CSV file and are running into an error because the CSV timestamp is formatted like this: 30:50.0 where we are fairly sure that its hours and minutes. With a decimal for seconds, however every decimal is 0. We are using this code to read and grab the times:
fmt = "%H:%M.0"

However, it returns this error:
ValueError: time data '30:50.0' does not match format '%H:%M.0'
similar error returned for using: '%H:%M.%S'
finally when just '%H:%M is used we get this error:
unconverted data remains: .0
We are out of ideas on how to either edit or otherwise read the time code. without manually editing the CSV file.
# Import moduels for use
from datetime import datetime as dt
import itertools

# Creating a function that will get the total difference in time between each point
def compute_delta_time(timelist):
    timetotal = []
    a, b = itertools.tee(timelist)
    next(b, None)
    fmt = "%H:%M.0"
    for start, end in itertools.izip(a,b):
        timetotal.append((dt.strptime(end, fmt) - dt.strptime(start, fmt)).total_seconds())
    return timetotal

Here is our entire function.

A: You could brute force it:
>>> x="30:50.0"
>>> h,mm=x.split(":")
>>> m,s=mm.split(".")
>>> int(h)
30
>>> int(m)
50
>>> int(s)
0

It's ugly, but workable.
Also, I suggest you add the tag "python" to your post.

A: %H must be in 0..23 range. You could parse the duration string manually as @PfunnyGuy suggested:
def to_seconds(duration_string):
    """'30:50.0' -> 111000"""
    hm, dot, seconds = duration_string.partition('.')
    hours, minutes = map(int, hm.split(':'))
    return (hours * 60 + minutes) * 60 + (int(seconds) if dot else 0)

Example:
durations = map(to_seconds, ["25:01", "30:50.0"])
time_diff =  [end - start for start, end in zip(durations, durations[1:])]
# ->  [20940]


text:
Q: how to break out of a for loop in lua i have the following code:
  for k, v in pairs(temptable) do
         if string.match(k,'doe') then
              if v["name"] == var2 then
                     txterr =  "Invalid name for "..k
                     duplicate = true
             end
             if duplicate then
                     break
             end
         end
    end

when duplicate is set to true, i want to exit the for loop all together. right now, it just loops through all the values in the table even if it finds a match.
i tried using the break statement but i think it is breaking out of the "if" statement.
i was thinking about a do while loop i could wrap around the entire for loop but i would still need a way to break out of the for.
thanks.

A: I tried the following:
temptable = {a=1, doe1={name=1}, doe2={name=2}, doe3={name=2}}
var2 = 1
for k, v in pairs(temptable) do
    print('trying', k)
    if string.match(k,'doe') then
        print('match doe', k, v.name, var2)
        if v["name"] == var2 then
            txterr =  "Invalid name for "..k
            duplicate = true
            print('found at k=', k)
        end
        if duplicate then
            print('breaking')
            break
        end
    end
end

and it works:
trying  doe2
match doe   doe2    2   1
trying  doe1
match doe   doe1    1   1
found at k= doe1
breaking

As you can see it skipped a and doe3. The error is therefore elsewhere: var2 or your names are not what you think (like the name values are strings whereas var2 is number), or you don't have any keys that match.


text:
Q: How to cancel other futures? I am creating multiple futures and I am expecting only one to achieve the desired goal.
How can I cancel all other futures from within a future?
This is how I create futures:
jobs = days_to_scan.map{|day|
      Concurrent::Future.execute do
        sleep_time = day.to_f / days_to_scan.count.to_f * seconds_to_complete.to_f
        sleep (sleep_time)
        if GoogleAPI.new.api_call(@adwords, ad_seeder, visitor, day)
           # How to cancel other futures here?
        end
      end
    }

A: I might be late to the party but I'm gonna reply anyway as other people might stumble upon this question.
So what you want is to probably force-shutdown the thread pool as soon as one Future finishes:
class DailyJobs
  def call
    thread_pool = ::Concurrent::CachedThreadPool.new
    jobs = days_to_scan.map{ |day|
      Concurrent::Future.execute(executor: thread_pool) do
        sleep_time = day.to_f / days_to_scan.count.to_f * seconds_to_complete.to_f
        sleep (sleep_time)
        if GoogleAPI.new.api_call(@adwords, ad_seeder, visitor, day)
           # How to cancel other futures here?
           thread_pool.kill
        end
      end
    }
  end
end

the thing is: killing a thread pool is not really recommended and might have unpredictable results
a better approach is to track when a Future is done and ignore other Futures:
class DailyJobs
  def call
    status = ::Concurrent::AtomicBoolean.new(false)

    days_to_scan.map{ |day|
      Concurrent::Future.execute do
        return if status.true? # Early return so Future does nothing

        sleep_time = day.to_f / days_to_scan.count.to_f * seconds_to_complete.to_f
        sleep (sleep_time)
        if GoogleAPI.new.api_call(@adwords, ad_seeder, visitor, day)
          # Do your thing
          status.value = true # This will let you know that at least one Future completed
        end
      end
    }
  end
end

It is worth noting that if this is a Rails application, you probably want to wrap your Future on Rails executor to avoid autoloading and deadlock issues. I wrote about it here

A: Okey, I could implement it as:
#wait until one job has achieved the goal
while jobs.select{|job| job.value == 'L' }.count == 0 && jobs.select{|job| [:rejected, :fulfilled].include?(job.state) }.count != jobs.count
    sleep(0.1)
end
#cancel other jobs
jobs.each{|job| job.cancel unless (job.state == :fulfilled && job.value == success_value) }
}


text:
Q: Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction I am trying to get images from a remote server. I keep getting this error:
  Warning database has been locked for 0:00:10.000000.
  Make sure you always use the transaction object for database operations during a transaction

And afterwards my application crash.

Widget carousel = new Container(
      height: 200,
      child: FutureBuilder<List<String>>(
          future: getPropImgs(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return new Carousel(

                boxFit: BoxFit.cover,
                images: snapshot.data.map((f) {
                  return new CachedNetworkImage(
                    imageUrl: f.toString(),
                    imageBuilder: (context, imageProvider) => Container(
                      decoration: BoxDecoration(
                        image: DecorationImage(
                            image: imageProvider,
                            fit: BoxFit.cover,
                            colorFilter:
                                ColorFilter.mode(Colors.blue, BlendMode.dstIn)),
                      ),
                    ),
                    placeholder: (context, url) => Center(
                        child: Container(
                            height: 30,
                            width: 30,
                            child: CircularProgressIndicator())),
                    errorWidget: (context, url, error) =>
                        Image.asset("assets/images/icon.png"),
                  );
                }).toList(),
                autoplay: true,
                animationCurve: Curves.fastOutSlowIn,
                animationDuration: Duration(milliseconds: 1000),
                indicatorBgPadding: 1.0,
                dotColor: Colors.black,

              );

A: I guess you are trying to perform huge amount of SQL queries.
Once slow solution is to make sure you await every calls. In the second line here you are missing an await:
 await db.transaction((txn) async {

However here it still create one transaction per insert so that will be super slow. One solution is to use batches (https://github.com/tekartik/sqflite/tree/master/sqflite#batch-support) and queue the insert statement (1000 by 1000 for example);
var batch = db.batch();
batch.rawInsert(statement1);
batch.rawInsert(statement2);
batch.rawInsert(statement3);
...
await db.commit(noResult: true);

A: DON'T CREATE A NEW DB VARIABLE INSIDE THE TRANSACTION...
DON'T DO THIS
 await db.transaction((txn) async {
  var batch = txn.database.batch();//Mistake.
  batch.insert(/*..table...*/, /*..toJson()..*/);

});

DO LIKE THIS
await db.transaction((txn) async {

      txn.batch().insert(/*..table...*/, /*..toJson()..*/);
      txn.batch().insert(/*..table...*/, /*..toJson()..*/);
      txn.batch().insert(/*..table...*/, /*..toJson()..*/);
      txn.batch().insert(/*..table...*/, /*..toJson()..*/);
      try{
        await txn.batch().commit(continueOnError: true);
        print("SUCESS ID : COMMIT " );
      }catch(e){
        print("faied to save to commit BRECASE ==> ${e.toString()}");
      }
    });


text:
Q: shell script is visible if checked manually in the path, but says 'No Such File or Directory' Following is the shell function which I execute remotely :
softrun() {
source /usr/local/bin/myscript.sh
#/bin/bash /usr/local/bin/myscript.sh
}

Command to execute above function stored in 'script1.sh' remotely is :
ssh user@host script1.sh softrun

But it gives error : No Such File or Directory
I have tried by 'source' & 'bash' method.
When I check manually the shell script exist in the location and is not a symbolic link

A: This isn't how you call a function in bash. You can't just pass a function name into the script. You need this in your script1.sh file:
#!/usr/bin/env bash

softrun() {
  source /usr/local/bin/myscript.sh
}

$1

Notice the $1 at the end of the file. This is your first argument to the script, which you're passing over ssh, which happens to be your function name. The reason you're getting "No Such File or Directory" error is because in your example ssh thinks that softrun is yet another file it's supposed to run after running script1.sh
UPDATE. Forgot. I think you'll also need to wrap the script name + its argument into quotes, so ssh thinks it's one single argument and not two files to be executed.


text:
Q: Creating sms verification system using twilio I am trying to create a sms verification system just for the sake of learning.
So the file structure would be following

Index.php   Form.php   Sendcode.php   Verify.php

What i am trying to achieve here is to try to learn, how can i force logged in users to be redirected to form.php and if they verify their number get redirected back to index.php otherwise prompted to verify their number back at form.php with an error. So if the status in DB is set as 1 the user can access index.php otherwise the status stays set at 0 and is required to verify number at form.php
Can someone help me with this? Perhaps write a sample index.php code
Here are the file contents
Form.php

Enter your phone number below, and we will send you a verification code to that phone number.

<form id = "phone" method  = "POST" action = "">
Phone number
<input name = "phone" type = "text" id = "phone_no" />
<input name = "submit" type = "submit" value = "Send Verification Code" />
</form>

Enter Verification Code received to the phone number specified above in the form below.

<form id = "verification" method  = "POST" action = "verify.php">
Verification Code
<input name = "code" type = "text" id = "code" />
<input name = "submit" type = "submit" value = "Verify" />
</form>

Sendcode.php
<?php
// configuration
/*** mysql hostname ***/
$hostname = 'localhost';
// database name
$dbname = '';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
// enter SID here
$twilioSid = '';
// enter twilio token here
$twilioToken = '';
if(isset($_POST['phone_no']))
{
    try
    {
        $verifyCode = rand(1000, 9999);

        $phone = $_POST['phone_no'];

        $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

        /*** add verification code and phone number to db **/
        $sth = "INSERT INTO user (phone, code) VALUES(:phone, :code)";
        $command = $dbh->prepare($sth);
        $command->bindParam(':phone', $phone, PDO::PARAM_STR);
        $command->bindParam(':code', $verifyCode, PDO::PARAM_INT);
        $command->execute();

        // twilio library
        require ('Services/Twilio.php');

        $client = new Services_Twilio($twilioSid, $twilioToken);

        // send sms with verifcation code
        $response = $client->account->sms_messages->create('555-555-555', $phone, 'Verification code ' . $verifyCode);

        echo '
A verification code was sent to your phone number. Please enter it below.
';

        /*** close the database connection ***/
        $dbh = null;
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}
?>

Verify.php
<?php
if(isset($_POST['code']))
{
    $verifyCode = $_POST['code'];

    /*** mysql hostname ***/
    $hostname = 'localhost';

    /*** database name ***/
    $dbname = '';
    /*** mysql username ***/
    $username = 'username';
    /*** mysql password ***/
    $password = 'password';

    try {

        $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

        // USER_ID is the login ID of the user
        $sql = "SELECT code FROM user WHERE id = {$user_id}";
        $sth = $dbh->query($sql);

        $code = $sth->fetchColumn();

        if($code == $verifyCode)
        {
            echo "Your account has been validated.";

            // verify user in db
            $todo = "UPDATE user SET status = 1 WHERE user_id = {$user_id}";
            $dbh->execute($todo);

        }
        else
        {
            echo "Your account has not been validated.";
        }

        $dbh = null;
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}
?>

A: Ricky from Twilio here.
We put together a sample application showing SMS account verification that may be helpful here:
https://www.twilio.com/docs/tutorials/walkthrough/account-verification/php/laravel
We used Authy, which is a Twilio product build specifically for this kind of use case. Breaking down a few parts to compare to your current code. Here's the section where we're sending an SMS:
$authyUser = $authyApi->registerUser($newUser->email, $newUser->phone_number, $newUser->country_code);
if($authyUser->ok())
{
    $newUser->authy_id = $authyUser->id();
    $newUser->save();
    $request->session()->flash(
        'status',
        "User created successfully"
    );

    $sms = $authyApi->requestSms($newUser->authy_id);
    DB::commit();
    return redirect()->route('user-show-verify');
}

And here's where we verify the code the user entered:
public function verify(Request $request, Authenticatable $user, AuthyApi $authyApi, TwilioRestClient $client)
{
    $token = $request->input('token');
    $verification = $authyApi->verifyToken($user->authy_id, $token);

    if ($verification->ok())
    {
        $user->verified = true;
        $user->save();
        $this->sendSmsNotification($client, $user);

        return redirect()->route('user-index');
    }
    else
    {
        $errors = $this->getAuthyErrors($verification->errors());
        return view('verifyUser',['errors' => new MessageBag($errors)]);
    }
}


text:
Q: Select default option on null angular I have this dropdown select is working
 <select name="name" [(ngModel)]="name">
 <option value="ACTIVE" [selected]="name.status=='ACTIVE' || name.status==null">Active</option>
 <option value="INACTIVE" [selected]="name.status=='INACTIVE'">Inactive</option>
</select>

but i want if name.status is null then by default select ACTIVE.
This is not working.
Any Solution Thanks

A: Using ngModel and selected aren't supposed to be used together.
In fact the selection selects whatever fits the options value compared to ngModels value.
Hence the right way would be:
<select [(ngModel)]="name.status">
  <option value="ACTIVE">Active</option>
  <option value="INACTIVE">Inactive</option>
</select>

This snippet only doesn't handle the case, that default is null. I recommend to patch the field on init.
Such a patch could look like:
name: NameType;
@Input()
set rawName(value: NameType) {
  this.name = {
    ...value,
    status: value.status || 'ACTIVE';
  }
}

A: Default select will work on behalf of your NgModule variable value .So you  have to mange inside .ts . if null value then assign active to your name.status

A: <select name="name" [ngModel]="name.status || 'ACTIVE'" (ngModelChange)="name.status=$event">
  <option value="ACTIVE">Active</option>
  <option value="INACTIVE">Inactive</option>
</select>

However, this will not change the value of name.status to 'ACTIVE' to do that you have to code it from .ts


text:
Q: error: '__assert_fail' was not declared in this scope Here's the error:
D:\libtorch_win_shared_with_deps_debug_1.8.1_cu102\libtorch\include\c10\macros\Macros.h:300: error: '__assert_fail' was not declared in this scope
     __assert_fail(#cond, __FILE__, static_cast<unsigned int>(__LINE__),  \
     ^


text:
Q: very poor performance (~0.4MB/s) with Linux usb bulk transfer kernel driver and hardware loopback I am writing a Linux kernel driver for a custom USB device which will use bulk endpoints, everything seems to work fine, however, I am getting very slow data rates. Specifically, it takes ~25 seconds to write and read 10MB worth of data. I tried this on an embedded system and a Linux VM running on a reasonable PC with similar results.
I am using a EZ-USB FX2 development kit from Cypress as the target board. It is running the bulkloop firmware which sets up two in and two out endpoints. Each endpoint is double buffered and supports 512 byte windows. The firmware polls out endpoints via a while(1) loop in main(), no sleep, and copies data from out to in endpoints when those data are available using autopointers. I have been told that this can move data fairly on Windows using their specific application but have not had a chance to verify this.
My code (relevant portions below) calls a function called bulk_io in the device probe routine. This function creates a number (URB_SETS) of out urbs which attempt to write 512 bytes to the device. Changing this number between 1 and 32 doesn't change performance. They are all copying from the same buffer. The callback handler for each write operation to an out endpoint is used to create a read urb on the corresponding in endpoint. The read callback creates another write urb until I have hit the total number of write/read requests that I want to run at a time (20,000). I am working now to push most of the operations in the callback functions into bottom halves in case they are blocking other interrupts. I am also thinking of rewriting the bulk-loop firmware for the Cypress FX2 to use interrupts instead of polling. Is there anything here that looks out of the ordinary to make the performance so low? Thank you in advance. Please let me know if you would like to see more code, this is just a bare-bone driver to test I/O to the Cypress FX2.
This is the out endpoint write callback function:
static void bulk_io_out_callback0(struct urb *t_urb) {
    // will need to make this work with bottom half
    struct usb_dev_stat *uds = t_urb->context;
    struct urb *urb0 = usb_alloc_urb(0,GFP_KERNEL);
    if (urb0 == NULL) {
            printk("bulk_io_out_callback0: out of memory!");
    }
    usb_fill_bulk_urb(urb0, interface_to_usbdev(uds->intf), usb_rcvbulkpipe(uds->udev,uds->ep_in[0]), uds->buf_in, uds->max_packet, bulk_io_in_callback0, uds);
    usb_submit_urb(urb0,GFP_KERNEL);
    usb_free_urb(urb0);
}

This is the in endpoint read callback function:
static void bulk_io_in_callback0(struct urb *t_urb) {
    struct usb_dev_stat *uds = t_urb->context;

    struct urb *urb0 = usb_alloc_urb(0,GFP_KERNEL);
    if (urb0 == NULL) {
            printk("bulk_io_out_callback0: out of memory!");
    }

    if (uds->seq--) {
            usb_fill_bulk_urb(urb0, interface_to_usbdev(uds->intf), usb_sndbulkpipe(uds->udev,uds->ep_out[0]), uds->buf_out, uds->max_packet, bulk_io_out_callback0, uds);
            usb_submit_urb(urb0,GFP_KERNEL);
    }
    else {
            uds->t1 = get_seconds();
            uds->buf_in[9] = 0; // to ensure we only print the first 8 chars below
            printk("bulk_io_in_callback0: completed, time=%lds, bytes=%d, data=%s\n", (uds->t1-uds->t0), uds->max_packet*SEQ, uds->buf_in);
    }
    usb_free_urb(urb0);
}

This function gets called to set up the initial urbs:
static int bulk_io (struct usb_interface *interface, struct usb_dev_stat *uds) {
    struct urb *urb0;
    int i;

    uds->t0 = get_seconds();

    memcpy(uds->buf_out,"abcd1234",8);

    uds->seq = SEQ; // how many times we will run this

    printk("bulk_io: starting up the stream, seq=%ld\n", uds->seq);

    for (i = 0; i < URB_SETS; i++) {
            urb0 = usb_alloc_urb(0,GFP_KERNEL);
            if (urb0 == NULL) {
                    printk("bulk_io: out of memory!\n");
                    return(-1);
            }

            usb_fill_bulk_urb(urb0, interface_to_usbdev(uds->intf), usb_sndbulkpipe(uds->udev,uds->ep_out[0]), uds->buf_out, uds->max_packet, bulk_io_out_callback0, uds);
                            printk("bulk_io: submitted urb, status=%d\n", usb_submit_urb(urb0,GFP_KERNEL));
            usb_free_urb(urb0); // we don't need this anymore
    }

    return(0);
}

Edit 1 I verified that udev->speed == 3, so USB_SPEED_HIGH, meaning this is not because Linux thinks this is a slow device....
Edit 2 I moved everything in the callbacks related to urb creation (kmalloc, submit) and freeing into bottom halves, same performance.

A: Reading and writing in small chunks is in my experience not very effective.

I am using a EZ-USB FX2 development kit from Cypress as the target board.
  It is running the bulkloop firmware which sets up two in and two out endpoints.
  Each endpoint is double buffered and supports 512 byte windows.

This is does not mean that you can write no more than 512 bytes to it at a time.
I would try writing no less than 4096 bytes to it at a time, because that is the standard pages size (perhaps not so standard in embedded systems). If that worked, I would try writing as much as 1/4 of a megabyte to it at a time, and then even more if that worked.
The key point here is knowing when that the writing window of the device is full. When it is - it will call whatever callbacks, or you get that information by any other means and use it in signaling your application to stop writing.
Note that the window will not be full after you "give the device" 512 bytes, because the device will start reading from this window as soon as there is anything to read.
Perhaps I've missed something important in your question, but what I'm saying is essentially you have to write more than 512 bytes at a time. This is why you get such poor performance.


text:
Q: Parse a string to date in specific format I have a TimeStamp '2013-06-24 10:46:11.0' and I need to cut off the .0 part, so what I did was to use the SimpleDateFormat to parse it to String and back then parse it to date, the first conversion was fine but the second (string to date) throws a java date time.
public void convert(Object object) {
    Date date;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    date = object().getDate();
    String formated = format.format(date);
    try {
       date = format.parse(formated);
    } catch (ParseException ex) {
       Logger.getLogger(DlgConsultaFactura.class.getName()).log(Level.SEVERE, null, ex);
    }
}

What I expect is a date like this 2013-06-24 10:46:11, but what I got is this date Mon Jun 24 10:46:11 CDT 2013
Any help will be appreciated. Thanks.

A: Mon Jun 24 10:46:11 CDT 2013 and 2013-06-24 10:46:11 is actually same value. Mon Jun 24 10:46:11 CDT 2013 is as per your default locale.
You're getting confused between date's internal representation and its display format.
To print in 2013-06-24 10:46:11 you can use same SimpleDateFormat object again.
You can use DateFormat#format(Date) to print the date or return the String representation in your desired format i.e. "yyyy-MM-dd HH:mm:ss". Something like this:
String myDt = format.format(date);
// 2013-06-24 10:46:11

A: Not the best way but a quick and easy one if you want just the string representation of the date ...
    formated = formated.substring(0, formated.length()-2);

:)

A: DateFormat i.e. SimpleDateFormat just formats the date as per your need.
Parse returns the Date representation of the String (or timestamp in your case) passed in.
Format returns the String representation of the Date object passed in.
In both the cases , you see the same date just the representation is different.


text:
Q: MySQL/Mariadb per-record overhead? what, if any, is the per-record disk overhead for mysql/mariadb? (i'm mostly interested in InnoDB, but any engine would interesting)
lets say you just have a
CREATE TABLE tbl (
    id BIGINT NOT NULL PRIMARY KEY
);

obviously this will use at least 8 bytes (BIGINT) per record, but will it use more than that per record?

A: There's a lot of overhead.

*

*Per 16KB block:  several pointers, flags, etc.

*Per row:  about 2 dozen bytes of links, transaction stuff, etc.  Even more, if a row is being touched by multiple transactions at the same time.

*Per column:  1- or 2-byte length and NULLness.  Yes even for that 8-byte BIGINT.

*PRIMARY KEY:  This is quite low because the PK is clustered with the data; it adds up to about 1% of the entire table.

*Secondary keys:  Each secondary key (INDEX(...)) contains the columns indicated, plus a copy of the PK column(s).  It is a separate BTree.  So, for this reason, there may be multiple copies of your BIGINT occupying disk space.

*InnoDB initially allocates in 16KB block chunks (data and each secondary index separately).  Later it pre-allocates in bigger chunks.  I think your sample table will use 16KB until you have several hundred rows in it.

*InnoDB does not release space back to the OS.  That is, if you insert a thousand rows, then the table will be expanded to several blocks.  Then, if you delete all the rows, the disk space won't shrink.

Aside from the indexes, that 8 bytes for the bigint, plus similar computations for other columns can be added up.  But then you must multiply by 2 to 3 to get the disk space needed for an InnoDB table.  (Of course, there are exceptions with less than 2x or more than 3x.)
I'll be happy to discuss other examples, but I cannot be very precise.


text:
Q: How do I keep a group header in crystal reports from appeaing when unnecessary? I am running a report on multiple salespersons and their multiple clients. I have a group header, which includes the name of the salesperson for that group, and a secondary group header, which includes the name of each of the salesperson's clients and all their info as well as headings for the columns with information.
I've set up both group headings to appear at the top of every page. It works for the most part with the group header at the top of every page along with the corresponding secondary group header for the particular client being reported on. However, I've run into a small problem. Sometimes when the next group for a for the next client is started it's toward the end of the page so that the end of page has the secondary group header with none of the details only to repeat at the top of the next page with the corresponding details. I don't want to start a new page for each client as some clients don't have a lot of information and multiple clients can be included on a page. How do I set it up so that if there is not enough space on a page for any details, the secondary header does not appear until the next page?
Thank you.

A: I realized that "keep it together" was only clicked for the main group not the subgroup that I was worried about. So I clicked it and that solved the problem


text:
Q: Does the NS_BLOCK_ASSERTIONS disable both NSAssert and assert() calls? Does the NS_BLOCK_ASSERTIONS switch off just the NSAssert calls or also the assert() calls. My app crashes in the Release mode on the line with assert(...) statement.
The documentation says only about NSAssert and does not tell if assert() calls are being disabled.
There are a couple questions related to mine that are not answering it. I'm linking them here:
NS_BLOCK_ASSERTIONS in Objective-C
NSAssert vs. assert: Which do you use, and when?
How to know if NSAssert is disabled in release builds?

A: No, assert() is controlled with the NDEBUG symbol:
#ifdef NDEBUG
#define assert(e)   ((void)0)
#else
...

(see /usr/include/assert.h if you have the Xcode Command Line Tools installed, or elsewhere in the Xcode.app bundle, if not).


text:
Q: Selecting HTML elements which are loaded from scripts The webpages of a certain website are all constructed out in sets of tables. Basically, each set of tables is constructed from scripts.
There are about 80 table tags in the DOM of any webpage I've checked in that site (I counted 77 tables in one page in the DOM). A very old site.
Some element children (td) include some tables inside themselves.
I Came to the conclusion that webpages in that site are constructed from scripts because of two reasons:
1) Either of these won't work on basically any table element in a webpage:
document.querySelector("#mySelector").style.display = "none";
document.querySelector(".mySelector").style.display = "none";
document.querySelector(" /* LONG-CSS-PATH-TAKEN-FROM-DEVTOOL (via "Copy CSS path") */ ").style.display = "none";

Such action will usually output:

TypeError: document.querySelector(...) is null

Ofcourse, all 3 examples work fine on other websites.
2) There are script segments before different parts of the DOM.

My question:
My question is comprised of the following two questions:
1) How could I prevent loading of a particular script that creates a certain set of tables? (a certain part of the whole webpage)?

*

*I ask this because it seems to be the only way to hide some elements in this odd layout, given that targeting them traditionally (ID, Class, CSS-PATH) gives the above error.

2) May there be another reason than "loading HTML from scripts" that causes the elements not to be targeted in the traditional way?
Notes:

*

*I run this script from Console.

*I also tried to run it with Greasemonkey inside a window.onload event handler.

A: If you can see the element in the DOM, you can query it.
One possible explanation for the behavior you're seeing is that the elements are being loaded into the DOM after your query. You haven't provided enough clues to offer any practical advice other than to figure out what scripts are being loaded and take it from there.
Another possible explanation is that the tables are in iframes. Querying against the DOM of the top frame won't return elements in the DOMs of other frames. You might see them in the DevTools Elements pane because it shows all the DOMs, but you have to get a reference to the correct frame's document before your can query it.
Last but definitely not least is the very simple question... WAT? What's going on there? Hundreds of tables? It makes no sense, even by the standards of the late 90s when using tables for layout was considered a good idea.
Your strategy shouldn't be to hide them but rather to completely get rid of them. Consider running away.


text:
Q: How to combine responses from two calls in one response? I'm getting an empty response ({}), whereas my expected response is of format:
{
    locationResponse: "location foo",
    forecastResponse: "forecast bar"
}

In my index file I have:
const {getCity} = require('./routes/city');
const {getForecasts} = require('./routes/forecast');

app.get('/forecasts', function (req, res) {
    var location = getCity(req, res);
    var forecast = getForecasts(req, res);

    //these are logged as undefined
    console.log("Inside index.js");
    console.log(location);
    console.log(forecast);
    res.send({locationResponse: location, forecastResponse: forecast});
});

Inside forecast file I have the following, and a similar one is in city file:
module.exports = {
    getForecasts: (req, res) => {
       var result = //mySQL DB calls and processing
       console.log("Inside getForecasts");
       console.log(result); //actual result printed
       return "Forecast";
    }

UPDATE: So I added some logs right before each call's return statements and figured out that the logs are printed in the following order, which means, it is not working as expected because I have not considered the fact that they are asynchronous calls.
Inside index.js
undefined
undefined
Inside getForecasts
{result}

A: The problem here is that in your ./routes/forecast/ getForecasts method, you're telling the response to send, with the data "Forecast". You should only ever use res.send once per request, as this will resolve the response and return to the client.
Instead, your getForecasts method should just return whatever data you need, and your index file should handle the response. If you need getForecasts to handle a response too, perhaps because you're sending requests directly to a forecasts endpoint that doesn't require location data, then you can refactor your code so that both index and forecasts make a call to get the data you need. For example:
/* index.js */
const {getCity} = require('./data/city');
const {getForecasts} = require('./data/forecast');

app.get('/forecasts', function (req, res) {
    var location = getCity();
    var forecast = getForecasts();
    res.send({locationResponse: location, forecastResponse: forecast});
});

/* data/forecast.js */
module.exports = {
    getForecasts: () => {
        return "Forecast";
    }
};

/* data/city.js */
module.exports = {
    getCity: () => {
        return "City";
    }
};

Then you can also have:
/* routes/forecast.js */
const {getForecasts} = require('../data/forecast');
module.exports = {
    getForecasts: (req, res) => {
        res.send(getForecasts());
    }
};

The above may be overcomplicating things, but I made the assumption that if you're using a routes directory, you probably want route handlers to be stored there. Hope this helps.

A: Seems both of your getCity() and getForecasts() functions are async. These asynchronous functions return a promise rather actual response.
So you can use simple asysn/await or Promise.all in JS to solve the issue.
Option 1: Use await for the promise to resolve before logging the message to the console:
app.get('/forecasts', async function (req, res) {
    var location = await getCity(req, res);
    var forecast = await getForecasts(req, res);

    //these are logged as undefined
    console.log("Inside index.js");
    console.log(location);
    console.log(forecast);
    res.send({locationResponse: location, forecastResponse: forecast});
});

Option 2: Use Promise.all() to wait for all the promises to have fulfilled.
app.get('/forecasts', function (req, res) {
    var list = await Promise.all([getCity(req, res), getForecasts(req, res)]);

    //these are logged as undefined
    console.log("Inside index.js");
    console.log(list[0]);
    console.log(list[1]);
    res.send({locationResponse: list[0], forecastResponse: list[1]});
});

A: You can make use of async/await syntax.
app.get('/forecasts', async function (req, res) {
    var location = await getCity(req, res);
    var forecast = await getForecasts(req, res);

    //these are logged as undefined
    console.log("Inside index.js");
    console.log(location);
    console.log(forecast);
    res.send({locationResponse: location, forecastResponse: forecast});
});


text:
Q: ERROR: function expression in form cannot refer to other relations of same query level : How to work around LATERAL DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE primes
        ( pos SERIAL NOT NULL PRIMARY KEY
        , val INTEGER NOT NULL
        , CONSTRAINT primes_alt UNIQUE (val)
        );

CREATE FUNCTION is_prime(_val INTEGER)
RETURNS BOOLEAN
AS $func$
DECLARE ret BOOLEAN ;
BEGIN

SELECT False INTO ret
WHERE EXISTS (SELECT *
        FROM primes ex
        WHERE ex.val = $1
        OR ( (ex.val * ex.val) <= $1 AND ($1 % ex.val) = 0 )
        );
RETURN COALESCE(ret, True);
END;
$func$ LANGUAGE plpgsql STABLE;

CREATE VIEW vw_prime_step AS (
        -- Note when the table is empty we return {2,3,1} as a bootstrap
        SELECT
           COALESCE(MAX(val) +2,2) AS start
         , COALESCE((MAX(val) * MAX(val))-1, 3) AS stop
         , COALESCE(min(val), 1) AS step
        FROM primes
        );
SELECT * FROM vw_prime_step;

        -- The same as a function.
        -- Works, but is not usable in a query that alters the primes table.
        -- ; even not with the TEMP TABLE construct
CREATE FUNCTION fnc_prime_step ( OUT start INTEGER, OUT stop INTEGER, OUT step INTEGER)
RETURNS RECORD
AS $func$
BEGIN
/***
CREATE TEMP TABLE tmp_limits
        ON COMMIT DROP
        AS SELECT ps.start,ps.stop,ps.step FROM vw_prime_step ps
        ;
-- RETURN QUERY
SELECT tl.start,tl.stop,tl.step INTO $1,$2,$3
FROM tmp_limits tl
LIMIT 1
        ;
***/
SELECT tl.start,tl.stop,tl.step INTO $1,$2,$3
FROM vw_prime_step tl
LIMIT 1;
END;
$func$
-- Try lying ...
-- IMMUTABLE LANGUAGE plpgsql;
-- Try lying ...
Stable LANGUAGE plpgsql;

        -- This works
SELECT * FROM fnc_prime_step();
INSERT INTO primes (val)
SELECT gs FROM fnc_prime_step() sss
 , generate_series( 2, 3, 1 ) gs
WHERE is_prime(gs) = True
        ;
        -- This works
SELECT * FROM fnc_prime_step();
INSERT INTO primes (val)
SELECT gs FROM fnc_prime_step() sss
 , generate_series( 5, 24, 2 ) gs
WHERE is_prime(gs) = True
        ;

        -- This does not work
        -- ERROR:  function expression in FROM cannot refer to other relations of same query level:1
SELECT * FROM fnc_prime_step();
INSERT INTO primes (val)
SELECT gs FROM fnc_prime_step() sss
 , generate_series( sss.start, sss.stop, sss.step ) gs
WHERE is_prime(gs) = True
        ;

SELECT * FROM primes;
SELECT * FROM fnc_prime_step();

Of course, this question is purely hypothetic, I am not stupid enough to attempt to calculate a table of prime numbers in an DBMS. But the question remains: is there a clean way to hack around the absence of LATERAL?
As you can see, I tried with a view (does not work), function around this view (does not work either), a temp table in this function (njet), and twiddling the function's attributes.
Next step will probably be some trigger-hack (but I really,really hate triggers, basically because they are invisible to the strictness of the DBMS schema)

A: you can use SRF function in target list, but there should be some strange corner cases. LATERAL is best.

postgres=# select i, generate_series(1,i) X from generate_series(1,3) g(i);
 i | x
---+---
 1 | 1
 2 | 1
 2 | 2
 3 | 1
 3 | 2
 3 | 3
(6 rows)


text:
Q: Passing values of an object between forms in VB.NET Here's my problem.
I'm making a project in VB.NET that (currently) exists out of 1 class (let's call it User.vb here) and 2 WinForms (frmDisplay & frmMain).
Let's say User.vb is currently looking like this:
Public Class User
  Private mName As String

  Public Sub New(ByVal name As String)
    Me.Name = name
  End Sub

  Public Property Name As String
    Get
        Return mName
    End Get
    Set(value As String)
        mName = value
    End Set
  End Property
End Class

Let's also say the form frmDisplay is just a form with a textfield txtString and a button btnSend.
Public Class frmDisplay
   Dim usr As New User()

   Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
      usr.Name = txtString.Text
      frmMain.Show()
      Me.Hide()
   End Sub
End Class

On the form frmMain I want to reach the value in the property Name that I stored in the class User on the first form.
The basic idea is (I know it doesn't work):
Public Class frmMain
   Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      lblStoredString.Text = usr.Name << This is where I'm stuck
   End Sub
End Class

I googled my problem and read many posts, but I just can't seem to understand it. Maybe you guys can help me. I am new to VB.NET and WinForm-stuff (about 3 months of exp.), but I have done some programming in the past in C# with webapplications.
Every bit of help is greatly appreciated.
Thanks a lot in advance!

A: My focus is ASP.NET, and I prefer C#, but I'll chime in.  There are numerous ways of providing data between the forms.  The first one that comes to mind is to use a cache of some kind.  The idea is that once the cache is made available to your program, you can add the value to the cache when the button is clicked, and then safely read the value whenever you need it.  This can be a static class with a Dictionary, or you can look into using the functionality provided by the System.Web.Caching namespace.  http://www.codeproject.com/Articles/8977/Using-Cache-in-Your-WinForms-Applications has an example.
Another way would be to use a shared data source.  The concept is similar to the caching, but this would allow you to pass more complex relational data between your forms, assuming your real goal is more complicated than you describe.  Here is a walkthrough for that:  https://msdn.microsoft.com/en-us/library/ms171925.aspx.
You could be quick and dirty, and write the values to a text file at some location, and then read the values from the second form.
The simplest way is probably to define a custom constructor for the second form, and pass the values you need when you instantiate the second form.  This is best suited if the values from the first form can be considered "parameters" to the instance of the second form.  Passing a textbox value from one form to another in windows application

A: Declare the usr variable Friend
Public Class frmDisplay
  Friend usr As New User()

It will then be available from the other form
Public Class frmMain
  Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    lblStoredString.Text = frmDisplay.usr.Name
  End Sub
End Class

It's a quirk of VB.NET that forms are automatically created with a public variable name the same as the class name. That's why you are able to use frmMain without having to create it (e.g. Dim frmMain as New frmMain). You can turn off this behaviour, but it isn't relevant to your problem.

A: Will there only ever be one User.Name that you are interested in throughout the app?
If yes, then change the class to:
Public Class User
    Public Shared Name As String
End Class

Then you can use User.Name from any form (or anywhere in the application) to get/set that value.
Note that you can still wrap the field in a property if you like:
Public Class User

    Private Shared _Name As String

    Public Shared Property Name As String
        Get
            Return _Name
        End Get
        Set(value As String)
            If (value.Trim <> "") Then
                _Name = value.Trim
            End If
        End Set
    End Property

End Class

A: On the other hand, if you want to do it "properly"...
Public Class frmDisplay
  Private usr As User

  Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
    usr = New User(txtString.Text)
    Dim f As New frmMain(Me, usr)
    f.Show()
    Me.Hide()
  End Sub
End Class

and frmMain...
Public Class frmMain
  Private myParent As Form
  Private usr As User

  Sub New(parent As Form, _usr As User)

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    usr = _usr
    myParent = parent
  End Sub

  Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Label1.Text = usr.Name
  End Sub

  Private Sub frmMain_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
    myParent.Show()
  End Sub

End Class

Here we instantiate frmMain and pass the User object to its constructor. We also pass the calling form so we can display it again when frmMain is closed.


text:
Q: How to Post a web request and receive a file from web API response? I have an Infopath Form Template on Sharepoint, I want to add a button there so when the user clicks on it, it will POST an string to the following Web API. The following web API is tested and returns an excel file as shown:
I want to Post the FileName of the excel file using post request and it is important for me the request method to be POST type. and then the user will download a file with the specified 'FileName'.
Actually i want to use post method because at the next stage i will send the content of the excel file too.
Important Note: I only can use .Net FrameWork 3.5 because this is the only framework supported in InfoPath Form Templates.
[HttpPost]
public HttpResponseMessage Post([FromBody]string FileName)
    {
        string reqBook = "c:\somefile.xlsx";
        //converting Excel(xlsx) file into bytes array
        var dataBytes = File.ReadAllBytes(reqBook);
        //adding bytes to memory stream
        var dataStream = new MemoryStream(dataBytes);

        HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
        httpResponseMessage.Content = new StreamContent(dataStream);
        httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = FileName;
        httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

        return httpResponseMessage;
    }

A: When you perform the HttpPost on the client side, you will want to read the HttpResponseStream to get the byte data of the response stream.
Once you have the response stream data, you can then deserialize it to the type of object in C# you want, or you could alternatively just write it to the disk as
File.WriteAllBytes("someexcel.xlsx",data);

An easy way to do it would be with the HttpClient class.
HttpClient client = new HttpClient();
var response = client.PostAsync("", null).Result;
var content = response.Content.ReadAsByteArrayAsync().Result;
File.WriteAllBytes("excel.xlsx", content);

Just fill in the PostAsync bit with the Url and the content you wish to post.
I am using .Result to keep everything synchronous - but you can use 'await' if you prefer.
If you are working with HttpWebRequests - then the process becomes more complicated, as you need to manage the streams yourself.
The HttpClient will manage and handle it all for you - so I recommend it, unless there is something special it needs to do that it currently does not.
Due to your .Net 3.5 requirement:
private static HttpWebResponse MakeRequest(string url, string postArgument)
    {

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = "POST";

        request.ContentType = "multipart/form-data;";
        Stream stream = request.GetRequestStream();
        string result = string.Format("arg1={0}", postArgument);
        byte[] value = Encoding.UTF8.GetBytes(result);
        stream.Write(value, 0, value.Length);
        stream.Close();

        return (HttpWebResponse)request.GetResponse();
    }

You can then do:
var response = MakeRequest("http://mywebsite.com/ProcessExcel", "accounts.xlsx");

And then do
Stream objStream = response .GetResponseStream();
BinaryReader breader = new BinaryReader(objStream);
byte[] data= breader.ReadBytes((int)webresponse.ContentLength);
File.WriteAllBytes("excel.xlsx",data);


text:
Q: Wrong validations messages are triggered when validating input text field knockout validation plugin I am researching the knockout validator plugin. I have an input text control in the view:
Prefix:
<input data-bind = "value: Prefix" />

I am doing some validation on the Prefix observable variable:
Prefix.extend({
            minLength: 3,
            required: true
        });

The validation is working but when I enter one character in the input text box and change the focus the message for required rule is shown, not that for minLength. I tried some alternative syntax:
Prefix.extend({ required: true })
            .extend({ minLength: 3 })

But nothing changes. If I enter the minimum required characters and then delete them one by one, the correct rule messages are triggered (minLength message and required message when no characters are left). I am not very much familiar with javascript and I cannot figure out what am I doing wrong. Any help will be appreciated. Thank You!

A: Check the version of knockout you're using. I ran into this issue and found that I was using knockout 2.0.0, the newest version (2.1.0) seems to fix this issue.


text:
Q: VC++ REGEX ANSI C equivalent I have the following C++ code, works ok:
#include <regex>
#include <iostream>
#include <string>

int main () {
    std::string str("mymail@yahoo.com;lslsls;myemail@gmail.com");
    std::tr1::regex rx("([a-zA-Z0-9_\\.]+@([a-zA-Z0-9\\-]+\\.)+[a-zA-Z]{2,4})");
    std::tr1::sregex_iterator first(str.begin(), str.end(), rx);
    std::tr1::sregex_iterator last;

    for (auto it = first; it != last; ++it)
    {
        std::cout << "[Email] => " << it->str(1) << std::endl;
    }

    return 0;
}

is there a simple way to earn this in C ANSI (*.cpp -> *.c) using native libraries? I'm using MS Visual Studio 2010.


text:
Q: Using VBA, scraping content of classes within classes in html file I am trying to scrape data from the below html code.
More precisely, for each i and j classes "flightCabin3 colmn[i] flightCabinOption_[j] cabin-block" (note: these classes are unique), get the content of the sub-classes "travel-class" and then either the "noAvlbl" class or the content of the "message-number-of-seats" class.
(To either know that there is no availability, like the below example in Premium Economy, or that there are X seats available, like 2 seats in Club World in the below example)

                Premium Economy

                                Not Available

                    2 LEFT
                Business Class

                                <input type="hidden" id="hdnSlngClsSB0-0-C" name="hdnSlngClsSB0-0-C" value="I">
                                <input data-sector-index="0" class="cabinSelector" id="journey0RadioButton0CabinCodeC" value="BA00015Friday 4 May 2023" name="0" type="radio" aria-label="Select /Enter to select cabin Club World">
                                <input class="shfv0" type="hidden" value="SHFV">
                                Available

                First

                                Not Available

My understanding of VBA is very basic. I've been able to get the data from other elements on the page using "getElementByID" and innerText, but I'm not sure what to do here given these elements don't have IDs, but classes, which aren't unique. (eg. "Travel class" shows up several time, how can I know which travel class is paired with which availability?)
I've been able to use querySelectorAll to identify the object "flightcabin3 [...]" but I'm not sure how to go from there.
This is what I have done so far
Sub Scraper()

Dim nodeDeparture_Time As Object
Dim nodeClass As Object
Dim Departure_Time As String
Dim Class(2, 3) As String

Set nodeDeparture_Time = ie.document.getElementByID("dtlDepartureTime0_0_1")
Departure_Time = nodeDeparture_Time.innerText

Set nodeClass = ie.document.querySelectorAll("flightCabin3 colmn1 flightCabinOption_0 cabin-block")

Range("A1").Value = Departure_Time

End Sub

Also for some reason I had to use "querySelectorAll" instead of "getElementbyTagName" which didn't work (despite being on IE9?)
Any help would be tremendously appreciated.
Thanks!


text:
Q: body mass is not changed using box2d cocos2d i just cant figure out how this mass thing works .
i have read the box2d docs, (which have many commands that are not in the cocos2d at the moment) and i was trying to understand the mass thing.
i know that if i change the body density it doesnt change a thing :
    //add body
b2BodyDef spriteBodyDef;
spriteBodyDef.type =b2_dynamicBody; //b2_staticBody;
spriteBodyDef.position.Set(pilot1.position.x/PTM_RATIO,pilot1.position.y/PTM_RATIO);
spriteBodyDef.userData = pilot1;
pilot1Body = world->CreateBody(&spriteBodyDef);
b2CircleShape spriteShape; //b2polygon-for box shape
spriteShape.m_radius = 15.0/PTM_RATIO;
b2FixtureDef spriteShapeDef;
spriteShapeDef.restitution = 0.4f;
spriteShapeDef.shape = &spriteShape;
//spriteShapeDef.density=10.0f;

b2Fixture *fix=pilot1Body->GetFixtureList();
fix->SetDensity(1.5f);
pilot1Body->ResetMassData();
NSLog(@"mass2: %f", pilot1Body->GetMass());
spriteShapeDef.isSensor = false;
pilot1Body->CreateFixture(&spriteShapeDef);
    [self addChild:pilot1];

thanks a lot.

A: You need to set new density for some or all the fixtures attached to the body using b2Fixture::SetDensity and then call b2Body::ResetMassData, for example:
    NSLog(@"mass1: %f", body->GetMass());
    b2Fixture *fix = body->GetFixtureList();
    while (fix) {
        fix->SetDensity(1.5f);
        fix = fix->GetNext();
    }
    body->ResetMassData();
    NSLog(@"mass2: %f", body->GetMass());


text:
Q: Matplotlib not getting installed on virtualenv I setup with Python3 I have created a virtualenv with Python3. I also installed matplotlib on the system. So when I try to use it outside the virtualenv, the system finds the installation. When I do pip list matplotlib shows as one of the packages. However when I activate my virtualenv it doesn't show it under python3. I tried removing and re-creating the virtualenv and it doesn't work. I also tried installing matplotlib pip install matplotlib under the virtualenv and again not working.
Any recommendation how to fix the issue?


text:
Q: How can I start the "speaking" in preview with key? I want my Mac to read things out in preview, now I have to click on Edit --> Speech --> Start speaking. How can I use keys/shortcuts to start it? I use MacOS BigSur 11.6

A: Method 1: Use VoiceOver
From Apple Support: Have your Mac speak text that's on the screen:

On your Mac, press the specified keyboard shortcut (the default key combination is Option-Esc).
If text is selected when you press the keyboard shortcut, the selected text is spoken.

Method 2: Add a keyboard shortcut in System Preferences to trigger menu the command
If you specifically need to trigger the menu command, you can create a keyboard shortcut in System Preferences. Here's the process:

*

*Open System Preferences

*Select "Keyboard" then open the "Shortcuts" tab

*Select "App Shortcuts" from the sidebar

*Create a new entry by clicking the "+" button

More detailed instructions can be found at Apple Support: Create keyboard shortcuts for apps on Mac
Screenshots


text:
Q: ag-grid : How to set custom background color in column header? I'm using ag-grid with Angular 4.
I want to be able to change the background color of individual column headers during runtime.
It seems that I have to use headerComponentFramework property in coldefs, but I have no idea how to use this.
Anybody has an idea?
regards,
Alex

A: If you have a predefined set of colors for the header, I would use the headerClass option:
defaultColDef: {
  headerClass: function(params) {
    // logic to return the correct class
    return 'header-one';
  }
}

Then in css use the background-color property:
.header_one {
  background-color: red;
}

See the following example where clicking on a cell changes the header color:
https://stackblitz.com/edit/ag-grid-header-color-dynamic?file=index.js

A: If using Sass then setting the header-background-color theme parameter should work.
The example below assumes you are using the alpine theme.
@import "~ag-grid-community/src/styles/ag-grid.scss";
@import "~ag-grid-community/src/styles/ag-theme-alpine/sass/ag-theme-alpine-mixin";

.ag-theme-alpine {
    @include ag-theme-alpine((
        header-background-color: deeppink
    ));
}

https://www.ag-grid.com/javascript-grid-themes-customising/#setting-parameters-using-sass

A: Here is a plunker that demonstrates a header component like what you want. I took it from the examples on the docs for ag-grid. Take a look mostly at header.component.html, that's where the magic is at.
I think the only confusing part would be when you create the HeaderComponent:
export class HeaderComponent implements IHeaderAngularComp {
    public color: string = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    public params: MyParams;
    private elementRef: ElementRef;

    ...

    //You will need to get the params from agInit so that you can access
    //the value for each column

    agInit(params: MyParams): void {
        this.params = params;
    }
}

Please check on their docs for more explanation, they get better every day


text:
Q: sequelize query between date range (createdAt) I wanted to query in sequelize between a range of start and end-date but it does not seem to work. I've tried using between but it does not seem to work either. What is the correct way of implementing this on sequelize ? what is wrong with the query below ? Thank you.
#My code
if (query && query.startDate && query.endDate) {
  query = {
    createdAt: {
      [Op.between]: [query.startDate, query.endDate],
    },
  };
}

#also have tried
if (query && query.startDate && query.endDate) {
      query = {
        [Op.and]: [
          { createdAt: { [Op.gte]: query.startDate } },
          { createdAt: { [Op.lte]: query.endDate } },
        ],
      };
    }

#query at the console
query {
  '$skip': '0',
  '$limit': '25',
  startDate: '2020-07-19',
  endDate: '2020-07-20'
}

A: Here is some demo code for example
// building query string to
    buildQuery(query) {
        var whereClause = {

        };
        // pms filter is necessery
        if(query && query.pms_id) {
            whereClause['pms_id'] = query.pms_id;
         }
        // checkin date filter
        if(query && query.start_date) {
            const arrivalFrom = moment(query.start_date).subtract(2, 'months').format('YYYY-MM-DD');
            whereClause['checkin_date'] >  arrivalFrom;
        } else {
            const arrivalFrom = moment().subtract(2, 'months').format('YYYY-MM-DD');
            whereClause['checkin_date'] >  arrivalFrom;
        }
        // checkout date filter
        if(query && query.end_date) {
            const arrivalFrom = moment(query.end_date).add(2, 'months').format('YYYY-MM-DD');
            whereClause['checkout_date'] <  arrivalFrom;
        } else {
            const arrivalFrom = moment().add(2, 'months').format('YYYY-MM-DD');
            whereClause['checkout_date'] <  arrivalFrom;
        }
        return whereClause;
    }
// query for getting bookings related to user
    getBookings(user_id,query="") {
        return bookingModel.findAndCountAll({
            where: this.buildQuery(query),
            include:[
                { model:pmsModel,
                  where: { user_id:  user_id},
                  required:false
                  },
                  {
                      model: propertyModel,
                      required:false
                  },
                  {
                    model: roomModel,
                    required:false
                }
                ],
        });
    }


text:
Q: Apple Script - Mark all files and/or folders within a specific folder as hidden I am familiar with the terminal command chflags hidden [file path]. But I would like to know how to apply it to all files and folders within a specific folder. I would like to run this command from within applescript using do shell script "...". How do I do this?

A: From man chflags, the -R option will also act upon the entire contents of a directory:
chflags -R hidden <file>


text:
Q: deploying an ML model on gcloud with numpy c-extensions failed I am trying to deploy a simple Machine Learning model online, so that others can access it online easily. I have tried to to deploy it locally on LocalHost, and it works well. So now, i am trying to deploy it as a web application by using gcloud.
I successfully followed this
https://www.freecodecamp.org/news/how-to-build-a-web-application-using-flask-and-deploy-it-to-the-cloud-3551c985e492/ , though it is not a ML model.
this is a view on my project directory ! (please click to view)(https://drive.google.com/open?id=1AvbZ4ERRsiS19exGPgOm8LfVjk_GWjM8)
i am using a Mac, so my python is 2.7, but as i am using Jupyter Notebook, i am on python 3.7 too. I develop my stuff mostly on Notebook through Anaconda.
This is the main.py:
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/predict',methods=['POST'])
def predict():

    int_features = [int(x) for x in request.form.values()]
    final_features = [np.array(int_features)]
    prediction = model.predict(final_features)

    output = round(prediction[0], 2)

    return render_template('index.html', prediction_text='The Forecast is  {}'.format(output))

@app.route('/results',methods=['POST'])
def results():

    data = request.get_json(force=True)
    prediction = model.predict([np.array(list(data.values()))])

    output = prediction[0]
    return jsonify(output)

if __name__ == "__main__":
    app.run(debug=True)

This is my app.yml:
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /static
  static_dir: static
- url: /.*
  script: main.app

libraries:
  - name: ssl
    version: latest

My appengine_conengine.py:
from google.appengine.ext import vendor
vendor.add('lib')

This is my requirement.txt
Flask
Werkzeug
numpy
sklearn

Then i run this:
pip install -t lib -r requirements.txt

to put the 4 required libraries in a folder named "lib". I do this because when i test run the main.py in Virtualenv, it needs Flask, numpy, and sklearn to successfully deploy on Localhost:5000.
However, when i run:
gcloud app deploy

to upload and deploy my project to gcloud, it says error like this:
1, in <module>
    import numpy as np
  File "/base/data/home/apps/n~sales-forecast-3mv3/20191110t154452.422348864415547477/lib/numpy/__init__.py", line 142, in <module>
    from . import core
  File "/base/data/home/apps/n~sales-forecast-3mv3/20191110t154452.422348864415547477/lib/numpy/core/__init__.py", line 47, in <module>
    raise ImportError(msg)
ImportError:

Importing the numpy c-extensions failed.
- Try uninstalling and reinstalling numpy.
- If you have already done that, then:
  1. Check that you expected to use Python2.7 from "/base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_dist/python",
     and that you have no directories in your PATH or PYTHONPATH that can
     interfere with the Python and numpy version "1.17.3" you're trying to use.
  2. If (1) looks fine, you can open a new issue at
     https://github.com/numpy/numpy/issues.  Please include details on:
     - how you installed Python
     - how you installed numpy
     - your operating system
     - whether or not you have multiple versions of Python installed
     - if you built from source, your compiler versions and ideally a build log

- If you're working with a numpy git repository, try `git clean -xdf`
  (removes all files not under version control) and rebuild numpy.

Would anyone please help? thank you very much.

A: You have to specify in your app.yaml the numpy library as followed:
app.yaml
runtime: python27
api_version: 1
threadsafe: true

handlers:
  - url: /static
    static_dir: static
  - url: /.*
    script: main.app

libraries:
  - name: ssl
    version: latest
  - name: numpy
    version: "1.6.1"


text:
Q: MFP 8 Push Notification to Particular USER ID Trying to send Push Notification based on DEVICE_ID, In MFP 8 Console, My device ID is showing under DEVICES section but if i try to send notification, Console throws error as "An error occurred while the notification was sent. Internal server error. No devices found."
Scope - push.mobileclient
Initialize, isPushSupported and then RegisterDevice is triggered and in logs, it shown the token as well. how to resolve ?

A: Device registration showing up in the Devices console does not mean that push registration is successful. Even if push registration is complete, it will depend entirely on the application logic that there is a user identity associated with the subscription.
When you attempt to send notification by userid and it says "No devices found", this means that there are no subscriptions against this userid. It is possible there is no subscription at all , or the subscriptions have been made against a different user - or even anonymous user.
Use get push registrations and get push subscriptions REST calls to verify your current registration and subscription. If these are with anonymous user identity verify your scope -> security check mapping and your application logic.


text:
Q: Parallel async queries with GraphQL for .NET and EF Core 3.0 Summary
I am currently migrating a project to AspNetCore 3.0 and are running into a issue with the GraphQL for .NET ParallelExecutionStrategy when querying for multiple things in one query. The project is using a MSSQL Server as the data store and it is access through Entity Framework Core 3.0. The error I get is:

A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.

I can resolve the issue if I implement IDocumentExecuter and change the ParallelExecutionStrategy to await each individual execution, from Task.WhenAll to await ExecuteNodeAsync (https://github.com/graphql-dotnet/graphql-dotnet/blob/master/src/GraphQL/Execution/ParallelExecutionStrategy.cs#L27).
Example query that I'm trying to execute:
query {
  thingA {
    id
  }
  thingB {
    id
  }
}

Edit:
Using DbContextPool doesn't seem to solve the problem either:
services.AddDbContextPool<DBCONTEXT>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("CONNECTIONSTRING")));

A: If you are using the built-in dependency injection container, you should consider using an IServiceScopeFactory<T>. It's essentially the same approach as Ganhammar's "StructureMap" based answer, except it's not a "Service Locator". The (relatively simple) IServiceScopeFactory<T> code is here and another answer related to this question is here.

A: We are using StructureMap for dependency injection, which is creating a new DbContext per HttpRequest, but we needed a unique DbContext for each query, the solution was to create a nested container and request the dependencies through the nested container.
public Constructor(IContainer container) => _dbContext = container.GetNestedContainer()
    .GetInstance<DbContext>();

A: See my implementation that solves this proboem.
The "trick" is create scope at resolver level
https://github.com/fenomeno83/graphql-dotnet-globalization-demo


text:
Q: Assign Graph API App Permissions to Managed Identity in Azure DevOps Pipeline - Authorization_RequestDenied I have the the following cobbled together from various sources in my devops pipeline:
$MIName= "my-identity-test-mi"
$RGName = "my-identity-test-rg"
$Location = "eastus"
$GraphAppId = "00000003-0000-0000-c000-000000000000"
$PermissionName = "Directory.Read.All"

New-AzResourceGroup -Name $RGName -Location $Location -Force

Install-Module -Name "Az.ManagedServiceIdentity" -Force

New-AzUserAssignedIdentity -ResourceGroupName $RGName -Name $MIName

Install-Module -Name "AzureAD" -Force

$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext

$graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, `
                        $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, `
                        $null, "https://graph.microsoft.com").AccessToken

$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, `
                    $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, `
                    "https://graph.windows.net").AccessToken

Write-Output "ID $($context.Account.Id)"

Write-Output "Account $($context.Account)"

Write-Output "Type $($context.GetType())"

Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken

$MSI = (Get-AzureADServicePrincipal -Filter "displayName eq '$MIName'")

$GraphServicePrincipal = Get-AzureADServicePrincipal -Filter "appId eq '$GraphAppId'"

$AppRole = $GraphServicePrincipal.AppRoles | Where-Object {$_.Value -eq $PermissionName -and $_.AllowedMemberTypes -contains "Application"}

New-AzureAdServiceAppRoleAssignment -ObjectId $MSI.ObjectId -PrincipalId $MSI.ObjectId -ResourceId $GraphServicePrincipal.ObjectId -Id $AppRole.Id

I have given the service principal that my pipeline runs as the following permissions:

But when my pipeline runs I get:
Error occurred while executing NewServicePrincipalAppRoleAssignment
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
RequestId: d06466ff-a2b9-4b3f-a5d8-43aa5e6e107c
DateTimeStamp: Sat, 17 Jul 2021 15:59:01 GMT
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
PowerShell exited with code '1'.

This is not a case of run it twice and it works as seen that issue referenced so I'm guessing I've not quite got the permissions of my devops service principal correct but can't for the life of me work out what those permissions should be!
Any advice appreciated


text:
Q: How to get CGI::Session cookie in VBA? I want to get cookie information from "https://www.kent-web.com/pwd/protect/enter.cgi" whose ID and PW is both "guest".
I write the following code refering "https://stackoverflow.com/questions/39709562/how-to-set-and-get-jsessionid-cookie-in-vba"
I tried following code however I couldn't get any cookie information.
Sub Test()
    Dim sUrl, sRespHeaders, sRespText, aSetHeaders, aList
    sUrl = "https://www.kent-web.com/pwd/protect/enter.cgi"
    XmlHttpRequest "POST", sUrl, Array(), "id=guest&pw=guest&login=LOG+IN", sRespHeaders, sRespText'Sending ID, PW and LOG+IN
End Sub

Sub XmlHttpRequest(sMethod, sUrl, aSetHeaders, sPayload, sRespHeaders, sRespText)
    Dim aHeader, strCookie
    With CreateObject("MSXML2.ServerXMLHTTP")
        .Open sMethod, sUrl, False
        For Each aHeader In aSetHeaders
            .SetRequestHeader aHeader(0), aHeader(1)
        Next
        .SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        .SetRequestHeader "Connection", "keep-alive"
        .Send (sPayload)
        sRespHeaders = .GetAllResponseHeaders'"set-cookie: CGISESSID=" can be obtained by browser. However the cookie value is empty via VBA
        sRespText = .ResponseText
        strCookie = .GetResponseHeader("Set-Cookie")
    End With
End Sub

I can get cookie information by the following C# code, however I need to get it through VBA.
    using System.IO;
    using System.Net;
    using System.Text;

    static void Main(string[] args)
    {
        var url = "https://www.kent-web.com/pwd/protect/enter.cgi";
        var req = (HttpWebRequest)WebRequest.Create(url);
        var cookieContainer = new CookieContainer();
        req.CookieContainer = cookieContainer;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        string postData = "id=guest&pw=guest&login=LOG+IN";
        var data = Encoding.ASCII.GetBytes(postData);
        req.ContentLength = data.Length;

        using (Stream stream = req.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);

            using (var res = (HttpWebResponse)req.GetResponse())
            {
                CookieCollection cookies = cookieContainer.GetCookies(new System.Uri(url));
            }
        }
    }


text:
Q: Check whether array has only constant entries? I have an array arr with n entries. Now I want to check whether
arr[[1]]==arr[[2]]&&arr[[2]]==arr[[3]]&&...arr[[n-1]]==arr[[n]]

Of course I could use a for-loop, like
arr = {0, 1, 0, 0};
IsConst = True;
For[i = 1, i <= Length[arr], i++,
  If[arr[[i]] != arr[[1]],
    IsConst = False;
    i = Length[arr];
  ];
];
Print[IsConst];

But that doesn't look too fast, so I wonder whether there is a faster way.

A: You can Apply (@@) Equal to your list:
constantQ = Equal@@#&;

constantQ @ {0,1,0,0}
(* False *)

or
constantQ2 = Max@#==Min@# &;
constantQ3 = Variance@#==0;
constantQ4 = Length@DeleteDuplicates@# == 1 &;

See also: SameQ
constantQ5 = SameQ @@ #&

Equal @@ {1, 1., 1}
(* True *)
SameQ @@ {1, 1., 1}
(* False *)

...

A: Not sure why people don't like DeleteDuplicates :)
Length@DeleteDuplicates@arr > 1

for me this is faster than other methods (using V9 OS X tonight)

A: If[Length[Tally[arr]] == 1, IsConst = True, IsConst = False]

A: Maybe the fastest is... just to compile the OP code
sameQ = Compile[{{arr, _Integer, 1}},
   Module[{IsConst = True, i},
    For[i = 1, i <= Length[arr], i++,
     If[arr[[i]] != arr[[1]],
      IsConst = False;
      Break[];
      ]];
    IsConst], CompilationTarget -> "C", "RuntimeOptions" -> "Speed"];

arr = ConstantArray[1, 10000000];
arr[[-1]] = 0;

sameQ[arr] // AbsoluteTiming
(* {0.027877, False} *)

constantQ4@arr // AbsoluteTiming (* fastest kguler's test *)
(* {0.062203, False} *)

A: This problem is in a manner an converse of How do you check if there are any equal arguments(even sublist) in a list? and is related to How do I check if any element in a list is positive? As with both of those there is a choice in approach of either scanning the entire light with a fast, vectorized operation, or providing for an early-exit behavior.  Which one is desirable will depend on the most commonly tested expression form.  Please review my answer to the second linked question for examples.
Using Tally or Max and Min are examples of methods that scan the entire list without the possibility of an early exist.
The length of the list can also affect the performance of the methods used.  For example, as noted here UnsameQ works well on short lists (few arguments) but not on long ones.   That doesn't appear to be the case with Equal and SameQ however so both of those are good general methods for your problem, and provide early exist behavior.  You can choose between numeric and structural equivalence.  kguler already showed these but repeated for completeness:
Equal @@ {1, 1, 1, 1}
SameQ @@ {1, 1, 1, 1}

True
True

Equal @@ {1, 1, 2, 1}
SameQ @@ {1, 1, 2, 1}

False
False

Equal @@ {1, 1, 1.0, 1}
SameQ @@ {1, 1, 1.0, 1}

True
False

To bring a unique method to this answer we can also use pattern matching for structural equivalence:
MatchQ[{1, 1, 1, 1}, {x_ ..}]
MatchQ[{1, 1, 2, 1}, {x_ ..}]

True

False

By naming the Pattern (x_) we restrict it to matching a particular expression.  See:

*

*Pattern to match a non-empty list of non-empty lists


text:
Q: Question on Geometry I have a B.Ed in Management, but recently developed interest in geometry & would love to study it on my own. Do i need or must have a B.A in Maths before doing this ?

A: No degree is needed to study math on one's own. And the "knowledge base" in mathematics that one acquires by completing a B.S. in mathematics is not a prerequisite for studying geometry in depth. If you have a passion to study geometry, dig in, starting just where you are!
A nice start might be refreshing your algebra-precalculus skills and reviewing and studying some of the Khan Academy video lectures and lessons on Geometry to cover the basics. Additionally, you might be obtaining a copy of Marvin Greenberg's Euclidean and Non-Euclidean Geometry, and work your way through it.


text:
Q: Javascript Variable Scope Issue - Error: TypeError: this.graphics is undefined I know this issue has been done to death, but I still don't understand it. I've read StackOverFlow's very own "this" keyword explanation (along with the Mike West article within it) as well as other scope related questions. I don't know why I don't get it, so I look to the more savvy JavaScript developer for help.
From the code and comments it should be fairly self explanatory. But it is querying an ESRI map service, returning graphics and placing these on the map.
But the issue is in the showResults function where I call this.graphics, which is the map's graphics property (a graphics layer). I'm aware it's now out of scope (which took more time to figure out than I'd like to admit), but how can I put it back in scope so I can use it? Even if I have alter the code substantially...
define([
"dojo/_base/declare",
"dojo/on",
"dijit/_WidgetBase",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
"dijit/form/Button",
"dijit/form/Form",
"dijit/form/FilteringSelect",
"dijit/form/ValidationTextBox",
"dojo/_base/array",
"dojo/_base/Color",
"dojo/_base/lang",
"esri/tasks/find",
"dojo/text!./Find/templates/Find.html"
], function(declare, on, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Button, Form, FilteringSelect, ValidationTextBox, array, Color, lang, find, FindTemplate) {

//anonymous function to load CSS files required for this module
(function() {
    var css = [require.toUrl("gis/dijit/Find/css/Find.css")];
    var head = document.getElementsByTagName("head").item(0),
        link;
    for(var i = 0, il = css.length; i < il; i++) {
        link = document.createElement("link");
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = css[i].toString();
        head.appendChild(link);
    }
}());

// Query Dijit
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
    widgetsInTemplate: true,
    templateString: FindTemplate,
    graphics: null,
    findTask: null,
    findParams: null,
    results: [],
    serverError: null,
    queryLayer: null,
    searchText: null,
    postCreate: function() {
        // Method is used to call a superclass method. It's good practice to assume that you are overriding a method that may
        // do something important in a class up the inheritance chain
        this.inherited(arguments);

        // Create graphics layer and add it to the map
        this.graphics = new esri.layers.GraphicsLayer({id:"queryGraphics"});
        this.map.addLayer(this.graphics);

        // Create find task with url to map service
        this.findTask = new esri.tasks.FindTask("arcgis/rest/services/MapServer");

        // Create find parameters and define known values
        this.findParams = new esri.tasks.FindParameters();
        this.findParams.outSpatialReference = this.map.spatialReference;
        this.findParams.returnGeometry = true;
        this.findParams.layerIds = [1];
        this.findParams.searchFields = ["OBJECTID", "Gauge ID", "FV_ID", "FDC_ID", "Flood_Stage", "Flood_Line", "Municipality", "WATERSHED"];

        // Listen for Submit button click
        on(this.submitButton, 'click', lang.hitch(this, 'execute'));
    },
    // Submit button click event
    execute: function execute() {
        // Set the WHERE search text
        this.findParams.searchText = dojo.byId("searchText").value;
        // Sends a request to the ArcGIS REST map service resource to perform a search based
        // on the FindParameters specified in the findParameters argument. On completion, the
        // onComplete event is fired and the optional callback function is invoked.
        this.findTask.execute(this.findParams, this.showResults, this.showError);
    },
    // Fires when the find operation is complete and returns an array of FindResult
    showResults: function showResults(results) {
        this.graphics.clear();
        // Build an array of attribute information and add each found graphic to the map
        dojo.forEach(results, function(result) {
            var symbol;
            switch(result.feature.geometry.type) {
                case "point":
                    symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new Color([255, 0, 0]), 1), new Color([255, 0, 0, 1.0]));
                    break;
                case "polyline":
                    symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH, new Color([255, 0, 0]), 1);
                    break;
                case "polygon":
                    symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.0]));
                    break;
                default:
                    symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new Color([255, 0, 0]), 1), new Color([255, 0, 0, 1.0]));
            }
            var graphic = new esri.Graphic(result.feature.geometry, symbol);
            this.graphics.add(graphic);
        });
    },
    // Fires if the find execution fails to complete
    showError: function showError(serverError) {
        alert("The server encountered an error. Error: " + serverError);
    }
});
});

UPDATE AFTER ANSWERS:
So, it wasn't one answer that solved this but a combination of two. I incorporated Buffalo's answer of
this.findTask.execute(this.findParams, lang.hitch(this, this.showResults), this.showError);

and Buffalo's comment to Craig's answer of
dojo.forEach(results, function(result) {
...
}, this);

but Craig's would have worked here as well. This combined with Tamil's answer I'm most certain would have worked too.
So I'll mark Buffalo's as the answer, but all three are worth looking at for any further readers.

A: You could use Function.bind(Beware! its not supported in all the browsers).
Change:
this.findTask.execute(this.findParams, this.showResults, this.showError);

To:
this.findTask.execute(this.findParams, this.showResults.bind(this), this.showError);

Or(If you are concerned about Function.bind browser support):
Use closure & Function.apply
execute: function execute() {
...
...
  var self = this;
  this.findTask.execute(this.findParams, function() {
    self.showResults.apply(self, arguments);
  }, this.showError);
}

A: The hitch method in dojo/_base/lang is going to be your best friend here.  What I assume the findTask function does is exceucte some asynchronous request and then invokes the 2nd param with the results.
First, add dojo/_base/lang to your Dependency list.
Then, change the line
this.findTask.execute(this.findParams, this.showResults, this.showError);

to
this.findTask.execute(this.findParams, lang.hitch(this,this.showResults), this.showError);

What lang#hitch does is take the first parameter (in this case the instance of your widget), and make it be the scope when the second parameter executes.  In this case we want showResults to execute in the current scope.

A: Your problem is with the following code
    dojo.forEach(results, function(result) {

        ...

        this.graphics.add(graphic);
    });

the function being executed does not have the scope of the widget.  Make it:
    dojo.forEach(results, lang.hitch(this, function(result) {

    }));