text:
Q: Access denied to Temporary ASP.NET Files folder after iisreset when browsing site using the server's own Internet Explorer Configuration:

*

*Windows Server 2008 R2/IIS 7.5

*ASP.NET web application using Windows Integrated Authentication. Application pool identity is set to NetworkService. Targeting .NET Framework 2.0. Managed Pipeline mode = Classic.

*Full permissions granted to the Temporary ASP.NET Files folder for the Users group and the Internet Guest Account

*Logged into server as a test user account (let's call it testuser) which is a member of the Administrators group

*User Account Control is on

*Internet Enhanced Security is off

*Internet Explorer is using all the default security settings and all Compatibility View settings are off
Now I do the following:

*

*iisreset.exe

*clear Temporary ASP.NET Files folder

*open Internet Explorer

*browse to the local ASP.NET web site => success

*close Internet Explorer

*iisreset.exe

*open Internet Explorer

*browse to the local ASP.NET web site => FAIL
So far, I have found a few things I can do to keep the site working after an iisreset.exe (each of these work individually, i.e. they do not have to be combined):

*

*Turn off User Account Control

*Log in as the Administrator

*Run Internet Explorer "As Administrator..." (instead of defaulting to the testuser account)

*Use Google Chrome or Mozilla Firefox instead of Internet Explorer(?!?) Those two browsers do not have to be run using the Administrator account but work perfectly well running under the user account and with User Account Control turned on.

*Browse the site using an Internet Explorer instance running on an external machine
This problem does not exist on Windows Server 2003. It would appear to be related to User Account Control somehow.
It makes no difference if the user is a member of the Administrators group or not.
Using Process Monitor, it would appear that the access denied problem happens when NetworkService (w3wp.exe) is impersonating the user, but given all the permissions granted to the Temporary ASP.NET Files folder, this still does not make much sense.
The question is:
Why does this only occur with the local Internet Explorer browser, running as a non-administrator user? I would like to use the local Internet Explorer browser for testing, but having to clear the Temporary ASP.NET Files folder after an iisreset is annoying.
What makes Internet Explorer different from Chrome or Firefox (which both work) in this scenario? I could understand if this was something that affected all local browsers, but this is not the case.
I could understand if my web application was doing something special when detecting that Internet Explorer is being used as the client browser, but I do not believe that to be the case and we are talking about an assembly binding failure here - I am not trying to access some arbitrary folder.
EDIT:

*

*The tests above were done using Internet Explorer 8. I have since tried Internet Explorer 9 on the same machine, but with the same results.

*If I enable ASP.NET Impersonation for the web site, the problem goes away - but I still would like to know why it does not work for a local Internet Explorer when ASP.NET Impersonation is disabled.
EDIT 2:
What I failed to mention the first time around is that logging in is a two-step process: When accessing the application (let's call it "MyWebApp"), you are redirected to a MyWebApp/Login directory where you will be prompted for your Windows credentials before granted access to the login page residing in that Login directory.
This always works.
After entering your application credentials (in case the code in the login page does not recognize your Windows credentials), you are redirected to a page in the root folder.
The Authentication settings for MyWebApp and MyWebApp/Login are as follows:
                             MyWebApp         MyWebApp/Login
                             --------         --------------
Anonymous Authentication     Enabled          Disabled
ASP.NET Impersonation        Disabled         Enabled
Basic Authentication         Disabled         Disabled
Digest Authentication        Disabled         Disabled
Forms Authentication         Enabled          Enabled
Windows Authentication       Enabled          Enabled

In both cases, I am getting the "Challenge-based and login redirect-based authentication cannot be used simultaneously" warning.
These settings date back to before I got involved with the project, but that is besides the point. Right now I am only interested in what it takes to get it right - preferably a set of settings that will work for IIS 6.0 and 7.x alike.
Setting ASP.NET Impersonation = Disabled for "MyWebApp/Login" appears to be another way of making my problem go away, but clearly there is more to be done here.

A: The issue is almost certainly related to Internet Explorer using Windows authentication rather than Basic Authentication (what you'd likely get with FF or Chrome).  The combination of Windows authentication and ASP.NET impersonation.  If you enable NTLM authentication in Firefox, you will likely see the same behavior there.  Likewise, disabling Windows authentication (forcing IE to use basic) or disabling impersonation will likely cause IE to behave like Firefox.

A: I cannot imagine that browsers have anything to do with it, but if you experienced differences, it must be true.
For ASP.NET to be able to compile an ASPX file, 2 things are imported (as we found out today:

*

*Write access to the ASP.NET Temporary files dir (where the compiled DLL is written)

*Write access to the Windows TEMP (where csc.exe writes intermediate files like *.obj)

Which user should have acces there? Depends. In our case the Application Pool user. In your case maybe the impersonated user. Or the IUSR. To me, that part is still obscure.


text:
Q: SWIFT: Troubles Modifying Some Parse Columns/ For Some Users. != ACL To start this is not an ACL issue.
I am having troubles adding and removing objects to some users this way:
PFUser.currentUser()!["Key"].addObject(object)
  etc... and actually any other way present in Parse documentation.
To make the problem clearer, I have several users in Parse and I can modify only one column of this one user. The other columns, with all similar attributes, are not responding to my requests, even though I only change the key from the one that works. Furthermore, for this same column that works for one user, doesnt work for the other...
I am weirded out. Anyway, I was wondering if anyone has ever encountered such issue. I have conducted several hypotheses but none revealed correct.
Any help would be acclaimed and welcomed with wide open arms.
Thank you for your time.
Viktor

A: Try PFUser.currentUser()!.refresh() before trying to set or get values to see if it's not a cache issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DVCS Choices - What's good for Windows? So I want to get a project on a distributed version control system, such as mercurial, git, or bazaar.  The catch is that I need the Windows support to be good, i.e. no instructions that start off with "install cygwin...".  Now I've heard that git's Windows support is decent these days, but don't have any first hand experience.  Also, it sounds like the bazaar team has an explicit goal of making it as multiplatform as possible.
Can I get any recommendations?

A: I use msys-git on windows every single day. Works fast and flawlessly.
Although the newer build has some problems with git-svn, this build (Git-1.5.5-preview20080413.exe) has a working git-svn.

A: There's a nice comparison between git, hg and bzr in this InfoQ article.  They all have their strengths and weaknesses.  You'll have to think about your project and your workflows and choose the best fit.  The good news is that they're all fairly good.

A: At last I checked, the only thing you need for Mercurial is Python and to grab a binary package. If you find yourself with more time and want to fiddle / build it yourself, look here.
The only real drawback with HG is its idea of branching .. but for some people that's a major plus.
I like it because its intuitive, easy to install and works on anything that Python does. I don't think that all of the available plugins will work for you, but most should.

A: I've had the best luck with Bazaar, followed by Mercurial. Never could get Git to work correctly. A quick search shows that Git still requires clunky emulation layers like Cygwin/MSYS, and I can't find any integration tools like TortoiseBzr for Git.
With Mercurial in Windows, I had several minor issues (insensitive paths, symlinks, ). They were usually fixed eventually, but I felt that the same quality of testing was not applied to running on Windows as for the other platforms. Bazaar also had better documentation for integrating with native applications like Visual C.

A: EDIT: Perhaps add a "dvcs", "distrubutedversioncontrol", "distrubuted"
I've used Mercurial on Windows with no problems. You can use TortoiseHG or just use the command line. Mercurial does require Python, but that is easy to install in Windows as well.
Mercurial Binary Packages

A: I agree with basszero. I'm using mercurial under windows and it's as easy and reliable as it can get. My development team is spread over Europe (well Dublin and Vienna :-).
We use VPN to commit or sometime the built in webserver (hgserve). Both work fine with no problems out of the box.
Also diff3 open source tool works perfect with mercurial and TortoiseHG out of the box.

A: If you are concerned about an easy to use interface:
The bazaar folk now include TortoiseBzr in their windows binary package.  That's got to be a pretty strong indicator that they think it is up to snuff.  I don't know what the maturity/stability of TortoiseHg is, but there certainly isn't a decent GUI interface for git yet, and the MSYS git build still needs some work IMO.
If your team are comfortable with or prefer the command line, then either bazaar or mercurial would probably work well for you, and are both probably about the same in terms of learning curve.  Git's learning curve is much higher.  It is like the swiss-army knife that is almost wider than it is long, with all the little gadgets and do-dads in it and hanging off it, with the springs so tight that you occasionally slice a finger open trying to prise a blade out.

A: In my experience using GIT on windows is a major pain.  But I have been using Fossil SCM for some time now, and I think it actually fits your needs exactly.
It also has a built in Ticket system and a Wiki.  And the whole program is contained in 1 file and it works right out of the box.
I totally recommend it.
Here is a link to the site http://www.fossil-scm.org/
Remember, this site is self hosting, what that means is you are looking at the web interface to fossil it self, when you look at tickets and the wiki and documentation, you actually are using fossil.
But if your project has millions of lines of code and is a few gigabytes in size, you have to use GIT, there is no way around that problem.
Enjoy.


text:
Q: Should I revoke login from the default pgsql user? I set up a localhost pgsql installation (os x catalina, homebrew, 12.*). I am developing a sql data warehouse and I'd like my dev environment to be as close to the production one as possible. Homebrew created a default superuser, chris. Is it ok (and possible) to revoke the login attribute from this user? I have set up dedicated users to interact with the data warehouse and the actual data in the system.
Thanks!

A: You will need a superuser that can login for administrative purposes. So don't change the existing superuser to NOLOGIN unless you create another superuser first (but tgen you could just as well rename the existing superuser). The secure thing to do is

*

*use a good password for the user

*severely restrict access for that user in pg_hba.conf, ideally to local connections
There is one scenario where you could change the only existing superuser to NOLOGIN: create a regular user admin with NOINHERIT and
GRANT chris TO admin;

Then admin can always assume superuser privileges with
SET ROLE chris;

This setup has the advantage that you don't need a shared password for the superuser. Each administrator can have her own normal user that can assume superuser privileges when necessary.


text:
Q: Can't access checkbox values from backing bean in ADF/JDeveloper New to both ADF and JDeveloper. Also first time posting on Stack Exchange.
The business case:
I want to get some data from a database, display as a tree with checkboxes at only the leaves (the lowest level nodes).
I then want the user to be able to check arbitrary checkboxes, click a submit button and then have the application do various operations on the data (specifically, which checkboxes are checked) in a managed bean. The data does not need to be saved back to the database, only operated on programmatically.
The steps I've taken:
I've set up my Entity Objects that tie into the database, created the View Objects and added them to the Application Module. I then added a Boolean transient attribute called Selected to the lowest level view object, setting Updatable to Always. I created the Facelets page and dragged and dropped to create a tree that shows up just like I want it.
I created another binding to the Selected attribute from my Data Control, and created a selectBooleanCheckbox right after the outputText under the nodeStamp facet. I then tweaked the rendered attribute so it would only render for the lowest level nodes.
So far so good. Tree displays and looks great.
I then created a commandButton and created an action binding to a method called submitTree in a request-scoped managed bean called TreeTest. The form component of my Facelet page now looks like this:
<af:form id="f1">
    <af:commandButton text="Submit" id="cb2" action="#{TreeTestBean.submitTree}" />
    <af:tree summary="A generic summary." id="t1"
             value="#{bindings.TopLevelVO.treeModel}" var="node" rowSelection="none"
             selectionListener="#{bindings.TopLevelVO.treeModel.makeCurrent}">
        <f:facet name="nodeStamp">
            <af:group id="g1">
                <af:selectBooleanCheckbox value="#{node.Selected}" id="sbc1"
                                       rendered="#{node.AccessDisplayName != null ? true : false}" />
                <af:outputText value="#{node}" id="ot1"/>
            </af:group>
         </f:facet>
    </af:tree>
</af:form>
I am now using the iterator approach on the bindings and have edited my backing bean code to look like the following:
public class TreeTestBean{
public void submitTree(){
    BindingContainer bindings = ADFUtils.getBindingContainer();
    DCIteratorBinding dcIteratorBinding = (DCIteratorBinding) bindings.get("TopLevelVOIterator");
    TopLevelVOImpl topLevelVO = (TopLevelVOImpl) dcIteratorBinding.getViewObject();
    RowSetIterator rowSetIterator = topLevelVO.createRowSetIterator(null);

    while (rowSetIterator.hasNext()){
        TopLevelVORowImpl applicationVORow = (TopLevelVORowImpl) rowSetIterator.next();
        ViewRowSetImpl secondLevelRowSet = (ViewRowSetImpl) topLevelVORow.getsecondLevelVO();
        while (secondLevelRowSet.hasNext()){
            SecondLevelVORowImpl secondLevelVORow = (SecondLevelVORowImpl) secondLevelRowSet.next();
            ViewRowSetImpl bottomLevelRowSetImpl = (ViewRowSetImpl) secondLevelpVORow.getBottomLevelVO();
            while (bottomLevelRowSetImpl.hasNext()){
                BottomLevelVORowImpl bottomLevelVORow = (BottomLevelVORowImpl) bottomLevelRowSetImpl.next();
                logger.info(bottomLevelVORow.getBottomLevelName() + " selected: " + bottomLevelVORow.getSelected());
        }
    }
}
rowSetIterator.closeRowSetIterator();
}

So, it appears that I am iterating through the tree correctly. getBottomLevelName correctly prints out the value I want. The checkboxes start as null. When I check a few of them, the ones that I check will show up as false (and the checks get cleared). All the rest stay null. I feel like there is something in the scope and/or lifecycle that I am misunderstanding.


text:
Q: Pyspark: compute percentage of active interval I have a large dataframe with intervals representing the active state of a signal such as:
Input:
df_b = spark.createDataFrame([
    (1.5, 5.0), (8.2, 10.0), (14.0, 15.6)
], ("start", "end"))
# +-----+----+
# |start|end |
# +-----+----+
# |1.5  |5.0 |
# |8.2  |10.0|
# |14.0 |15.6|
# +-----+----+

On a range of fixed frequency intervals, i want to compute
the ratio of the time that the signal is activated within each interval.
Expected result:
df_a = spark.createDataFrame([
(0, 1, 0.0), (1, 2, 0.5), (2, 3, 1.0), (3, 4, 1.0), (4, 5, 1.0), (5, 6, 0.0), (6, 7, 0.0), (7, 8, 0.0), (8, 9, 0.8),
(9,  10, 1.0), (10, 11, 0.25), (11, 12, 0.0)
], ("from", "to", "active_ratio"))
# +----+---+------------+
# |from|to |active_ratio|
# +----+---+------------+
# |0   |1  |0.0         |
# |1   |2  |0.5         |
# |2   |3  |1.0         |
# |3   |4  |1.0         |
# |4   |5  |1.0         |
# |5   |6  |0.0         |
# |6   |7  |0.0         |
# |7   |8  |0.0         |
# |8   |9  |0.8         |
# |9   |10 |1.0         |
# |10  |11 |0.25        |
# |11  |12 |0.0         |
# +----+---+------------+

Visualization:

How can I do this in Pyspark efficiently for a large dataframe?


text:
Q: Can you get a refund either RP or IP on a champion if you do not like them? I bought a champion the other day with RP and I'm not particularly fond of them. Does Riot state a return policy (I didn't notice one) on refunding a champ for the price that I paid for it?

A: There is now in-game support for refunding up to 3 champions or skins, no need to contact Riot support. You get back the same currency used to purchase them (RP/IP).
Here are the full limitations, according to Riot's page:

*

*You only get three refunds per account, per lifetime

*You can only refund skins and champions, not runes, boosts, or bundles

*We can only refund a purchase that you've made in the last 90 days, so no hocking last year's promotional skins back to us!

*If you own a champion and some of their skins, you need to return the skins before you can get a refund on the champion

A: If you e-mail riot support they are usually willing to give ONE refund if you ask nicely, but this is rare because they are not supposed to.

A: You can get a refund addition times if you bought a champ with IP/RP but then promise them that you are going to buy a champion bundle that includes that champion but hesitate because you spent IP/RP already on part of the bundle.  This also involves e-mailing someone in Riot, and is done so on a case-by-case basis.

A: You get a 1 time refund on anything... use it well.

A: Yes you are able to get one refund but normally its when a champion goes on sale or is reduced with in 24 hours of purchase.


text:
Q: CakePHP auth Pluggin redirect issue I am using cakephp auth Plugin .
After login what happening is .
The default log-in page is set by defining the loginAction variable in the beforeFilter function in your UsersController or AppController.
But if you have used plug-ins in your application, and if a user tries to access a controller action of a plug-in the user is redirected to an invalid page like this.
http://satyam.vakharia.com/plugin_name/users/login
BeforeFilter functionality is like this..
function beforeFilter() {
Security::setHash('md5');
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'home', 'action' => 'index');
$this->Auth->loginError = 'Invalid Username or Password.';
$this->Auth->authError = "You are not authorized to access.";
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');

}

A: $this->Auth->loginAction = array('plugin' => false, 'controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('plugin' => false, 'controller' => 'home', 'action' => 'index');
$this->Auth->loginError = 'Invalid Username or Password.';
$this->Auth->authError = "You are not authorized to access.";
$this->Auth->logoutRedirect = array('plugin' => false, 'controller' => 'users', 'action' => 'login');

There.


text:
Q: How to decode received data with NSJSONSerialization as base64EncodedString and convert it to NSData in Swift We are able to encode an image data as base64EncodedString and send from an iOS device to an other one using NSJSONSerialization.
Besides, We are able to receive the image data as base64EncodedString but we are unable
to convert received base64EncodedString to an image at receiving  iOS device.
We tested if we were received base64EncodedString using following code
    let gotInfo = notification.userInfo! as Dictionary
    let receivedData:NSData = gotInfo["data" ] as NSData
    let message = NSJSONSerialization.JSONObjectWithData(receivedData, options:NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
    let receivedString = message
    let receivedD: AnyObject? = message.objectForKey("Field")
    println ("received2: \(receivedD )")

At that point "println" shows base64EncodedString of image but following code gives error "extra argument 'base64EncodedString' incall" and we are unable find why we are having this error.
    let decodedData = NSData(base64EncodedString: receivedD, options:NSDataBase64DecodingOptions())

Once we are able to convert received data to NSData we hope converting it to an image using
    let decodedimage = UIImage(data: decodedData!)

A: After more hours searching and tries, we reached an answer.
we replaced
      let decodedData = NSData(base64EncodedString: receivedD, options:NSDataBase64DecodingOptions())

with
      let decodedData = NSData(base64EncodedString: receivedD! as String, options: NSDataBase64DecodingOptions())

and here is picture.


text:
Q: Creating multiple class instances from a list of names in Python? Can someone explain to me how to return a new instance of a class by iterating over a list of names and a list of dicts?
I know that I can unpack my dictionary using **, and I know that I can iterate through my list of dictionaries.
So I attempted to create a for loop function that creates new instances of my Card class for each card in the cardList.
Here is the code I thought would work:
def createCardInstances(x):
    for i in range(len(x)):
        namesOfCards[i] = Card(**cardList[i])
        return namesOfCards[i]

namesOfCards is a list of card names that I would like to turn into instances of the Card class. cardList is a list of the dictionaries that represent cards and their values.
For instance, I can do this:
Knight = Card(**cardList[0])
Which works fine. But, if I'm developing a card game and have upwards of a 100 individual cards or more, I would like to avoid having to write out each card name individually and copy\pasting the =Card(**cardList[]) code each time.
How do I automate the creation of new instances? Is that even feasible?

EDIT:
I'm trying to use the names in namesOfCards to make new instances of Card. It was suggested to me that my next step in learning python while creating a card game was to make it more object oriented.
So my goal right now is to use the names of the cards - saved in the list namesOfCards - to make new instances of Card. i.e.:
[Knight, Mage, Warrior, ...]
And I want to have the ability to take those and do this:
Knight = Card(**cardList[0])
Mage = Card(**cardList[1])
Warrior = Card(**cardList[2]
and so on and so forth.
Is that possible? Or do I need to use the list comprehension suggestion to store all of the class instances into a list, and then have to access the instances by using new_cards[0].name or new_cards[1].attack?

A: you are returning an individual card when you pass it a list?  also if cardNames is a list of names you shouldn't be overwriting it with Card objects. You should be able to do something like this?
new_cards = [Card(**card) for card in card_list]  # make new card objects
cards = {card.name: card for card in new_cards}  # dict to ref cards by name
print cards['Knight'].name

or simply
cards = {card['name']: Card(**card) for card in card_list}

if you are wanting to restrict that cards to only those in namesOfCards. you could
cards = {card['name']: Card(**card) for card in card_list if card['name'] in names_of_cards}

(note: this all assumes that you dont have two cards with the same name)
It is also possible to put those cards into your local namespace like the question asks, but I would highly discourage it. But if you really really want to ...
locals().update(cards)
print Knight.name

A: make sure that your list contains string like
CARDS = ['Knght', 'Mage'] #and so on

I'm not sure if this is what you need but see the code below:
CARD = ['knight','mage']

class cards:
    def __init__(self, name):
        self.n = name
        self.attack = "attack " + self.n

print knight.attack

using that you can loop through a list or dictionary to create an instance of your class


text:
Q: Eclipse PHP Incorrect Color Formatting / Highlighting Sometimes my code color syntax formatting is off on some of my php files. In my case nearly everything is the same color except for keywords. This seems to be random and there are no apparent errors in my code. I'm thinking perhaps there is a small bug somewhere causing this.

A: I've found at least one quick fix.
Simply make a copy of the php file, delete the original, then rename the copy to the original name. When you open/close and re-open the new file, the color syntax highlighting seems to magically fix itself.
If anybody knows what might be causing this in the first place please post your thoughts.


text:
Q: Continuity of Lipschitz constant with respect to Hausdorff metric I was thinking about Lipschitz constants and their dependence on the domain. This led me to the following question:
Let $f$ a function that is Lipschitz continuous over the domain $A\subset\mathbb{R}^{n}$ be given. Suppose $K(A)$ is the set of compact subsets of $A$. This has a topology induced by the Hausdorff metric (See here for the definition).
Let $L_{f}(B)\colon K(A)\to\mathbb{R}$ be the (best) Lipschitz constant for $f$ on the compact set $B\in K(A)$. Is this continous with respect to the standard topology of euclidean space and the Hausdorff metric topology of $K(A)$?
I suspect the answer is probably not. A function with a sufficient discontinuous derivative should break things, but I'm having trouble engineering an example.
I'm also wondering when it might be true? For $C^{\infty}$ functions? For polynomials? Maybe this is true for a certain class of bounds for $L_{f}$ (e.g bounds on the gradient) for a given class of functions $f$ (e.g $C^{1}$ functions)?
Another thought: What is the relation between $L_{f}$ and the idea of a local Lipschitz function?

A: For an easy counterexample to continuity of $L_f(B)$, take $$f(x) = \begin{cases} x \,\text{if $x \ge 0$} \\ 2x \,\text{if $x \le 0$} \end{cases}
$$ So $L_f[0,1]=1$ and $L_f[-\epsilon,1]=2$ for all $\epsilon > 0$, whereas the Hausdorff distance between $[0,1]$ and $[-\epsilon,1]$ equals $\epsilon$.


text:
Q: Google scripts copy range from one spreadsheet to another based on date I am currently trying to automatically archive responses from a Google form. I have a script which runs every time the form is submitted and does some processing of the last submit.
What I want to do is on the first submit of the month, create a separate spreadsheet with just last months entries.
I am doing this by getting the date from last month, creating a new spreadsheet with last months name and year as the name of the file.
What I now need to do is select a range based on dates. So in column A is a timestamp (e.g. 31/12/2014 22:21:31) - I would want to select all rows between for example 1/12/2014 00:00:00 and 31/12/2014 23:59:59.
Using this example I know its possible to copy a range but it's finding the correct range I need help with:
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var target = SpreadsheetApp.openById("0Aqv8.....");
  var source_sheet = ss.getSheetByName("Form Responses");
  var target_sheet = target.getSheetByName("Sheet1");
  var source_range = source_sheet.getRange("A2:A");
  var target_range = target_sheet.getRange("A2:A");

  var values = source_range.getValues();
  target_range.setValues(values);

I am using the following to get the start time, and end time of the month:
  var x = new Date();
  var d = new Date();

  // Start Time:
  x.setDate(1);
  x.setHours(0);
  x.setMinutes(0);
  x.setSeconds(0);
  x.setMonth(x.getMonth()-1);

  // Finish Time:
  d.setDate(0);
  d.setHours(23);
  d.setMinutes(59);
  d.setSeconds(59);

A: Ok so this probably isn't the best answer, but hey it seems to work for me:
var x = new Date();
var d = new Date();
// Start Time:
x.setDate(1);
x.setHours(0);
x.setMinutes(0);
x.setSeconds(0);
x.setMonth(x.getMonth()-1);
// Finish Time:
d.setDate(0);
d.setHours(23);
d.setMinutes(59);
d.setSeconds(59);
// Create a blank spreadsheet:
var root = DocsList.getRootFolder()
var newFileId = SpreadsheetApp.create(archiveName).getId();
var newFile = DocsList.getFileById(newFileId);
newFile.addToFolder(destFolder);
newFile.removeFromFolder(root);

// Get the spreadsheets:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.openById(newFileId);
var sheet = ss.getSheetByName("Form Responses");
var target_sheet = target.getSheetByName("Sheet1");

// Record the range:
var firstRow = 1;
var lastRow = 1;
var width = sheet.getDataRange().getWidth();

// Get all the current data:
var numRows = sheet.getDataRange().getNumRows();
var data = sheet.getDataRange().getValues();

// Get the first entry:
for(var i=0; i<numRows; i++){
  var tmp = new Date(data[i][0]);
  if (tmp > x) {
    firstRow = i+1;
    Logger.log(i + " - is the first row");
    i = numRows;
  }
}

// Get the last entry:
for(var i=0; i<numRows; i++){
  var tmp = new Date(data[i][0]);
  if (tmp > d) {
    lastRow = i;
    Logger.log(i + " - is the last row");
    i = numRows;
  }
}

// Copy the title:
var source_range = sheet.getRange(1,1,1,width);
var target_range = target_sheet.getRange(1,1,1,width);
var values = source_range.getValues();
var formats = source_range.getNumberFormats();
target_range.setValues(values);
target_range.setNumberFormats(formats);
target_sheet.setFrozenRows(1);

// Copy the last months values:
var source_range = sheet.getRange(firstRow,1,lastRow-firstRow+1,width);
var target_range = target_sheet.getRange(2,1,lastRow-firstRow+1,width);
var values = source_range.getValues();
target_range.setValues(values);


text:
Q: Unity Container passing runtime constructor parameters I have two constructors, the first works fine as follows:
    public ESite(Func<IOrg> unityOrgFactory)
    {
        this.OrFactory = unityOrgFactory;
        this.Kid = Guid.Empty;
    }
_IoC.RegisterType<IESite, ESite>();
IESite eSite = boClass.IoC.Resolve<IESite>();

Now, I need to pass in a key at runtime so I add a constructor as usual:
    public ESite(Func<IOrg> unityOrgFactory, Guid kid)
    {
        this.OrFactory = unityOrgFactory;
        this.Kid = kid;
    }

Syntax for this registration and resolve usage? I've tried several InjectionConstructor variants but can't get it right...I'm missing something. After several search-and-try rounds, time to ask! I have read several posts on related topics...
Thanks for tips!
GG

A: A reasonable workaround (not necessarily the best answer) is to disencumber the constructor by moving the injected parameters to an InjectionMethod
Register:
// Use InjectionMethod Initializer to free up constructors. http://msdn.microsoft.com/en-us/library/ff953186(v=pandp.50).aspx   new InjectionMethod("Initialize", typeof(Database), "CustomerServices")
        _IoC.RegisterType<IESite, ESite>(
            new InjectionMethod("Initialize", typeof(Func<IOrg>))
            );

Use:
        //http://msdn.microsoft.com/en-us/library/ff953186(v=pandp.50).aspx
    [InjectionMethod]
    public void Initialize(Func<IOrg> unityOrgFactory)


text:
Q: Share one single cookie through subdomains I have a blogs subdomain that works well, however, the signin is detached from all subdomains, and consequently, if a user signs in his cookie is only valid on the non-subdomain pages. How can I set my app to make the cookies be valid throughout all subdomains and normal pages?
I worked through this topic: Share session (cookies) between subdomains in Rails? but unfortunately without success. I even tried that long step by step rack middleware approach but wihtout success.
I am using Rails 3.2.13.
Any help appreciated! :)

A: All I needed to do was to specify the domain when creating the cookie, as commented earlier above.
cookies[:remember_token] = { value: user.remember_token, domain: ".lvh.me" }

A: Put domain: all at the end of the line in your config/session_store.rb
eg.
YourApp::Application.config.session_store :encrypted_cookie_store, key: '_yourapp_session', domain: :all

You also may need to change this parameter in your config/environments/production.rb
config.action_dispatch.tld_length = 2

If your domain is example.com then your tld_length (Top Level Domain Length) is 1 (which is the default).  example.com.au is 2, 127.0.0.1.xip.io is 5, and so on.


text:
Q: Bulk import of PrestaShop combinations I need to import a massive amount (approx. 2.3 million) of attribute combinations to PrestaShop instance. Trying to import data via CSV files in parts of 3000 rows ends with server timeout.
Is there any simple way to import combinations in a reliable time? (except for writing own script that will put this data directly to MySQL database)
Thanks for your help.


text:
Q: Extracting a JSON out of a string using JSONPath I have Json data as follows:
{
   "template" : [
      "{
         "Id": "abc"
      }"
   ]
}

I am using JSONPath to extract data from the Json above. I would like to extract the "Id" data from the Json using JsonPath.
The problem I see is, the data is being treated as a string and not as a Json as shown below.
"{
   "Id": "abc"
}"

If there were no double-quotes I could have used JsonPath as follows:
$.template[0].Id

But due to the double-quotes, I am unable to access the "Id" data. I suspect there is a way to access this data using JsonPath-Expression but I am pretty much a novice here and no amount of research helped me out with a resolution.
How do I treat it as a Json and not as a string using JsonPath? Kindly help me out here.

A: JSON Path isn't going to be able to parse JSON that's encoded within a string. You need to perform three operations:

*

*Get the string (use JSON Path or something else)

*Parse the string as JSON.

*Get the data you're looking for on that (JSON Path or something else)


text:
Q: Read XML files one by one as a queue in a folder directory using NODE js I need help to find a possible way to read XML files in a directory in a QUEUE process and read data using node js
so far I have tried to read the XML data without using a queue,
const path = require("path");
const fs = require("fs");
const  convert = require('xml-js');

const WATCH_TARGET = './feed';
fs.watch(WATCH_TARGET, (eventType, filename) => {
   console.log('File "' + filename + '" was changed: ' + eventType);
});

const feedPath = path.join(process.cwd(), "feed");

const filenames = fs.readdirSync(feedPath);

const filePosts = filenames.map((name) => {
  const fullPath = path.join(process.cwd(), "feed", name);

  fs.watch(`${fullPath}`, { persistent: true }, function (event, fileName) {
    console.log("Event: " + event);
    console.log(fileName + "\n");
  });

  const file = fs.readFileSync(fullPath, "utf-8");
  const result = convert.xml2json(file, {compact: true, spaces: 4});

  console.log(result);
  console.log(name);
});


text:
Q: Twilio test credentials region permission error I'm receiving the following error when using test credentials to create an SMS message using the Javascript SDK (v3.54.2):
function call: await this.twilio.messages.create({...})
Error Message:
Error: Permission to send an SMS has not been enabled for the region indicated by the 'To' number: +47********.

According to the these docs, the "to" number should be validated as normal. I am using the special test "from" number: +15005550006
With the live credentials, this error does not occur, so I would not expect this error to occur with test credentials... but it does.


text:
Q: "Error: Can't open display" with ubuntu bash and Xming I failed to open Xdisplay from ubuntu bash (opened in command prompt from Win11).
Setup:

*

*Launch XLaunch with all default options

*In command prompt, enter bash (Ubuntu)

*Maybe relevant configs: In "/etc/ssh/sshd_config", X11Forwarding yes and X11UseLocalhost yes. In "/etc/ssh/ssh_config", ForwardX11 yes and ForwardX11Trusted yes.

*Opening xeyes straight from Xming works just fine.

*DISPLAY=172.17.112.1:0.0; xeyes will hang for a couple of minutes and then gives Error: Can't open display:. Any other DISPLAY I've tried (such as 127.0.0.1:0.0, localhost:0.0) instantly gives the error message. Similarly, gvim or matplotlib from python scripts fail as well.

Ideally after this is resolved, I can use Xdisplay from ssh sessions (opened from bash) as well. Any help is appreciated.


text:
Q: How can I access a specific variable of a function from another script? I have implemented a code here using tensorflow to train a CSV file. This works without any problems.
# training.py

import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

def trainingTS():
    df = pd.read_csv('my_data.csv')
    X = pd.get_dummies(df.drop(['Fire'], axis=1))
    y = df['Fire']
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

    model = Sequential()
    model = tf.losses.MeanSquaredError(),optimizer = tf.optimizers.Adam())
    model.add(LSTM(128, return_sequences=True, activation='relu'))
    model.add(Dense(units=1, activation='sigmoid'))
    model.fit(X_train, y_train, epochs=100, batch_size=32)
    model.save('my_model.h5')

    return model

Now to my current problem. I need the variable model in another python file publish.py.
#main.py

from training.py import trainingTS

def finallyVisual():

    model = trainingTS()
    model.load_weights('my_model.h5')
    # ...

To do this, I simply called the Python training.py method trainingTS(). But when I run the python file main.py, the complete python file of training.py is executed. How can I access this one variable model without outputting the complete function? I am currently still a beginner and do not know how to execute this. Implementing the variable model outside of the function is not possible, because I need the finished or trained model version.

A: According to the documentation after saving you can use .load_model('path/to/location').
https://www.tensorflow.org/guide/keras/save_and_serialize

#main.py

#from training.py import trainingTS
from tensorflow import keras

def finallyVisual():

    #model = trainingTS()
    model = keras.models.load_model('my_model.h5')
    model.load_weights('my_model.h5')
    # ...


text:
Q: Web Deployment Project - specify version of aspnet_merge to use we are having some problems with our WDP, which is deploying a ASP.NET 4.0 site. It seems to all go fine but when its deployed we are getting the  System.BadImageFormatException: Bad binary signature. (Exception from HRESULT: 0x80131192) error, when hitting a particular page , which appears - from other reading - may be to do with the version of aspnet_merge the WDP is using by default.
thing is, we have just had all our machines changed and it was working fine on the old ones..
I have found how to specify which version in the Microsoft.WebDeployments.Targets file (enter link description here), but not convinced it is actually using that..
  <AspnetMergeName>aspnet_merge.exe</AspnetMergeName>
    <!-- OLD
    <AspnetMergePath>$(MSBuildExtensionsPath)\Microsoft\WebDeployment\v10.0</AspnetMergePath>
    <AspnetMergePath Condition="Exists('$(TargetFrameworkSDKDirectoryBin)$(AspnetMergeName)')">$(TargetFrameworkSDKDirectoryBin)</AspnetMergePath>
    -->
    <AspnetMergePath>C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools</AspnetMergePath>
    <AspnetMergePath Condition="'$(TargetFrameworkVersion)' == 'v4.0'">C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools</AspnetMergePath>

I got the paths from here: http://msdn.microsoft.com/en-US/library/bb397866.aspx#findingthecorrectversion
is there a way of setting the path to aspnet_merge directly in the wdproj file?
this is all assuming that this is the problem in the first place of course..
thanks
nat


text:
Q: Sitecore no layout found I'm working on a Sitecore site that's part of a multi-site installation that uses a shared codebase (dlls, etc...) and my own code. Unfortunately I don't know much about the shared code as I didn't write any of it.
A recent build has caused my site to stop working. Whenever I try to browse to a page directly I get an error that the layout cannot be found ({00000000-0000-0000-0000-000000000000}). However, if I try to preview the same page from Content Editor, it will display. I've tried undoing pending changes and rolling back code but it's not working. Any ideas/help would be appreciated.

A: I often see this issue when Templates are missing from the Web database.
Preview generally works from the Master database, so it isn't affected by unpublished content in the Web database.
Try doing a full republish of the User Defined templates folder:
/sitecore/templates/User Defined

A: After much searching and getting help from the folks who wrote the foundation it was discovered that there was a missing configuration that was causing the wrong site definition file to be referenced.


text:
Q: Use GLM in R to see if sex ratio varies by group I have a bunch of data on how things developed in the laboratory. This involves different collection site information and different treatments.
My question here: Did the groupings (place and treatment) have an effect on the resulting sex ration of adult males to females? And can I figure this out with a GLM?
[I don't know how many of each sex I put in, it was random, some juveniles died during development and I only sexed the adults]
I followed along this tutorial where I used a GLM to investigate the sex ratios:
http://www.simonqueenborough.info/R/stats-basic/glm.html
Here is my data and code:
mo<-"Temp   Locality    Females Males
A   APR 88  110
B   APR 101 97
C   APR 85  94
A   ARS 65  69
B   ARS 57  78
C   ARS 54  76
A   RMO 103 90
B   RMO 97  101
C   RMO 82  78
A   RPV 89  92
B   RPV 98  86
C   RPV 64  76
A   SJU 66  63
B   SJU 57  66
C   SJU 16  17
A   TLC 45  46
B   TLC 41  43
C   TLC 27  44
A   TPN 25  20
B   TPN 22  25
C   TPN 16  22"

data <- read.table(text=mo, header = TRUE)
y<-cbind(data$Males,data$Females)
model<-glm(y~data$Temp+data$Locality, family=binomial)
summary(model)

#results of summary (model)
Call:
glm(formula = y ~ sexy$Temp + sexy$Locality, family = binomial)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-0.8231  -0.5549  -0.2398   0.5038   1.2954

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)       0.03839    0.09885   0.388    0.698
sexy$TempB        0.03032    0.09093   0.333    0.739
sexy$TempC        0.14538    0.09818   1.481    0.139
sexy$LocalityARS  0.14092    0.13098   1.076    0.282
sexy$LocalityRMO -0.13872    0.11938  -1.162    0.245
sexy$LocalityRPV -0.07783    0.12213  -0.637    0.524
sexy$LocalitySJU -0.01914    0.14600  -0.131    0.896
sexy$LocalityTLC  0.07243    0.15286   0.474    0.636
sexy$LocalityTPN -0.03022    0.19444  -0.155    0.877

From both model summary, I found no significant differences in sex ratio by temperature or locality. Is this real? Is the GLM appropriate or is there another method?

A: Not a question for here... but I'll answer it anyways.
Your model doesn't make sense. A binomial model should have a 1 or 0 dependent variable. The question with a binomial model would be "for each individual observation of a female or male (1 or 0), does temperature or locality influence the probability that a female or male is observed". So instead of modeling the # of females vs. the # of males, you model the probability that at any given point a female or male will be observed based on the influence of temperature/locality.
You could model ratio explicitly by creating a dependent variable of males/female or vice versa and use that in a linear regression model. But that would probably be ill-advised. Modeling proportions in a linear framework can be anti-conservative particularly if proportions are skewed close to 1. But if your ratios are well distributed between 0:1 and not skewed close to 1, then it might not be that awful (though it's still a bit of not great way to model a ratio).
I would consider reformatting your data so you can actually model it within a binomial framework, like your original idea. The modeling logic of binomial model is relatively close to your intended question (what influences the probability that I will observe a male or female)? Just make a data frame that has 1 observation of Temperature and 1 observation of Locality for each observation of gender (coded as a 1 or 0 (e.g., male == 1, female == 0)) and model that in a binomial/logistic framework.
You could do a 2nd binomial model of dead vs. not dead if you want to see what temp/locality diffs. influenced development to adulthood.
ALSO - you need to contrast code your categorical predictors if you have any interest in interpreting the effect directions, etc. of different temp/localities.


text:
Q: getActivity() returns null in ActionBar Fragment getActivity() within a Fragment will return null if called before fragment.onAttach(activity).
fragment.onActivityCreated(savedInstanceState) is called after fragment.onAttach(activity). See developer.android for info on fragment lifecycyle.
I have a method within my fragment that attempts to instantiate a database connection. When the method initially is called, it works fine.
public void onActivityCreated(Bundle savedInstanceState){
   super.onActivityCreated(savedInstanceState);
    Log.d("MyTag", "Activity being created");
    if (savedInstanceState == null){
        listAdapter.setContext(getActivity());
        execSearch(0);
    } else { listAdapter.setContext(getActivity()); }
}

public void execSearch(Long searchId) {
    MySQLiteHelper dbHelper = new MySQLiteHelper(getActivity());
    SQLiteDatabase database = dbHelper.getReadableDatabase();
    ...
}

Now when this same method is called via an interface after a button click within a listview, getActivity() returns null (in the fragment.
Here is the button callback from within the ListAdapter:
private final View.OnClickListener editSearchListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Long search_id = (Long) v.getTag();
        ((MyInterface) context).searchCalled(search_id);
    }
};

And the interface implementation within the MainActivity:
@Override
public void searchCalled(Long search_id) {
    fragment.execSearch(id);
}

This second time around I get the null response from getActivity() within fragment.execSearch(id).
I'm stuck!! Does this have something to do with the interface call coming from a UI action. Do I need to implement mainActivity.searchCalled as a runnable on the UI thread???

A: Since this was my first time developing an Android app, wanted to share some of the things I learned to make solving this problem more intuitive for other new Android developers. Background on what I was developing:

*

*Three fragment that allowed for creation of searches, a list of searches, and lists of search results. These all could be initialized on their own, but could send messages and receive messages from a shared interface (ie the SearchManager interface below).

*A FragmentPagerAdapter which was used for assigning fragment to their respective tabs and moving between them. This was more appropriate for my design because I only had three tabs to swipe between. For more numerous tab sets use FragmentStatePagerAdapter.

*a SearchManager Interface to communicate between fragments.

Why I had the problem above and numerous similar problems
Basically what I was trying to do is preserve any changes to the UI that the user had made across configuration changes (It's helpful for noobs to understand that activity creation is not the same as app launch - activities are repeatedly created when an app experiences configuration changes, or is replaced by another app. This was not intuitive to me at first.).
There are two ways to do this. You can either save the necessary data in Fragment.onSaveInstanceState and then re-create your fragments with the saved data when a new activity is created OR you can call setRetainInstance in your Fragment.onCreate.
I originally used the savedInstanceState method. Since this did not preserve my fragment instances, anytime I got getActivity() == null, it was because code was running from an old fragment instance not attached to the activity. This can happen when an interface is called, say from an onClickListener, that has not been updated to point to the current Activity instance (ie the one attached to the current activity). i.e. the listener was created before a configuration change, and called after the configuration change without ever being told that a new Activity instance had been created.
I eventually elected to go the setRetainInstance(true) route. This means:

*

*onCreate is not called when a new activity is created.  onDestroy is not called withen the activity is destroyed.

*savedInstanceState in your onActivityCreated will always be null

*any attributes on your fragments will be preserved.

This makes things easy and difficult. Basically I recommend this route if you have a lot of attributes/data that are not dependent on knowing what the current activity is (eg form values, lists to display). However, in this situation, any attributes that need to know about the current activity must be told when a new activity is created. You can do this as follows:
     @Override
     public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (MainActivity) activity;
        // custom method on list adapter, so any calls to SearchManager interface
        // are properly routed to current activity
        myListAdapter.setContext(activity);
     }

Other Useful Things that Would've Helped to Know
Communication between fragment instances
I've heard conflicting suggestions about how to communicate between fragments. On one hand, I've heard that you shouldn't have references to your fragment instances outside of the adapter. On the other hand, you hear fragment instances should not communicate directly with each other. This would imply using your FragmentPagerAdapter to implement communication interface for your fragments. However, even in this case you'd have to be clever about getting your fragment instances within the adapter (eg you can get the adapter's tag for your fragments or better leverage the adapter's instantiateItem method).
Ultimately, because any way you cut the pie you've got to hack around to get your fragment instances, I went outside the adapter and created a headless fragment that implemented my SearchManager interface. That keeps the interface separated from the adapter, avoids communication between my functional fragments, and out of the MainActivity.
Preserving Views across configuration Change
One last note. When I created my New Search Form, I noticed all of the inputs were erased on my configuration changes (ie when new fragment was attached/created). This is because even if setRetainInstance is set to true, the fragment's onCreateView method is still called, requiring you to inflate your view and return it. It's this process that erases any user manipulation of the view. So I did the following in all of my fragment's onCreateView methods:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if (view == null){
        view = inflater.inflate(R.layout.doc_list_fragment,
            container, false);
    } else {
        ((ViewGroup) view.getParent()).removeView(view);
    }
    setContext();
    return view;
}

Because setRetainInstance is true, the view is preserved within the fragment instance after it has been inflated the first time. The removeView business prevents this error:
FATAL EXCEPTION: main java.lang.IllegalStateException:
The specified child already has a parent. You must call removeView() on the child's parent first.

Also, I made a call to my custom setContext method here because it is at this point that i have both my view and my activity. Therefore, if any click listeners need to know what the current activity is, I now have my prepared view and can create listeners to properly point them to the current activity.
Completed Project
You can check out the completed app on GitHub.


text:
Q: How to prompt user to choose between browser or app when play youtube video in webview android I created a simple browser in android using Web-view. I have a Text-edit and a go button. When i got to YouTube i can play the video fine, but when I turn device sideways video stop and ask to play again, then it wont play anymore or any other videos. Is there a way to prompt user to choose between browser or YouTube app when click play in video?
Also is there a way to make android realize my app is a web browser?

A: startActivity(Intent.createChooser( shareIntent, title ));

Where shareIntent is the intent you want to launch (the intent to show the video).  It will create a chooser with all of the apps which can handle that intent.
TO make android realize you're a web browser, you need to set up an intent filter that says you can view the HTML mime type.


text:
Q: How to check existing Worklight version installed :- Consumer or Enterprise I am trying to download a fix pack from fix central and i have two options consumer or enterprise, Is there a way to check existing WL server installation is consumer edition or enterprise edition depending on which i can start the download.

A: There is no technical difference between the Enterprise and Consumer editions.
The difference is in your license terms with IBM. So whichever you download, it's the same.
So if you want to know which to download - contact your Business unit and ask them which you should download (even though technically they are the same...). Don't mess with the Legal departments. :-)
Read more here: http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.0.0/com.ibm.worklight.getstart.doc/getstart/c_wl_editions.html


text:
Q: Rotate a single view within ViewController In my iOS 7/8 app, I have several viewcontrollers all of which should be portrait. I have a view controller which has a full screen view which will play video. I need this view to able to rotate depending on orientation of the phone. However the view controller that contains the video view is not allowed to rotate, reason being there are some other views sometimes overlaid above the full screen video view that are part of the viewcontroller and these should not be rotated.
So how can I rotate a single view and how do I get informed that the orientation of the device has changed. The usual [UIApplication sharedApplication].statusBarOrientation doesn't work as the viewcontroller itself does not rotate.
How to solve this problem.
Thanks

A: You can't rotate the screen forcefully. There is another way, in your case you have all the screens in Portrait, and you need a ViewController which can rotate both ways. You need to follow few steps described below.
See image for the settings you need to do in the Build Settings.

*

*Create a Custom Class of type UINavigationController say CustomNavController, then in the .m class add the following code.
-(BOOL)shouldAutorotate{

    return YES;
}

- (NSUInteger)supportedInterfaceOrientations{

     return UIInterfaceOrientationMaskAll;
}

*Present the video controller as Modal using the CustomNavController, like below
VideoViewController *controller=[[VideoViewController alloc] initWithNibName:@"VideoViewController" bundle:nil];
CustomNavController *nav=[[CustomNavController alloc] initWithRootViewController:controller];
[self presentViewController:nav animated:YES completion:nil];
nav.navigationBar.hidden=YES;

And it should work, the trick is to separate rotations.


text:
Q: Disabling Safari autofill on usernames and passwords You might already know, that Safari has a nasty autofill bug where it fills email, username and password fields no matter if you set autocomplete="off" or not.
Here's a basic form:
<form action="/" method="post">

        E-mail
        <input type="text" name="email" value="" />

        Password
        <input type="password" name="password" value="" />

</form>

...Safari autofills those fields on page load like it should, job well done!
If you put autocomplete="off" to the fields and/or the form element, Safari still autofills those fields:
<form action="/" method="post" autocomplete="off">

        E-mail
        <input type="text" name="email" value="" autocomplete="off" />

        Password
        <input type="password" name="password" value="" autocomplete="off" />

</form>

Even this doesn't work:
<form action="/" method="post" autocomplete="off">

        E-mail
        <input type="text" name="secretfield1" value="" autocomplete="off"/>

        Password
        <input type="password" name="secretfield2" value="" autocomplete="off" />

</form>

...since Safari looks up those  elements if they contain words "E-mail", "Password" etc. and goes ahead with the autofill.
Aaaahhhhha!, I thought, and tried this:
<form action="/" method="post" autocomplete="off">

        %REPLACE_EMAIL_TITLE%
        <input type="text" name="%REPLACE_EMAIL_NAME%" value="" autocomplete="off"/>

        %REPLACE_PASSWORD_TITLE%
        <input type="password" name="%REPLACE_PASSWORD_NAME%" value="" autocomplete="off" />

</form>

...and replace %TAGS% with the real names using JavaScript. Safari autofill kicks in. No matter if you set a 10 second timeout on the replacement.
So, is this really the only option?
<form action="/" method="post" autocomplete="off">

        That electronic postal address we all use, but can't write the title here because Safari fills this with YOUR information if you have autofill turned on
        <input type="text" name="someelectronicpostaladdress" value="" autocomplete="off"/>

        A set of characters, letters, numbers and special characters that is so secret that only you or the user you are changing it for knows, but can't write the title here because Safari sucks
        <input type="password" name="setofseeecretcharacters" value="" autocomplete="off" />

</form>

I hope not?
UPDATE: @skithund pointed out in Twitter, that Safari is getting a 4.0.3 update, which mentions "Login AutoFill". Does anyone know if that update is going to fix this?

A: This question has already been successfully answered, but as of today's date, the solution didn't work for me without making some oddly particular changes - so I'm noting it here as much for my own reference if I decide to come back to it as for everyone else's.

*

*The fake input needs to be after the real email input in the dom.

*The fake input requires a fake label.

*The fake label cannot be absolutely positioned.

*Can't use display, visibility or opacity to hide the fake elements.

The only solution I found was to clip the visibility of the fake elements with overflow: hidden.
Email
<input autocomplete="off" type="text" value="user@email.com" name="user[email]" id="user_email">

Email
<input type="text" name="fake[email]" id="fake_email" style="height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px)" tab-index="-1" aria-hidden="true">

For the record, the particular case this hack came in useful for was one where an admin is editing the profile of other users and Safari was replacing the email of the user with the email of the admin. We've decided that for the small (but frustrating) amount of support requests that this Safari 'feature' creates, it's not worth maintaining a hack that seems to need to evolve as Safari tightens up on it, and instead provide support to those users on how to turn off autofill.

A: Just put search into the name, Safari will ignore the field for autofill.
<input type="password" name="notsearch_password">

A: After scanning through Apple's Safari HTML pages and not finding anything on auto complete, I did some searching and thinking.
After reading a (mildly) related question on Apple discussions, I remembered that the default is to not allow remembered passwords, etc (which can be enabled in iDevice system settings, or at the prompt). Since Apple has moved this feature out of the browser and into their (proprietary, i)OS (screen shots on this article), I believe they are ignoring the HTML form/field property entirely.
Unless they change their mentality as to this feature, as I'm sure this is their expected behavior, on their locked down devices, I would work under the assumption that this isn't going away. This is probably different for native iOS apps. Definitely keep the form autocomplete="off" and hopefully they'll one day get back to the HTML5 standard for the feature.
I know this doesn't include any work around, but I think if you come to terms with it being a non-browser 'feature' on iDevices, it makes sense (in an Apple kind of way).

A: The reason browsers are ignoring autocomplete=off is because there have been some web-sites that tried to disable auto-completing of passwords.
That is wrong.
And in July 2014 Firefox was the last major browser to finally implement the change to ignore any web-site that tries to turn off autocompleting of passwords.

*

*June 2009: IEInternals blog where they discuss keeping the user in control (archive)

*February 2014: Chrome's announcement when they began ignoring autocomplete=off (archive)

*January 2014: Bugzilla Bug 956906 - ignore autocomplete="off" when offering to save passwords via the password manager (archive)

*Reddit discussion (archive)

One of the top user-complaints about our HTML Forms AutoComplete feature is "It doesn't work– I don't see any of my previously entered text."  When debugging such cases, we usually find that the site has explicitly disabled the feature using the provided attribute, but of course, users have no idea that the site has done so and simply assume that IE is buggy.  In my experience, when features are hidden or replaced, users will usually blame the browser, not the website.

Any attempt by any web-site to circumvent the browser's preference is wrong, that is why browsers ignore it. There is no reason known why a web-site should try to disable saving of passwords.

*

*Chrome ignores it

*Safari ignores it

*IE ignores it

*Firefox ignores it

At this point, web developers typically protest "But I wouldn't do this everywhere– only in a few little bits where it makes sense!"  Even if that's true, unfortunately, this is yet another case where there's really no way for the browser to tell the difference.  Remember, popup windows were once a happy, useful part of the web browsing experience, until their abuse by advertisers made them the bane of users everywhere. Inevitably, all browsers began blocking popups, breaking even the "good" sites that used popups with good taste and discretion.

What if I'm a special snowflake?
There are people who bring up a good use-case:

I have a shared, public area, kiosk style computer. We don't want someone to (accidentally or intentionally) save their password so the next user could use it.

That does not violate the statement:

Any attempt by any web-site to circumvent the browser's preference is wrong

That is because in the case of a shared kiosk:

*

*it is not the web-server that has the oddball policy

*it is the client user-agent that has the oddball policy

The browser (the shared computer) is the one that has the requirement that it not try to save passwords.
The correct way to prevent the browser from saving passwords
is to configure the browser to not save passwords.
Since you have locked down and control this kiosk computer: you control the settings. That includes the option of saving passwords.
In Chrome and Internet Explorer, you configure those options using Group Policies (e.g. registry keys).
From the Chrome Policy List:

AutoFillEnabled
Enable AutoFill
Data type: Boolean (REG_DWORD)
Windows registry location: Software\Policies\Chromium\AutoFillEnabled
Description: Enables Chromium's AutoFill feature and allows users to auto complete web forms using previously stored information such as address or credit card information. If you disable this setting, AutoFill will be inaccessible to users. If you enable this setting or do not set a value, AutoFill will remain under the control of the user. This will allow them to configure AutoFill profiles and to switch AutoFill on or off at their own discretion.

Please pass the word up to corporate managers that trying to disable autocompleting of password is wrong. It is so wrong that browsers are intentionally ignoring anyone who tries to do it. Those people should stop doing the wrong thing.™
Put it another way
In other words:

*

*if the users browser

*mistakes "Please enter the name of your favorite maiden name's first color." for a new password

*and the user

*doesn't want their browser

*to update their password,

*then they

*will click Nope

*

*if i want to save my HIPPA password: that's my right

*if i want to save my PCI password: that's my right

*if i want to save the "new password for the user": that's my right

*if i want to save the one-time-password: that's my right

*if i want to save my "first color's favorite maiden" answer: that's my right.

It's not your job to over-rule the user's wishes. It's their browser; not yours.

A: I can't believe this is still an issue so long after it's been reported. The above solutions didn't work for me, as safari seemed to know when the element was not displayed or off-screen, however the following did work for me:

  Username <input type="text" name="fake_safari_username" >
  Password <input type="password" name="fake_safari_password">

Hope that's useful for somebody!

A: I had the same problem. And though my solution is not perfect, it seems to work. Basically, Safari seems to look for an input field with password and username and always tries to fill it. So, my solution was to add a fake username and password field before the current one which Safari could fill. I tried using style="display: none;" but that did not work. So, eventually, I just used
<input id="fake_user_name" name="fake_user[name]" tabindex="-1"
               style="display:none;" type="text" value="Safari Autofill Me"

and this hid the input field out of sight and seemed to work fine.
I did not want to use JavaScript but I guess you could hide it with JavaScript.
Now Safari never autocompletes my username and password fields.

A: I have also been bitten by Safari's weird default autocomplete behaviour, but rather than completely disable it, I managed to make it work for me by following the guidelines at https://www.chromium.org/developers/design-documents/form-styles-that-chromium-understands.
Specifically, I put autocomplete="username" on the username field and autocomplete="password-current" on the password field. This tells the browser which fields to autofill, rather than having it guess, and it fixed autocomplete for my use case.
This approach works for both "email first" login forms (password field not immediately visible, eg Google login) as well as conventional login forms with both username and password fields visible.

A: Fix: browser autofill in by readonly-mode and set writable on focus
 <input type="password" readonly onfocus="this.removeAttribute('readonly');"/>

(focus = at mouse click and tabbing through fields)
Update:
Mobile Safari sets cursor in the field, but does not show virtual keyboard. New Fix works like before but handles virtual keyboard:
<input id="email" readonly type="email" onfocus="if (this.hasAttribute('readonly')) {
    this.removeAttribute('readonly');
    // fix for mobile safari to show virtual keyboard
    this.blur();    this.focus();  }" />

Live Demo https://jsfiddle.net/danielsuess/n0scguv6/
// UpdateEnd
Explanation: Browser auto fills credentials to wrong text field?
Ok, you just noticed that:

Safari autofill kicks in. No matter [what the fields are named] @Jari

and there's an assumption that:

Safari seems to look for an input field with password and username and always tries to fill it @user3172174

Sometimes I notice this strange behavior on Chrome and Safari, when there are password fields in the same form. I guess, the browser looks for a password field to insert your saved credentials. Then it autofills username into the nearest textlike-input field , that appears prior the password field in DOM (just guessing due to observation). As the browser is the last instance and you can not control it,
sometimes even autocomplete=off would not prevent to fill in credentials into wrong fields, but not user or nickname field.
This readonly-fix above worked for me.

A: Adding the CSS to the input will hide the Safari button pseudo-element and users will not be able to use autocomplete:

input::-webkit-contacts-auto-fill-button,
input::-webkit-credentials-auto-fill-button {
  visibility: hidden;
  position: absolute;
  right: 0;
}

A: My issue: I have a section in an admin area that allows users to set all language values, some of which contain the words "password", "email", "email address" etc. I don't want these values to be filled with the user's details, they are for creating translations into another language. This is then a valid exception to the "circumvent the browser's preference" mentioned.
My solution: I simply created alternate names:
$name = str_replace('email','em___l',$name);
$name = str_replace('password','pa___d',$name);

<input type="text" name="<?=$name?>" id="<?=$name?>" />

Then when the form is posted:
foreach($_POST as $name=>$value) {
    $name=str_replace('em___l','email',$name);
    $name=str_replace('pa___d','password',$name);
    $_POST[$name]=$value;
}

This is the only method that worked for me.

A: For me, this problem was very sharp. But only about password autofill.
Safari generates it's 'strong' password into a sign-in form. Not a sign-up form. Only the user's password will work in sign-in form, not generated. Obvious.
I made a few tries to disable it with advice from here. But without results.
BTW. It was easy to fix with angular binding. So. This code will work 4 you only in case of using Angular2+ in the web layer.
<mat-form-field appearance="fill">
  <mat-label>Enter your password</mat-label>
  <input #pwd
         matInput
         [type]="pwd.value.length === 0 ? 'text': 'password'"
         formControlName="passwordCtrl"
  required>
</mat-form-field>

Attribute [type] use one side binding with "[", "]". And automatically set value by the condition "(condition) ? option1: option2". If no symbols in the input - then the type is 'text'.
And not very 'clever' Safari browser doesn't perform autofill. So. Goal reached. Autofill disabled.
After more than 1 symbol in the input field. Type changes to 'password' very fast. And the user has no idea about something that happened. The type of the field is 'password'.
Also, it works with (keypressed) Event. Or using [(ngModel)]="pwd" instead of #pwd. And access by reactive forms.
But the basic thing that solved the problem for my cases - angular binding.

A: I came up with a similar solution to Nikita Danilov's, but for vanilla JavaScript instead of Angular.
Basic principle is for the field to start off as a generic type like "text" or "number", then switch to "password" or "email" where appropriate. onkeydown is a good event to bind here - should work on Desktop and Mobile.
Example:
<input
  type="text"
  name="password"
  id="password"
  autocomplete="off"
  onkeydown="this.setAttribute('type','password')"
>

While I understand the points made against introducing this behaviour, I think many make an assumption that the context of a password field is always a login / registration form that the end-user interacts with. In some cases e.g. where passwords or other details are being set on admin panels, by users other than the end-user, I believe it is justified to avoid engaging the browser's autofill, as it is linked against the current user's personal data. In such case the current user, is not the end-user.

A: You can try this variant. It works for me.
If you change field value once, Safari will change it again. If user clicked at this field, after this the value wouldn't be changed by Safari automatically.
  $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
        if($.browser.chrome){
            $.browser.safari = false;
        }

        var isChanged=false;

        $('#Email').change(function () {
            if ($.browser.safari && !isChanged) {
                $('#Email').val('@Model.Email');
            }
        });

        $('#Email').click(function () {
            if ( $.browser.safari && !isChanged) {
                isChanged = true;
            }
        }); var isChangePassword = false;
    $('#OldPassword').change(function () {
        if ($.browser.safari && !isChangePassword) {
            $('#OldPassword').val('');
        }
    });

    $('#OldPassword').click(function () {
        if ($.browser.safari && !isChangePassword) {
            isChangePassword= true;
        }
    });

A: Better than use JS to clear content - simply fake password field:
<input type="text" name="user" />
<input fake_pass type="password" style="display:none"/>
<input type="password" name="pass" />

A password type doubled put the browser in incertitude so it autocompletes only user name
fake_pass input should not have name attribute to keep $_POST clean!

A: It seems the browser programmers think they know more than the website writers. While it's sometimes handy to allow the user to save passwords, there are other times when it's a security risk. For those times, this workaround might help:
Start by using a conventional text input, instead of a 'password' type.
Password: &nbsp <input type="text" id="fkpass" name="bxpass" class="tinp" size="20" />

Then - if you wish - set the focus to the input field.

Put the JS at the end of the page.

Now you have a conventional form field. What good is that?
Change the CSS style for that input so it uses a font that is all 'bullets' instead of characters.

Yes, you could 'tidy up' the code, and add .svg to it.
Either way, the end result is indistinguishable from the 'real' password input, and the browser won't offer to save it.
If you want the font, it's here.
It was created with CorelDraw and converted with an online webfont conversion utility.  (dot_webfont_kit.zip  19.3k)
I hope this helps.

A: Remove <form> element. To keep form behavior you can listen keypress event for input fields to handle enter key pressed. Just in case I removed input type="submit" too. You can use button type="button".

A: The CSS display: none solutions mentioned here did not work for me (October 2016). I fixed this issue with JavaScript.
I don't mind the browser remembering passwords, but wanted to prevent a bad autofill. In my case, a form with a password field and no associated username field. (User edit form in Drupal 7 site, where the password field is required only for some operations.) Whatever I tried, Safari would find a victim field for the username of the autofilled password (the field placed visually before, for instance).
I'm restoring the original value as soon as Safari does the autofill. I'm trying this only for the first 2 seconds after page load. Probably even lower value is OK. My tests showed the autofill happens around 250 ms after page load (though I imagine this number depends a lot on how the page is constructed and loaded).
Here's my JavaScript code (with jQuery):
// Workaround for Safari autofill of the e-mail field with the username.
// Try every 50ms during 2s to reset the e-mail to its original value.
// Prevent this reset if user might have changed the e-mail himself, by
// detecting focus on the field.
if ($('#edit-mail').length) {
  var element = $('#edit-mail');
  var original = element.attr('value');
  var interval = setInterval(function() {
    if ($(document.activeElement).is(element)) {
      stop();
    } else if (element.val() != original) {
      element.val(original);
      stop();
    }
  }, 50);
  var stop = function() {
    clearTimeout(timeout);
    clearInterval(interval);
  }
  var timeout = setTimeout(function() {
    clearInterval(interval);
  }, 2000);
}

A: I had the same problem suddenly in a SPA with React in Mobile Safari 10.3.1
I do not need any tricky workarounds before in all tested browsers, even Mobile Safari IOS 10.2
But since 10.3.1 username or password will be filled in fields mentioning the words 'password','email','username' in any forms after login with active remember option. It seems that the rendered DOM-Tree is 'analyzed' using a full text search and then the user agent fill in data without respecting any autocomplete="off" setting.
Happens funnyli also on placeholder text for a field. So you must be very carful with naming, when you don't want to have prefilled username or password in places where this data is not useful.
The only solution after hours of investigating was the solution here posted too.
Provide a input field named "email" and hideout the containing div with height: 0px, overflow: hidden.

A: You can disable it by adding this attribute to password input
autocomplete="new-password"


text:
Q: Altium: Error on PCB Footprint Updating I am using Altium 14.1.5
I made a change to a footprint in a non-integrated library and then wanted to update my PCB with the new footprint and it is not updating properly. I may be doing something wrong.
Here is the scenario: the part is on the bottom side (all silk, pads, etc). When I go to the Tools>Update PCB With Current Footprint and click ok with all the boxes checked

my footprint on the PCB rotates 180 degrees and the silk is now on the topside (pads and everything else stays on the bottom). However, when I look at the part information nothing has changed, not even the rotation.
Properties Before:

Properties After:

I erased some information due to confidentiality.
I am not sure why this is happening. Is it a bug that used to be in the in the older version of Altium?
I am adding a pic of the PcbLib footprint and the before and after of what I am trying to explain.
PcbLib:

PCB Before:

PCB After:


text:
Q: constructor for 'SiteList' must explicitly initialize the member 'sites' which does not have a default constructor I have a class called SiteList that contains an array that contains Site objects. But when I compile, I get an error that reads,

error: constructor for 'SiteList' must explicitly initialize the member 'sites' which does not have a default constructor

Can anybody help me out?
Here is my header file SiteList.h
#include <iostream>
#include "Site.h"
using namespace std;

class SiteList {
public:
    int getLength();
    string checkStatus(int, int);
    void printList();
    void inputData(Site);
    SiteList(Site);
private:
    Site sites[600];
    int arrayCounter;
};

And my constructor (just my constructor)
SiteList::SiteList(Site site){
    sites[600];
    arrayCounter = 0;
}

A: First of all I do not understand why the constructor has parameter Site site that is not used?
SiteList::SiteList(Site site){
    sites[600];
    arrayCounter = 0;
}

Also this statement
sites[600];

means access to element of the array sites with index 600. It is obvious that it has no any sense.
As for the error message then it is clear enough:class Site has no default constructor. What do you not understand in this phrase?
When this constructor is called it tries to create data member Site sites[600]; calling the default constructor of type Site for each element of the array. But the class has no default constructor.
From the C++ Standard:

A default constructor for a class X is a constructor of class X that
  can be called without an argument.

You should provide the default constructor for class Site.
Some additional remarks
Member functions getLength and printList should be defined as constatn functions
int getLength() const;
void printList() const;

instead of the magic number 600 it is better to introduce a symbolic constant. For example
private:
    static const int N = 600;
    Site sites[N];
    int arrayCounter;
};

A: In your constructor, the line
sites[600];

doesn't do what you think it does (probably). It refers to the element at index 600 of the sites array, and doesn't do anything with it. (Also, it's undefined behaviour, since the array only has indices 0 through 599.)
The compilation error arises because the Site class, presumably, has no default constructor. If a class has no default constructor, then the compiler doesn't know how to initialize it unless you explicitly provide constructor arguments. And yet, every time you instantiate a SiteList, you create an array of Site objects, so the compiler has to know how to initialize Site objects.
The solution is to add a default constructor for Site, i.e.,
Site::Site() {
    // ...
}


text:
Q: Add IFCONFIG in config.xml I have a requirement where I need to add my custom discount block only if the discount module is enabled from backend. I can obviously add it in using getStoreConfig() values, but I need to know is it possible to add IFCONFIG in our modules etc/config.xml file ?
Below is my sample config.xml file code but somehow its not working.
<global>
    <sales>
          <quote>
                <totals>
                    <testing ifconfig="mysettings/foo/sayhello">
                        <class>NameSpace_ModuleName_Model_Testing</class>
                        <after>subtotal</after>
                    </testing>
                </totals>
            </quote>
     </sales>
</global>

A: The ifconfig attribute only works in certain layout XML definitions, not in config XML files
You would have to go with your idea of checking with getStoreConfig() in your custom class.
It is possible to inject custom XML values conditionally at run-time, but there is no good place for it at the moment so the best idea would be to override the core config model and pass your own version into the bootstrapper in index.php (meaning this also has to be done for all shell/external scripts)
When we're on the subject of quote totals and the <after> tag, make sure you don't have any other third party modules or admin settings that modify the sort order and gives you unexpected results. You might need to specify <before> as well, together with multiple comma-separated totals codes in both.


text:
Q: How to loop json data in jquery or filter a certain data so that it wont repeat I'm confuse on jquery, it's not the same on php.

I want to achieve this kind of table but the output of my jquery is this

Here is my json

Jquery:
$.get('/dev/api/getPODetails?id=' + id, function(data){

            $.each(data, function(index, getPODetails){

               $('.table tbody').append('
'+getPODetails.id+'
');
                      $('.table tbody').append('
'+getPODetails.itemdesc+'
');
                })
            })
    });

I don't know what's the problem of the loop, all I want is to display none repeating PO#. Can someone share some idea? Thank you in advance.

A: Try this, i make it easier way:
Controller:
public function getPOHeader(){

        $supplierid = Input::get('id');

        $getPOHeader = PurchaseHeader::where('partner_id', $supplierid)
                        ->get();
        return Response::json($getPOHeader, 200, array(), JSON_PRETTY_PRINT);
    }

    public function getPODetails(){

            $supplierid = Input::get('id');

            $getPODetails = DB::table('purchase_details')
                            ->where('purchase_details.po_no_id', $supplierid)
                            ->leftJoin('items', 'purchase_details.item_id', '=', 'items.id')
                            ->join('uoms', 'purchase_details.uom_id', '=', 'uoms.id')
                            ->select('items.description as itemdesc', 'purchase_details.qty as ordered', 'uoms.name as uom',
                                        'purchase_details.price as unitprice', 'purchase_details.disc as disc', 'purchase_details.disc_type as disc_type',
                                        'purchase_details.total_amt as netunitprice')
                                ->get();

            return Response::json($getPODetails, 200, array(), JSON_PRETTY_PRINT);
    }

My view:
 $.get('/dev/api/getPOHeader?id=' + id, function(data){
    $.each(data, function(index, getPOHeader){

        $.get('/dev/api/getPODetails?id=' + getPOHeader.id , function(data1){
         $('.table tbody').append('
PO #'+getPOHeader.id+'
');
         $.each(data1, function(index, getPODetails){
            $('.table tbody').append('
'+getPODetails.itemdesc+'	'+getPODetails.ordered+'	---------	<input type="text" name="" >	'+getPODetails.uom+'	'+getPODetails.unitprice+'	'+getPODetails.disc+'	'+getPODetails.disc_type+'	'+getPODetails.netunitprice+'	00.00
');
         })
       })
    })
});

and the route:
Route::get('dev/api/getPOHeader','Search\SearchDataController@getPOHeader');
Route::get('dev/api/getPODetails','Search\SearchDataController@getPODetails');

A: You have to take a separate javascript array so that no element repeats in the loop.
$.get('/dev/api/getPODetails?id=' + id, function(data){
    var dataDisplayed = [];

    $.each(data, function(index, getPODetails){
        if(jQuery.inArray(getPODetails.id, dataDisplayed) !== -1)
        {
            return;
        }
        $('.table tbody').append('
'+getPODetails.id+'
');
        $('.table tbody').append('
'+getPODetails.itemdesc+'
');
        dataDisplayed.push(getPODetails.id);
    })
});

I think the above code will work for you.. :-)

A: You have to store a reference to the id somewhere.
$.getJSON('/dev/api/getPODetails?id=' + id, function(data){
  var store = {};

  for (var i = 0, len = data.length; i < len; ++i) {
    if (!store[data[i].id]) = {itemdesc: data[i].itemdesc, ordered: 0}

    store[data[i]].ordered += parseInt(data[i].ordered);
  }

  for (var key in store) {
    $('.table tbody')
      .append('
' + store[key].id + '
')
      .append('
' + store[key].itemdesc + '
');
  }
});

Or something like
$.getJSON('/dev/api/getPODetails?id=' + id, function(data){
  var used = [];

  for (var i = 0, len = data.length; i < len; ++i) {
    if (used.indexOf(data[i].id) < 0) {
      $('.table tbody')
        .append('
' + data[i].id + '
')
        .append('
' + data[i].itemdesc + '
');

      used.push(data[i].id);
    }
  }
});


text:
Q: $timeout not changing variable in angularjs I am working on a button and trying to shake it on clicking it if the form fields above it are invalid.
Here is my code for the controller :-
if(valid){.. do valid stuff here ..}

else{
console.log(this.shakeNotValid);
        // SHAKE ANIMATION
        this.shakeNotValid = true;

        $timeout(function() {
            this.shakeNotValid = false;
        } , 500);
}

No where else is this.shakeNotValid is defined or assigned.
The console line returns me undefined for the first time and the button shakes but subsequently it keeps returning me true again and again and doesnt shake.
In the html I am assigning a class to the button like this :-
        <div ng-click="main.mClick()"
        ng-class="{isDisabled: !main.isValidContact && main.showContactCard,
        isShaking: main.shakeNotValid}">

What I want is that this button can shake multiple times until all becomes valid as and when the user clicks.
Some help please, thanks !

A: I believe that this in this.shakeNotValid = true and this in this.shakeNotValid = false are two different objects.
If I were you, I'd try to change your code the following way and try it out:
if(valid){.. do valid stuff here ..}

else {
        _this = this;
        console.log(_this.shakeNotValid);
        // SHAKE ANIMATION
        _this.shakeNotValid = true;

        $timeout(function() {
            _this.shakeNotValid = false;
        } , 500);
}


text:
Q: accessing androids auto correct facilities? Is there a way of using Android's auto correct / predictive text capabilities with a bespoke input method? I'd like to be able to access a list of the nearest words to the word entered, similar to what happens when we send a text. For example if I entered the string "hapy" I would get a list containing "happy", harpy", "hazy" ...

A: Looks like a yes.
And the place to start: http://developer.android.com/guide/topics/text/spell-checker-framework.html

A: You wouldn't want to.  First off, predictive text was only turned into a service with 4.0.  Before then it was just part of the keyboard, and most keyboards still implement their own I suspect.  Secondly, it would be optimized for typing mistakes, not voice mistakes.  Typing g instead of f is common (they're next to each other), doing it by voice is not.  It wouldn't work well.
But the built in voice to text behavior does return alternatives-  it returns an array list of possible texts.  That is your auto-correct.


text:
Q: Mysql multiple limit i have created a query for my packages.
SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT * FROM wp_posts
    INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
WHERE 1=1
    AND (((wp_posts.post_title LIKE '% %')
       OR (wp_posts.post_content LIKE '% %')))
    AND wp_posts.post_type = 'listing_type'
    AND (wp_posts.post_status = 'publish'
       OR wp_posts.post_status = 'private')
    AND ( (wp_postmeta.meta_key = 'packageID'
    AND CAST(wp_postmeta.meta_value AS CHAR) = '4'
       OR CAST(wp_postmeta.meta_value AS CHAR) = '1'
       OR CAST(wp_postmeta.meta_value AS CHAR) = '2'
       OR CAST(wp_postmeta.meta_value AS CHAR) = '3'
       OR CAST(wp_postmeta.meta_value AS CHAR) = '0' ) )
GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value  ASC, wp_posts.post_date DESC`

It is working fine. But now i want to set limit in each meta_key value so based on that i can display the products in my packages.
Thanks
Sanket

A: Try this:
SELECT SQL_CALC_FOUND_ROWS DISTINCT *
FROM wp_posts wp
INNER JOIN wp_postmeta wpm ON (wp.ID = wpm.post_id)
WHERE 1=1 AND (((wp.post_title LIKE '% %') OR (wp.post_content LIKE '% %'))) AND
      wp.post_type = 'listing_type' AND wp.post_status IN ('publish', 'private') AND
      wpm.meta_key = 'packageID' AND wpm.meta_value IN (0, 1, 2, 3, 4)
GROUP BY wp.ID
ORDER BY wpm.meta_value  ASC, wp.post_date DESC
LIMIT 10


text:
Q: Images from my stylesheet will not load I currently using WAMP Server 2.1 on both my own computer and on my girlfriends laptop. I synchronizing my files through Dropbox and I link some images (the logotype, background-image, etc.) via my stylesheet to my personal website.
The images is visible on my own computer but they are just gone on my girlfriends laptop, just like as they are not on her computer which they are. All files are fully synchronized between these 2 computers and I ask you now; what do you think is wrong here?
WAMP Server has the same settings and modules on the laptop as on my computer.
Thanks in advance.

A: Check the path of image make sure that image is in www folder also check the directory .


text:
Q: Android Studio does not see the "android" package from the library file My MainActivity.java file starts like this:
package com.example.testble2;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

In the same project, the blessed module is created, with the BluetoothCentralManager.java file, which starts like this:
package com.example.blessed;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelUuid;

The problem is that in the BluetoothCentralManager.java file all import android.* directives are marked in red with the message "Cannot resolve symbol". Please help me to solve this problem.

A: The problem was that the module was created with the command: menu -> new module -> java library, and should be created with the command: menu -> new module -> android library


text:
Q: UPS for 30A service to server racks Our server rack has two 208V 30A dedicated circuits running to it, each to a PDU mounted in the rack. Most of the equipment has redundant power supplies so one goes to each PDU. I'm not sure who had this installed but it seems like overkill for our relatively modest amount of equipment -- this is not a high-density data center.
Our building gets frequent power flickers and we'd like to get a UPS in there to keep things running smoothly. The rack currently houses our SAN, so losing power unexpectedly is not ideal.
The problem is that I'm having trouble finding a UPS for 208V/30A service. If we want to keep our dual power supply setup we're looking at dual 4kW UPS's at a total of $10k or so, which just seems silly when our power draw is closer to 1kW total.
Is this 208V/30A setup standard and I'm just not looking in the right place for power equipment? Should we have an electrician change the L6-30 connectors for L6-20 connectors and put in a 20A breaker instead? Our other server rack runs just fine off a single 120V/20A circuit.

A: Looking at APC, you can buy a 2.1kW online UPS (SURTD3000XLT) for about $2k each.  Or a step-down transformer (AP9626) for about $500 each.
Electricians cost money as well.  It would be a shame to downgrade your circuit and find you need it a couple years later.

A: Changing out the outlets to downgrade from 30A to 20A is not ideal. Remember that you'll want to calculate maximum draw from a particular leg and/or PDU. Maximum draw is presented when a server/equipment first starts up. Also, if a power supply goes bad or is unplugged, the load is solely on one leg of your supply.
We installed L6-30 outlets across our datacenter, even for the racks with low density. We're using a APC SymmetraPX. This unit delivers 3 legs/phases of 30A service. From there, we can essentially load balance between the 3 phases to even out the load.
One aspect we were calculating for in the wiring is the rare event that everything needs to be shutdown. When those servers come back online, they'll all be pulling quite a bit more amperage. Unless you're starting one at a time, you may need those 30A circuits.
When you're looking for a battery backup unit, always calculate max load for each systems; then give some more. As stated, APC makes a great product and they should be able to accommodate 5kw and below. Eaton is also another good product that can easily scale with lower end loads.


text:
Q: Add XElement to XML file with formatting and indenting XML
Source XML
<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement>
</Root>

Desired XML
<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement>

    <ThirdElement>
        <FourthElement>thevalue</FourthElement>
    </ThirdElement>
</Root>

Now my output XML is
<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement><ThirdElement><FourthElement>thevalue</FourthElement></ThirdElement>
</Root>

Note that I need to load the XML with LoadOptions.PreserveWhitespace as I need to preserve all whitespaces (desired by customer).
The desired output is to put 2 newlines after the last child element of the "root" and add with the proper indent
<ThirdElement>
    <FourthElement>thevalue</FourthElement>
</ThirdElement>

Any ideas how to realize this?
Code
var xDoc = XDocument.Load(sourceXml, LoadOptions.PreserveWhitespace); //need to preserve all whitespaces
var mgr = new XmlNamespaceManager(new NameTable());
var ns = xDoc.Root.GetDefaultNamespace();
mgr.AddNamespace("ns", ns.NamespaceName);

if (xDoc.Root.HasElements)
{
    xDoc.Root.Elements().Last().AddAfterSelf(new XElement(ns + "ThirdElement", new XElement(ns + "FourthElement", "thevalue")));

    using (var xw = XmlWriter.Create(outputXml, new XmlWriterSettings() { OmitXmlDeclaration = true })) //omit xml declaration
        xDoc.Save(xw);
}

A: Ideally, you should explain to your client that this really isn't important.
However, if your really need to mess around with whitespace, i'd note that XText is what you need. This is another XObject that represents text nodes and can be interspersed as part of your content. This is probably a much better approach than string manipulation.
For example:
doc.Root.Add(
    new XText("\n\t"),
    new XElement(ns + "ThirdElement",
        new XText("\n\t\t"),
        new XElement(ns + "FourthElement", "thevalue"),
        new XText("\n\t")),
    new XText("\n"));

See this demo.

A: My solution is to beautify just before saving by reparsing the document.
string content = XDocument.Parse(xDoc.ToString()).ToString();
File.WriteAllText(file, content, Encoding.UTF8);