text:
Q: axios - how to chain axios calls within a single promise I am still very new to Axios and promises.  I'm close to understanding this, but I know I am doing some things wrong.  I have a javascript method that is supposed to return a promise.  Inside that method, I have an Axios post with two .then methods chained onto it.  If my initial post fails, I get this ugly error in the console: Unhandled promise rejection ReferenceError: "reject is not defined".  I have a feeling I shouldn't be nesting the .catch methods like I am.  I'm thinking it should simply be post.then.then.catch.
Additionally, can anyone see why I'm not getting itemInformation being sent back in the response in the second .then?
Here is the relavant Javascript code(the addToCartVue method gets called first):
addToCartVue(itemData) {
  let vm = this;
  return new Promise((resolve, reject) => {

    vm.buildDataString(itemData);

    axios.post(POST_ENDPOINT, {
        data: vm.dataString
      },
      {
        /*headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }*/
      }).then(response => {
      return vm.updateCartInfo(vm.dataString, itemData.addToCartParameters.itemId, vm.selectedStoreId, vm.quantity);
    }).then(response => {
      if (itemData.addToCartParameters.showLB) {
        vm.emitGlobalEvent('addToCart::open', itemData);
        resolve(response);
      }
    }).catch(error => reject(error));
  }).catch(error => reject(error));
}, // end of addToCartVue method

buildDataString(itemData) {
  // irrelevant code that builds quantity and dataString variables

  vm.quantity = quantity;
  vm.dataString = dataString;
}, // end of buildDataString method

updateCartInfo(dataString, itemId, selectedStore, quantity) {
  axios.get(GET_ENDPOINT, {
    params: {
      data: dataString
    }
  }).then(response => {
    cartDropDown.populateCartDropDown(response);
    const addedItem = response.addedItem;
    const basketInfo = response.basketInfo;

    let productQuantity = quantity;
    if (addedItem.quantity > -1) {
      productQuantity = addedItem.quantity;
    }

    const itemInformation = {
      "itemId": itemId,
      "selectedStore": selectedStore,
      "addedItem": addedItem,
      "basketInfo": basketInfo,
      "displayValues": null,
      "quantity": productQuantity,
      "isCustomProduct": false
    };

    return itemInformation;
  }).catch(err => error => reject(error));
} // end of updateCartInfo method

A: I think the issue is missing 'return' keyword.
Try adding return in two places.
 return axios.post(POST_ENDPOINT...

And also inside updateCartInfo,
return axios.get(GET_ENDPOINT,...

Also, i don't think you need to wrap you code inside a Promise object since axios already returns a promise.This will avoid reject reference error.
let vm = this;
vm.buildDataString(itemData);
return axios.post(POST_ENDPOINT, {
    data: vm.dataString
  },
  {
    /*headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }*/
  }).then(response => {
  return vm.updateCartInfo(vm.dataString, itemData.addToCartParameters.itemId, vm.selectedStoreId, vm.quantity);
}).then(response => {
  if (itemData.addToCartParameters.showLB) {
    vm.emitGlobalEvent('addToCart::open', itemData);
    return response
  }
})

And catch your errors in the call to
addVue().then(data => console.log(data).catch(err => console.log(err))


text:
Q: MySQL Workbench "->" Support It looks like MySQL Workbench is now supporting JSON functionality, however I'm still seeing parser errors on MySQL 5.7.9 functionality, such as the "->" operator.
When I use the following query, I'm getting a syntax error over the "$.test" portion:
Record
record: {"test": 123}
Query
SELECT test->"$.test" FROM table
The query still executes successfully, however I'm curious as to why the syntax parser is incorrectly showing an error.

A: OK, the problem is probably something else than what I posted in my comments. You are using double quotes, which represent strings only if the ANSI quotes are not enabled (then they wrap identifiers). Use single quotes instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to change the format of datetime column when it is bound dynamically in gridview protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DateTime dt,dt1;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            dt = Convert.ToDateTime(e.Row.Cells[4].Text);
            e.Row.Cells[4].Text = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
            dt1 = Convert.ToDateTime(e.Row.Cells[5].Text);
            e.Row.Cells[5].Text = dt1.Month.ToString() + "/" + dt1.Day.ToString() + "/" + dt1.Year.ToString();
        }

    }

This is my code and the column with index 5 is a datetime the problem is that it can be NULL so the following error turns up when it is
"String was not recognized as a valid DateTime"
Any Solution Please help??!
thank u!

A: Try using DateTime.TryParse instead and only if it returns true run the rest of the code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DateTime dt,dt1;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            bool success = DateTime.TryParse(e.Row.Cells[4].Text, dt);

            if(success)
            {
                e.Row.Cells[4].Text = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
                dt1 = Convert.ToDateTime(e.Row.Cells[5].Text);
                e.Row.Cells[5].Text = dt1.Month.ToString() + "/" + dt1.Day.ToString() + "/" + dt1.Year.ToString();
            }
    }
}

A: Did you try a simple check?
something like
if (!String.IsNullOrEmpty(e.Row.Cells[4].Text))
    e.Row.Cells[4].Text = Convert.ToDateTime(e.Row.Cells[4].Text).ToString("MM/dd/yyyy");
else
    e.Row.Cells[4].Text = "-";

A: What about setting the BoundField.DataFormatString and the BoundField.NullDisplayText properties, like:
<asp:GridView ID="BoundFieldExample" runat="server">
     <Columns>
          <asp:BoundField DataFormatString="{0:d}" NullDisplayText="Not Found" />
     </Columns>
</asp:GridView>

The above will display dates in short date string format for the current culture and the text "Not Found" for Null values.
See GridView BoundField Class for more information.


text:
Q: How to manually trigger Paypal error 10486 in sandbox? Paypal says, use CCREJECT-REFUSED for address1 in credit card detail. https://developer.paypal.com/webapps/developer/docs/classic/express-checkout/ht_ec_fundingfailure10486/
I tried creating new test user (CC credential was automatically created). Login into sandbox and add CC detail I got from first step. I change address line to CCREJECT-REFUSED. Save it. And then tested it, checking out via sandbox. Error 10486 was not triggered.
Any hint?

A: Mistake I made was to edit the SHIPPING address instead of the BILLING address.
Your best bet is to log directly into https://www.sandbox.paypal.com  and hit the 'Profile' tab and try to add or edit a card there.
Watch out for the following :

*

*Make sure you put exactly CCREJECT-REFUSED for BILLING address Line 1 with no spaces and TWO C at the beginning

*They seem to be incompetent to keep the site running smoothly at all times so just try again
later if you get Service Temporarily Unavailable.

*Make sure if you're adding a new card (you can use your own real card number) that you aren't getting a message telling you This card number is already assigned to another PayPal account. For security reasons, each card may only be assigned to one PayPal account because then you'll not be adding anything

*Make sure payment method is actually set to credit card before you hit Submit for the order.
It does actually work though (as of today)

A: Okay, I was wrong to assume that the error can be triggered using direct CC payment.
As the document suggest:

*

*You need to create a test user account

*Login into sandbox using fore-mentioned account.

*Change address part of test user CC to: CCREJECT-REFUSED
Then, in order to test it, run your express checkout flow as usual. But on the last part, do not use direct CC input. Instead, choose the other option -- login into your test user paypal account.
You will then received this kind of response:

TIMESTAMP=2013%2d08%2d19T06%3a50%3a45Z&CORRELATIONID=6761aff7944b&ACK=Failure&VERSION=104&BUILD=7319395&L_ERRORCODE0=10486&L_SHORTMESSAGE0=This%20transaction%20couldn%27t%20be%20completed%2e&L_LONGMESSAGE0=This%20transaction%20couldn%27t%20be%20completed%2e%20Please%20redirect%20your%20customer%20to%20PayPal%2e&L_SEVERITYCODE0=Error

A: All of these answers are now out of date. It's impossible to add a card with CCREJECT-REFUSED as the address and, if you could, it wouldn't do anything. You should follow the instructions at: https://developer.paypal.com/docs/classic/lifecycle/sb_error-conditions/
For the majority of APIs exposed by PayPal, this usually involves setting the order amount to the desired error code after enabling negative testing mode for your sandbox business account.
For example, triggering a 10486 via the Express Checkout NVP API would involve setting the AMT to $104.86.

A: As taking directly from their tutorial: (see step 2)

*

*Login to https://www.sandbox.paypal.com using your buyer's test PayPal account.

*Replace the contents of the street address Line-1 of the buyer's test credit card, with CCREJECT-REFUSED.

*Execute a typical Express Checkout payment flow against the Sandbox test environment using the same buyer account and with the same credit card that you just modified.

*When you execute DoExpressCheckoutPayment, error code 10486 will be returned. Your code should redirect the buyer back to PayPal using the same redirect URL used to start the checkout flow and the same Express Checkout token.


text:
Q: Selenium test go too fast and redirect to next page before clicking on element Selenium test go too fast and redirect to next page before  clicking on element
I have the following test : login with multiple users loaded from excel file and create multiple persons  which is also loaded from excel file
the problem I meet is that the test goes to create-person page before the login done but when  setting Thread.sleep(1000) the test passed
for more clarification here is my code below
@Given("user logged in and populates the form and click create and logout")
public void user_logged_in_and_populates_the_form_and_click_create_and_logout() throws InterruptedException {
    userLoginCreationPage.init();
    logger.info("**************************************** init the driver && go to login page http://localhost:4200/login");

    for (UserLoginPageData userLoginPageData : userLoginPageDataList) {
        logger.info("Line  " + userLoginPageData.getRowIndex() + "from Excel file");
        userLoginCreationPage.enterUsername(userLoginPageData.getUsername());
        userLoginCreationPage.enterPassword(userLoginPageData.getPassword());
        userLoginCreationPage.clickOnLogin();
        Thread.sleep(500);
        logger.info(userLoginPageData.toString() + "is login");
        personCreationPage.init();
        logger.info("**************************************** init the driver && go to creation page http://localhost:4200/dossier-person/new");
        for (PersonPageData personPageData : personPageDataList) {
            if (userLoginPageData.getIdUser().equals(personPageData.getIdUser())) {
                personCreationPage.refresh();
                personCreationPage.enterUsername(personPageData.getUsername());
                personCreationPage.enterEmail(personPageData.getEmail());
                personCreationPage.enterPassword(personPageData.getPassword());
                personCreationPage.clickTab();
                personCreationPage.clickOnCreate();
                logger.info(personPageData.toString() + " ****************************************  is created by " + userLoginPageData.getUsername());
            }
        }
        userLoginCreationPage.clickOnLogout();
    }
}


text:
Q: Fade in PNG fix for IE8 I am using the jQuery Cycle plugin to fade in an animation. This works fine on everything except for PNG files having half transparent pixels in them in IE8. The half transparent pixels are black during the fade.
Things i tried:

*

*Unit PNG : Solved it, but messed the CSS up so bad that it even makes it worse.

*jquery.pngFix.js : Doesn't do anything.

*Malsup's cycle tips: cleartype:false (no result) and cleartypeNoBg: true (Works, except for the fading itself).

*Adding BG-color: Works, but i'd like to background to be transparent. It doesn't work to add a transparent BG image.

*Trying X-UA-Compatible mode : Doesn't do anything.

Any guesses?
JSFiddle here: http://jsfiddle.net/HaEym/

A: It's not glamorous, but you can replace png's with gifs using IE specific css hacks. Once I had to show the PNG (because the gif was LQ, so after the animation I replaced the gif with the png.
For specific examples see another Stack Overflow


text:
Q: Sheldon Axler 4.11: How to understand the proof I have trouble in understanding the proof of 4.11 in Linear Algebra Done Right (Third Edition). The Theorem is the following:

4.11 Each zero of a polynomial corresponds to a degree-1 factor
Suppose $p\in\mathcal{P}(F)$ and $\lambda\in F$. Then $p(\lambda)=0$ if and only if there is a polynomial $q\in\mathcal{P}(F)$ such that
$p(z)=(z-\lambda)q(z)$
for every $z\in F$.

The second paragraph proof to prove "$p(\lambda)=0$  => $p(z)=(z-\lambda)q(z)$" given is the following:

Proof
...
To prove the other direction, suppose $p(\lambda)=0$. The polynomial $z-\lambda$ has degree 1.
...

I don't understand that sentence "The polynomial $z-\lambda$ has degree $1$".
Questions:

*

*Since $\lambda\in F, z\in F$, Shouldn't the polynomial $z-\lambda$ have degree $0$?

*Why does the polynomial $z-\lambda$ have degree $1$?


text:
Q: How to always show all apps in Dash? I have Oneiric running in Virtualbox with Unity (3D), it's up todate as of now. When I go to the Dash to find an app I have to click a small arrow to show all the apps in that category.

Once I click it, it shows all the apps during the current session. However, after rebooting I have to click the arrow again to show all apps.
Is there anything I could do to save this 'Show all apps' settings permanently?

A: It is not possible at least for now ,it is hardly coded in unity ,To it you have to create a patch for unity


text:
Q: Retrieve saved (hidden) SSH password from PhpStorm 2017.1 I have forgotten SSH password from Remote Server, but it is saved in IDE (PhpStorm 2017.1) in hidden way:

Is there any way to view hidden password?

A: I finally could retrieve password from PhpStorm 2017.1:

*

*Go to Settings/Preferences | Appearance & Behavior | System Settings | Passwords, enter new master password and save.

*Open /.PhpStorm2017.1/config/c.kdbx (in "Keepass 2" or "Keeweb") with saved master password.

*Here it is!
Thanks to @LazyOne


text:
Q: How to get two mysql querie results in one JSON array? in my current project I have to create a JSON array, in which for each day a status with a colour is displayed in a calendar (FullCalendar) and additionally a button with a link is to be displayed for all days where an event is planned.
For this I have two SELECT's which both work on their own. I have already tried some things how to put the results of both SELECT's into one JSON array, but I keep getting the error 'Undefinded Variable'.
How do I have to pack the results of the two SELEC T's put together that all results are displayed correctly?
header('Content-Type: application/json');

include "../../../includes/db.php";

if(isset($_GET['team_id'])) {
   $team_id = $_GET['team_id'];
}

$stmt = $connection->prepare("SELECT date FROM date");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {

   $date = $row['date'];

   $team_planner_user_status_present = 1;
   $team_planner_user_status_absent = 2;
   $team_planner_user_status_reservation = 3;
   $stmt1 = $connection->prepare("SELECT
                                   (
                                      SELECT COUNT(*)
                                      FROM team_planner_user
                                      INNER JOIN user ON team_planner_user.user_id = user.user_id
                                      WHERE user.team_id = ?
                                      AND team_planner_user.date = ?
                                      AND team_planner_user.team_planner_user_status = ?
                                   ) AS present,
                                   (
                                      SELECT COUNT(*)
                                      FROM team_planner_user
                                      INNER JOIN user ON team_planner_user.user_id = user.user_id
                                      WHERE user.team_id = ?
                                      AND team_planner_user.date = ?
                                      AND team_planner_user.team_planner_user_status = ?
                                   ) AS absent,
                                   (
                                      SELECT COUNT(*)
                                      FROM team_planner_user
                                      INNER JOIN user ON team_planner_user.user_id = user.user_id
                                      WHERE user.team_id = ?
                                      AND team_planner_user.date = ?
                                      AND team_planner_user.team_planner_user_status = ?
                                   ) AS reservation
                                ");
$stmt1->bind_param("sssssssss", $team_id, $date, $team_planner_user_status_present,
                                $team_id, $date, $team_planner_user_status_absent,
                                $team_id, $date, $team_planner_user_status_reservation);
$stmt1->execute();
$result1 = $stmt1->get_result();
while($row1 = $result1->fetch_array()) {

    $present = $row1['present'];
    $absent = $row1['absent'];
    $reservation = $row1['reservation'];

    if($present >= 5) {
        $color = '#a1ff9e';
    } else if($present + $reservation >= 5) {
        $color = '#fcff9e';
    } else {
        $color = '#ff9e9e';
    }
}

$stmt1->close();

$stmt2 =$connection->prepare("SELECT * FROM game_planned INNER JOIN game_role ON game_planned.match_role_id = game_role.match_role_id WHERE team_id = ? AND game_planned_date = ?");
$stmt2->bind_param("ss", $team_id, $date);
$stmt2->execute();
$result2 = $stmt2->get_result();
while($row2 = $result2->fetch_array()) {
    $match_role_name = $row2['match_role_name'];
    $game_planned_id = $row2['game_planned_id'];
}

$data[] = array(
    'start' => $date,
    'display' => 'background',
    'color' => $color,
);

if($result->num_rows === 0) {
    echo "";
} else {
    $data[] = array(
        'title' => $match_role_name,
        'url' => 'http://localhost/r6team-redesign/team/team.php?team=details-match-plan&match_planned_id='.$game_planned_id,
        'start' => $date,
    );
}
}

$stmt->close();

echo json_encode($data);


text:
Q: Convert Set with specific Type to Array - Swift 2.3 Using Swift 2.3, I have a Core Data Set defined with a specific type, like this :
@NSManaged public var personEntities: Set<PersonEntity>?

And I simply want to convert that to a swift 2.3 Array of PersonEntity - simple right?  Ive tried the following and they all produce errors of various kinds :
cell.people = Array(self.memory.personEntities)

(Cannot invoke initializer for type .. with an argument list of type ..)
cell.people = self.memory.personEntities.flatMap({$0 as? PersonEntity})!

(Cannot assign value of type Person Entity to type [PersonEntity])
cell.people = self.memory.personEntities.flatMap({$0})

(Flatmap produces U, not the contextual result type _)
Any help much appreciated.

A: With thanks for contributers via comments, this was the correct answer :
cell.people = Array(self.memory.personEntities ?? [])

It failed previously because self.memory.personEntities is an Optional.  So by adding ?? [] it could fail to get personEntities (if its nil) and instead just provide an empty array [].


text:
Q: New todo created but not displayed - todos app with EmberJS without ember-data I am getting started with EmberJS, followed the Screencast. I am trying to do the TODOs app without ember-data.
Following is my HTML
<!doctype html>

    <meta charset="utf-8">
    <title>Ember.js • TodoMVC</title>
    <link rel="stylesheet" href="css/style.css">

    </script>

The javascript - all in one place.
window.Todos = Ember.Application.create();

Todos.Router.map(function () {
  this.resource('todos', { path: '/' });
});

Todos.TodosController = Ember.ArrayController.extend({
   actions:{
      createTodo: function(){
         var title = this.get('newTitle');
         if(!title.trim()){return;}
         todos.push({
            id: todos[todos.length-1].id +1,
            title: title,
            isCompleted: false
         });
         this.set('newTitle','');
      }
   }
});

Todos.TodosRoute = Ember.Route.extend({
    model: function(){
        return todos;
    }
});

var todos=[{
      id: 1,
      title: 'Learn Ember.js',
      isCompleted: true
   },
   {
      id: 2,
      title: '...',
      isCompleted: false
   },
   {
      id: 3,
      title: 'Profit!',
      isCompleted: false
}];

The problem is when I try to add a new todo entry, it is not shown in the UI as added, but when I type todos on the console.
I see the new entry had been added. Why is it that the model is changed but nothing is shown in the UI ?
I also notice that the new entry in the todos array does not have methods like getTitle, setTitle, get isCompleted, set isCompleted that other objects have - which makes me think I am definitely not missing something here.
It seems like I need to get hold of model for TodosRoute and add to it, if that is what I need to do.
How can I do that ?

A: You have to use todos.pushObject() instead of simple array.push().
Short explanation: "Push the object onto the end of the array. Works just like push() but it is KVO-compliant." http://emberjs.com/api/classes/Ember.MutableArray.html#method_pushObject
Somewhat longer explanation: While Ember extends JS objects like array by default to make them better citizen in Emberland, it doesn't override existing methods like push(). This is why you need to use a separate method (pushObject) - it's Ember's solution to make data binding work on JS objects like an array.
Almost the same goes for plain JS objects: Ember has Ember.Object, which has some methods of it's own, which are not needed when all you need is a classic JS object. That doesn't mean you must use Ember.Object every time, in this case Ember is smart enough to set up data binding for you, based on the properties you access from your Handlebars template.


text:
Q: JavaScript and Hide div not working I am trying to hide the dive using style property of div i.e.
    <div id="<%=divCount%>" style="display: block" hidden>

But it is not working.
 And I am also writing a script in the head for hiding/showing divs. It is also not working


text:
Q: safari does not allowed cross-domain cookies in iframe IE & Safari Browser blocks cross-domain cookies in an iframe.
e.g.
I have two websites, let's say they're example.com and anotherexample.net.
On example.com, I have one page http://example.com/someform.asp and in this page i am using cookies. When I open http://example.com/someform.asp directly in browser, it is working fine.
On anotherexample.net, I have page http://anotherexample.net/page.asp, this page contains an IFRAME SRC="http://example.com/someform.asp". Now when we open http://anotherexample.net/page.asp page in browser, the cookies for example.com are not saved. In Firefox and chrome this problem doesn't appear.
I found that using p3p policy we can fix this, but after setting below p3p policy in IIS response header and its works for IE only.
P3P : CP="This is  a P3P policy! See  http://www.workplaceanswers.com/privacy-and-terms/"

But, I am still getting the same error in safari. I have tried with different p3p policy values as below but not able to fix it.
P3P : CP="CUR ADM DEV HIS TEL STA STP COM"
P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"
P3P:CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"

Is there any way to make this work in Safari?

A: There is a solution posted by Vitaliy Ryepnoy at github: https://github.com/vitr/safari-cookie-in-iframe
The gist:
In the main window (example.com), you should detect if the browser is safari,if so, you redirect the user to iframe.com/fix_safari.html, where you set a cookie and redirect again to example.com.
Then, safari let's you set a cookie in the iframe, because there is already a cookie there from iframe.com
worked for me, after hours of frustration
more details and code example in the github page

A: Actually, I was suffered from cross domain cookie issue in safari web browser in mac & iPhone devices.
                  So, I was create one temp file on client machine and save all cookies in that temp file for One domain. And when I  was try to read that cookies from another domain file then in that file i was made changes like if cookies are not set then fetch cookies data from that temp file And again set cookies for that second domain. It's work successfully.


text:
Q: CakePHP: Pagination in an Element on home.ctp I'm using CakePHP to create a frontend UI for PowerDNS, using a MySQL backend. On the front page of the app I want to have a handful of widgets ('Quickly add a record', 'Quickly add a domain' etc.). One of the widgets I want is a paginated list of existing domains.
The index function in DomainsController.php looks like this:
public $paginate = array(
  'fields'     => array('id', 'name'),
  'limit'      => 25,
  'order'      => array( 'name' => 'asc' ),
  'conditions' => array( "NOT" => array( "name LIKE" => "%.arpa" ) )
);

public function index() {
  $domains = $this->paginate();
  if ( $this->request->is('requested')) {
    return $domains;
  } else {
    $this->set('domains', $domains);
  }
}

I've created an element that looks like this:
<?php $domains = $this->requestAction('Domains/index'); ?>

  <?php foreach( $domains as $domain) :?>

echo $domains['domain']['name']

  <?php endforeach; ?>

<?php echo $paginator->numbers(); ?>

When I visit the front page, I get an 'Undefinied variable: paginator' error. I've tried using $this->Paginator->numbers() instead but that just gives me 'Undefined property: View::$Paginator'. Adding the 'Paginator' helper to PagesController.php doesn't help either - $this->Paginator becomes available but I get 'Undefined index: pageCount'.
Is it possible to do this kind of pagination from an element on home.ctp or am I going to have to do some custom JavaScript stuff?
EDIT
Now I'm getting somewhere: I changed my DomainsController index function to this:
public function index() {
 $domains = $this->paginate();
 $paginator = $this->params;
 if ( $this->request->is('requested')) {
  return compact( 'domains', 'paginator' );
 } else {
  $this->set('domains', $domains);
 }
}

And added the following to the domainList.ctp element:
<?php
$result = $this->requestAction('Domains/index');
$domains = $result['domains'];
$this->Paginator->request = $result['paginator'];
?>

  <?php foreach( $domains as $domain) :?>

echo $domains['domain']['name']

  <?php endforeach; ?>

<?php echo $paginator->numbers(); ?>

$this->Paginator is now working properly and I can access all of its methods and properties and so on as normal. My problem now is that if I click on, say, '2', the browser navigates to /pages/home/page:2 but the domain list still shows page 1. Just need to figure out how to pass 'page:2' to the element. And AJAX-ify the whole thing so that I don't need to refresh the whole page.

A: Firstly, don't do this:
$domains = $this->requestAction('Domains/index');
It's expensive and not good practice and I'm not sure why you need to be doing it from your example.
Secondly, call your paginate like this:
$domains = $this->Paginate('Domain');

A: OK, I solved this problem, although my solution probably isn't very elegant.
DomainsController.php has a listDomains() function that looks like this:
public function listDomains() {
 $domains = $this->paginate();
 $paginator = $this->params;
 if ( $this->request->is('ajax') ) {
  $this->set( 'domains', $domains );
 }
 if ( $this->request->is('requested')) {
  return array( 'domains' => $domains, 'paginator' => $paginator, 'paging' => $this->params['paging'] );
 } else {
  $this->set( 'domains', $domains );
 }
}

home.ctp references an element called domainList.ctp. domainList.ctp, below, in turn uses requestAction() - I know, I know - to call the domainList() function above. Bequest the request is requested, an array containing the values of $domains and $paginator is sent back to the element.
domainList.ctp contains this code:
<?php
$result = $this->requestAction('Domains/listDomains', array('updateId' => 'domainList') );
$domains = $result['domains'];
$paginator = $result['paginator'];
$this->Paginator->request = $paginator;

$this->Paginator->options(array(
 'update' => '#domainList',
 'evalScripts' => true,
 'url' => array('controller' => 'Domains', 'action' => 'listDomains', 'updateId' => 'domainList' ),
));

?>

Essentially what I'm doing here is manually re-populating $this->Paginator->request with the params that were originally sent to the DomainController's domainList() function. This lets me access the various paginator functions, like numbers(), prev() and next(), properly. It's a bit messy but guess what? It gets a little messier.
When you click on the links created by those paginator functions, the 'if ( $this->request->is('ajax') )' segment is executed and the div object on the page is updated with the contents of View/Domains/domainList.ctp instead of View/Elements/domainList.ctp. The contents of View/Domains/domainList.ctp is more or less the same as the corresponding element and the two have to be kep more or less syncronised. The difference is that we don't need to manually populate $this->Paginator:
<?php
$this->Paginator->options(array(
 'update' => '#domainList',
 'evalScripts' => true,
 'url' => array('controller' => 'Domains', 'action' => 'listDomains', 'updateId' => 'domainList' ),
));

?>

Like I said, it's messy and inelegant but it worked for me. I'd be happy to know if anyone has a less kludgy way to do this.


text:
Q: How to use Wait async process in c#? i have problem with my code. I have launcher and auto updates.
i want unzip proccess wait the download but i cant do it. Can you help me ?
Hi,
i have problem with my code. I have launcher and auto updates.
i want unzip proccess wait the download but i cant do it. Can you help me ?
async void DownFile(string savep, string url)
{
    using (WebClient webClient = new WebClient())
    {
        webClient.UseDefaultCredentials = true;
        webClient.DownloadProgressChanged += client_DownloadProgressChanged;
        webClient.DownloadFileCompleted += client_DownloadFileCompleted;
        await webClient.DownloadFileTaskAsync(new Uri(url), savep);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Download In Process";
    DownFile(savep, url);
    label1.Text = "unzip";

    Program.ExtractZipFile(savep, "", Application.StartupPath);

    button1.Enabled = false;
}

Await - Async Download Problem

A: DownFile is an async void Method. Calling such a method is called fire and forget, because you have no chance to determine when the asynchronous operation finished. In fact you almost never want to use async void except in the case of event handlers. Instead use async Task for asynchronous operations that don't return a value. In your case you have a perfect example when to use async void and when async Task.
async Task DownFile(string savep, string url)
{
    using (WebClient webClient = new WebClient())
    {
        webClient.UseDefaultCredentials = true;
        webClient.DownloadProgressChanged += client_DownloadProgressChanged;
        webClient.DownloadFileCompleted += client_DownloadFileCompleted;
        await webClient.DownloadFileTaskAsync(new Uri(url), savep);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Download In Process";
    await DownFile(savep, url);
    label1.Text = "unzip";

    Program.ExtractZipFile(savep, "", Application.StartupPath);

    button1.Enabled = false;
}


text:
Q: Adding FontCombo to ToolBar by using CMFCToolbarFontComboBox in VC++2012? I'm using VC++2012 to learn MFC programming, with the wizard generation, there are systems toolbar already. I want to edit text in my document, so I set view class to derived from "CRichEditView" class then I can add button and control to toolbar, but a problem is that I cannot add any controls to toolbar which the toolbar itself has CMFCToolBar as a baseclass.I actually planned to add a font combobox and fonsize combobox, eventhough I did do a researh,but it's still no answer where is wrong.Here are some sample link I failed to compile.
http://www.drdobbs.com/windows/adding-a-combo-box-to-a-toolbar/184416845
After modified I got it buid without failed, but I have no idea why popup "debug assertion failed" error.
some sample from here also didn't work
https://stackoverflow.com/questions/15084210/the-combobox-on-the-toolbar-can-load-itemsprint-them-in-the-output-window-while
Anyway I seem to found out here--->
http://msdn.microsoft.com/en-us/library/vstudio/bb982559.aspx
I think it is something I want to, but with my knowledge at the moment, after took a look at the Remarks, I really have no idea how to do each step in more detail.
I prefered to use a CMFCToolBarFontComboBox class with CMFCToolBar, and with CRichEditView.
Any answer or recommended would be appreciate.

A: You find a complete sample here.
WordPad Sample
It is exactly what you are currently trying to build.

A: OK, now I have a Fontcombo in my toolbar, my next question is that how to change the selected font in CRichEditView when I'm changing a fontname in the list.
I have used CMFCToolbarFontComboBox::Setfont(), but didn't work, what handler should I deal with, or is there anyway(exclude: WordPad Sample) to sync font between font in view and font in list of combo?


text:
Q: Android Options Menu for login how to change android option menu in session management.
session.isLoggedIn();
menu items:-
Login
Logout
my code is
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    if(session.isLoggedIn()){
        menu.findItem(R.id.action_logout).setVisible(true);
        menu.findItem(R.id.action_register).setVisible(false);
    }else{
        menu.findItem(R.id.action_logout).setVisible(false);
        menu.findItem(R.id.action_register).setVisible(true);
    }

    return true;

}


text:
Q: Is a HTML helper a place for Business Logic? I asked this question earlier about business logic and presentation logic, and it got me thinking.. I think it's easier to spot questionable practice when looking at code in a View because I'm automatically suspicious when I see it. Usually it's ok because it's presentation logic, but I always tend to look closer.
But I don't look as close when it's in a HTML helper. In fact, I know I've done it before and I've told others to move the business logic into a Helper. But is that right?
My guess now is that it's not.. I think the job of the helper is the same as the job of the view. Presentation only. What do you guys think?

A: The HtmlHelper should be concerned only with outputting the relevant html into your view and should not have knowledge of any business rules. This should be done in your business layer / domain model layer.
The question you need to ask yourself is, "If I took the HtmlHelper out of the current application and put it into another MVC application, could it be reused without modification?". If the answer is no, there's a good chance it knows too much :)

A: I think you should better put your business logic into your domain model or into services. That way it's much more testable and reusable

A: Without wishing to sound obvious, the HTML in HTMLHelper is a big clue as to the fact that this component is presentation focused. I would expect to find no business logic here, and purely HTML functionality (that, likely, could be reused in other projects?)

A: All your HTMLHelpers should allow being ported over to another assembly and be used across your org :)


text:
Q: Issue creating isolated scope in Angular + UI Bootstrap I have a simple table of data, created using AngularJS. One of the columns of the table is calculated from a function on the controller.
I have a button on the page that opens a new modal. When I open a modal using UI bootstrap, I get a new isolated scope (child of the root scope), as expected. If, however, I have an input text in the modal any key-presses in this text field automatically invoke functions on the parent scope - even though I can verify that the scope is isolated.
Here is a plunkr of the behavior: http://plnkr.co/edit/JzhxSDcSefDe04Psxq0w
As shown in the example, the third column of the table is calculated with a function called "ageNextYear". When the table is being rendered, this function is called many times as expected (and can be verified in the console log). If however, I open the modal and type some text in to the field, the "ageNextYear" function on the parent scope still gets called (type some text in the input field and watch the console log output).
I'm not sure whether this is intended behavior, or whether I'm doing something wrong. I have tried using dot notation on both scopes, and explicitly passing a new scope to $modal.open, but with no joy.
I can get around the problem (by creating a watchCollection on "people" and updating the table that way - which may be a better way of doing this overall) but wanted to validate whether others have seen this behavior also.

A: The issue you are experiencing is not related to the scope of the Modal Dialog.  The issue is related to the use of a function within an ng-repeat expression.  In general, using functions within expressions is a performance issue, but it's a much larger problem within an ng-repeat.  according to This excellent article regarding common pitfalls of using scopes,

When using expressions in views or watchers, you should always remember that an expression is called every time AngularJS thinks it is needed. You will not get the best performance using functions, you might even miss some change events.
That means an expression…

*

*within a ng-repeat will be called for each item separately. Additionally, this is used by the repeat directive to determine data changes.

*Can be evaluated multiple times in one digest. This can happen when you're using multiple directives or additional scope watchers.

*Can be evaluated even if the direct scope seems to be unchanged.

*Containing a function will not be evaluated if the return value of the function changes, but only if the function definition has changed.

Your example causes 3 of these 4 to occur.

*

*You repeat the function call for each object in your scope, 3 items = 3 calls to the function.

*You add an additional watcher indirectly by calling the Modal Dialog.

*Changes to the data in the Modal Dialog's scope causes evaluation of the scope of the controller containing the ng-repeat, even though the data within the ng-repeat didn't change (no way for it to know if the data changed until the $digest is called).  Each change to the Modal causes the $digest, which causes another trip through the ng-repeat, and another call for each item in the ng-repeat.

In your case, the logic does not need to run every time the expression will be evaluated. It is better to compute and write the logic into the scope when the logic result has changed. This decouples the logic from the object and the view.
in summary,

Best practices:

*

*DO NOT use functions in expressions.

*DO NOT use other data besides the scope in an expression.

*DO use $scope.$apply() when applying external data changes.

A: Simon,
I liked your question and I added watch on the scope and saw the digest cycle is getting called
$scope.$watch(function watchMe(scope) {  console.log('Digest watched me!'); });
The following is the fork with the digest.
http://plnkr.co/edit/5PTO1uPFvmLrg7K9vzTm?p=preview
I donot know this is the reason but I think  expressions inside the ng-repeat are calling the digest as it tries to evaluate expression on any event on that item.
I think we should evaluate expressions in the model and give the updated model to the ng-repeat to solve the issue.


text:
Q: Is there anything like Spring TestExecutionListener for TestSuite? Currently for tests I'm using TestExecutionListener and it works just perfect
public class ExecutionManager extends AbstractTestExecutionListener {

    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
        System.out.println("beforeClass");
    }

    @Override
    public void afterTestClass(TestContext testContext) throws Exception {
        System.out.println("afterClass");
    }
}

Test classes:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(ExecutionManager.class)
public final class TC_001 {

    @Test
    public void test() {
        System.out.println("Test_001");
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(ExecutionManager.class)
public final class TC_002 {

    @Test
    public void test() {
        System.out.println("Test_002");
    }
}

When I include those tests in test suite, beforeTestClass(TestContext testContext) and afterTestClass(TestContext testContext) methods are executed for each test class, what is quite logical:
@RunWith(Suite.class)
@Suite.SuiteClasses({
        TC_001.class,
        TC_002.class
})
public final class TS_001 {
}

Is there anything like SuiteExecutionListener (TestExecutionListener for suites)?
Basically I need non-static @BeforeClass and @AfterClass for suite
OR
In ExecutionListener I need to find out what class has been launched: case or suite. For this purpose I can:

*

*analyze StackTrace and get calling class

*use Reflection.getCallerClass(int i) (which is deprecated)

*pass caller class to ExecutionManager (By the way, how can I do that? Is it possible to put Object into TestContext like in Android Bundle?)

But I don't really like those solutions. SuiteExecutionListener is much more preferable
Thank you

A: No, there is unfortunately no such thing as a SuiteExecutionListener in the Spring TestContext Framework (TCF).
The TCF does not integrate with JUnit 4 at the suite level.
If you want to store something in the TestContext, that's not a problem. TestContext implements org.springframework.core.AttributeAccessor, so you can store attributes in the TestContext. Note, however, that the lifecycle of a given TestContext is tied to a test class.


text:
Q: Connection between EC2 instance & RDS in 2 different VPC We have a Amazon RDS database in a different VPC and our EC2 servers in a different VPC but in the same region i.e. us-east-1.
Our servers connect to the RDS via it's publicly accessible endpoint.
We are working on reducing our aws bills and we can see high data transfer cost.
Does connecting to RDS instance from an ec2 instance from a different VPC affect the data transfer cost as compared to connecting from the same VPC?
I couldn't find the answer from google or aws forums. Any information will be much appreciated.

A: AWS bandwidth is fairly expensive, and they charge whenever traffic leaves an available zone. The best way to have zero bandwidth bill is to have them in the same VPC and in the same availability zone. I suspect VPC peering will reduce the price compared with public endpoints, but I haven't checked that - someone will likely comment to let me know, and I'll edit this answer later.
The AWS Open Guide has a good diagram of AWS network pricing. Unfortunately I can't include the image here, I suspect it has hotlink protection enabled, so you will have to visit the site to view it.
Another approach is to use VPC sharing. You can read the blog post here, and the documentation here. Basically you can have a shared VPC across multiple accounts which can reduce or eliminate traffic costs.


text:
Q: Selecting unique column values and returning corresponding values in mysql table

SlNo
UserID
points

1
001
Three

2
002
Three

3
001
Three

I have the following table named 'userdata' and I would like to get the points of just the unique usernames.
SELECT points from userdata where USERID==distinct

Is there a functionality in mysql that works similar to ==     ?

A: Use Distinct
Query
Select distinct UserId, points
From userdata;

A: There are some possibilities
IN clause or a INNER JOIN
Latter will be faster on big tables

CREATE TABLE userdata (
  `SlNo` INTEGER,
  `UserID` INTEGER,
  `points` VARCHAR(5)
);

INSERT INTO userdata
  (`SlNo`, `UserID`, `points`)
VALUES
  ('1', '001', 'Three'),
  ('2', '002', 'Three'),
  ('3', '001', 'Thr');

SELECT `points` FROM userdata WHERE `UserID` IN (SELECT `UserID` FROM userdata GROUP BY `UserID` HAVING COUNT(*) = 1)

| points |
| :----- |
| Three  |

SELECT `points`
FROM userdata  u1 INNER JOIN (SELECT `UserID` FROM userdata GROUP BY `UserID` HAVING COUNT(*) = 1) u2  ON u1.`UserID` = u2.`UserID`

| points |
| :----- |
| Three  |

db<>fiddle here


text:
Q: full Screen mouse wheel scroll causes white I made a full screen website and it has a wrapper which holds the content in a 1170pixels block.
The wrapper is centered.
When i try to make a full screen background with width 100% it works fine when i use it on my desktops full size.
But if i re-size the screen and then use the horizontal scroll bar or the mouse wheel all the backgrounds don't show up only what was visible when i resized the page.
I have tried to put 100% width for the body but it is not working at all. Same is happening on both mobile and tablet devices.

A: width:100%;
Takes the width of the screen as it is when you open the site if you only want to make a background why not use this:
body{
    background-color: black;
}


text:
Q: Pandas how to shift na values to the right? I have a dataframe like
|x |y |z |
|na|na|1 |
|na|2 |1 |
|2 |3 |1 |
|na|na|1 |

and I want to shift the NA values so the NA elements will move to the last keeping the order of the non-na values columns like
|x |y |z |
|1 |na|na|
|2 |1 |na|
|2 |3 |1 |
|1 |na|na|

A: Let us try
df=df.replace('na',np.nan).transform(lambda x : sorted(x,key=pd.isnull),1)
   x    y    z
0  1  NaN  NaN
1  2    1  NaN
2  2    3    1
3  1  NaN  NaN


text: Q: Binding second type parameter through reflection Is there a way to create a generic type with unbound first parameter but with bound second parameter? More specifically, I need to call Queryable.Where<T>(IQueryable<T> source, Expression<Func<T, bool>> predicate) and don't know how to distinguish between overloads, one of which takes Expression<Func<T, int, bool>>


text:
Q: Cannot run PyQt program on another computer I started working on a Python 3.9 QT5 program about a year ago on Ubuntu 20.04 (Focal) and then let it slide. Today I tried to work with it on another computer, which runs Ubuntu 21.10 (Impish) and there seems to be an issue with PyQt somehow.
python src/main.py
QFactoryLoader::QFactoryLoader() checking directory path "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqeglfs.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqeglfs.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "eglfs"
        ]
    },
    "archreq": 0,
    "className": "QEglFSIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("eglfs")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqlinuxfb.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqlinuxfb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "linuxfb"
        ]
    },
    "archreq": 0,
    "className": "QLinuxFbIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("linuxfb")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqminimal.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqminimal.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "minimal"
        ]
    },
    "archreq": 0,
    "className": "QMinimalIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("minimal")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqminimalegl.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqminimalegl.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "minimalegl"
        ]
    },
    "archreq": 0,
    "className": "QMinimalEglIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("minimalegl")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqoffscreen.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqoffscreen.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "offscreen"
        ]
    },
    "archreq": 0,
    "className": "QOffscreenIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("offscreen")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqvnc.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqvnc.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "vnc"
        ]
    },
    "archreq": 0,
    "className": "QVncIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("vnc")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-egl.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-egl.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "wayland-egl"
        ]
    },
    "archreq": 0,
    "className": "QWaylandEglPlatformIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("wayland-egl")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-generic.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-generic.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "wayland"
        ]
    },
    "archreq": 0,
    "className": "QWaylandIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("wayland")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-xcomposite-egl.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-xcomposite-egl.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "wayland-xcomposite-egl"
        ]
    },
    "archreq": 0,
    "className": "QWaylandXCompositeEglPlatformIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("wayland-xcomposite-egl")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-xcomposite-glx.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwayland-xcomposite-glx.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "wayland-xcomposite-glx"
        ]
    },
    "archreq": 0,
    "className": "QWaylandXCompositeGlxPlatformIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("wayland-xcomposite-glx")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwebgl.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqwebgl.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "webgl"
        ]
    },
    "archreq": 0,
    "className": "QWebGLIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("webgl")
QFactoryLoader::QFactoryLoader() looking at "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so"
Found metadata in lib /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "xcb"
        ]
    },
    "archreq": 0,
    "className": "QXcbIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("xcb")
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/platforms" ...
Cannot load library /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so: (libxcb-xinerama.so.0: cannot open shared object file: No such file or directory)
QLibraryPrivate::loadPlugin failed on "/home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so" : "Cannot load library /home/mslinn/venv/default/lib/python3.9/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so: (libxcb-xinerama.so.0: cannot open shared object file: No such file or directory)"
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Aborted

I tried pip install PyQt5 but that made no difference. How can this problem be solved?

A: The following resolved the problem. There was need to diddle with any pip-related stuff:
$ sudo apt install qt5dxcb-plugin


text:
Q: coffeescript loop through associative array magnitudeArray = []
for index, dataPoint of chartData
     magnitudeArray.push dataPoint.magnitude if dataPoint.magnitude?

The above code works, but for coffeescript its ugly and un-coffeescripty. First of all, the index var is completely un-used, its just there so I can access the dataPoint var as the result fo the associative array and not the index. Also its three lines! With coffeescript loops arrays are supposed to be writable with one line, off of a loop.
I imagine something like this is possible:
magnitudeArray = for dataPoint of chartData when dataPoint.magnitude?

Do you know of the cleaner coffeescriptier way of doing this?

A: Yes, you should be able to use an array comprehension in this case, though you will need to use a variable for the keys of chartData, which i assume is an object. You can use _ to denote an unused variable (though i don't know if this is common practice in CoffeeScript):
magnitudes = (point.magnitude for _, point of chartData when point.magnitude?)

Example at coffeescript.org.

A: You can use 'deconstructing assignment' to compact it down a bit more
magnitudes = (magnitude for i, {magnitude} of chartData when magnitude?)

or even
magnitudes = (m for i, {magnitude: m} of chartData when m?)


text:
Q: How to fix cannot access video stream (NotAllowedError) in flutter webview to use html5+webRTC camera api? I am using instascan.min js library to scan QR Codes in my web angular js application. but in my flutter web view, I got an error - Cannot access video stream (NotAllowedError), And I am unable to fix it. I don't have too much knowledge of flutter.
I have tried to give permission to camera access but it's not working.
//# My Flutter Code
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

void main () => runApp(MyApp());
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
  title: 'FOTOFACE WALLET',
  debugShowCheckedModeBanner: false,
  home: Home(),
);
}
}

class Home extends StatefulWidget{
@override
 _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home>{
@override
Widget build(BuildContext context) {
 return WebviewScaffold(
  appBar: PreferredSize(
      preferredSize: Size.fromHeight(0),
      child: AppBar(
        automaticallyImplyLeading: true, // hides leading widget
        backgroundColor: new Color(0xFF404E67),
      )
  ),

  url: "https://fotofacewallet.com",
  initialChild: Center(
    child: CircularProgressIndicator(),
  ),
);
}
}

//# this is my scanner code in angular js controller
$scope.scan = () => {
var overlay = $('.overlay'),
close = $('
close
');
overlay.append(close);
let scanner = new Instascan.Scanner({
   video: document.getElementById('preview')
});

scanner.addListener('scan', function (content) {
scanner.stop();
$('.overlay').fadeOut();
$('.overlay').hide();
$scope.scanpayProcess(content);
});
Instascan.Camera.getCameras().then(function (cameras) {

if (cameras.length > 0) {
    if(cameras[1]){
        scanner.start(cameras[1]);
    } else {
        scanner.start(cameras[0]);
    }
} else {
  alert('No cameras found.');
}

}).catch(function (e) {
alert(e);
});
$('.overlay').show();
}

I am expecting a camera view in a flutter web view.

A: I have done something like this
on my index.html page or the file that you have created in your angular side
I have added one button :
<button type="button" onclick="displayMsg()" class="btn btn-default btn-login">Scan</button>

and handled its click event as below and we will post message as 'scan'

added this package in my pubspec.yaml file

flutter_barcode_scanner: ^0.1.5+1

do run flutter pub get to update dependencies
then on my main.dart file
I have imported
import 'dart:async';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';

in main.dart file added below code to handle the event triggered on displayMsg() function - 'scan' message
  final Set<JavascriptChannel> jsChannels = [
      JavascriptChannel(
          name: 'Print',
          onMessageReceived: (JavascriptMessage message) {
            if(message.message == 'scan'){

              print(message.message);
              sBarcode(MyApp());
            }
          }),
    ].toSet();

  sBarcode(someVal) async {
 String bCode = await FlutterBarcodeScanner.scanBarcode("#ff6666", "Cancel", true);   print(bCode);
   someVal.enterBarcode(bCode); // to get the scanned barcode
return; }

enterBarcode(barc) {
    flutterWebViewPlugin.evalJavascript("document.getElementById('yourtextboxid').value="
+ barc);   }

This is how my complete main.dart file looks now
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

const kAndroidUserAgent =
    'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36';

String selectedUrl = 'add_your_url_here';

// ignore: prefer_collection_literals
final Set<JavascriptChannel> jsChannels = [
  JavascriptChannel(
      name: 'Print',
      onMessageReceived: (JavascriptMessage message) {
        if(message.message == 'scan'){
          //MyApp.startBarcode();
          print(message.message);
          sBarcode(MyApp());
        }
      }),
].toSet();

sBarcode(someVal) async {
  String bCode = await FlutterBarcodeScanner.scanBarcode("#ff6666", "Cancel", true);
  print(bCode);
  someVal.enterBarcode(bCode);
  return;
}
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final flutterWebViewPlugin = FlutterWebviewPlugin();

  enterBarcode(barc) {
    flutterWebViewPlugin.evalJavascript("document.getElementById('barcodenumber').value=" + barc);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter WebView Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
       // '/': (_) => const MyHomePage(title: 'Flutter WebView Demo'),
        '/': (_) {
          return WebviewScaffold(
            url: selectedUrl,
            javascriptChannels: jsChannels,
            withZoom: true,
            withLocalStorage: true,
            withJavascript: true,
            hidden: true,
            initialChild: Container(
              color: Colors.white,
              child: const Center(
                child: Text('Loading...'),
              ),
            ),
          );
        },
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // Instance of WebView plugin
  final flutterWebViewPlugin = FlutterWebviewPlugin();

  // On destroy stream
  StreamSubscription _onDestroy;

  // On urlChanged stream
  StreamSubscription<String> _onUrlChanged;

  // On urlChanged stream
  StreamSubscription<WebViewStateChanged> _onStateChanged;

  StreamSubscription<WebViewHttpError> _onHttpError;

  StreamSubscription<double> _onProgressChanged;

  StreamSubscription<double> _onScrollYChanged;

  StreamSubscription<double> _onScrollXChanged;

  final _urlCtrl = TextEditingController(text: selectedUrl);

  final _codeCtrl = TextEditingController(text: 'window.navigator.userAgent');

  final _scaffoldKey = GlobalKey<ScaffoldState>();

  final _history = [];

  @override
  void initState() {
    super.initState();

    flutterWebViewPlugin.close();

    _urlCtrl.addListener(() {
      selectedUrl = _urlCtrl.text;
    });

    // Add a listener to on destroy WebView, so you can make came actions.
    _onDestroy = flutterWebViewPlugin.onDestroy.listen((_) {
      if (mounted) {
        // Actions like show a info toast.
        _scaffoldKey.currentState.showSnackBar(
            const SnackBar(content: const Text('Webview Destroyed')));
      }
    });

    // Add a listener to on url changed
    _onUrlChanged = flutterWebViewPlugin.onUrlChanged.listen((String url) {
      if (mounted) {
        setState(() {
          _history.add('onUrlChanged: $url');
        });
      }
    });

    _onProgressChanged =
        flutterWebViewPlugin.onProgressChanged.listen((double progress) {
      if (mounted) {
        setState(() {
          _history.add('onProgressChanged: $progress');
        });
      }
    });

    _onScrollYChanged =
        flutterWebViewPlugin.onScrollYChanged.listen((double y) {
      if (mounted) {
        setState(() {
          _history.add('Scroll in Y Direction: $y');
        });
      }
    });

    _onScrollXChanged =
        flutterWebViewPlugin.onScrollXChanged.listen((double x) {
      if (mounted) {
        setState(() {
          _history.add('Scroll in X Direction: $x');
        });
      }
    });

    _onStateChanged =
        flutterWebViewPlugin.onStateChanged.listen((WebViewStateChanged state) {
          print(state.type);
      if (mounted) {
        setState(() {
          _history.add('onStateChanged: ${state.type} ${state.url}');
        });
      }
    });

    _onHttpError =
        flutterWebViewPlugin.onHttpError.listen((WebViewHttpError error) {
      if (mounted) {
        setState(() {
          _history.add('onHttpError: ${error.code} ${error.url}');
        });
      }
    });
  }

  @override
  void dispose() {
    // Every listener should be canceled, the same should be done with this stream.
    _onDestroy.cancel();
    _onUrlChanged.cancel();
    _onStateChanged.cancel();
    _onHttpError.cancel();
    _onProgressChanged.cancel();
    _onScrollXChanged.cancel();
    _onScrollYChanged.cancel();

    flutterWebViewPlugin.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.all(24.0),
              child: TextField(controller: _urlCtrl),
            ),
            RaisedButton(
              onPressed: () {
                flutterWebViewPlugin.launch(
                  selectedUrl,
                  rect: Rect.fromLTWH(
                      0.0, 0.0, MediaQuery.of(context).size.width, 300.0),
                  userAgent: kAndroidUserAgent,
                  invalidUrlRegex:
                      r'^(https).+(twitter)', // prevent redirecting to twitter when user click on its icon in flutter website
                );
              },
              child: const Text('Open Webview (rect)'),
            ),
            RaisedButton(
              onPressed: () {
                flutterWebViewPlugin.launch(selectedUrl, hidden: true);
              },
              child: const Text('Open "hidden" Webview'),
            ),
            RaisedButton(
              onPressed: () {
                flutterWebViewPlugin.launch(selectedUrl);
              },
              child: const Text('Open Fullscreen Webview'),
            ),
            RaisedButton(
              onPressed: () {
                Navigator.of(context).pushNamed('/widget');
              },
              child: const Text('Open widget webview'),
            ),
            Container(
              padding: const EdgeInsets.all(24.0),
              child: TextField(controller: _codeCtrl),
            ),
            RaisedButton(
              onPressed: () {
                final future =
                    flutterWebViewPlugin.evalJavascript(_codeCtrl.text);
                future.then((String result) {
                  setState(() {
                    _history.add('eval: $result');
                  });
                });
              },
              child: const Text('Eval some javascript'),
            ),
            RaisedButton(
              onPressed: () {
                setState(() {
                  _history.clear();
                });
                flutterWebViewPlugin.close();
              },
              child: const Text('Close'),
            ),
            RaisedButton(
              onPressed: () {
                flutterWebViewPlugin.getCookies().then((m) {
                  setState(() {
                    _history.add('cookies: $m');
                  });
                });
              },
              child: const Text('Cookies'),
            ),
            Text(_history.join('\n'))
          ],
        ),
      ),
    );
  }
}

check and test and let me know if that works for you or not, This is working fine at my end.
Print will generate error in browser you need to test this in android or ios.
Hope this helps.

A: You get the Cannot access video stream (NotAllowedError) error because you need to grant the right permissions to the webview.
For Android, in the AndroidManifest.xml, you need to add these permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.VIDEO_CAPTURE" />
<uses-permission android:name="android.permission.AUDIO_CAPTURE" />

But this is not enough! To request permissions about the camera and microphone, you can use the permission_handler plugin.
So, for the webview, you can use my plugin flutter_inappwebview and use the androidOnPermissionRequest event for Android, that is an event fired when the WebView is requesting permission to access the specified resources (that is the Android native WebChromeClient.onPermissionRequest event).
An example of using WebRTC that works on Android:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:permission_handler/permission_handler.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Permission.camera.request();
  await Permission.microphone.request();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: InAppWebViewPage()
    );
  }
}

class InAppWebViewPage extends StatefulWidget {
  @override
  _InAppWebViewPageState createState() => new _InAppWebViewPageState();
}

class _InAppWebViewPageState extends State<InAppWebViewPage> {
  InAppWebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text("InAppWebView")
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                child: Container(
                  child: InAppWebView(
                      initialUrl: "https://appr.tc/r/158489234",
                      initialOptions: InAppWebViewGroupOptions(
                        crossPlatform: InAppWebViewOptions(
                          mediaPlaybackRequiresUserGesture: false,
                          debuggingEnabled: true,
                        ),
                      ),
                      onWebViewCreated: (InAppWebViewController controller) {
                        _webViewController = controller;
                      },
                      androidOnPermissionRequest: (InAppWebViewController controller, String origin, List<String> resources) async {
                        return PermissionRequestResponse(resources: resources, action: PermissionRequestResponseAction.GRANT);
                      }
                  ),
                ),
              ),
            ]))
    );
  }
}

This example uses the room 158489234 on https://appr.tc/, that is a video chat demo app based on WebRTC (https://github.com/webrtc/apprtc).
To get it work, you need to set the option mediaPlaybackRequiresUserGesture to false and implement (for Android) the onPermissionRequest event.


text:
Q: Installing TortoiseSVN and TortoiseGit together I have TortoiseSVN installed and it works great. Would like to have an equally great interface to things hosted on Git.

*

*Is TortoiseGit as good as TortoiseSVN?

*

*Can they both be installed without much trouble? Will menus be duplicated? Will stuff be weird? Any experiences with this?

I'm running Windows 7 64-bit, if that makes any difference.

A: I'm running windows 7 32bit. I had tortoisesvn for a long time now, and I added tortoise git about a week ago...
So far the only bad thing I noticed is that, sometimes, if I try to open a folder that is svn'ed it takes a few seconds more, but that's it :-)

A: *

*TortoiseGit has been rewritten in the same style as TortoiseSVN, it looks like some additions and some changes from the outside. It depends more on asking the question if Git is as goot as SVN. Seems they finished porting TortoiseGit, when I last tried it it was around 60% ported.

*I know that each thing that will be inserted in the system contains the word SVN, so with TortoiseGit that would be Git. They can be used next to each other, although you should watch out with the overlay icons. Just don't mix them up by using them in the same directory...
Just go and try it, nothing can go wrong. :-)


text:
Q: Java return a value from a method - beginner I am really a beginner in Java and I would be grateful if someone could explaine me how can I get a return from my method in order to use it in another class from where I actually call the following one. My code is:
private static String[] months(int val){

    String[] monthsNames = { "January", "February", "March", "April",
            "May", "June", "July", "August", "September", "October",
            "November", "December"};

                   return monthsNames[val];
}

edit: I did
public static String months(int val){

    String[] monthsNames = { "January", "February", "March", "April",
            "May", "June", "July", "August", "September", "October",
            "November", "December"};

                   return monthsNames[val];
}

and what I get from eclipse is that monthsNames cannot be resolved to a variable
edit2**
now it works. Thanks everybody for your help!

A: You are returning one String, not a String[]. Change
private static String[] months(int val){

to
private static String months(int val){

But, if you want to call it from another class you will need to change private to public (or if the other class is in the same package, you could remove private and then you would have package-private level permission). Finally, if the other class is a sub-class, you might change private to protected (and then it is only visible to sub-classes).

A: Making the method private restricts the visibility to the class in which the method is declared.  If you want to use this method in another class you should make it more visible, for example by declaring it public.
Secondly your method is currently returning an array of String (String[]).  If you want to return a String you should use public static String months(int val) instead of public static String[] months(int val)
If the method returned the monthsNames variable, String[] would be correct, however the elements of monthsNames are just String.
public static String months(int val) {
    String[] monthsNames = { "January", "February", "March", "April",
            "May", "June", "July", "August", "September", "October",
            "November", "December"};
    return monthsNames[val];
}

A: Change the return type, you want to return the string when given the index...
private static String months(int val){..

A: If you want to return months Name from monthsNames just change the return type and access modifier.
private static String[] months(int val);

to
public static String months(int val);


text:
Q: How do I create an infinite scroll section in vuejs? I'm trying to create a infinite horizontal scroll section in vuejs for a few products but I'm struggling to get the infinite effect. I've tried removing the card that goes out of view and adding it on as the last card but that causes a weird snapping effect instead of a smooth scroll.
Here is a CodePen with the smooth scroll using scrollTo and setting the behaviour to smooth.
Is there a better alternative than just removing and adding a card to the end?

A: You can use scroll detection to determine if the scroll reach to end and add more items;
Here is an example of how to achieve that!
Html:
<div :style="height:350px ';overflow-y: auto;overflow-x: hidden;'" @scroll="onScroll">
HTML CODE HERE
</div>

We set the style to have a fixed height in this case the example works for vertical infinite scroll. But you can adapt to use for horizontal.
We use the @scroll to detect when a scroll is executed and call the onScroll(e) function
Javascript
onScroll(e){
  if((e.target.offsetHeight + e.target.scrollTop) >= e.target.scrollHeight) {
    // Insert your logic here! Request api for example and add to the list of items
  }
},

This function compares if the scroll reaches the end and execute the code.
Extra:
You can add a transition group to your HTML to give the effect of items being added.
If your items are static and they are hardcoded they are other approaches, let me know if this is the case


text:
Q: Jqgrid file upload path I am using the code like this for file  upload. After click the edit button the event fire into ashx page. And also read the value from form.get method. But i can't able to get the path of the file upload. Please help me to get this.
jQuery("#grid").jqGrid({
    url:'handler.ashx',
    datatype: 'json',
    mtype: 'GET',
    colNames:['Seriel Number', 'Script Name', 'Script Location','Host Url','Protocol','Rampup Time','No of Users','Loop','Delay'],
    colModel:[
        {name:'sr_no',index:'sr_no', width:55,editable:false,editoptions:{readonly:true,size:10},hidden:true},
        {name:'script_name',index:'script_name', width:100,editable:true, editrules:{required:false}, editoptions:{size:10, maxlength: 15}},
        {name:'script_loc',index:'script_loc', width:100,editable:true, editrules:{required:false},edittype: 'file', editoptions:{enctype: "multipart/form-data"}},
        {name:'host_url',index:'host_url', width:100,editable:true, editrules:{required:true}, editoptions:{ size:10, maxlength: 25}},
        {name:'protocol',index:'protocol', width:100,editable:true, editrules:{required:true}, editoptions:{size:10, maxlength: 10}},
        {name:'rampup_time',index:'rampup_time', width:100,editable:true, editrules:{required:true}, editoptions:{defaultValue: '0',size:2, maxlength: 4}},
        {name:'noof_users',index:'noof_users', width:100,editable:true, editrules:{required:false}, editoptions:{size:4, maxlength: 8}},
        {name:'loops',index:'loops', width:100,editable:true, editrules:{required:true}, editoptions:{defaultValue: '1'  ,size:1, maxlength: 2}},
        {name:'delay',index:'delay', width:100,editable:true, editrules:{required:true}, editoptions:{defaultValue: '0',size:1, maxlength: 4}}
    ],
    postData: {
    },
    rowNum:20,
    rowList:[20,40,60],
    height: 200,
    autowidth: true,
    rownumbers: true,
    pager: '#pager',
    sortname: 'sr_no',
    viewrecords: true,
    sortorder: "asc",
    caption:"Users",
    emptyrecords: "Empty records",
    loadonce: false,
    loadComplete: function() {
    },
})

A: Here is how i have used jqgrid in my code. use this code as reference.I dont say this is exact colution but it may be of use for you.
In my jqgrid script i have specified url with param  as url:'controller.aspx?p=load'
    jQuery("#jQGridDemo").jqGrid({
     url: 'controller.aspx?p=load',
     datatype: 'json',
     mtype: 'POST',
     colNames: ['Job Order #', 'Part #', 'Operation #' ...],
     colModel: [...]
     ....
     ....
    });

In my controller.aspx page:
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.AddHeader("Content-type", "text/javascript");

     if (Request.Params["p"].Equals("load"))
     {
        bool success = true;
        OrderEntity[] arrReturn = Order.getOrderArray(0, -1);
        int arry_size = arrReturn.Length;

        string data = JsonConvert.SerializeObject(arrReturn);
        string ret = "{data:" + data + ",\n";
        ret += "recordType : 'object'}";
        if (data == null)
        {
            success = false;
            Response.Write("0");
        }
        if (success == true)
        {
            Response.Write(data);
        }
       }
      }

refer this code in question on jqgrid-handler example handler with jqgrid


text:
Q: How do I find the position of a word in a list using a function? I know this question was asked many times on here, but could not find an adequate answer.
I need to find the position of the words in a list, when I run my code it gives me None
Here is the code:
words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']

def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value in words == type_word:
            return idx

positions = get_position(words, 'Apple')
print(positions)

Preferred Output:
[2, 3, 8]

A: if you use return then function will return the value you want to give back. same is happening here in your code, it is returning the first matched value and not checking further.
either use yield or a temporay list where you saved match result and then return back
def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value == type_word:
            yield idx

or
def get_position(words, type_word):
    matched = []
    for idx, value in enumerate(words):
        if value == type_word:
            matched.append(idx)
    return matched

A: You have to declare an empty list and append the index to the list when you find a match.
Then after the loop, you have to return the list.
The code will be something like this:
words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']

def get_position(words, type_word):
    ret = []
    for idx, value in enumerate(words):
        if value in words == type_word:
            ret.append(idx)
    return ret

positions = get_position(words, 'Apple')
print(positions)

A: outlist = []
def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value == type_word:
            outlist.append(idx)
    return outlist

A: You can use list comprehension.
Use:
def get_position(words, type_word):
    return [idx for idx, w in enumerate(words) if w == type_word]

Output:
>>> get_position(words, "Apple")
[2, 3, 8]

A: Here is another way of solving this issue:
words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']

def get_indexes(lst_from):
    lst = []
    for i in range(len(lst_from)):
        index = lst_from[i:].index('Apple') + i
        if index not in lst:
            lst.append(index)

    return lst


text:
Q: Android Java Apache FTP: 425 Unable to build data connection: Connection timed out I have an Android application which needs to do some FTP tasks at particular points of the operation:

*

*Upload a list of files from phone folder to FTP host

*Get list of files in FTP host folder

*Download selected files from FTP to phone, erasing a file from FTP host after download

It is code and working nicely under FTP, but when I go to FTPS (DDL/TLS), it all goes wrong, with the above message.
Download:

2020-08-20 20:45:45.556 17674-18751/com.centralock.android.app.centralock I/System.out: PORT 10,1,10,46,165,169

2020-08-20 20:45:45.716 17674-18751/com.centralock.android.app.centralock I/System.out: 200 PORT command successful

2020-08-20 20:45:45.732 17674-18751/com.centralock.android.app.centralock I/System.out: STOR Folder1/Folder2/File1.txt

2020-08-20 20:47:53.207 17674-18751/com.centralock.android.app.centralock I/System.out: 425 Unable to build data connection: Connection timed out

The attempt to list files does the same thing.
I found some code I thought might help: SSLSessionReuseFTPSClient / prepareDataSocket, but I don't think I installed it properly: I just included the code in my FTP management class file
.

A:
... I/System.out: PORT 10,1,10,46,165,169

The PORT command indicates that you are using active mode in FTP. In active mode the server creates a connection to the client to transfer the data. This mode is known to cause massive problems if there is a firewall in the way or some NAT or Carrier Grade NAT done, i.e. typical access from home network to the internet or from mobile networks.
The infrastructure (firewall, NAT) might try to add the necessary firewall and translation rules for the connection from server to client, but for this visibility to the PORT commands is needed. With FTPS the control connection is encrypted though and thus visibility is not possible.  That's why it fails with FTPS but not with FTP.
The best way is to not use FTP and FTPS in the first place since these protocols are known to cause troubles. Use HTTP or SFTP (file transfer over SSH) instead if the server supports this. If this is not possible use FTP in passive mode, where the client will create connections to the server and not the other way. Using enterLocalPassiveMode seems to be the way to do this, see also Apache Commons Net FTPClient and listFiles().

A: We were playing with active vs. passive. You are right, passive was correct.
As it turns out, the day after posting this, our NAS manufacturer issued a code update, and everything just started working. So feel free to ignore this request for help!


text:
Q: retaining entered variable names inside a custom function in r I am trying to figure out how to retain variable names that are entered as arguments in a custom function. I want to allow users to enter the arguments to the function in two different ways (data = df, x = x, y = y) or (data = NULL, x = df$x, y = df$y) and trying to prepare labels in either case.
# libraries needed
library(dplyr)
library(rlang)
library(datasets)

# defining the custom function
# allow two ways to enter the arguments to the function-
# (data = df, x = x, y = y) or (data = NULL, x = df$x, y = df$y)

prac.fn <- function(data = NULL, x, y) {
  #===================== creating labels out of entered variables ===============
  if (!is.null(data)) {
    # if dataframe is provided
    lab.df <- colnames(dplyr::select(.data = data,
                                     !!rlang::enquo(x),
                                     !!rlang::enquo(y)))
    xlab <- lab.df[1]
    ylab <- lab.df[2]
  } else {
    # if vectors were provided
    # split the name of the entered variable by `$` sign and
    # select the second part of the split string
    xlab <- strsplit(quote(x), "$", fixed = TRUE)[[1]][[2]]
    ylab <- strsplit(quote(y), "$", fixed = TRUE)[[1]][[2]]
  }
  print(xlab)
  print(ylab)
}

# checking if the code works
# using the `data` argument (this works!)
prac.fn(data = iris, x = Species, y = Sepal.Length)
#> [1] "Species"
#> [1] "Sepal.Length"

# without using the `data` argument (this doesn't work)
prac.fn(x = iris$Species, y = iris$Sepal.Length)
#> Error in strsplit(quote(x), "$", fixed = TRUE): non-character argument

# desired output
# xlab should be assigned the character 'Species'
# xlab should be assigned the character 'Sepal.Length'

Created on 2018-02-19 by the reprex package (v0.2.0).

A: EDIT
What you are looking for is deparse(substitute(x)), here is how your function can be written:
prac.fn <- function(data = NULL, x, y, xlab=deparse(substitute(x)), ylab=deparse(substitute(y))) {

  if (!is.null(data)) {
    # if dataframe was provided
    df <- data.frame(x=data[,xlab], y=data[,ylab])

  } else {
    # if vectors were provided
    df <- data.frame(x = x, y = y)
    xlab <- gsub(".*\\$", "", xlab)
    ylab <- gsub(".*\\$", "", ylab)
  }
  print(df)
  print(xlab)
  print(ylab)
}

Then, both prac.fn(x = iris[1:5,]$Species, y = iris[1:5,]$Sepal.Length)
and prac.fn(data = iris[1:5,], x = Species, y = Sepal.Length) give:
       x   y
1 setosa 5.1
2 setosa 4.9
3 setosa 4.7
4 setosa 4.6
5 setosa 5.0
[1] "Species"
[1] "Sepal.Length"

OLD ANSWER
I am not sure to have correctly understood your question, but here is a very simplified version of your code that might help you:
prac.fn <- function(data = NULL, xlab="x", ylab="y") {

  df <- data[, c(xlab, ylab)]
  colnames(df) <- c("x", "y")

  print(df)
  print(xlab)
  print(ylab)
}

prac.fn(data = iris[1:5,], xlab = "Species", ylab = "Sepal.Length")


text:
Q: How to show translation text in angularjs controller alert from json file? I have a JSON file with translations, like this one:
"ALERT_MESSAGE" : "Select a row"

Now, I want to show an alert from my controller when the user try to access to a link without select a row.
$scope.goToNext = function () {
    if($scope.isSelected === false){
        alert("What should I put here?");
    }
    else{
        Navigator.goTo("/next", {
            back: "/previus",
            asd: $scope.asd
        });
    }
};

How can I use my translations file on the controller?

A: Another possibility is using the $translate service itself (if you are using angular-translate ;))
alert($translate.instant('ALERT_MSG'));

A: Finally adding $filter to the controller and using it like here:
alert($filter('translate')('ALERT_MSG'));

A: Following function will show the changed language:
 $scope.translateLangText=function(text){
             $scope.$watch(
                    function() { return $filter('translate')(text); },
                     function(newval) { alert(newval); }
                 );
             }

$scope.translateLangText('Hello');


text:
Q: How can I extract images and their metadata from PDFs? Is it possible to use Java to extract images from a PDF file and export them to a specific folder without losing their original creation and modification dates? I tried to achieve this goal by using IText and PDFBox but had no success. Any ideas or examples are welcome.

A: Images do not contain metadata and are stored as raw data which needs to be assemebled into images. I wrote 2 blog posts explaining how image data is stored in a PDF file at  https://blog.idrsolutions.com/2010/04/understanding-the-pdf-file-format-how-are-images-stored/ and https://blog.idrsolutions.com/2010/09/understanding-the-pdf-file-format-images/

A: I don't agree to the others and have a POC for your question: You can extract the XMP Metadata of images using pdfbox in the following way:

public void getXMPInformation() {
    // Open PDF document
    PDDocument document = null;
    try {
        document = PDDocument.load(PATH_TO_YOUR_DOCUMENT);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Get all pages and loop through them
    List pages = document.getDocumentCatalog().getAllPages();
    Iterator iter = pages.iterator();
    while( iter.hasNext() ) {
        PDPage page = (PDPage)iter.next();
        PDResources resources = page.getResources();
        Map images = null;
        // Get all Images on page
        try {
            images = resources.getImages();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if( images != null ) {
            // Check all images for metadata
            Iterator imageIter = images.keySet().iterator();
            while( imageIter.hasNext() ) {
                String key = (String)imageIter.next();
                PDXObjectImage image = (PDXObjectImage)images.get( key );
                PDMetadata metadata = image.getMetadata();
                System.out.println("Found a image: Analyzing for Metadata");
                if (metadata == null) {
                    System.out.println("No Metadata found for this image.");
                } else {
                    InputStream xmlInputStream = null;
                    try {
                        xmlInputStream = metadata.createInputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        System.out.println("--------------------------------------------------------------------------------");
                        String mystring = convertStreamToString(xmlInputStream);
                        System.out.println(mystring);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // Export the images
                String name = getUniqueFileName( key, image.getSuffix() );
                    System.out.println( "Writing image:" + name );
                    try {
                        image.write2file( name );
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                }
                System.out.println("--------------------------------------------------------------------------------");
            }
        }
    }
}

And the "Helper methods":
public String convertStreamToString(InputStream is) throws IOException {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            is.close();
        }
        return sb.toString();
    } else {
        return "";
    }
}

private String getUniqueFileName( String prefix, String suffix ) {
    /*
    * imagecounter is a global variable that counts from 0 to the number of
    * extracted images
    */
    String uniqueName = null;
    File f = null;
    while( f == null || f.exists() ) {
        uniqueName = prefix + "-" + imageCounter;
        f = new File( uniqueName + "." + suffix );
    }
    imageCounter++;
    return uniqueName;
}

Note: This is a quick and dirty proof of concept and not a well-styled code.
The Images must have XMP-Metadata when placed in InDesign before building the PDF document. The XMP-Metdadata can be set by using Photoshop for example. Please be aware, that p.e. not all IPTC/Exif/... Information is converted into the XMP-Metadata. Only a small number of fields are converted.
I'm using this method on JPG and PNG images, placed in PDFs build with InDesign. It works well and I can get all image-informations after the production-steps from the ready PDFs (picture coating).

A: Short Answer
Maybe, but probably not.
Long Answer
PDF natively supports JPEG, JPEG2000 (which is growing more common), CITT (fax) 3 & 4, and JBIG2 (really rare).  Images in these formats can be copied byte-for-byte into the PDF, preserving any metadata WITHIN THE FILE.  Creation/change dates are generally part of the file system, not the image.
JPEG: doesn't look like it supports internal metadata.
JPEG2000: Yep.  Lots of stuff in there potentially
CITT: doesn't look that way.
JBIG2: Err.. I think so, but it's none to clear from the specs I've just skimmed.
All other image formats must be turned into pixels and then compressed In Some Way (often with Flate/ZIP).  These conversions could keep the metadata as part of the PDF's xml metadata or the image's dictionary, but I've never even heard of that happening.  It just gets pitched.

A: The original creation and modification dates are generally not saved when the image is embedded into the PDF. Just the raw pixel data is compressed and saved. However, according to Wikipedia:

Raster images in PDF (called Image XObjects) are represented by dictionaries with an associated stream.

The dictionary contains meta data, amongst which you might find the dates.

A: Get the Meta Data From PDF file Using SonwTide API . Use PDFTextStream.jar At the end it will return all the PDF Properties and print on command line.
public static void getPDFMetaData(String pdfFilePath) throws IOException{

            // input pdf file with location Add PDFTextStream.jar from snowtide web site to your code build path
            PDFTextStream stream = new PDFTextStream(pdfFilePath);

            // get collection of all document attribute names
            Set attributeKeys = stream.getAttributeKeys();

            // print the values of all document attributes to System.out
            Iterator iter = attributeKeys.iterator();
            String attrKey;
            while (iter.hasNext()) {
                attrKey = (String)iter.next();
                System.out.println(attrKey + " = " + stream.getAttribute(attrKey));

            }

}