Q: How to type "line1", "line2", "line3".... using for loop in python For example, I want to generate below output using a "for" loop, having the for loop automatically populate the number at the end of the word line:
line1
line2
line3
line4
line5
line6
line7

A: Here is how to do it with "f-strings" and the range() class object in a for loop:
for_loop_basic_demo.py:
#!/usr/bin/python3

END_NUM = 7
for i in range(1, END_NUM + 1):
    print(f"line{i}")

Run command:
./for_loop_basic_demo.py

Output:
line1
line2
line3
line4
line5
line6
line7

Going further: 3 ways to print
The 3 ways I'm aware of to print formatted strings in Python are:

*

*formatted string literals; AKA: "f-strings"

*the str.format() method, or

*the C printf()-like % operator

Here are demo prints with all 3 of those techniques to show each one for you:
#!/usr/bin/python3

END_NUM = 7
for i in range(1, END_NUM + 1):
    # 3 techniques to print:

    # 1. newest technique: formatted string literals; AKA: "f-strings"
    print(f"line{i}")

    # 2. newer technique: `str.format()` method
    print("line{}".format(i))

    # 3. oldest, C-like "printf"-style `%` operator print method
    # (sometimes is still the best method, however!)
    print("line%i" % i)

    print() # print just a newline char

Run cmd and output:
eRCaGuy_hello_world/python$ ./for_loop_basic_demo.py
line1
line1
line1

line2
line2
line2

line3
line3
line3

line4
line4
line4

line5
line5
line5

line6
line6
line6

line7
line7
line7

References:

*

****** This is an excellent read, and I highly recommend you read and study it!: Python String Formatting Best Practices

*Official Python documentation for all "Built-in Functions". Get used to referencing this: https://docs.python.org/3/library/functions.html

*

*The range() class in particular, which creates a range object which allows the above for loop iteration: https://docs.python.org/3/library/functions.html#func-range

A: You can use f strings.\
n = 7
for i in range(1, n + 1):
    print(f"line{i}")


Q: Getting Facebook Access Token from User Id and Facebook App Secret? I'm trying to understand how the facebook api works. The end goal is to be able to read the posts from a facebook page.
If someone has connected with my app on facebook can my c# application then get the posts from a public facebook page if it knows their facebook account id (and has the facebook app secret hard coded).
If so what are the http requests it needs to make in order to get the access token which can then be used to get the posts, and what are the requests to get a new access token before one expires?
If you could provide an example in c# (maybe using the acebooksdk.net library) that would be great!
Thanks.

A: The way to do it was using "The Login Flow for Web (without JavaScript SDK)" api to get a user access token. A user access token is required to be sent with graph api queries in order to get page posts.
The first step is to create an app on facebook where you specify what information you want the program to be able to access via the graph api. The end user will then choose to accept these permissions later.
The program creates a web browser frame and navigates to https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token
The response type "token" means that when the (embedded) web browser is redirected to the redirect_uri the user access token will be added to the end of the url as a fragment. E.g the browser would end up on the page with url https://www.facebook.com/connect/login_success.html#access_token=ACCESS_TOKEN...
The redirect uri can be anything but facebook has that specific one set aside for this scenario where you are not hosting another server which you want to receive and process the response.
Basically facebook gathers all the information required from the user and then sends them to the redirect_uri. Some information they may require is for them to login and accept permissions your app on facebook requires.
So the program simply keeps an eye on what url the embedded browser is on and when it matches the redirect_uri it parses the url which will contain the data as fragments and can then close the browser.


Q: "Call to undefined method PHPUnit\Framework\TestSuite::sortId()" Error while executing Test Case with Coverage
Call to undefined method PHPUnit\Framework\TestSuite::sortId()

Getting this error while trying to execute test case with coverage.
Command:
phpunit -v --debug ./Test.php --coverage-clover ../clover.xml

Putput: (first two lines)
PHPUnit 9.5.4 by Sebastian Bergmann and contributors.
Runtime:       PHP 7.3.33-1+ubuntu21.10.1+deb.sury.org+1
...

A: It appears that you have different installations of PHPUnit mixed up.
For instance, you may have used Composer to install PHPUnit and have configured the autoloader generated by Composer as PHPUnit's bootstrap script but then you invoke PHPUnit using an executable other than vendor/bin/phpunit.


Q: python csv delimiter doesn't work properly I try to write a python code to extract DVDL values from the input.  Here is the truncated input.
      A V E R A G E S   O V E R   50000 S T E P S

 NSTEP =    50000   TIME(PS) =     300.000  TEMP(K) =   300.05  PRESS =   -70.0
 Etot   =    -89575.9555  EKtot   =     23331.1725  EPtot      =   -112907.1281
 BOND   =       759.8213  ANGLE   =      2120.6039  DIHED      =      4231.4019
 1-4 NB =       940.8403  1-4 EEL =     12588.1950  VDWAALS    =     13690.9435
 EELEC  =   -147238.9339  EHBOND  =         0.0000  RESTRAINT  =         0.0000
 DV/DL  =        13.0462
 EKCMT  =     10212.3016  VIRIAL  =     10891.5181  VOLUME     =    416404.8626
                                                Density    =         0.9411
 Ewald error estimate:   0.6036E-04

      R M S  F L U C T U A T I O N S

 NSTEP =    50000   TIME(PS) =     300.000  TEMP(K) =     1.49  PRESS =   129.9
Etot   =       727.7890  EKtot   =       115.7534  EPtot      =       718.8344
BOND   =        23.1328  ANGLE   =        36.1180  DIHED      =        19.9971
1-4 NB =        12.7636  1-4 EEL =        37.3848  VDWAALS    =       145.7213
EELEC  =       739.4128  EHBOND  =         0.0000  RESTRAINT  =         0.0000
DV/DL  =         3.7510
EKCMT  =        76.6138  VIRIAL  =      1195.5824  VOLUME     =     43181.7604
                                                Density    =         0.0891
 Ewald error estimate:   0.4462E-04

Here is the script.  Basically we have a lot of DVDL in the input (not in the above truncated input) and we only want the last two.  So we read all of them into a list and only get the last two.  Finally, we write the last two DVDL in the list into a csv file. The desire output is
13.0462, 3.7510
However, the following script (python 2.7) will bring the output like this.  Could any guru enlighten?  Thanks.
13.0462""3.7510""
Here is the script:
import os
import csv

DVDL=[]
filename="input.out"
file=open(filename,'r')

with open("out.csv",'wb') as outfile: # define output name
    line=file.readlines()
    for a in line:
        if ' DV/DL  =' in a:
            DVDL.append(line[line.index(a)].split('        ')[1])  # Extract DVDL number

    print DVDL[-2:]        # We only need the last two DVDL
    yeeha="".join(str(a) for a in DVDL[-2:])
    print yeeha
    writer = csv.writer(outfile, delimiter=',',lineterminator='\n')#Output the list into a csv file called "outfile"
    writer.writerows(yeeha)

A: As the commenter who proposed an approach has not had the chance to outline some code for this, here's how I'd suggest doing it (edited to allow optionally signed floating point numbers with optional exponents, as suggested by an answer to Python regular expression that matches floating point numbers):
import re,sys

pat = re.compile("DV/DL += +([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)")
values = []
for line in open("input.out","r"):
    m = pat.search(line)
    if m:
        values.append(m.group(1))
outfile = open("out.csv","w")
outfile.write(",".join(values[-2:]))

Having run this script:
$ cat out.csv
13.0462,3.7510

I haven't used the csv module in this case because it isn't really necessary for a simple output file like this. However, adding the following lines to the script will use csv to write the same data into out1.csv:
import csv

writer = csv.writer(open("out1.csv","w"))
writer.writerow(values[-2:])


Q: Perl (opendir): Receiving "Can't use an undefined value as a symbol reference at line 46." I am trying to use opendir to open a directory. When ever this happens I get the error: "Can't use an undefined value as a symbol reference at line." From searching other questions this usually originates from trying to use a variable that is out of scope. From all that I can tell my variable that I am using for my directory location is in scope and my handler for opendir is defined in the function like all examples. Please help me figure out what is going wrong. Line 46 where it is claiming the error is at is double starred.
use File::Find;
use File::Copy;
use File::Path;

my @imagelocations = ('/some/location1','/some/location2');
my $destination = '/some/location';

foreach $a (@imagelocations)
{
    find (\&Move_Images, $a);
}

sub Move_Images
{
     my $file = $_;
     if (-e $file && $File::Find::dir eq $a && $file ne ".")
     {
        if (-M $file < 1)
        {
            my @folder = split(/_/, $file);
            my ($var1,$var2,$var3) = @folder[0,1,4];
            if (lc $var1 ne "manual" && lc $var1 ne "test")
            {
                if (-d ($File::Find::dir.'/'.$file))
                {
                    $var3 = substr ($var3,1,-2);
                    my $open = $File::Find::dir."/$file";
                    **opendir (my $dh, $open) or die "Can't open directory $!";**
                    my @files = readdir($dh);
                    ...


Q: How to fix unexpected token in ESLint? I install ESLint globally using the command npm install -g eslint on my Mac. It was successful installing, but when I run eslint -v this is the issue I encounter:
$ npm install -g eslint
path/to/bin/eslint -> path/to/lib/node_modules/eslint/bin/eslint.js
+ eslint@7.3.1
added 107 packages from 63 contributors in 4.823s

$ eslint -v
path/to/lib/node_modules/eslint/bin/eslint.js:93
        } catch {
                ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

I would like to know what are the missing steps that cause this issue? I'm using Node.js v8.16.2 and NPM v6.4.1.

A: The error happens because } catch { is a relatively recent (ES2019) language feature called "optional catch binding"; prior to its introduction, binding the caught error (e.g. } catch (err) {) was required syntactically. Per node.green, you need at least Node 10 to have that language feature.
So why does this happen in ESLint? Per e.g. the release blog, version 7 has dropped support for Node 8; they're no longer testing against that version and more modern language features will be assumed to be supported.
To fix it, either:

*

*Upgrade Node (Node 8 is out of LTS, which is why ESLint dropped support); or

*npm install eslint@6 (with -g if you want to install globally) to use the older version of ESLint with Node 8 support.

A: In case it's helpful for anyone, I had a slightly different twist on the other answer. In my case, the error was happening during the Travis CI build process and causing it to fail. The solution in my case was to update my .travis.yml file to node_js: "16"


Q: IE11 emulates IE7 even though it's set to EDGE My website has the following settings:

But IE11 renders the page in IE7 mode:

This is on a machine with a fresh IE11 install, and it's the first time I'm visiting the website with the browser.
Any idea what could be wrong?

A: Does moving the X-UA-Compatible  tag to be immediately underneath the  tag make a difference?
See answer by neoswf:
X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode
Cheers,


Q: How to create read-only user in pgAdmin 4? Creating a read-only user in pgAdmin 4 is a little tricky.
Here is a guide on how I did it.
First of all a few words about the process.
The whole process is based on editing a schema (very simple and safe) for your DB, so this creates limitations for using the method for all the DBs you have unless you edit schemas for each DB (again, it is easy).
First, we have to open a main dialogue, select the target DB you need the read-only user for -> Schemas -> right mouse click on "public" schema -> Properties.

In the opened window go to "Default privileges" and click the "+" in the right corner.

*

*In the "Grantee" column enter: "pg_read_all_data",

*in "Privileges" column click on the field and you will see options. Enable only "Select".

On the rest tabs (Sequences, Functions, Types) you can do the same (Select or Usage).
Hit "Save".
In the left sidebar scroll down and find "Login/Group Roles". Click right button -> Create -> Login/Group Role.
OR if you have an existed user role you want to make read-only, click the right button on it and select "Properties".
In the opened window enter the name of the user, on the "Definition" tab enter a password, on the "Previliges" tab select "Can login" and "Inherit rights from the parent roles?"
In the "Membership" tab hit "+" in the "Member of" table and type "pg_read_all_data" into the "User/Role" column.

In the "Parameters" tab hit "+".
Select "role" in the "Name" column's dropdown,
type "pg_read_all_data" in the "Value" column.
In the "Database" column select the desired DB (where you have edited the schema in the previous steps).
Note, you can add more rows with the same settings for different databases (of course, if those DBs have edited schemas as shown above).

Click "Save".
Now you can log into your PhpPgAdmin (or psql or wherever you need) under this user and do only selects. A real read-only user role.

I hope it will help someone.

A: I don't have enough reputation to comment on your very helpful post, but wanted to add that the public schema by default gives full access to the PUBLIC role (implicit role that all users belong to).
So you would first need to revoke this access.
This can be done in pgAdmin in the Security tab of the schema properties dialog, or with the SQL command
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

See also:

*

*Issue creating read-only user in PostgreSQL that results in user with greater permission with public schema

*PostgreSQL - Who or what is the "PUBLIC" role?


Q: Grouping rows with Groupby and converting date & time of rows of start date-time and end date- time columns I have a dataset looking like this:

Blast Hole East Coordinate North Coordinate Collar Theoritical Depth Tag Detector ID Date and Time Detection_Location Detection Date & Time
64 16745.42 107390.32 2634.45 15.95 385656531 23-08-2018 2:39:34 PM CV23 2018-09-08 14:18:17
61 16773.48 107382.6 2634.68 16.18 385760755 23-08-2018 2:38:32 PM CV23 2018-09-08 14:24:19
63 16755.07 107387.68 2634.58 16.08 385262370 23-08-2018 2:39:30 PM CV23 2018-09-08 14:12:42
105 16764.83 107347.67 2634.74 16.24 385742468 23-08-2018 2:41:29 PM CV22 2018-09-06 20:02:46
100 16752.74 107360.32 2634.33 15.83 385112050 23-08-2018 2:41:08 PM CV22 2018-09-06 20:15:42
99 16743.1 107362.96 2634.36 15.86 385087366 23-08-2018 2:41:05 PM CV22 2018-09-06 20:49:21
35 16747.75 107417.68 2635.9 17.4 385453358 23-08-2018 2:36:09 PM CV22 2018-09-23 05:47:44
5 16757.27 107452.4 2636 17.5 385662254 23-08-2018 2:35:03 PM CV22 2018-09-23 05:01:12
19 16770.89 107420.83 2634.81 16.31 385826979 23-08-2018 2:35:50 PM CV22 2018-09-23 05:52:54

I intended to group all the rows having 3 detections at one place ( in column Detection_location) in one hour.
I used the following code for grouping the rows falling in one hour per 3 detection:
df2 = df1.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'),
      df1.Detection_Location]).size().reset_index(name = 'Tags')

This code gave me a result like this:

I would rather like to have result in which each rows have start time when the first detection was there in that hour and when the last detection was seen and thus i would like to have a result like this:

This is the required output:

Detection Date & Time - Start  Detection Date & Time - End Detection_Location Tags
2018-09-06 20:02:46 2018-09-06 20:49:21 CV22 3
2018-09-08 14:12:42 2018-09-08 14:24:19 CV23 3
2018-09-23 05:01:12 2018-09-23 05:47:44 CV22 3

Can anyone suggest what else should i add in my group-by function to get this result.
Thanks

A: Check if this works for you. Inside the aggregate function, you can pass all the values that you want to capture.
df2 = (df.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'),df.Detection_Location],sort=False)['Detection Date & Time']
   .agg(['first','last','size'])).reset_index().rename(columns={"first": "Detection Date & Time - Start", "last": "Detection Date & Time - End", "size": "Tags"})


Q: Linking to iOS simulator binaries on OSX I was curious what would happen if I linked to an iOS simulator framework in a Mac app. So I copied UIKit to it's own folder (so the Framework search path wouldn't include all the iOS simulator framework, as like CoreFoundation is both on Mac and iOS but has different headers), and dragged it into the link section in Xcode. The error Xcode gave me was:

building for MacOSX, but linking against dylib built for iOS Simulator
  file '/Users/jonathan/Desktop/macuikit/UIKit.framework/UIKit' for
  architecture x86_64

Both architectures are x86_64, so how can it tell the framework is specifically for the iOS simulator, I removed all references to iOS in things like Info.plist, even tried deleted everything but the UIKit binary, but the same error came up. Is there something in the binary it self that tells the linker which platform it can run on, rather than just the architecture? I looked at the Mach-O header but there is only fields for CPU type and subtype, and neither has a value for the simulator as expected.

A: After a little bit of digging, it turns out that the platform on which the library can run on is indeed specified in the binary. In fact, you can edit the binary in your favorite Hex editor and make the linker skip this check entirely.
This information is not specified in the Mach-O header (as you have already realized). Instead, it is specified as a load command type. You can see the available types by digging through the LLVM sources. Specifically, the enum values LC_VERSION_MIN_MACOSX and LC_VERSION_MIN_IPHONEOS look interesting.
Now, find the offset for this in our binary. Open the same in MachOView (or any other editor/viewer or your choice) and note the offset:

Once the offset is noted, jump to the same in a Hex editor and update it. I modified LC_VERSION_MIN_IPHONEOS (25) to LC_VERSION_MIN_MACOSX (24)
Save the updates and try linking again. The error should go away. Of course, you will hit other issues when you try to actually run your example. Have fun with LLDB then :)


Q: Find all the combinations that return a particular value from a function This is a variation on finding all the combinations that add to a target, with two constraints:

*

*We have a limited set of numbers to work with.

*The numbers must result in the target number when fed into a separate function.

In this case, the limited set of numbers include 25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400, etc.
And the function is to add the values together and then multiply by a number based on how many numbers we had:

*

*If 1 number, multiply by 1.

*If 2 numbers, multiply by 1.5

*If 3-6 numbers, multiply by 2

*If 7-10 numbers, multiply by 2.5

*If >10 numbers, multiply by 3

Examples:
[50, 50, 50] => 300
[100, 100] => 300
Target numbers include 300, 600, 900, 1500, 3000, 3600, 4400, 5600, 6400, 7600, 9600, etc.
My intuition is that this can't be done recursively, because each step doesn't know the multiplier that will eventually be applied.

A: Here's a recursive example in JavaScript that seems to answer the requirements:

function getNextM(m, n){
  if (n == 1)
    return 1.5;
  if (n == 2)
    return 2;
  if (n == 6)
    return 2.5;
  if (n == 10)
    return 3;

  return m;
}

function g(A, t, i, sum, m, comb){
  if (sum * m == t)
    return [comb];

  if (sum * m > t || i == A.length)
    return [];

  let n = comb.length;

  let result = g(A, t, i + 1, sum, m, comb);

  const max = Math.ceil((t - sum) / A[i]);

  let _comb = comb;

  for (let j=1; j<=max; j++){
    _comb = _comb.slice().concat(A[i]);
    sum = sum + A[i];
    m = getNextM(m, n);
    n = n + 1;
    result = result.concat(g(
      A, t, i + 1, sum, m, _comb));
  }

  return result;
}

function f(A, t){
  return g(A, t, 0, 0, 1, []);
}

var A = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400];

var t = 300;

console.log(JSON.stringify(f(A, t)));

A: I wrote a small script in Python3 that may solve this problem.
multiply_factor = [0,1,1.5,2,2,2,2,2.5,2.5,2.5,2.5,3]
def get_multiply_factor(x):
    if x< len(multiply_factor):
        return multiply_factor[x]
    else:
        return multiply_factor[-1]

numbers = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400]
count_of_numbers = len(numbers)

# dp[Count_of_Numbers]
dp = [[] for j in range(count_of_numbers+1)]

#Stores multiplying_factor * sum of numbers for each unique Count, See further
sum_found =[set() for j in range(count_of_numbers+1)]

# Stores Results in Unordered_Map for answering Queries
master_record={}

#Initializing Memoization Array
for num in numbers:
    dp[1].append(([num],num*get_multiply_factor(1)))

for count in range(2,count_of_numbers+1):   # Count of Numbers
    for num in numbers:
        for previous_val in dp[count-1]:
            old_factor = get_multiply_factor(count-1)   #Old Factor for Count Of Numbers = count-1
            new_factor = get_multiply_factor(count)     #New Factor for Count Of Numbers = count

            # Multiplying Factor does not change
            if old_factor==new_factor:
                # Scale Current Number and add
                new_sum = num*new_factor+previous_val[1]
            else:
                #Otherwise, We rescale the entire sum
                new_sum = (num+previous_val[1]//old_factor)*new_factor

            # Check if NEW SUM has already been found for this Count of Numbers
            if new_sum not in sum_found[count]:
                # Add to current Count Array
                dp[count].append(([num]+previous_val[0],new_sum))
                # Mark New Sum as Found for Count Of Numbers = count
                sum_found[count].add(new_sum)
                if new_sum not in master_record:
                    # Store Seected Numbers in Master Record for Answering Queries
                    master_record[new_sum] = dp[count][-1][0]

# for i in dp:
#   print(i)
print(master_record[1300])
print(master_record[300])
print(master_record[2300])
print(master_record[7950])
print(master_record[350700.0])

Output :-
[100, 100, 450]
[100, 100]
[25, 25, 1100]
[25, 50, 3900]
[1800, 5900, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400]
[Finished in 0.3s]

My Algo in a nutshell.
Iterate over Count[2, Limit], I've considered limit = Number of Elements
    Iterate over List of Numbers
        Iterate over Sums found for previous count.
            Calculate New Sum,
            If it does not exist for current count, update.

I am assuming that the number of queries will be large so that memorization pays off. The upper limit for count may break my code as the possibilities may grow exponentially.


Q: Multiple widget changes based on one button event in Kivy I'm trying to build this application which contains multiple buttons. I can bind each button event to a callback but I am not able to change the state (namely the label) of any other button except for the one that fired the event. Does anyone know how to do this?

A: All you need is a reference to the other button, then you can do other_button.text = 'whatever'.
The way to do this depends on how you've constructed the program. For instance, if you constructed in the program in kv language, you can give your buttons ids with id: some_id and refer to them in the callback with stuff like on_press: some_id.do_something().
In pure python, you could keep references to the button in the parent class when you create them (e.g. self.button = Button()) so that the callback can reference self.button to change it. Obviously that's a trivial example, but the general idea lets you accomplish anything you want.

A: Probably not the official way, but try out the following code. It will change the text property of the buttons...
Ezs.kv file:
 #:kivy 1.8.0

<Ezs>:
    BoxLayout:
        orientation: 'vertical'
        padding: 0
        spacing: 6

        #choose
        Button:
            id: btn_1
            text: 'text before'
            on_press: btn_2.text = 'Whatever'
            on_release: self.text = 'Who-Hoo'
        #choose
        Button:
            id: btn_2
            text: 'Press this'
            on_release: self.text = 'HEEYY'
            on_press: btn_1.text = 'text after'

.py file:
class Ezs(BoxLayout):

class EzsApp(App):

    def build(self):
        return Ezs

if __name__ == '__main__':
    EzsApp().run()


Q: C++ CLI error C3767: candidate function(s) not accessible I'm new to C++ CLI coming from unmanaged C++ world.
I'm getting this error:
candidate function(s) not accessible

when I pass a std::string as part of the method argument.
Here's the exact code:
Lib Project (compiled as .dll project)
//Lib.h
#pragma once

public ref class Lib
{
public:
  Lib(void);

public:
  void Extract( std::string& data_ );
};

//Lib.cpp
#include "Lib.h"

Lib::Lib(void)
{
}

void Lib::Extract( std::string& data_ )
{
  data_.empty();
}

LibTest Project (compiled as application.exe)
// LibTest.h
#pragma once

ref class LibTest
{
public:
  LibTest(void);
};

// LibTest.cpp
#include "LibTest.h"

LibTest::LibTest(void)
{
  Lib^ lib = gcnew Lib;
  lib->Extract( std::string("test") );
}

int main()
{
  return 0;
}

Compiler Error:
1>------ Build started: Project: LibTest, Configuration: Debug Win32 ------
1>Compiling...
1>LibTest.cpp
1>.\LibTest.cpp(7) : error C3767: 'Lib::Extract': candidate function(s) not accessible

A: if you simply must access the internal methods another work around would be making the projects as Friend Assemblies like that:
//Lib Project
#pragma once

//define LibTest as friend assembly which will allow access to internal members
using namespace System;
using namespace System::Runtime::CompilerServices;
[assembly:InternalsVisibleTo("LibTest")];

public ref class Lib
{
 public:
  Lib(void);

 public:
  void Extract( std::string& data_ );
};

//LibTest Project
#pragma once

#using <Lib.dll> as_friend

ref class LibTest
{
  public:
    LibTest(void);
};

A: The problem is that std::string will compile as a internal (non public) type. This is actually a change in VS 2005+:
http://msdn.microsoft.com/en-us/library/ms177253(VS.80).aspx:
Native types are private by default outside the assembly
Native types now will not be visible outside the assembly by default. For more information on type visibility outside the assembly, see Type Visibility. This change was primarily driven by the needs of developers using other, case-insensitive languages, when referencing metadata authored in Visual C++.
You can confirm this using Ildasm or reflector, you will see that your extract method is compiled as:
public unsafe void Extract(basic_string<char,std::char_traits<char>,std::allocator<char> >* modopt(IsImplicitlyDereferenced) data_)

with basic_string being compiled as:
[StructLayout(LayoutKind.Sequential, Size=0x20), NativeCppClass, MiscellaneousBits(0x40), DebugInfoInPDB, UnsafeValueType]
internal struct basic_string<char,std::char_traits<char>,std::allocator<char> >

Note the internal.
Unfortunately you are then unable to call a such a method from a different assembly.
There is a workaround available in some cases: You can force the native type to be compiled as public using the make_public pragma.
e.g. if you have a method Extract2 such as:
void Extract2( std::exception& data_ );

you can force std::exception to be compiled as public by including this pragma statement beforehand:
#pragma make_public(std::exception)

this method is now callable across assemblies.
Unfortunately make_public does not work for templated types (std::string just being a typedef for basic_string<>)
I don't think there is anything you can do to make it work. I recommend using the managed type System::String^ instead in all your public API. This also ensures that your library is easily callable from other CLR languages such as c#

A: In addition to the solutions described above, one can subclass the templated type to obtain a non-templated type, and include its definition in both projects, thus overcoming some of the problems mentioned above.


Q: using sass with compass - 404 css not found I'm using the followig config for compass with grunt:
   compass: {
    options: {
    sassDir: '<%= yeoman.app %>/styles',
    cssDir: '.tmp/styles',
    imagesDir: '<%= yeoman.app %>/images',
    javascriptsDir: '<%= yeoman.app %>/scripts',
    fontsDir: '<%= yeoman.app %>/styles/fonts',
    importPath: 'app/components',
    relativeAssets: false
  },
  dist: {},
  server: {
    options: {
      debugInfo: true
    }
  }
},

and I see that the sass is getting compiled since it shows in the .tmp/styles folder
but for some reason when I call the css files from the <%= yeoman.app %>/styles filder it's not found


Q: Javascript - change r attribute of circle wrapped in #shadow-root My html tree looks as follows:
<svg id="floating-button-svg" style={{fill: `${floatingButton.backgroundColor}`}}>
  <use id="use-tag" href="
     <svg>
       <circle id="semi-circle" class="cls-1" cx="500" cy="500" r="50"/>
     </svg>"
  />
</svg>

Afer compilation the href dissolves to data:image/svg+xml;base64,PCEtLSA8P3htbCB2ZXJzaW9uPSIxLjAiIGVuY29kaW5nPSJ1dGYtOCI/Pgo8c3ZnIHZlcnNpb249IjEuMCIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CjxjaXJjbGUgaWQ9InNlbWktY2lyY2xlIiBjeD0iNTAwIiBjeT0iNTAwIiByPSI1MDAiLz4KPC9zdmc+IC0tPgoKCjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTAwMCIgaGVpZ2h0PSI1MDAiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCI+CiAgPGRlZnM+CiAgICA8c3R5bGU+CiAgICAgIC5jbHMtMSB7CiAgICAgICAgZmlsbDogIzAwMDsKICAgICAgfQogICAgPC9zdHlsZT4KICA8L2RlZnM+CiAgPGNpcmNsZSBpZD0ic2VtaS1jaXJjbGUiIGNsYXNzPSJjbHMtMSIgY3g9IjUwMCIgY3k9IjUwMCIgcj0iNTAiLz4KPC9zdmc+Cgo=#semi-circle
If anyone wants to test it, please replace the value in the href above with this link.
I am trying to change the radius of the circle through
document.getElementById('use-tag').setAttribute('r', '25')

but instead it only gives use an attribute of r=25. Is there any way I can change the radius of the circle? I have tried to fetch it using
 getElementById

but it just gives me null (I'm assuming because it's wrapped in a shadow root).
edit: The gist of the problem here I believe is that I am trying to change the attributes of a closed shadow root which is impossible to achieve. So can someone please tell me why am I get a closed root instead of an open one? And how can I get an open one?
edit: Here is a demo of this situation: https://codesandbox.io/embed/smoosh-sun-nnevd?fontsize=14&hidenavigation=1&theme=dark

A: Since you have direct access to circle with id semi-circle, you can update it as the below snippet.
The snippet is running under a setTimeout to show the difference.

setTimeout(function() {
  var circle = document.getElementById('semi-circle');
  circle.setAttribute('r', 60)
}, 3000)
<svg id="floating-button-svg" height="100" width="100">
  <circle id="semi-circle" class="cls-1"  cx="50" cy="50" r="40" fill="red" />
</svg>

You can also do it in another way, check the snippet

setTimeout(function() {
  var circle = document.getElementById('floating-button-svg');
  circle.firstElementChild.setAttribute('r', 60)
}, 1500)
<svg id="floating-button-svg" height="400" width="400">
      <circle id="semi-circle" class="cls-1"  cx="80" cy="80" r="40" fill="red" />
</svg>


Q: How to replace this componentWillReceiveProps? I have a login and register component with forms that were created a while ago before these methods were deprecated, I've been looking around but cannot seem to find a solution, how would I go about refactoring this to using getDerivedStateFromProps?
  componentWillReceiveProps(nextProps) {
    if (nextProps.auth.isAuthenticated) {
      this.props.history.push("/dashboard")
    }

    if (nextProps.errors) {
      this.setState({
        errors: nextProps.errors
      });
    }

A: Since you're using componentWillReceiveProps to keep a local state in sync with props you have two alternatives:
Declare your initial state based on props and use componentDidUpdate to ensure props synchronicity
class Component extends React.Component{
    state = { foo : this.props.foo }

    componentDidUpdate(prevProps){
        if(this.props.foo !== prevProps.foo)
            this.setState({ foo : prevProps.foo })
    }
}

This is actually triggering an extra render everytime, if you have some local state that is always equal to some prop you can use the prop directly instead.
Use getDerivedStateFromProps to update the state based on a prop change, but keep in mind that you probably don't need to use it
class Component extends React.Component{
    static getDerivedStateFromProps(props){
        return { foo : props.foo }
    }
}

A: The answer to the question you asked is probably not going to be satisfactory. :-) The answer is that if you really need to derive state from props (you probably don't, just use props.errors directly in render), you do it with the newer getDerivedStateFromProps static method that accepts props and state and (potentially) returns a state update to apply:
static getDerivedStateFromProps(props, state) {
    return props.errors ? {errors: props.errors} : null;
}

or with destructuring and without the unused state parameter:
static getDerivedStateFromProps(({errors})) {
    return errors ? {errors} : null;
}

But, you're saying "But that doesn't do the authentication thing...?" That's right, it doesn't, because that componentWillReceiveProps shouldn't have, either, it violates the rule props are read-only. So that part shouldn't be there. Instead, if that entry in props.history is supposed to be there, it should be put there by the parent component.


Q: Axios import breaks rest of javascript file I'm using encore and yarn to set up my javascript and css in a symfony project. I want to use axios so I use:
yarn add axios

then I add this code to app.js
import '../css/app.scss';
import axios from "axios";

console.log('test');

axios({
    url: 'https://dog.ceo/api/breeds/list/all',
    method: 'get',
    data: {
        foo: 'bar'
    }
});

Then yarn watch picks up the modifications and compiles it to this:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["app"],{

/***/ "./assets/css/app.scss":
/*!*****************************!*\
  !*** ./assets/css/app.scss ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),

/***/ "./assets/js/app.js":
/*!**************************!*\
  !*** ./assets/js/app.js ***!
  \**************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../css/app.scss */ "./assets/css/app.scss");
/* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_app_scss__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ "./node_modules/axios/index.js");
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__);

console.log('test');
axios__WEBPACK_IMPORTED_MODULE_1___default()({
  url: 'https://dog.ceo/api/breeds/list/all',
  method: 'get',
  data: {
    foo: 'bar'
  }
});

/***/ })

},[["./assets/js/app.js","runtime","vendors~app~normalization"]]]);

When I remove the import of Axios the console.log('test') runs but when I add the import it won't. So the import breaks the other code.
Could someone explain how I import axios without trouble?


Q: Css counter for list I am trying to use the counter increment in css on my ordered list but its not working
This is what I want to display:
1. Acknowledgements
   1.1 blah, blah ....
   1.2 blah, blah ....
   1.3 blah, blah ....

2. Risk Statement
   2.1 blah, blah ....
   2.2 blah, blah ....
   2.3 blah, blah ....

3. License
   3.1 blah, blah ....
   3.2 blah, blah ....
   3.3 blah, blah ....

But this s what is happening... http://jsfiddle.net/XQKcy/

A: Demo Fiddle
You were very close:
body {
    counter-reset: listCounter;
}
ol {
    counter-increment: listCounter;
    counter-reset: itemCounter;
    list-style:none;
}
li{
    counter-increment: itemCounter;
}
li:before {
    content: counter(listCounter) "." counter(itemCounter);
    left:10px;
    position:absolute;
}


Q: Global var vs Shared Instance swift What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.

A: A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this:
var bar = Bar()

You would then be able to access the instance from anywhere, like this:
bar
bar.foo()

A shared instance, or singleton, looks like this:
class Bar {
    static var shared = Bar()
    private init() {}
    func foo() {}
}

Then you can access the shared instance, still from anywhere in the module, like this:
Bar.shared
Bar.shared.foo()

However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables:
var bar2 = Bar()
var bar3 = Bar()

However, using a singleton (shared instance), the initialiser is private, so trying to do this...
var baaar = Bar()

...results in this:

'Bar' initializer is inaccessible due to 'private' protection level

That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced.
If you want more information about this, there's a great article by KrakenDev here.

A: Singleton (sharing instance)
Ensure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app.
The dispatch_once function, which executes a block once and only once for the lifetime of an app.
Global variable
Apple documentation says Global variables are variables that are defined outside of any function, method, closure, or type context.


Q: How to set layout with XML in View for BaseAdapter getView() method The following Java code (from https://www.intertech.com/Blog/android-adapters-adapterviews/) is from getView(), a method implementation from a Android Adapter class, and it builds a View in Java to populate items on a List. I get how it works, but the same page says it can be built using an XML file, which makes sense to me, but I'm unable to find any examples. I understand how to use XML resource files to set Activity layout using setContentView(). But how would I invoke an XML resource file to build the View in the getView() method?
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        Context context = parent.getContext();
        LinearLayout view = new LinearLayout(context);
        view.setOrientation(LinearLayout.HORIZONTAL);
        view.addView(new CheckBox(context));
        TextView nameTextView = new TextView(context);
        nameTextView.setText(courses.get(position).getName());
        nameTextView.setPadding(0, 0, 10, 0);
        view.addView(nameTextView);
        TextView parTextView = new TextView(context);
        parTextView.setText(Integer.toString(courses.get(position).getPar()));
        view.addView(parTextView);
        return view;
    }
    return convertView;
}

A: like this
item_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="name" />
</LinearLayout>

adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Holder holder; // use holder
    if (convertView == null) {
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_test, parent, false);
        holder = new Holder(convertView);
        convertView.setTag(holder);
    } else {
        holder = (Holder) convertView.getTag();
    }
    holder.name.setText("name");
    return convertView;
}

public class Holder {
    private TextView name;

    public Holder(View view) {
        name = view.findViewById(R.id.name);
    }
}


Q: project using moleculer-sentry example I have been trying to use the moleculer-sentry mixing in a moleculer project. But it is not working.
Does someone have an example project using this mixing?
Also i have been searching answers in internet, but nothing.


Q: How Javascript asyc and await working in this particular code? I have implemented an async function which creates an XHR object inside a Promise, requests a data from the server and fulfills the Promise with the response received from the server
async function playWordsAudio(id, type, check=false){

    let file_namePromise = new Promise(function (onSuccess, onFailure){
        var xhttp = new XMLHttpRequest();
        xhttp.onload = function(){
            if(this.readyState == 4 && this.status == 200){
                if(this.responseText !== "No Data"){
                    file_name = this.responseText;
                    if(check == false){
                        audio = new Audio('assets/uploads/wav/' + file_name);
                        audio.play();
                    }else{
                        onSuccess(file_name);
                    }
                }else{
                    if(check){
                        onSuccess('Not Found');
                    }
                }
            }
        };

        xhttp.open("GET", "scripts/get_word_audio.php?id=" + id + "&type=" + type, true);
        xhttp.send();
    });

    let resultant = await file_namePromise;

    if(check){
        return resultant;
    }
}

Later I have defined another function which calls the async function shown above
function modify_object(id, type, obj){
    result = playWordsAudio(id, type, true);
    result.then(function(value){
        if(value == "Not Found"){
            obj.classList.remove('fa-play');
        }
    });
}

Later in the implementation I also call the modify_object function and pass it an object for modification as described in the function.
modify_object(id, type, plays[i]);

In the async function I have created a Promise, on success I pass it the file_name received from the XHR response or else I pass it 'Not Found'.
Here I am confused on how the await part works inside the asyc function.
It returns the resultant to the caller of the async function which is
result = playWordsAudio(id, type, true);

If so, what does the onSuccess method in the Promise do
let file_namePromise = new Promise(function (onSuccess, onFailure){
/*
    Some Codes
*/

onSuccess(file_name);

/*
    Some more code
*/

onSuccess('Not Found);

/*
    Rest of the Code
*/
}

As I have checked by commenting out the return statement after the await statement
if(check){
//    return resultant;
}

The Promise is not fulfilled.
How does each part of the implementation work as described above?


Q: Convert ts object to data.frame and keep row- and colnames I want to convert a ts (i.e. timeseries) R object to a data.frame. The names of rows and columns of the ts object should be retained.
Consider the AirPassengers data set:
data(AirPassengers)

I could convert this ts object to a data.frame as follows:
AirPassengers <- data.frame(matrix(as.numeric(AirPassengers), ncol = 12, byrow = TRUE))
colnames(AirPassengers) <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
rownames(AirPassengers) <- 1949:1960

However, this seems to be way too complicated. Surprisingly, a google search didn't show a simpler solution.
Question: Is there a simple solution how to convert ts objects to a data.frame without losing colnames and rownames?

A: The underlying issue is that the output of print for a time series object is quite heavily processed by .preformat.ts. If you want to convert it to a data frame that is visually similar to the print results this should do:
df <- data.frame(.preformat.ts(datasets::AirPassengers), stringsAsFactors = FALSE)

Note that this will produce characters (as that is how .preformat.ts works), so be careful with the use (not sure what is the purpose of the conversion?).


Q: Where does setup.py install console scripts to? When I set up my package using setup.py to have a console script entry point, pip install -e . creates a cli exe in the C:\Users\...\anaconda3\envs\envname\Scripts\foo.exe.
However on a separate computer the python executable is the one from the Windows Store:
C:\Users\...\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n6khra8p0\python.exe
This doesn't set the PATH environment variable correctly to make .exes in the Scripts folder callable from the command line, so I need the full path to the .exe to call it.
Anyway I want to find the location of foo.exe on this second computer (which I don't have access to), is there a command I can instruct the second computer to run which will tell me where a console script will be located for that given sys.executable? I.e. for my computer, I expect it to print C:\Users\...\anaconda3\envs\envname\Scripts.

FWIW, this is my setup.cfg:
[options]
py_modules = xml2csv
python_requires = >=3.10

[options.entry_points]
console_scripts =
    xml2csv=xml2csv:main


Q: Using the button tag, can I customize the button? I want to use a custom button image that I drew up for my application, but doing so I need to use different images for the button being focused and another for it being pressed.
I came across the selector tags but for some reason it doesn't like it. Eclipse complains about a 'broken rendering library'. The error I get is this:
Broken rendering library; unsupported DPI. Try using the SDK manager to get updated.

And I have, I've updated every API past 10. If it matters, my target API is 15 and my compile API is 17.
If I can't get this working, can I simply use the Button tag and maybe change it in the Java src code or something?

A: use a custom layout like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/pressed"></item>

    <item android:state_focused="true" android:drawable="@drawable/focus"></item>

    <item android:drawable="@drawable/normal"></item>
</selector>

Also note that the the selector should be defined in this particular way else they will give problem .i.e.
1)state_pressed
2)state_focused ( work only if you scroll to that button using the hardware key)
3)drawable i.e. normal

If you changed the ordering of the selector then it won't work. One easy way to remember it is visualizing a qwerty phone - first i saw the button (normal), then moved to that particular button using arrow keys (state_focused), then i pressed that button (state_pressed). Now write them backwards.

A: Instead of button,create ImageView and do necessary things on click of the image.
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="Method_Name"
        android:src="@drawable/selector" >
    </ImageView>

Also inorder to give different images on click and focus,create selector.xml in drawable folder and set background of imageview as selector file.
selector.xml
    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >

     <item android:drawable="@drawable/image1"  android:state_focussed="true" />
     <!-- Inactive tab -->
    <item android:drawable="@drawable/image2"  android:state_pressed="true" />
     <!-- Pressed tab -->

     </selector>

Hope this will help you!


Q: How to show button when adding fragment? Bottom button(234) is not showing after adding fragment. I don't want to resize my fragment size.

Home_Fragment.xml This is the main Fragment page. It also have profile Fragment. From Profile Fragment we are calling next fragment that is hiding bottom button (TV_Chat button name)
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <!-- View pager to swipe views -->
    <Button
        android:id="@+id/button3"
        android:layout_width="125dp"
        android:layout_height="59dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="0dp"
        android:background="@color/white"
        android:text="" />

    <com.medyc.us.customViews.CustomViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tabLayout"
        android:background="@color/light_background"
        />

    <Button
        android:id="@+id/tv_chat"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="@drawable/circle_blue_gradient"
        android:text="234"
        android:gravity="center"
        android:textSize="@dimen/twenty_sp"
        android:textColor="@color/white"
        android:textStyle="bold"
        android:visibility="visible"
        android:fontFamily="@font/helvetica"
        android:layout_centerHorizontal="true"
        android:layout_alignBottom="@+id/tabLayout"
        android:layout_marginBottom="@dimen/thirty_dp"
        />
    <!-- our tablayout to display tabs  -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        app:tabIndicatorHeight="0dp"
        />

    <View
        android:id="@+id/bottomview"
        android:layout_width="match_parent"
        android:layout_height="43dp"
        android:layout_alignParentBottom="true"

        android:layout_alignParentStart="true"
        android:layout_marginBottom="50dp" />

</RelativeLayout>


Q: ASP.NET/GridView: Using only a subset of the data fields in the table I have a list of objects called Activity and I want to display the date, type and notes for each and every one of these activities. This is the code I'm using.
<asp:GridView ID="gvTable" runat="server" AllowSorting="true" ShowHeader="true">
  <Columns>
    <asp:BoundField DataField="ActivityDate" HeaderText="Date"
      HeaderStyle-CssClass="date" />
    <asp:BoundField DataField="ActivityType" HeaderText="Type" />
    <asp:BoundField DataField="ActivityNotes" HeaderText="Notes" />
  </Columns>
  <PagerSettings Position="Bottom" Mode="NextPrevious" PageButtonCount="5"
    PreviousPageText="Older activities" NextPageText="Newer activities" />
</asp:GridView>

However, all of the attributes of each object is displayed in the header. How can I force it to display only the columns that I want to use?

A: gvTable.AutoGenerateColumns = false
or
<asp:GridView ID="gvTable" runat="server" AutoGenerateColumns="False" AllowSorting="true" ShowHeader="true">

should do the trick.

A: Set the attribute on your gridview:
AutoGenerateColumns="false"

A: You need to set the AutoGenerateColumns property on the grid to false.

A: Have you tried AutoGenerateColumns="false" in the gridview?


Q: iOS Build Error: missing file Icon102.png I have a Xamarin Forms App running on Android and iOS. Everything works fine on a Simulator and on lokal devices.
When I push the Buid to AppCenter, the Android Version gets build without a problem, but the iOS Build alsways fails with the following error:
(_CoreCompileImageAssets target) ->   /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png : error : File not found: /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png [/Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/O365Info.iOS.csproj]
24 Warning(s)
1 Error(s)

Time Elapsed 00:01:01.73
[error]Xamarin.iOS task failed with error Error: /Library/Frameworks/Mono.framework/Versions/6_6_1/bin/msbuild failed with return code: 1. For guidance on setting up the build definition, see https://go.microsoft.com/fwlink/?LinkId=760847.
[section]Finishing: Build Xamarin.iOS solution.
In the first builds I didn't even had a Iconset called AppIcon.appiconset (my Iconset was named appiconset1) and the whole project didn't include a file named "Icon1024.png".
I then renamed my Iconset to appioconset and included a file named "Icon1024.png", but I'm still getting the same error.
No ideas, where this error might come from. Any suggestions?

A: Copied From ColeX at:
https://forums.xamarin.com/discussion/179775/build-error-with-missing-file-icon1024-png

*

*Edit csproj file to remove the bogus entries (just delete them)

*Ensure that a 1024*21024 png icon (file does not have Alpha or transparent) add into Assets.xcassets

*Ensure the 1024 file information included in csproj file

Refer
Where to find 'Missing Marketing Icon'
https://forums.xamarin.com/discussion/129252/problems-with-missing-appicons-files


Q: What really happens internally when an update happens on a record with indexed column in sql server I know that when a table has indexed column(s), sql server duplicates the data of these columns so that it can be accessed fast without looking through every record. And if the index is covered with other columns then all these included columns are also stored along with the indexed columns.
So, I am assuming when an update happens on any of the indexed columns or included columns then it is obvious that the update should happen in both the actual record location and the index location. This point looks interesting to me because if a table is expected to have more updates than searches, then wouldn't it be overhead to have the index? I wanted to confirm on this and also would like to know the internals on what actually happens behind the screen when a update happens.

A: Yes, you have it correct.  There is a trade-off when adding indexes.  They have the potential to make selects faster, but they will make updates/inserts/deletes slower.

A: When you design an index, consider the following database guidelines:

*

*Large numbers of indexes on a table affect the performance of INSERT, UPDATE, DELETE, and MERGE statements because all indexes must be adjusted appropriately as data in the table changes. For example, if a column is used in several indexes and you execute an UPDATE statement that modifies that column's data, each index that contains that column must be updated as well as the column in the underlying base table (heap or clustered index).

*Avoid over-indexing heavily updated tables and keep indexes narrow, that is, with as few columns as possible.

*Use many indexes to improve query performance on tables with low update requirements, but large volumes of data. Large numbers of indexes can help the performance of queries that do not modify data, such as SELECT statements, because the query optimizer has more indexes to choose from to determine the fastest access method.

*Indexing small tables may not be optimal because it can take the query optimizer longer to traverse the index searching for data than to perform a simple table scan. Therefore, indexes on small tables might never be used, but must still be maintained as data in the table changes.

For more information have a look at the below link:-
http://technet.microsoft.com/en-us/library/jj835095(v=sql.110).aspx


Q: How do I clear an array in the state of my Redux store? I am building a small e-commerce shop and I am trying to clear my cart after a successful checkout. The cart contains cartItems which are stored in the Redux store. I am getting the console log in my function in the StripeCheckoutForm component and the action creator.
I am not seeing the console log for the reducer so I suspect something is wrong with my action creator. I am not sure about best practices concerning action creators. I was wondering when, why, and how to use dispatch in the action creator. The docs for Redux aren't exactly clear for me.
Here is my StripeCheckout:
import React, {Component} from 'react';
import { CardElement, injectStripe } from 'react-stripe-elements';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { clearCart } from '../actions/clearCartAction';
import getTotal from '../helpers/getTotalHelper';
import { Container, Col, Form, FormGroup, Input } from 'reactstrap';
import './StripeCheckoutForm.css';

const cardElement = {
  base: {
    color: '#32325d',
    width: '50%',
    lineHeight: '30px',
    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
    fontSmoothing: 'antialiased',
    fontSize: '18px',
    '::placeholder': {
      color: '#aab7c4'
    }
  },
  invalid: {
    color: '#fa755a',
    iconColor: '#fa755a'
  }
};

const FIREBASE_FUNCTION = 'https://us-central1-velo-velo.cloudfunctions.net/charge/';

// Function used by all three methods to send the charge data to your Firebase function
async function charge(token, amount, currency) {
  const res = await fetch(FIREBASE_FUNCTION, {
      method: 'POST',
      body: JSON.stringify({
          token,
          charge: {
              amount,
              currency,
          },
      }),
  });
  const data = await res.json();
  data.body = JSON.parse(data.body);
  return data;
}

class CheckoutForm extends Component {
  constructor(props) {
    super(props);
    this.submit = this.submit.bind(this);
  }

  state = {
    complete: false
  }

  clearCartHandler = () => {
    console.log('clearCartHandler');
    this.props.onClearCart()
  }

  // User clicked submit
  async submit(ev) {
    console.log("clicked!")
    const {token} = await this.props.stripe.createToken({name: "Name"});
    const total = getTotal(this.props.cartItems);
    const amount = total; // TODO: replace with form data
    const currency = 'USD';
    const response = await charge(token, amount, currency);

    if (response.statusCode === 200) {
      this.setState({complete: true});
      console.log('200!!',response);
      this.clearCartHandler();

    } else {
      alert("wrong credit information")
      console.error("error: ", response);
    }
  }

  render() {

    if (this.state.complete) {
      return (

Purchase Complete

          <Link to='/'>
            <button>Continue Shopping</button>
          </Link>

      );
    }

    return (

      <Container className="App">

Let's Checkout

          <Form className="form">
            <Col>
              <FormGroup>
                <Input
                  type="first name"
                  name="first name"
                  id="exampleEmail"
                  placeholder="first name"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="last name"
                  name="last name"
                  id="exampleEmail"
                  placeholder="last name"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="address"
                  name="address"
                  id="exampleEmail"
                  placeholder="address"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="city"
                  name="city"
                  id="exampleEmail"
                  placeholder="city"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="prefecture"
                  name="prefecture"
                  id="exampleEmail"
                  placeholder="prefecture"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="zipcode"
                  name="zipcode"
                  id="exampleEmail"
                  placeholder="zipcode"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="email"
                  name="email"
                  id="exampleEmail"
                  placeholder="myemail@email.com"
                />
              </FormGroup>
            </Col>

            <CardElement style={cardElement}/>

          </Form>
        <button className="checkout-button" disabled={false} onClick={this.submit}>Submit</button>
      </Container>

    );
  }
}

const mapStateToProps = state => {
  return {
    cartItems: state.shoppingCart.cartItems
  }
}

const mapDispatchToProps = state => {
  return {
    onClearCart: () => (clearCart())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(injectStripe(CheckoutForm));

Here is my action creator:
import { CLEAR_CART } from './types';

// export const clearCart = (dispatch)  => {
//   console.log('clear_action')
//   dispatch({
//     type: CLEAR_CART,
//   })
// }

export function clearCart() {
  console.log('clear_action')
  return {
    type: CLEAR_CART
  }
}

and finally my reducer:
import {ADD_TO_CART} from '../actions/types';
import {REMOVE_FROM_CART} from '../actions/types';
import {CLEAR_CART} from '../actions/types';

const initialState = {
  cartItems: [],
}

export default function(state = initialState, action) {
  switch(action.type) {
    case ADD_TO_CART:
    console.log('ADD_reducer');
      return {
        ...state,
        cartItems: [...state.cartItems, action.payload],
      }
    case REMOVE_FROM_CART:
    console.log('REMOVE_REDUCER', action.payload, state.cartItems);
      return {
        ...state,
        cartItems: state.cartItems.filter(item => item.id !== action.payload.id)
      }
    case CLEAR_CART:
    console.log('CLEAR_REDUCER');
      return {
        ...state,
        cartItems: []
      }
    default:
      return state;
  }
}

A: Action has to be dispatched like below. Let me know if it works
const mapDispatchToProps = (dispatch) => {
  return {
    onClearCart: () => (dispatch(clearCart()))
  }
};


Q: Zoomable fullscreen image in portrait and landscape mode I am a beginner at programming. I have an app where you can tap into any of the images that are on display to show that image in full-screen mode and can pinch to zoom. The issue I am having is that if you rotate the phone then the image is only half visible.
I'm using a scroll view to achieve the zoom functionality as that seems to be the consensus of the best way to do it.
It works perfectly in portrait mode, or if I enter the fullscreen image while the app is already in landscape orientation, but If I go into the landscape while in the fullscreen image that's where it goes wrong. Here is the code:
class PictureDetailViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollView: UIScrollView!
var routeData = IndividualRoute(numberOfRoute: UserDefaults.standard.integer(forKey: "currentRoute"))

var detailPicture = UserDefaults.standard.bool(forKey: "segueFromDetailvc")

var detailImage = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()

    routeData.routesValues()
    scrollView.delegate = self
    selectImage()
    scrollView.frame = UIScreen.main.bounds
    scrollView.addSubview(detailImage)
    scrollViewContents()
    setupConstraints()
    let scrollViewFrame = scrollView.frame
    let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
    let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height
    let minScale = min(scaleHieght, scaleWidth)
    scrollView.minimumZoomScale = minScale
    scrollView.maximumZoomScale = 1
    scrollView.zoomScale = minScale
    let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreen))
    tap.numberOfTapsRequired = 2
    view.addGestureRecognizer(tap)

}

//****************************************

//Image Setup

func setupConstraints() {

    scrollView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        scrollView.topAnchor.constraint(equalTo: view.topAnchor),
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        scrollView.centerYAnchor.constraint(equalTo: view.centerYAnchor)])

    scrollView.contentSize = (detailImage.image?.size)!

}

func selectImage() {
    if !detailPicture {
        let foo = "\(routeData.achievements[UserDefaults.standard.integer(forKey: "currentAchievement")])"
        detailImage.image = UIImage(named: "\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0")
    } else {
        let foo = "\(routeData.achievements[0])"
        detailImage.image = UIImage(named: "\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0")
        print("\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0")
    }

    guard let width = detailImage.image?.size.width else {
        return
    }
    guard let height = detailImage.image?.size.height else {
        return
    }

    let frame: CGRect = CGRect(x: 0, y: 0, width: width, height: height)
    detailImage.frame = frame
    detailImage.isUserInteractionEnabled = true

}

//**************************************

//Scrollview setup

@objc func dismissFullscreen(){
    scrollView.setZoomScale(1, animated: true)
}

func scrollViewContents() {

    let boundSize = UIScreen.main.bounds.size
    var contentFrame = detailImage.frame

    if contentFrame.size.width < boundSize.width {
        contentFrame.origin.x = (boundSize.width - contentFrame.size.width) / 2
    } else {
        contentFrame.origin.x = 0
    }
    if contentFrame.size.height < boundSize.height {
        contentFrame.origin.y = (boundSize.height - contentFrame.size.height) / 2
    } else {
        contentFrame.origin.y = 0
    }

    detailImage.frame = contentFrame

}

func scrollViewDidZoom(_ scrollView: UIScrollView) {
    scrollViewContents()
}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {

    return detailImage
}

Sorry for posting so much code but its pretty much all relevant (I think).
Here are screenshots of the problem:

A: Okay, I've managed to fix it! Had a little jump around with delight.
I set up a new function called setupScale() that is called in viewdidload when the view is presented. I also added the viewwillLayoutSubview() override and called the setupScale() function inside it.
If looks like this:
private func setupScale() {

    scrollView.frame = UIScreen.main.bounds
    scrollView.contentSize = (detailImage.image?.size)!
    scrollViewContents()
    let scrollViewFrame = scrollView.frame
    let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
    let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height
    let minScale = min(scaleHieght, scaleWidth)
    scrollView.minimumZoomScale = minScale
    scrollView.maximumZoomScale = 1
    scrollView.zoomScale = minScale
}
override func viewWillLayoutSubviews() {
    setupScale()
}

Results look perfect on my iPad and iPhone 7 in landscape and portrait.


Q: EXEC master.sys.sp_MSforeachdb error when looping through databases I am getting the following the error when executing the statement:
EXEC master.sys.sp_MSforeachdb
    'INSERT INTO AuditDatabase.dbo.[DataDictionary]
         exec sp_get_extendedproperty use [?] "?"'

Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'master'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'tempdb'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'model'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'msdb'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'AdventureWorks2014'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'TestDatabase'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'AuditDatabase'.

If I run it without the use syntax like this:
EXEC master.sys.sp_MSforeachdb
    'INSERT INTO AuditDatabase.dbo.[DataDictionary]
        exec sp_get_extendedproperty "?"'

It only loops through the AdventureWorks2014 and msdb databases. It does not loop through any other database.
sp_get_extendedproperty is on master db.

A: The use statement is in the wrong place. Try something like this:
I
   exec sp_MSforeachdb 'use ? rest of statement here  '
I just executed this and it worked fine:
exec sp_MSforeachdb 'use ? select * from sys.objects;'

If your proc is name sp_xxx and is in master it should be available in all databases.


Q: Find prev element source I know this code below doesn't work, but is it possible with a call to get the "src" from the prev, with a little tweak to the jquery below?
HTML:

    Diffuse green

        <button class="btn-publish chooseTheme">Choose Theme</button>

Jquery:
$(".chooseTheme").click(function () {
    var src = $(".chooseTheme").find("img");
    alert(src.text());
});

A: $(".chooseTheme").click(function () {
        var src = $(this).closest('li').find("img").attr('src');
        alert(src);
});

A: $(".chooseTheme").click(function () {
    var src = $("li").find("img").attr('src');
    alert(src);

});


Q: What should be passed as input parameter when using train-test-split function twice in python 3.6 Basically i wanted to split my dataset into training,testing and validation set. I therefore have used train_test_split function twice. I have a dataset of around 10-Million rows.
On the first split i have split training and testing dataset into 70-Million training and 30-Million testing. Now to get validation set i am bit confused whether to use splitted testing data or training data as an input parameter of train-test-split in order to get validation set. Give some advise. TIA
X = features
y = target

# dividing X, y into train and test and validation data 70% training dataset with 15% testing and 15% validation set

from sklearn.model_selection import train_test_split

#features and label splitted into 70-30
X_train, X_test, y_train, y_test = train_test_split(X, y,  test_size = 0.3, random_state = 0)

#furthermore test data is splitted into test and validation set 15-15
x_test, x_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5)

A: Don't make a testing set too small. A 20% testing dataset is fine. It would be better, if you splitted you training dataset into training and validation (80%/20% is a fair split). Considering this, you shall change your code in this way:
X_train, X_test, y_train, y_test = train_test_split(X, y,  test_size = 0.2, random_state = 0)

x_test, x_val, y_test, y_val = train_test_split(X_train, y_train, test_size=0.25)

This is a common practice to split a dataset like this.


Q: Initialize a multidimensional array of JButtons declared in a different class using get method I have to create a battleship game where there is a multidimensional array of JButtons to denote the player grid. I  am supposed to initialize the JButtons in the main UI class but they need to be declared in a separate class holding the player grid. I have tried this to add the buttons:
for(int i = 0; i <= 10; i++){
        for(int j = 0; j <= 10; j++){
           playerOnePanel.add(playerOne.getBoard());
         }
    }

But this returns a null pointer exception. The class I'm trying to reference is:
public class Player {
    private Color shipColor;
    private String userName;
    private boolean isFirst;
    private JButton[][] buttonBoard = new JButton[rows][cols];
    private final static int rows = 10;
    private final static int cols = 10;

    public Player(String name){
        initComponents();
    }

    private void initComponents(){
        for(int i = 0; i <= rows; i++){
            for(int j = 0; j <= cols; j++){
                buttonBoard[i][j] = new JButton();
            }
        }
    }

     public JButton[][] getBoard(){
         return buttonBoard;
     }
}

And the code I want to use the object in is:
public class BattleshipUI extends JFrame {
    private JMenuBar menuBar;
    private JMenu gameMenu;
    private JMenu optionMenu;
    private JMenuItem playerPlayer;
    private JMenuItem playerComputer;
    private JMenuItem computerComputer;
    private JMenuItem exit;
    private JMenuItem game;
    private JMenuItem player;
    private JButton deploy;
    private JPanel shipLayoutPanel;
    private JPanel playerOnePanel;
    private JComboBox shipCb;
    private JComboBox directionCb;
    // Data arrays for various components on the UI
    private String[] rowLetters = {" ","A","B","C","D","E","F","G","H","I","J"};
    private String[] columnNumbers = {" ","1","2","3","4","5","6","7","8","9","10"};
    private String[] ships = {"Carrier","Battleship","Submarine","Destroyer", "Patrol Boat"};
    private String[] direction = {"Horizontal","Vertical"};
    private static final int PLAYER_ONE = 0;
    private static final int PLAYER_TWO = 1;
    private Player playerOne;
    private Player playerTwo;
    private Player[] players = new Player[2];
    private Color[] color = {Color.cyan, Color.green, Color.yellow, Color.magenta, Color.pink, Color.red, Color.white};

    public BattleshipUI(){
        initComponents();
        initObjects();
    }

    public BattleshipUI getThisParent(){
        return this;
    }

    private void initObjects(){
        playerOne = new Player("Player One");
        playerTwo = new Player("Player Two");
        players[1] = playerOne;
        players[2] = playerTwo;
    }

    private void initComponents(){
        this.setTitle("Battleship");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(500,500));
        this.setMinimumSize(new Dimension(500,500));

        menuBar = new JMenuBar();
        gameMenu = new JMenu("Game");
        optionMenu = new JMenu("Option");
        menuBar.add(gameMenu);
        menuBar.add(optionMenu);

        playerPlayer = new JMenuItem("Player vs. Player");
        playerComputer = new JMenuItem("Player vs. Computer");
        computerComputer = new JMenuItem("Computer vs. Computer");
        exit = new JMenuItem("Exit");
        gameMenu.add(playerPlayer);
        gameMenu.add(playerComputer);
        gameMenu.add(computerComputer);
        gameMenu.add(exit);
        playerPlayer.setEnabled(false);
        computerComputer.setEnabled(false);

        game = new JMenuItem("Game Options");
        player = new JMenuItem("Player Options");
        optionMenu.add(game);
        optionMenu.add(player);

        shipLayoutPanel = new JPanel();
        shipLayoutPanel.setBorder(BorderFactory.createTitledBorder("Select Ship and Direction"));

        shipCb = new JComboBox(ships);
        directionCb = new JComboBox(direction);
        deploy = new JButton("DEPLOY");
        deploy.setEnabled(false);

        shipLayoutPanel.add(shipCb);
        shipLayoutPanel.add(directionCb);
        shipLayoutPanel.add(deploy);

        playerOnePanel = new JPanel(new GridLayout(11,11));
        playerOnePanel.setMinimumSize(new Dimension(400,400));
        playerOnePanel.setPreferredSize(new Dimension(400,400));
        playerOnePanel.setBorder(BorderFactory.createTitledBorder("Player  One"));

        for(int i = 0; i <= 10; i++){
            for(int j = 0; j <= 10; j++){
               playerOnePanel.add(playerOne.getBoard());
             }
        }

        this.setJMenuBar(menuBar);
        this.add(shipLayoutPanel, BorderLayout.NORTH);
        this.add(playerOnePanel, BorderLayout.WEST);
        this.setVisible(true);
    }
}

Is there a way to do this? I need to use the methods and variables listed.

A: You seem to initialize the players (and their boards respectively) after trying to add their board to a panel, which is impossible since you did not create the players yet.
 public BattleshipUI(){
     initComponents(); //Here you try to add the board of a player
     initObjects(); //Here you initialize the players (ergo nullpointer)
 }

 private void initComponents(){
     for(int i = 0; i <= 10; i++){
         for(int j = 0; j <= 10; j++){
             //playerOne is not instantiated yet
             playerOnePanel.add(**playerOne**.getBoard());
         }
     }
 }

  private void initObjects(){
        **playerOne** = new Player("Player One");
        playerTwo = new Player("Player Two");
        players[1] = playerOne;
        players[2] = playerTwo;
}

A: Another thing I see is: You are trying to add a multi-dimensional JButton-Array at once to the JPanel. I think this will not work (please correct me if i am wrong). You have to do this Button by Button:
JButton[][] board = playerOne.getBoard();
for(int i=0;i<rowSize;i++){
   for(int j=0;j<columnSize;j++){
       playerOnePanel.add(board[i][j]);
   }
}

Notice: Obviously you have to get somehow the row size and column size and declare as a variable as here as rowSize and columnSize.


Q: How to run all javascript files in a folder with NodeJS? I want to have a folder with javascript files and be able to programmatically run whatever is on them asynchronously. For example:
async.each(folder_files, function(content, cb){
    run_script(content);

    cb();
},function(err){
    if(err){
        console.log(err);
    }else{
        console.log("All scripts ran succesfully :D");
    }
});

Is this even possible?
EDIT: Just to clarify, I want to be able to change the folder contents with any number of scripts and run them through the main JS file.

A: Here is a simple solution using  async  , but you need to put all your scripts inside scripts folder beside the main file
const fs = require('fs')
const exec = require('child_process').exec

const async = require('async') // npm install async

const scriptsFolder = './scripts/' // add your scripts to folder named scripts

const files = fs.readdirSync(scriptsFolder) // reading files from folders
const funcs = files.map(function(file) {
  return exec.bind(null, `node ${scriptsFolder}${file}`) // execute node command
})

function getResults(err, data) {
  if (err) {
    return console.log(err)
  }
  const results = data.map(function(lines){
    return lines.join('') // joining each script lines
  })
  console.log(results)
}

// to run your scipts in parallel use
async.parallel(funcs, getResults)

// to run your scipts in series use
async.series(funcs, getResults)


Q: PHP code in JavaScript to get variable When I press on any of the ‘region’ names in the list ('href' links), the matching list of 'cities' is showing underneath.
<?php while(has_list_regions()) { ?>
  <a href="javascript:show_region('<?php echo list_region_id() ?>');">
<?php } ?>

Is it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected ‘href’ that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn’t work.

A: PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on.
You can however use PHP to generate the required JS along with your content.
The way you've written it won't work.

For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic)
function show_region(chosen_region_id) {
    ...
    $.post('yourserver.com/getclickedtag.php',
        {clicked_tag: chosen_region_id},
        function(data) { ... });
    ...
}

A: In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.


Q: unique form field validation in extjs4 Is there a cleaner way to define unique form field in extjs. Below is a sample code that is checking on client UID on client creation/edition. This code is working but has some bugs - for example on client creation if you enter a value that is already present in DB validator returns true until you unfocus the field.
Ext.define('AM.view.client.UniqueField', {
    extend: 'Ext.form.field.Text',
    alias : 'widget.uniquefield',

    vtype: 'UniqueUid',

    initComponent: function() {

    Ext.apply(Ext.form.field.VTypes, {

        UniqueUidMask : /[0-9]/i,
        UniqueUid : function(val,field) {
            if (val.length < 9) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Company ID is too small'
                });
                return false;
            } else {
              var paste=/^[0-9_]+$/;
              if (!paste.test(val)) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Ivalid characters'
                });
                return false;
               } else {

                 var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
                     mask.show();
                 var test= 0;
                 var store = Ext.create('AM.store.Clients');
                     store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
                     store.on('load', function(test) {
                      mask.hide();
                        if(parseInt(store.getTotalCount())==0){
                         this.uniqueStore(true);
                        }else{
                           Ext.apply(Ext.form.field.VTypes, {
                              UniqueUidText: 'Company ID is already present'
                           });
                         this.uniqueStore(false);
                        }
                     },this)

                return true;
               }
            }}
      },this);

    this.callParent(arguments);

    },

    uniqueStore: function(is_error){

        Ext.apply(Ext.form.field.VTypes, {
        UniqueUidMask : /[0-9]/i,
        UniqueUid : function(val,field) {
            if (val.length < 9) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Company ID is too small'
                });
                return false;
            } else {
              var paste=/^[0-9_]+$/;
              if (!paste.test(val)) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Ivalid characters'
                });
                return false;
               } else {

                 var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
                     mask.show();

                 var store = Ext.create('AM.store.Clients');
                     store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
                     store.on('load', function(test) {
                      mask.hide();
                        if(parseInt(store.getTotalCount())==0){
                         this.uniqueStore(true);
                        }else{
                         this.uniqueStore(false);
                        }
                     },this)

                return is_error;
               }
            }}
      },this);

    }

});

A: How about using server side validation?
I answered to similar issue here: extjs4 rails 3 model validation for uniqueness
Obviously you can change it to use "ajax" instead of "rest" proxy.


Q: Is it possible to set the initial topic assignments for scikit-learn LDA? Instead of setting the topic_word_prior as a parameter, I would like to initialize the topics according to a pre-defined distribution over words.  How would I set this initial topic distribution in sklearn's implementation? If it's not possible, is there a better implementation to consider?

A: If you have a predefined distribution of words in a pre-trained model you can just pass a bow_corpus through that distribution as a function.  Gensims LDA and LDAMallet can both be trained once then you can pass a new data set through for allocation without changing the topics.
Steps:

*

*Import your data

*Clean your data: nix punctuation, numbers, lemmatize, remove stop-words, and stem

*Create a dictionary
dictionary = gensim.corpora.Dictionary(processed_docs[:])
dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000)

*Define a bow corpus
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]

*Train your model - skip if it's already trained
ldamallet = gensim.models.wrappers.LdaMallet(mallet_path,
            corpus=bow_corpus, num_topics=15, id2word=dictionary)

*Import your new data and follow steps 1-4

*Pass your new data through your model like this:
  ldamallet[bow_corpus_new[:len(bow_corpus_new)]]

*Your new data is allocated now and you can put it in a CSV


Q: Why I should add '&' before the parameter which is an unordered_map? unordered_map<int, string>::iterator findElement(unordered_map<int, string> &intString, int index){
    return intString.find(index);
}

If I don't add the & before the intString, the code will crash.

A: The & in the type for the function-parameter intString means that the function gets a reference to the passed argument, instead of a copy of it.
Thus, the iterator which is returned from .find() and which it returns in turn will point into the passed argument, instead of being a dangling iterator pointing somewhere into a no longer existing copy.
And accessing destroyed objects, especially if the memory was re-purposed, can have all kinds of surprising results, which is why it is called Undefined Behavior (UB).


Q: Call Python google cloud endpoint api from android At this point I have created a python app-engine endpoint api called paper (as also noted in the app.yaml) file. I have placed all the jars, including the …-java-1.13.2-beta-sources.jar file, in the libs directory of my android project. How do I call one of my web services (aka endpoint methods)? As in I don't know the name of the package that would lead me to the api, which in the python backend is simply class PageApi(remote.Service):. Imagine the paper api has a method called countPages(self):. How would I call the service? I have already tried importing import com.appspot.api.services.[etc] but eclipse does not see the importing path.
EDIT:
I reload the api. I check that everything looks okay on api explorer. Then I found two packages that seem to be my packages -- except they contain no classes at all.
import com.google.api.services.page.*;
import com.google.api.services.page.model.*;

If they are indeed the packages, why would the classes be missing?

A: First.  Once you have your projects setup correctly then the same wizard that generated your client library will copy it to your Android project and extra the source files.  then you will find the packages you need in the endpoint-libs folders in your project explorer.  Take a look at this post for tips on getting that working.
Then you invoke an endpoint using Android code like this:
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = new JacksonFactory();

endpointname.Builder builder = new endpointname.Builder( transport, jsonFactory, null );
builder.setApplicationName( appName );

endpointname service = builder.build();

try {
   response = service.methodName( parameters ).execute();
} catch (IOException e) {
   Log.e(...);
}


Q: Multipeer Connectivity Session in iOS7 I've looked into Apple's documentation but is still uncleared about one thing, the session.

*

*When - (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler is called, we need to pass in a session to the invitationHandler. What will happen to this session?
When A invites B to join a session that A created, does B provide a new session to A as well? What is inside B's session? Is it just A alone or does it include all the peers that are currently in A's session? Should B keep track of the session that's been used to accept A's invitation?
Inside this article, http://nshipster.com/multipeer-connectivity/, the tutorial creates a new session on the fly and uses it to accept the invitation, wouldn't you lose the session once the function is ended; thus losing information to connected peers?

*Assuming that B, C and D are all invited by A, and now B wants to send something to C. Is it required that B needs to send the information to A first or can B send the information directly to C?

*According to the Apple's documentation, a single session can only hold no more than 8 peers. Is it possible to make an array of sessions so that you can invite more than 8 people to join your device? If that is the case, does client also need to respond with an array so that it can carry more than 8 peers in its list?

*Assuming A and B are now connected, and A now invites C to join. How does B know that C is now in the session?
Thank you for reading such a long post.

A: There's not much in the way of documentation on Multipeer Connectivity, so these answers are based on my own experiments:

*

*There are lots of questions inside this one question, but in a nutshell A's session(s) manage invitations that A has sent or accepted. So if B invites and A accepts, the session that A passes when accepting will then be used in the MCSessionDelegate session: peer: didChangeState: callback to say whether the connection happened. At this point the connectedPeers property of A's session will contain B (if the connection succeeded). The session that B used to send the invitation will also get the same callback once A accepts, and will contain A in connectedPeers. Neither A nor B will have any information on the other's session that managed this connection between them. And yes, if you want to send any data to the newly connected peer, you need to keep a reference to the session that handled the connection. I've yet to see any real advantage in creating a new session for each invitation.

*Based on the above, B has no information on who A is connected to. So if A is connected to B,C and D, the only peer B knows about is the peer that it connected to - A. What Multipeer Connectivity offers here is the ability for B to discover C or D via A. So if the A-B connection was made over WiFi, and A-C over Bluetooth, but B does not have Bluetooth enabled, and C is on a different WiFi network to B, B and C can still discover each other through A. The process of inviting and accepting is still up to B and C to handle though.

*I answered a question about session management here that may be helpful Best option for streaming data between iPhones

*B doesn't know anything about A connecting to C. All B can do is discover C for itself and add C to it's own session.

A: *

*From quickly looking over Chris's answer it seems accurate from what I've been working on at my job.

*I'm currently working on a game using multipeer connectivity and have found that:
(Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C.
the Multipeer Framework is a P2P framework and automatically connects everyone together.
even if (as in my current project) you set it up as a Server-client model, all peers will still be connected and you can send messages between B and C without going through A. Depending on what you are doing with your app.

*Go with Chris's answer

*Addressed in #2
I recommend looking at the example project in the Apple Docs and carefully watch what happens in the debug area when you connect.
Also, as a side note:
Scenario:(A is only on wifi),(B is on wifi and bluetooth),(C is on bluetooth only)

if A connects to B via wifi, and B connects to C via bluetooth, A will still be connected to C but you won't be able to send a message from A directly to C because they are on different networks.

A: @SirCharlesWatson:

(Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C.
the Multipeer Framework is a P2P framework and automatically connects everyone together.

My question is: when B automatically connected to C, will B & C receive a state change notification on the existed session?

*

*A: session:peer:B didChangeState(MCSessionStateConnected)

*B: session:peer:A didChangeState(MCSessionStateConnected)


Q: javascript to allow me to collapse accordion that is extended I have a side navigation bar that consists of multiple accordions that when expanded shows more navigation buttons. I have a bit of JavaScript that will only allow one of those accordions to be expanded at a time. However if I click on one accordion to expand it, when I click the same accordion it remain open.
I would like to get it so that I can expand and collapse the accordion without having to expand another accordion.
JavaScript:
var acc = document.getElementsByClassName("nav-link-bottom-main");
var i;
var last;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        if (last) {
            last.nextElementSibling.classList.toggle("show");
        }
        this.nextElementSibling.classList.toggle("show");
        last = this;
    }
}

html:

    <button class="nav-link-bottom-main toggle">Endpoint Section 1</button>

        <button class="nav-link-bottom-sub toggle">GETendpoint 1.1</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 1.2</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 1.3</button>

    <button class="nav-link-bottom-main toggle">Endpoint Section 2</button>

        <button class="nav-link-bottom-sub toggle">GETendpoint 2.1</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 2.2</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 2.3</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 2.4</button>

A: It looks like whenever if (last) condition is true and it's the same element as this, you're toggling show class twice on same element, so probably this is why it remains open (actually it closes and opens again at the same time).
So try to check if you're not toggling same element like this:
if (last && last != this) {
    last.nextElementSibling.classList.toggle("show");
}
this.nextElementSibling.classList.toggle("show");

And I hope it helps.


Q: how can i plot series first bar's close price of super trend (long/short)? how can i plot series first bar's close price of super trend (long/short) ?
//@version=5
indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)

[supertrend, direction] = ta.supertrend(factor, atrPeriod)

bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green,      style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red,     style=plot.style_linebr)

fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)

A: var float first_close = 0.
if barstate.isfirst
    first_close := supertrend

A: You will have to save the close price whenever the direction changes into a variable and then you can plot that variable. Example below
//@version=5
indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)

[supertrend, direction] = ta.supertrend(factor, atrPeriod)

bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green,      style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red,     style=plot.style_linebr)

fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
var firstbarsclose=close
if direction<0 and direction[1]>0
    firstbarsclose:=close
if direction>0 and direction[1]<0
    firstbarsclose:=close
plot(firstbarsclose,style=plot.style_stepline)