text:
Q: Log in to my web from a chrome extension I've got a web where logged in users can fill out a form to send information. I wanted my users to do this from a chrome extension too. I managed to get the form to sen information working but I only want to be logged in users to be able to do that. It's like a twitter or Springpad extension when the user first opens up the extension, it would have to log in or register. I saw the following answer at stack overflow: Login to website with chrome extension and get data from it
I gave it a try and put this code in background.html:
function login() {
    $.ajax({
        url: "http://localhost/login", type: "GET", dataType: "html", success: function() {
            $.ajax({
                url: "http://localhost/login", type: "POST", data: {
                    "email": "me@alberto-elias.com",
                    "password": "mypassword",
                },
            dataType: "html",
            success: function(data) {
               //now you can parse your report screen
            }
            });
        }
    });
}

In my popup.html I put the following code:
var bkg = chrome.extension.getBackgroundPage()
$(document).ready(function() {
    $('#pageGaffe').val(bkg.getBgText());
    bkg.login();
});

And on my server, which is in node.js, I've got a console.log that shows user information when he logs in, so I saw that when I load my extension, it does log in. The problem is how can I get the user to log in by itself, instead of manually putting my details in the code, how to stay logged in in the extension and when submitting the form, sending the user's details to the web.
I hope I've managed to explain myself correctly.
Thanks.

A: Before answering this question I would like to bring to your notice that you can make cross origin xhr from your content scripts as of Chrome 13 if you have declared proper permissions. Here is the extract from the page

Version note: As of Chrome 13, content scripts can make cross-origin requests to the same servers as the rest of the extension. Before Chrome 13, a content script couldn't directly make requests; instead, it had to send a message to its parent extension asking the extension to make a cross-origin request.

Coming to the point. You simply have to make an XmlHttpRequest to your domain from your extension (content script or background page) and wait for the response.
At Server
Read the request and session cookie. If session is valid send proper response, else send an error code. 401 or anything else.
At client
If response is proper display it, else display a login link directing to login page of your website.
How it works:
It will work if cookies in user's browser is enabled. Whenever user logs in to your website your server sets a session cookie which resides in user's browser. Now with every request that the browser sends to your domain, this cookie is transmitted. This cookie will be transmitted even if the request is from a Google Chrome Extension.
Caveat
Make sure you display proper cues to user indicating that they are logged in to your application. Since your UI will be mostly inside the extension, it is possible that user might not be aware of their valid session with your website and they might leave an active session unattended which might be abused if user is accessing it from a public internet kiosk.
Reference
You can take a look at a similar implementation that I have done with my extension here.

A: So the user logs into your server and you know that. I am a bit confused if you then want the user to be able to browse your website with those credentials or a third party website with those credentials.
If it is your website then you should be able to set a cookie that indicates whether they are logged in. Then detect this server side when they navigate your site.
If it is a third party site then the best you can do is create a content script that either fills out the login form and autosubmits for them or analyze the login post data and send it along yourself, then force a refresh.


text:
Q: UICollection view didSelectItemAtIndexPath not working well I have made simple collectionview in uiviewcontroller but didSelectItemAtIndexPath not always reacts to touch of cells. DataSource and Delegates are connected on storyboard. For example if i touch all my cells it doesnt return all of them, 2 or 3 of cells even are not clickable .
Below is my code
//TestCollectionView.h
    #import <UIKit/UIKit.h>

    @interface TestCollectionView : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>

    @property (strong, nonatomic) IBOutlet UICollectionView *myCollection;

    @end

TestCollectionView.m
#import "TestCollectionView.h"
#import "TestCell.h"

@interface TestCollectionView ()

@end

@implementation TestCollectionView

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
      TestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"testCell" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor redColor];

    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 20;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    NSLog(@"slected index is %ld",(long)indexPath.row);

}

@end

redpajama_set_name: RedPajamaStackExchange


text:
Q: import by module.exports from external file in NodeJS? I am trying to import a function from another file. I tried by doing this:
main.js:
const oauth2 = require('./utils/oauth2');
function startOAuth() {
  var token = oauth2.OAuth2.getToken();
}

utils/oauth2.js:
module.exports =  (function() {

    window.OAuth2 = {

        /**
         * Initialize
         */
        init: function() {
            this._key = "token";
        },
        /**
         * Get Token
         *
         * @return OAuth2 access token if it exists, null if not.
         */
         getToken: function() {
            try {
                return window['localStorage'][this._key];
            }
            catch(error) {
                return null;
            }
         }
       };

    OAuth2.init();
})();

I get the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'getToken')

What did I do wrong? Why does NodeJS not find the getToken() function?
Thank you very much for your help!
PS: I know here is the wrong place to say I am a beginner but I am one ;)

A: You're exporting a result of calling a function without a return. What you've assigned to the module.exports is a pattern called Immediately-invoked-function-expression.
The code should work if you instead assigned OAuth to a variable, called init() right after the declaration and then export it.
const OAuth2 = {
  /**
   * Initialize
   */
  init: function () {
    this._key = "";
  },
  /**
   * Get Token
   *
   * @return OAuth2 access token if it exists, null if not.
   */
  getToken: function () {
    try {
      return window["localStorage"][this._key];
    } catch (error) {
      return null;
    }
  },
};

OAuth2.init();

module.exports = OAuth2;


text:
Q: Sum up drop down lists in Excel I have 4 drop down lists in Excel with the possible choice of either Yes or No as the two options. I also have conditional formatting too which makes a nice red/green colour.
I need a way to cout how many of the boxes have been set to Yes, I have tried =SUMIF(A1:A4, "Yes") but this hasn't worked. I will include a screenshot of my simple worksheet.

A: use countif
=COUNTIF(A:A,"yes")


text:
Q: Why in $F = iLB$, $L$ is a vector but $i$ is not? I learned $F = iLB$ recently. However, I don't understand why $L$ is marked as a vector but $i$ is not.
For a normal rod, how should I define the direction of length vector $L$? And if I reverse the current in it, the force exerted on it by the magnetic field would reverse direction, correct?
So I think in this formula, $i$ should be the vector but not $L$. Am I right?
I'm using the Physics II by Halliday Resnick and Krane

A: I believe that in that text, $i$ refers to the magnitude of the current (a scalar), which is assumed to be in the same direction as the length vector $\vec{L}$ (a vector).
There's no need for both $i$ and $\vec{L}$ to be vectors. Think of current flowing through a wire—if $i$ were a vector ($\vec{i}$), then the direction of $\vec{i}$ would always be the same as the direction of the wire, because current always flows along a wire. The direction of the wire is already captured by $\vec{L}$, so it's not necessary to make $i$ a vector quantity also.

A: $$ F = (iL)\times B$$  Here $B$ is a vector and $(iL)$ is also a vector. Direction of $(iL)$ is that of flowing current along the lengh $L$. $F$ is cross product of $(iL)$ and $B$ .

A: Well, in theory - We've taken the element of length $l$ which carries current $I$. Hence, the vector belongs to the whole product, which is named as the current element $\vec{Il}$. Strictly speaking, current $I$ is a vector quantity. It's not like voltage or energy. It has a direction, which we say - "It's flowing from here to here".
(Just like every theory, where we consider a small element of length or area or volume so that we can work our calculations in it.)

A: Simply put, current doesn't add like a vector. If I have a star-junction:

with currents $i_1$ and $i_2$ entering from the bottom and $i_3$ leaving the top, $-_3=i_1+i_2$, which is scalar addition. If we try to add the corresponding vectors, we get $\vec i_1+\vec i_2=\sqrt3(|\vec i_1|+|\vec i_2|)\hat i_3 \neq \vec i_3$.
On the other hand, $d\vec l$ is a vector. So, force on a small element of a wire = $id\vec l\times\vec B$. For a rod in a uniform magnetic field, we can integrate to get $\vec F=i\vec L\times\vec B$ since the other terms are independent of the position on the wire, and $\int d\vec L = \vec L$


text:
Q: Change List Toggle in in jquery I have this code in which I have two lists. This helps to make the list items go right or left by clicking the arrow button. I want to make a change in it so that to toggle an active class on click of ul > body to only one item in the list at a time. When the item goes to the right lis its active class gets removed. Currently you can can select multiple item in list.
I have worked on various changes in this JS and jQuery but failed to get the desired result.

$(function() {
  $('body').on('click', '.list-group .list-group-item', function() {
    $(this).toggleClass('active');
  });

  $('.list-arrows button').click(function() {
    var $button = $(this),
      actives = '';
    if ($button.hasClass('move-left')) {
      actives = $('.list-right ul li.active');
      actives.clone().appendTo('.list-left ul');
      actives.remove();
    } else if ($button.hasClass('move-right')) {
      actives = $('.list-left ul li.active');
      actives.clone().appendTo('.list-right ul');
      actives.remove();
    }
  });

  $('.dual-list .selector').click(function() {
    var $checkBox = $(this);
    if (!$checkBox.hasClass('selected')) {
      $checkBox.addClass('selected').closest('.well').find('ul li:not(.active)').addClass('active');
      $checkBox.children('i').removeClass('glyphicon-unchecked').addClass('glyphicon-check');
    } else {
      $checkBox.removeClass('selected').closest('.well').find('ul li.active').removeClass('active');
      $checkBox.children('i').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
    }
  });

  $('[name="SearchDualList"]').keyup(function(e) {
    var code = e.keyCode || e.which;
    if (code == '9') return;
    if (code == '27') $(this).val(null);
    var $rows = $(this).closest('.dual-list').find('.list-group li');
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    $rows.show().filter(function() {
      var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
      return !~text.indexOf(val);
    }).hide();
  });
});
.dual-list .list-group {
  margin-top: 8px;
}

.list-left li,
.list-right li {
  cursor: pointer;
}

.list-arrows {
  padding-top: 100px;
}

.list-arrows button {
  margin-bottom: 20px;
}
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

              <input type="text" name="SearchDualList" class="form-control" placeholder="search" />

bootstrap-duallist github

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

      <button class="btn btn-default btn-sm move-left">

            </button>

      <button class="btn btn-default btn-sm move-right">

            </button>

              <input type="text" name="SearchDualList" class="form-control" placeholder="search" />

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

A: You need to removeClass of siblings too. Reference
$('body').on('click', '.list-group .list-group-item', function() {
  $(this).toggleClass('active').siblings().removeClass('active');
});

$(function() {
  $('body').on('click', '.list-group .list-group-item', function() {
    $(this).toggleClass('active').siblings().removeClass('active');
  });

  $('.list-arrows button').click(function() {
    var $button = $(this),
      actives = '';
    if ($button.hasClass('move-left')) {
      actives = $('.list-right ul li.active');
      actives.clone().appendTo('.list-left ul');
      actives.remove();
    } else if ($button.hasClass('move-right')) {
      actives = $('.list-left ul li.active');
      actives.clone().appendTo('.list-right ul');
      actives.remove();
    }
  });

  $('.dual-list .selector').click(function() {
    var $checkBox = $(this);
    if (!$checkBox.hasClass('selected')) {
      $checkBox.addClass('selected').closest('.well').find('ul li:not(.active)').addClass('active');
      $checkBox.children('i').removeClass('glyphicon-unchecked').addClass('glyphicon-check');
    } else {
      $checkBox.removeClass('selected').closest('.well').find('ul li.active').removeClass('active');
      $checkBox.children('i').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
    }
  });

  $('[name="SearchDualList"]').keyup(function(e) {
    var code = e.keyCode || e.which;
    if (code == '9') return;
    if (code == '27') $(this).val(null);
    var $rows = $(this).closest('.dual-list').find('.list-group li');
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    $rows.show().filter(function() {
      var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
      return !~text.indexOf(val);
    }).hide();
  });
});
.dual-list .list-group {
  margin-top: 8px;
}

.list-left li,
.list-right li {
  cursor: pointer;
}

.list-arrows {
  padding-top: 100px;
}

.list-arrows button {
  margin-bottom: 20px;
}
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

              <input type="text" name="SearchDualList" class="form-control" placeholder="search" />

bootstrap-duallist github

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

      <button class="btn btn-default btn-sm move-left">

            </button>

      <button class="btn btn-default btn-sm move-right">

            </button>

              <input type="text" name="SearchDualList" class="form-control" placeholder="search" />

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros


text:
Q: CAGradientLayer with Rounded Top Corners (without using .mask) I am looking to create a CAGradientLayer with rounded corners. I can't use .cornerRadius because I would like to round only the top two corners. Also, I cannot use .mask because I would like to take a screenshot of it afterwards and renderInContext does not support CALayer masks.
How can I either:

*

*A: Create an CALayer with a gradient and two rounded corners without using masks

or

*

*B: Take a screenshot similar to UIGraphicsGetImageFromCurrentImageContext, but respecting the mask.

A: I figured out a programmatic approach to doing this.  It involves creating a rounded layer then drawing a square layer on top of it.  You'll have to do some playing around with the gradient colors and positions to get something that looks good.
NOTE: Not sure if this solution will work for you given your requirement about masks
+ (void)makeGradientButton:(UIButton *)button {
    // Create a rounded layer
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = button.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
    gradient.cornerRadius = 8.0f;

    // Now create a square layer that draws over the top
    CAGradientLayer *gradient2 = [CAGradientLayer layer];
    gradient2.frame = CGRectMake(0, 9, button.bounds.size.width, button.bounds.size.height-9);
    gradient2.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor redColor] CGColor], nil];
    gradient2.cornerRadius = 0.0f;

    [gradient setMasksToBounds:YES];
    [button.layer insertSublayer:gradient atIndex:0];
    [button.layer insertSublayer:gradient2 atIndex:1];
    [button setBackgroundColor:[UIColor clearColor]];
}


text:
Q: How to automatically set the y-axis limits after limiting the x-axis Let's say that I have a certain number of data sets that I want to plot together.
And then I want to zoom on a certain part (for example, using ax.set_xlim, or plt.xlim or plt.axis). When I do that it still keeps the calculated range prior to the zoom. How can I make it rescale to what is currently being shown?
For example, using
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

data_x = [d for d in range(100)]
data_y = [2*d for d in range(100)]
data_y2 = [(d-50)*(d-50) for d in range(100)]

fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(2, 1, figure=fig)

ax1 = fig.add_subplot(gs[0, 0])
ax1.grid()
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.scatter(data_x, data_y, s=0.5)
ax1.scatter(data_x, data_y2, s=0.5)

ax2 = fig.add_subplot(gs[1, 0])
ax2.grid()
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.scatter(data_x, data_y, s=0.5)
ax2.scatter(data_x, data_y2, s=0.5)
ax2.set_xlim(35,45)

fig.savefig('scaling.png', dpi=300)
plt.close(fig)

Which generate

as you can see the plot below gets hard to see something since the y-axis kept using the same range as the non-limited version.
I have tried using relim, autoscale or autoscale_view but that did not work. For a single data set, I could use ylim with the minimum and maximum values for that dataset. But for different data set, I would have to look through all of them.
Is there a better way to force a recalculation of the y-axis range?

A: *

*Convert the lists to numpy arrays

*

*create a Boolean mask of data_x based on xlim_min and xlim_max

*use the mask to select the relevant data points in the y data

*combine the two selected y arrays

*select the min and max values from the selected y values and set them as ylim
import numpy as np
import matplotlib.pyplot as plt

# use a variable for the xlim limits
xlim_min = 35
xlim_max = 45

# convert lists to arrays
data_x = np.array(data_x)
data_y = np.array(data_y)
data_y2 = np.array(data_y2)

# create a mask for the values to be plotted based on the xlims
x_mask = (data_x >= xlim_min) & (data_x <= xlim_max)

# use the mask on y arrays
y2_vals = data_y2[x_mask]
y_vals = data_y[x_mask]

# combine y arrays
y_all = np.concatenate((y2_vals, y_vals))

# get min and max y
ylim_min = y_all.min()
ylim_max = y_all.max()

# other code from op
...

# use the values to set xlim and ylim
ax2.set_xlim(xlim_min, xlim_max)
ax2.set_ylim(ylim_min, ylim_max)

*

*Instead of using ylim and xlim, you can do x_vals = data_x[x_mask] and then plot x_vals with y_vals and y2_vals, which removes 5 lines of code.

*

*This is similar to Matplotlib - fixing x axis scale and autoscale y axis
# use a variable for the xlim limits
xlim_min = 35
xlim_max = 45

# convert lists to arrays
data_x = np.array(data_x)
data_y = np.array(data_y)
data_y2 = np.array(data_y2)

# create a mask for the values to be plotted based on the xlims
x_mask = (data_x >= xlim_min) & (data_x <= xlim_max)

# use the mask on x
x_vals = data_x[x_mask]

# use the mask on y
y2_vals = data_y2[x_mask]
y_vals = data_y[x_mask]

# other code from op
...

# plot
ax2.scatter(x_vals, y_vals, s=0.5)
ax2.scatter(x_vals, y2_vals, s=0.5)


text:
Q: I am not getting data while working with angular with web api by seperate service It is services.js file which is getting data from server. I have main script file that while is not getting the data into the main java script method form services layer.

Blockquote

Please check the code, and if I have any mistake please let me know:
app.factory("studentServices", function ($http)##

----------

 ##
 return {

        postData: function (student) {

            $http.post("/api/Student/Register", student)
              .then(function (response) {
                console.info(response.data);

                debugger;
                return response.data;

            }, function (error) {

                console.info("error in reruest");
            });
        },
        getData: function () {
            debugger;
            var rt;
            $http.get("/api/Student/getStudent").then(function (response) {
                console.info(response.data);
                debugger;
                rt=response.data;
            }, function (error) { console.info("error in geting"); })
            debugger;
            return rt;
        }

        }
    })

"here is other servise for factory"
/// <reference path="../Scripts/angular.js" />
/// <reference path="script.js" />
var app = angular.module("myModule", []).controller("myController", function ($scope, $http, studentServices) {
    debugger;
    console.info("init");

    $scope.addStudent = function () {
        console.info("just");
        console.info($scope.id);
        $scope.result="";
        var student = {id:$scope.id,name:$scope.name,email:$scope.email,college:$scope.college,mobile:$scope.mobile}
        console.info(student);
      //  $http.post("/api/Student/Register", student).then(function (response) {
        //    console.info(response.data);
        $scope.result = studentServices.postData(student);
            console.info("result " + $scope.result);
            get();
       // }, function (error) { console.info("error in reruest") })
        //$scope.getStudents();
    }

    $scope.getStudents = function get() {
        debugger;
            console.info("gettinf studetn list");
        //    $http.get("/api/Student/getStudent").then(function (response) {
        //      console.info(response.data);
            var local = studentServices.getData();
            debugger;
            $scope.students = local;  //response.data;
            debugger;
            console.info("getdata list  ");

    //        }, function (error) { console.info("error in geting") })

        }
        console.info("last");

})

A: You need to correct below things :
1.In your factory method just return the api promise. for example:
postData: function (student) {
    return  $http.post("/api/Student/Register", student);
}

2.In your controller consume the factory method and its response:
for example:
studentServices.postData(student).then(function (result){
    $scope.result = result.data;
}, function(error){
    // handle error
})

Do similar for getData.
Since $http is async, you have to resolve data in controller, so get data. See this fiddle,


text:
Q: Where are the NPC settlements and vendors? Are there any NPC settlements that have vendors where you can sell your loot, buy stuff, and get healed up? In the other Fallout games it seems like you found these right away, but I can't find them in this game. One of the loading screen tooltips says that most of the settlements have doctors that can heal radiation and crippled limbs, but I can't find these - I can just find the empty settlement locations that you have to build on. Where is the first NPC settlement that you get to?

A: Here are some merchants you can sell stuff to:
Abernathy Farm - Connie
Drumline Diner - Trudy
Diamond City - Major hub/Many vendors
Good Neighbor - Minor hub/a few vendors
Grey Garden - Supervisor Green
Bunker Hill - Minor hub/a few vendors
Also vendors will visit your settlements (such as sanctuary) on occasion.
You will get a marker for Diamond City relatively early on during the quest:

 When Freedom Calls

A: In addition to z''s list, there's also Covenant, Bunker Hill and The Slog.
Once you can build in a settlement, one of the stores you can make is a clinic. Build this and assign a worker, they become the local doctor, even when not at the store.


text:
Q: Building X-Sendfile header sender to see "hidden" files Today I got an issue, which says I should hide some files from the public. Actually these are some "user specific" files so others than the owner should not be able to see them.
I didn't want to read the files with fread or something like that if there are other options so I did some research about the problem and found X-Sendfile mod for apache on an other thread here on SO.
It works almost as I need it. Except one thing.
The files are hidden with htaccess, they aren't visible for the "world" and I can serve them with X-Sendfile header after authentication.
BUT what if someone create a php script what does the same thing as mine? Users may remember the urls for the files. The files will be available for them. That's bad...
Do you have any idea what can I do to prevent others than the owners to access their files without permissions? I need a solution for nginx at first.
The files are on a server without PHP, it's only a static file server.
Moving files to an other directory won't work, it would make much more pain.
Thank you
UPDATE
It seems like I missed that the downloaded file was 0Kb or something like that, because I wasn't able to do the trick again.

A:
BUT what if someone create a php script what does the same thing as mine?

Why are you letting users upload arbitrary code?

Users may remember the urls for the files.

Users will never see the URLs except for the script that uses X-Sendfile.

Do you have any idea what can I do to prevent others than the owners to access their files without permissions?

Verify their auth in the script that uses X-Sendfile.


text:
Q: Mysql php querying improvement over SELECT star...beginner easy I have a table with following fields:
ID,tomato1,tomato2,tomato3

tomato1,2,3 are text columns.
Each tomato1 entry is unique, ID is autoincrement int, everything else is VARCHAR
I am given tomato1 only.
I am using the query:
SELECT * WHERE tomato1='whatever'

I hear some people on the internet who say don't use SELECT * so I want to ask, Is this a bad way to do this?  IS there a more efficient query code/method?

A: The asterisk means that you're always selecting all the columns from this table.  So if you only want the entry of tomato3, your query should read : SELECT tomato3 FROM tomatoes WHERE tomato1='whatever'

A: Generally just query for data you need, because it limits amount of transmitted data, so SELECT ID, tomato2, tomato3 WHERE tomato1 = 'whatever' might be better.

A: It's mainly down to retrieving more data than is required, and thus a performance hit. Do you use the data from all of the columns?
It could help with code maintance too, as you are explicitly calling everything rather than a generic '*'.

A: Additionally, if you change your table in the future, and your application is expecting only the fields that exist today, SELECT * will bring fields the application doesn't expect.
SELECT with named fields is more mantainable.


text:
Q: Using json_encode to send html returns "null" string at the end I'm using this to load php functions and send them to javascript in a plugin, like:
function me_nav_query_submit() {

    $urlcall = nav_me_paises(); /* fetches a large html string */
    $response = json_encode($urlcall); /* encode to display using jQuery */

    //header( "Content-Type: application/json" );
    echo $response;

    exit;
}

I insert the html on the page, using
function(response) {
    jQuery('#navcontainer').html(response);
}

and everything works fine, except that i get a "null" string at the very end of the result.
json_encode() documentation talks about null strings on non-utf-8 chars, but this doesn't seem to be the case. I've also tried using utf8_encode() with no success. I've read a bunch of other questions here on SO, but most of them either talk about one given value returned as null or bad UTF-8 encoding and in my case everthing just works, and then append "null" to the end.
note: Defining that header() call is recommended in the WP Codex, but i commented it because it was giving a "headers already sent" error.
Any ideas?
EDIT this is the function called:
function nav_me_paises() {
    ?>

        <?php $tquery = $_POST['wasClicked']; ?>
        <?php $navligas = get_terms($tquery,'hide_empty=0') ?>
        <?php foreach ($navligas as $liga) : ?>
            <?php $link = get_term_link($liga); ?>

<a href="<?php echo $link; ?>" ><?php echo $liga->name; ?>

        <?php endforeach; ?>

    <?php
}

A: nav_me_paises() is not returning anything. the html block is treated as output!
function nav_me_paises() {
 $output = '
';
 $tquery = $_POST['wasClicked'];
 $navligas = get_terms($tquery,'hide_empty=0')
 foreach ($navligas as $liga) {
   $link = get_term_link($liga);
   $output .= '
'.$liga->name.'
';
  }
  $output .='
';
  return $output;
}

A: nav_me_paises() doesn't return anything. Passing this "nothing" to json_encode() gives "null". Convert the function so that it returns the HTML instead of outputting it
function foo()
{
};

var_dump(json_encode(foo()));

string(4) "null"

A: Also, if it's just plain HTML, why json it? Just send it to JS, it will be a string stored in a variable, and you handle it normally.
I presume all you wanna do is put that HTML inside some div, because you'd not parse it into a DOM and process its elements... because if u'd do that u'd not use HTML for it.


text:
Q: Convert Array in the string type to regular array using JavaScript I have a string variable in javascript called temp:
temp = "[{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]"
How I can convert the string temp to array?
To be like:
temp = [{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]

A: If the string were in valid JSON format you could use JSON.parse(). But it's not, so the only general solution (short of writing your own parser) is eval().

var temp = "[{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]"
var result = eval(temp);
console.log(result);

A: This can be extracted as array using eval javascript function.

const input = "[{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]";
const output = eval(input);
console.log(output);

A: const arr = ['foo,', 'bar', 'red,', 'car']
console.log(arr.join(' '))//"foo, bar red, car"

You can simply use the join() function to convert the array into string

A: JSON.parse should work, if I understand the question correctly
You can use the answer from this question for fixing the JSON before parsing it


text:
Q: GWT Widget inheritance and Compositions In my GWT project, I have a widget "composition(? not 100% sure about the term)", called MenuItem. This has the following structure:

I want to create widgets, which all have this structure, but in place of , for instance an IconMenuItem would put a FontAwesome icon, or ImageMenuItem would put a small thumbnail there.
I'm kind of new to GWT and reading the documentation and some topics here at SO, I suspect that MenuItem should extend Composite and *MenuItem should extend this MenuItem.
However, I'm not sure how I would enforce the HTML structure above without duplicating it. I'm also unsure about what the best practice would be to allow different types of elements, like I said about the image and icon example.
What would be the good class structure, which class should inherit/compose which class?


text:
Q: Swift iOS app - issue with change storyboard segue kind - cant change from modally to show As you can see - i selected show but on main storyboard and in app it works like modaly.
What's wrong with it?

Even if i change to any other option, it works modally!
Edit: If i add button and segue to other view - it works always modally to even if i change this value.

A: For appearing with "Back" button in the navigation bar, you need to use Navigation Controller at first. In order to can push inside.
Check the image, Now it will be handled to push inside the stack of the view controllers of the navigation controller.


text:
Q: Why isn't my backtracking solution for N queens problem working? Here's the output that it returns when I call it from the main function by passing args: 0 and board where 0 is the row number to start from and board is a 4x4 board filled with zeros:
9       1       1       1
1       1       9       1
1       1       1       1
1       0       1       1

Note: 9 means a queen and 1 means a cell attacked by a queen, 0 is a safe cell which neither has a queen on it nor is attacked by a queen.
bool queen_placer(int row, std::vector<std::vector<int>> &board)
{
    if (row == board.size())
    {
        return true;
    }
    for (int col = 0; col < board[0].size(); col++)
    {
        bool safe = is_valid(row, col, board); //is_valid returns true if the position doesn't contain any queen and is not attacked by any queen
        if (safe)
        {
            board[row][col] = 9;
            value_assigner(row, col, board); //value assigner just assigns the attack values of the queen so placed
            if (queen_placer(row++, board))
            {
                return true;
            }
            else
            {
                continue;
            }
        }
    }
    return false;
}

A: You're not backtracking - backtracking involves undoing a choice that leads to failure, but your board[row][col] is forever.
You need to restore the board to its previous state if the recursion fails.

A: The following is the correct code which solves this problem with changes made to the original code only on lines 9 and 21:
bool queen_placer(int row, std::vector<std::vector<int>> &board)
{
    if (row == board.size())
    {
        return true;
    }
    for (int col = 0; col < board[0].size(); col++)
    {
        std::vector<std::vector<int>> board_prev = board; //Added line
        bool safe = is_valid(row, col, board); //is_valid returns true if the position doesn't contain any queen and is not attacked by any queen
        if (safe)
        {
            board[row][col] = 9;
            value_assigner(row, col, board); //value assigner just assigns the attack values of the queen so placed
            if (queen_placer(row + 1, board))
            {
                return true;
            }
            else
            {
                board = board_prev; //Added line
                continue;
            }
        }
    }
    return false;
}

Here's the output that this code gives:
1       9       1       1
1       1       1       9
9       1       1       1
1       1       9       1


text:
Q: Mail for Exchange confirmation android 2.2 device I would like to ask what kind of support is provided for "Microsoft Mail for exchange" on android 2.2 devices and onwards.
Question:

*

*Can developers setup an exchange account programmatically?

*Are there API's to access an exchange server?

*It is included on the Device Administration API as one of the examples that benefits Device Admin but it didn't include emails on the example. Where can we find examples and resources about this one?

*Does this also support for other IMAP or POP3 accounts?
Thanks


text:
Q: No prompt from Biggoron to enter a secret I am trying to speak with Biggoron to give him the secret to get the Biggoron sword, but for some reason I cannot get him to ask about the secret. I have done the trading sequence (and got the Noble Sword) and have completed the first five dungeons.
I have successfully entered secrets in this particular save before, so that is not the issue. Did I miss something?


text:
Q: Recalculate field with JS I am trying to recalculate one field in Odoo based on another field so for example my model is following:
class ProductTemplate(models.Model):
    _inherit = 'product.template'

    margin = fields.Float()
    netto_price = fields.Float()

So based on netto_price i would like to calculate margin. Now i added js file to /static/src/js/products.js and in openerp.py i added 'js': ['static/src/js/products.js'],
Than i wrote following js just to try if its working or not
openerp.product_mycustom = function(instance) {

    var QWeb = openerp.web.qweb;
    _t = instance.web._t;

    instance.web.FormView.include({
        load_form: function(data) {
            var self = this;
            this.$el.find('#netto_price').on('change', function() {
                alert( this.value );
            });
        },
    });
};

And no success. Am i doing something wrong


text:
Q: Let $a,b,c,d \in \mathbb Z$ such that $cd\neq 0$. Then there exist $x,y \in \mathbb Z$ such that $(a-cx+dy)^2 + (b-cy-dx)^2 \le (c^2+d^2)/2$ In proving the ring of Gaussian integers is a principal ideal domain, I boil down to

Theorem: Let $a,b,c,d \in \mathbb Z$ such that $cd\neq 0$. Then there exist $x,y \in \mathbb Z$ such that $$(a-cx+dy)^2 + (b-cy-dx)^2 \le (c^2+d^2)/2$$

I presented a proof here. Because of heavy algebraic manipulation, I'm not fond of it.
I would like to ask for a cleaner way to prove this theorem. Thank you so much for your elaboration!

A: How do you do Euclidean division in $\mathbb Z$ (e.g. $u$ divided by $v$, at least for $v>0$)? You divide the numbers without remainder ($u/v$), and then you truncate the quotient ($q=\lfloor u/v\rfloor$) and take the remainder ($r=u-vq$). The idea here is that the quotient $q$ is "close" to the real quotient $u/v$, so that the remainder $r$ is "small" (smaller than $v$ in "size"). Indeed, $|r|=|u-vq|=|v(u/v)-vq|=|v(u/v-q)|=|v||u/v-q|$ and, as long as $q$ is very close to $u/v$ (in our case, due to truncation, the difference is less than $1$), $|r|<|v|\cdot 1=|v|$.
The same idea can be used in $\mathbb Z[i]$. Take two numbers $u=a+ib$ and $v=c+id$ from $\mathbb Z[i]$, and:

*

*First divide them as you would divide any two complex numbers. You get something like $u/v=x_0+iy_0$, but $x_0, y_0$ may not be integers.

*Now, what complex number is in $\mathbb Z[i]$ and "close" to $x_0+iy_0$? If you imagine the whole complex plane to be divided into $1\times 1$ grid, $x_0+iy_0$ belongs to one of those squares, and you can pick one of the corners of the grid - in fact, the closest corner $q=x+iy, x,y\in\mathbb Z$.

With that choice, $|(x+iy)-(x_0+iy_0)|\le\sqrt{2}/2$. Now you can try to estimate the "size" of the remainder $r=u-vq$. You would get, just as in $\mathbb Z$, that $|r|=|v||u/v-q|$ and, as $|u/v-q|\le\sqrt{2}/2$, we have $|r|\le|v|\sqrt{2}/{2}$ - or, equivalently, $|r|^2\le|v|^2/2$.
Now remind yourself that $r=u-vq=(a+ib)-(c+id)(x+iy)=(a-cx+dy)+i(b-cy-dx)$ and you will reach your desired inequality.


text:
Q: (c++) Read .dat file as hex using ifstream This is my first post so sorry if I break any unwritten rules. :P I am a beginner/intermediate programmer and I need help with this program.
I am trying to infile/read/ifstream (whatever) a .dat file as HEX into one big string.
I don't want to read it as text. I want the hex format so I can search through the string and make changes to it. (Like an automatic hex editor)
ex. my file "00000000.dat" is ~7kb in size.
In hex editor, the hex look like this:
0A 00 00 0A 00 05 4C 65 76 65 6C 07 00 06 42 6C 6F 63 6B 73 00 00 80 00 07 FF 39
01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02
FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF
39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03
02 FF 3F 00..... for a while...

I need all of it in a string variable (with no spaces preferably).
My current code sucks and for now only prints the result. (got it from ehow) and seems to pick and choose what it wants to input/print.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    ifstream input;
    input.open("00000000.dat");

    unsigned char h1,h2;

    do
    {
        input >> h1;
        cout << hex << (unsigned int)h1;
        input >> h2;
        cout << hex << (unsigned int)h2;
    }while(!input.eof());

cin.get();
return 0;
}

It's a big file so I can't show yo what it prints, but it is missing some bytes. (ex "0A 00 00 0A 00 05....." prints as "00 05.....") this is true for the ending as well.
Sorry if I didn't explain it well :(

A: You should open the stream as binary, as mentioned. You can use the regular >> operator if you tell it not to skip white space.
unsigned char x;
std::ifstream input("00000000.dat", std::ios::binary);
input >> std::noskipws;
while (input >> x) {
    std::cout << std::hex << std::setw(2) << std::setfill('0')
              << (int)x;
}

To get the content into a string, you can use an ostringstream instead of cout.

A: You want to open the file to read as binary.  You're reading as text right now.  So it should look like
//Open file object to read as binary
std::ifstream input("00000000.dat", std::ios::in | std::ios::binary);

You also might want to use reinterpret_cast to read one byte at a time (i.e. can't figure out what you want -- your code and your description are doing opposite things).
//Read until end of file
while(!input.eof())
{

    //Or .good() if you're paranoid about using eof()

    //Read file one byte at a time
    input.read(reinterpret_cast<char *>(&h1), sizeof(unsigned char));

}

Or if you just want everything in one string, why not just declare a string and read it into that?


text:
Q: running function based on user input in C# console application I'm trying to run a console application that will allow a user to pick which type of job they would like to run on their PC and their response will translate to which functions the program runs. The way it is written right now the program will lock up and not allow anything else when the user inputs any options other than 4 which will successfully close the program.
        static void Main(string[] args)
        {
            int userInput = 0;

            DisplayMenu();

            do
            {
                if (userInput == 1)
                {
                    QuickClean();
                }
                else if (userInput == 2)
                {
                    DeepClean();
                }
                else if (userInput == 3)
                {
                    SuperClean();
                }
            } while (userInput != 4);

        }

        static public int DisplayMenu()
        {
            Console.WriteLine("");
            Console.WriteLine();
            Console.WriteLine("1. Quick Clean");
            Console.WriteLine("2. Deep Clean");
            Console.WriteLine("3. Super Clean (admin needed)");
            Console.WriteLine("4. exit");
            var result = Console.ReadLine();
            return Convert.ToInt32(result);
        }

        static void QuickClean()
        {
            Console.WriteLine("quickclean");
            Console.ReadLine();
        }

        static void DeepClean()
        {
            Console.WriteLine("deepclean");
            Console.ReadLine();
        }

        static void SuperClean()
        {
            Console.WriteLine("superclean");
            Console.ReadLine();
        }

A: The DisplayMenu method returns what your user chooses but you don't assign this return to your usermenu local variable.
As you have written it now, you ask for input just one time and then enter the loop without setting the local variable usermenu to the user choice so it is still zero when it reaches the while to test the exit condition and the loop enters the infinite condition.
You need to move the call to DisplayMenu inside the loop and assign the return value to usermenu, so your user can see again the menu and input a different choice and you can perform the required operations.
static void Main(string[] args)
{
    int userInput = 0;
    do
    {
        userInput = DisplayMenu();
        if (userInput == 1)
        {
            QuickClean();
        }
        ....
    } while(userInput != 4)
}

I suggest also to change the code in DisplayMenu and avoid to use Convert.ToInt32 to parse the user input. If the user doesn't type a number the Convert.ToInt32 will crash your program. Instead use Int32.TryParse
    static public int DisplayMenu()
    {
        Console.Clear();
        while(true)
        {
            Console.WriteLine("");
            Console.WriteLine();
            Console.WriteLine("1. Quick Clean");
            Console.WriteLine("2. Deep Clean");
            Console.WriteLine("3. Super Clean (admin needed)");
            Console.WriteLine("4. exit");
            int result;
            if(Int32.TryParse(Console.ReadLine(), out result))
                return result;
            else
                Console.WriteLine("Please enter a number");
        }
     }

A: You are not storing the returned value anywhere. userInput is still 0 after DisplayMenu() is called, that's why you get into an infite loop at the do-while.
do{
    int userInput = DisplayMenu();
    [...]
} while (userInput != 4)


text:
Q: PHP Table 2D Leap year I have a following problem:
I need to create a 2D table from year 1990 to 2014. If that year is leap year, it goes on the right side, if not, on the right:

This is what I have so far:
<?php
echo "
";
for($i=0;$i<1;$i++) {
echo "
";
echo "" . "Leto je prestopno" . "	";
echo "" . "Leto ni prestopno" . "	";
echo "
";
    for($j=0;$j<12;$j++){

    }
}
echo "
";
?>

A: Can try this
function is_leap_year($year)
{
    return ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));
}

echo '
';
echo '
Leap Year	Not Leap Year
';
for($i = 1990; $i < 2015; $i++){
    if(is_leap_year($i)){
        $left_td = $i;
        $right_td = '-';
    }else{
        $left_td = '-';
        $right_td = $i;
    }
    echo '
'.$left_td.'	'.$right_td.'
';
}
echo '
';


text:
Q: Use of relationship and ForeignKey modules in SQLAlchemy I'm a little confused over the use of the two modules from SQLAlchemy. This is the code I have:
Base = declarative_base()

class Restaurant(Base):
    __tablename__ = 'restaurant'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class MenuItem(Base):
    __tablename__ = 'menu_item'
    name =Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer,ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

I understand that ForeignKey is used to define the foreign key relationship between the restaurant_id column of menu_item table and the id column of restaurant table. But why then is restaurant = relationship(Restaurant) used?

A: restaurant_id will refer to an id (the column value). restaurant will refer to a Restaurant instance that will be lazy loaded from the db on access (or eager loaded if you set up the right stuff earlier). If you set backref on the relationship you can also access a list of MenuItem objects from a Restaurant.


text:
Q: Reading time and date on webpage with Python New to python, intermediate at VB7
I have been trying to create a program which will reach out and log news articles based on the text in the url. I have encountered many difficulties no doubt due to my unfamiliarity with the language, and I was hoping I might find some help here on this problem as I have others.
Here is an example block of webpage code I am working with. (I'm sorry, I know its ugly.)

Aug-29-17 09:05AM
Yahoo newsGlobeNewswire
+18.95%

Aug-25-17 07:30AM
Corporate News Blog -
ACCESSWIRE -5.73%

I have Beautifulsoup, request, and at this point feel confident enough to handle any other module that I may need.
What I am trying to do figure out now is recording the time and date on the webpage, or perhaps checking it against today's date so that I don't read old news.
Thank you for reading.

A: You need to use datetime module.
If you already parsed the string with date and time ("Aug-29-17 09:05AM" in your case) use datetime.strptime() to create datetime object.
mydate = datetime.datetime.strptime('Aug 29 17 09:05AM', '%b %d %y %I:%M%p')

Than you can compare it with today's date - datetime.now().

A: If your question is how to scrap time and date with their responsive content from site's source code then you can do it using bs4 like so:
#!/usr/bin/env python

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

html = '''

   Aug-29-17 09:05AM

      Yahoo newsGlobeNewswire
      +18.95%

   Aug-25-17 07:30AM

      Corporate News Blog -
      ACCESSWIRE -5.73%

'''

import re
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")

for i,j in zip(soup.find_all('tr'), soup.find_all('td', attrs={'align':'left'})):
    print '\n[time and date] => {}'.format(i.td.text)
    print '[Content] => {}'.format(re.sub('<[^>]*>', '', str(j)).replace('\n',' '))
    print '[Link] => {}'.format(j.find('a').get('href'))

This will give as a result:
[time and date] => Aug-29-17 09:05AM
[Content] =>  Yahoo newsGlobeNewswire     +18.95%
[Link] => https://finance.yahoo.com/news/abeona-therapeutics-receives-fda-breakthrough-130500766.html

[time and date] => Aug-25-17 07:30AM
[Content] =>  Corporate News Blog -  ACCESSWIRE -5.73%
[Link] => https://finance.yahoo.com/news/

A: You can use the time module:
import time
currentTime = time.asctime(time.localtime(time.time()))

it might look frustrating, but its syntax is actually very easy and comprehendable.
I hope I've helped!


text:
Q: Does Apache NiFi support looping? Is there an option to perform processor operation in a loop on specific flowfile content?
As a specific example, when using EvaluateXPath I want to check the Phone element's value in each child using the following:
/Parent/Childrens/Child[i]/Phone[@Value='111']

A: All relationships can be directed back to the processor they come from as long as that processor supports incoming connections.  For your example, you could provide the 'matched' relationship back to the same processor and have it again evaluate the path you were looking for.  This would continue on until that expression no longer evaluates to a match.

A: Is your JSON structure recursive, or are you looking to iterate over the single "Child" array? If the latter, the SplitJson processor will create a new flow file for each element in your array, then you can use EvaluateJsonPath to get the value for "Phone" in each child, then RouteOnAttribute to filter on those whose value is 111:

This template (with a simple version of the JSON structure you gave) is available as a Gist (here). Note it needs NiFi 0.5.0+ for InvokeScriptedProcessor (which generates the sample JSON file)


text:
Q: Basic Database Design - Optional Participation Working on basic database design homework and ERD drawing in Visio, and can't wrap my head around this problem.

United Helpers is a nonprofit organization that provides aid to people after natural disasters. Based on the following brief
  description of operations, create the appropriate fully labeled Crow's
  Foot ERD.
•Individuals volunteer their time to carry out the tasks of the organization. The name, address, and telephone number for each
  volunteer are tracked. Each volunteer may be assigned to several tasks
  during the time that he or she is doing volunteer work, and some tasks
  require many volunteers. It is possible for a volunteer to be in the
  system without having been assigned a task yet. It is possible to have
  tasks that no one has been assigned. When a volunteer is assigned to a
  task, the system should track the start time and end time of that
  assignment.
•For each task, there is a task code, task description, task type, and task status. For example, there may be a task with task code
  "101," a description of "answer the telephone," a type of "recurring,"
  and a status of "ongoing." There could be another task with a code of
  "102," a description of "prepare 5000 packages of basic medical
  supplies," a type of "packing," and a status of "open."
•For all tasks of type "packing," there is a packing list that specifies the contents of the packages. There are many different
  packing lists to produce different packages, such as basic medical
  packages, child-care packages, food packages, etc. Each packing list
  has a packing list ID number, a packing list name, and a packing list
  description, which describes the items that ideally go into making
  that type of package. Every packing task is associated with only one
  packing list. A packing list may not be associated with any tasks, or
  may be associated with many tasks. Tasks that are not packing tasks
  are not associated with any packing list.
•Packing tasks result in the creation of packages. Each individual package of supplies that is produced by the organization is tracked.
  Each package is assigned an ID number. The date the package was
  created and the total weight of the package are recorded. A given
  package is associated with only one task. Some tasks (e.g., "answer
  the phones") will not have produced any packages, while other tasks
  (e.g., "prepare 5000 packages of basic medical supplies") will be
  associated with many packages.
•The packing list describes the ideal contents of each package, but it is not always possible to include the ideal number of each item.
  Therefore, the actual items included in each package should be
  tracked. A package can contain many different items, and a given item
  can be used in many different packages.
•For each item that the organization provides, there is an item ID number, item description, item value, and item quantity on hand stored
  in the system. Along with tracking the actual items that are placed in
  each package, the quantity of each item placed in the package must be
  tracked too. For example, a packing list may state that basic medical
  packages should include 100 bandages, 4 bottles of iodine, and 4
  bottles of hydrogen peroxide. However, because of the limited supply
  of items, a given package may include only 10 bandages, 1 bottle of
  iodine, and no hydrogen peroxide. The fact that this package includes
  bandages and iodine needs to be recorded along with the quantity of
  each that is included.It is possible for the organization to have
  items donated that have not been included in any package yet, but
  every package will contain at least one item.

My thought would be entity VOLUNTEER & TASK creating the composite entity ASSIGNMENT which could generate the task PACKING.  That task uses PACKING LIST & ITEMS which generates PACKAGE.

However my confidence in this solution is zero.  Wondering if it's remotely correct?  Or am I completely going about this the wrong way?
Thanks

A: You're going about it in the right way, or at least heading in the right direction, but the end result is wrong (although the entities in the top row of your diagram are more or less correct)
Pay attention to the phrases "For each task, there is a ... task type" and "For all tasks of type "packing," there is a packing list". This would suggest that a "packing task" is a type of task, not a type of assignment.

A: Before you can do this homework assignment in any meaningful way,  you and your teacher need to be of one accord about whether an ERD expresses Data Analysis or Database Design.  In previous questions concerning ERD, I've always offered the view that ERD is for data analysis, and database design ought to be expressed in some other diagramming scheme, such as a relational schematic diagram.
However, it's very possible that your teacher doesn't see this the same way I do. A large number of professionals use ERD as an alternative to relational schematics, and express database design in an ERD.  Your solution looks like design to me, and not analysis.
If your teacher doesn't distinguish between analysis and design (and some don't) there is something fundamental that you need to learn, and that your teacher will not be able to teach you.  You need to distinguish between the features of the problem and the features of the proposed solution to the problem.  If you don't make that distinction you end up in one of several pitfalls.
The most common pitfall is coming up with the right solution to the wrong problem.  I've seen this happen over and over again in the field.
The second most common pitfall is changing the problem definition in order to make the problem easier to solve.  Sometimes this is done intentionally, in order to meet a deadline with limited resouirces.  But when it's done unintentionally,  a host of problems crop up.
The third pitfall is what may be called "thinking inside of the box".  In this pitfall, the would be solver adds a constraint that was not in the original problem definition, but is a feature of the first faulty solution.  The "box" is a feature of a proposed (faulty) solution and not a feature of the problem as originally stated.  But once it's been accepted as part of the problem, the problem becomes unsolvable.

A: I think it should be like this

A there's only five tables Specified, I thing the packing task, is the task table.


text:
Q: In my project sub folders are viewable. I need to make it forbidden. How shall i make it? For example, if i give the below url in the address bar all images are viewable right now.
URL : http:///www.test.com/images/
How shall i able to avoid this.. It should not be viewable or it should be restricted or redirected to some other page.
How can this be done?
Thanks in advance...

A: We can do it by using
Options -Indexes
which should be entered in .htaccess file and should be placed inside the corresponding folder.
And its working fine now...


text:
Q: is there way to get cookies unique ID? I trying to create a shopping cart where user will be able to add to cart without needed to login.
I have 3 ways to do this:
Session - this works but issue is that soon as they close the website... then session will get destroy
Cookie - This fixes the session issue but cookies have small size limit and user can block it also
DataBase - I can store cart in database for 3 days and manual remove the record in database
I like the database solution but there is a issue. how can I get unquite ID of user who is not logged in?
I could use session to get unquie id but than if user close website.. re-open website than his session ID will change also.

A: Use FingerPrintJS2 for your case.


text:
Q: How to get confidence estimate of random forest model predictions? I am working on binary classification using random forest model with dataset shape of 977, 6. Class proportion is 77:23
I built the ML model using my input data and obtained the probabilities of the outcome using predict_proba function from the scikit-learn package.
However, I want to know whether we can get the confidence of the model predictions?
For example, I am expecting my output to be something like below

Currently, I ran the predict_proba function once on test set, so I have computed the probability once. So, am not sure how can we find out the confidence of our model predictions? Is there any python package that can help us get this sort of confidence?


text:
Q: AS3: create template for XML file I need to create DB report as excel file. The best (and simplest) way I can see - create the XML representation and save it as XLS.
The Header and Footer parts of this file should be constant, so I'd prefer to load them from config (or template) file instead of hard coded string constants.
And it has no sense to use the XML per se - the "string" will be more than enough.
The question is: how I can do it? I mean - load XML content as string, or as a last resort - create string constant.
I've tried what was recommended for multi-line constants in one of stackoverflow answers (use CDATA). But seems, for XML content it doesn't work.
Thanks in advance.

A: URLLoader will load any file as String by default. Otherwise, use XML for XML data, not XML string packed into CDATA of other XML (if I understand your thought correctly).


text:
Q: $.get not working with jQuery
Possible Duplicate:
jQuery.ajax fails when url is from different server

I have a code like this on my test page:
$(document).ready(function() {

    $.get(
        "http://www.google.com",
        function(data) { alert(data); }
    );

});

The problem is, that I never get the alert and I don't know why.
Does anybody know what the error could be? Its a simple html page and all other jQuery stuff is working.

A: This isn't working for you, because you're trying to perform crossdomain XmlHttpRequest. You might want to check out this Cross domain mod for jQuery

A: The $.get function in jQuery executes an AJAX request with the HTTP type of GET. Due to Same origin policy, you can't request pages from outside of your domain.
If you need to request pages from another domain, you would need to setup a script hosted on your site to proxy these requests.

A: If its google.com you are trying to get then it wont work, XHR only works on your own domain. the other site need to have Cross-site XMLHttpRequest enabled.


text:
Q: Haskell dividing num I'm having an issue I want to learn more about, and how to avoid. I've got this code
len :: (Num r ) => [a] -> r
len [] = 0
len xs = 1 + len ( tail xs )

avg :: (Num t) => [t] -> Double
avg xs = ( sum xs ) / ( len xs )

Which renders the following error

len.hs:6:9:
    Couldn't match expected type `Double' against inferred type `t'
      `t' is a rigid type variable bound by
          the type signature for `avg' at len.hs:5:12
    In the expression: (sum xs) / (len xs)
    In the definition of `avg': avg xs = (sum xs) / (len xs)

Now, I know this error (thanks to irc.freenode.net#haskell) is a result of the division function
(/) :: (Fractional a) => a -> a -> a

However, I don't know what to do. My avg function signature should have nothing to do with the division opperators quirks (requiring Fractional typeclass). So, I'm left thinking the right way to overcome this is by casting to a type that impliments they Fractional typeclass but I have no idea how, or even if this is right? Any ideas?

A:
My avg function signature should have nothing to do with the division operator's quirks

Why is that? If you want to compute the average of a bunch of Integers, you'll have to divide at some point, so you'll have to convert them from Integers to the division-supporting type of your choice. A close look at the Num class (:i Num in ghci) reveals one problem with the type of avg: Num doesn't have enough methods — basically enough to add, multiply, and subtract. There's no guarantee that the number I give to avg can be converted to a Double at all.
If you enter an untyped function to compute an average, Haskell responds with the most generic type possible:
Prelude List> :type \x -> sum x / genericLength x
\x -> sum x / genericLength x :: (Fractional a) => [a] -> a

So that's the correct type of avg.
You might notice that avg [1,2,3 :: Integer] gives a type error. You can get around that by passing the argument to toRational or fromIntegral first, which use the Real and Integral instances for Integer, respectively.

Regarding the expression sum [1,2,3] / len [1,2,3]: It's true that a literal number like 1 has the type of Num a => a, which calls fromInteger on whatever type it turns out to be, but an expression like 1/2 has a more specific type of Fractional a => a, which you can see if you ask for the type of that expression instead of printing it out.
Something that might be helpful is :set -Wall in ghci, which turns on lots of warnings whenever a default type is chosen for you, giving a clue that the most generic type might no longer be correct.

A: You're overly constraining the type of avg. Use the more general version, avg ::  (Fractional a) => [a] -> a

A: hhm the really problem is if it is an integral type you want to cast to a fractional type, but if it is an fractional type you want to leave it alone.
Try this
fromRational ((sum xs) % (leng xs))

A: I've encountered this problem. This best I've managed to do is have two functions for averaging: one for integrals and one for fractionals:
avgInt :: (Integral i, Fractional f) => [i] -> f
avgInt xs = fromIntegral (sum xs) / fromIntegral (length xs)

avgFrac :: (Fractional f) => [f] -> f
avgFrac xs = sum xs / fromIntegral (length xs)


text:
Q: very tricky html characters as text
   M,W,Th,F 7:30 AM - 4:00 PM <br />Tu 7:30 AM - 6:00 PM <br />

will be rendered as this
M,W,Th,F 7:30 AM - 4:00 PM
Tu 7:30 AM - 6:00 PM

Now i need to replace the <br /> as an empty space before it is rendered??
I already asked a similar question, but i underestimated the trickiness of this..
I did this
$('.WorkingHours').text().replace(/
/g, " ");

didn't work..can someone help me out of this?
Shouldn't this work?
$('.WorkingHours').text().replace(/<br \>/g, " ");

A: This will work:
$('.WorkingHours').text(function(i, text) {
    return text.replace(/
/g, " ");
});

DEMO
In this case .html() would return the HTML entities (<) whereas .text() returns the decoded characters (i.e. <). Given that,
$('.WorkingHours').text().replace(/
/g, " ")

actually works as well but you still have to assign the result back to the element.
See also my previous answer.

Regarding replacing the last
 with a different character: It might be possible with regular expressions, but in that case, I would just parse the text as HTML and perform the same operation as I showed in my previous answer:
var $content = $('
').html($('.WorkingHours').text());
$content
 .find('br').last().replaceWith('.')
 .end().replaceWith(' ');

$('.WorkingHours').html($content.html());

DEMO

A: you have to escape the HTML characters to complete the pattern...
replace(/\
/g, " ");

A: If you have html entities in markup try replacing those instead
   replace('<br \/>', ' ')

Looks like you were missing a "/"


text:
Q: How to set limit value dynamic? I'm using BI Tool which has an option to write SQL Queries. I have a tables like
Table Name - Analysis

Module
Value

Lead
5

Deal
3

Table Name - Leads

module_name
Name
created_date

Lead
AAA
03-02-2021

Lead
BBB
03-02-2021

Lead
CCC
03-02-2021

Lead
FFF
03-02-2021

Lead
MMM
03-02-2021

Lead
ooo
02-02-2021

Lead
ppp
02-02-2021

Table Name - Deals

module_name
Name
created_date

Deal
DDD
03-02-2021

Deal
GGG
03-02-2021

Deal
EEE
03-02-2021

Deal
QQQ
03-02-2021

Deal
SSS
02-02-2021

Deal
TTT
02-02-2021

The above values are not static values, they will get updated on an hourly basis.
I have to use those values and set the limit for no of rows to display based on the latest created date
I have to get output as

Module
lead_name

Lead
AAA

Lead
BBB

Lead
CCC

Lead
FFF

Lead
MMM

Deal
DDD

Deal
GGG

Deal
EEE

I tried the following
SELECT module_name as module,
    lead_name as name
    from Leads
    left join Analysis on Leads.module_name=Analysis.Module
    Order by Leads.Created_Date DESC
    LIMIT to_integer(Analysis.Value)
 UNION
 SELECT Deals.module_name as module,
    Deals.deal_name as name
    from Deals
    left join Analysis on Deals.module_name=Analysis.Module
    Order by Deals.Created_Date DESC
    LIMIT to_integer(Analysis.Value)

Is it possible to set the limit dynamically?
Thanks

A: I would suggest using row_number():
select l.module_name, l.Name, l.created_date
from (select l.*,
             row_number() over (order by created_date desc) as seqnum
      from leads l
     ) l
where seqnum < (select a.value from analysis a where a.module = 'Lead')
union all
select d.module_name, d.Name, d.created_date
from (select d.*,
             row_number() over (order by created_date desc) as seqnum
      from deals d
     ) d
where seqnum < (select a.value from analysis a where a.module = 'Deal');

Note:  Use UNION ALL.  UNION incurs overhead for removing duplicate values.  And there appear to be no duplicate values in your data.
Also, the LEFT JOIN is superfluous.  Presumably, you would get no rows if there were no matches in analysis.

A: Finally, it was painful task, however I have written the code in MySql v8.0. If you are using lower version then you might not able to use CTE. On that scenario you can use subquery.So, Here is the code given below=>
WITH CTE AS
(SELECT module_name as module,
    lead_name as name,
    CASE WHEN
     ROW_NUMBER() OVER(Order by Leads.module_name)<=Analysis.Value
     THEN 1
     ELSE 0 END AS IsSelected
    from Leads
    left join Analysis on Leads.module_name=Analysis.Module

 UNION
 SELECT Deals.module_name as module,
    Deals.deal_name as name,
     CASE WHEN
     ROW_NUMBER() OVER(Order by Deals.module_name)<=Analysis.Value
     THEN 1
     ELSE 0 END AS IsSelected
    from Deals
    left join Analysis on Deals.module_name=Analysis.Module
 )
 SELECT module,name FROM CTE WHERE IsSelected=1

NOTE: You can check my code in DB Fiddle.

A: In a Stored Procedure, you can construct a query and then execute.  That is a way to dynamically change the table name, LIMIT, OFFSET, and a few other things.
I prefer to make such changes in the application code.


text:
Q: Запомнить пользователя, если хотя бы раз вошел Намучился с проблемой уже с неделю, пытаюсь записать логин вошедшего юзера в SharedPreferences, но вот как ни кручу эти настройки, код все время при отладке показывает там null, может есть у кого возможность глянуть код и помочь с этим казусом.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

public static final String TAG = "activity_main";

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private TextView email;
private TextView password;
private ProgressBar progressBar;
SharedPreferences mSettings;
public static final String APP_PREFERENCES_USER = "User";
public static final String APP_PREFERENCES = "mysettings";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_main);

    mAuth = FirebaseAuth.getInstance();     // get instance of fireBase

    progressBar = (ProgressBar)findViewById(id.progressBar);

    email = (TextView) findViewById(id.email);
    password = (TextView) findViewById(id.password);

    **mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
    if(mSettings.contains(APP_PREFERENCES_USER)){
        email.setText(mSettings.getString(APP_PREFERENCES_USER, "rea"));
    }**

    mAuthListner = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                Log.d(TAG, "Sign_in" + user.getUid());
            } else {
                Log.d(TAG, "Sign_out");
            }
        }
    };

    findViewById(id.sign_in_Button).setOnClickListener(this);
    findViewById(id.registration_Button).setOnClickListener(this);
}

public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListner);
}

public void onStop() {
    super.onStop();
    if (mAuthListner != null) {
        mAuth.removeAuthStateListener(mAuthListner);
    }
}

@Override
public void onClick(View v) {
         if (v.getId() == id.sign_in_Button) {
             if ((!email.getText().toString().equals(null) && !email.getText().toString().equals(""))
                     || (!password.getText().toString().equals(null)&& !password.getText().toString().equals(""))) {
                 progressBar.setVisibility(View.VISIBLE);
                 mAuth.signInWithEmailAndPassword(email.getText().toString(), password.getText().toString())
                         .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                             @Override
                             public void onComplete(@NonNull Task<AuthResult> task) {
                                 if (task.isSuccessful()) {
                                    **Editor editor = mSettings.edit();
                                     editor.putString(APP_PREFERENCES_USER, email.getText().toString());
                                     mSettings.edit().apply();**
                                     if (email.getText().toString().equals("admin@rea.ru")) {
                                         Intent intent = new Intent(MainActivity.this, admin_Activity.class);
                                         startActivity(intent);
                                         progressBar.setVisibility(View.INVISIBLE);
                                     } else{
                                         Log.d(TAG, "Succesful enter");
                                         Intent intent = new Intent(MainActivity.this, Categories.class);
                                         startActivity(intent);
                                         progressBar.setVisibility(View.INVISIBLE);
                                     }
                                 }
                             }
                         })
                         .addOnFailureListener(new OnFailureListener() {
                             @Override
                             public void onFailure(@NonNull Exception e) {
                                 Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                             }
                         });
             }else{
                 Toast.makeText(MainActivity.this, "Password or email is empty", Toast.LENGTH_SHORT).show();
             }
         }

        if (v.getId() == id.registration_Button) {
            progressBar.setVisibility(View.VISIBLE);
            Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
            startActivity(intent);
            progressBar.setVisibility(View.INVISIBLE);
        }
}

}

A: Вы записываете настройку в один Editor, но сохраняете изменения в другом.
Надо так:
 Editor editor = mSettings.edit();
 editor.putString(APP_PREFERENCES_USER, email.getText().toString());
 editor.apply();
//вместо mSettings.edit().apply();

или даже в одну строку так:
mSettings.edit().putString(APP_PREFERENCES_USER, email.getText().toString()).apply();

Также вы используете префы активити, а не всего приложения. Т.е. в других активити значение записанное доступно не будет. Используйте глобальные префы. Их получают так:
SharedPreferences mSettings = PreferencesManager.getDefaultSharedPreferences(context);


text:
Q: How I can pause a thread for some time in python? I am working for build a software where I wan't to pause/stop a thread for some time or for a event
here are some essential code to understand you better
self.staff_list_thread = Thread(target = self.get_staff_list, kwargs = {"master": self.frame_staff_list}, daemon = True)
self.staff_list_thread.start()

def get_staff_list(self, master, *args, **kwargs):
    def add_staff_button_callback():
        self.get_add_staff(self.frame_staff_add)

    def detail_edit_staff_button_callback(email):
        if email is not None:
            self.get_detail_edit_staff(self.frame_staff_detail, email)

    row = 1
    self.staff_introduction = get_a_label(master, text="This is staff area", row=0, column=0, padx=(10, 10), pady=(10, 10))
    self.staff_introduction.config(style="Title.TLabel")
    self.add_staff_button = get_a_button(master, text="Add New Staff", row=0, column=1, padx=(10, 10), pady=(10, 10), ipadx=7, ipady=4)
    self.add_staff_button.config(command=add_staff_button_callback)

    staffs = self.get_staff_queryset()
    if staffs is not None:
        for staff in staffs:
                self.staff_data_button = get_a_button(master, text='{} as {}'.format(staff[1], staff[5]), row=row, column=0, padx=(0, 0), pady=(5, 5), ipadx=10, ipady=10, relief=FLAT, use_ttk=False)
                self.staff_data_button.config(command = lambda email=staff[2]: detail_edit_staff_button_callback(email))
                row = row + 1

In the end of function I wan't to end of pause the thread and when the new staff is added I wan't to recount or reset the list with current data so I need to run thread again
Here are the button call func
def get_add_staff(self, master, *args, **kwargs):
    self.add_staff_current = True
    if self.have_one_detail:
        # self.destroy_child(self.frame_staff_detail)
        self.have_one_detail = False
        self.frame_staff_detail.destroy()
        self.frame_staff_detail         = get_a_frame(self.staff_add_update_panedwindow, column=1, sticky="wn")

    FullName, Email, Phone, Joining, Designation, Active = self.get_staff_variable()

    def cancel_new_staff_button_callback():
        # self.destroy_child(master)
        self.frame_staff_detail.destroy()
        self.frame_staff_detail         = get_a_frame(self.staff_add_update_panedwindow, column=1, sticky="wn")
        self.add_staff_current = False

    def staff_button_callback():
        data = {
            'full_name': FullName.get(),
            'email': Email.get(),
            'phone': float(Phone.get()),
            'joining': Joining.get(),
            'designation': Designation.get(),
            'responsibility': self.add_staff_responsibility_data.get(1.0, 'end'),
            'about': self.add_staff_about_data.get(1.0, 'end'),
            'active': Active.get()
        }
        execute = self.execute_staff_data(data=data)
        if execute is True:
            # self.staff_list_thread.start()
            cancel_new_staff_button_callback()

    self.get_staff_labels(master)

    self.add_staff_fullname_data                = get_a_entry(master, textvariable=FullName, width=36, row=1, column=1)
    self.add_staff_email_data                   = get_a_entry(master, textvariable=Email, row=2, width=36, column=1)
    self.add_staff_phone_data                   = get_a_entry(master, textvariable=Phone, row=3, column=1)
    self.add_staff_joining_data                 = get_a_entry(master, textvariable=Joining, row=4, column=1)
    self.add_staff_designation_data             = get_a_entry(master, textvariable=Designation, width=36, row=5, column=1)
    self.add_staff_responsibility_data          = get_a_text(master, width=36, height=4, row=6, column=1)
    self.add_staff_about_data                   = get_a_text(master, width=36, height=10, row=7, column=1)
    self.add_staff_active_data                  = get_a_radio(master, text="Active", variable=Active, value=1, row=8, column=1)
    self.add_staff_inactive_data                = get_a_radio(master, text="Inactive", variable=Active, value=0, row=9, column=1)

    self.save_new_staff_button                  = get_a_button(master, text="Add Staff", row=10, padx=(20, 20), pady=(30, 30))
    self.cancel_new_staff_button                = get_a_button(master, text="Cancel", row=10, column=1, padx=(20, 20), pady=(30, 30))
    self.save_new_staff_button.config(command=staff_button_callback)
    self.cancel_new_staff_button.config(command=cancel_new_staff_button_callback)

A: To simply answer your title question, you can pause a thread with the time.sleep()
import time
time.sleep(30) #pause for 30 seconds

With a naive implementation, you could just run this on a loop checking if the function should be called. Be careful that this will lock the whole paused thread.
From the code though I don't really understand where you want to pause it.
To react to an event, pausing a thread is not the right question, you need to implement a subscribe/register and callback logic.


text:
Q: How to extract a gz file in python I have a .gz file, inside which there is another file. I need to extract the file inside the zipped file.
f = gzip.open(dest, 'rb')

This only opens the file but I need to download that particular file which is inside gz instead of just opening the gz file.
This question has been marked as duplicate which I accept, but I haven't found a solution where we can actually download the file and not just read its content. Same is the case with the link mentioned.

A: You could just open two files, read from the gzipped file and write to the other file (in blocks to avoid clogging the memory).
import gzip

def gunzip(source_filepath, dest_filepath, block_size=65536):
    with gzip.open(source_filepath, 'rb') as s_file, \
            open(dest_filepath, 'wb') as d_file:
        while True:
            block = s_file.read(block_size)
            if not block:
                break
            else:
                d_file.write(block)

Otherwise, you could use shutil, as suggested in How to unzip gz file using Python:
import gzip
import shutil

def gunzip_shutil(source_filepath, dest_filepath, block_size=65536):
    with gzip.open(source_filepath, 'rb') as s_file, \
            open(dest_filepath, 'wb') as d_file:
        shutil.copyfileobj(s_file, d_file, block_size)

Both solutions would work in Python 2 and 3.
Performance-wise, they are substantially equivalent, at least on my system:
%timeit gunzip(source_filepath, dest_filepath)
# 129 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit gunzip_shutil(source_filepath, dest_filepath)
# 132 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: I have resolved the issue like this:
f = gzip.open(dest, 'r')
file_content = f.read()
file_content = file_content.decode('utf-8')
f_out = open('file', 'w+')
f_out.write(file_content)
f.close()
f_out.close()

dest is the file with gz


text:
Q: How to json encode a single object as a json objects array using PHP For two objects:
    {"publications":[{"nom":"toto","id":"2029","userid":"22","publication":"bla bla bla","time":"2017-02-20 00:00:00","avatar":{}},{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}]}

For One object:
    {"publications":{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}}

i want to have always a json array as a return no matter how the number of objects.
PHP Code:
    $result = $conn->query($sql);
    $json = new SimpleXMLElement('<xml/>');

  if ($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
    $mydata = $json->addChild('publications');
    $mydata->addChild('nom',$row['nom']);
    $mydata->addChild('id',$row['id']);
    $mydata->addChild('userid',$row['userid']);
    /*echo(utf8_encode($row['publication']));*/
    $mydata->addChild('publication',utf8_encode($row['publication']));
    $mydata->addChild('time',$row['time']);
    $mydata->addChild('avatar',$row['avatar']);

     }
     echo( json_encode ($json));
    } else {
      echo "0";
    }

A: Well you are not using XML for anything else but convert it to JSON, so there is no need for XML. Use array
$result = $conn->query($sql);
$json = ['publications' => []];

if($result->num_rows > 0)
{
    while($row = $result->fetch_assoc())
    {
        $json['publications'][] = [
            'nom' => $row['nom'],
            'id' => $row['id'],
            'userid' => $row['userid'],
            'publication' => $row['publication'],
            'time' => $row['time'],
            'avatar' => $row['avatar']
        ];
    }
    echo json_encode($json);
}
else
{
    echo "0";
}

A: It's a particluar behaviour of SimpleXML.
If you have one child in xml - you will have an object in json, if you have more than one child - you will get array of objects. So, I advise you to rewrite your code using simple arrays instead of xml-approach:
$result = $conn->query($sql);
$json = [];  // just array

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // add new item
        $json[] = $row;

        // or more specifically
        $json[] = [
            'nom' => $row['nom'],
            'id' => $row['id'],
            // more fields that you need
        ];
    }
}
echo json_encode(['publications' => $json]);


text:
Q: Android sliding tabs - 2 line text on tabs I came across this image online and I was wondering: is it possible to have a two line text view for one of my tabs within my sliding tabs project?

Hello tab error

DeafultTabView code
protected TextView createDefaultTabView(Context context) {
    TextView textView = new TextView(context);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
    textView.setTypeface(Typeface.DEFAULT_BOLD);
    textView.setTextColor(context.getResources().getColor(R.color.black));

    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    textView.setWidth(size.x / 2); // (size.x / number of textviews);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // If we're running on Honeycomb or newer, then we can use the Theme's
        // selectableItemBackground to ensure that the View has a pressed state
        TypedValue outValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
                outValue, true);
        textView.setBackgroundResource(outValue.resourceId);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
        textView.setAllCaps(true);
    }

    int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
    textView.setPadding(padding, padding, padding, padding);

    return textView;
}

A: Use this in the TextView returned from createDefaultTabView() method
myTextView.setText(Html.fromHtml("Line one
Line two"));

set text like this (Generic condition)
private void setCustomText(TextView textView, String[] msg, boolean isSingleLine){
    if(isSingleLine)
        textView.setText(msg[0]);
    else
        textView.setText(TextUtils.join("
", msg));
}


text:
Q: Using node/express/passport, how can I make a user object available to the browser? This is a 'best practices' question. (UPDATED for clarity)
I am trying to find the best way to make my browser-side code adaptive to user attributes, like whether the user is authenticated, an admin, or has certain attributes.
I am creating a static application.  For some valid reasons, I cannot have the pages rendered by the server.  They need to be static; the same pages are served to everyone; so a solution where the server renders pages isn't feasible (please take that as given for the sake of this question).
All of the security of this application is server-side.  All served pages and routes are access-managed by express and passport, verifying authentication from the cookie sent by the browser, and redirecting to /login when authentication fails.  So this isn't about moving security to the browser side; I very much am implementing security server-side;  this is about how to present state to the user.
I am using express-session to store the session id in a cookie.  By default, it only puts the session id in the cookie, and marks it httpOnly, so I can't access it from browser code.
I modified the config of express-session to turn off httpOnly, so I can now see the cookie on the browser via javascript, but it is still just the session id.
What I'd like to be able to do is attach additional, specific information to the session cookie so my pages can decide what to show/hide based on this information.
So the question comes down to:
How do I get express/passport to pass a session cookie with additional, specific user attributes, and how do I read it on the client?

A: You mentioned that you are using passport for authentication so that will be the starting point of my proposed solution.
Remember we invoke done(err) if an exception occurs while trying to connect to our database, otherwise if the user is not found or the passwords do not match, we invoke done(null, false). If successful we invoke done(null, user). This attaches the user object to the request object of express (req.user).
Now that we have that out of the way, this is how we can make the user object attributes available to the user:
app.get('/',function(req, res) {
    res.render('index', {
        // Ternary operator which checks if the user object is empty or not
        username: req.user ? req.user.username: '',
        title: 'Tutorial'
    })
);

I then display the 'username', if a user is logged in the username will not be empty otherwise I display the form:
<%if( !username ) {%>

Signup

Signin

    <%} else {%>

<%= username %>

        <form method="post" action="/posts">
            <input type="text" name="title">

            <textarea name="content"></textarea>

            <input type="submit" value="Post">
        </form>
    <%}%>

You could do the same with an attribute like 'role' for your users and check if the role is an admin or not in your view file. I am not quite sure if this answers your question though, hope it helps.

A: @robertklep's suggestion ended up being what I implemented.
Since express-session intentionally places only a session id it the session cookie, and that appears to be unchangeable, my only route to do this was to place an additional cookie in the response using res.cookie(), and I read that in my client app wherever needed.


text:
Q: Any regexp to transform a single new line to double new lines? For instance:
Foo\n\nBar
Would stay the same, but:
Foo\nBar would change to Foo\n\nBar
I'm looking for a regexp to do this, hopefully it would recognize other forms of new lines like \r and \r\n.

A: "Foo\nBar".gsub(/[\r\n]+/, "\n\n")   # => "Foo\n\nBar"
"Foo\n\nBar".gsub(/[\r\n]+/, "\n\n") # => "Foo\n\nBar"
"Foo\rBar".gsub(/[\r\n]+/, "\n\n")   # => "Foo\n\nBar"
"Foo\r\nBar".gsub(/[\r\n]+/, "\n\n") # => "Foo\n\nBar"


text:
Q: C# - Geocode pharmacy by name and location How can I find the coordinates of a pharmacy by it name and location?
I'm trying to search with the Google geocode API like this:
var pharmacyName = "Farmácia Ereirense";
var address = "Cartaxo, Santarém";

var url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + pharmacyName + ", " + address + "&sensor=false";

but I only got ZERO_RESULTS on the GeoResponse Status, and if I google "Farmácia Ereirense, Cartaxo, Santarém" it found the right location...
I already tried to do:
var pharmacyName = "Farmácia Ereirense";
var address = "Cartaxo, Santarém";

var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?name=" + pharmacyName + ", " + address + "&key=" + apiKey;

but I got the INVALID_REQUEST result.
Documentation I based on

A: Finally I found the solution! We can do a Text Search request like this:
var pharmacyName = "Farmácia Ereirense";
var address = "Cartaxo, Santarém";

var url = "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" + pharmacyName + ", " + address + "&key=" + apiKey;

And it works just fine, like Google's search.
Documentation


text:
Q: How to get length from glue The objective of the following code is to occupy the rest of a line with a parbox. I know this is a wrong way. So, how to get length from glue?
\documentclass{article}
\usepackage{geometry}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\geometry{showframe}
\begin{document}
A B C D\parbox{\hfill}{Fill the rest length of this line with a parbox}
\end{document}

A: As long as one only needs to know the horizontal position on a page, the tabto package can suffice.
\documentclass{article}
\usepackage{geometry,tabto}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\geometry{showframe}
\newlength\tolinened
\begin{document}
A B C D%
\tabto{\linewidth}%
\setlength\tolinened{\dimexpr\linewidth-\TabPrevPos}%
\tabto*{\TabPrevPos}%
\parbox[t]{\tolinened}{Fill the rest length of this line with a parbox
  Fill the rest length of this line with a parbox
  Fill the rest length of this line with a parbox
  Fill the rest length of this line with a parbox
  Fill the rest length of this line with a parbox
  Fill the rest length of this line with a parbox
}
\end{document}

A: You can record a position using \pdfsavepos and use it on a later run:

\documentclass{article}
\usepackage{geometry}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\geometry{showframe}
\def\tx{Fill the rest length of this line with a parbox Fill the rest length of this line with a parbox
Fill the rest length of this line with a parbox Fill the rest length of this line with a parbox
Fill the rest length of this line with a parbox}
\makeatletter
\newcommand\currentpos[1]{%
  \ifcsname length#1\endcsname\else
  \expandafter\gdef\csname length#1\endcsname{0sp}%
  \fi
\pdfsavepos
\write\@auxout{%
  \gdef\expandafter\string\csname length#1\endcsname{\the\pdflastxpos sp}}%
  }
\makeatother
\begin{document}

\noindent X\dotfill X

A B C D \currentpos{a}\parbox[t]{\dimexpr\textwidth-\lengtha+1cm}{\tx}

A B C D E F \currentpos{b}\parbox[t]{\dimexpr\textwidth-\lengthb+1cm}{\tx}

A B C D E F G H \currentpos{c}\parbox[t]{\dimexpr\textwidth-\lengthc+1cm}{\tx}
\end{document}


text:
Q: @OnApplicationStart not working in Play framework I have a class
@OnApplicationStart
public class OnStartManager extends Job{
    private DataGridServiceManager  dataGridServiceManager = null;
    @Override
        public void doJob() {

               dataGridServiceManager = DataGridServiceManagerImpl.getInstance();
       }

}

This is executing when the application starts, but it also executes when i access other pages or even the same page. But i want to execute it only once during the start of the application. What should i do to achieve this.

A: If you are running in DEV mode, Play sometimes automatically restarts the application. This will cause the @OnApplicationStart jobs to be rerun as well. Maybe this is what you are experiencing?
Quote from Jobs section of Play documentation:

When you run the application in DEV mode, the application waits for
  the first HTTP request to start. Moreover when you are in DEV mode,
  the application will sometimes automatically restart when needed.

A: I do processing of some information and storing before my index.html loads. I used the @OnApplicationStart tag for my bootstrap.java file. It works without a sweat.


text:
Q: Insert a mean record in sas using proc sql I want to insert a record of mean into the data set according the identifier variable. The data set is like DS1 and I want to insert a variable if we have more than one pair of a-b values. Such as the target data set would be like DS2. Thanks my friends.
data DS1;
input a b c;
cards;
1 2 23
1 2 43
1 2 23
1 3 55
1 4 48
2 1 43
2 1 56
2 2 34
;
run;

data DS2;
input a b c;
cards;
1 2 23
1 2 43
1 2 23
1 2 27.66
1 3 55
1 4 48
2 1 43
2 1 56
2 1 44.5
2 2 34
;
run;

A: Why SQL? If you're going to request a specific solution it's good to know why.  Here's two methods, one uses a data step and the other is SQL. Essentially the SQL solution calculates the values and UNION ALL appends them into the data set. The DATA STEP calculates the values as it passes through the data set, requiring only one pass through the data, and maintaining the order of the original data set.
data want_datastep;
set ds1;
by a b;
retain sum count;
if first.b then do;
    sum=0;
    count=0;
end;

sum=sum+c;
count+1;

if last.b and not first.b then do;
    output;
    c=sum/count;
    output;
end;
else output;
run;

proc sql;
create table want_sql as
select * from
(select ds1.* from ds1 as ds1
union all
(select ds1_x.a, ds1_x.b, mean(ds1_x.c) as c
from ds1 as ds1_x
group by ds1_x.a, ds1_x.b
having count(ds1_x.b)>1))
order by a, b, c;
quit;


text:
Q: how to implement "server push " on apache-php-mysql machine? here is the question:
    when one user upload something to the server(apache).
the server will " push " the request data to all the users .
  and I don't want to use "ajax" or javascript "timeout reload"。
It costs a lot
  so, Is there any javascript lib can implement the "server push" technology?

A: You could use WebSockets. I, for one, am using long pooling through XMPP, but I think WebSockets looks promising (maybe my next product version will use WebSockets).
See this StackOverflow question for some details regarding WebSockets support.
Implementation wise, you could use a combination of Socket.IO and node.js to achieve the WebSockets "server push". An example of someone doing this can be found here.


text:
Q: Develop conversational chatbot for chinese language in python I want to develop a conversational chatbot for chinese language in python like the user says "你好" which means "hello" in chinese and chatbot respond. i think it will be very difficult to build from scratch and write every expected response for chatbot. i want to find an opensource library to connect with my API which is able to respond to user and do the conservation with the user. i already know about a chatbot developed by Microsoft called "Xiaobing" which is especially developed for chinese people but i don't know if they provide an API for developers or not.There is also another github project called brobot(https://github.com/lizadaly/brobot/)
but i don't know if it provide chinese language support. Any suggestions or guidance from anyone here would be appreciated.

A: Have a look at ChatterBot Python module. It is language independent. Means you can train it with any language.
sample snippet to train your bot.
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

chatbot = ChatBot("bot")    # create an instance of ChatBot and name it.
chatbot.set_trainer(ListTrainer)

data = ["你好",
        "我很高兴认识你"]    # add data for training

chatbot.train(data)        # train the bot

while True:
    try:
        user_input = input("you - ")                 # ask something to bot
        bot_input = chatbot.get_response(user_input)   # get curresponding output from bot
        print("bot - ",bot_input)
    except(KeyboardInterrupt, EOFError, SystemExit):
        break

output:
List Trainer: [####################] 100%
you - 你好
bot -  我很高兴认识你

You can train it with more and more conversations. Just add those conversation in a text file and train with it.
Refer ChatterBot docs for further information on training the data.