Q: Using MouseOver and MouseOut Hi guys im working on my first website and im trying to implement a sliding menu using jquery.
This is what a got so far :
         Show box

When i MouseOver the control my menu slides down but slides back up automatically.
What I would like is to let the user the time to select and option from the menu and if he doesn't, i would like the menu to close as soon as the mouse leaves the control.
Any idea why this isn't working ?
Thanks in advance.

A: Do your stuff without the inline JS, and remember to close the  element and use a ready function
Show box

FIDDLE

A: As you're using jQuery I believe it would be beneficial for you to use something similar to:
$("#box").hover(
   function() {
      //.stop() to prevent propagation
      $(this).stop().animate({"bottom": "200px"}, "fast");
   },
   function() {
      $(this).stop().animate({"bottom": "0px"}, "fast");
   }
);

What this will mean is that whilst the mouse is over the menu, the menu will stay in its open position. When the mouse exits the menu it will close. Obviously change the id, and animation CSS values to suit your needs :)!
Here is a working example:
http://jsfiddle.net/V3PYs/1/

A: Really there is no problem here - the script is doing exactly what you told it to. However, from what I understand, what you want is for the menu to stay open when you leave the "trigger" element if the user's mouse is now over the menu. Try this:

This way, the user is left some time after mousing out of the trigger element to get to the menu. You might need to fiddle with the timeout, but this should work. I tested this and it seems to be working. Just be sure, if necessary, to wrap this in $(document).ready to make sure all elements are loaded and ready.
Demo: http://www.dstrout.net/pub/menu.htm

A: If you're using jQuery this would be the proper way to go about it:
Show box

(just copy/paste this in and it should work)


Q: checking type of reference in generics java I am currently building a game in java(turn based RPG) and am facing a problem in inventory UI. Perhaps my problem is well known or has a simple solution, but having never had any training, I will still ask the question.
While displaying the inventory after selecting an item I check if that item implements the SpecificItemWorker interface , that is, acts on a specific GameObject that has to be passed in to its takeAction() method. While selecting that object which has to be passed, I display all the possible candidate objects for the user to select. For example, suppose the user selects a UpgradeParchment that acts on any object that implements Upgradable interface. Here, I initiate a ItemSelector that displays all the items in the inventory that implements Upgradable. However with a different class , the interface that the object needs to implement in order to be a possible candidate will differ.(Note that some objects act on the game environment rather than on a specific object, but we are not considering that case here.).Now instead of hard-coding the possible interfaces in a switch case statement , i want it to be dynamic.I tried to use generics, but it does not allow to check if an object is an instanceof of the Type parameter.
The following code gives a compile error:
package ui;

import objects.Collectable;

public class ItemSelector<T> {
    public void test(Collectable ob) {
        if (ob instanceof T) {// compile error
            // do work
        }
    }
}

Does anyone know how this can be achieved?Thanks for any help.
Looking for a speedy reply,
Thanks.
EDIT :
The parameter in the testAction() method will be of type Collectable as in my inventory class, there is only a list of Collectable objects.Similarly, in my test method , I have updated the types.Although it is a minor change, sorry for any inconvenience.Collectable is also an interface.

A: Due to runtime type erasure, you need to provide what's called a type token to the class:
public class ItemSelector<T> {
    private final Class<T> clazz;
    public ItemSelector(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void test(GameObject ob) {
        if (clazz.isInstance(ob)) {// use token to check type
            // do work
        }
    }
}

This requires a class object to be passed to the constructor, usually by passing a class literal, eg MyClass.class

A: There is a way to check the type with class.getTypeName().
I assume the SpecificItemWorker is a game object as shown in the code.
package stackoverflow.question39718130;

public class SpecificItemWorker extends GameObject {
}

package stackoverflow.question39718130;

public class ItemSelector<T> {

    private T t;

    public ItemSelector(final T t) {
        this.t = t;
    }

    public T getT() {
        return t;
    }

    public void test(final GameObject ob) {
        /*if (ob instanceof T) {// compile error
            // do work
        }*/

        if (t.getClass().getTypeName() == ob.getClass().getTypeName()) {
            System.out.println("Grab item.");
        } else {
            System.err.println("No item found.");
        }
    }
}

There is a test example to pass the GameObject.
package stackoverflow.question39718130;

public class GameObjectTest {

    public static void main(final String[] args) {
        specificItemWorkerTest();
    }

    public static void specificItemWorkerTest() {
        final GameObject specificItemWorker = new SpecificItemWorker();

        final ItemSelector<GameObject> selector = new ItemSelector<>(specificItemWorker);
        selector.test(specificItemWorker);
    }
}

I hope I understood you right with the SpecificItemWorker. Please let me know if this fits to your solution.


Q: Add custom comparatorClass class in Solr I am newbie in Solr. I want to add a custom comparatorClass in Solr. I also need to use fields - term and count in my custom class which I have defined in my schema.xml.
Structure of indexing document :
"docs": [
      {
        "count": 98,
        "term": "age",
      },
      {
        "count": 6,
        "term": "age assan",
      },
      {
        "count": 5,
        "term": "age but",
      },
      {
        "count": 10,
        "term": "age salman",
      }]

I have stored ngrams with term and their count but solr gives frequency by own that I don't need. I want my count frequency which I have defined for each term. And that term and count, I need to use and want to sort with frequency(count) and then edit distance which I need to implement by creating own class in comparator class or there is something else which helps me. Please share..
How can I do this.  Any help please.
Thanks.

A: You should be able to do this without implementing a custom similarity class. The first requirement is (from your description) a straight forward sort on the count value, while the latter can be implemented by sorting on the value from the strdist() function. You can also multiply or weight these values against each other in a single sort statement by using several functions.
If you really, really need to build your own scorer (which I don't think you need to do from your description) - these are usually written to explore other ranking algorithms than tf/idf, bm25 etc. for larger corpuses, a search on Google gives you many resources with pre-made, easy to adopt solutions. I particularly want to point out "This is the Nuclear Option" in Build Your Own Custom Lucene Query and Scorer:

Unless you just want the educational experience, building a custom Lucene Query should be the “nuclear option” for search relevancy. It’s very fiddly and there are many ins-and-outs. If you’re actually considering this to solve a real problem, you’ve already gone down the following paths [...]


Q: naming uploaded image after username? I am developing using CodeIgniter framework.
I have an image upload folder which permission is set to 755. My host is using suPHP so site users are able to upload to it.
I just noticed that when user uploads an image, the IMAGE file permission is 666.
I am naming the images using usernames so it would be quite easy for someone to guess that someone with username ‘hello’ would have an image stored in that directory named ‘hello.jpg’ or ‘hello.png’
Is this unsafe? Could a malicious visitor do something like erase or replace a member’s image from that image upload directory?
Do I have to name the image something random and then store that random image name into that user’s db table row so I know which image name matches which user?

A: You should always validate any user input of course, but you could in this case simply check that the current user's username matches the name being used as the filename (assuming you authenticate the users prior to allowing them to upload), and ensure they have no means to specify the filename via anything they input.
In short, authenticate, and name your files using known user info', server-side data only.


Q: How to control 1000+ flash app instances? I have a flash app running on 1200 machines on a local network. Currently, the app polls the php server every 10 seconds, and is returned a 14 byte string with the state. If the state is new, the app changes mode and gets new data from the server.
1200 machines polling every 10 seconds to pick up ~8 state changes per day seems like an awful lot of network traffic for this.
There is other traffic on the network (streaming video, web surfing etc). When the network load gets high, some of the machines loose the ability to communicate with the server and hang. When I run 400 machines I don't run into this problem. Looks like a scalability problem.
What would you recommend for lightweight communication between server and 1200 clients? Remoting with AMFast? XML Sockets? Something else entirely?
Thanks very much!

A: Socket communication, and having the server send a message to the clients when the state changes, instead of the clients polling the server, seems like the way to go here. Almost a textbook example for sockets vs polling, I would say.
In applications for public web, socket communication in Flash can sometimes be troublesome because of firewall settings and using other ports than 80 and so on, but in your internal system, it  should work fine.

A: Do you need the state to be a 14 Byte string (14 Bytes is 112-bits which would support 5.19 x 10^33 different status'), are there really that many states that you need to communicate?
How many states do you need to convey?


Q: RestKit Object mapping issue I have this JSON response that I can't figure out how to map. It looks like this:
{
  "responseError": null,
  "displayMenuList": {
    "MenuList": [
      {
        "ID": "3223",
        "Name": "Main",
        "AddressURL": "www.mysite.com",
        "DisplayType": "True",
        "ImageURL": "main.png",
        "NotSplitBUser": "True",
        "ParentCategoryId": "3223",
        "PrivateUser": "True",
        "SortOrder": 1,
        "SplitBUser": "True",
        "TargetURL": "_self"
      },
      {
        "ID": "3307",
        "Name": "Contact",
        "AddressURL": "www.mysite.com",
        "DisplayType": "True",
        "ImageURL": "service.png",
        "NotSplitBUser": "True",
        "ParentCategoryId": "3224",
        "PrivateUser": "True",
        "SortOrder": 0,
        "SplitBUser": "True",
        "TargetURL": "_self"
      },
      {
        "ID": "3298",
        "Name": "Call Us",
        "AddressURL": "www.mysite.com",
        "DisplayType": "True",
        "ImageURL": "service.png",
        "NotSplitBUser": "True",
        "ParentCategoryId": "3224",
        "PrivateUser": "True",
        "SortOrder": 1,
        "SplitBUser": "True",
        "TargetURL": "_self"
      },
      {
        "ID": "3224",
        "Name": "Service",
        "AddressURL": "www.mysite.com",
        "DisplayType": "True",
        "ImageURL": "service.png",
        "NotSplitBUser": "True",
        "ParentCategoryId": "3224",
        "PrivateUser": "True",
        "SortOrder": 2,
        "SplitBUser": "True",
        "TargetURL": "_self"
      }
    ]
  },
  "responseCurrentBillState": null,
  "responseGetPcrfSubBuckets": null,
  "userData": {
    "abroadInd": null,
    "accountType": "B",
    "customerId": "",
    "fullName": "Juan",
    "subscriberNumber": ""
  }
}

I just can't figure out how to map those objects, I've created object called RKSideMenu, also an object called RKUserData they look like this:
@interface RKSideMenu : NSObject
@property (copy, nonatomic) NSString *addressURL;
@property (copy, nonatomic) NSString *displayType;
@property (copy, nonatomic) NSNumber *id_number;
@property (copy, nonatomic) NSString *imageURL;
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) BOOL splitBUser;
+ (NSDictionary*)getAttributes;
@end

@implementation RKSideMenu
+ (NSDictionary*)getAttributes
{
    return [NSDictionary dictionaryWithObjects:@[@"addressURL", @"displayType", @"id_number", @"imageURL", @"name", @"splitBUser"]
                                       forKeys:@[@"AddressURL", @"DisplayType", @"ID", @"ImageURL", @"Name", @"SplitBUser"]];
}
@end

@interface RKUserData : NSObject
@property (copy, nonatomic) NSString *abroadInd;
@property (copy, nonatomic) NSString *accountType;
@property (copy, nonatomic) NSString *customerID;
@property (copy, nonatomic) NSString *fullName;
@property (copy, nonatomic) NSString *subscriberNumber;
+ (NSDictionary*)getAttributes;
@end

@implementation RKUserData
+ (NSDictionary*)getAttributes
{
    return [NSDictionary dictionaryWithObjects:@[@"abroadInd", @"accountType", @"customerID", @"fullName;", @"subscriberNumber"]
                                       forKeys:@[@"abroadInd", @"accountType", @"customerId", @"fullName;", @"subscriberNumber"]];
}
@end

I started mapping with those two methods, but than I stuck and don't know what to do. I look at https://github.com/RestKit/RestKit/wiki/Object-mapping, but still couldn't get it right.
RKObjectMapping *sideMenuMapping = [RKObjectMapping mappingForClass:[RKSideMenu class]];
[sideMenuMapping addAttributeMappingsFromDictionary:[RKSideMenu getAttributes]];

RKObjectMapping *userDataMapping = [RKObjectMapping mappingForClass:[RKUserData class]];
[userDataMapping addAttributeMappingsFromDictionary:[RKUserData getAttributes]];

Thanks in advance!
Edit: Json on top replaced with real json from server.

A: So what you need to do in order to setup your mapping is first of all define the base url of your API, like so:
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"URL_TO_YOUR_API"]];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];

Then you need to set a response descriptor for the url that outputs the json above:
[[RKObjectManager sharedManager] addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:sideMenuMapping
                                                                                method:RKRequestMethodAny
                                                                                pathPattern:@"/mainScreenData"
                                                                                keyPath:@"displayMenuList.MenuList"
                                                                                statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];

"RKRequestMethodAny" should be replaced by the Request Method you are using e.g. "RKRequestMethodGET".
Then you just retrieve the objects by calling:
  [[RKObjectManager sharedManager] getObjectsAtPath:@"/mainScreenData"
                   parameters:nil
                      success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {

                          NSArray *sideMenuList = [NSMutableArray arrayWithArray:[mappingResult array]];
                      }
                      failure:^(RKObjectRequestOperation *operation, NSError *error) {
                          NSLog(@"%@",[error localizedDescription]);
                      }];

I would highly recommend you having a look at the demos that are supplied by RestKit. That makes the whole process a lot clearer.
Cheers,
Sebastian


Q: Scope of "use module" and associated linking error I am trying to navigate my way around fortran 90 and I have this toy example using which I would like to ask a question
module foo
implicit none
contains

subroutine foobar()
print *,'foobar'
end subroutine foobar
end module foo

Then the main program -
program test

use foo

real a,b,c

a = 10.
b= 10.
c= 10.
print *,'hello world'

call abc(a,b,c)
end program test
subroutine abc(a,b,c)

call def(a,b,c)

end subroutine abc

subroutine def(a,b,c)

call foobar()
print *,'def'

end subroutine def

If I do not include the 'use foo' statement in subroutine def I get a linking error while linking test.o and foo.o-undefined reference. Why is that ? By declaring use foo at the 'main' level do the subroutines also not get access to the symbol foo ?
I would  guess not based on the compiler error. So this means the only way to move forward is to include the use foo statement in every subroutine. What is the motivation behind this ?


Q: How to sort an array of numbers which has separator in between? I have an array of numbers each with numbers in both side but a separator between both numbers.For example:
$selectTableRows= array("1_6", "3_4", "10_1", "2_2", "5_7");

I need to sort the array depending on the numbers after the separator "_".Thus, the result should be like,
10_1 , 2_2  , 3_4 , 1_6 , 5_7
Need help in php.
Thank You

A: The solution using usort and explode functions:
$selectTableRows = array("1_6", "3_4", "10_1", "2_2", "5_7");
usort($selectTableRows, function ($a, $b){
    return explode('_', $a)[1] - explode('_', $b)[1];
});

print_r($selectTableRows);

The output:
Array
(
    [0] => 10_1
    [1] => 2_2
    [2] => 3_4
    [3] => 1_6
    [4] => 5_7
)


Q: SAP HANA data provider for Microsoft ado.net I need to connect my C# web application with SAP HANA database using Entity Framework 6. I've got this documentation: obsolete link (possibly, Microsoft Entity Framework Support (SAP HANA Data Provider for Microsoft ADO.NET) may correspond.)
This document explains how to use SAP HANA data provider for Microsoft ado.net. But I unable to find from where could I download SAP HANA data provider for Microsoft ado.net.
Could any one provide me a link for the same?

A: You can get the ado.net driver (+ python, java, etc..) from this address: https://tools.hana.ondemand.com/#hanatools

A: It is part of the SAP HANA client package.
Go to https://service.sap.com/hana, login, then click "Software download", and select your edition. Proceed with "SAP HANA Client 1.00", not with the proposed "Studio".


Q: Why data types was changed while calling the apply function in Pandas? While using the apply function to process a DataFrame, the data type of columns was changed unexpectedly. What should I do to prevent this?
For example:
In [1]: import pandas as pd

In [2]: from pandas import DataFrame

In [3]: tmp = DataFrame({'item':[1,2,3]})

In [4]: tmp['score'] = 0.0

In [5]: tmp.dtypes
Out[5]:
item       int64
score    float64
dtype: object

In [6]: tmp
Out[6]:
   item  score
0     1    0.0
1     2    0.0
2     3    0.0

In [7]: def Test(x):
   ...:     return x
   ...:

In [8]: tmp = tmp.apply(Test,axis=1)

In [9]: tmp.dtypes
Out[9]:
item     float64
score    float64
dtype: object

The data type of tmp['item'] was changed into float. How to maintain the original data type of it?

A: This is happening because .apply essentially iterates over rows (when axis=1) and applies the function to a Series that represents each row. Since Series must contain the same data type, a Series made from a row of mixed int and float types will properly promote ints to float:
In [4]: def test(x): return x

In [5]: tmp.iloc[0]
Out[5]:
item     1.0
score    0.0
Name: 0, dtype: float64

In [6]: tmp.apply(test, axis=1)
Out[6]:
   item  score
0   1.0    0.0
1   2.0    0.0
2   3.0    0.0

Note what happens when we select a column, though:
In [7]: tmp.iloc[:,0]
Out[7]:
0    1
1    2
2    3
Name: item, dtype: int64

In [8]: tmp.apply(test, axis=0)
Out[8]:
   item  score
0     1    0.0
1     2    0.0
2     3    0.0


Q: Compute the maximum-coverage path in an Occupancy Grid I am implementing a basic robot which uses a SLAM algorithm to produce an occupancy grid of it's environment. It is very simple with no probabilistic aspect, simply an enum to represent Empty, Occupied, Unexplored, Unreachable etc.
I was wondering if there is a well known algorithm to find the shortest path necessary to visit all of the grid cells once (it's a Vacuum cleaner!). Is this the Travelling Salesman Problem?
I have researched a couple of solutions based on Graphs, for example finding Hamiltonian Cycles, but i wondered if there was anything which efficiently worked on Grids directly.
The grid will be around 250x250 cells.
Thanks!

A: Just thought id add my solution to this unanswered question - Most algorithms I tried out were just too computationally complex. I settled on an approximation of the maximum-coverage path which was quite efficiently computed using the reverse wavefront algorithm.
Using this algorithm I was able to construct a maximum-coverage path of a 250x250 array of grid cells in around 5 seconds, which was certainly acceptable in my scenario.


Q: Check if the image and file type exist inside directory This is my code:
$file = 'images/img_' . $post->_id . '.jpg'; // images/img_1.jpg
    if (file_exists($file) && is_file($file)) {
                //show the image
                echo '';
            }
            else {
                // show default image
                echo '';
            }

What this basicly does is to check if the an image (eg img_1.jpg) exist in my images folder and display it, if not it shows a default image.
This works fine, the only problem, as you probably 've seen, is that it checks only the .jpg files and not *.gif or *.png too (the file could also be img_1.gif or img_1.png, right? ) .
How can I make sure that it will check against all valid file types too and show the file with the correct format?

A: You could loop through an array of file extensions and check them i've made a sample script to show what i mean listed below
$array = array('.jpg','.png','.gif');
foreach($array as $key => $value){

    $file = 'images/img_' . $post->_id . $value; // images/img_1.jpg
    if (file_exists($file) && is_file($file)) {
       $filefound = '';
    }
}

if(isset($filefound)){
    echo $filefound;
}else{
    echo '';
}

A: The most efficient way to do this is probably to store the extension in the database, that way you're not scanning your file system for matches.
However, you could also use the glob();; function and check if results has anything.
$result = glob('images/img_' . $post->_id . '.*');
If you want to further narrow down your extension types you can do that like this:
$result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE)
New code might look something like this (untested but you get the idea):
$result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE);

if(!empty($result)) {
    //show the image
    echo '';
} else {
    // show default image
    echo '';
}

A: It is obvious that your script will check only for .jpg not for others because you have written statically the file extension.
$file = 'images/img_' . $post->_id . '.jpg';
                                         ^

Now Make change in this line to make available the extension dynamically. I am supposing that you are storing  the image name with extension than:
   $file = 'images/img_' . $post->_id . $post->image_name;

Note : $post->image_name should be like :
$post->image_name = abc.png (image_name.extension);


Q: What is the importance of watch command in ExtJS I am using ExtJS 5 to create a web application.
I am also using sencha app build command to create the production build.
During development I never use sencha app watch or sencha app build commands. I just do the changes in the application code and in our web server's(tomcat) server.xml file I have given context path of the application code root folder. I just start the tomcat server and load the context by giving the context path.
Now i want to know what is the use of sencha app watch command and what are the benefits that developer is going to get using watch command.

A: Well, besides providing a web server, the watch command does two main things:

*

*it rebuilds your bootstrap.js file continuously.

*it provides a Fashion server

If you're trying to change the CSS for your app, by introducing a custom theme, then using Fashion and sencha app watch is a massive time saver.
You can also use Tomcat and sencha app watch in parallel, by making your Tomcat instance a proxy to the sencha app watch version.


Q: how to write cell array to text file MATLAB, error with dlmwrite I understand that this is a recurrent topic, I have tried understanding the answers that people provided but none of them seemed easy to transfer to my particular problem as the solutions are usually for an implementation that is too far from what I'm trying to do
Could anyone help with the following.
When I run the code below I get:
Error using dlmwrite (line 118)
The input cell array cannot be converted to a matrix.
Error in GAVNeuroScan (line 25)
dlmwrite(outputfile, CondRowDone);
I give an example of what I want to achieve in the comments at the end of the code.
If someone can help me getting the contents of CondRowDone to a text file as exemplified in the comments that would be great!
studyname='TestGav';

subjects={'504','505'};

conditions={'HighLabel','LowLabel','HighSound','LowSound'};

nCond=4;

GFPorBMR='GFP';

for curCond=1:length(conditions)

    for curSubject=1:length(subjects)

        gavRow{curSubject}=[subjects(curSubject) '-' conditions{curCond} '-' GFPorBMR '.avg'];
    end

       CondRowDone{curCond,:}=['GROUPAVG' '{' gavRow '}' 'G Y 1 N N' conditions{curCond} 'avg.'];

end

outputfile = [studyname '_GAV_' curSubject '.txt'];
dlmwrite(outputfile, CondRowDone);

% What I want is a text file that would look exactly like that. I think I'm
% not far but it fails to write...
%
% GROUPAVG {{HighLabel-504-GFP.avg} {HighLabel-505-GFP.avg}} G Y 1 N N {HighLabel.avg}
% GROUPAVG {{LowLabel-504-GFP.avg} {LowLabel-505-GFP.avg}} G Y 1 N N {LowLabel.avg}
% GROUPAVG {{HighSound-504-GFP.avg} {HighSound-505-GFP.avg}} G Y 1 N N {HighSound.avg}
% GROUPAVG {{LowSound-504-GFP.avg} {LowSound-505-GFP.avg}} G Y 1 N N {LowSound.avg}

A: From what I have seen using the debugger, you have a little bit of confusion between the curly braces as text and the curly braces to handle MATLAB cell arrays.
Here is a re-write of your for-loop to produce the cell array of strings you have given in your code example. Also, to produce the exact output you specified, subject and condition have to be given in a different order:
for curCond=1:length(conditions)
    gavRow = [];

    for curSubject=1:length(subjects)

        if (curSubject ~= 1)
            gavRow = [gavRow ' '];
        end

        gavRow = [gavRow '{' [conditions{curCond} '-' subjects{curSubject} '-' GFPorBMR '.avg'] '}'];
    end

    CondRowDone{curCond}=['GROUPAVG ' '{' gavRow '} ' 'G Y 1 N N {' conditions{curCond} '.avg}'];

end

As for the task of writing the strings to disk, MATLAB is telling you that it cannot handle your cell array as a matrix. When it comes to write cell arrays to disk, I think you have to write it yourself using low-level functions, like this:
outputfile = [studyname '_GAV_' curSubject '.txt'];

fid = fopen(outputfile, 'w');
for i=1:length(CondRowDone)
    fprintf(fid, '%s\n', CondRowDone{i});
end
fclose(fid);

A: dlmwrite only handles numeric data. One way around this, if you have Excel, would be to use xlswrite - it can take in (some kinds of) cell arrays directly.
xlswrite(outputfile, CondRowDone);
Then, do some batch xls to csv conversion (for example, see this question and answers). To get a text file directly you'll need to use lower level commands (as in blackbird's answer).


Q: Security Best Practices for Email-based User Registration? I have a website, and want to register new users.  The registration process is as follows:

*

*User enters email address, clicks 'Register'

*email address is sent to server

*Server generates a registration code, stores a hashed version

*Server sends an email containing a link:  confirm?code=<reg_code>

*User checks email, clicks link

*Server receives request, confirms validity of code

*Server stores email address as a user id

*Server issues token, stores token, sends response with token

*User's browser stores token as a cookie

*Cookie is used as a Bearer token for authentication in subsequent requests.

I was wondering if there is any way to improve the security of this approach.  Here are some considerations:

*

*Manual cut-and-paste of code, with session-id check

In step 4, instead of providing a link confirm?code=<reg_code>, the email could contain a link to a 'code submission' page which says "Please cut-and-paste the code in your email here, and click submit".  This way, javascript could grab a session cookie that was previously generated and stored during step 1.  Then, the server could validate that the session cookies match between requests.

*

*2FA

After the user clicks the original email link, the system could ask for a second factor confirmation.
It seems that the Manual cut-and-paste with session-id check takes care of a stolen email scenario, because that would fail the session-id check.
And, 2FA requires the hacker to hack a second channel, or to steal a device.  Both of these measures seem extremely secure.
However, the Manual cut-and-paste is onerous for the user, and the 2FA is annoying because it must ask the user for a phone number or to install some authenticator app.
Is there any other way?


Q: How do I set credentials for Symfony plugins? I have a backend with SfGuard, and I have plugins like sfGuard, which have modules. How do I change their security settings? they don't have folders in my backend app where I could put a security.yml.

A: Create module which you would like to secure, for example
/app/backend/modules/sfGuardRegister

After that you can secure the module with creating
/module_path/config/security.yml

and configure credentials.
I have not tryed that beheivour with security.yml, but I've rewroten the templates, actions, components. It should work.


Q: How to pass List through activities ArrayList<Item> arrayOfList;

I want to pass arrayOfList; to next activity on Itemclick of listview
Tried Things
    Intent sec = new Intent(this, IndividualPage.class);
    Bundle b = new Bundle();
    b.putParcelableArrayList("mylist", arrayOfList);
    sec.putExtras(b);

To retrieve the arraylist
        Bundle b = this.getIntent().getExtras();
        ArrayList<Item> cats = b.getParcelableArrayList("mylist");
        System.out.println(cats);

But i am getting null in console.
Is there any other efficient way to pass the data.
Item.java
public class Item implements Parcelable {
private String Name;
private String Location;
private String Image;
private String Sector;
private int Founded;
private String Status;
private int RowVAls;

public String getName() {
    return Name;
}

public void setName(String Name) {
    this.Name = Name;
}

public String getLocation() {
    return Location;
}

public void setLocation(String Location) {
    this.Location = Location;
}

public String getImage() {
    //return "http://23.253.164.20:8099/"+Image;
    return "http://23.253.164.20:8099/"+Image;
}

public void setImage(String Image) {
    this.Image = Image;
}

public String getSector() {
    return Sector;
}

public void setSector(String Sector) {
    this.Sector = Sector;
}

public int getFounded() {
    return Founded;
}

public void setFounded(int Founded) {
    this.Founded = Founded;
}

public String getStatus() {
    return Status;
}

public void setStatus(String Status) {
    this.Status = Status;
}

public int getRowVAls() {
    return RowVAls;
}

public void setRowVAls(int RowVAls) {
    this.RowVAls = RowVAls;
}

protected Item(Parcel in) {
        Name = in.readString();
        Location = in.readString();
        Image = in.readString();
        Sector = in.readString();
        Founded = in.readInt();
        Status = in.readString();
        RowVAls = in.readInt();
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() {
        @Override
        public Item createFromParcel(Parcel in) {
            return new Item(in);
        }

        @Override
        public Item[] newArray(int size) {
            return new Item[size];
        }
    };

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(Name);
    dest.writeString(Location);
    dest.writeString(Image);
    dest.writeString(Sector);
    dest.writeInt(Founded);
    dest.writeString(Status);
    dest.writeInt(RowVAls);
}

Note:- Item is neither Parcelable nor Serializable .
And i would not like to make any changes in that.

A: You should make your Item implement Parcelable. Try this site to make your Item Parcelable

A:
Item is neither Parcelable nor Serializable . And i would not like to
  make any changes in that.

then you can't. I would strongly recommend you to look into the Parcelable interface, avoiding tricks like making the field public static

A: As others have said, you can't do it properly without implementing parcelable - which sometimes isn't possible.
You're only other option is to architect a way in which you can put your list in a static context so it's accessible from wherever.
You could create a singleton SparseArray and related integer, and pass around the integer between activities describing the position in the SparseArray. You'd just have to ensure that you incremented your integer and removed the item from the SparseArray once you'd grabbed it. Off the top of my head -
private class ComplexObjectPassing {
    private static SparseArray<Object> sArray = new SparseArray<Object>();
    private static int count = 0;

    public static int putObject(Object obj) {
        count++;
        sArray.put(count, obj);
    }

    public static Object getObject(int index) {
        Object obj = sArray.get(index);
        sArray.put(index, null);
        return obj;
    }
}

Obviously, this would end with a huge memory leak when you passed things and they weren't pulled out by the new activity. All of the alternatives are going to have downsides and need to be carefully managed to reduce inevitable problems.


Q: Creating a java program that calculates fares for a toll road I am having a hard time getting started with this program. It is supposed to promped user for vehichle typ, number of miles to be traveled, and whether or not they have an EZ-Pass. then calculate and print vehicle type, number of miles traveled, whether or not they have an EZ-Pass, and the fare collected.
toll road spans 76.4 miles.
Fares for the toll road are calculated based on vehicle type:
Motorcycle – Flat Fee of $1.06
Car - $0.05 per mile
SUV - $0.08 per mile
Truck - $0.14 per mile
Vehicles having an E-ZPass attached to them earn a 10% discount off their fare.
After the user has indicated they wish to exit the program (this is the only way the program should exit), the program will display a report containing a list of each vehicle type and the number of fares collected for that vehicle type, the total number of vehicles, the number of vehicles that used an E-ZPass, and the total fare collected across all vehicles.
I tried using if statements but wasn't happy with the result, maybe for statements fit it better?
Thanks for reading

A: Try starting with a defining diagram that helps you identify the problem you're trying to solve, continuing through the remaining steps of the problem solving process. This will yield a much better result than jumping immediately to coding and posting algorithm questions on Internet forums (which by the way, violates the Honor Code).
Good luck!


Q: when sending strings via put extra the underline under some words has gone when I send strings via put extra the underlined words will not be underlined
<string name="s_hello_txt">\n{ hello all }\n</string>

MainActivity Button Code
public void c_hello(View v){
    Intent hello= new Intent(MainActivity.this,
            MainTextActivity.class);
    intent_collection_e3tiraf.putExtra("key",getResources().getString(R.string.s_hello_txt));
    startActivity(hello);
    finish();
}

MainActivityText onCreate Code
textview = (TextView) findViewById(R.id.id_text_txt);
    Intent n = getIntent();
    String mrng = n.getStringExtra("key");
    textview.setText(mrng);

if I put a text with direct string it will be underlined
For Example if I put in the layout of MainActivityText(activity_maintext.xml)
<TextView
    android:id="@+id/id_dailyprayers_txt"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/s_hello_txt"
    android:textSize="30sp" />

the textview in MainActivityText Show the text(hello all) underlined
any help!!!!

A: As long as the string still has the underline html you should be able to utilize the Html.fromHtml method to style the string.
textview.setText(Html.fromHtml(mrng));

A: Actually, the string getResource().getString(R.string.s_hello_txt) is not be underlined.
The best way to add html source code in strings.xml is to use <![CDATA[html source code]]>. Here is an example:
<string name="s_hello_txt"><![CDATA[Text]]></string>

And then use Html.fromHtml(mrng) to show the underlined string

A: // Try This One This Will Help For Your Acheivement
**String.xml**
 <string name="s_hello_txt"><br/>{ <u>hello all</u> }<br/></string>

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

   <TextView
       android:id="@+id/txtValue"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/s_hello_txt"/>

   <Button
       android:id="@+id/btnClick"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="GoTo Second Activity"/>

</LinearLayout>

**MainActivity1 Activity**
public class MainActivity1 extends Activity {

    private Button btnClick;
    private TextView txtValue;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        txtValue = (TextView)findViewById(R.id.txtValue);
        btnClick = (Button)findViewById(R.id.btnClick);

        txtValue.setText(Html.fromHtml(getString(R.string.s_hello_txt)));
        btnClick.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(MainActivity1.this, MainActivity2.class);
                intent.putExtra("EXTRA",getString(R.string.s_hello_txt));
                startActivity(intent);
            }
        });
    }

}

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

    <TextView
        android:id="@+id/txtValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

**MainActivity2 Activity**
public class MainActivity2 extends Activity {

    private TextView txtValue;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        txtValue = (TextView)findViewById(R.id.txtValue);

        txtValue.setText(Html.fromHtml(getIntent().getStringExtra("EXTRA")));

    }

}


Q: IPython import error - pattern I'm a newbie to IPython/Anaconda (for Windows 7), and for some reason, I'm getting an import error:
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-6-484073d472a5> in <module>()
      6 import matplotlib.pyplot as plt
      7 import requests
----> 8 import pattern

ImportError: No module named pattern

Here's what I did to set up Anaconda/IPython:

*

*Installed Anaconda. I already have a version of python on this computer. The Anaconda distribution was installed to C:\Users\MyName, while the regular python distribution (2.7) was installed to C:\Python27.

*When I tried to import some packages (sklearn, pandas, requests, pattern), for some reason those packages just wouldn't import so I installed them manually (downloading them to a local folder on my desktop and running $ python setup.py install, and after that it all seemed to work).

*I can run IPython notebooks fine. However, when I try to import pattern specifically, I get that error (which I don't get for sklearn or any of the other packages I installed manually). Printing my sys path from the terminal (import sys print sys.path) and IPython notebook gives:
Terminal:
    ['C:\\Users\\MyName\\Desktop\\Data Science\\cs109\\Labs', 'C:\\python27\\lib\\site-
    packages\\mrjob-0.4.2_dev-py2.7.egg', 'C:\\python27\\lib\\site-
    packages\\simplejson-3.3.1-
    py2.7.egg', 'C:\\python27\\lib\\site-packages\\pyyaml-3.10-py2.7-win32.egg',
    'C:\\python27\\lib\\site-packages\\boto-2.18.0-py2.7.egg',
    'C:\\python27\\lib\\site-packages\\requests-2.0.1-py2.7.egg',
    'C:\\Windows\\system32\\python27.zip',
    'C:\\Python27\\lib\\site-packages\\Orange\\orng', 'C:\\python27\\DLLs',
    'C:\\python27\\lib', 'C:\\python27\\lib\\plat-win', 'C:\\python27\\lib\\lib-tk',
    'C:\\python27', 'C:\\python27\\lib\\site-packages', 'C:\\python27\\lib\\site-
    packages\\PIL', 'C:\\python27\\lib\\site-packages\\win32',
    'C:\\python27\\lib\\site-
    packages\\win32\\lib', 'C:\\python27\\lib\\site-packages\\Pythonwin']

IPython notebook:
    ['', 'C:\\Users\\MyName\\Anaconda\\python27.zip', 'C:\\Python27\\lib\\site-
    packages\\Orange\\orng', 'C:\\Users\\MyName\\Anaconda\\DLLs',
    'C:\\Users\\MyName\\Anaconda\\lib', 'C:\\Users\\MyName\\Anaconda\\lib\\plat-win',
    'C:\\Users\\MyName\\Anaconda\\lib\\lib-tk', 'C:\\Users\\MyName\\Anaconda',
    'C:\\Users\\MyName\\Anaconda\\lib\\site-packages',
    'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\PIL',
    'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\win32',
    'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\win32\\lib',
    'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\Pythonwin',
    'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-
    info', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\IPython\\extensions']

If I do
    import pattern
    print pattern

It shows that pattern is located at:
    C:\python27\lib\site-packages\pattern\__init.pyc

Any thoughts as to why IPython can't import pattern?

A: I struggled with this - I kept getting an error saying package couldn't be found.
Running below in command prompt worked for me.
conda install -c asmeurer pattern=2.5

A: On windows, open cmd.exe and type:
conda install pattern

This should do it ;)

A: Sometimes this happens when you have multiple versions of Python/Anaconda installed on your machine. As the Pattern package does not run on Python 3.4, you need to launch IPython Notebook from the Anaconda server that runs Python 2.7.
So the first step is to make sure that you install the Pattern package using pip in the version of Anaconda that runs Python 2.7.
For example, C:\Users\MyName\Anaconda\Scripts\pip install pattern
The second step is to make sure that you run ipython notebook from the correct path.
For example, C:\Users\MyName\Anaconda\Scripts\ipython notebook
That should do it.


Q: How to pass operators like "<",">","=" (less than,greater than,equals to) as parameters to a native query in springboot? For example let my query be as shown below:
String query="select * from table_name where column_name1 > ?1 and column_name2 < ?2";

@Query(value = query, nativeQuery = true)
public List<Object[]> getResult(String filterValue1,Integer filterValue2);

how to pass the operator(<,>,=) also as a parameter?
I am using postgreSQL database.
Thank you.

A: If you have an option to construct/concat a String prior to run the query, there is no problem:
public String methodOne(String firstOperator
, String secondOperator) {
return "select * from table_name where column_name1 "
+ firstOperator + " ?1 and column_name2 "
 + secondOperator +" ?2";
}

It is more complicated if you use SpringData repositories.
There isn't a lot you can do with native queries parameters because SpringData is looking for native SQL operators inside the query string. But you can try to do some tricks with LIKE operator and built-in functions (in SQL, sometimes >,< can be replaced with LIKE)
(not completely an answer to your question, but)
A condition that can be omitted
 @Query(value =
... AND column_name LIKE IIF(:myParam <> '%', :myParam,'%')
<skipped>

... repositoryMethod(@Param("myParam") String myParam);

IIF - a ternary operator function in MSSQL, you can find something like this in your RDBMS
when you send myParam='actualValue' it will be transformed into
and column_name LIKE 'actualValue'

i.e. column_name='actualValue'
when you send myParam='%' it will be transformed into
and column_name LIKE '%'

i.e. "and TRUE"


Q: video-stabilization


Q: Wordpress Pagination not work in category page I want to display pagination on category pages of WordPress theme
This is my code

    global $post;
    $category = get_the_category($post->ID);
    $category = $category[0]->cat_ID;
    $posts = get_posts(array(
        'numberposts' => 150,
        'posts_per_page'=>16,
        'offset' => 0,
        'category__not_inint' => array($category),
        'post_status'=>'publish',
        'order'=>'ASC'
    ));

  foreach($posts as $post){
        setup_postdata($post);

        $city_name = get_field( "city-name" );

        $display = '' . $city_name . '';
    }

    the_posts_pagination();
    wp_reset_query();
    return $display;

and displays the pagination. But the results of all pages are similar to the first page.

A: You shouldn't be using get_posts if you need the query to be paginated.
Whilst it can be done, this is a total ball ache to achieve. Instead, you should be looking at WP_Query.
Further reading on WP_Query - WP_Query @ wordpress.org
Your code could look something like the following;
<?php
$paged = (get_query_var('page')) ? get_query_var('page') : 1; // explain to wordpress we need this paged
$wp_query = new WP_Query(array( // the query
'post_type' => 'post',
'post_category' => '',
'post_status' => 'publish',
'numberposts' => 150,
'posts_per_page' => 15,
//'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged));

while ($wp_query->have_posts()) : $wp_query->the_post(); // the loop

// some code to make it look pretty
?>

<a href="<?php the_permalink(); ?>">

<?php the_title(); ?>

<?php endwhile;

echo ( paginate_links($args = array(
'base'         => site_url().'%_%', // site_url prefix is needed for pagination on homepage
'format'       => '?page=%#%',
'total'        => $wp_query->max_num_pages,
'current'      => $paged,
'show_all'     => false,
'end_size'     => 2,
'mid_size'     => 2,
'prev_next'    => true,
'prev_text'    => 'Prev',
'next_text'    => 'Next',
'type'         => 'list',
'add_args'     => false,
'add_fragment' => ''
 )));

wp_reset_query();


Q: Why when i debug my value option tag html is undefined? I've tried debugging the following error for several hours with no solution JS is still undefined but id parameter in controller has a value. Please help. I need it.
This html code when i debug, the value is undefined, why the value is undefined?
<select id="cmbTipe" class="form-control">
                <option value="-1">Select Jenis</option>
                <option value="undefined">undefined</option>
                <option value="undefined">undefined</option>
            </select>

My Controller
namespace PerhitunganKeuntunganParkir.Controllers{

public class ParkirController : Controller
{
    private readonly JenisKendaraanRepository _jeniskendaraanRepository = null;
    private readonly TipeKendaraanRepository _tipekendaraanRepository = null;
    private readonly ParkirContext _context = null;

    //Dependency Injection
    public ParkirController(JenisKendaraanRepository jenisKendaraanRepository, TipeKendaraanRepository tipeKendaraanRepository, ParkirContext context)
    {
        _jeniskendaraanRepository = jenisKendaraanRepository;
        _tipekendaraanRepository = tipeKendaraanRepository;
        _context = context;
    }

    public async Task<ViewResult> GetAllJenis()
    {
        ViewBag.Jenis = await _jeniskendaraanRepository.GetJenisKendaraan();

        return View();
    }

    public IActionResult LoadTipeC(int jenisId)
    {

        return Json(_context.TipeKendaraan.Where(s=>s.JenisKendaraanId ==
            jenisId).Select(s=> new TipeKendaraanModel{
                Id = s.Id,
                Tipe=s.Tipe

        }).ToList());
    }

My View
In HTML my cascading dropdown the value is undefined, why does this happen? The JavaScript is working but the value is undefined in HTML
@{
    ViewData["Title"] = "Input Form";

@model JenisKendaraanModel

    <form method="post" asp-action="GetAllJenis" asp-controller="Parkir">

            <select id="cmbJenis" class="form-control">
                <option value="-1">Select Jenis</option>
                @foreach (var jenis in ViewBag.Jenis)
                {
                    <option value="@jenis.Id">@jenis.Jenis</option>
                }
            </select>

            <select id="cmbTipe" class="form-control">
            </select>

    </form>

A: After my test, I found that your problem may lie in your Js.
Try to change your code:
 for (var i = 0; i < result.length; i++)
{
  s += '<option value="' + result[i].Id + '">' + result[i].Tipe + '</option>';
}

To
for (var i = 0; i < result.length; i++)
{
  s += '<option value="' + result[i].id + '">' + result[i].tipe + '</option>';
}

id and tipe the first letter should be lowercase.


Q: change output directory of nuget package I created a NuGet package from my project. The output directory of the package is the solution directory. I would like to output it to a specific directory. I tried a target in the csproj file and in the nuspec file. None worked. How do I get the package generated in the specified folder?
In my .csproj:
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
  <PropertyGroup>
    <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
  </PropertyGroup>
  <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

In my .nuspec:
<?xml version="1.0"?>
<package >
  <metadata>
    <id>MyPackage.dll</id>
    <version>1.0.0</version>
    <authors>me</authors>
    <owners>me</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Package description</description>
    <releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
    <copyright>Copyright 2016</copyright>
    <files>
      <file src="bin\MyPackage.dll" target="C:\LocalPackageRepository" />
    </files>
  </metadata>
</package>

A: In the 'old' way of NuGet (which you seem to use, check this for info on new vs old) this was possible by using the command in the .nuget\NuGet.targets file you mention. If you change the line with PackageOutputDir to below it will work.
<PackageOutputDir Condition="$(PackageOutputDir) == ''">C:\LocalPackageRepository</PackageOutputDir>

Even better would be to set a property on the PropertyGroup in the .csproj like this:
<PackageOutputDir>C:\LocalPackageRepository</PackageOutputDir>

In the new way of NuGet you would add this key to the NuGet.config file:
<add key="repositoryPath" value="C:\LocalPackageRepository" />

A: Not sure why the global config settings didn't work for me, but adding below solution solved my problem:

*

*Create an environment variable under user variables:

Variable name: MyNugetsOutput
Variable value: D:\myteam\teampackages

*

*Then add below settings to .csproj file:

<Target Name="CopyPackage" AfterTargets="Pack">
  <Copy SourceFiles="$(OutputPath)\$(PackageId).$(PackageVersion).nupkg"
        DestinationFolder="$(MyNugetsOutput)\$(PackageId).$(PackageVersion).nupkg" />
</Target>

reference: Target build order
Update
Currently I'm using below code, it is simpler but it copies all .nupkg files to the "Local" path
<Target Name="AfterPack" AfterTargets="Pack">
    <Exec Command="dotnet nuget push $(PackageOutputPath)*.nupkg --source Local" />
</Target>

A: You cannot do this from the .nuspec file. You can create a NuGet.Config file and define a global packages directory for all solutions:
<configuration>
  <config>
    <add key="repositoryPath" value="C:\myteam\teampackages" />
  </config>
  ...
</configuration>

This is done outside  the .nupkg file and stored either under your profile or in a subdirectory which is a parent to all the directories containing your solutions. See the NuGet documentation for more details on this feature.


Q: When does a javascript function is being executed in a jquery mobile page? I have a php function that, after it did his computations, contains this code:
echo("<script> window.location.replace('index.php#login'); </script>");

meant to redirect the page to another, under certain circumstances. The function works, the javascript code works, but if fails in one case. If i write manually the address of the page the javascript part of the code seems not to be executed, while if i manually reload the page (for example using the reload button in firefox) works like a charm.
The php function is being executed, with his redirect code, at the beginning of the page index.php in the head section. The page index php is a jquery mobile page, that include every other page of the site, so if i want to call a page, i have to write an address like site.com/index.php#nameOfThePage. The problem happen when i am, for example on a page site.com/index.php#Page1 and i call another Page manually deleting from the address the part "Page1" and writing, for instance, "Page2". Instead, if i reload, the script is being correctly executed.
So the question is: when does a javascript function is being executed in a jquery mobile page? What i have to do to make the function works in every way, even manually, a page is called?
EDIT: the problem happens in firefox e safari, while with chrome the code works in every case...


Q: Trying to email photo attachment without edit screen I'm trying to send an email with a photo attachment without showing the editor.  Eventually I'm trying to make it so when someone logs into the app it will send them an email automatically.
My implementation:
if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {
    videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
    //initiates a still image and returns
    //samplebugger data was captured
    stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
        if (sampleBuffer != nil) {
            var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
            //creates core graphics image
            var dataProvider = CGDataProviderCreateWithCFData(imageData)
            var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)

            var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)

            //saves image after taken
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

            var myController =  MFMailComposeViewController()
            myController.mailComposeDelegate = self
            myController.setSubject(" Your Sherpa Photo")
            myController.setMessageBody("hello World", isHTML: false)
            myController.setToRecipients(["keli5466@colorado.edu"])

            var emailimageData =  UIImagePNGRepresentation(image)
            myController.addAttachmentData(emailimageData, mimeType: "image/png", fileName: "image")
            self.presentViewController(myController, animated: true, completion: nil)
        }
    })
}

// ...

func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
    if result.value == MFMailComposeResultSent.value {
        let alertView = UIAlertView()
        alertView.message = "Mail Sent!"
        alertView.addButtonWithTitle("OK")

        alertView.show()
    }

    self.dismissViewControllerAnimated(false, completion: nil)
}

A: Short answer: You can't do that, by design. The only way you can send email without display a compose mail view controller is if you have a server that offers mail services, but you will have to collect the user's mail credentials.
Apple does not want 3rd party developers sending email from a user's account with the user being the one to click the button and do the sending. This protects the user from apps sending mail without the user's knowledge or permission.
Imagine the explosion of spam if this restriction was not in place.


Q: List of classes and indices for my trained neural network model in keras I have trained the MNIST dataset using the code from https://www.kaggle.com/code/himanshuyadav95627/image-classification, and the model is working perfectly. Now I want to extract the class names and indices from the trained model. Why I need this: I am trying to produce a heatmap. The MNIST data set has handwritten images of the numbers 0 to 9. I believe the classes here will be 0 to 9.
My code:
jsn_model = model.to_json()# here model is my trained NN model and I am converting to json format
clasdf = pd.read_json(jsn_model) # convert it to a dataframe
print(clasdf['class_name'])

present output:
layers    Sequential
name      Sequential
Name: class_name, dtype: object

Expected output:
 Class names 0 to 9 and indices 0 to 9 or 1 to 10

For instance, an example class and indices for a known dataset
https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json


Q: Worksheet Change: Multiple target values not working Need to hide/ unhide rows in a multiple excel sheets based on dropdown cell values in a cell of another sheet.
I have 3 sheets, Dashbaord, Data Inputs, Metrics table,
I have put the following code in Dashboard sheet. The 3 cells mentioned below are dropdown and contain different set of values.
When a user selects one value say in dropdown C4, I'm hiding/ unhiding  certain rows in all the 3 sheets mentioned above. But only the select case of cell C4 works fine. As you can see I have formulas for C23 and C32 as well, but it doesn't seem to work, not sure it is due to operations on same sheets
Another example, when say I select a dropdown value for Cell C23. The operations listed under C23 below works fine (respective macro is called and rows are hidden/ unhidden). But when I check the earlier selection on Cell value C4 is gone.
Please help
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range
If Not Intersect(Target, Range("C4,C23,C32")) Is Nothing Then

For Each c In Intersect(Target, Range("C4,C23,C32"))
    Select Case c.Address(0, 0)

        Case "C4"
            If Target.Value = "Ecommerce" Then Call Ecommerce
            If Target.Value = "Non-Commerce" Then Call NonCommerce
            If Target.Value = "Ecommerce & Non-Commerce" Then Call Both
            If Target.Value = "Select Ecommerce/Non-Commerce" Then Call Both

        Case "C23"
            If Target.Value = "Select Year" Then Call SelectYear
            If Target.Value = "2020" Then Call Twentytwenty
            If Target.Value = "2021" Then Call TwentyOne
            If Target.Value = "2022" Then Call TwentyTwo
            If Target.Value = "2023" Then Call TwentyThree
            If Target.Value = "2024" Then Call TwentyFour
            If Target.Value = "2025" Then Call TwentyFive

        Case "C32"
            If Target.Value = "Select PPC" Then Call SelectPPC
            If Target.Value = "PPC 2" Then Call PPCTwo
            If Target.Value = "PPC 3" Then Call PPCThree
            If Target.Value = "PPC 4" Then Call PPCFour
            If Target.Value = "PPC 5" Then Call PPCFive
            If Target.Value = "PPC 6" Then Call PPCSix
            If Target.Value = "PPC 7" Then Call PPCSeven

        End Select
Next c
End If
End Sub

I want the sheet to operate on all the 3 cells together, right now its broken and only one works at a time. Appreciate your help.

A: Reading the comments, it sounds like every time you select a different value from one of the three drop downs, you want to run three macros, depending on the values selected.  If that is the case, then you don't need to iterate through the Target cells (only one can be assigned, using the drop down anyway).
All you need to do is identify that one of the three cells has been changed and then based on the three specific cells, run the corresponding macros.
Private Sub Worksheet_Change(ByVal Target As Range)
    ' This is all that you have to check, before deciding to run the macros
    If Intersect(Target, Range("C4,C23,C32")) Is Nothing Then Exit Sub

    Select Case Range("C4").Value
    Case "Ecommerce"
        Call Ecommerce
    Case "Non-Commerce"
        Call NonCommerce
    Case "Ecommerce & Non-Commerce", "Select Ecommerce/Non-Commerce"
        Both
    End Select

    Select Case Range("C23").Value
    Case "Select Year"
        Call SelectYear
    Case "2020"
        Call Twentytwenty
    Case "2021"
        Call TwentyOne
    Case "2022"
        Call TwentyTwo
    Case "2023"
        Call TwentyThree
    Case "2024"
        Call TwentyFour
    Case "2025"
        Call TwentyFive
    End Select

    Select Case Range("C32").Value
    Case "Select PPC"
        Call SelectPPC
    Case "PPC 2"
        Call PPCTwo
    Case "PPC 3"
        Call PPCThree
    Case "PPC 4"
        Call PPCFour
    Case "PPC 5"
        Call PPCFive
    Case "PPC 6"
        Call PPCSix
    Case "PPC 7"
        Call PPCSeven
    End Select
End Sub

Or better yet, listen to BruceWayne and you end up with something like this:
Private Sub Worksheet_Change(ByVal Target As Range)
    ' This is all that you have to check, before deciding to run the macros
    If Intersect(Target, Range("C4,C23,C32")) Is Nothing Then Exit Sub

    Select Case Range("C4").Value
    Case "Ecommerce"
        Ecommerce
    Case "Non-Commerce"
        NonCommerce
    Case "Ecommerce & Non-Commerce", "Select Ecommerce/Non-Commerce"
        Both
    End Select

    If IsNumeric(Range("C23").Value) Then SelectYear CInt(Range("C23").Value)

    If IsNumeric(Mid(Range("C32").Value, 5)) Then SelectPPC CInt(Mid(Range("C32").Value, 5))
End Sub

Sub SelectYear(Year As Integer)
    ' Do stuff
End Sub

Sub SelectPPC(Value As Integer)
    ' Do stuff
End Sub

FYI, You don't really need to use Call.  The only real difference that it makes is whether parenthesis are required or not, when a Sub-routine has parameters.


Q: Check if any of the textboxes is empty wpf Is there any way to iterate through all the textboxes to see if any of the textboxes is empty? I want the user to enter values in all textboxes. Suppose the event handler has the following code:
private void Add_Click(object sender, RoutedEventArgs e)
        {
            //check if textboxes are empty
            if (/*logic here for checking*/)

                MessageBox.Show("Please enter values in all the fields");
            else
            {//send values entered to other window.
                Window1 w1 = new Window1(customername.Text, "", "", "", Phoneno.Text, Symptoms.Text, Total.Text, datepick);

                this.Hide();
                this.Owner.Show();

            }
        }

A: This code should work:
private void Add_Click(object sender, RoutedEventArgs e)
{
    if (gridcontrol.Children
        .OfType<TextBox>()
        .Any(tb => string.IsNullOrEmpty(tb.Text)))
    {
        MessageBox.Show("Please enter values in all the fields");
    }
    else
    {
        ...
    }
}


Q: Error handling with loop and user input For i = 1 To repNumber
    TryAgain:
    On Error GoTo ErrH:

    repName = InputBox("Enter rep name you want to exclude.", "Name of Rep")
    .PivotItems(repName).Visible = False
Next i

ErrH:
        MsgBox "Try Again"
        GoTo TryAgain:

It shows an error if I type in Rep name that doesn't exist in the PivotTable. So I'm trying to use an error handler to let a user type Rep name again.
But after the second time I type something wrong, instead of going to the  error handler, the code terminates itself.
I'm not sure if 'On Error GoTo' is in the wrong line.

A: You can avoid Error Handing and GoTo statements all together (which is definitely best practice) by testing within the code itself and using If blocks and Do loops (et. al.).
See this code which should accomplish the same thing:
Dim pf As PivotField, pi As PivotItem
Set pf = PivotTables(1).PivotField("myField") 'adjust to your needs

For i = 1 To repNumber

    Do

        Dim bFound As Boolean
        bFound = False

        repName = InputBox("Enter rep name you want to exclude.", "Name of Rep")

        For Each pi In pf.PivotItems

            If pi.Value = repName Then
                pi.Visible = False
                bFound = True
                Exit For
            End If

        Next pi

    Loop Until bFound = True

Next i

A: Try Resume TryAgain instead of GoTo TryAgain.
(You don't need : in these statements, it is by coincidence allowed because it is also used to seperate multiple statements within a line, so it is just meaningless here).


Q: App engine - raw request body - stripe webhooks I'm trying to run my node.js app app engine and I am having trouble with stripe webhooks - with the constructEvent, that I need to give a request raw body. Worked on virtual machine but not on app engine.
event = stripe.webhooks.constructEvent(req.rawBody, sig, stripeKeys.webhookPaymentIntent);

Says:
No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing

A: Just looking at the code that you posted here, I wonder if the last parameter is indeed the value that you wanted to pass to the constructEvent function. it reads webHookPaymentIntent. I wonder if this should really be the webhook signature secret? It may be that it really is the webhook secret value, but just named a bit misleadingly.
Maybe this is something though you can verify? A simple test would really to be to pass the string literal here to see if that would work first. Of course make sure not to commit that to any source control.
The stripe-node method params are listed here for reference: https://github.com/stripe/stripe-node/blob/1d6207e34f978d8709d42d8a05d7d7e8be6599c7/lib/Webhooks.js#L11


Q: Facebook public profile without graph api I am making a testimonial for a website and i want a user to login through facbook so that i can save his profile picture and name etc in my database
Is there any code of facebook that we can get picture and public information of the user without graph api and facebook app?
Cz now facebook need https to make a app.

A:
Is there any code of facebook that we can get picture and public information of the user without graph api and facebook app?

No.
The Graph API is the basis of any automated communication with Facebook’s systems, and an app id is the basis of using the API.

Cz now facebook need https to make a app.

Rightfully so. You should not compromise your users’ security and privacy by not using HTTPS any more these days, especially if any kind of “login” is involved.
Getting a certificate doesn’t have to cost you much any more - Let’s Encrypt is widely available.


Q: How to get JSON data from php webservice : "no value for data" error I am new to the Android Platform and I want to fetch value's from a PHP Web Service through JSON Parser. But I am not getting the data, rather the error: No value for data25 ,data26 and data27.
I appreciate any help sorting out this problem.
try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++)
            {
            HashMap<String, String> map = new HashMap<String, String>();

              JSONObject json_data = jArray.getJSONObject(i);

            map.put("data25", "date25:" + json_data.getString("data25"));
            map.put("data26", "data26:" + json_data.getString("data26"));
            map.put("data27", "data27:" + json_data.getString("data27"));

            mylist.add(map);

            }

The JSON result is as follows:
[
{
    "data1": "5794",
    "data2": "2922",
    "data3": "6799",
    "data4": "2729",
    "data5": "9860",
    "data6": "4486",
    "data7": "9903",
    "data8": "0113",
    "data9": "9936",
    "data10": "5470",
    "data11": "7423",
    "data12": "1237",
    "data13": "6564",
    "data14": "1261",
    "data15": "4730",
    "data16": "7714",
    "data17": "2410",
    "data18": "7486",
    "data19": "7046",
    "data20": "8263",
    "data21": "4305",
    "data22": "6244",
    "data23": "2495",
    "data24": " 19\/09\/2012(Wed)"
},
{
    "data1": "555",
    "data2": "039",
    "data3": "353",
    "data4": "1438",
    "data5": "8720",
    "data6": "7490",
    "data7": "1294",
    "data8": "4000",
    "data9": "6017",
    "data10": "2294",
    "data11": "4042",
    "data12": "0064",
    "data13": "8441",
    "data14": "1252",
    "data15": "9609",
    "data16": "0797",
    "data17": "1680",
    "data18": "0917",
    "data19": "7492",
    "data20": "9488",
    "data21": "3253",
    "data22": "7915",
    "data23": "1071",
    "data24": " 19\/09\/2012(Wed)",
    //--heredata25,
    data26,
    data27----------"data25": "9555",
    "data26": "3039",
    "data27": "6353"
},
{
    "data1": "0395",
    "data2": "5928",
    "data3": "8998",
    "data4": "6447",
    "data5": "1827",
    "data6": "8131",
    "data7": "7454",
    "data8": "4647",
    "data9": "1892",
    "data10": "3656",
    "data11": "1989",
    "data12": "9095",
    "data13": "6826",
    "data14": "1860",
    "data15": "9766",
    "data16": "6069",
    "data17": "6050",
    "data18": "6526",
    "data19": "8392",
    "data20": "0520",
    "data21": "7540",
    "data22": "3608",
    "data23": "7430",
    "data24": " 19\/09\/2012(Wed)"
},

A: As per the response you have posted, it is a JSONArray of JSONObjects. Each JSONObject contains the values with the keys like data1, data2...etch. But every JSONObject doesn't contain the keys data25, data26, data27. If you don't want to throw exception even the response does n't contain the data25,data26, data27 keys in every JSONObject then you need to modify the code like below:
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++)
        {
        HashMap<String, String> map = new HashMap<String, String>();

          // getJSONObject() will throw exception if the key is not found in the jsonObject. Instead of it use optJSONObject() to get the values from JSONObject. It returns the value if contains otherwise returns the empty jsonObject.
          // JSONObject json_data = jArray.getJSONObject(i);
          JSONObject json_data = jArray.optJSONObject(i);

        //map.put("data25", "date25:" + json_data.getString("data25"));
         map.put("data25", "date25:" + json_data.optString("data25")); // returns empty string on not finding the key in JSONObject.

        //map.put("data26", "data26:" + json_data.getString("data26"));
        //map.put("data27", "data27:" + json_data.getString("data27"));

        mylist.add(map);

        }


Q: How to decompress tar.gz file with low memory usage [php 7]? I have a 4 gb tar.gz file i'd like to decompress into a tar file. I've been using
$p = new PharData('/path/to/file/name');
$p->decompress();

to try and do so. However I get an error 'PHP Fatal error:  Allowed memory size of 8589934592 bytes exhausted (tried to allocate 36864 bytes)'
Things I've tried:
(1) ini_set('memory_limit', '-1');
Result: Generic 'Killed' error message
(2) ini_set('memory_limit', '6000M');
Result: 'PHP Fatal error:  Allowed memory size of 8589934592 bytes exhausted (tried to allocate 36864 bytes)' error message
I've also gone into the php.ini file to make the same changes. How can I decompress the tar.gz file into a tar file?

A: Apparently the phar:// stream wrapper will allow you to read the CSV file contents directly out of the gzipped TAR.
$fh = fopen('phar://example.tar.gz/target_file.csv', 'r');

while( $row = fgetcsv($fh) ) {
    // code!
}

This should leverage PHP's stream goodness so that reading from the file doesn't require more than a few kilobytes actually reside in memory at a given time.
That said, if you start just appending rows to an array in that loop you're going to have the same memory problems. Do something with the row, and then discard it.


Q: Import different openapi.json file to spring boot app I have custom openapi.json file and empty spring boot app. When I start the app I want it to import that file and show it in swagger-ui URL.
I couldn't find how to do it. All answers were how to generate openapi.json file from code. But my task is opposite.


Q: EXTJS 4.1.1. iframes reloads when switching tabs in TabPanel on Firefox: I've got a problem with PDF's in the TabPanel (only on Firefox). They are reloading everytime I switch tabs. The PDF is in a iframe.
Because of it the user can not compare two PDF files. When you click a tab with a PDF it loads 10 seconds, then you switch to a second tab and it also loads 10 seconds and so on....
I know this problem with Firefox has been around for years (which relates IFRAME, OBJECT, elements, FF reinitializes the objects, if their size changes).
It cannot be that there is no solution for this problem.
However, I have not found any for Extjs4 yet.
It would be great if someone could help me with it.


Q: Javascript regex to strip selective html tags I am trying to strip all (except some) html tags from a string using regex. What I am trying currently trying is as follows:
var a = "

This is a test

";
var b = a.replace(/(\<|\<\/)[^\>,p,li,br,b]*\>/ig,"");

but b's value is returned as "

This is a test

"
It seems any tags that contain even a single instance of [>,p,li,br,b] are not being removed, as here all pre, span and p contains the character p. However, I only want to ignore the exact characters in [^\>,p,li,br,b].
The output I am expecting is "
This is a test
".
what am I doing wrong ?

A: var a = "

This is a test

";
var b = a.replace(/\<(?!\/?(p|li|br|b)[ >])[^>]*\>/ig,"");

This regex matches the leading < or </ only if it is not followed by one of the tag names you want to keep p, li, br, b (followed by a space or closing >, so that it doesn't think
 is
).
Then it matches everything up to the closing >.

A: See this answer.
That said, square brackets [] match on single characters, not words - for more information on what yours is doing, see the bottom of this answer.  Instead, you would need to use parentheses (?:p|li|br|b) to match words - the ?: is used to avoid capturing.  Also, the parentheses would occur outside of the square brackets.
Since you're using a negative match you may wish to look into lookarounds; specifically, the section on Positive and Negative Lookbehind.

[^\>,p,li,br,b] translates to not > and not , and not p and not , and not l and not i and not , and not b and not r and not , and not b.


Q: Difficulty deploying lumen app I'm trying to deploy a small application to my remote server, however, I seem to be having difficulty with some of the routes.  Bare in mind that everything works on my local machine.
Here is what I've done:

*

*Uploaded the entire project to /home/user/app

*Moved contents of /home/user/app/public to /home/user/public_html/api

*Modified /home/user/public_html/api/index.php from:

$app->run();
to
$request = Illuminate\Http\Request::capture();
$app->run($request);

...this allowed my first route to work, but I cannot load any other routes such as:
http://www.mywebsite.com/api/v1/book
Please note that only http://www.mywebsite.com/api is the only route that loads correctly.
My routes.php looks like this:
$app->get('/', function() use ($app) {
    return "Lumen RESTful API";
});

$app->group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers'], function($app)
{
    $app->get('book','BookController@index');

    $app->get('book/{id}','BookController@getbook');

    $app->post('book','BookController@createBook');

    $app->put('book/{id}','BookController@updateBook');

    $app->delete('book/{id}','BookController@deleteBook');
});

My .htaccess is as follows:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

The error I am receiving:

Let me know if you need any more information?
Any help would be greatly appreciated!

A: Change route group prefix to:
$app->group(['prefix' => 'v1'


Q: How does the onDraw(Canvas) function of the View class work? I need to implement an interactive graph in Android
For a start I am trying to see how this code works
There, in a class called LineChartView Which extends the user generated class ChartView which extends the View class, there is an @overrideed function called onDraw(Canvas canvas). How and when does this function get called? the output of that code is a bunch of graphs on full screen, but my interactive graph should only take up a part of the screen. Does the onDraw() function get called automatically? If so, when? And what is the size of the canvas? Is it always the full screen occupied by the current activity's window?

A: in this link View Android Developer there is a section on implementing a custom view
onDraw(Canvas canvas) is called whenever a view should render its content
if you define to use this view in your layout xml or even in code you can specify the attributes
android:layout_width=
android:layout_height=

and those attributes will be applied to the size that the view will use
in your layout.xml
<your.package.name.extendedviewclass
android:layout_width="100dp"
android:layout_height="100dp"/>


Q: Javascript uncaugh error in promise even with a catch With Javascript, I am trying to make a call to an external API when a form is submited.
I am using promises in order to set follow up actions once the call is done and to catch eventual errors.
This is where my problem is, even if I think I am catching my errors correctly, the console throws an

Uncaught (in promise) error : [The error I throw]

I do not understand why.
Here is a minimal version of my code which would reproduce the error when the refreshToken is expired :
try {
        functionGeneratingTheError();
    } catch (error) {
        doSomethingElse();
    }

function functionGeneratingTheError() {

    var getTokenCallPayload = {
        "client_id" : clientId,
        "client_secret" : clientSecret,
        "refresh_token" : refreshToken,
        "grant_type" : "refresh_token"
    };
    var getTokenCallOptions = {
        "method" : "POST",
        "body" : JSON.stringify(getTokenCallPayload),
        "muteHttpExceptions" : false
    };
    fetch(tokenURL, getTokenCallOptions)
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error("Error");
        }
    })
    .then(data => {
        doSomething();
    })
    .then(response=> {
        doSomethingAgain();
    })
    .catch(error => {
        throw error;
    });
}

If I understand correctly, when the fetch is a bad request, it should throw the error "Error" which should then be caught in the first catch and run the doSomethingElse() function.
However, instead of doing that, I get this error in the browser console "Uncaught (in promise) Error: Error"
What am I doing wrong ?
I have tried including the fetch in a try{}catch(){} but it doesn't change anything.
I also tried not throwing the error and directly call my doSomethingElse() function, but then the following .then fails because data is undefined.

A: Change your functionGeneratingTheError function to return the chained promise like below:
function functionGeneratingTheError() {

    var getTokenCallPayload = {
        "client_id" : clientId,
        "client_secret" : clientSecret,
        "refresh_token" : refreshToken,
        "grant_type" : "refresh_token"
    };
    var getTokenCallOptions = {
        "method" : "POST",
        "body" : JSON.stringify(getTokenCallPayload),
        "muteHttpExceptions" : false
    };

    return
    fetch(tokenURL, getTokenCallOptions)
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error("Error");
        }
    })
    .then(data => {
        doSomething();
    })
    .then(response=> {
        doSomethingAgain();
    })
    .catch(error => {
        throw error;
    });
}

And then await it in your calling code by wrapping the calling code inside an async self invoking function like so:
(async function() {
try {
        await functionGeneratingTheError();
    } catch (error) {
        doSomethingElse();
    }
})();

You can read more about async/await here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


Q: $.ajax not loading data data everytime from server I have written a simple jQuery.ajax function which loads a user control from the server on click of a button. The first time I click the button, it goes to the server and gets me the user control. But each subsequent click of the same button does not goes to the server to fetch me the user control.
Since my user control fetches data from db, I need to reload the user control everytime i hit the button. But if anyhow I get my user control to unload from the page, and re-click the button, it goes to the server and fetches me the user control. Here's the code:

$("#btnLoad").click(function() {
    if ($(this).attr("value") == "Load Control") {
 $.ajax({
  url: "AJAXHandler.ashx",
  data: { "lt": "loadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });
 $(this).attr("value", "Unload Control");
    }
    else {
 $.ajax({
  url: "AJAXHandler.ashx",
  data: { "lt": "unloadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });
 $(this).attr("value", "Load Control");
    }
});

Please let me know if there is any other way I can get my user control loaded from server everytime I click the button.

A: Add a cache property with the value false to the objects you pass to jQuery.ajax.
 $.ajax({
  url: "AJAXHandler.ashx",
  cache: false,
  data: { "lt": "loadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });

You can set this globally by:
jQuery.ajaxSetup({
    cache: false
});

jQuery will used cached responses for anything except SCRIPT/ JSONP by default.

A: If your btnLoad is inside the user control you're reloading, you need to do this instead:
$("#btnLoad").live('click', function() {

When loading ajax, you're replacing the elements, and any event handlers bound directly to them.  If you use .live() instead, it won't be destroyed as part of the callback...it works differently and the event handler lives higher in the DOM, so it doesn't get blown aware with the button itself.


Q: Mikrotik Router Management via Web App I need help in building a project. Let me first describe my project -
I want to build a Web application (using php / php framework(laravel) , html, css, javaScript, bootstrarp ) that will help ISP owner to manage their router (most of them use Mikrotik router).
Reason to build this App:
Most ISP provider here use Mikrotik router to manage their internet business. But managing the router using Winbox ( a desktop based windows software that is build to manage Mikrotik router) seems complex to them. Just for creating new ip to assign a new user, blocking a user if he/she do not pay bills and managing bandwidth they need to operate winbox every time which they find difficult. My approach is to build a web application that will ease their work.
The features I want to provide are-

*

*Creating new IP address and addressing them to user (internet user / end user)

*Manage bandwidth of an IP address

*Block / Lock any particular IP address automatically (in this case any particular user) who have not paid their monthly bill on certain date of a month

*Re-enabling blocked IP address on paying their dues automatically

*Showing daily graph of bandwidth received and used

*Recording client history (client IP address, Monthly rent, Name, Address etc.)

*Recording payment history of client

*Auto bill calculation / due calculation

*Auto sort out of due users of months

I am able to do 6 - 9  features as described but I have no idea how to implement 1 - 5 features !
Problem That I am facing :
a. I don't know how to connect to a MikrotiK router via web application
b. If some how i can access to the MikrotiK router using router IP address , I don't know how to create new IP address on that router database
c. how to manage bandwidth via web application
d. how to block / lock ip address !
Points I get myself :
I think using management vlan (router Ip address) i can access to that router form command promt using ssh/telnet. After that what would be the command to create, lock/block, manage bandwidth of an IP address ? IF all this things can be done using command prompt, how can I make it for my web application ?
Can anyone please help me with this, referring any link?? I googled but only thing I find is Mikrotik router management manual !

A: I did part of what you are asking for a customer weeks ago. Your question is to broad, very extensive, it will take months to accomplishes the job.
Start your project with the basic that you can find at http://wiki.mikrotik.com/wiki/API_PHP_class, then you can grow your application and post specific questions about your problems in places like stackoverflow or reddit.
Follow a sample to connect to the API, then execute commands and then disconnect.
$API = new RouterosAPI();
$API->debug = true; // turn debug on to learn more about your api
if ($API->connect($server , $username , $passwd, $port)) {

    // wireless registration table
    $API->write('/interface/wireless/registration-table/print',false);
    $API->write('=stats=');
    // print output here

} else {

    // connection fails
}
$API->disconnect();

Ref.:

*

*https://www.reddit.com/r/mikrotik/

*http://wiki.mikrotik.com/wiki/API_PHP_class

A: You should either use APIs or a remote command protocols like ssh/telnet(PHP-SSH2).
This is a PHP API project you could use:
https://github.com/BenMenking/routeros-api
After connecting you can commit commands just like you do on mikrotik console.
Mikrotik commands wiki

A: In my opinion you better use Radius server with database on MySQL. Mikrotik works perfect with Radius. In application implement interface with the database and all interaction with Mikrotik leaves to Radius. Read about FreeRadius for example:
https://www.howtoforge.com/authentication-authorization-and-accounting-with-freeradius-and-mysql-backend-and-webbased-management-with-daloradius


Q: system.diagnostics.contracts.contract exists in both v4.0 v3.5 I just upgraded to visual studio 2010 and installed the code contracts msi.  When I try to use it I get a compiler error that the system.diagnostics.contracts.contract dll exists in both the v3.5 and v4 framework.  Anyone know what I should do to resolve this?  Thanks.

A: If you're upgrading a .NET 3.5 project that uses contracts to .NET 4.0, make sure you remove your reference to the Microsoft.Contracts assembly.
The Microsoft.Contracts assembly provides code contracts for use in .NET 2.0 or 3.5 projects, but is provided by default with .NET 4.0 in mscorlib, so you don't need it. They both share the System.Diagnostics.Contracts namespace, so by having references to both at the same time, the compiler isn't able to figure out which one you're trying to use.

A: I solved it by first installing it, thou that did not actually solve it.
Then removed the references and then I changed the project versions to 4.5 and after that, it worked.


Q: can't list files in a directory I'm using CF 7 and this code is not returning any files:
<cfset fileLocation = "\\server\uploader\pass-fail">
<cfdirectory
  action = "list"
  directory = fileLocation
  name = "pass_fail_files"
  >

     <cfdump var="#pass_fail_files#" expand="yes"   label="files in pass-fail" >

     <cfoutput>#pass_fail_files.name#</cfoutput>
     <cfoutput>#pass_fail_files.directory#</cfoutput>
     <cfoutput>#pass_fail_files.size#</cfoutput>
     <cfoutput>#pass_fail_files.type#</cfoutput>
     <cfoutput>#pass_fail_files.dateLastModified#</cfoutput>
     <cfoutput>#pass_fail_files.attributes#</cfoutput>
     <cfoutput>#pass_fail_files.mode# </cfoutput>

I have checked to make sure that the directory indeed has several text files.  But when I run the code, all I get is:
alt text http://img682.imageshack.us/img682/5603/nofiles.png
What am I doing wrong?

A: I've just tried this:
<cfset fileLocation = "\\192.168.8.20\websites">
<cfdirectory
  action = "list"
  directory = "#fileLocation#"
  name = "pass_fail_files"
  >
<cfdump var="#pass_fail_files#" expand="yes"   label="files in pass-fail" >

On CF7, CF8 and Railo, and works everytime.
Notice I updated your code so it uses the directory attribute as directory = "#fileLocation#" as opposed to directory = fileLocation.
Trying your code, I never got results, but didn't get errors either. Changing it to use double-quotes and hashes did the trick, as it stopped using it as a variable.
Hope it helps you.

A: My first question would be, does the ColdFusion Service User have read access on folder?
Actually, I think your code should be

<cfdirectory
  action = "list"
  directory = "#fileLocation#"
  name = "pass_fail_files"
  >

I think right now, you're telling it to look in a directory named "fileLocation".

A: Assuming you've done all the latest CF7 updates/patches/hotfixes..


Q: Redirect POST-request in apache I'm trying to do a transparent redirect of a post-request in my apache server.
The request looks like this:
POST www.domain.com//maincontroller.php/api

I want to redirect this to:
POST www.domain.com/maincontroller.php/api

I don't want a 301 redirect but instead a silent redirect (edit the Post address and send it to httpd).
Everything I tried with mod_rewrite didn't rewrite the POST, but successfully rewrote a GET.

A: Coworker found it !
    RewriteCond %{THE_REQUEST} POST
    RewriteCond %{THE_REQUEST} ^[A-Z]+\s//+(.*)\sHTTP/[0-9.]+$ [OR]
    RewriteCond %{THE_REQUEST} ^[A-Z]+\s(.*/)/+\sHTTP/[0-9.]+$
    RewriteRule .* http://%{HTTP_HOST}/%1 [P]


Q: Django Session Form (save form temporarily) I have created a page for review form. All users can fill out the form, but only logged in users can submit the form. If users is not logged in, they will be redirected to the login page. After they login, they will be redirected to the profile page.
So the flow will be like this  :
User fills out the form > click the submit > redirected to login page > user login and redirected to profile page (at the same time, the form they have filled in is automatically saved)
I want the form they have filled in automatically saved after they login. How to do that?
My idea is to create a session that saves the form temporarily, then save to database after they login. But I'm confused how to write the code
Can anyone explain a bit what a django session is like? and how to write code to handle this problem?

A: You can try something like,

1 User fills out the form and hits submit

2 in the POST view where you handle the form, use the "**is_authenticated**" function and,
    a)if the user is authenticated you handle the form as usual...
    b)else set the contents of the form into a session variable in the views and redirect to the login page like,

request.session['review_body'] = request.post.get(the_form_body_field)

3 as per what you've said, after login it goes to profile page and form is submitted...
    a)so in views where you serve the profile page, check if the session variable containing form data's exist and has values
    b)if yes, directly save the contents from your views and clear the session data


Q: Chef - Returning a variable from powershell script I would like to know if there is a way to return a variable value from a powershell script defined in powershell_script resource?
My powershell resource looks like following:
powershell_script "Test Script" do
  code <<-EOH
    Write-Host "Hello World!"
   return "test"
  EOH
end

I would like to use the returned value test from the script to use in other resources based on if conditions.
Thanks

A: Ohai!
I think you actually want to use the PowershellOut Mixin found here in the Powershell cookbook.
Chef resources rarely return values, but that's what heavy-weight resources are for!
If you have the powershell cookbook, you can do this:
include Chef::Mixin::PowershellOut
cmd = powershell_out!('command')
cmd.stdout #=> ...
cmd.stderr #=> ...

A: We actually came across this exact issue and solved it by writing our own Mixlib to get the exit code from a powershell script. Example:
# get the result object (and exit code) from the code execution:
result = Mixlibrary::Core::Shell.windows_script_out(:powershell, mycode)
exit_status = result.exitstatus

@carpNick is planning on open-sourcing this perhaps as soon as this week....at the moment it only handles powershell, but we plan on implementing support for other types as well (bash, win modules, etc.) -- which should be fairly easy to add on support for others.
We are currently using it in-house and it works great. I'm sure Chef will want to review Nick's excellent code once he gets it out there. We are just waiting on legal to tell us what open-source license to use.
Ask Nick for more details... @carpnick | https://github.com/carpnick


Q: add record via has_many with default scope Records are added with default scope, but not with required.
class PostsTag
  # published is false by default
end

class Post
  has_many :posts_tags

  {published: true, private: false}.each do |key, val|
    has_many "#{key}_tags",
      through: "posts_tags",
      conditions: ["posts_tags.published = ?", val],
      source: :tag
  end
end

#--------------------

Post.first.published_tags << Tag.first
Post.first.published_tags.count # = 0
Post.first.private_tags.count # = 1

What do I wrongly? Thanks for advance.

A: Inserting a new Tag into published_tags does not set its published attribute to true by default.
What you need to do is to extend the published_tags association and override the << method of it to set the published attribute to true upon insertion. The code will look something like that:
has_many :published_tags do
  def <<(tag)
    tag.published = true
    proxy_association.owner.posts_tags+= [tag]
  end
end

I've written a full working example of exactly this case here, you should definitely have a look at it to get some more insights.