text:
Q: How to fix infinite loop with struct in C I have a problem with the struct when storing data. I want to make a sentinel loop so please have a look and help me thank you.
#include<stdio.h>
#include<stdlib.h>
struct Vehichle
{
    char vecType[100];
    char plateNo[10];
    float hours;
};
struct Parking
{
  int parkNo ;
  // 1 =true 0=false
  int availability;

};
int main()
{
  int c = 0;
  int x;
  struct Vehichle vehicle[c];
  struct Parking park[50];

  int counter = 1;
  while(x!=-1)
  {
    printf("Enter -1 to end: \n");
    scanf("%d", &x);
    printf("Enter Vehicle Type etc: suv,mpv and more:");
    scanf("%d",&vehicle[x].vecType);
    printf("Please enter parking Number :");
    scanf("%d",&park[x].parkNo);

    park[x].availability = 1;

    counter++;
  }
}

I expect that after it is stored in the struct, the program will loop.

A: There are a number of problems in your code. Here is your code where I have added some comments:
int main()
{
  int c = 0;
  int x;                      // UPS: x is uninitialized
  struct Vehichle vehicle[c]; // UPS: c is zero so you don't get an array
  struct Parking park[50];

  int counter = 1;
  while(x!=-1)                // UPS: Use of uninitialized x
  {
    printf("Enter -1 to end: \n");
    scanf("%d", &x);
    printf("Enter Vehicle Type etc: suv,mpv and more:");
    scanf("%d",&vehicle[x].vecType);             // UPS: vecType is char array so
                                                 // use %s instead of %d
                                                 // and don't use a &
    printf("Please enter parking Number :");
    scanf("%d",&park[x].parkNo);

    park[x].availability = 1;

    counter++;

  }
}

Besides that you have a problem when the user input is -1. The current code just continues and adds an element at index -1. That's illegal.
To fix add an extra line after the scanf. Like:
    scanf("%d", &x);
    if (x == -1) break;  // Stop the while loop

With that change you can do while(1) instead of while(x!=-1)
Some extra comments:
You should check that the user input (aka x) is within the valid range to be used as array index.
You should also check the return value of scanf. Like:
if (scanf("%d", &x) != 1)
{
    // Invalid input"
    ... error handling ...
}

A: (1) Below is an updated code as your code had several problems.
I'm sure that looking at the below code, you would be able to understand the mistakes in your code.
Feel free to use this as the base for writing your own version.
(2) Please read the inline comments carefully. The comments elaborately
explain the intention of that section of code
(3) This is just a quick code. I've not compiled/run/tested this code.
My intention is just to give you an idea about it with one possible example.
/* A very basic parking manager module
When a vehicle comes in for parking
a)capture vehicle info & parking lot number where it is parking
b)mark that lot as unavailable
When the vehicle is leaving the parking,
capture parking lot number which is being emptied,
and mark that lot as available
And, have some fun on the way.
*/
#include<stdio.h>
#define YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER                                                                                ({printf("HA HA HA, You didn't read and follow the inline comments !!\nNow stand up, jump 3 times, then sit down, and read all the comments again and do the min code modif to make me go away, else i won't let you escape the parking lot ... hoo ha ha ha ha >-)\n"); updateVehicleParkingInfo=1;})
#include<stdlib.h>

struct Vehichle{
    char vecType[100]; //type of vehicle eg suv,mpv and more...
    char plateNo[10];  //number plate of the vehicle
    float hours;       //???
};

struct Parking{
  int parkNo ; //parking lot num
  bool availability; //Is tbis parking space available? Yes/No
};

struct VehicleParkingInfo{
  struct Vehicle vehicle; //vehicle info
  struct Parking parking; //corresponding parking info
};

//maximum number of parking lots that the parking space has
#define MAX_PARKING_LOTS 10

//parking lot avaialble flags
#define PARKING_LOT_AVAILABLE true
#define PARKING_LOT_UNAVAILABLE false

//flags for vehicle coming in or leaving
#define VEHICLE_ENTERING true
#define VEHICLE_LEAVING false

void main(){
    int updateVehicleParkingInfo; //flag indicating that user wants to update parking info.
    int vehicleDirection; //flag for indicating whether the vehicle is coming in or going out of the parking
    int parkingIdx; //index of the parking lot to fetch values from.

    //array for info about all the parking lots
    struct VehicleParkingInfo vehicleParkingInfo[MAX_PARKING_LOTS];

    //initialize the parking & vehicle info of all the parking lots to zeros
    memset(vehicleParkingInfo,0,MAX_PARKING_LOTS*sizeof(VehicleParkingInfo));

    //for each parking lot, mark it as available and assign parking lot numbers serially
    for(parkingIdx = 0; parkingIdx < MAX_PARKING_LOTS; parkingIdx++){
        vehicleParkingInfo[parkingIdx].parking.parkNo = parkingIdx;
        vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
    }

    //get user's input if parking info needs to be updated or it is time to close and go home
    printf("Update parking info? Enter 0 to end");
    scanf("%d",&updateVehicleParkingInfo);

    /*
    ****  SENTINEL LOOP  ****
    Continue updating the parking info until the user wants to even for unlimited number of times.
    Stop only when user enters a specific value i.e. 0.
    */
    while(updateVehicleParkingInfo != 0){

        printf("vehicle direction? 1 for entering, 0 for leaving:");
        scanf("%d",&vehicleDirection);

        if(vehicleDirection == VEHICLE_ENTERING){
            do{
                printf("Please enter parking Number:");
                scanf("%d",&parkingIdx);

                //*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
                //TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails

                //if parking is not available, print an error message
                if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE){
                    //TODO: change the below messages to fine-tune fun, humor, teasing etc levels (remember humor setting of TARS from Interstellar?)
                    printf("There is some other vehicle parked in this parking lot, please enter another parking lot number\n");
                    printf("BTW, I know which lots are available, but I won't tell you ... hehehe >-) \n, keep trying ...hoo hoo hooo\n");
                }
            //check if the requested parking lot is available, if yes, then take further actions, else request a new parking lot number
            }while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE);

            printf("Yipee, this parking lot is available\n");

            //mark this parking lot number as being used so that another vehicle cannot come here.
            vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_UNAVAILABLE;

            //get vehicle type info and
            // *** CRASH ALERT!!! ***  The scanf below will crash if the user enters more 99+ characters (buffer overflow)
            // Best is to use fgets or getline with the stdin as the stream.
            // Ref https://stackoverflow.com/questions/4023895/how-do-i-read-a-string-entered-by-the-user-in-c
            // TODO: Replace below scanf() with a better/safer implmentation
            printf("Enter Vehicle Type etc: suv,mpv and more:");
            scanf("%s",vehicleParkingInfo[parkingIdx].vehicle.vecType);

            //TODO: other steps.
        }

        if(vehicleDirection == VEHICLE_LEAVING){
            do{
                printf("Please enter parking Number:");
                scanf("%d",&parkingIdx);

                //*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
                //TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails

                //if parking is available, print an error message
                if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE){
                    printf("It appears that the parking lot number is incorrect, please enter correct parking lot number\n");
                }
            //check if the requested parking lot is available, if yes, then request a new parking lot number, else proceed further
            }while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE);

            printf("Bye bye, drive safely\n");

            //mark this parking lot number as available for other incoming vehicles.
            vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
        }

        //get user's input if parking info needs to be updated or it is time to close and go home
        printf("Update parking info? Enter 0 to end");
        scanf("%d",&updateVehicleParkingInfo);

        //TODO: remove the following line of code before running the program
        YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER;

        //go back to while loop,
        //check if the vehicle parking info needs to be updated,
        //break if the user has entered 0

    }//end of the Sentinel loop

    //the above loop will run indefinitely. The user has quite a lot of ways to come out of the loop
    //(1) Enter the sentinel value '0', (easiest path)
    //(2) Somehow stop the program e.g. by banging his/her head really hard on the computer such that computer breaks .. etc

}//end of main()


text:
Q: Access php array index issue After use fgetcsv() function I get an array, then I use a foreach() and I get a "simple" associative array like:
Array
(
  [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1
)

Then I try to access any element and I fail:
 echo $record['ix'];

Notice: Undefined index: ix

echo next($record);  // return nothing!

Maybe is offtopic (not centred in php language) but I'm using some lib (not necessary of course from PHP commenter in http://php.net/manual/es/function.fgetcsv.php)
<?php

require "..\CsvImporter.lib.php";

$importer = new CsvImporter('my_route\\my.csv',true);
while($records = $importer->get())
{
    // debug
    print_r($records[0]);
    exit;

    foreach ($records as $record)
    {
      \\ ..
    }
}

And my screen output is
Array ( [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1 )

My data:
ix,radical,variant,simplified,pinyin,english,strokes
1,一,,,yi1,one,1
2,丨,,,gun3,line,1
3,丶,,,zhu3,dot,1

So how is possible I'm unable to access any key ?

A: As you posted your data above. Your csv importer giving you each row with comma. So you need to explode it then use however you want to use
Example code \
 $i=0;
 while($records = $importer->get())
 {
      if($i>0) //skip first row it is heading
      {
           $data = explode(',',$records);
           print_r($data);
          // now `$data[0]` contains `ix` value for your first csv row and so on
      }
      $i++;
 }

A: I used some lib and the default delimiter was "\t" so something like 'ix,radical,variant,simplified,pinyin,english,strokes' was THE key and '一,,,yi1,one,1' the only value
Now, I see the problem I can do it easy:
$f = 'file.csv';
$separator = ',';

$file = file_get_contents($f);

// bi-dimensional array
$regs = array_map(function($reg){return (explode($separator,$reg));},explode("\n",$file));

Thanks all!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Регулярное выражение, проблема с пробельными символами Здравствуйте, помогите с написанием регулярного выражения в одну строчку, пробовал заменять отступы на \t а где перенос строки на \n но все равно не работает выражение, а если вернуть все на место работает без проблем.

                      (.*?)
                    <\/b>

                      (.*?)
                    <\/i>

A: Если не совпадет, выложите, пожалуйста, на pastebin то, с чем должна совпасть регулярка
$a = '
                      some text

                      some text

';
$pat = '-\s*\s*(.*)\s*\s*
\s*\s*(.*)\s*\s*
\s*
-';
var_dump(preg_match($pat, $a));

пробовал заменять отступы на \t а где перенос строки на \n

в приведенной вами регулярке не отступы, а пробелы, плюс перенос строки на винде будет не просто \n, а \r\n


text:
Q: JavaScript: Why []+(-~{}-~{}-~{}-~{})+(-~{}-~{}); returns "42" Saw this in my newsletter. Tested on Chrome and Firefox.  I still can't figured it out.
[]+(-~{}-~{}-~{}-~{})+(-~{}-~{});    //=>  "42"

A: Evaluating:
~{}

is evaluated using the internal function:
~ToInt32({})

which gives -1.
Ref ECMA spec - http://www.ecma-international.org/ecma-262/5.1/#sec-9.5
and this explanation - http://jibbering.com/faq/notes/type-conversion/#tcToInt32
Therefore, in this case
(-~{}-~{}) == 2
(-~{}-~{}-~{}-~{}) == 4

As you have []+ in the start of expression, javascript use plus operands like string. So you have "" + "4" + "2" = "42"

A: The ~ operator is a Bitwise NOT operator. It returns the "1's complement" of a number. Because of that {} is converted into a number, resulting in NaN. The same would happen with +{} == NaN. The bitwise not of ~NaN == -1. So:
(-~{}-~{}-~{}-~{}) == 4 & (-~{}-~{}) == 2
The DefaultValue for an empty array is an empty string. For example []==[]+[] && []+[]==''
From that, the full parsing is:
[]+ /*converted to ''+*/ (-~{}-~{}-~{}-~{}) /*Equals numeric 4, but concatenated as a string to become '4'*/ + (-~{}-~{}) /*Equals numeric 2, but concatenated as a string to become '2'*/ and the end result is actually '42'.
You can validate this via typeof([]+(-~{}-~{}-~{}-~{})+(-~{}-~{})) === 'string'


text:
Q: HOUCKS UP A LUGI
Daisy Domergue looks over the letter with interest…
  THEN…
  HOUCKS UP A LUGI
  and SPITS it on the letter with a BIG SPLAT.

Source: https://indiegroundfilms.files.wordpress.com/2014/01/1390849759320.pdf Page 16 of PDF, numbered page 14.
This is a quote from the script from the movie The Hateful Eight by Quentin Tarantino. What does "houcks up a lugi" mean? My GOOGLE research failed. In the scene Daisy just spat on the letter.

A: Actually, the spelling with which I am am familiar is

to hock up a loogie

Here is a definition from urban dictionary

hock a loogie
  To cough up and spit out a large glob of flem usually resulting in a loud a cough and throat clearing noise.

Here is a tutorial.

A: This is mostly a spelling issue.
The phrase is normally spelled "Hock a loogie"... and it has an Urban Dictionary article:

To cough up and spit out a large glob of flem usually resulting in a loud a cough and throat clearing noise.

Note that we generally spell "flem" - phlegm...
Essentially, "hocking up a loogie" is the act of clearing one's throat and then spitting out a blob of phlegm.

A: Both Urban Dictionary
and the script in question misspell the first word.
The standard spelling is hawk:

hawk3 – verb 1

  Clear the throat noisily:

  'he hawked and spat into the flames'

  1.1.   [with object] (hawk something up) Bring phlegm up from the throat.

'Well most people can hawk it up and spit it out of their mouth… but I cannot do that.'

– OxfordDictionaries.com

Incidentally, the pronunciation familiar to me (west coast USA)
is like "huck," which is slang for throw.
The second word is nonstandard English and typically spelled loogie:

loogie – noun

  1.   (US, slang) A thick quantity of sputum, usually containing phlegm.

  2.   (US, slang) Any thick, disgusting liquid.

– Wikitionary.org


text:
Q: Counting and Outputting like characters between two strings I would like to compare two user-defined strings and output the count of the number of characters shared between the two strings, without resorting to using arrays. I then need to output each of those characters. I understand the user-input part using a Scanner, but afterwards I am clueless.
For example, "hamper" as string1, and "happened" as string2 would return:
number of shared characters = 5
shared characters >> "h", "a", "p", "p", "e", "e"
Here is what i have so far.  It prints each character on a separate line though.  Is there a way without arrays to list them all on one line like above?:
    public class CountMatches {

  public static void main(String[] args)
  {
    //Declare both Strings.
    String word1;
    String word2;
    int count = 0;

    //Call for User Input.
    Scanner inputDevice = new Scanner(System.in);
    System.out.print("Input String 1 >> ");
    word1 = inputDevice.next();
    System.out.print("Input String 2 >> ");
    word2 = inputDevice.next();
    inputDevice.close();

    //Determine lengths and set label accordingly.
    String BigWord;
    String SmallWord;

    if (word1.length() > word2.length())
    {
        BigWord = word1;
        SmallWord = word2;
    }
    else
    {
        BigWord = word2;
        SmallWord = word1;
    }

    //Count and Display the like characters.
    for (int i = 0; i < SmallWord.length(); i++)
    {
        if (BigWord.contains(String.valueOf(SmallWord.charAt(i))))
        {
            System.out.println("both words contain the letter " + SmallWord.charAt(i));
            count++;
        }
    }

    //Display the count of like characters.
    System.out.print("Number of like characters >> " + count);
  }

    }

A: Let's say you have word1 and word2:
String biggerWord;
String smallerWord;
if (word1.length() > word2.length()) {
   biggerWord = word1;
   smallerWord = word2;
} else {
   biggerWord = word2;
   smallerWord = word1;
}
for (int i = 0; i < smallerWord.length(); i++) {
  if (biggerWord.contains(String.valueOf(smallerWord.charAt(i)))) {
    counter++;
  }
}

This figures out which word is bigger. Then for the length of smallerWord, iterate over it one character at a time and see if biggerWord contains that character. If it does, increment the counter.
counter should then have the number of common characters by the end of the loop.
This was written freehand, so be aware of syntax and minor logic errors. Or I misunderstood your assignment. It should be pretty close though.

A: A really nice way is to sort the string alphabetically.
sortedWord1 = new String(Arrays.sort(word1.toCharArray()));
sortedWord2 = new String(Arrays.sort(word2.toCharArray()));

What that does is turn the words into character arrays, sort them alphabetically, then makes them into a string again.
The next step is just to iterate from the beginning and print out all common characters. This would be easier since they're sorted.
int index1 = 0;
int index2 = 0;
while((index1 < sortedWord1.length()) && (index2 < sortedWord2.length()) {
  if(sortedWord1.charAt(index1) == sortedWord2.charAt(index2)) {
    System.out.print(sortedWord1.charAt(index1) + " ");
    index1++; index2++;
  }
  else if(sortedWord1.charAt(index1)> sortedWord2.charAt(index2)) {
    index2++;
  }
  else {
    index1++;
  }
}

I haven't checked it for syntax errors, but it should be good.


text:
Q: WinRAR "Total path and file name length must not exceed 260 characters" WinRAR is giving me the 260 character limit error on a path/filename that is only 216 characters long. See below. The reason is the extraction destination is a temporary folder that is tool long. See https://superuser.com/questions/154969/where-winrar-extracts-files for details on this folder.
!   C:\<path>\<filename.rar>: Cannot create <filename>
Total path and file name length must not exceed 260 characters

How do I modify this?

A: You can change Winrar's default temp directory from Winrar's Options > Settings > Paths tab. Thanks to https://superuser.com/questions/154969/where-winrar-extracts-files for the solution.
For the shortest path possible, set it to c:/ or some other driver's root. Pay attention to the temporary folders it will create (and not delete) that starts with "RAR..." or "Rar...". You can delete this once WinRAR is done.


text:
Q: Stop float right dropping to next line (Float Drop) I have the following code at http://jsfiddle.net/ssCqe/, I am trying to get the text "icon" not to drop to the next line.
Updated
Seems it doesn't work in firefox 10.0.1
Please can anyone help me?
Thanks

A: If you remove white-space: nowrap; from UL.jqueryFileTree LI it works on FF, IE9 and Chrome
Check it on JsFiddle


text:
Q: SignalR Hubs in a class library? Is this a good idea or a bad one? I'm fairly new to SignalR.
I started writing a hub and putting that logic in a class library.
Here's what I'm trying to accomplish:
I have a "preprocessor" service that goes off and pre-fetches a number of objects/documents/etc from external sources and puts them into the cache. I am using the hub to communicate to clients when all items have been pre-fetched.
We also have several client consumers. Among them include:

*

*a typical MVC app/project

*a console app we use for quick testing

*a webapi and a WCF/SOAP project for exposing our services to external parties

*a unit test project

The problem
By putting the hub in the class library, I've made all the downstream consumers (including other class libraries) have a dependency on OWIN... and I now need my startup class (and or app config settings to tell Owin to not use it).
public class Startup
{
   public void Configuration(IAppBuilder app)
   {
      app.MapSignalR();
   }
}

or
<add key="owin:AutomaticAppStartup " value="false" />

The Architecture?
This 'smells' to me. Maybe SignalR hubs are not meant to be in a class library? If that is the case, what would be a better design? e.g. have the hub in its own WebApi Service? And proxies to this service? That way, my preprocessor logic (contained in a class library) can call the Hub?
Suggestions would be greatly appreciated.

A: You can have your SignalR stuff in a class library for sure, but in your case that should probably be a different one from the one you have where the preprocessing happens. The SignalR one would be pure infrastructure, and no business logic would happen, just messaging. You can define some interface in the middle and plug the infrastructure into your preprocessing one. This way the dependency on SignalR is behind an interface, your code is clean, and the dependency on Owin is isolated into the infrastructure.


text:
Q: Fresh Ubuntu Install Rtl88x2bu wireless adapter I'm having a really difficult time getting this wifi usb adapter working on a fresh install. Last night I hopped from Manjaro where it was working (with some config originally) to Ubuntu. The Adapter is a Realtek 8812BU Wireless USB. I have gone through each of the other postings with a similar issue but none seemed to solve my issue. I'm guessing it is the last step of below that never completes.
Here is what i've tried. I saw on some other posts that this git repo https://github.com/cilynx/rtl88x2bu was useful in getting it to work. So I did the following.
Clone the repo
cd rtl88x2bu
VER=$(sed -n 's/\PACKAGE_VERSION="\(.*\)"/\1/p' dkms.conf)
sudo rsync -rvhP ./ /usr/src/rtl88x2bu-${VER}
sudo dkms add -m rtl88x2bu -v ${VER}
sudo dkms build -m rtl88x2bu -v ${VER}
sudo dkms install -m rtl88x2bu -v ${VER}
sudo modprobe 88x2bu

However on the very last step (modprobe) my terminal just hangs there every time. I've even given it over an hour on one try.
Running:
OS: Ubuntu 20.04.1 LTS
Does anyone have any ideas as to how to fix this?

A: Following the comments, I was able to solve my issue after noticing that kernel module 8822 was loading but never live. After a big of digging through logs I saw that I was getting an out-of-tree module taints kernel message. I removed the module with the following code:
sudo dkms remove 8822bu/1.1 --all

Then after a reboot everything was working perfectly.


text:
Q: 2 Computers, 2 Internet Connections, 1 Router, Need LAN capability My old college roommate moved into an apartment above mine. He has his own Internet via cable and I have mine. I am trying to include his machine as part of my workgroup/homegroup LAN network in Windows 7 without me sharing his Internet Connection or him sharing mine. But we'd like to be able to access each others files like music and tv-shows, we also work together in a graphics firm so I'd like the ability to transfer large PSD's over CAT5. Might also try video gaming. Basically I'm seeking a physical connection, wireless is not an option.
Is that possible? Can it be done using one router or do I have to use two, one for each machine and then connect the routers? Reason I ask is he's connected straight to the modem, I'm connected through a router.
Thank you.

A: There are lots of ways to do this, depending on how much you want to spend, how much security you want to put in place between your network and his machine, and whether or not you want to plan for the day when he has more than just the one machine on his network.
For now, if you want to minimize costs and aren't too worried about security, you would add a second network card to his machine (if it doesn't already have a spare) and connect that card into a spare switch port on your network. Then configure his second network card to have a static IP address on your home network, but don't tell the second network card about your default gateway. Without knowing about your default gateway, his OS won't try to get out to the Internet via your network.
Don't turn on any kind of Internet Connection Sharing (NAT, or any kind of bridging/switching or IP forwarding) and his machine won't pass traffic from your network onto his Internet connection.
So basically, make his machine multi-homed on the two networks, but not acting as a gateway, and let it think your network is a just a stub network with no off-subnet connection.  All the machines on your network will think his machine is just another machine on your network, and they won't have a way to go "through" his machine to get to his Internet connection.


text:
Q: Executing SQL query in Golang I've seen two ways of people executing queries using Golang builtin database/sql queries. One of them is using fmt.Sprintf:
func (db *DB) CreateUserTable() (sql.Result, error) {
    statement := "CREATE TABLE %s (%s, %s, %s, %s, %s)"
    v := []interface{}{"User", "ID int PRIMARY KEY NOT NULL", "Name varchar(100) UNIQUE", "Email varchar(100) UNIQUE", "Address varchar(100) ",  "Username varchar(100) UNIQUE"}
    return db.Exec(fmt.Sprintf(statement, v...))
}

and the other one is using prepared statement:
func (db *DB) CreateUserTable() (sql.Result, error) {
    statement, err := db.Prepare("INSERT INTO User(tbl1,tbl2,tbl3) VALUES(?,?,?)")
    if err != nil {
        log.Fatal(err)
    }
    return statement.Exec("value1", "value2", "value3")
}

The first gives benefit by enabling you to dynamically set the table name, column name, and the values. But the second one only for values. What's the difference? Which one should I use?

A: It is cleaner to use prepared statements so that whenever a requirement changes you can easily modify the statements. Also to prevent SQL injections.

Prepared statements is much better than concatenating strings, for all
  the usual reasons (avoiding SQL injection attacks, for example).
In MySQL, the parameter placeholder is ?, and in PostgreSQL it is $N,
  where N is a number. SQLite accepts either of these.

One more thing is Prepared statements can be used for repetitive approach, can be executed multiple times and can be destroyed.
stmt, err := db.Prepare("select id, name from users where id = ?")
if err != nil {
    log.Fatal(err)
}
defer stmt.Close() // closing the statement
rows, err := stmt.Query(1)

And you are using interfaces
func (db *DB) CreateUserTable() (sql.Result, error) {
    statement := "CREATE TABLE %s (%s, %s, %s, %s, %s)"
    v := []interface{}{"User", "ID int PRIMARY KEY NOT NULL", "Name varchar(100) UNIQUE", "Email varchar(100) UNIQUE", "Address varchar(100) ",  "Username varchar(100) UNIQUE"}
    return db.Exec(fmt.Sprintf(statement, v...))
}

which can take any type of parameter under the hood which can be vulnerable
For more detailed information Go for this Link

A: Never build SQL from strings that come from outside your system.

Always use the ? syntax.
If you must set SQL parts like table names, prepare multiple, complete SQL statements that contain ? for the values. Select the SQL to execute, maybe based on user input, but never build SQL from user input.


text:
Q: Another CURL to C# conversion attempt Here is my CURL example, provided by the API author:
$data = array("username" => "XX", "password" => "XX");
$data_string = json_encode($data);
$ch = curl_init('https://<url excluded>');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//Attached the path to .CRT file
curl_setopt($ch, CURLOPT_CAINFO, getcwd() ."/AddTrustExternalCARoot.crt");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '
. strlen($data_string))
);
$result = curl_exec($ch);
echo $result;

The method should return an alphanumeric API key for use in subsequent API calls.  All of my attempts using WebClient and HttpRequest have returned either 400 or 403 errors.
Any help I can get figuring out the correct C# library and syntax would be great.

A: using RestSharp and clarifying the communication requirements with the API provider allowed me to get this working.  Thanks for the suggestion.


text: Q: Files with same name is not uploading through move_uploaded_file My folder name is 'upload-images'. I am using move_uploaded_file function of PHP to upload files into this folder and it is working correctly but if I try to upload a file twice it is not uploading. Means two files with same name is not uploading. Anyone have solution to this ??


text:
Q: Viewpager inside Viewpager Scroll Issue in my main activity i have a horizontal viewpager. Inside one of the fragment of the viewpager i have another vertical viewpager. Both works fine. But for the horizontal viewpager, i need to scroll from the edge of the screens. But i want it to be scrolled from anywhere in the screen.
my horizontal viewpager setup:
viewPager = (ViewPager) findViewById(R.id.viewpager);
        adapterViewPager = new HorizontalViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapterViewPager);
        viewPager.setCurrentItem(1);

horizontal viewpager adapter:
public class HorizontalViewPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 3;

    public HorizontalViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return MoreFragment.newInstance("Fragment MoreFragment", "HA HA HA");
            case 1:
                return NewsFragment.newInstance("Fragment 1", "HA HA HA");
            case 2:
                return WebViewFragment.newInstance("Fragment Webview", "HA HA HA");
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + position;
    }
}

in my news fragment i have another viewpager.
viewPager = view.findViewById(R.id.shortpager);
        adapterViewPager = new VerticalPagerAdapter(getActivity().getSupportFragmentManager(), newsList);
        viewPager.setAdapter(adapterViewPager);

My vertical viewpager class:
public class VerticalViewPager extends ViewPager {

    public VerticalViewPager(Context context) {
        super(context);
        init();
    }

    public VerticalViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // The majority of the magic happens here
        setPageTransformer(true, new VerticalPageTransformer());
        // The easiest way to get rid of the overscroll drawing that happens on the left and right
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    /**
     * Swaps the X and Y coordinates of your touch event.
     */
    private MotionEvent swapXY(MotionEvent ev) {
        float width = getWidth();
        float height = getHeight();

        float newX = (ev.getY() / height) * width;
        float newY = (ev.getX() / width) * height;

        ev.setLocation(newX, newY);

        return ev;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev){
        boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
        swapXY(ev); // return touch coordinates to original reference frame for any child views
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(swapXY(ev));
    }

    private class VerticalPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.75f;

        @Override
        public void transformPage(View view, float position) {

            if (position <= -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 0) { // [-1,0]
                // Use the default slide transition when moving to the left/top page
                view.setAlpha(1);
                ViewCompat.setElevation(view, 1);
                // Counteract the default slide transition
                view.setTranslationX(view.getWidth() * -position);
                view.setTranslationY(0);

                //set Y position to swipe in from top
                float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);

            } else if (position <= 1) { // [0,1]
                view.setAlpha(1);
                ViewCompat.setElevation(view, 2);

                // Counteract the default slide transition
                view.setTranslationX(view.getWidth() * -position);
                view.setTranslationY(position * view.getHeight());

                // Scale the page down (between MIN_SCALE and 1)
                view.setScaleX(1);
                view.setScaleY(1);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }

        }
    }

}

vertical viewpager adapter:
public class VerticalPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 3;
    private final ArrayList<News> newsList;

    public VerticalPagerAdapter(FragmentManager fm, ArrayList<News> newsList) {
        super(fm);
        this.newsList = newsList;
    }

    @Override
    public Fragment getItem(int position) {
        return ShortFragment.newInstance("Fragment 1", "HA HA HA", newsList.get(position));
    }

    @Override
    public int getCount() {
        return this.newsList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + position;
    }
}

Vertical viewpager scrolls smoothly. Currently for horizontal viewpager, i have to scroll from the edge of the screens. But i need to make it scrolled like the vertical one from anywhere in the screen.

A: Issue with your code is your VerticalViewPager
If you notice the code,
@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
    boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
    swapXY(ev); // return touch coordinates to original reference frame for any child views
    return intercepted;
}

Step-1, Call super with swapped gesture.
Step-2, Perform actions on vertical view pager with current gesture.
And if you specifically see the comment, // return touch coordinates to original reference frame for any child views this clearly tells that gesture is first consumed by child.
So in your vertical view pager since you are swapping the gestures, it is consuming the Horizontal Gesture even before passing it to the parent. Thats why your horizontal view pager do not get the gesture.
If you are using Vertical View Pager with any conflicting gesture implementation like ScrollView, Lists, RecyclerView, ViewPager, etc. use the one as in the link below. It is deprecated but works with all Gesture Conflicting Views.
https://github.com/kaelaela/VerticalViewPager

A: I had this issue and I resolved it by wrapping the viewpager in a Scrollview
<ScrollView
            android:id="@+id/nested_scroll"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <androidx.viewpager2.widget.ViewPager2
                android:id="@+id/view_pager"
                android:nestedScrollingEnabled="false"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </ScrollView>


text:
Q: ImageMagick displays garbled text instead of image I am trying to use ImageMagick class functions in PHP.
To get familiar with ImageMagick, I wrote a few lines of code in PHP to display a red square in my browser.
Instead of displaying a red square, I get garbled text.
I know ImageMagick is installed because I can use ImageMagick functions to save the red square to a file.
Thanks in advance for any help for this newbie to ImageMagick and StackOverflow!
Here's my PHP code:
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');
$image->writeImage("MyOutput.png");

header('Content-type: image/png');
echo $image;  //This causes just raw text to be displayed. :(

echo ''; //Displays a 100x100 red image!
                               //..So, ImageMagick IS installed.

Here's my full PHP file.
<!DOCTYPE html>

    <title>ImageMagick Test</title>

<?php

$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;
?>

A: The main problem you have is that you're sending Content-Type: image/png after putting some output. Once you put any output, PHP immediately sends all response headers and proceeds to the body part of response. The default Content-Type is text/html on most servers, so your browser is interpreting image content as HTML, and thats why you're seeing some garbage. It's a bit like opening PNG file in notepad.
See this question for more information about sending response headers
Also you can't return HTML and image content upon one request, so do not put any HTML in your image-generating file. The image is independent file and it has to be returned upon it's own, separate request, containing only headers, image bytes and nothing more.
This should work:
<?php
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;

Note, that this is whole PHP file and you can't send any other output neither from outside of <?php ?> nor by echoing.
If you want to include your image into HTML you need a second file (it may be plain HTML), which should look as follows:
<!DOCTYPE html>

    <title>ImageMagick Test</title>

Then you can refer either to PHP file if you want to see only image or to HTML file if you want to see image put into HTML context.


text:
Q: Exporting the entire database for elastic search in csv Any ideas on how to export the entire database in elastic search in csv? I just need one index to be exported.
I tried the following python plugin but elastic search as a service provider is complaining on root certificates:
https://github.com/taraslayshchuk/es2csv/blob/master/README.rst
es2csv -i leads -a user:password -u https://host.us-east-1.aws.found.io:9243 -q '' -o database.csv
but I get: elasticsearch.exceptions.ImproperlyConfigured: Root certificates are missing for certificate validation. Either pass them in using the ca_certs parameter or install certifi to use it automatically.
help? I'm using Elasticsearch.co as a service for my elastic search

A: You can use Logstash to export an index to CSV:
input {
 elasticsearch {
    hosts => "localhost:9200"
    index => "some-index"
    query => '{"query": {
                 "match_all": {}
             }}'
}
output {
  file {
    codec => line { format => "%{field1},%{field2}"}
    path => "some-index.csv"
  }
}

Warning: There is a csv output plugin, but it has a known bug for versions Logstash 5.x. The above configuration should be fine.

A: As taraslayshchuk has already said, es2csv has been updated to support SSL. For an elastic.co hosted ES I've been using something like this:
es2csv.py -u https://myserverurl -i myindex-* -r -q '
{
  "query": {
      "range": {
            "@timestamp": {
                "gte": "2017-04-16T00:00",
                "lt": "2017-04-23T23:59",
                "time_zone": "-06:00"
            }
        }
    }
}
' -o outputfile.csv --auth user:password --use-ssl --verify-certs

A: The latest update of es2csv has a SSL patch, which should resolve your problem.


text:
Q: Python request to API gives SSL error I am working with Python2.7 and I need to access a certain API (Nuagen): https://nuagenetworks.github.io/vsd-api-documentation/usage.html
In the documentation, they say the following:

Getting the API key.
  To obtain and API key, the first step is to make a /me API call. This API call returns information about the account being used.

    GET /me HTTP/1.1
    X-Nuage-Organization: my company
    Content-Type: application/json
    Authorization: $AUTHORIZATION_STRING

The authorization string for the /me API MUST be formatted like the following:

    $AUTHORIZATION_STRING = Basic base64($LOGIN:$PASSWORD)

So I try to build my requests in the folowing way;
import requests

url = 'https://an.ip.add.ress:8443/nuage/api/v4_0/me'
user = 'myuser'
passw = 'mypass'
cps = 'myorganization'

headers = {
    "Authorization": "Basic d29jdTpjdXdv",
    "Cache-Control": "no-cache",
    "Content-Type": "application/json",
    "X-Nuage-Organization": "csp",
}

response = requests.get(url, auth=(user, passw), headers=headers)
# Also tried with:
# response = requests.get(url, headers=headers)

However, I'm always getting this error:
requests.exceptions.SSLError: bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],)

Any idea on how to access this API with Python requests? Or any other way?


text:
Q: Bluetooth Low Energy UUID number Now i working on Bluetooth low energy devices i fully read office documentation and i downloaded sample source code from office website
https://developer.android.com/guide/topics/connectivity/bluetooth-le.html
all are working perfectly but i don't know how they are take UUID number ex
'public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb".enter image description here

A: C++ functions using UUID require a pointer to a 16-byte structure (not a string).
If UUID is given as a string, it must be changed to a structure, like this:
String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
UUID Heart_Rate_UUID = { 0x00002a37, 0x0000, 0x1000, 0x00, 0x80, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb };

The struct UUID is { long, short[2], char[8] }
so note, the 3rd group in the string (-8000-) must be reversed (0x00, 0x80) because of processor endianness.
The resulting binary code will actually be
37 2a 00 00 00 00 00 10 00 80 00 80 5f 9b 34 fb
The byte order is totally scrambled for the x86 processor.
For this reason, UUID are normally passed as text in web applications because the network byte order may be different from the processor-dependent byte order.
Microsoft compilers have some extensions such as MIDL (q.v.) that help with the conversion but a lot of programmers just re-write it by hand as I showed above.


text:
Q: this.props.history.push does not redirect on first attempt We are trying to redirect to a search results page once we have our results. We are using axios.get() to send the get request which follows:
export const searchPosts = (type, query) => async dispatch => {
    dispatch({ type: PARTIAL_LOADING, payload: false });

    const res = await axios.get('/api/search/',
    {
        params: {
            type: type,
            query: query
    }});

    dispatch({ type: PARTIAL_LOADING, payload: true });

    dispatch({
        type: SEARCH,
        payload: res.data
    });
};

We are trying to redirect to the next page using the following:
async submitSearch(values) {
  const type = values.type ? values.type : "Default";
  const query = values.query;

  if (type && query)
  {
    await this.props.searchPosts(type, query)
    .then(_ => {
      this.props.history.push('/search_results');
    });
  }
}

This redirects after the first attempt but will always fail the first time.


text:
Q: CCheckBoxColumn with cgridview creating checkboxes when moving between pages I wanted to delete selected columns so I did like this in cgridview and in controller I was able to get the values and delete so every thing is working fine regarding this.
array(
    'class'=>'CCheckBoxColumn',
    'id'=>'images-grid',
)

But, when I click on pagination numbers check boxes are getting created automatically at bottom.

and also this top check box which is used to select all is getting disappeared when navigating I think that check box is getting displayed in bottom I guess.

Please, let me know how to solve this issue.

A: Problem Solved :) I was using id of checkbox same as id of cgridview, now I changed it to autoId. that solved the problem but no Idea why It was creating checkbox below gridview when we navigate and how autoId solved it. –


text:
Q: Conservation for $u_t + cu_x = 0$ This question is about Exercise 3.6 (p. 73) of Miller's Applied Asymptotic Analysis, which asks:

Let $u_0(x)$ be differentiable and suppose $\int_\mathbb{R} u_0(x)^2 \,dx < \infty$.  Show that whenever $u(x,t)$ is a smooth solution of the initial value problem
  $$
u_t + cu_x = 0, \qquad u(x,0) = u_0(x),
$$
  the integral
  $$
\int_\mathbb{R} u(x,t)^2\,dx
$$
  is independent of $t$.  Hint: begin by multiplying the PDE by $u$.

(The goal of the rest of the exercise is to prove existence and uniqueness of solutions for the PDE.)
Following the hint I multiply through by $2u$ to get
$$
2uu_t + 2cuu_x = (u^2)_t + c(u^2)_x = 0,
$$
then integrate with respect to $x$:
$$
\int_\mathbb{R} \left[ (u^2)_t + c(u^2)_x \right]dx = 0.
$$
Supposing that at least one of the terms is integrable I split it in two, so that
$$
\int_\mathbb{R} (u^2)_t\,dx + c \int_\mathbb{R} (u^2)_x\,dx = 0.
$$
Now I have the following questions:

1. To show what is asked it seems necessary that
  $$
\lim_{x \to \pm\infty} u(x,t)^2 = 0,
$$
  since then
  $$
\int_\mathbb{R} (u^2)_x\,dx = 0.
$$
  This isn't implied by the assumptions as far as I can tell.  What can I do?
2. How can I justify the interchange of integral and derivative:
  $$
\int_\mathbb{R} (u^2)_t\,dx = \frac{d}{dt} \int_\mathbb{R} u^2\,dx
$$
  ?  The usual justification I know would be to show that $|(u^2)_t| \leq f(x)$ for some integrable $f$, but this doesn't seem like it can be true in this case.
(It fails for $u(x,t) = \exp[-(x-ct)^2]$, for instance.)

A: 1) Usually people impose the condition that $c > 0$. If this is also true for your case, do you see how 1) is resolved?
2) I'm a little embarassed that I haven't quite figured out how to do this in the way your book probably wants you (admittedly, I haven't looked at it to fairly say this). Nevertheless, here's a way of doing this.
a) Notice that the function $f(t,x) = u(t, x+ ct)$ satis $\partial_t f(t,x) = 0$ (why?), hence it's a depending solely on $x$, and in particular , by setting $t=0$, we must have $f(t,x) = u_0(x)$
b) By relabeling, we must have $u(t,x) = u_0(x - ct)$
c) $\int_{\mathbb{R}} u^2(t,x) dx = \int_{\mathbb{R}} u^2_0(x - ct) dx = \int_{\mathbb{R}} u^2_0(x) dx$
Where the final expression is finite (by the given) and independent of $t$.


text:
Q: Why is the allowRegexes keyword in pyinputplus allowing ABC in pyip.inputNum(allowRegexes=[r'(C)+'])? Working through Automate the Boring Stuff, and can't see why allowRegexes keyword in pyinputplus doesn't seem to be working for me.
for example
>>> import pyinputplus as pyip
>>> pyip.inputNum('input: ', allowRegexes=[r'(C)+'])
input: AB
'AB' is not a number.
input: ABC
'ABC'

It seems as though as long as I input any string containing C it will be allowed. But it should be only C or CCCC... that should pass I think.
I can't see that anyone else had issues with this. Is this some issue with Python versions, or am I missing something and being a regular expression donut?

A: The issue is either within your assumption of how the parameter allowRegexes works, or in your regex. Though I guess it's probably the former.
The behavior is this: If the regex set in allowRegexes matches any part of the input, the whole string will be valid (respectively invalid, if used in blockRegexes). The regex does not need to match the entire input. Granted, that may not be completely clear from the wording in the documentation, but the examples listed in the description of pyinputplus.inputInt() illustrate this behavior.
Since (C)+ will match any C in a string, any sequence that contains a C anywhere will pass validation, as you observed. If you wanted only sequences of C without spaces, like C, CC, CCC, etc., to be added as valid input, your regex could e.g. look like this: ^C+$. See https://regex101.com/r/x03Fes/1
>>> import pyinputplus as pyip
>>> pyip.inputNum('input: ', allowRegexes=[r'^C+$'])
input: ABC
'ABC' is not a number.
input: ACB
'ACB' is not a number.
input: CAB
'CAB' is not a number.
input: CAC
'CAC' is not a number.
input: CCC CCC
'CCC CCC' is not a number.
input: CCC
'CCC'


text:
Q: OpenFileDialog under the hood This is my first question here because I ended up in dead end.
I'm using ZIP 2 Secure EXE (very good software from Chilkat) to create setup.exe for application. ZIP 2 Secure EXE can be run without GUI with one or more parameters.
The problem is that when I call ZIP 2 Secure EXE (ChilkatZipSE.exe) without using OpenFileDialog form to determine location of ChilkatZipSE.exe, it doesn't run process with System.Diagnostics.Process class. The way I call ChilkatZipSE.exe is "..\ChilkatZipSE.exe -cfg settings.xml". Everything is OK with settings.xml and there is UnlockCode node which is needed for creating setup.exe file. When I use OpenFileDialog ChilkatZipSE.exe creates desired setup.exe and it's working fine.
Bellow is my code that I use:
Private Sub btnStartApp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartApp.Click

    If txtExtAppPath.Text.Length > 0 AndAlso System.IO.File.Exists(txtExtAppPath.Text) Then

        Dim myFile As New FileInfo(txtExtAppPath.Text)
        txtExtAppLog.Text = StartApplication(myFile.FullName, txtExtParams.Text, chkIsHidden.Checked)
        'txtExtAppLog.Text = StartApplication(txtExtAppPath.Text, txtExtParams.Text, chkIsHidden.Checked)

    End If

End Sub

Public Function StartApplication(ByVal fileFullPath_ As String, ByVal fileParameter_ As String, ByVal isHidden_ As Boolean) As String

    Dim lassie As String = String.Empty

    Try

        Dim newProcess As New ProcessStartInfo()
        newProcess.FileName = fileFullPath_
        newProcess.Arguments = fileParameter_
        If isHidden_ Then newProcess.WindowStyle = ProcessWindowStyle.Hidden

        If System.IO.File.Exists(fileFullPath_) Then

            Using startedNewProcess As Process = Process.Start(newProcess)
                'startedNewProcess.EnableRaisingEvents = True
                startedNewProcess.WaitForExit()
            End Using

        Else

            lassie = "File " + fileFullPath_ + " doesn't exist."

        End If

    Catch ex As Exception

        lassie = ex.Message

    End Try

    Return lassie

End Function

Thanks, magnumx.

A: the problem was the given parameter. When using OpenFileDialog it knows where settings.xml is. But when calling "..\ChilkatZipSE.exe -cfg settings.xml" without OpenFileDialog it must be used as "..\ChilkatZipSE.exe -cfg ..\settings.xml"


text:
Q: Use same XAML files in multiple projects I have four similar apps with different branding.
App
\ Views
  \ MainPage.xaml
  \ LoginPage.xaml
  \ YourAccountPage.xaml
  \ TodoListPage.xaml
  \ TodoDetailsPage.xaml
  \ TodoItemView.xaml
\ Images
  \ App1_logo.png

I want to make my projects easier to manage. When I make one change I must usually have 4 instances of Visual Studio up and do the same change in all projects, or risk forgetting it.
I do API calls and display data in .xaml.cs files.
I have already separate projects for models and service implementation. But it's not straightforward with XAML files.

A: You are giving very little information on the context of your application. Since you are using XAML I'm assuming you intend to use MVVM.
I think your problem is that you call data and do API calls in code behind (xaml.cs). Aggregating data to display is what a view model is for.
You should design your view with the thought in mind that the data you need will be provided for you by the view model (it does not matter how yet). If need be, imagine that you told some other developer exactly what kind of data you need, i.e. a list, sorted by timestamp. How that other dev aggregates that data is not your concern.
Avoid doing logic in the view as this will cause a coupling of your business logic with your view which will lead to exactly the problem you have right now.
Once your view is decoupled from the logic you could make a library with just the views.


text:
Q: Android - TextView height issue according to content (text) I have a RelativeLayout whose layout_height is set to "wrap_content" and inside that I have a TextView whose text is set at runtime. I have set android:layout_height="wrap_content" to my TextView, but it doesn't seems to change the height of the Textview even if the content is larger than 1 line.
It only takes the height of single line and displays 1 line, and all the remaining lines appears to be marquee vertically which is seen when I drag it manually...
So plz anyone can help me out.

A: <TextView
    android:id="@+id/someId"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ellipsize="none"
    android:layout_weight="1"
/>


text:
Q: How to get page object by name or number relative to another page object in Selenium WebDriver Is it any way how to return page object by name or number like this:
homePage.get(widget.class, "Name").get(Input.class, 1).setValue("yahoo");

I create classes of my UI elements (widget, Input) with get methods which can return objects of any class
Class of Widget
public class widget{
    WebDriver driver;
    By searchResult = By.xpath("//div[@id='ires']//a[contains(text(), '')]");

    public widget (WebDriver driver) {
        this.driver = driver;
    }

    public void click() {
        driver.findElement(searchResult).click();    }

    public <T> T get(Class<T> expectedPage, String uiclass){
        return PageFactory.initElements(driver, expectedPage);
    }

}

Class of Button object
public class Button {
    WebDriver driver;

    public Button (WebDriver driver) {
        this.driver = driver;
    }

    @FindBy(name="btnG")
    WebElement button;

    public void click() {
        button.click();
    }

    public <T> T get(Class<T> expectedPage){
        return PageFactory.initElements(driver, expectedPage);
    }

}

Class of HomePage
public class HomePage {
    WebDriver driver;

    public HomePage(WebDriver driver) {
        this.driver = driver;
    }

    @FindBy(xpath="//div[@class='widget']//a[text()='']")
    WebElement linkInWidget;

    public void click() {
        linkInWidget.click();
    }

    public <T> T get(Class<T> expectedPage, String name){

        return PageFactory.initElements(driver, expectedPage);
    }

}

My test
public class searchTest {
    WebDriver driver;

    @BeforeTest
    public void setup() {
        driver = new FirefoxDriver();
        driver.get("https://www.google.com.ua/");
    }

    @Test
    public void testUI() {
        HomePage homePage = PageFactory.initElements(driver, HomePage.class);
        widget widget = PageFactory.initElements(driver, widget.class);

        homePage.get(widget.class).get(Input.class).setValue("yahoo");
        homePage.get(widget.class).get(Button.class).click();

   }
}

And a result is that we can compose any object by using our classes
homePage.get(widget.class).get(Input.class).setValue("yahoo");

Question:
My xpath is dynamic and should contain name
"//div[@class='widget']//a[text()='+name+']"

How to return new object with  specific name with construction like this:
page().get(Widget.class, "Widget name").get(Button.class, "Button name").click

Any ideas?

A: Before you click on new window set the window into a map
after you open the window this window is not in the list so you can get his number
i have some method using java8

//Before click
 public static String initWindows(WebDriver driver) {
    windows = new HashSet<String>();
    driver.getWindowHandles().stream().forEach(n -> windows.add(n));
    return driver.getWindowHandle();
  }

//After the click
  public static String getNewWindow(WebDriver driver) {
    List<String> newWindow = driver.getWindowHandles().stream()
        .filter(n -> windows.contains(n) == false).collect(Collectors.toList());
    System.out.println(newWindow.get(0));
    return newWindow.get(0);
  }


text:
Q: addReplyTo doesn't seem to work everyone.
I'm trying to configure a email specifying an email address to reply to using the addReplyTo method and although the email is sent successfully

when I log into the email account(octunprg@gmail.com) to read and reply to the email that has just been sent, the email address that appears in the To field is the same email address (octunprg@gmail.com) not the one I indicated using "addReplyTo"(eddysmith1818@gmail.com) when I set the email.
Is it the normal operation?? Am I doing something wrong??

            Email email = new SimpleEmail();
            email.setHostName("smtp.gmail.com");
            email.setSmtpPort(587);
            email.setAuthenticator(new DefaultAuthenticator("octunprg@gmail.com", "123456"));
            email.setTLS(true);
            email.setFrom(from, name);// 'eddysmith1818@gmail.com', 'Eddy Smith'
            email.setSubject(subject);
            email.setMsg(message);
            email.addReplyTo(from, name);   // 'eddysmith1818@gmail.com', 'Eddy Smith'
            email.addTo("octunprg@gmail.com");
            email.send();

A: This may be a mistake in your email client (Gmail, as I see).


text:
Q: How to interact with a MySQL database using winJS? I just started with Win 8 apps and I need to create an app that interacts with a MySQL database. I think I will go with the HTML5 & WinJavascript way but I have not seen a way about how to do it.
Can somebody give me some example using queries like select, insert and delete on WinJS?
I know some Javascript and HTML, and the lifecycle of a Win app. I tried to search for answers on how to connect to a database but I could not find anything.

A: WinJs is Javascript.
You can use Ajax to call webservice that will perform your queries.
Or if you don't have too big of a database I recommend you use Azure Mobile Services for storing your data. It's very well integrated with WinJs and it make it easy to work with.


text:
Q: Safari: Shortcut to switch between developer window and safari In every other application (including Chrome I'm coming from - before the Catalina update) I was able to switch between windows with Cmd + ` (on a German keyboard that is Cmd + >).
Is there a shortcut to switch between an undocked developer window and the safari browser window?
I'm not talking about switching Tabs (I fixed that already :D).
Update
I just saw, that I can change FROM browser TO dev window with Cmd.+ ` but not back. (!!? :D)

A: Switch one way: Cmd + `
Switch the other way: Cmd + Shift + `

*

*Replace ` with the necessary language specific equivalent.

*Your solution was very close. Normally the key combination you mentioned loops through available windows. In this specific case you have to return to a previous window by adding Shift.


text:
Q: Local Variable NullPointerException I'm getting a nullpointerexception when I click on the signup button on the Login class it gives that error. I've tried to tinker around with the local and global variables and nothing seems to fix the error, I might have got mixed up on the onClickListener as when I remove that code it seems to work.
Signup.class.
public class Signup extends Activity {

    /*List Variables */
    private ScrollView scrollView1;

    private EditText editTextUN;

    private EditText editTextPW1;

    private EditText editTextPW2;

    private EditText editTextEMAIL;

    private Button buttonSignup;

    private Button buttonCancelSignup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        /*set ContentView */
        setContentView(R.layout.signup);

        /*Populate fields */
        populate();

    }

    private void populate() {
        // TODO Auto-generated method stub

        /*initialize the ScrollView */
        ScrollView scrollView1 = (ScrollView) findViewById(R.id.scrollView1);

        /*initialize the EditText for the FIRST username field */
        final EditText editTextUN = (EditText) findViewById(R.id.editTextUN);

        /*initialize the FIRST password field */
        final EditText editTextPW1 = (EditText) findViewById(R.id.editTextPW1);

        /*initialize the SECOND password field */
        final EditText editTextPW2 = (EditText) findViewById(R.id.editTextPW2);

        /*initialize the signup Button */
        Button buttonSignup = (Button) findViewById(R.id.btsignup);

        /*initialize the cancel Button */
        Button buttonCancelSignup = (Button) findViewById(R.id.buttonCancelSignup);

        /*initialize the email EditText */
        final EditText editTextEMAIL = (EditText) findViewById(R.id.editTextEMAIL);

        /*setup OnClickListener */
        buttonSignup.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                /*check to see if it's the signup button */
                if(v.getId()== R.id.buttonSignup) {

                    /*get everything to a string */
                    String user = editTextUN.getText().toString();

                    String pass1 = editTextPW1.getText().toString();

                    String pass2 = editTextPW2.getText().toString();

                    String email = editTextEMAIL.getText().toString();

                    /*check to see if there's Text in all the Edit Text's */
                    if(user !=null && user.length()>5 && pass1.length()>5 && pass1 !=null && pass2.length()>5 && pass2 !=null && email.length()>5 && email !=null) {

                        /*send to comHelper */
                        ComHelper.sendSignUp(user, pass1, pass2, email);

                        while(ComHelper.sendSignUp(null, null, null, null)) {

                        }

                    }

                } else {
                    finish();
                }

            }
        });
    }

}

LogCat:
06-06 17:15:30.045: E/AndroidRuntime(1197): FATAL EXCEPTION: main
06-06 17:15:30.045: E/AndroidRuntime(1197): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.qwuik/com.gta5news.qwuik.Signup}: java.lang.NullPointerException
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.os.Looper.loop(Looper.java:137)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.ActivityThread.main(ActivityThread.java:4424)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at java.lang.reflect.Method.invokeNative(Native Method)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at java.lang.reflect.Method.invoke(Method.java:511)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at dalvik.system.NativeStart.main(Native Method)
06-06 17:15:30.045: E/AndroidRuntime(1197): Caused by: java.lang.NullPointerException
06-06 17:15:30.045: E/AndroidRuntime(1197):     at com.gta5news.qwuik.Signup.populate(Signup.java:70)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at com.gta5news.qwuik.Signup.onCreate(Signup.java:40)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.Activity.performCreate(Activity.java:4465)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-06 17:15:30.045: E/AndroidRuntime(1197):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)

EDIT: This is on the x86 emulator.

A: all the above statements are right but I think  NullPointerException is due to :
as  in Button buttonSignup = (Button) findViewById(R.id.btsignup); right id is R.id.buttonSignup
so looks buttonSignup is null there
as you used at
........................................
/*check to see if it's the signup button */
            if(v.getId()== `R.id.buttonSignup`) {

...........................................

A: I have updated your code and added comments, now it's working fine with me
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;

public class Signup extends Activity {

    /*List Variables */
    private ScrollView scrollView1;
    private EditText editTextUN;
    private EditText editTextPW1;
    private EditText editTextPW2;
    private EditText editTextEMAIL;
    private Button buttonSignup;
    private Button buttonCancelSignup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
        /*Populate fields */
        populate();
      }

    private void populate() {

        /*initialize the ScrollView */
        ScrollView scrollView1 = (ScrollView) findViewById(R.id.scrollView1);
        /*initialize the EditText for the FIRST username field */
        final EditText editTextUN = (EditText) findViewById(R.id.editTextUN);
        /*initialize the FIRST password field */
        final EditText editTextPW1 = (EditText) findViewById(R.id.editTextPW1);
        /*initialize the SECOND password field */
        final EditText editTextPW2 = (EditText) findViewById(R.id.editTextPW2);
        /*initialize the signup Button */

        /* here.........i have added final .........*/
       final  Button buttonSignup = (Button) findViewById(R.id.btsignup);
        /*initialize the cancel Button */
        Button buttonCancelSignup = (Button) findViewById(R.id.buttonCancelSignup);
        /*initialize the email EditText */
        final EditText editTextEMAIL = (EditText) findViewById(R.id.editTextEMAIL);

        /*setup OnClickListener */
        buttonSignup.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                /*check to see if it's the signup button */
                //if(v.getId()== R.id.btsignup) {

                /* here.........i have added if condition .........*/
                    if(v==buttonSignup){
                        Toast.makeText(getApplicationContext(), "button has been pressed", Toast.LENGTH_SHORT).show();

                    /*get everything to a string */
                    String user = editTextUN.getText().toString();
                    String pass1 = editTextPW1.getText().toString();
                    String pass2 = editTextPW2.getText().toString();
                    String email = editTextEMAIL.getText().toString();

                    /*check to see if there's Text in all the Edit Text's */
                    if(user !=null && user.length()>5 && pass1.length()>5 && pass1 !=null && pass2.length()>5 && pass2 !=null && email.length()>5 && email !=null) {

                   }
                }
                else
                {
                    finish();
                }
            }
        });
    }
}


text:
Q: Wordpress Media Import, images not in Media Library I have performed two imports using the WP Importer plugin, one of a custom post type and the 2nd of the Media Library. Both imports appear to work, on fact a second attempt to import the Media Library gives "File Exists" messages.
In the individual post the featured image is showing, with thumbnail, with the correct, updated URL.  In cPanel, all the images are in place with correct folder structure and thumbnails
But in the media library, there is nothing showing.


text:
Q: Merging array of objects I want to merge two array of objects. Following are the two arrays:-
let listing=[
{name:'name1',age:14,email:'name1@gmail.com'},
{name:'name2',age:15,email:'name2@gmail.com'},
{name:'name3',age:13,email:'name3@gmail.com'},
{name:'name4',age:12,email:'name4@gmail.com'},
{name:'name5',age:15,email:'name5@gmail.com'},
{name:'name6',age:16,email:'name6@gmail.com'},
{name:'name7',age:12,email:'name7@gmail.com'},
{name:'name8',age:16,email:'name8@gmail.com'},
{name:'name2',age:15,email:'name2@gmail.com'},
{name:'name9',age:17,email:'name9@gmail.com'},
]

let info=[
{name:'name1',class:7,roll_no:4},
{name:'name3',class:6,roll_no:10},
{name:'name2',class:8,roll_no:2},
{name:'name5',class:8,roll_no:18},
{name:'name6',class:9,roll_no:23},
{name:'name7',class:5,roll_no:9},
{name:'name8',class:9,roll_no:13},
{name:'name2',class:8,roll_no:4},
{name:'name8',class:9,roll_no:13},
{name:'name2',class:8,roll_no:4},
]

Output should be in this form:-
let resultant_array=[
    {name:'name1',age:14,email:'name1@gmail.com',class:7,roll_no:4},
    {name:'name2',age:15,email:'name2@gmail.com',class:8,roll_no:2},
    {name:'name3',age:13,email:'name3@gmail.com',class:6,roll_no:10},
    {name:'name5',age:15,email:'name5@gmail.com',class:8,roll_no:18},
    {name:'name6',age:16,email:'name6@gmail.com',class:9,roll_no:23},
    {name:'name7',age:12,email:'name7@gmail.com',class:5,roll_no:9},
    {name:'name8',age:16,email:'name8@gmail.com',class:9,roll_no:13},
    {name:'name2',age:15,email:'name2@gmail.com',class:8,roll_no:4},
    {name:'name8',age:16,email:'name8@gmail.com',class:9,roll_no:13},
    {name:'name2',age:15,email:'name2@gmail.com',class:8,roll_no:4},
    ]

I want that all the objects specified in info array where name is same in both the objects should be included in new array and the objects should be inserted in the same format as listing array.
resultant_array=listing.map(x => Object.assign(x, info.find(y => y.name== x.name))); displays only first match. If i use filter then all the matched objects are inserted in one element only.

A: const result = []
listing.forEach(x => {
  result.push(Object.assign(x, info.find(y => y.name== x.name) || {}))
})

A: This will work on any number of matching keys, without having specify the object property you are trying to match.
let resultant_array = listing.map((item, i) => Object.assign({}, item, info[i]));


text:
Q: Save instance of object during runtime and use it later for testing java I was wondering if it possible to save instance of an object during runtime and use that instance latter on for testing.
My case is that my application makes request to server, parses json response to objects and latter on I want to use some of these instances for junit testing.
I don't want to serialize them.
For example I have Set containing strings "1","2","3". At given point i want to save an instance of it. Program goes, expects all the fields of the object, makes new instance, initialize it with current values and stores it as MySet or something like this and it contains the given strings.
I hope I was clear enough.

A: There are plenty of ways even if you dont want to use serialization. This question has several of them listed. Most of them persist the object to the disk in some form, or use a database. XStream is pretty quick to set up and easy to use.

A: If you need a quick and messy way to save objects, Object streams are a easy way to do this.
See http://docs.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html
and http://docs.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html.

A: Automated tests use Data Providers to provide different test data. After the object gets created, log it out printing the value of each member.
Use these logged values to re-create the required object from within a data provider when testing


text:
Q: Google closure compiler with Maven I am trying to minify my JS file using google closure compiler
I used the following simple POM file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxx</groupId>
<artifactId>closurecompiler</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>closurecompiler Maven Webapp</name>
<url>http://maven.apache.org</url>

<build>
    <finalName>closurecompilertest</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.google.javascript</groupId>
                                <artifactId>closure-compiler</artifactId>
                                <version>r1810</version>
                                <type>jar</type>
                                <overWrite>true</overWrite>
                                <outputDirectory>target/builddependency</outputDirectory>
                                <destFileName>closure-compiler.jar</destFileName>
                            </artifactItem>
                            <artifactItem>
                                <groupId>args4j</groupId>
                                <artifactId>args4j</artifactId>
                                <version>2.0.12</version>
                                <type>jar</type>
                                <overWrite>true</overWrite>
                                <outputDirectory>target/builddependency</outputDirectory>
                                <destFileName>args4j.jar</destFileName>
                            </artifactItem>
                            <artifactItem>
                                <groupId>com.google.guava</groupId>
                                <artifactId>guava</artifactId>
                                <version>r07</version>
                                <type>jar</type>
                                <overWrite>true</overWrite>
                                <outputDirectory>target/builddependency</outputDirectory>
                                <destFileName>guava.jar</destFileName>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.7</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <configuration>
                        <target>
                            <echo
                                message="Minifying JS files. This takes a few minutes, please be patient" />
                            <apply executable="java" failOnError="true">
                                <arg line="-cp target/builddependency/args4j.jar;target/builddependency/guava.jar;target/builddependency/closure-compiler.jar com.google.javascript.jscomp.CommandLineRunner --compilation_level WHITESPACE_ONLY --charset UTF-8 --js " />
                                <fileset dir="src/main/webapp/js/" includes="*.js" />
                                <redirector>
                                    <outputmapper id="out" type="glob" from="*.js" to="target/cc/*.js" />
                                </redirector>
                            </apply>
                        </target>
                    </configuration>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

i placed three js files in the source and when I check the output folder, i am getting empty files without any content
The same command works fine if run in command prompt.
any idea why i am getting empty file?


text:
Q: What is the size allocated to a self referential structure pointer struct node
{
    int data1;
    int data2;
    struct node* link; //line 5
};

How much memory will be allocated for line 5 ,and will it be 1 memory block or 2 memory block since what it is pointing to is having two seperate integers.
Please help i am confused with self referencing pointers memory allocation.

A: The size of an object pointer is always same in standard C++ regardless of what the pointed object contains. The size can vary between systems, but as a rule of thumb, a pointer is 64 bits on 64 bit programs, 32 bits on 32 bit programs and ... you hopefully get the pattern.
An analogy for this is addresses of buildings. The size of the building has no effect on the size of the address of the building.

A: There's 2 memories in there, one is the memory used to store the pointer in the struct, the other is the memory pointed by the struct.
The size of the pointer itself within the struct is sizeof(struct node*) which is usually a long int or 8 bytes (it might not be that, check for your system).
NO memory will be allocated for the pointer. It will likely be pointing to nullptr / 0. You are responsible for allocating that memory through malloc, new or any other allocation mechanism.

A: The type of the pointer link is struct node *. So logically it is evident that the pointer will point to an object of the type struct node. So the allocated extent of memory pointed to by the pointer will be equal to sizeof( struct node ).
Though in general you may allocate an array of objects of the type struct node the first element of which will be pointed to by the pointer.:) In this case the memory extent will be equal to N * sizeof( struct node ) where N is the number of elements in the allocated array.
On the other hand, as the pointer is a data member of the structure then it will occupy the part of the extent of memory allocated for an object of the type struct node. Usually size of a pointer is equal to 4 or 8 bytes depending on the used system.
Here is a demonstrative program.
#include <stdio.h>

struct node
{
    int data1;
    int data2;
    struct node* link; //line 5
};

int main(void)
{
    printf( "sizeof( struct node ) = %zu\n", sizeof( struct node ) );
    printf( "sizeof( link ) = %zu\n", sizeof( struct node * ) );

    return 0;
}

The program output is
sizeof( struct node ) = 16
sizeof( link ) = 8

Or the demonstrative program can look the following way.
#include <stdio.h>

struct node
{
    int data1;
    int data2;
    struct node* link; //line 5
};

int main(void)
{
    struct node obj;

    printf( "sizeof( obj ) = %zu\n", sizeof( obj ) );
    printf( "sizeof( obj.link ) = %zu\n", sizeof( obj.link ) );

    return 0;
}

The output of this program is similar to the output of the previous program
sizeof( obj ) = 16
sizeof( obj.link ) = 8

that is the size of an object of the type struct node is equal to 16 while its data member link has the size equal to 8.


text:
Q: UIAlertViewStylePlainTextInput undeclared I keep getting this property as undeclared when it should be available in the framework.
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Email Alert" message:@"Enter your Email Address" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
[alert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
[alert show];
[alert release];

A: I have used UIAlertViewStylePlainTextInput in this way. Please modify the code as needed.
                 alertType = @"phoneNumberAlert";
                 UIAlertView *phoneNumberAlert = [[UIAlertView
                 alloc]initWithTitle:@"Notice"
                 message:@"Please enter your Phone Number" delegate:self
                 cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
                 [phoneNumberAlert setAlertViewStyle:UIAlertViewStylePlainTextInput];
                 UITextField *alertTextField = [phoneNumberAlert textFieldAtIndex:0];
                 alertTextField.keyboardType = UIKeyboardTypeNumberPad;
                 [phoneNumberAlert show];
                 [phoneNumberAlert release];

A: Did you implement properly methods of the UIAlertViewDelegate?
like this one (without renaming it)?
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

A:
> alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
>     [alertView textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;


text: Q: Chrome stuck in full screen mode I'm trying to help a family member with a Chrome browser problem remotely, but there's no possibility of using remote interaction software. So I'm stuck asking here if anyone has seen this problem where Chrome won't exit out of full screen mode. She hits F11 and it toggles between what you see in the screenshots. However, she can't minimize, drag to the right, or resize the window to normalcy. It's just toggling between these two views with F11 with no ability to interact with the browser in non-fullscreen mode. Several times she has reinstalled Chrome but it still does this. Any ideas?


text:
Q: Flattening and constructing new columns into Pandas df from nested json file I am working with Python 3.7.0, and I am currently facing a problem that I cannot find a solution. Consider the following single entry of data from an API:
data = {'publications': [{'title': 'The effect of land‐use changes on the hydrological behaviour of Histic Andosols in south Ecuador',
   'author_affiliations': [[{'first_name': 'W.',
      'last_name': 'Buytaert',
      'researcher_id': 'ur.01136506420.02',
      'affiliations': [{'id': 'grid.442123.2',
        'name': 'University of Cuenca',
        'org_types': ['Education'],
        'city': 'Cuenca',
        'city_id': 3658666,
        'country': 'Ecuador',
        'country_code': 'EC',
        'state': None,
        'state_code': None},
       {'id': 'grid.5596.f',
        'name': 'KU Leuven',
        'org_types': ['Education'],
        'city': 'Leuven',
        'city_id': 2792482,
        'country': 'Belgium',
        'country_code': 'BE',
        'state': None,
        'state_code': None}]},
     {'first_name': 'G.',
      'last_name': 'Wyseure',
      'researcher_id': 'ur.012246446667.91',
      'affiliations': [{'id': 'grid.5596.f',
        'name': 'KU Leuven',
        'org_types': ['Education'],
        'city': 'Leuven',
        'city_id': 2792482,
        'country': 'Belgium',
        'country_code': 'BE',
        'state': None,
        'state_code': None}]},
     {'first_name': 'B.',
      'last_name': 'De Bièvre',
      'researcher_id': 'ur.013305075217.11',
      'affiliations': [{'id': 'grid.442123.2',
        'name': 'University of Cuenca',
        'org_types': ['Education'],
        'city': 'Cuenca',
        'city_id': 3658666,
        'country': 'Ecuador',
        'country_code': 'EC',
        'state': None,
        'state_code': None}]},
     {'first_name': 'J.',
      'last_name': 'Deckers',
      'researcher_id': 'ur.0761456127.40',
      'affiliations': [{'id': 'grid.5596.f',
        'name': 'KU Leuven',
        'org_types': ['Education'],
        'city': 'Leuven',
        'city_id': 2792482,
        'country': 'Belgium',
        'country_code': 'BE',
        'state': None,
        'state_code': None}]}]],
   'FOR': [{'id': '2539',
     'name': '0406 Physical Geography and Environmental Geoscience'}],
   'issn': ['0885-6087', '1099-1085'],
   'journal': {'id': 'jour.1043737', 'title': 'Hydrological Processes'},
   'type': 'article',
   'research_org_country_names': ['Belgium', 'Ecuador'],
   'doi': '10.1002/hyp.5867',
   'year': 2005,
   'times_cited': 72}],
 '_stats': {'total_count': 957, 'limit': 1, 'offset': 0}}

My aim is to construct a data frame where the nested dictionaries end up combined (separated by commas), and in other cases, with more complicated combinations. For giving an idea, what I am looking for, is something with the following structure:

In the case of the 'author_affiliations' column, this is the trickiest one. Taking into account the entry that I put above, for the first author, this shall be like 'W. Buytaert (University of Cuenca, Ecuador; KU Leuven, Belgium)' and so on...
So far, my attempts have miserably failed. The nearest I got, has been with this very naive code:
from pandas.io.json import json_normalize
data = data['publications']
df = json_normalize(data)

I know that there are a lot of questions alike to mine. However, I haven't found something similar (or at least I haven't noticed that easily). I appreciate your comments and help.
EDIT
As suggested in a comment, I put the desired output as text:
FOR              |  author_affiliations                                                |doi              | issn                | journal.id   |    journal.title       | countries       | times_cited | title          | type    | year
0406 Physical... | W. Buytaert (University of Cuenca, Ecuador;KU Leuven, Belgium), ... | 10.1002/hyp.5867| 0885-6087,1099-1085 | jour.1043737 | Hydrological Processes | Belgium,Ecuador |      72     | The effect ... | article | 2005

A: Try using nested_to_record, then convert to pandas data-frame, then manually change the columns:
from pandas.io import json
data = data['publications']
df = json.nested_to_record(data)
df=pd.DataFrame(df)
df['FOR']=df['FOR'].tolist()[0][0]['name']
df['author_affiliations']=','.join([i[0]['first_name']+i[0]['last_name']+' ('+i[0]['affiliations'][0]['name']+', '+i[0]['affiliations'][0]['country']+';'+i[0]['affiliations'][1]['name']+', '+i[0]['affiliations'][1]['country'] for i in df['author_affiliations'][0]])
df['issn']=','.join(df['issn'][0])
df['research_org_country_names']=','.join(df['research_org_country_names'][0])

And now:
print(df)

Is (shown as an image, jupyter notebook result, because too big for my idle):

Note: json.nested_to_record produces error, do json.json_normalize instead


text:
Q: Easy Ruby data table/search question So I have a table that looks like this:
A    B
A    C
B    A
C    A
C    B

I want to delete the lines that the connection of two values are already in represented (so A----B is the equivalent connection as B----A). Basically I want my table to look like this.
A    B
A    C
B    C

How can I do this in Ruby?
-Bobby
EDIT:
Here is my current code:
require 'rubygems'

f = File.new("uniquename.txt","w")
i = IO.readlines('bioportnetwork.txt').collect{|l| l.split.sort}.uniq
i.each do |z|
f.write(z + "\n")
end

I tried this code, but I think the IO.readlines did not read my columns correctly. Here is one part of my table.
9722,9754   8755
8755         9722,9754
9722,9754   7970,7971
7970,7971    9722,9754

How can I get it read correctly, then saved out correctly as a TSV file?
-Bobby

A: So, let's say you have loaded your TSV file into an array of pairs:
arr = [["A", "B"], ["A", "C"], ["B", "A"], ["C", "A"], ["C", "B"]]
Hash[arr.map{|pair| [pair.sort, pair]}].values
#=> [["B", "A"], ["C", "A"], ["C", "B"]]

This is OK if the order of pairs in original array is not important.
And if neither order of elements in pairs is important:
arr.map(&:sort).uniq
#=> [["A", "B"], ["A", "C"], ["B", "C"]]

A: I'm assuming by 'table' you mean an array-of-arrays similar to this:
x = [['A', 'B'],
     ['A', 'C'],
     ['B', 'A'],
     ['C', 'A'],
     ['C', 'B']]

If so, you can de-duplicate the list with x.collect{|a| a.sort}.uniq.
Update:
To read the data out of the file and into the array, use something like:
lines = IO.readlines('filename.txt')
x = []
lines.each {|l| x << l.split}

Update 2:
Or, you can one-line the whole thing:
IO.readlines('test.txt').collect{|l| l.split.sort}.uniq

Update 3:
When writing out to the file, don't use IO.write.  It converts the array to a string automatically, which might be where you are running into your problem.  Instead, use IO.puts:
f.puts x[0].to_s << "\t" << x[1].to_s

A: Set equivalency is defined in ruby, and Sets use equivalency only to check new members, so you can use a nested set structure to solve this quickly and easily.
set_of_all_sets = Set.new
file.each_line do |line|
  line =~ /(\S)\s(\S)/
  set_of_all_sets << Set.new([$1, $2])
end
array_of_all_sets.map{|set| set.to_a}


text:
Q: How to redirect on another page in wordpress I Don't have any ideas to how  redirect my page on another page after submitting my contact form.
my code is here

<?
  header('Location: http://astrologerdelhi.co.in/?page_id=119, true, 301');

?>
but it is not working ?.

Thanks for your help

A: you can try wp_redirect()
wp_redirect( 'Location: http://astrologerdelhi.co.in/?page_id=119', 301 );
exit;

wp_redirect() does not exit automatically and should almost always be followed by exit.
for more info


text:
Q: Microsoft Authentication Library (MSAL) loginPopup: Error The "provided request must include a 'client_secret' input parameter.| I am trying to use MSAL to add SSO for my single page app, for the purpose of getting an Oauth2 token to be used for resolving a Microsoft SaaS subscription. I have configured my code based on this sample repo: https://github.com/Azure-Samples/ms-identity-javascript-v2. This uses MSAL 2.0, instead of 1.X versions.
Here is the relevant code snippet, ran on the /signup page:
var config = {
      auth: {
        clientId: <MY_CLIENT_ID>,
        authority: "https://login.microsoftonline.com/common",
        redirectUri: <APP_URL> + "/signup",
      },
      cache: {
        cacheLocation: "sessionStorage",
        storeAuthStateInCookie: false,
      }
    };
var msalInstance = new msal.PublicClientApplication(config);
msalInstance.loginPopup(["openid", "profile", "User.Read"]).then((response) => {
      console.log(response)
    }).catch(error => {
      console.error(error);
    });

Calling this code inside my application, I successfully log in using the popup window, but get the following error: ServerError: invalid_client: 70002 - [2020-09-03 16:55:35Z]: AADSTS70002: The provided request must include a 'client_secret' input parameter.
I can see the underlying network call is https://login.microsoftonline.com/common/oauth2/v2.0/token with the following form data:
client_id: <MY_CLIENT_ID>
redirect_uri: <APP_URL>/signup
scope: openid profile
code: <some value>
code_verifier: <some value>
grant_type: authorization_code
client_info: 1
client-request-id: <some value>

Based on the documentation here https://learn.microsoft.com/en-us/advertising/guides/authentication-oauth-identity-platform?view=bingads-13#request-accesstoken, this call should have a configurable client_secret parameter, which results in the error I am getting I believe.
I have the required client secret from my App on Azure Portal. My question is, how can I configure the client secret in my config object? I have not been able to find any examples online, as well I tried adding clientSecret as a key under auth inside my config blindly, this did not pass it to the login.microsoftonline.com call.
UPDATE
After a bit more digging around, I realized the underlying issue of my setup was that I was trying to use the authorization grant flow to request a token but needed to use the client credentials flow. After moving the token acquisition to the backend (and using the client secret there), and some more help in this followup thread I was able to get SSO and token acquisition working as expected.

A: Instead of creating Web create Single-page-application this will solve you problem. See the example below

A: We have debugged your sample and we are able to use it with out any issue. After testing  we believe the issue is occurring  sine your code is not able to call Signin() method in '/authPopup.js'.You will not face any issue if this method call happens in your  index.html.

A: Instead of using MSAL directly, consider looking into using the new SSO capabilities inside Teams - it wraps a lot of this for you and makes it easier to use. Here's an overview and here is a working sample.
Regarding the sample, it's in node, and I'm working on a dotnet version of the same. It looks like you use node, so you should rather refer to the original, but I think I found a few bugs so you can look at the client-side script in my version if you run into any issues - see here.


text:
Q: PHP FatalErrorException - Declaration of ' ' must be compatible with ' ' Just started learning OOP and I'm trying to extend an Abstract Class provided by a package and this is the error I'm getting:

Declaration of Clio::getResourceOwnerDetailsUrl() must be compatible with League\OAuth2\Client\Provider\AbstractProvider::getResourceOwnerDetailsUrl(League\OAuth2\Client\Token\AccessToken $token)

Here is the documentation I'm following for that package here
The Abstract Class itself is a long one but Im pasting the abstract method I'm trying to implement in my extended Class:
/**
 * Returns the URL for requesting the resource owner's details.
 *
 * @param AccessToken $token
 * @return string
 */
abstract public function getResourceOwnerDetailsUrl(AccessToken $token);

And, here is what I have as my Controller Class:
class Clix extends League\OAuth2\Client\Provider\AbstractProvider{

public function getBaseAuthorizationUrl(){}
public function getBaseAccessTokenUrl(array $params){}
public function getResourceOwnerDetailsUrl(AccessToken $token){}
protected function getDefaultScopes(){}
protected function checkResponse($response, $data){}
protected function createResourceOwner(array $response, $token){}}

Please let me know what is wrong here. By the way I'm doing this in Laravel 5.3 running PHP v5.6.25

A: If you read the PHP docs on abstract classes, it clearly states:

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.

If you want to extend the class League\OAuth2\Client\Provider\AbstractProvider, you have to define all of these methods in your extending class:
abstract public function getBaseAuthorizationUrl();
abstract public function getBaseAccessTokenUrl(array $params);
abstract public function getResourceOwnerDetailsUrl(AccessToken $token);
abstract protected function getDefaultScopes();
abstract protected function checkResponse(ResponseInterface $response, $data);
abstract protected function createResourceOwner(array $response, AccessToken $token);

It looks to me like your parameter declarations don't match up on checkResponse and createResourceOwner.


text: Q: lock a part of value in input tag suppose my input include two part, country and name.The part of name could change the value arbitrarily and the part of country's value is decided by an select only. How can I lock the value of country part ? perhaps separate a input into two is a better idea?