text:
Q: .Net MySQL Generic CRUD Repository Is it possible to create a generic CRUD repository in VB.Net for MySQL connection without depending to any third party ORM?
I mean, MySQL CRUD depends on string to identify which table(s) and field(s) you want to access, meanwhile what we have is a .Net object.
Is the only way to achieve this is to use ORM and/or Reflection class? Can't we do something about the object or string to match each other?
Let's say I got this repository interface :
public interface IRepository<T> where T:class
{
    void Insert(T entity);
    void Delete(T entity);
    IQueryable<T> GetAll();
    T GetById(string id);
}

What comes in my mind after seeing this interface is to create a personal Repository for each of my object, even though the CRUD method is very similar.
For example I have to create a repository for Employee CRUD.
class EmployeeRepository : IRepository<Employee>
{
    private string _query;

    public IQueryable<Employee> GetAll(Employee entity)
    {
        _query = "SELECT * FROM tbl_msemployee";
        //Do query here, which will eventually return a list of Employee object
    }
}

A: I guess that is better to use an existing ORM to handle CRUD operations. You then build above this orm layer your repositories (t4 maybe or other code-generation) and your service layer.


text:
Q: How to covert std::string to NSString? You can read code from the picture.The function getResult() return a std::string ,like" <s> 启 动 <unk> <_Apps_> 照相机 </_Apps_> </s> \n-4.93",but the result is garbled,and the NSString res is nil.
And I used lldb command po,find the _data,what is it? Why the  NSString res is nil.

This is the code causing problems:
std:string result = getResult();

NSString *res = [NSString stringWithCString:result.c_str() encoding:NSUTF8StringEncoding];

This is the getResultfunction code:
std::string getResult()
{
    char *res = NULL;

    asGetResult(&res);

    if (res != NULL) {

     printf("asGetResult = %s \n",res);
     return std::string(res);
    }
   else
   {
     return std::string("");
   }

}
And the function getResult is included in a static library,which is written by c++.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C not printing whole string My problem is that it's only printing out 1 letter, when it's supposed to print the whole string. I would really appreciate your help! Thank you once again for helping me.
#include < stdio.h >

int main(void) {

    int val;

    val=1;

    while (val!=0) {

        printf("\n");

        printf("Choose\n");

        printf("1) Add new letter\n");

        printf("2) Empty string\n");

        printf("3) Print string\n");

        printf("0) Stop\n");

        printf("Choice: ");

        scanf("%d",&val);

        printf("\n");

        char sign[200];

        char sign2[200];

        int size;

        size = strlen(sign2);

        switch (val) {

            case 1:

                printf("Give some letter: ");

                scanf("%s",&sign2);

                strcpy(sign, "");

                strcat(sign,sign2);

                sign2[size]=sign2;

                sign2[size+1]='\0';

                break;

            case 2:

                if (val==2) {

                    printf("Emptied string.\n");

                    sign2[0] = '\0';

                }
                break;

            case 3:

                if (size == 0) {

                    printf("Is empty\n");

                } else {

                    printf("String: %s\n",sign);

                }

                break;

            case 0:

                printf("Stopping.\n");

                break;

            default:

                printf("Unknown.\n");

                break;

        }

    }

        return 0;
}

My problem is that it's only printing out 1 letter, when it's supposed to print the whole string. I would really appreciate your help! Thank you once again for helping me.

A: Lots of problem - but yes we can discuss one by one

*

*strlen returns the length of the nul terminated char array. The content of the array in your case is indeterminate at the time you are applying strlen on it. This is undefined behavior. You may wanted to initialize the char array char sign2[200]={0} so that you can use strlen on it. (By the way - if you want to get the size of the char array use sizeof(sign2) )

*scanf("%s",&sign2); will be scanf("%s",sign2); because char array converted ("decays") into pointer to the first element - which is a pointer to the sign2[0]. That is what you are supposed to pass to scanf. Your compiler complained about it.

*sign2[size]=sign2; is not doing what you are thinking it is doing - this is trying to assign a char* to a char variable which is wrong.

*Also every time you are overwriting what is there in sign2. Ideally you want to get a char input and that will be scanf(" %c",&somecharvar);.

*After you get the input in somecharvar then adding it would be easy. You can simply get the length of the string and then add the character and also the nul terminating char. In case you are thinking - what will be the case the very first time then you will have do one thing - initialized sign2 with \0 initially. That way even if you call strlen over it the very first time - it will give you the result of 0.
char somevar;
if( scanf(" %c",&somevar)!= 1){
    fprintf(stderr,"Error in input\n");
    exit(1);
}
size_t sz = strlen(sign2);
if(sz+1 < sizeof(sign2)){
    sign2[sz]=somevar;
    sign2[sz+1]=0;
} else {
    fprintf(stderr,"Noe enough space\n");
    exit(1);
}

*As you have already seen, strlen returns the length of the string which of type size_t. size_t is guaranteed to hold the size of any object in C.

*For scanf always check it's return value, in case it fails you will know it and terminate the program or handle it accordingly( most plausible being - eating out the wrong inputs from stdin that would still be there because scanf couldn't parse it).

*This is a good practice you can say - instead of using hard-coded value (magic numbers) like 200 or similar use a macro or constant to incorporate them.


text:
Q: What heart pieces are unavoidable? I'm attempting a three-heart run in The Legend of Zelda: Wind Waker. I'm not picking up the heart containers after bosses, and I'm trying not to get more than three heart pieces.
So far, I've picked up one heart piece, which I believe might not have been avoidable: playing hide-and-seek in Windfall Village, if I'm not mistaken, is required in order to get access to the cabana later and grab the Triforce piece inside of it.
Also, the first time you get a letter in the mailbox, it contains a heart piece. This means that I have to accept the heart piece if I'm going to do any side quests involving the mailbox later on.

*

*Am I right in believing that it's impossible to complete the game without getting the first heart piece, or could I have skipped it?

*If I take both of the heart pieces I mentioned so far, will it be possible for me to finish without being forced to take two more heart pieces? Or are there at least two more main questline events that award me heart pieces?

A: You're on the right track:

*

*That heart piece is unavoidable.

*You can avoid all other heart pieces so even if you pick up one or two by mistake, your run won't be spoiled.


text:
Q: iPhone Dev - Is it possible to load an app's mainWindow conditionally? Is it possible to code this sequence of events once an iPhone app has been launched?

*

*User launches application.

*AppDelegate.m checks if data is present in internal database.

*If yes, MainWindow.xib loads.

*If no, AnotherViewController.xib loads.

I've only seen app examples that load the MainWindow.xib without conditions.
If it is possible, which method in AppDelegate.m handles the logic? (applicationDidFinishLaunching? viewDidLoad?)

A: I don't think you want to load the MainWindow conditionally.  Instead, load and show a viewController conditionally. This can be done in applicationDidFinishLaunching.


text:
Q: PHP Gearman Duplicate tasks I got:

*

*Debian 6

*nginx 1.2.6

*PHP 5.3.20-1~dotdeb.0 (fpm-fcgi) (built: Dec 24 2012 11:53:16)

*gearmand 1.1.4

*pecl gearman ext 1.1.1

And I got two scripts (Probably I copied them from php.). Client:
<?php
$gmc= new GearmanClient();
$gmc->addServer();

$gmc->setCompleteCallback("reverse_complete");
$gmc->setStatusCallback("reverse_status");

$gmc->addTask("reverse", "!dlroW olleH", null, "2");

if (!$gmc->runTasks())
{
    echo "Error " . $gmc->error() . "\n";
    exit;
}

echo "Done\n";

function reverse_status($task)
{
    echo "Status: " . $task->unique() . ", " . $task->jobHandle() . " - " . $task->taskNumerator() .
         "/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
    echo "Done: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

And worker:
<?php
$gmworker= new GearmanWorker();
$gmworker->addServer('127.0.0.1');
$gmworker->addOptions(GEARMAN_WORKER_GRAB_UNIQ);
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for tasks...\n";
while($gmworker->work())
{

  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{

  echo "uniq: " . $job->unique() . "\n";
  echo "I got job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size is done\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "The result: $result\n";

  return $result;
}

?>

I run gearmand via "gearmand -d".
I start worker via "php worker.php".
I open up my client script from my browser, the task goes to server, everything's ok.
But when I open up the same script from 2+ browser tabs gearmand receives 2+ similar tasks with the same unique IDs.
That doesn't happen when I add background tasks or use doBackground method or in CLI mode.
That also doesn't happen from 2+ different browsers.
I tried different client and server versions. The same thing happens.
I'm totally stuck.
Thanks for the help.

A: $gmc->addTask("reverse", "!dlroW olleH", null, "2"); the last option is your unique key. so of course it is always the same.

A: old, but i guess i figured that out. browsers don't allow to send 2+ identical queries at a time. the second one waits on the first one to finish first.


text:
Q: How do I add app to share menu for iOS/Android I'm trying to add my app to the list of available shares for other apps, and I wanted to make sure I had it right. The documentation doesn't explicitly state this, and I really want to be sure of what it means before I move forward:
Every app that wants other apps to share to them needs to add their app to the Share Extension, correct?
I.E. if I want to share to another app, they would have to make the requisite changes on their app so that it would be listed in the list of available apps to share to, correct?


text:
Q: Scale a PostgreSQL stored procedure My current implementation of a PostgreSQL stored procedure doesn't scale, though the problem could easily be split into parallel processes/threads.

The setup
An application that behaves very much alike a dating platform, i.e. users sign up, enter a couple of profile details and based on these details a matching against all other users is done. The details can be summed up to 60-70 attributes, mostly booleans, which are stored within the user record in the user_attributes table. So there's one large user_attributes table, consisting of user id and the attributes (other profile data is stored in a separate table). The attribute-by-column scheme was chosen due to performance concerns, i.e. prevent additional queries for getting all attributes of one user. For every matching, there's a per-user matching table, so every user has its own table consisting of user_id, other_user_id, matching_score.
We'd like to have up to 300k users per DB instance, but it'd be interesting to see how it could scale ten times, i.e. up to 3 million users. Beyond that, we can scale by distributing to other database instances. Nevertheless, we start to have scalability problems around 80k users.

The question
As mentioned before, due to performance concerns the attributes were all together put into a user_attributes table with one column per attribute. We've create a stored procedure (create_user) that takes all of the 60-70 attributes as arguments, create a record in the user table and then starts to select all other users, including their attributes, from the user_attributes table and starts to calculate the matching score with the final result being inserted into the newly created UserXYZ_matches table.
We now run a test to see how the setup performs (insert one user at time, until 300k users is reached) and it turns out that around 80k users, our CPU becomes the bottleneck. Though the test machines comes with 4 cores / 8 threads, only one is actually utilized. The problem is that the matching-per-other-user takes so long (PL/pgSQL performs really poor here), but the core issue is that all of these matchings happen on one CPU. For example, the matching against all other users could be split up into 8 different operations, each taking 1/8 of the user_attributes table records, performing the matching and inserting into the result table. We can optimize the badly performing PL/pgSQL, but I don't know a way on how to distribute the work across other CPU cores/threads.

Other Information
Please post recommendations on the approach as a whole as comments. I really appreciate advice on how to do better in general, but not as an answer to this specific question.
All of the user matching tables are stored within one tablespace which is backed by XFS and LVM striping across a couple of disks. The number of user matching tables (one per user) doesn't seem to be scalability problem (as we first thought). So disks are not a problem and the huge amount of tables seems to be covered by the specific setup.
A call/query to create_user should be atomic, i.e. transaction based. That's for our test-run, but doesn't need to be a hard requirement for the end product.
The create_user procedure basically looks like this (too long to post as a whole):
CREATE OR REPLACE FUNCTION create_user(...)
    -- (1) input_user = INSERT INTO user_attributes VALUES (parameter0, parameter1, ...)
    -- (2) create userXYZ_matching_table
    -- (3) FOR row IN SELECT * FROM "user_attributes" WHERE "id" <> input_user."id" LOOP
    --        -- repeat for every attribute
    --        IF row.this_attribute = input_user.this_attribute THEN
    --           match := match + 1
    --        END IF;
    --        -- finally
    --        INSERT INTO userXYZ_matching_table VALUES (input.user.id, row.id, match)
    --     END LOOP;
LANGUAGE PLPGSQL;

I know that the high CPU usage comes from the amount of IF, ELSIF, END IF blocks (60-70). Again, this can be optimized but the question on how to scale such a stored procedure remains.
The server where the tests currently run on looks like below, which illustrates the problem pretty well:

A: To the best of my knowledge and documentation-reading abilities, PL/pgSQL does not support parallelism, nor does the server parallelize processing for individual queries.  I'm inclined to say, therefore, that scaling further will require parallelization at the client (new users inserted via multiple concurrent threads / processes with separate connections).
Overall, though, you have an inherent scaling problem in that to add a new record you need to compare it to all the other records.  The cost of doing that for N total records scales as N^2, and you're already pegging the CPU 25% of the way through.  Adding the 320,000th record will be four times as expensive as adding the 80,000th, and adding the 320,000 records in total will be at least sixteen times as expensive as adding 80,000.
It is conceivable that you could somewhat improve performance by using a SELECT INTO query instead of a stored procedure, but that won't improve the asymptotic complexity.  You could also consider creating the matching tables asynchronously, to improve the initial response.

A: (Elaborating on John's answer; please accept his not mine):
PL/PgSQL is probably a poor choice for this task.
It's slow for mathematical and logical operations. Very slow. PL/PgSQL is great for gluing a few SQL statements together - where most of the work is done by the SQL statements. It's terrible for lots of mathematical work and logic.
It also cannot exploit any CPU parallelism.
Additionally, running many individual small inserts like you do will be extremely slow. Don't do that. Instead, if you must do this in PL/PgSQL, have your function return a set of tuples for the results to be inserted, and call it as INSERT INTO target_table SELECT * FROM my_procedure(...) or similar. It'll be a lot faster.
Doing the work synchronously as part of the user insert makes the whole thing a lot worse, because the issues are more visible to the user. Particularly because, as John notes, this scales at O(N2), i.e. quadratically.
Your design is completely nonviable and needs to be rethought from scratch.
I suggest an approach that relies on fact tables, like in a star schema. Each attribute is a "fact" about the user. Each fact table is a (user_id, fact_value) tuple. A composite index exists on (user_id, fact_value).
When the user is inserted, mark their user record as pending matching with a flag in the user record its self, and insert entries into the fact tables for it in the same transaction you insert the user.
Then have your application process a queue of users pending matching asynchronously as a background task. Join on the fact tables to find users who are most similar, i.e. with the most facts with the most similar values. Your application can exploit multiple PostgreSQL connections for parallelism, either processing multiple users at once or doing partial joins to produce interim results in temp table that you then join to find the final results.

A: It a old tread and a interesting read. I came across this when i was trying to find if we can use threads kind of mechanism inside a SP.
The design explained in this thread of discussion (not sure if this is still relevant), what we can do is keep the insert in user table in one stored procedure and all the logic to create user_attribute table and population it can be move to a triggers.
Not sure if you can devise flow for multilevel triggers as per your design.
Downside is it may increase the number of fail points.. but once tested well should just do the trick..


text:
Q: Focus on textarea in popup When I click on a button , a popup will appear which consists of textarea. I want the textarea to be focused when the popup is opened.
I tried using autofocus, textarea.focus .. but it is not working.
Can anyone please help...
by default popup= false

enter your answer

    <textarea  #textarea1 id = "ta"></textarea>

<button (click)="popup= true;
textarea1.focus()">Answer Popup</button>

A: The following works for me, however most likely there is a better way to do it in Angular using states and event binding instead of this more like "plain JavaScript" solution:
app.component.ts
import { Component, ElementRef } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  constructor(private _elementRef: ElementRef) {
  }

  openPopUp() {
    const div = this._elementRef.nativeElement.querySelector('#the_div')
    div.style.display = 'block'
    const textarea = this._elementRef.nativeElement.querySelector('#the_textarea')
    textarea.focus()
  }
}

app.component.html

  <textarea id="the_textarea"></textarea>

<button (click)="openPopUp()">
  Answer Popup
</button>


text:
Q: Using python cx_Oracle, how do I call DBMS_METADATA.SET_TRANSFORM_PARAM, which has multiple declarations? Here's the call and error I currently receive:
cursor.callproc('DBMS_METADATA.SET_TRANSFORM_PARAM', ['DBMS_METADATA.SESSION_TRANSFORM', 'STORAGE', 'false'])
cx_Oracle.DatabaseError: ORA-06550: line 1, column 7:
PLS-00307: too many declarations of 'SET_TRANSFORM_PARAM' match this call
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

A: The issue is related to the use of quotations. The syntax for the procedure DBMS_METADATA.SET_TRANSFORM_PARAM
DBMS_METADATA.SET_TRANSFORM_PARAM (
   transform_handle   IN NUMBER,
   name               IN VARCHAR2,
   value              IN VARCHAR2|IN BOOLEAN DEFAULT TRUE|IN NUMBER,
   object_type        IN VARCHAR2 DEFAULT NULL);

the last parameter(object_type) needn't to be specified obviously, since it has NULL value as default.
the penultimate parameter(value) might have three options for data type. Seems that is intended to be as BOOLEAN. So, remove quotes around false.
lastly, the first parameter(transform_handle) is also considered as numeric. So, remove quotes here too.
As a result, call the procedure as
cursor.callproc('DBMS_METADATA.SET_TRANSFORM_PARAM',
                [DBMS_METADATA.SESSION_TRANSFORM, 'STORAGE', false]);


text:
Q: mysql inserting data to table, duplicate i got 2 tables that i want to combine its data.
the id is my key field (incremental and distinct).
table 1  and table 2 field description for example:
id - name - value
i want to insert all of table 2 data into table 1, they have different data but in some rows the same id.
so when i try to:
INSERT INTO ladatabase.table2 SELECT * from ladatabase.table1;
i get duplicate entry error.
please help me to suggest how can i solve it and combine the data with different id values for the new data.
Alex.

A: here are 2 ways:
first you can use if the id AUTO INCREMENT
INSERT INTO ladatabase.table2
 SELECT '', name, value from ladatabase.table1;

or you find the first free ID and add it
INSERT INTO ladatabase.table2
 SELECT id+555 , name, value from ladatabase.table1;

A: No insert all fields (exclude 'id'-field from SELECT):
INSERT INTO ladatabase.table2 SELECT name,value from ladatabase.table1;

A: You need to copy all but the ID column, and it will assign new IDs. You need to list all the other columns explicitly. Leaving out the ID column will cause it to get its default value, which are sequential IDs for an auto_increment field.
INSERT INTO table2 (col2, col3, col4, ...)
SELECT col2, col3, col4, ...
FROM table1


text:
Q: ASP.NET Ajax - Using jQuery BlockUI in two places; can I unblock a specific div? I'm using the jQuery BlockUI Plugin (v2) because it rocks the casbah.
For every ASP.NET AJAX request made on the page, I use the InitializeRequest and EndRequest client-side events to block and unblock the UI, respectively -- this allows me to easily throw up a "Please wait..." dialog. Code is as follows:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequest);
prm.add_initializeRequest(InitializeRequest);
var blockTimer;
var blockTimerFired;

function InitializeRequest(sender, args) {
    blockTimer = setTimeout(blockPage, 100);
    blockTimerFired = false;
}

function EndRequest(sender, args) {
    unblockPage();
}

function unblockPage() {
    // Check if the timer has run yet, and if it hasn't, cancel it
    if (blockTimerFired) {
        document.body.style.cursor = "default";
        $.unblockUI();
    }
    else {
        clearTimeout(blockTimer);
    }
}

function blockPage() {
    document.body.style.cursor = "wait";
    var loadingMessage = '
 Please wait...
';
    $.blockUI({ centerX: true, centerY: true, css: { backgroundColor: '#ebebeb', color: '#000' }, message: loadingMessage });
    blockTimerFired = true;
}

The above behavior works fine. However, in some cases I also use blockUI (on the same page) to create a yes/no modal dialog. This dialog is loaded when the document is ready.
The problem is that my $.unblockUI() call in unblockPage() seems to kill both dialogs. Is there a way I can easily target a specific div with $.unblockUI()? It'd be great if I could call $.unblockUI("#myYesNoDiv"), for example.

A: I was overcomplicating this problem.
When you use the command $.blockUI(), it first deletes any existing blockUI divs on the page. I had asked if I could target a specific div, but only one div exists on the page at a time, so my question was pointless. Sorry!
As a result, all I have to do is give the div I'm checking for an id and then check if it exists on the page. I was able to simplify the code and solve my problem:
New code:
function unblockPage() {
    // Check if the timer has run yet, and if it hasn't, cancel it
    if ($("#divBlockPage").length > 0) {
        document.body.style.cursor = "default";
        $.unblockUI();
    }
    else {
        clearTimeout(blockTimer);
    }
}

// Blocks page UI.
function blockPage() {
    document.body.style.cursor = "wait";
    var loadingMessage = '
 Please wait...
';
    $.blockUI({ centerX: true, centerY: true, css: { backgroundColor: '#ebebeb', color: '#000' }, message: loadingMessage });
}

A: Doesn't seem to have that option. Take a look at simplemodal. I'm thinking it rocks the casbah myself these days. I know you might be tied to blockui but I thought I'd mention it.


text:
Q: Content script is not executed when I run browser.tabs.executeScript in Extension Browser I am developing the extension on web browser to record the user activity on the website (event recorder), for example, if the user clicks on the button, on links or input some text on them, it will extract this informations. I use them to create the automation tests for Selenium and Cypress. The extension works very well when I run it directly on the taskbar.
Now the problem happens, when I want to run the extension from my own website (currently a React localhost website). The website contains a click button and a text box where I enter the URL link (e.g. google.com or some website to test).
Here is the picture of this click button and text box
When I click the button, the browser will jump to the new tab with that URL using window.open(url); and tries to run the extension. The extension was started, but it records nothing at all.
The function that starts the extension on my Localhost website
/**
 * Click start button to run the manuel test and also start the Recording
 * @param giveURL
 */
const onRecording = (giveURL: string) => {
    let url = giveURL;
    var extensionId = "onneeadcdhgnlomhihgbhplgadkaepce"
    window.open(url);
    chrome.runtime.sendMessage(extensionId, {openUrlInEditor: url},
        function(response) {
          if (!response.success) {console.log("failed to send");}
          else console.log("Pass to send");

        });

}

I tried to isolate the problem, and the problem was in following:
The workflow of my background script: it first call the onConnect.addListener on handleNewConnection (this methode will do some jobs later). Then it signal the start of the Extension by using control(handleMessage, { type: ControlAction.START }).
function initialize(): void {
  browser.runtime.onConnect.addListener(handleNewConnection);
  browser.runtime.onMessage.addListener((message) =>
    control(handleMessage, message)
  );

  browser.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
      control(handleMessage, { type: ControlAction.START })
    });

  control(cleanUp);
}

In handleMessage, it will call injectEventRecorder() Methode and execute the contentscript using browser.tabs.executeScript()
function handleMessage(action: ControlAction): Promise<void> {
  return new Promise((resolve, reject) => {
    switch (action) {
      case ControlAction.START:
        injectEventRecorder()
          .then(() => resolve())
          .catch((err) => reject(err));
        break;
      case ControlAction.STOP:
        ejectEventRecorder()
          .then(() => resolve())
          .catch((err) => reject(err));
        break;
      case ControlAction.RESET:
        resetRecording()
          .then(() => resolve())
          .catch((err) => reject(err));
        break;
      default:
        reject(new Error(`Invalid action: ${action}`));
    }
  });
}

function injectEventRecorder(
  details?: browser.webNavigation._OnCommittedDetails
): Promise<void> {
  return new Promise((resolve, reject) => {
    if (!details || details.frameId === 0) {
      browser.tabs.executeScript({ file: "browser-polyfill.js" });
      let executing = browser.tabs.executeScript({
        file: "/content-scripts/eventRecorder.js",
      });
      executing.then(
        () => {
          resolve();
        },
        () => {
          if (browser.runtime.lastError) {reject(browser.runtime.lastError);}
          resolve();
        }
      );
    } else {
      resolve();
    }
  });
}

Theoretically, when the content script will be executed after calling executeScript(), it will signal the methode HandleNewConnection to start. Because this methode will be fired when a connection is made from the content script. But it won't...
When I tried to debug browser.tabs.executescript. It execute the script but it turns out that the content script (where the recording takes place) was not started, and no error came up either. The content script is simply not running.
I use Console.log to debug the workflow as following:
Correct workflow when I start the extension on Browser Taskbar
Go into initialize() --> Go into injectEventRecorder() -->  Execute Contentscript --> Go into handleNewConnection()  --> Go out handleNewConnection() --> Go out injectEventRecorder() --> Go out initialize()

Incorrect workflow when I start the extension using localhost website
Go into initialize() --> Go into injectEventRecorder() --> Execute Contentscript --> Go out injectEventRecorder() --> Go out initialize()

I don't really know why this is happening. But my thought was because I jump into the new tab (from localhost website tab to new tab), there may be confusing for the extension to know which tab it should run. But I don't really know the solution.
If anyone knows why and how to fix it, please let me know. I really appreciate it and thank you in advance.
Here is my shortened manifest.json
  {
           ...
  "manifest_version": 2,
  "permissions": [
    "activeTab",
    "storage",
    "webNavigation",
    "<all_urls>"
  ],
  "optional_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "background": {
    "scripts": [
      "browser-polyfill.js",
      "./background/background.js"
    ],
    "persistent": false
  },
  "browser_action": {
    "default_popup": "./popup/index.html"
  },
  "externally_connectable": {
    "matches": ["https://localhost:4000/*"]
  }


text:
Q: Show only once a div per user I´m new in Javascript and i´m trying to do a animation a "terms and conditions" of the website, and it works!
Now I just trying to use cookies to show only once the "terms and conditions" until a new version of the "terms and conditions", but it not working!
This accept terms will be used in a wordpress site.
I don´t know what is wrong
Any tips, articles, anything else will be a great useful

document.cookie="username, expires= Sat, 31 Dec 2016 12:00:00 GMT";

$('txt .avia-button').click(function()){
    if ($.cookie('#txt .avia-button')) $('#txt').animate();
    else {
        $('#txt .avia-button').click(function(){
            $('#txt').animate({
         bottom: '-300px',
  height: 'toggle',
            });
        });
    }
});

A: Something like this:
if ($.cookie('seenTOS')!='1'))
{
  $('#txt').hide();
}
$('#txt .avia-button').click(function() {
    $.cookie('seenTOS','1', { expires: 7, path: '/' });
    // Show #txt
    $('#txt').animate({
        bottom: '-300px';
        height: 'toggle';
    });
});


text:
Q: Is SQL Server Compact *ever* OK to use on a web server? I'd like to host a personal database for about 500 people (1 database per person) on my web server.  A person could possibly share their database with a friend or two.  On my web server, I'd have some web services, perhaps for doing synchronization, and maybe even an ASP.NET Web Forms front end to the database.
If I restart my IIS web server, would this likely cause database corruptions?  Would this be expected to perform ok?
If not Compact, should I instead use SQL Express and create a database in SQL Server for each of my 500 people?

A: It looks like ScottGu says it's OK:
http://weblogs.asp.net/scottgu/archive/2010/06/30/new-embedded-database-support-with-asp-net.aspx


text:
Q: Properly configuring closure to capture results I am writing some custom store methods for in app purchases; sort of a wrapper for SwiftyStore.  The problem I'm running into is the inability to get the results from the closures before they exit.
Any suggestions on how to properly set them up? IE: Closures...
I have a function that checks for an existing subscription and returns true if it finds one in firebase, if it doesn't then it goes out to the apple store to verify a previously purchased subscription:
func checkSubscription() -> Bool {
        var RetVal: Bool = false
        var retStat: String = ""
        var myVal: Bool = false

        self.rootRef.child("users").child(self.userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            let mySubType = value?["subtyp"] as? String ?? ""
            // set value
            if mySubType == "" {
                // get receipt
                if self.myStore.getReceipt() == true {
                    (myVal, retStat) = self.myStore.verifyPurchase(product: "com.xxxxx.xxxxx.monthly")
                    if myVal == true && retStat == "Valid" {
                        // we have a valid product update firebase
                        print("Valid")
                    } else if myVal == true && retStat == "Expired" {
                        // we have a valid product that is expired
                        print("Expired")
                    }
                }
            } else {
                // we have a purchase, verify its not expired.
                print("Purchased")
                RetVal = true
            }

        }) { (error) in
            print(error.localizedDescription)
        }
        return RetVal
    }

The problem here is its dropping down to the return RetVal before the closure is complete so the function could be returning an invalid value.  Not sure how I can fix this in the current setup, but any suggestions or pointers would be appreciated.

A: func checkSubscription(completion: (_ scuess:Bool) ->()){
  var RetVal: Bool = false
        var retStat: String = ""
        var myVal: Bool = false

        self.rootRef.child("users").child(self.userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            let mySubType = value?["subtyp"] as? String ?? ""
            // set value
            if mySubType == "" {
                // get receipt
                if self.myStore.getReceipt() == true {
                    (myVal, retStat) = self.myStore.verifyPurchase(product: "com.xxxxx.xxxxx.monthly")
                    if myVal == true && retStat == "Valid" {
                        // we have a valid product update firebase
                        print("Valid")
                    } else if myVal == true && retStat == "Expired" {
                        // we have a valid product that is expired
                        print("Expired")
                    }
                }
              completion(false)
            } else {
                // we have a purchase, verify its not expired.
                print("Purchased")
                completion(true)
            }

        }) { (error) in
            print(error.localizedDescription)
            completion(false)
        }
        return RetVal
    }

call completion(true) whenever your retValue supposed to be true and completion(false) whenever your retValue supposed to be true
Then call this function this way:
checkSubscription { (sucuess) in
    if(sucuess){
       print("OK")
     }else{
        print("BAD")
     }
 }

A: To expand on Tom's comment, if you want to return a result when the nested asynchronous function is complete, you could pass in a completion handler closure that uses the Result type that Swift offers like the following:
func checkSubscription(completion: @escaping (Result<Bool, Error>) -> Void) {
    var RetVal: Bool = false
    var retStat: String = ""
    var myVal: Bool = false

    self.rootRef.child("users").child(self.userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let mySubType = value?["subtyp"] as? String ?? ""
        // set value
        if mySubType == "" {
            // get receipt
            if self.myStore.getReceipt() == true {
                (myVal, retStat) = self.myStore.verifyPurchase(product: "com.xxxxx.xxxxx.monthly")
                if myVal == true && retStat == "Valid" {
                    // we have a valid product update firebase
                    print("Valid")
                } else if myVal == true && retStat == "Expired" {
                    // we have a valid product that is expired
                    print("Expired")
                }
            }
        } else {
            // we have a purchase, verify its not expired.
            print("Purchased")
            RetVal = true
        }

        completion(.success(RetVal))

    }) { (error) in
        print(error.localizedDescription)
        completion(.failure(error))
    }
}

Calling the function using this type of completion handler would look something like this:
checkSubscription { (result) in
    switch result {
    case .success(let boolValue):
        // do something with resulting boolean
        break
    case .failure(let error):
        // do something with resulting error
        break
    }
}


text:
Q: SQL display status for records with null values I am trying to create a query that lists records from table 1 along with a status based on  corresponding records in table 2 that have null values in one or more of the fields.  The problem I am running into is how to include records from table 1 which have no corresponding record in table 2.
In my example, I want to list the names of all students in tblStudent along with a field indicating the status of their schedule in tblStudentSchedule.  If either course or teacher field in tblStudentSchedule is Null or no corresponding record in tblStudentSchedule is found then I want to display "Incomplete".  Otherwise, I want to display "Complete".
desired result
Name  | Schedule Status
-----------------------
Bob   | Incomplete
Sally | Incomplete
Jane  | Incomplete
Matt  | Incomplete
Jim   | Complete

I'm working in Access.  I would post my query attempts but I think they would just confuse the issue.  This is probably very basic but I am having a mental block trying to wrap my brain around this one.
tblStudent
studentID | studentName
-----------------------
1         | Bob
2         | Sally
3         | Jane
4         | Matt
5         | Jim

tblStudentSchedule
studentID | period | course | teacher
-------------------------------------
1         | 1      | math   | Jones
1         | 2      | <null> | Watson
2         | 1      | reading| <null>
4         | 1      | <null> | Crick
5         | 1      | math   | Jones

A: select  s.studentName as Name
,       iif(sum(iif(ss.course is null or ss.teacher is null, 1, 0)) = 0,
            'Complete', 'Incomplete')
        as [Schedule Status]
from    tblStudent s
left join
        tblStudentSchedule ss
on      ss.studentID = s.studentID
group by
        s.studentName

A left join returns a single row with null when a match is not found.  So the check on ss.course is null will also trigger when the student is absent from the schedule table.

A: If no corresponding record in tblStudentSchedule is found, you can get rows from this table as null coulmns by using left or right joins. Read below:
http://office.microsoft.com/en-us/access-help/left-join-right-join-operations-HP001032251.aspx
And then to convert null column use isnull function
http://www.techonthenet.com/access/functions/advanced/isnull.php
Or use a case statement to check for null
http://www.techonthenet.com/access/functions/advanced/case.php


text:
Q: Does QThread::quit() immediately end the thread or does it wait until returning to the event loop? There are a lot of Qt multi-threading tutorials out there that state that a QThread can be stopped safely using the following two lines.
qthread.quit(); // Cause the thread to cease.
qthread.wait(); // Wait until the thread actually stops to synchronize.

I have a lot of code doing this, and in most cases of stopping thread, I'll always set my own cancel flag and check it often during execution (as is the norm).  Until now, I was thinking that calling quit would perhaps cause the thread to simply no longer execute any waiting signals (e.g. signals that are queued will no longer have their slots called) but still wait on the currently executing slot to finish.
But I'm wondering if I was right or if quit() actually stops the execution of the thread where it's at, for instance if something is unfinished, like a file descriptor hasn't been closed, it definitely should be, even though in most cases my worker objects will clean up those resources, I'd feel better if I knew exactly how quit works.
I'm asking this because QThread::quit() documentation says that it's "equivalent to calling QThread::exit(0)".  I believe this means that the thread would immediately stop where it's at.  But what would happen to the stackframe that quit was called in?

A: In case, if you want to use Qt's builtin facility then try QThread::requestInterruption().
Main thread
struct X {
  QThread m_Thread;
  void Quit ()
  {
    m_Thread.quit();
    m_Thread.requestInterruption();
  }
};

Some Thread referred by X::m_Thread
while(<condition>) {
  if(QThread::currentThread()->isInterruptionRequested())
    return;
  ...
}

As per the documentation:

void QThread::requestInterruption()
Request the interruption of the thread. That request is advisory and it is up to code running on the thread to decide if and how it should act upon such request. This function does not stop any event loop running on the thread and does not terminate it in any way.

A: QThread::quit does nothing if the thread does not have an event loop or some code in the thread is blocking the event loop. So it will not necessarily stop the thread.
So QThread::quit tells the thread's event loop to exit. After calling it the thread will get finished as soon as the control returns to the event loop of the thread.
You will have to add some kind of abort flag if you are blocking event loop for example by working in a loop. This can be done by a boolean member variable that is public or at least has a public setter method. Then you can tell the thread to exit ASAP from outside (e.g. from your main thread) by setting the abort flag. Of course this will require your thread code to check the abort flag at regular intervals.
You may also force a thread to terminate right now via QThread::terminate(), but this is a very bad practice, because it may terminate the thread at an undefined position in its code, which means you may end up with resources never getting freed up and other nasty stuff. So use this only if you really can't get around it. From its documentation:

Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

I think this is a good way to finish a thread when you are using loops in a thread:
myThread->m_abort = true; //Tell the thread to abort
if(!myThread->wait(5000)) //Wait until it actually has terminated (max. 5 sec)
{
  myThread->terminate(); //Thread didn't exit in time, probably deadlocked, terminate it!
  myThread->wait(); //We have to wait again here!
}


text:
Q: About invariant spaces Let $A\in M_{n}$ and $W\subseteq\mathbb{C}^n$ be a subspace, such that $\textrm{dim}(W)\geq 1$.
If $W$ is $A$-invariant, then $A$ has an eigenvector in $W$.
I don't know how to prove it.

A: Hint: Let $A_W$ is the restriction $A$ on $W$. Since $\mathbb{C}$ is algebraically closed, then the polynomial $\det(A_W-\lambda E)$ has a root (= eigenvalue).


text:
Q: Generate PDF - how to create paged HTML content beforehand? My task is to create ready-to-print invoices from a .NET web app.
I am already generating the printer-friendly HTML for an invoice - it consists of an invoice header (that will actually need to appear on each printed page) and invoice positions (that may span multiple printed pages).
Now, my task is to generate a PDF server-side, populate a header on each of its pages, then populate its pages with invoice positions. I need to generate the PDF from the existing HTML data - by simply passing HTML input to the PDF generator library.
I've started using ABCPDF - I am using the AddImageHtml method. The problem I have is that ABCPDF seems to expect me to supply HTML content already paged. So, it won't work correctly when I feed it HTML content that would span on more than 1 PDF page.
So, my question is - do you have any suggestions on making this work with ABCPDF? Or, more generally speaking, what other tools/approaches would you use for this - generating PDF doc with headers/footers from HTML input?
Thanks

A: Found an answer for my ABCPDF-specific question. I am now passing the contents of my generated HTML file as a string to the method below:
private void GeneratePdf(string output)
{
    var theDoc = new Doc();
    theDoc.Rect.Inset(72, 144);

    int theID = theDoc.AddImageHtml(output, true, 800, true);

    while (true)
    {
        theDoc.FrameRect();
        if (!theDoc.Chainable(theID))
            break;
        theDoc.Page = theDoc.AddPage();
        theID = theDoc.AddImageToChain(theID);
    }

    string fileLocation = Server.MapPath("testAbcPdf.pdf");
    theDoc.Save(fileLocation);
   // send file to browser as downloadable PDF here
}

A: It sounds doggy for me to generate invoice from existing html. Somehow I feel insecure...
I would generate pdf on server based on data there, but not from html.
Check out xsl-fo to pdf components.

A: Take a peek at print-CSS styles - these are usually also used for HTML to PDF creation. Styles like 'page-break-after' will help you get the page breaks where you need them, so you can create content that is paged (just like you would for the print version of a website).
Hope this helps!

A: PDF Duo .NET is HTML to PDF converting component for .NET - In contrast to ABC pdf PDF Duo .NET has its own html parsing engine. Here is an example of adding the header & footer:
     string string _ html = @"Or you can point here the html file. Put your image <img src='pic.jpg' widtd='140' height='70'>";
     string file _ pdf = @"K:\new.pdf";

     try
     {
         DuoDimension.HtmlToPdf conv = new DuoDimension.HtmlToPdf();
         conv.Header = "Invoce Document";
         conv.Footer = "* If payment made by Bank transfer kindy please forward to us the copy of the bank transfer slip";
         conv.OpenHTML(file _ html);
         conv.SavePDF(file _ pdf);
         conv.ShowPDF(file _ pdf, Response)
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }


text:
Q: Codeigniter 3 404 Page Not Found I have uploaded a codeIgniter 3 application from local to server setting up following files:
File .config
$config['base_url'] = 'http://www.myswebsite.com/project';

File .routes
$route['default_controller'] = 'projects';

File .htaccess
RewriteEngine On
RewriteBase /project

RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

When I go to the mainController projects I can see the page, but after the login (the page requires a login) I get following error:
404 Page Not Found
URL: www.mywebsite.come/project/login
I cannot understand the reason...

A: I had same problem but I overcame this by doing such a way
Enable mod_rewrite for Apache 2.2 or latter. To do so, create .htaccess file in your root project directory. Add the code bellow in your file and save it.
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteBase /projectname/
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Other important thinks keep in mind :
Controller file name and class name first letter must be upper case.
Example :
file name: Test.php but not test.php
class name: class Test extends CI_Controller {} but not class test ...
Read the link carefully to understand more better:
https://www.codeigniter.com/userguide3/general/controllers.html#let-s-try-it-hello-world
Note : URL must not contain any uppercase letters. All should be small letter.
Example :
correct
www.projectname.com/test/some_method
incorrect
www.projectName.com/Test/someMethod
I hope you will be remedy from this problem.

A: Check Controller class name it should be capitalized letter. first character should be capital

A: You might need to redirect to projects not project controller.


text:
Q: Create a parameter in rdlc report I am a newbie to rdlc reports.
I need to create a parameter that i will pass to a subreport. However I cannot find where in the report designer to create parameters.I am using VS 2010
Thanks in advance

A: Have you tried View --> Report Data? Then you should see Parameters in the Report Data window.
This is how I get to the parameters in VS2010.

A: Just a quick remark for people using VS2008: open the RDLC in the designer and a Report main menu item should appear. The first sub-menu item is Report Parameters. You can configure the parameters from there.


text:
Q: VBA Issue with date format auto conversion A software exports data to xls. Software has date-time format "dd/mm/yyyy hh:mm:ss", but exported sheet, when opened in Excel, date is automatically changed to "m/d/yyyy hh:mm:ss" only when day or month is <10, and it takes day as month and month as day. Any guidance is appreciated.

A: Select cells or a range of your data in date format then look for the Data Tools section of the Data menu tab. Choose Text to Columns, click Next  then click Next again. Mark Date in the option button of column data format and choose DMY, then click Finish.


text:
Q: How to change the Android navigation bar color in a PWA? I would like to change the color of the Android navigation bar on the web when I add the page on the Android home screen (Progessive Web App) but when I open the PWA, the color of the Android navigation bar is black and I want Change the color to white. In the manifest, you can change the color of the theme and I do, but still follow the color black.
Is it possible to do that?
I mean the Android navigation bar, not the notification bar.

A: You can add a meta tag to your HTML page.
<meta name="theme-color" content="#225577"/>

A: As far as I know it is currently not a PWA supported feature.

A: You can play with manifest.json and set "theme_color":"#000000", "background_color": "#000000" - your browser might pick those colors and apply them to the nav bar (or might not, Samsung's standard browser used to ignore this setting and never changed nav bar color). It seems there's still no such feature in PWA (which existis in Android native apps) that allows specifing navbar color alone.

A: The color  of the navigation bar doesn't work with dark theme. Change to light theme and it will work.

A: I believe there is still no workaround for this in 2023.
The Android navigation bar's background color in PWAs depends on the theme setted in your phone settings. If your phone is set as dark mode, it will appear dark. Otherwise, it will appear as white in PWAs.
That's why it is probably a good idea to add toggle theme functionality in your PWA.

A: Yes, you can change navigation them color when you transfer your 'pwa' into a 'twa' android app using bubblewrap.
After initializing your project using bubblewrap you get the file "twa-maifest.json"
In this file you get json-code something like below
"navigationColor": "#000000",
"navigationColorDark": "#000000",
"navigationDividerColor": "#000000",
"navigationDividerColorDark": "#000000",

change those color-code according to your requirement then build your app.
I tried this and got result.
I hope you also get result as you want.


text:
Q: CannotPullContainerError: Error response from daemon: pull access denied for ECR Repo Image, repository does not exist or may require 'docker login' I have pushed a docker image in an ECR Repo  in SourceAccount.
I have deployed a codepipeline in the SourceAccount.
When that codepipeline is run, it deploys ECS stack in TargetAccount. In that stack, ECS tasks are created with containers using the above said image from SourceAccount. However, those tasks remain pending and moved to stopped state ultimately. They show the following error:
Status reason   CannotPullContainerError: Error response from daemon: pull access denied for <SourceAccountId>.dkr.ecr.<Region>.amazonaws.com/<RepoName>, repository does not exist or may require 'docker login'

Please advise how to pull images from SourceAccount ECR and create ECS tasks in TargetAccount.
Note:
1) When I push the same image in the ECR of TargetAccount, everything works fine. ECS tasks fail to run only when trying to pull images from another account.
2) The stack rolled back with the following error:
Service arn:aws:ecs:<Region>:<TargetAccount>:service/<ServiceName> did not stabilize.

A: As specified on https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-pull-ecr-image.html, you need to specify the AWS account id, when you use docker pull:

docker pull aws_account_id.dkr.ecr.us-west-2.amazonaws.com/amazonlinux:latest

A: I fixed it by adding the following policy to the ECR repo in SourceAccount:
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowCrossAccountPull",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::<TargetAccount>:root"
      },
      "Action": "ecr:*"
    }
  ]
}


text:
Q: Adding numbers having more digits after decimal point How to add two decimal numbers, having more than 18 digits, (ex: "0.12345678901234567345342343" and "-0.540811569342790340234") to all the decimal places accurately in vb.net. I tried using double datatype but it did round-off for 18 digits after decimal point. So how i can achieve this?

A: You could use Decimal data type instead. It gives you precision of 28-29 significant digits - should be enough for most needs.


text:
Q: Is there a way to check the camera HAL version from a Java application? Is there a way to check the camera HAL version from a Java application?
This is to verify that the camera2 api and HAL3 api is supported. Slide 38 http://www.slideshare.net/lbk003/an-devcon2013-camera3kaurfinal

A: You shouldn't need to know the exact HAL version of the device, and instead query the camera's capabilities through the camera API.
For the new camera2 API, look at the CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL and REQUEST_AVAILABLE_CAPABILITIES fields to check whether the device has full-capability support or some lesser set of features.


text:
Q: Error subscribing through XMPP Jabber-net I am trying to connect my .net application to xmpp server for events through Jabber-Net. I am not able subscribe for events and keep getting error.
I used matrix and able to connect to the XMPP server. I cam not use matrix for my project there for I need to get it working through Jabber-Net.
I compared both the libraries send & receive message and following is the difference:
Matrix:
SEND:
<iq id="MX_1" type="set" xmlns="jabber:client"> <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>MatriX</resource>  </bind></iq>

RECV:
<iq type="result" id="MX_1" to="server9.host9.com/4bbc160" xmlns="jabber:client"> <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><jid>3002@server9.host9.com/MatriX</jid></bind></iq>

Jabber-Net
Send:
<iq id="jn_1" type="set" to="XMPP_SERVER_IP"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>Jabbernet</resource></bind></iq>

RECV
<iq type="error" id="JN_1" from=" XMPP_SERVER_IP " to="server9.host9.com/e5c0c0b8"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>Jabber.Net</resource></bind><error code="400" type="modify"><bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>

I know there is slight change in two request. Any idea how can I correct it in Jabber-Net

A: You likely got JabberClient.NetworkHost and JabberClient.Server switched.  You shouldn't need to set NetworkHost unless your DNS setup is bad.


text:
Q: LinkedIn API Error: "serviceErrorCode": 100, "message": "Not enough permissions to access: GET-handleString /clientAwareMemberHandles", "status": 403 I got the access token using the following permissions:

r_emailaddress, r_liteprofile and w_member_social

But when I try to do a GET request using the below link,
https://api.linkedin.com/v2/clientAwareMemberHandles?q=handleString&handleString={someone@email.com}

I get the following Error:
{
    "serviceErrorCode": 100,
    "message": "Not enough permissions to access: GET-handleString /clientAwareMemberHandles",
    "status": 403
}

and with /people also I get the same error,
https://api.linkedin.com/v2/people/(id:{_us123456)}?projection=(id,firstName,lastName)

Error:
        {
            "serviceErrorCode": 100,
            "message": "Not enough permissions to access: GET /people/(id:%7B_us123456)%7D",
            "status": 403
        }

Can someone let me know what permission am I missing? How do I resolve this issue?
FYI, I am able to do a GET request to https://api.linkedin.com/v2/me with the same access token and it returns the appropriate JSON on Postman.

A: I've been struggling for the same problem i think the doc says : https://learn.microsoft.com/en-us/linkedin/shared/integrations/people/handle-lookup

The use of this API is restricted to those developers approved by
LinkedIn and subject to applicable data restrictions in their
agreements.

I think all you need to do is be a partner of linkedin :(


text:
Q: Invalid Csrf token when making a cross origin request I have been stuck on it for a while now. I cant understand what is the cause for it. Basically i am making a fetch request to my node js rest api(/csrf-token) to get the csrf token cookie and i am successful in doing so. But when i make a post request from the client it gives me invalid csrf token but that's the part i don't understand because when i open up my devtools i can clearly see an x-xsrf-token header along with _csrf cookie in the request. I would really appreciate if someone can help me point out where iam going wrong. I am using csurf library and below is my code:
Backend :
const corsOptions = {
origin: function (origin, callback) {
    if (whitelist.includes(origin)) {
        console.log("Origin", origin)
        callback(null, true)
    } else {
        callback(new HTTP401Error('Not allowed by CORS'))
    }
},
credentials: true,
methods: 'GET,POST,PUT, DELETE, OPTIONS',
allowedHeaders: "Origin, Content-type, Accept, Authorization, x-xsrf-token"
}

app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended: true }))
const csrfprotection = csrf({
    cookie: true
})

app.use(cors(corsOptions))
app.use(helmet());
app.use(fileupload({
    createParentPath: true,
    limits: {
        fileSize: 1 * 1024 * 1024 * 1024 //2MB max file(s) size
    },
    abortOnLimit: true,
}))

const sessionMiddleware = session({
    name: process.env.SESS_NAME,
    secret: process.env.SESS_SECRET,
    resave: false,
    rolling: true,
    saveUninitialized: false,
    store: store,
    cookie: {
        httpOnly: true,
        sameSite: 'none',
        domain: process.env.NODE_ENV === 'production' ? '.domain.com' : {},
        secure: process.env.NODE_ENV === 'production' ? true : false,
        maxAge: parseInt(process.env.SESS_LIFETIME)
    }
})
app.set('trust proxy', 1);
app.use(sessionMiddleware)
app.use(csrfprotection)

app.get('/csrf-token', (req, res) => { // -->MY GET REQUEST WHICH SEND THE CSRF COOKIES
    // res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.cookie('XSRF-TOKEN', req.csrfToken())
    return res.status(200).json({
        message: "success"
    })
});

My frontend code :
const handleLogin = async () => {
        const { csrftoken } = useSelector(state => state.csrfReducer)
        try {
            console.log("csrf token", csrftoken)
            const result = await fetch('https://api.domain.com/auth/login', {
                method: "POST",
                body: JSON.stringify({
                    email: values.email,
                    password: values.password
                }),
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'X-XSRF-TOKEN': csrftoken
                },
                credentials: "include",
            })
            if (result.ok) {
                const data = await result.json()
                console.log(data)
            } else {
                throw result
            }
        } catch (err) {
            console.log(err)
        }
    }


text:
Q: Lifecycle hooks in Angular Components, DOM Manipulation I'm having issues activating the controller lifecycle hooks in my Angular 1.57 / Typescript app. I am using components (not controllers).
The reason i am doing this is because I need to do some DOM manipulation after all of my HTML is loaded. The two methods i've tried so far are below.
The $postLink is a NGcontroller lifecycle hook that should fire after all the DOM elements are loaded. This is the first function i have in my component.
The $viewContentLoaded essentially does the same thing from what i've seen. I have this inside my $routerOnActivate function.
Method 1
public $postLink(){
    this.log.debug('postLink all done');
}

Method 2
$routerOnActivate(next, prev) {
    this.$scope.$on('$viewContentLoaded', (event) => {
        this.log.debug('viewContentLoaded all done');
    });
};

With these two methods implemented, the $postLink all done log gets triggered before everything else and my $viewContentLoaded all done log never gets triggered.
The purpose of this is so i can trigger actions on HTML elements that are on the page. So i need to wait until all the HTML is loaded before i can trigger those actions.

A: Adding a code snippet would help a lot.
Several things are unclear.

*

*are we talking about a Single Page Application, or is just a component?

*Is this $postLink hook in the main component?

*Regarding the router please see: https://docs.angularjs.org/guide/component-router

$routerOnActivate / $routeOnReuse : called by the Router at the end of a successful navigation. Only one of $routerOnActivate and $routerOnReuse will be called depending upon the result of a call to $routerCanReuse.

A: The documentation for $postLink() states that the hook fires before directives with templateUrl complete.

Life-cycle hooks

*

*$postLink() - Called after this controller's element and its children have been linked. Similar to the post-link function this hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain templateUrl directives will not have been compiled and linked since they are waiting for their template to load asynchronously and their own compilation and linking has been suspended until that occurs.

-- AngularJS Comprehensive Directive API -- Life-cycle hooks.
Either avoid directives using templateURL or use the $postLInk() hook inside those directives to indicate readiness.


text:
Q: jquery no toma la información del input Tengo unos input que recogen la información ingresada y construye la otra parte del link:

// Variables para la modificación de URL
var data1 = ''
var data2 = ''

// Al usar un tecla y levantarla
$('#data1').keyup(function() {
  // Modificar la URL que se ve
  $('#spanData1').text($('#data1').val())
  // Guardar el dato en la variable correspondiente
  data1 = $('#data1').val();
})

// Hace lo mismo que el anterior pero para el segundo
$('#data2').keyup(function() {
  $('#spanData2').text($('#data2').val())
})

//Al hacer click en el boton ir
$('#ir').click(function() {
  // Crear la URL para la redirección y...
  var url = 'http://ejemplo.com/' + data1 + '/' + data2;
  // Hacer la Redirección en una ventana nueva
  //window.open(url, '_blank');
  console.log(url)
})

URL

http://ejemplo.com//

  <input type="text" id="data1">
  <input type="text" id="data2">

  <button id="ir">Ir</button>

Lo que sucede es que solo toma la información del primer input y no la del segundo, por lo tanto cuando doy click en 'ir' me lleva a un link a medio construir, qué hago?

A: Como ya te indican en un comentario data2 está vacio.
Te corrijo tu código y comento los fallos en él.

// Variables para la modificación de URL
var data1 = ''
var data2 = '' //Definida pero nunca usada

// Al usar un tecla y levantarla
$('#data1').keyup(function() {
   // Guardar el dato en la variable correspondiente
   data1 = $('#data1').val();
  // Modificar la URL que se ve
  $('#spanData1').text(data1) //Cambio esta parte en pos de la simplicidad de
  //código y su legibilidad

})

// Hace lo mismo que el anterior pero para el segundo
$('#data2').keyup(function() {
  // Guardar el dato en la variable correspondiente
   data2 = $('#data2').val();
  $('#spanData2').text(data2)
})

//Al hacer click en el boton ir
$('#ir').click(function() {
  // Crear la URL para la redirección y...
  var url = 'http://ejemplo.com/' + data1 + '/' + data2;
  // Hacer la Redirección en una ventana nueva
  //window.open(url, '_blank');
  console.log(url)
})

URL

http://ejemplo.com//

  <input type="text" id="data1">
  <input type="text" id="data2">

  <button id="ir">Ir</button>

Como te indica @lois6b hay métodos para evitar que te sucedan estas cosas. Empieza a construir de arriba a bajo simplificando lo mas posible el código y, si es necesario, hazte un esquema en papel, el gran olvidado de nuestro tiempo. El mero hecho de pintar la idea te puede ayudar mucho a encontrar el problema. Un saludo.


text:
Q: Way to use a screen in a dark environment Im looking for the name of a technique so I can use my web browser in a darker environment. I want to create a web application that would allow the screen to be visible but without glaring too bright so I cant see other things in the dark
I know this technique is used in Stellarium as 'night mode which gives the screen a reddish sort of tint and decreased brightness but It would let me look at my pc and observe the sky without being too bright so my eyes would still let me see things in the dark?
Any hints on what this technique is called?/Ways to do this in html/js

A: Determine the users' whereabouts and/or time based on their IP address with the Geolocation API or getTimezoneOffset and then provide differrent styles based on the time of day.


text:
Q: How to solve this integral in a simple way I am working on a problem in electrodynamics and all sorts of difficult integrals pop up. In this case I am working out the electromagnetic field from a fluctuating wire current (an antenna).
$$2I_{0}\int^{h/2}_{0}\sin\left[\frac{2\pi}{\lambda}\left(\frac{h}{2}-z'\right) \right]\cos\left(\frac{2\pi}{\lambda}z'\cos(\theta)\right)dz'=\cdots =I_{0}\frac{\lambda}{\pi}\frac{\cos\left(\frac{\pi h\cos(\theta)}{\lambda}\right)-\cos\left(\frac{\pi h}{\lambda}\right)}{\sin^{2}(\theta)}$$
What happens at the solution step between these two expressions? I cannot understand what trick they use to get the expression on the RHS. I have tried the addition formulas, which I beleive is the key to sucess here, but I cannot get it to work.

A: It's just an application of the identity $\sin(\alpha)\cos(\beta)=\frac 12(\sin(\alpha-\beta)+\sin(\alpha+\beta))$. When you apply it to your product of sine and cosine, you get the sum of two integrals of a sine function. The first one (the $2$ cancels) is
$$
\begin{align}
I_0&\int_0^{\frac h2}\sin\left(\frac{\pi h}{\lambda}-\frac{2\pi}{\lambda}(1+\cos\theta)z'\right)\mathrm{d}z'\\
&=I_0\frac{\cos\left(\frac{\pi h}{\lambda}-\frac{2\pi}{\lambda}(1+\cos\theta)z'\right)}{\frac{2\pi}{\lambda}(1+\cos\theta)}\Bigg\vert_0^{\frac h2} \\
&=I_0\frac{\lambda}{\pi}\frac{\cos\left(\frac{\pi h}{\lambda}\cos\theta\right)-\cos\left(\frac{\pi h}{\lambda}\right)}{2(1+\cos\theta)}
\end{align}$$
using $\int\sin(ax+b)\mathrm{d}x=-\frac{\cos(ax+b)}{a}$ and similarly for the second integral, which turns out to be
$$I_0\frac{\lambda}{\pi}\frac{\cos\left(\frac{\pi h}{\lambda}\cos\theta\right)-\cos\left(\frac{\pi h}{\lambda}\right)}{2(1-\cos\theta)}
$$
When you sum the two, you get your answer.


text:
Q: Android - Automatic updating view when any change in database I am developing an android application where it shows a list of name from database and when database values are changed (inserting/deleting item) then View should automatically reflect that change.
I don't want polling and Broadcast Receiver.I want things like binding ListView to database. is it possible?

A: Assuming that your database entries do have unique ids and you do have a reference to the ListView while performing database actions you could tag your views in the ListView with those ids at the same time you do it with the names. When performing an insert or delete operation of your database you run a refresh function which iterates through your ListView. If the updated id matches one of the tagged views you refresh the data inside the view.


text:
Q: xcconfig files device families - universal I am changing the name of my app based on the device it is running on through configuration files, i.e. I put in an _iPhone, _iPad or _Universal in the display name accordingly.
To do this I am using xcconfig files as follows:
TARGETED_DEVICE_FAMILY = 1,2

APP_NAME1 = Something_iPhone
APP_NAME2 = Something_iPad
APP_NAME1,2 = Something_Universal //1,2 The "," causes a problem here.

The problem is that the comma character is causing a problem:
  *Build setting 'APP_NAME1,2' does not have a valid base name.*
Any ideas?

A: No apps will be approved for app store with using the trade marked names such as iPhone or iPad try using something else. I have had that even in the binary and not in the display and they rejected it in review. If you want to create a set of codes for universal porpose the take a look at this code snippet. I use this a lot in my universal apps.
`if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    NSLog(@"iPad Idiom");
else
#else
    NSLog(@"iPhone Idiom");
#endif

Adrian


text:
Q: How to setup Spring Boot CLI behind a proxy I am currently attempting to leverage the Spring Boot CLI behind my corporate proxy.  I have tried a bunch of different ways of setting up the proxy for the Spring Boot CLI without success.
I have tried setting:
1) JAVA_OPTS environment variables for proxies
-Dhttp.proxyHost=proxyhostURL
-Dhttp.proxyPort=proxyPortNumber
-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword

2) I have tried configuring just the http proxy environment variable
 http_proxy

I have previously found the github bug that was closed years ago, but it doesn't seem to be relevant:
https://github.com/spring-projects/spring-boot/issues/136
Thanks for any help!
C:\Windows\system32>spring cloud eureka
Resolving dependencies..

███████╗██████╗ ██████╗ ██╗███╗   ██╗ ██████╗      ██████╗██╗      ██████╗ ██╗   ██╗██████╗
██╔════╝██╔══██╗██╔══██╗██║████╗  ██║██╔════╝     ██╔════╝██║     ██╔═══██╗██║   ██║██╔══██╗
███████╗██████╔╝██████╔╝██║██╔██╗ ██║██║  ███╗    ██║     ██║     ██║   ██║██║   ██║██║  ██║
╚════██║██╔═══╝ ██╔══██╗██║██║╚██╗██║██║   ██║    ██║     ██║     ██║   ██║██║   ██║██║  ██║
███████║██║     ██║  ██║██║██║ ╚████║╚██████╔╝    ╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝
╚══════╝╚═╝     ╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝      ╚═════╝╚══════╝ ╚═════╝  ╚═════╝ ╚═════╝

-- Spring Cloud Launcher --

2016-11-22 07:21:24.970  INFO 12076 --- [-cloud-launcher] o.s.boot.SpringApplication               : Starting application on WKSP0006B796 with PID 12076 (D:\UPSData\DevRepo\spring-boot-cli-1.4.1.RELEASE-bin\spring-1.4.1.RELEASE\lib\spring-boot-cli-1.4.1.RELEASE.jar started by GSD4TYK in C:\Windows\system32)
2016-11-22 07:21:24.998  INFO 12076 --- [-cloud-launcher] o.s.boot.SpringApplication               : No active profile set, falling back to default profiles: default
2016-11-22 07:21:26.097  INFO 12076 --- [-cloud-launcher] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@34f39db4: startup date [Tue Nov 22 07:21:26 EST 2016]; root of context hierarchy
2016-11-22 07:21:28.503  INFO 12076 --- [-cloud-launcher] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-11-22 07:21:30.727  INFO 12076 --- [-cloud-launcher] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-11-22 07:21:30.792  INFO 12076 --- [-cloud-launcher] o.s.boot.SpringApplication               : Started application in 9.955 seconds (JVM running for 17.554)
Exception in thread "spring-cloud-launcher" java.lang.IllegalStateException: failed to resolve MavenResource: org.springframework.cloud.launcher:spring-cloud-launcher-eureka:jar:1.2.1.RELEASE
        at org.springframework.cloud.deployer.resource.maven.MavenArtifactResolver.resolve(MavenArtifactResolver.java:276)
        at org.springframework.cloud.deployer.resource.maven.MavenResource.getFile(MavenResource.java:169)
        at org.springframework.cloud.deployer.spi.local.AbstractLocalDeployerSupport.buildExecutionCommand(AbstractLocalDeployerSupport.java:96)
        at org.springframework.cloud.deployer.spi.local.AbstractLocalDeployerSupport.buildProcessBuilder(AbstractLocalDeployerSupport.java:141)
        at org.springframework.cloud.deployer.spi.local.LocalAppDeployer.deploy(LocalAppDeployer.java:122)
        at org.springframework.cloud.launcher.deployer.Deployer.deployInternal(Deployer.java:199)
        at org.springframework.cloud.launcher.deployer.Deployer.deploy(Deployer.java:105)
        at org.springframework.cloud.launcher.deployer.DeployerThread.launch(DeployerThread.java:116)
        at org.springframework.cloud.launcher.deployer.DeployerThread.run(DeployerThread.java:61)
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Could not transfer artifact org.springframework.cloud.launcher:spring-cloud-launcher-eureka:jar:1.2.1.RELEASE from/to central (http://repo1.maven.org/maven2): Connect to repo1.maven.org:80 timed out
        at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:444)
        at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
        at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveArtifacts(DefaultRepositorySystem.java:302)
        at org.springframework.cloud.deployer.resource.maven.MavenArtifactResolver.resolve(MavenArtifactResolver.java:273)
        ... 8 more
Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact org.springframework.cloud.launcher:spring-cloud-launcher-eureka:jar:1.2.1.RELEASE from/to central (http://repo1.maven.org/maven2): Connect to repo1.maven.org:80 timed out
        at org.eclipse.aether.connector.basic.ArtifactTransportListener.transferFailed(ArtifactTransportListener.java:43)
        at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:355)
        at org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run(RunnableErrorForwarder.java:67)
        at org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute(BasicRepositoryConnector.java:581)
        at org.eclipse.aether.connector.basic.BasicRepositoryConnector.get(BasicRepositoryConnector.java:249)
        at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:520)
        at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
        ... 11 more
Caused by: org.apache.http.conn.ConnectTimeoutException: Connect to repo1.maven.org:80 timed out
        at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:122)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
        at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:328)
        at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:612)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:447)
        at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:884)
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
        at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:164)
        at org.eclipse.aether.transport.http.HttpTransporter.execute(HttpTransporter.java:287)
        at org.eclipse.aether.transport.http.HttpTransporter.implGet(HttpTransporter.java:243)
        at org.eclipse.aether.spi.connector.transport.AbstractTransporter.get(AbstractTransporter.java:59)
        at org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask(BasicRepositoryConnector.java:447)
        at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:350)
        ... 16 more
2016-11-22 07:22:02.575  INFO 12076 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@34f39db4: startup date [Tue Nov 22 07:21:26 EST 2016]; root of context hierarchy
2016-11-22 07:22:02.591  INFO 12076 --- [       Thread-1] o.s.cloud.launcher.deployer.Deployer     :

Shutting down ...

2016-11-22 07:22:02.591  INFO 12076 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
C:\Windows\system32>

A: Can you try maven proxy settings?? I got this issue resolved after setting correct proxy and the correct corporate repository.
https://maven.apache.org/guides/mini/guide-proxies.html
In settings.xml, you can use:
<settings>
  .
  .
  <proxies>
   <proxy>
      <id>example-proxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.example.com</host>
      <port>8080</port>
      <username>proxyuser</username>
      <password>somepassword</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>
  .
  .
</settings>

https://maven.apache.org/guides/introduction/introduction-to-repositories.html
In pom.xml in project, you can use:
<project>
  ...
  <repositories>
    <repository>
      <id>my-internal-site</id>
      <url>http://myserver/repo</url>
    </repository>
  </repositories>
  ...
</project>

Please let me know if it doesnt work for you..

A: I had the same problem, go to your .m2 folder and open the settings.xml. In the settings.xml-file delete the proxy dependencies, close the file and retry!


text:
Q: pandas how to split single row into multiple row based on comma and remove 3rd bracket and single quotation? I have data frame like this where I have multiple image in a single row for every product.
link           https://shopnox.com/collections/all/products/s...
image          ['//cdn.shopify.com/s/files/1/2149/0521/produc...
title                         SLIQUID ORGANICS NATURAL ALOE LUBE
price                                                       $10

I want to split multiple row based on comma and also want to remove 3rd bracket and single quote of image row. I tried this but didn't work
data['image'].replace("[]'", '') #I added single quote inside double quote because I also want to remove  single quote

A: You could try str.split with explode and mask:
data['image'] = data['image'].str.strip('[]').str.replace("'", '').str.split(',')
data = data.explode('image')
data['price'] = data['price'].mask(data['price'].shift() == data['price'])
print(data)


text:
Q: VSTO x64 runtime installed but can't be found I created a WiX installer deploying an add in for Windows 2010. Target system is currently x64 Win & Office installed. I walked through several microsoft sites telling me that i'll need than an x64 installer & runtime (because the add in loads into the process of current word running).
This installer checks the existence of VSTO Runtime using this statement:
<?if $(var.Platform)=x64 ?>
<?define win64Flag = "yes"?>
<?else ?>
<?define win64Flag = "no"?>
<?endif ?>

<Property Id="VSTORUNTIMEREDIST">
    <RegistrySearch Id="VSTORuntimeRedist" Root="HKLM" Key="SOFTWARE\Microsoft\vsto runtime setup\v4R\VSTORFeature_CLR40" Name="Version" Type="raw" Win64="$(var.win64Flag)"/>
</Property>

<Property Id="OFFICERUNTIME">
    <RegistrySearch Id="OfficeRuntime" Root="HKLM" Key="SOFTWARE\Microsoft\VSTO Runtime Setup\v4" Name="Version" Type="raw" Win64="$(var.win64Flag)"/>
</Property>
<Condition Message="The Visual Studio 2010 Tools for Office Runtime is not installed. Please install the Office Runtime.">
    <![CDATA[Installed OR VSTORUNTIMEREDIST>="10.0.30319" OR OFFICERUNTIME>="10.0.21022"]]>
</Condition>

Actually it's working for the x86 Version of my Installer, but build in x64 mode, it is unable to find the x64 entry in the registry at any time (even if the runtime is installed).
I already tried to uninstall and reinstall the runtime (with reboot acutally) but it does not worked.
I also removed the check to get my Add In installed but it's not loading  then acutally.
Therefore my question is, if there is any known bug-issue or I used the wrong registry key?

A: On x64 systems WoW64 apps are transparently redirected into Wow6432Node node of the registry, so they actually look for a key like HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VSTO Runtime Setup there it is located. But the real x64 apps look into real HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSTO Runtime Setup node, and the key is, naturally, not present there. This, most probably causes your installer to fail. So, for a x64 installer you need to specify full node with Wow6432Node path part.
This is called Registry Reflection and covered in details here.


text:
Q: Array string to csv in php I have an array with string array("firstname" => "Mary", "lastname" => "Johnson", "age" => '0025') i want to export to csv file but i got no 0 like this 25 when i export to csv file.
i try these code and i got result without 0
$data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => '0025')
  );

  $colnames = array(
    'firstname' => "Fname",
    'lastname' => "Last name",
    'age' => "Age",
  );

  function map_colnames($input)
  {
    global $colnames;
    return isset($colnames[$input]) ? $colnames[$input] : $input;
  }

  function cleanData(&$str)
  {
    if($str == 't') $str = 'TRUE';
    if($str == 'f') $str = 'FALSE';
    if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
      $str = "$str";
    }
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // filename for download
  $filename = "website_data_" . date('Ymd') . ".csv";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: text/csv");

  $out = fopen("php://output", 'rw');

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      $firstline = array_map(__NAMESPACE__ . '\map_colnames', array_keys($row));
      fputcsv($out, $firstline, ',', '"');
      $flag = true;
    }
    array_walk($row, __NAMESPACE__ . '\cleanData');
    fputcsv($out, array_values($row), ',', '"');
  }

  fclose($out);
  exit;

i got these result
Fname   Lastname   Age
MAry    Johnson    25

Any solution for this?


text:
Q: tikz execution order of transformation Is the execution order of transformation that if the transformation command is after \tikz@addtransform, it will be performed after otherwise right now?
This question rises from following example:
\documentclass[tikz, border=1cm]{standalone}
\tikzset{
  base/.style={
    minimum height=5mm, minimum width=15mm, draw, rotate=#1
  },
  A/.style={base=#1},
  B/.style={base=#1, below=1cm},
}
\begin{document}
\begin{tikzpicture}
  \node [A=90] (a) at (0, 0) {};
  \node [B=90, red] (b) at (a.south) {};
  \usetikzlibrary{positioning}
  \node [B=90, blue] (b) at (a.south) {};
\end{tikzpicture}

I looked up the code in tikz.code.tex and tikzlibrarypositioning.code.tex. The difference I find is the shift transformation code:
tikz.code.tex has a \tikz@addtransform before transformation operation
\tikzoption{below}[]{\def\tikz@anchor{north}\tikz@possibly@transform{y}{-}{#1}}%
\def\tikz@possibly@transform#1#2#3{%
  \let\tikz@do@auto@anchor=\relax%
  \def\tikz@test{#3}%
  \ifx\tikz@test\pgfutil@empty%
  \else%
    \pgfmathsetlength{\pgf@x}{#3}%
    \pgf@x=#2\pgf@x\relax%
    \edef\tikz@marshal{\noexpand\tikz@addtransform{%
        \expandafter\noexpand\csname  pgftransform#1shift\endcsname{\the\pgf@x}}}%
    \tikz@marshal%
  \fi%
}%

while tikzlibrarypositioning.code.tex does not have a \tikz@addtransform before the transformation
\tikzset{below/.code=\tikz@lib@place@handle@{#1}{north}{0}{-1}{south}{1}}%
\def\tikz@lib@place@handle@#1#2#3#4#5#6{%
  \def\tikz@anchor{#2}%
  \let\tikz@do@auto@anchor=\relax%
  \edef\tikz@temp{#1}%
  \def\tikz@lib@place@single@factor{#6}%
  \expandafter\tikz@lib@place@handle@@\expandafter{\tikz@temp}{#3}{#4}{#5}%
}%
\def\tikz@lib@place@handle@@#1#2#3#4{%
  \pgfutil@in@{of }{#1}%
  \ifpgfutil@in@%
    \tikz@lib@place@of#1\tikz@stop{#4}%
  \else%
    \edef\tikz@lib@place@nums{#1}%
  \fi%
  \ifx\tikz@lib@place@nums\pgfutil@empty%
    Ok, nothing to do, we have set the anchor and we are happy...
  \else%
    \expandafter\tikz@lib@place@parse@nums\expandafter{\tikz@lib@place@nums}%
    \pgf@x=#2\pgf@x%
    \pgf@y=#3\pgf@y%
    \edef\tikz@lib@pos@call{\noexpand\pgftransformshift{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
  \fi%
}%

If the real reason is what I guessed, why positioning does not use a \tikz@addtransform?

A: I think you are right. One can look up \tikz@addtransform,
\def\tikz@addtransform#1{%
  \ifx\tikz@transform\relax
    #1%
  \else
    \expandafter\def\expandafter\tikz@transform\expandafter{\tikz@transform#1}%
  \fi
}%

so it adds a transformation to \tikz@transform that gets executed later. Apart from the effect you have mentioned, this effect also can be seen when updating the node distance.
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[nodes={circle,draw,inner sep=10pt},node distance=2cm]
 \node (A) at (0,2){};
 \node[right of=A,blue] (A-1){};
 \node[right of=A,node distance=4cm,dashed,red] (A-2){};
 \node[node distance=4cm,right of=A,dashed,cyan,inner sep=20pt] (A-3){};
 \node (B) at (0,0){};
 \node[right=of B,blue] (B-1){};
 \node[right=of B,node distance=4cm,dashed,red] (B-2){};
 \node[node distance=4cm,right=of B,dashed,cyan,inner sep=20pt] (B-3){};
\end{tikzpicture}
\end{document}

As you can see, when you use the built in (but deprecated) way of positioning nodes relatively, it does not matter if you update the node distance before or after right. On the other hand, if you use positioning, it does.
In principle, one could think of using \tikz@addtransform also in the positioning library. However, this will break existing coded. See, however issue 869 which deals with the question whether or not one should make changes.


text:
Q: Android doesn't detect click on EditText I am working on an Android tablet application with a little bit complex forms (layout has a ListView and the layout with the form included so I have to inflate EditText) . My idea is that if I click on a TextView where the date is shown the DataPicker would be shown in dialog.
The problem is that click is not detected. There is no Logs.
Java:
    public static EditText datep;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admissions_all);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        View inf = LayoutInflater.from(getApplicationContext()).inflate(R.layout.admissions, null);
        datep = (EditText) inf.findViewById(R.id.date_value);

        datep.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.i("Date", "You clicked me mate!");
                showDatePickerDialog(v);
            }
        });

    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
        Log.i("Date", "I want to show datePicker");
    }

    public static class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day= c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
             datep.setText(day + "." + month+ "." + year);
        }
    }

XML:
<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/general"
        android:layout_alignRight="@id/general"
        android:layout_below="@+id/general"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp" >

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="Data"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <View
            android:id="@+id/line"
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
            android:layout_below="@+id/title"
            android:background="#333333" />

        <EditText
            android:id="@+id/date_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/line"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:layout_toRightOf="@+id/date_desc"
            android:ems="9"
            android:inputType="date" >
        </EditText>

        <TextView
            android:id="@+id/date_desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/date_value"
            android:layout_alignBottom="@+id/date_value"
            android:layout_alignParentLeft="true"
            android:text="Date:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

I followed this: http://developer.android.com/guide/topics/ui/controls/pickers.html

A: You need to set date_value's focusable in touch mode to false. You can do so either by adding android:focusableInTouchMode="false" to your xml or in your code with datep.setFocusableInTouchMode(false);. This should then have your on click event fire. (tested on emulator)
See also: How to do something after user clicks on my EditText
Reference: http://android-developers.blogspot.com/2008/12/touch-mode.html

A: I didn't see any dateup.setclickable(true);, try to add this. Maybe that's why it's not work , You can also debug it and see , if it call the onlciklistner  or not
I saw that you wrote something like this.
datep = (EditText) inf.findViewById(R.id.date_value);

when you have this
setContentView(R.layout.admissions_all);

It means that you editText is in another Activity , but you are setting his onclickListner in another one , so it will not work. Initialize his onlcikListner in the activity, that content view is inf.xml. If all these will not help please add more part of your Code
Regards Hayk Nahapetyan

A: Could you change the DatePickerFragment to DatePickerDialog. Then do a DatePickerDialog.show();
Something like :
DatePickerDialog datePickerDialog = null;
datep.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i("Date", "You clicked me mate!");
            showDatePickerDialog();
        }
    });

private void showDatePickerDialog() {
    datePickerDialog = new DatePickerDialog(context, new DateSetListener(), year, month, day);
    datePickerDialog.show();
}


text:
Q: How does the equivalence part work? Considering now a random variable X with a geometric distribution with parameter p > 0, we have
$$E(X) =\sum_{k=1}^\infty kp(1-p)^{k-1} $$
We already shown that
$$\sum_{k=1}^\infty p(1-p)^{k-1} =1 $$
Which implies
$$\sum_{k=1}^\infty (1-p)^{k-1}=1/p $$
If we take the derivative on p we get
$$\sum_{k=1}^\infty(k-1)(-1)(1-p)^{k-2}=-1/p^2$$
which is equivalent to
$$\sum_{k=1}^\infty k(1-p)^{k-1}=1/p^2 $$
I know this is a silly question, but I couldnt get the equivalent part how is$$\sum_{k=1}^\infty k(1-p)^{k-1}$$ is equivalent to$$\sum_{k=1}^\infty(k-1)(-1)(1-p)^{k-2}$$  it will be much appreciated if someone explain on how they are equivalent?

A: \begin{align}
\sum_{k=1}^\infty k(1-p)^{k-1} = {} & 1(1-p)^0 + 2(1-p)^1 \\ & {} + 3(1-p)^2 + 4(1-p)^3+\cdots \\[12pt]
\sum_{k=1}^\infty (k-1)(1-p)^{k-2} = {} & 0(1-p)^{-1} \\
& {} + 1(1-p)^0 + 2(1-p)^1 \\[8pt]
& {} + 3(1-p)^2 + 4(1-p)^3 + \cdots
\end{align}


text:
Q: Unable to read params from request My Angular :
$http.get('/api/orders', {
        params: {
            userId:userId,
            token:token
        }
     })
     .success(function (data,status) {

     });

My Node :
  router.route('/')
        //GET all Orders
        .get(function(req, res, next)
            {
           console.log(req);
          });

My Result :
.......
.
.
params:{},
query :{token:'mytoken',userId:'myUserId'}
.
.
......

Why my params is blank and query is filled with parameters.I want my data in params.Where I'm wrong ?

A: By setting params object, to $http.get method in agular you are simply adding data to query string. As written here:
params – {Object.<string|Object>} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.

So, it`s logic for them to appear in req.query object on server side. In order to get this data in req.param object, you have to map it in the route. Change route to:
app.get('/api/orders/:userId/:token', ...);

And angular request to:
$http.get('/api/orders/' + userId + '/' + token })
     .success(function (data,status) {

     });


text:
Q: Biblatex - remove extra spacing in citation range I am using a biblatex-gost package with a gost-numeric style. Here is a MWE:
\documentclass[12pt,a4paper]{article}
\begin{filecontents}{\jobname.bib}
@book{halanay,
    langid = {english},
    title = {Differential Equations Stability, Oscillations, Time Lags},
    author = {A. Halanay},
    location = {New York--London},
    publisher = {Acad. Press},
    year = {1968},
    pagetotal = {568},
}
@book{lakshmikantham,
    langid = {english},
    title = {Theory of Integro-Differential Equations},
    author = {V. Lakshmikantham and M. R. M. Rao},
    location = {London},
    publisher = {Gordon and Breach},
    year = {1995},
    pagetotal = {384},
}
@book{hartman,
    langid = {english},
    title = {Ordinary Differential Equations},
    author = {P. Hartman},
    location = {Philadelphia},
    publisher = {Society for Industrial and Applied Mathematics},
    year = {2002},
    pagetotal = {612},
}
\end{filecontents}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english,ukrainian]{babel}
\usepackage[backend=biber,bibencoding=utf8,maxbibnames=999,style=gost-numeric,language=auto,autolang=other]{biblatex}
\addbibresource{\jobname.bib}

\toggletrue{bbx:gostbibliography}
\usepackage[autostyle]{csquotes}

\begin{document}

This was investigated in \cite{halanay,lakshmikantham,hartman}. And that -- in \cite{hartman,halanay}.

\end{document}

But I get [1   -3 ] and [1 ; 2 ], respectively.

How do I remove extra spacing in the citation range? I need to have simply [1-3] and [1,2] (comma instead of a semicolon, if possible).

A: On a fully updated system I get

as desired.
In the comments we established that if you change language=auto to
language=autobib

the spaces disappear. That shows that the problem lies with the language definitions on your system. The possible sources of problems are

*

*Missing % to avoid spurious spaces in ukrainian.lbx

*Missing % in \DefineBibliographyExtras{ukrainian}

*Missing % in ukraineb.ldf
Since we don't have your files, you will have to investigate that yourself. While it may be tempting to just say language=autobib and not investigate the source of the spurious space further that just treats the symptom, not the cause. You may end up with unwanted spaces in other situations where there is no easy way out, so do investigate a bit.

If you want to change the separator from a semicolon

[1; 2]

into a comma you need
\renewcommand*{\multicitedelim}{\addcomma\space}

to get

[1, 2]