text:
Q: Creating Microsoft Word (.docx) documents in Ruby Is there an easy way to create Word documents (.docx) in a Ruby application? Actually, in my case it's a Rails application served from a Linux server.
A gem similar to Prawn but for DOCX instead of PDF would be great!

A: You can use Apache POI. It is written in Java, but integrates with Ruby as an extension

A: This is an old question but there's a new answer. If you'd like to turn an HTML doc into a Word (docx) doc, just use the 'htmltoword' gem:
https://github.com/karnov/htmltoword
I'm not sure why there was answer creep and everyone started posting templating solutions, but this answers the OP's question. Just like Prawn, except Word instead of PDF.
UPDATE:
There's also pandoc and an API wrapper for pandoc called docverter. Both have slightly complicated installs since pandoc is a haskell library.

A: I know if you serve a HTML document as a word document with the .doc extension, it will open in Word just fine. Just don't do anything fancy.
Edit: Here is an example using classic ASP. http://www.aspdev.org/asp/asp-export-word/

A: As has been noted, there don't appear to be any libraries to manipulate Open XML documents in Ruby, but OpenXML Developer has complete documentation on the format of Open XML documents.
If what you want is to send a copy of a standard document (like a form letter) customized for each user, it should be fairly simple given that a DOCX is a ZIP file that contains various parts in a directory hierarchy. Have a DOCX "template" that contains all the parts and tree structure that you want to send to all users (with no real content), then simply create new (or modify existing) pieces that contain the user-specific content you want and inject it into the ZIP (DOCX file) before sending it to the user.
For example: You could have document-template.xml that contains Dear [USER-PLACEHOLDER]:. When a user requests the document, you replace [USER-PLACEHOLDER] with the user's name, then add the resulting document.xml to the your-template.docx ZIP file (which would contain all the images and other parts you want in the Word document) and send that resulting document to the user.
Note that if you rename a .docx file to .zip it is trivial to explore the structure and format of the parts inside. You can remove or replace images or other parts very easily with any ZIP manipulation tools or programmatically with code.
Generating a brand new Word document with completely custom content from raw XML would be very difficult without access to an API to make the job easier. If you really need to do that, you might consider installing Mono, then use VB.NET, C# or IronRuby to create your Open XML documents using the Open XML Format SDK 1.0. Since you would just be using the Microsoft.Office.DocumentFormat.OpenXml.Packaging Namespace to manipulate Open XML documents, it should work okay in Mono, which seems to support everything the SDK requires.

A: Using a technique very similar to that suggested by Grant Wagner I have created a Ruby html to word gem that should allow you to easily output Word docx files from your ruby app. You can check it out at http://github.com/nickfrandsen/htmltoword - Simply pass it a html string and it will create a corresponding word docx file.
def show
  respond_to do |format|
    format.docx do
      file = Htmltoword::Document.create params[:docx_html_source], "file_name.docx"
      send_file file.path, :disposition => "attachment"
    end
  end
end

Hope you find it useful. If you have any problems with it feel free to open a github issue.

A: Disclosure: I'm the leader of the docxtemplater project.
I know you're looking for a ruby solution, but because all other solutions only tell you how to do it globally, without giving you a library that does exactly what you want, here's a solution based on JS or NodeJS (works in both)
DocxTemplater Library
Demo of the library
You can also use it in the commandline:
npm install docxtemplater -g

docxtemplater <configFile>

----config.docxFile: The input file in docx format
----config.outputFile: The outputfile of the document

A: This is a way Doccy (doccyapp.com) has a api that does just that which you can use. Supports docx, odt and pages and converts to PDF as well if you like

A: Further to Grant's answer, you can also send Word a "Flat OPC" file, which is essentially the docx unzipped and concatenated to create a single xml file. This way, you can replace [USER-PLACEHOLDER] in one file and be done with it (ie no zipping or unzipping).

A: If anyone is still looking at this, this post explains how to use an XML data source.  This works nicely for me.
http://seroter.wordpress.com/2009/12/23/populating-word-2007-templates-through-open-xml/

A: Check out this github repo: https://github.com/jawspeak/ruby-docx-templater
It allows you to create a document from a word template.

A: Maybe this gem is interesting for you.
https://github.com/trade-informatics/caracal/
It like prawn but with docx.

A: If you're running on Windows, of course, it's a matter of WIN32OLE and some pain with the Word COM objects.
Chances are that your serving from a *nix environment, though. Word 2007 uses the "Microsoft Office Open XML" format (*.docx) which can be opened using the appropriate compatibility pack from Microsoft.
Some of the more recent Office apps (2002/XP and 2003 at least) had their own XML formats which may also be useable.
I'm not aware of any Ruby tools to make the process easier, sadly.
If it can be made acceptable, I think I'd be inclined to go down the renamed-html file route. I just saved a document as HTML from WordXP, renamed it to a .doc and opened it without problem.

A: I encountered the same problem. Unfortunately I could not manipulate the xml because my clients should themselves to fill in templates. And to do this is not always possible (for example, office for mac does not allow this).
As a solution to this problem, I made a simple gem, which can be used as an rtf document template with embedded ruby: https://github.com/eicca/rtf-templater
I tested it and it works ok for filling reports and documents. However, formatting badly displays for complex loops and conditions.


text:
Q: mount same tmpfs on two mountpoints I have this in my /etc/fstab:
tmpfs   /home/user1/tmp tmpfs  rw,nodev,nosuid,noexec,size=16G  0   0

user1 has tmpfs mounted as /home/user1/tmp.
I would like to mount same tmpfs for user2 as well, so that they can share same tmpfs.
How can I do this in fstab, so that user2 has same tmpfs mounted at /home/user1/tmp ?

A: Add another line with a bind mount:
/home/user1/tmp /home/user2/tmp none bind,x-systemd.requires=/home/user1/tmp

The systemd is just for ordering, but you may not need/want it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting error of Null type with getelementbyid in html I am Struck at simple code , getelementbyid.innerHtml in html page. Please help me.

<!doctype html>

  <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You

A: Your javascript is called before your browser render your HTML page. So when your browser call getElementById the ID isn't defined.
Just move your javascript at the end of your file

A: Just move the script below... the causing is beacause the id isnt render yet.

<!doctype html>

  <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You

A: Utilize onload property of window to call a function when window has loaded

<!doctype html>

  <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You

A: just put the script part before close body and it will work.

<!doctype html>

        <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You

A: Browsers parses html page from top to down. So, if you put your script in the head, it will get rendered first and then your body. So your script is searching for an id which is yet not rendered to the DOM.
By placing script at the bottom, it solves your problem.

<!doctype html>

  <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You

A: It is working fine just use script tag in end. For more clearity check.
https://jsfiddle.net/djmayank/Lzewxgyw/
HTML

        <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You

JS
var code = document.getElementById("one").innerHTML;
        code = code + " !!";
        console.log(code);

A: The script is loaded before your element with the id of one is loaded, therefore one does not exist yet. You have the following options:

*

*You put the script after the tag you need:

<!doctype html>

        <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You

*Make a function and use the onload attribute, which is preferable, as the code will be reusable for other features:

<!doctype html>

        <title>Dom examples</title>

 DOM practise page

 This page is for practise of DOM model in JS

 Thank You


text:
Q: how can I show the console of a headless running vbox vm I have a virtualbox headless VM running on CentOS 7. I can show the console of the VM by opening up the virtualbox manager, right clicking the machine and choose "Show". Is there a way to do this (pop up the head of the headless client) without opening up the gui manager, i.e., from the command line? I've tried most likely commands for vboxmanage but get errors or the wrong result.

A: So far, no answers. After more research it looks like VirtualBox does not provide this functionality. Best that it seems I can do is to use a remote desktop. For my CentOS, the most convenient app is rdesktop. You need to have the extension pack installed. Then enable remote desktop protocol for the client. Once the VM is running you can then use rdesktop to access the client console. If rdesktop is started immediately after the VM, you do get access to the boot sequence. Thus:
$ vboxmanage modifyvm "archive" --vrde on
$ vboxmanage startvm "archive" --type headless ; rdesktop localhost


text:
Q: Php sessions only work in Google Chrome My php sessions only work in Google Chrome.  Every other browser they don't appear.  Does anyone know why?
Here is my code for the first page...
 <?php
 // this starts the session
 session_start();

 // this sets variables in the session
 $_SESSION['color']='red';
 $_SESSION['size']='small';
 $_SESSION['shape']='round';
 print "Done";
 ?>

Here is my code for the second page...
 <?php
 // this starts the session
 session_start();

 // echo variable from the session, we set this on our other page
 echo "Our color value is ".$_SESSION['color'];
 echo "Our size value is ".$_SESSION['size'];
 echo "Our shape value is ".$_SESSION['shape'];
 ?>

On the second page it will not display the session variables in any browser other than Chrome.  Does anyone know how to fix this?

A: Perhaps cookies aren't enabled on your test browsers, or maybe the security level is set too high (for IE).
Try enabling them else make sure they're being set correctly.


text:
Q: Create a new column using detecting the domain of a url from an existing column I would like to create new column to the existing dataframe I have which will has as value for every row a specific url. This url exists in every row of the Content column of the following dataframe:
data <- read.table(text='"Content"     "date"
  1     "a house a home https://example.com"     "12/31/2013"
  2     "cabin ideas http://example.com/name in the woods"     "5/4/2013"
  3     "motel is a hotel www.example.com"   "1/4/2013"', header=TRUE)

However the problem is that the url contains different version but the domain remain the same. The domain is this example.com. How is it possible to create the new column with urls using only the domain to detect it in every row?

A: library(tidyverse)

data <- read.table(text = '"Content"     "date"
  1     "a house a home https://example.com"     "12/31/2013"
  2     "cabin ideas http://example.com/name in the woods"     "5/4/2013"
  3     "motel is a hotel www.example.com"   "1/4/2013"', header = TRUE)

data %>%
  mutate(url = Content %>% str_extract("(www\\.|http[s]?://)[A-z0-9./]*"))
#>                                            Content       date
#> 1               a house a home https://example.com 12/31/2013
#> 2 cabin ideas http://example.com/name in the woods   5/4/2013
#> 3                 motel is a hotel www.example.com   1/4/2013
#>                       url
#> 1     https://example.com
#> 2 http://example.com/name
#> 3         www.example.com

Created on 2022-03-30 by the reprex package (v2.0.0)
If this does not work you might expand your regex e.g. (?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])


text:
Q: Minimum space for N points at distance D A few days ago, a certain government announced, as part of an incipient Covid-19 lockdown de-escalation plan, that they would allow citizens to gather in groups of up to 10 people at their homes, as long as the security distance of 2 metres was respected. In my effort to figure out just how disconnected the members of this government are from the reality of said citizens, I wondered how big a room I would need to hold a gathering of 10 people, all separated 2 metres apart from each other.
More generally, I would like to know how much space I would need to have $N$ points separated by a minimum distance $D$. By space, initially I was thinking of the area of for example a rectangle, or a (convex?) polygon in general, but then I realised I could "cheat" and put every point in a line and have a $D(N-1)\times 0$ rectangle with null area. So I have two possible "valid" statements for the problem:

*

*What is the side of the smallest square containing $N$ points separated by a distance of at least $D$ from each other?

*What is the smallest perimeter of a polygon (or convex polygon if preferred) containing $N$ points separated by a distance of at least $D$ from each other?

I have been thinking about it for a while, mostly about the square version, and I feel the answer may not be trivial. I think if $N=M^2$ is a perfect square then a square with side $D(M-1)$ would contain all points optimally in a grid. For example, for $N=9$ you would have this $2D$ side square:

But I don't think that if I add a single more point, then I would need to increase the each side by $D$. In fact, I think for $N=13$ the optimal may be this $2\sqrt{2}D$ side square, still smaller than the next $D$ increment to the side that would be optimal for $N=16$ ($3D$):

Is there a solution to each of these problems, or some closely related one?

A: This is the problem of how big a square you need to fit $N$ $1$ meter disks.  This is a hard problem.  Many results are at http://www.packomania.com/  If you just look at the pictures you can see that the best known packing is often not symmetric.  In particular, for $n=10$ the best known packing is into a square about $6.4764$ meters on a side.  You can subtract $2$ in each direction as the edge people do not need to be $1$ meter from the wall, giving a $4.4764$ meter square.The specific packing is not easy to describe.
For large $N$ you can just assume hexagonal packing.  Each person then occupies an area of $2 \sqrt 3$.  There is some error along the edge, but that goes down as $N$ gets large.


text:
Q: Apache SVN realtime recommended backup solution I have an apache subversion running in production environment, the repository size is around 100 GB. Now I am trying to build a failover standby for the primary SVN server. I have gone through a couple of backup mechanisms, but I couldn't find an ideal one which is apt of my failover setup. Can anyone could suggest me an ideal solution for a realtime backup for svn with easy failover and disaster recovery.
I have the following backup info, but I need to know which is the most recommended one.

*

*Using svnadmin dump for complete backup. (for 100GB everytime this would be a head ache, restoring is also a pain)

*Using svnadmin dump with incremental backup. (This is my current backup scenario, It take incremental backups on a daily basis)

*rsync the primary svn directory to standby host. (I am not sure about the integrity of files using this mechanism. Any sudden outage on primary could left a corrupted svn repo on secondary.? Im not sure about this)

*Using svnsync for mirroring repositories.
Please suggest how to move forward with valuable comments.
Thanks
Arun

A: svnadmin hotcopy is more reliable (and easy) way, than incremental dumps (and, BTW, it "just work").
Rsynced (or by any other way copied on file-level) repositories can't be broken anyway - SVN is transaction-based, you just skip and will not see not finished in Main operation on Backup


text:
Q: Making HTTPS requests within a Docker image behind a Zscaler firewall I'm interested in running a simple image like this behind a corporate Zscaler firewall:
FROM rocker/r-base
RUN apt-get update && apt-get install libssl-dev
CMD Rscript -e "install.packages('beepr')"

Building the image with docker build -t test . fails with errors like this:
Certificate verification failed: The certificate is NOT trusted. The certificate issuer is unknown.  Could not handshake: Error in the certificate verification. [IP: ]

I've tried some of the solutions from here but they don't work. For example:
FROM rocker/r-base

# Add local certificate to Docker
ADD ./zscaler.cer /usr/local/share/ca-certificates/zscaler.crt

# Move the certificate to the cert dir of openssl and update certificates
RUN CERT_DIR=$(openssl version -d | cut -f2 -d \")/certs ; cp /usr/local/share/ca-certificates/zscaler.crt $CERT_DIR ; update-ca-certificates

# Try making https requests
RUN apt-get update && apt-get install libssl-dev
CMD Rscript -e "install.packages('beepr')"

Same errors persist with docker build -t test .. I've read some possible solutions online but all of them continually fail either for apt-get or for installing packages with R. Is there anyone who has experienced this and found a fix?

A: Apparently, the current advice is slightly wrong. The certificate should not go in /etc/ssl/certs/ (which is the result of CERT_DIR=$(openssl version -d | cut -f2 -d \")/certs) but rather on CERT_DIR=/usr/local/share/ca-certificates/ (at least on this Ubuntu image). After changing that, update-ca-certificates correctly updates the certificate an all HTTPS requests are successful.
This should work now:
FROM rocker/r-base

# Add local certificate to Docker
ADD ./zscaler.pem /usr/local/share/ca-certificates/ZscalerRootCertificate-2048-SHA256.crt

# update certificates
RUN update-ca-certificates

# Try making https requests
RUN apt-get update && apt-get install libssl-dev
CMD Rscript -e "install.packages('beepr')"


text:
Q: @PostPersist doesn't save the Audit Record to the DB I have a Listener with @PostPersist method called "doAudit" to audit create action.On debugging I see This method gets called and Audit record is created on JAVA side. But when I verify the DB I don't see the record.
public class AuditListener {
    @PostPersist
    public void doAudit(Object object) {
        AuditDao auditManager = AuditDaoImpl.getInstance();
        auditManager.logEvent("create", object);
    }
}

public interface AuditDao {
    @Transactional(propagation= Propagation.REQUIRED)
    public AuditEntity logEvent(String action, Object object);
}

@Component
public class AuditDaoImpl implements AuditDao {

    private static AuditDaoImpl me;

    public AuditDaoImpl() {
        me = this;
    }

    public static AuditDaoImpl getInstance() {
        return me;
    }

    @Autowired
    private AuditDao dao;

    @Transactional
    @Override
    public AuditEntity logEvent(String action, Object object) {

        AuditEntity act = new AuditEntity();
        act.setAction(action);
        act.setObject(object);

        dao.create(act);
        return act;
    }
}

I am using Open JPA 2.0 as for my ORM. Deployed on karaf container. I am using Postgres SQL as my backend.

A: Add a debug breakpoint and check if the current stack-trace contains the TransactionInterceptor. If there's no such entry, the Spring transaction management is not properly configured and your DAOs don't use transactions at all.
JPA allows you to run queries without configuring transactions explicitly. For saving data, transactions are mandatory.


text:
Q: React app CodeShip-Heroku deployment: initial build breaks with 503 error code I'm deploying my React frontend with CodeShip and Heroku. I can open the application, but CodeShip shows that the build has broken, the cause being this:
Trying (1 of 6) 'wget --no-check-certificate --output-document=/dev/null http://******.herokuapp.com'
--2020-03-11 21:59:01--  http://******.herokuapp.com/
Resolving ******.herokuapp.com (******.herokuapp.com)... 52.214.138.78, 54.77.242.148, 54.171.40.67, ...
Connecting to ******.herokuapp.com (******.herokuapp.com)|52.214.138.78|:80... connected.
HTTP request sent, awaiting response... 503 Service Unavailable
2020-03-11 21:59:35 ERROR 503: Service Unavailable.

But when I check my Heroku logs after I open the root url I get this, none of them is Error 503.
2020-03-11T22:12:59.322877+00:00 heroku[router]: at=info method=GET path="/" host=******.herokuapp.com request_id=57f74e93-a951-4179-ae00-3761976d2656 fwd="176.63.10.67" dyno=web.1 connect=0ms service=3ms status=304 bytes=173 protocol=https
2020-03-11T22:12:59.389496+00:00 heroku[router]: at=info method=GET path="/sockjs-node" host=******.herokuapp.com request_id=516c3825-2bc9-4dfd-a4b9-7a84d2b40bf4 fwd="176.63.10.67" dyno=web.1 connect=1ms service=32093ms status=101 bytes=129 protocol=https
2020-03-11T22:12:59.475750+00:00 heroku[router]: at=info method=GET path="/static/js/0.chunk.js" host=******.herokuapp.com request_id=ab42c365-d66e-4439-be0a-525f425ebec5 fwd="176.63.10.67" dyno=web.1 connect=0ms service=32ms status=304 bytes=176 protocol=https
2020-03-11T22:12:59.476304+00:00 heroku[router]: at=info method=GET path="/static/js/main.chunk.js" host=******.herokuapp.com request_id=a78e6524-3792-42d6-8fab-760aa27aea3b fwd="176.63.10.67" dyno=web.1 connect=1ms service=32ms status=304 bytes=174 protocol=https
2020-03-11T22:12:59.451102+00:00 heroku[router]: at=info method=GET path="/static/js/bundle.js" host=******.herokuapp.com request_id=9e4977bc-ab8e-4cd5-8500-b3ebc411feaa fwd="176.63.10.67" dyno=web.1 connect=0ms service=5ms status=304 bytes=174 protocol=https
2020-03-11T22:12:59.793691+00:00 heroku[router]: at=info method=GET path="/manifest.json" host=******.herokuapp.com request_id=3b248e90-9da2-472a-9653-f0d25f840d76 fwd="176.63.10.67" dyno=web.1 connect=1ms service=6ms status=304 bytes=237 protocol=https
2020-03-11T22:12:59.809653+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=******.herokuapp.com request_id=7dab8f56-c457-42a1-a190-37f8a0a687fd fwd="176.63.10.67" dyno=web.1 connect=1ms service=21ms status=200 bytes=9780 protocol=https

The '/' root path returns this in my React code:
//App.js
<PublicRoute exact path='/' component={Home} layout={LandingLayout} />

//PublicRoute.js
const PublicRoute = ({ component: Component, layout: Layout, ...rest }) => (
    <Route {...rest} render={props => (
        <Layout>
            <Component {...props} />
        </Layout>
    )}
    />
);

//Home.js
import React, { Component } from 'react';

export default class Home extends Component {
  static displayName = Home.name;

  render () {
    return (
      <div>
      </div>
    );
  }
}

How should I resolve this issue?

A: The prosaic answer is a bit saddening:
I'm using the free version of heroku which might cause the application startup to have less resources and become simply slower.
Also it seems that all heroku application build process has 30 seconds timeout limit which sends back an H12 Request timout error if reached.
If I manually keep calling the application right after the -----> Build succeeded! message is logged to CodeShip from Heroku, I get a faster response for some random reason and the build does not break in this case.
As you can see on the image this is what I've done the previous build. For testing purposes I've restarted the build again and did not open the application manually. Reached 30 seconds timeout and the build had broken.

Trying again, keep refreshing the heroku app url it sends back the 200 OK code again indeed.
Trying (1 of 6) 'wget --no-check-certificate --output-document=/dev/null http://******.herokuapp.com'
--2020-03-14 14:59:15--  http://******.herokuapp.com/
Resolving ******.herokuapp.com (******.herokuapp.com)... 34.255.174.179, 52.18.75.143, 52.208.237.242, ...
Connecting to ******.herokuapp.com (******.herokuapp.com)|34.255.174.179|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1700 (1.7K) [text/html]
Saving to: /dev/null

Reading heroku docs it is clear there's no exact answer how to handle this issue. Long loops or heavy calculation demands from the app can easily cause a 30 seconds timeout.
Anyway, my application is rather lightweighted with no serious logic, only the lot of dependency by React itself. It is not much of an automated delivery this way, so I'm going to reach out for Heroku and try to find out whether it is truly a problem of the free version or not.
EDIT:
Turns out Heroku does not provide any support for free users, they redirect you to stackoverflow.com instead:

The circle is complete I guess.


text:
Q: How to add a space at the end of a string in Javascript I am writing a program which creates a slanted d based off of user input.
The program asks for the number of rows and produces the output accordingly.
If the user enters in 5 it should produce an output of:
d
 d
  d
   d

My actual output is:
d
d
d
d

Here is my Javascript code:
spaceArray = [];
space = ' ';
spaceMain = ' ';

function processingFunction(rows){ //passes the input as variable rows
    var spaceCounter = 0;
    var counter = 0;

    while (counter<rows){
        while (spaceCounter<counter){
            spaceMain = spaceMain + space;  //adds a space before the d
            spaceCounter++;
        }
        counter++;
        spaceCounter=0;
        spaceArray.push(spaceMain);  //adds spaceMain to the end of spaceArray
        spaceMain = ' ';
    }

    for (i = 0; i<rows; i++){
        d = spaceArray[i]+"d
";
        document.getElementById("outputNumber1").innerHTML += d;
    }

}

When I replace the space variable string from ' ' to '-' it seems to work with an output of:
d
-d
--d
---d

I am not sure what I need to change to get the above output but with spaces instead of dashes.
HTML:
<!DOCTYPE>

Slanted d

Input the number of rows you would like your slanted d to be in the input text box

    <input type="text" id="inputNumber"></input>
    <button type="button" onclick="processingFunction(document.getElementById('inputNumber').value)">Create slanted d</button>

    <output type="text" id="outputNumber1"></output>

A: In place of spaces use the html code   your code will start working, because by default the browser accepts only a single space no matter how many you give.
Example:
space = ' ';

A: By default, the browser will "collapse" all spaces into a single space.
One solution is to use the
 element for the output instead. Like this:

 shows pre-formatted text. So the output is displayed with all spaces and newlines preserved.
If you don't want to change the element type, you can add the CSS declaration white-space:pre to the element to achieve the same result as above. Like this:
<output type="text" id="outputNumber1" style="white-space:pre;"></output>

or you can set it separately in your

A: You can use &nbsp which stands for No-break space In the html language.

A: use nbsp this add a non breaking space to your html.


text:
Q: jQuery attr vs. prop, there are a list of props? This is not a duplicate question, I need only to decide if the better/fast/correct is to use attr or to use prop. The simplest and reliable way is checking into a list. A "list of element-name where the better is use prop(name) and/or a list where the better is use attr(name)".
PS: I am using jQuery 1.9+, and suppose that attr() is not a deprecated method.
Example of decisions (where the LIST have the answer):

*

*is better get ID value by $(x).prop('id') or by $(x).attr('id')?

*is better change title with $(x).prop('title','BLABLA') or with  $(x).attr('title','BLABLA')?

*can I use $(x).attr('selectedIndex')?

*what property names have risk with "Cross-browser consistency"?

*there are some case (with Microsoft-IE p.ex.) where $(x).attr('name') and $(x).prop('name') will return different things?

Perhaps a full list is not necessary, only a list of things that make some difference or risk for jQuery.
Edited after close: please click in the REOPEN link below to accept this edited question text.

A: They vary from browser-to-browser, but here's IE's list...http://msdn.microsoft.com/en-us/library/ie/hh773183(v=vs.85).aspx

A: Have a look at https://developer.mozilla.org/en-US/docs/DOM/element#Properties and also consider that many properties are only available on special types of elements.


text:
Q: Why is my recursive memoized Fibonacci code wrong? Something in the main function is wrong, but I don't know what. If I go through the code with a debugger I can see that my code isn't even reaching the fibonacci function right now.
public class Fibonacci {
    public static void main(String[] args) {
        for (int n=1; n<50; n++) {
            System.out.println("Element "+ n + " of the sequence: " + newFib(n));
        }
    }

    public static ArrayList<BigInteger> memo = new ArrayList<BigInteger>();

    static BigInteger newFib(int n){
        assert n >= 1: "the fibonacci sequence starts at 1";
        BigInteger result=BigInteger.valueOf(1);

        if (memo.get(n) != null) {
            return memo.get(n);
        }
        else if( n  == 1  || n  ==  2 ) {
            memo.add(n, BigInteger.valueOf(1));
            return BigInteger.valueOf(1);
        }
        else {
            result= newFib(n-1).add(newFib(n-2));
            memo.add(n,result);
            return result;
        }
    }
}

A: Your code was throwing some exceptions.  You simply needed to debug the exceptions and implement the proper checks.  Using the code with these changes should work as intended:
import java.math.*;
import java.util.ArrayList;
public class Fibonacci {

    public static void main(String[] args) {
        for (int n=1; n<50; n++) {
        System.out.println("Element "+ n + " of the sequence: " + newFib(n));
        }

    }

    public static ArrayList<BigInteger> memo = new ArrayList<BigInteger>();
        static BigInteger newFib(int n){
            assert n >= 1: "the fibonacci sequence starts at 1";
            BigInteger result=BigInteger.valueOf(1);

            if (memo.size() - 1 >= n && memo.get(n) != null) {
                return memo.get(n);
            }
            else if( n  == 1  || n  ==  2 ) {
                memo.add(n-1, BigInteger.valueOf(1));
                return BigInteger.valueOf(1);
            }
            else {
                result= newFib(n-1).add(newFib(n-2));
                memo.add(n,result);
                return result;
            }
        }
}

A: Your current code does not handle out of bounds correctly and as I mentioned in the comments, the fibonacci sequence does not necessarily start at one and the logic can be simplified. I would use a HashMap<Integer, BigInteger> for storing the memoization and I would also prefer to populate the initial constants once (and as constants). For example,
private static Map<Integer, BigInteger> memo = new HashMap<>();
static {
    memo.put(0, BigInteger.ZERO);
    memo.put(1, BigInteger.ONE);
}

static BigInteger newFib(int n) {
    if (!memo.containsKey(n)) {
        if (n < 0) {
            memo.put(n, newFib(n + 2).subtract(newFib(n + 1)));
        } else {
            memo.put(n, newFib(n - 2).add(newFib(n - 1)));
        }
    }
    return memo.get(n);
}

Which can then be tested like
public static void main(String[] args) {
    for (int i = -8; i < 9; i++) {
        if (i != -8) {
            System.out.print(" ");
        }
        System.out.printf("%-5s", String.format("F(%d)", i));
    }
    System.out.println();
    for (int i = -8; i < 9; i++) {
        if (i != -8) {
            System.out.print(" ");
        }
        System.out.printf("%-5s", newFib(i));
    }
}

To reproduce the example given in the Fibonacci number Wikipedia entry.
F(-8) F(-7) F(-6) F(-5) F(-4) F(-3) F(-2) F(-1) F(0)  F(1)  F(2)  F(3)  F(4)  F(5)  F(6)  F(7)  F(8)
-21   13    -8    5     -3    2     -1    1     0     1     1     2     3     5     8     13    21


text:
Q: Actiontec C1000a not factory resetting I had changed around the ip settings on my C1000a dsl modem (which I'm trying to set up as a repeater since we no longer have dsl), and the issue is that I can no longer access the gui. I've tried resetting 4 times, and it's still not kicking in. Held down reset for  near a minute...
Any ideas?

A: The following will reset the device to defaults according to the manufacturer.
To reset the device, begin with the unit powered up and with a solid Green Power light, then using a small tool depress and hold the Reset button on the back of the device just until you see the color of the Power light change from Green to Amber, and then release it before it turns Red.
The length of time that the Reset button must be held to accomplish the reset varies from model to model, but as long as the Reset button is released while the power light is Amber the Reset will be successful.

A: Read the manual for your router.  Some "reset" buttons need to be held down before the device is powered on, some after.
Another possibility is that the button itself is broken.  If you feel comfortable, you can try shorting the circuit by hand, or soldering on a new button.

A: Unfortunately, neither CenturyLink (who brands and sells this modem) nor ActionTec (who manufactures it) have a proper User's Manual where you might look up this basic information.  Instead, there's an 8 page brochure that comes with the modem and a sprawling set of FAQs on CenturyLink's site.
Luckily, Dave M above had the correct answer here, confirmed by CenturyLink phone tech support: hold the button ONLY UNTIL THE AMBER LIGHT IS LIT, then release it before it turns red.  (Why would it time out and turn red?)   That will reset the modem to it's default settings including unique passwords and SSID; you'll have to have saved the sticker that came with the modem or look on the label attached to its underside to figure those parameters out.


text:
Q: Unable to execute PowerShell script from inside App Directory C#/.net Core I'm not quite sure why, but if I execute a script from a local folder outside my solution things run fine. When I call the file inside my project I get the following error:
System.Management.Automation.PSSecurityException: 'AuthorizationManager check failed.'

Inner Exception
FileNotFoundException: C:\path\to\myproject\Modules\PSDiagnostics\PSDiagnostics.psm1

This is the code I am trying to run:
InitialSessionState _initialSessionState = InitialSessionState.CreateDefault2();
_initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
//var script = Environment.CurrentDirectory + @"\MachineInfo.ps1";
var script = @"C:\scripts\MachineInfo.ps1";
using (var run = RunspaceFactory.CreateRunspace(_initialSessionState))
{
    run.Open();
    var ps = PowerShell.Create(run);
    ps.AddCommand("Import-Module");
    ps.AddParameter("SkipEditionCheck");
    ps.AddArgument("CIMcmdlets");
    ps.Invoke();
    var err = run.SessionStateProxy.PSVariable.GetValue("error");
    System.Diagnostics.Debug.WriteLine(err);//This will reveal any error loading

    ps.AddCommand(script);
    ps.AddArgument(Machine);
    var result = ps.Invoke();
    run.Close();
}

Can anyone help me understand why it only works if I call script externally (see the commented out line) from the project source? I'm setting MachineInfo.ps1 to Copy Always and Content (I've tried None too) for Build Action.
This is running via PowerShell 7 inside a C# WinUI 3 .NET Core app. PSDiagnostics.psm1 does not exist inside C:\scripts nor should it have to exist inside my app directory.

A: Turns out this is a known issue, if you are building a self-contained application. The modules are not deployed into the publish folder correctly. See https://github.com/PowerShell/PowerShell/issues/15274
I fixed this by adding a build step that copies the modules into the correct place. There is a more sophisticated solution in the mentioned Github issue, I reduced it to a simpler build task since I am only targeting Windows.
<!--
Fix PS modules being in wrong place when publishing with a runtime identifier.
-->
<Target Name="PostPublish" AfterTargets="Publish">
  <ItemGroup>
    <PowerShellModules Include="$(ProjectDir)$(OutputPath)runtimes\win\lib\net6.0\Modules\**\*.*"/>
  </ItemGroup>
  <Copy SourceFiles="@(PowerShellModules)" DestinationFiles="$(PublishDir)\Modules\%(RecursiveDir)%(Filename)%(Extension)" />
</Target>


text:
Q: Why is the image of my ImageView (Android Studio) only changing when the onClick-Method ends? The following code shows how to load an image from my server into an ImageView with Picasso (on Android). I figured out that the image in the ImageView is changing when the method finishes - but I want to change it when the line of code is executing.
btn_startlive.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

    while(something_that_is_true_for_a_long_time){
       Picasso.with(img_live.getContext()).load("http://localhost:8000/livepicture")
                      .networkPolicy(NetworkPolicy.NO_CACHE)
                      .placeholder(img_live.getDrawable())
                      .memoryPolicy(MemoryPolicy.NO_CACHE)
                      .into(img_live);
         }

            }
        });

In this example the image does not change. Is it because the method does not end? And how to fix it?

A: Your onClickListener() looks right. In your onClickListener() method SystemClock.sleep(2000); stops your application (All thread as I know). Because of that your image cannot load immediately.
Just remove SystemClock.sleep(2000); and that is it.
If you want to use your Picasso library more effeciently, you can check this answer
If your image is loading so slow after removing SystemClock.sleep() (you said that is just for showing your case), maybe your images are too large to process.
If you load a lot of image, try to use resize for better memory performance:
Picasso.with(getActivity()).load(getPixId).resize('widthImageView', 'heightImageView').noFade().into(imageView);

EDIT : If you try to load too large image files to Picasso, it shows images with some delay. For eliminate the problem that is about your image size or not, please add .resize() method in your Picasso line.
 Picasso.with(img_live.getContext())
.load("http://localhost:8000/livepicture")
.networkPolicy(NetworkPolicy.NO_CACHE)
.placeholder(img_live.getDrawable()) .memoryPolicy(MemoryPolicy.NO_CACHE)
.resize(100, 100)
.into(img_live); // resizes the image to these dimensions (in pixel). does not respect aspect ratio


text:
Q: How do I make it show up how many questions the user gets right? I am trying to make a simple Algebra quiz in HTML and JavaScript, but can't figure out how to make it show up how many answers you got correct. I made it to where the it would turn the correct answer variables into booleans, true is correct and false is incorrect. Then I made if and else statements to see how many answers were correct but the alert (which will be changed) is just displaying zero no matter what. Here is a link to my code.
https://jsbin.com/yivapi/edit?,js

A: Trenner, I'm not going to be able to answer your question properly without untangling your code, so what I thought I'd do is show you a different (and hopefully easier) way to approach the problem. I hope that's okay.
HTML
Here are the inputs for the questions as I imagine you've set them out. I've only used three here for simplicity. There's a submit button which I'll get to in a moment.
<input id="q1" />
<input id="q2" />
<input id="q3" />
<button id="submit">Submit</button>

JavaScript
First we grab our submit button and assign a function getAnswers to its click event.
var submit = document.getElementById('submit');
submit.onclick = getAnswers;

This is a shortcut function to grab the input values so you don't need to keep writing document.getElementById(id).value later.
function getValue(id) {
    return document.getElementById(id).value;
}

OK. So now, instead of having a load of if...else statements we're going to use an object to store all of our information. If you've used other languages they might call something like this a hash map. Basically it's a store of information that has key/value pairs and it's great for storing connected information together. In this case each question is a key which has another object as its value, and that object's keys are value and answer, and it's values are the value of the input element and the actual answer.
function getAnswers() {

    // create the object
    var quiz = {};

    // for each question assign set up a new key (question1)
    // and get the input value using our shortcut function.
    // We set the actual answer here too.
    quiz.question1 = { value: getValue('q1'), answer: '2√19' }
    quiz.question2 = { value: getValue('q2'), answer: '√87' }
    quiz.question3 = { value: getValue('q3'), answer: '8x√2' }

    // Once we've loaded the questions, we can check the answers
    // We pass in our quiz object as an argument
    checkAnswers(quiz);
}

Here we use a loop to iterate over our quiz object. A simple loop of 7 lines instead of all those horrible if...else statements.
function checkAnswers(quiz) {

    // set up out correctAnswers variable
    var correctAnswers = 0;

    // loop over the quiz object and...
    for (var q in quiz) {

        // ...for each question we test the input value we've stored
        // against the answer also held in that object
        // If they match increase the correctAnswers variable
        if (quiz[q].value === quiz[q].answer) {
            correctAnswers++;
        }
    }

    // finally alert the correctAnswers
    alert("You got " + correctAnswers + " out of 15 questions right!");
}

This DEMO will show you the working code. Just add 2√19 into the first input box and press submit and you will get an alert of 1 correct answer(s).
Sorry for not directly answering your question, but I hope you find this code interesting and useful. Good luck with your JavaScript coding.


text:
Q: Android Volley return value from response How do I get the response out of onResponse so that I can return it? I have found this but I don't really understand how to implement it for me. How can I return value from function onResponse of Volley?
I hope there is an updated method or something easier that I might have missed
This is my code
public Boolean checkIfPersonExists(Context context, final Person aPerson){
        StringRequest postRequest = new StringRequest(Request.Method.POST, USEREXISTS, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("RESPONSE",response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("email",aPerson.getEmail());
                params.put("phone",aPerson.getPhone());
                return params;
            }
        };
        Volley.newRequestQueue(context).add(postRequest);
        return null;
    }

A: As it was mentioned, you need to implement interface and get a callback
Create a new interface like this
public interface GeneralCallbacks {
void VolleyResponse(String data);
}

Implement the interface on your activity class
public class YourActivity implements ScoreboardCallback
{
    @Override
    public void VolleyResponse(String data)
    {
      //do stuff with data
    }
}

And finally changing your response function to something like this
        @Override
        public void onResponse(String response) {
            ((GeneralCallbacks)context).VolleyResponse(response); // This will make a callback to activity.
            aPerson.SomeFunction(); // This will call person's function
            Log.d("RESPONSE",response.toString());
        }


text:
Q: Draw a transparent image on surface view My objective is to run a glowing animation on an image.I am changing the image alpha to produce this effect.
I have used basic AlphaAnimation provided in android framework but found that its slowing down other animations. So i extended a class from SurfaceView and created a thread to update it. ( Again here, i am manipulating alpha of the image ).
Everything seems fine, except that i am not able to draw a transparent image onto SurfaceView.Its showing black color on the transparent areas of the bitmap.
Canvas mCanvas = holder.lockCanvas(null);
Bitmap mybit = BitmapFactory.decodeResource(mFrameLayout.getResources(), R.drawable.icon);
mCanvas.drawColor(0, Mode.CLEAR);
mCanvas.drawBitmap(mybit, 0, 0, null);
holder.unlockCanvasAndPost(mCanvas);

Thanks in advance.

A: There is an example of a Spinning cube in the samples.  You should be have to have a look at that and see how they got a transparent background.

A: I haven't tried, but I assume you set the color of the Paint to a transparent one, and then use the Paint object to draw your bitmap.


text:
Q: Allow user to select the number of checkboxes equal to the value of a text input you want help me, I have a form where I have an input text and 4 chechbox, what I do is, if you write a value in the input, is the same number of checked I can make the checkbox, eg write the value 3 in the input and in the group of checkbox only allows me to select any 3 boxes and missing fourth box is off or you can not do checked.
thanks and regards.
HTML:
    <input id="iddata_13561" name="data_13561" type="text" value="" >

    <input name="data" id="iddata_13562" type="checkbox"  value="1">
    <input name="data" id="iddata_13570" type="checkbox"  value="1">
    <input name="data" id="iddata_13578" type="checkbox"  value="1">
    <input name="data" id="iddata_13586" type="checkbox"  value="1">

JS:
     $(document).ready(function () {
           $("input[name='tech']").change(function () {

              var maxAllowed = $('#iddata_13561').attr('value');

              var cnt = $("input[name='tech']:checked").length;

             if (cnt > maxAllowed)
              {
                 $(this).prop("checked", "");
                 alert('Select maximum ' + maxAllowed + ' technologies!');
             }
          });
        });

A: You don't want the attribute value, you want the current value.  For that you use val:
var maxAllowed = $('#iddata_13561').val();

http://jsfiddle.net/efKAb/
Note: I changed name='data' to tech as I assume that was a copy/paste error.


text:
Q: Expand Bash variable with forward slash in name After something like
env "my/test=hi" bash

I now have an environment variable set named my/test, but various ways I've tried to expand it don't seem to work and produce various weird errors. For example, the straightforward option:
$ echo $my/test
/test

more clever:
$ echo $"my/test"
my/test

still no:
$ echo ${my/test}

(that just returns \n)
Running printenv I can clearly see the variable is set. How do I reference it so it expands/substitutes in like a "normally" named variable?

A: Nope. That's not a valid shell variable name. bash defines a name as:

A word consisting solely of letters, numbers, and underscores, and beginning with a letter or underscore. Names are used as shell variable and function names. Also referred to as an identifier.

You'll have to parse the output of printenv to get the value.


text:
Q: In Visual Basic 2010 - System.Net showing error on certain kind of web links My aim was to create a small application which when given a website link such as
http://digikey.com/product-detail/en/ATF1502ASV-15JU44/ATF1502ASV-15JU44-ND/1008571/
it will extract datas from its Page Source like
Manufacture PartNumber
Item Description etc
I used this code to get the page source
Dim PartURL As String = "http://digikey.com/product-detail/en/LM567CN/LM567CN-ND/2607028"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(PartURL)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New     System.IO.StreamReader(response.GetResponseStream())
Dim sourcecode As String = sr.ReadToEnd()
TextBox1.Text = sourcecode

But i found something out of my knowledge
It will access and get source code from this link
http://digikey.com/product-detail/en/ATF1502ASV-15JU44/ATF1502ASV-15JU44-ND/1008571`
but will not access this
http://digikey.com/product-detail/en/PIC18F45K20-I%2FPT/PIC18F45K20-I%2FPT-ND/1228485
I observed a lot and found that the difference between the two link was that first one's part number was ATF1502ASV-15JU44-ND and second ones was PIC18F45K20-I/PT-ND,
Former one doesnt have "/" in the name but second one has it,
so inorder to differentiate the "/" in partnumber from that of the normal weblinks "/" they put "%2F" replacing it in the name
So they changed
PIC18F45K20-I/PT-ND to
PIC18F45K20-I%2FPT-ND
I dont know whether my inference is correct
But the 2nd link always shows error and sourcecode cant be accessed
And also when i get the source code what i do is
search for a particular string "Manufacturer Part Number" in the source code and then from that line i find the Part number
Iam sure there will be better efficient easier ways for this
Please help me with that too

A: Here is the code for VBA
Sub xmlHttp()
    Dim xmlHttp As Object
    Dim strVal As String
    Dim URl As String

    URl = "http://www.digikey.com/product-detail/en/LM567CN/LM567CN-ND/2607028"
    Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    xmlHttp.Open "GET", URl, False
    xmlHttp.setRequestHeader "Content-Type", "text/xml"
    xmlHttp.send

    Dim html As Object
    Set html = CreateObject("htmlfile")

    html.body.innerHTML = xmlHttp.responseText

    Set thele = html.getElementsByTagName("th")

    For Each i In thele

        If i.innerHTML = "Manufacturer" Then
            strVal = i.NextSibling.innerText
            MsgBox "Manufacturer :" & strVal
        ElseIf i.innerHTML = "Manufacturer Part Number" Then
            strVal = i.NextSibling.innerText
            MsgBox "Manufacturer Part Number : " & strVal
        ElseIf i.innerHTML = "Description" Then
            strVal = i.NextSibling.innerText
            MsgBox "Description :" & strVal
        End If

    Next

End Sub


text:
Q: Unable to get city name by current latitude and longitude in swift I'm trying to get city name from my current location coordiate by using CLGeocoder().reverseGeocodeLocation.
It gives me country name, street name, state and many other things but not city. Is there anything wrong with my code?
Here's my code:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]
    CLGeocoder().reverseGeocodeLocation(location) { (placeMark, error) in
        if error != nil{
            print("Some errors: \(String(describing: error?.localizedDescription))")
        }else{
            if let place = placeMark?[0]{
                print("country: \(place.administrativeArea)")

                self.lblCurrentLocation.text = place.administrativeArea
            }
        }
    } }

I use the below code too. But doesn't work for me. Here's the another way.
        let geoCoder = CLGeocoder()
    let location = CLLocation(latitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.longitude)!)
    geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

        // Place details
        var placeMark: CLPlacemark!
        placeMark = placemarks?[0]

        // Address dictionary
        print(placeMark.addressDictionary as Any)

        // Location name
        if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
            print("locationName: \(locationName)")
        }
        // Street address
        if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
            print("street: \(street)")
        }
        // City
        if let city = placeMark.addressDictionary!["City"] as? NSString {
            print("city : \(city)")
        }
        // Zip code
        if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
            print("zip :\(zip)")
        }
        // Country
        if let country = placeMark.addressDictionary!["Country"] as? NSString {
            print("country :\(country)")
        }
    })

Please someone help me to get city name.

A: The field is called locality
 if let locality = placeMark.addressDictionary!["locality"] as? NSString {
            print("locality :\(locality)")
        }

Locality Apple docs
https://developer.apple.com/documentation/corelocation/clplacemark/1423507-locality?language=objc
CLPlacemark
https://developer.apple.com/documentation/corelocation/clplacemark?language=objc
Update:
Try this
import Foundation
import CoreLocation

let geoCoder = CLGeocoder()
let location = CLLocation(latitude: 40.730610, longitude:  -73.935242) // <- New York

geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, _) -> Void in

    placemarks?.forEach { (placemark) in

        if let city = placemark.locality { print(city) } // Prints "New York"
    }
})


text:
Q: How do I make my search case insensitive? I have a web app that searches through a few databases, some of the data saved is in uppercase and some a mix of upper and lowercase, however when searching the keyword I want it to ignore the case and just bring up results that match the word. for example I want to search "document_reference" without having to write the proper way it is saved which is "Document_Reference"
I was told to add case insensitivity in my index hwoever not sure what to do or add in there,
I tried this (found it in whoosh documentation)
class CaseSensitivizer(analysis.Filter):
    def __call__(self, tokens):
        for t in tokens:
            yield t
            if t.mode == "index":
                low = t.text.lower()
                if low != t.text:
                    t.text = low
                    yield t

this what my index and query parser looks like
def open_index(indexDirectory):
    # open index and return a idex object
    ix = index.open_dir(indexDirectory)
    return ix

def search_index(srch, ix):
    #  Search the index and print results
    #  ix = open_index(indexDirectory)
    results = ''
    lst = []
    qp = MultifieldParser(['Text', 'colname',
        'tblname', 'Length', 'DataType', 'tag_name'],
        schema=ix.schema, group=qparser.OrGroup)
    # qp = QueryParser('Text', schema=ix.schema)
    q = qp.parse(srch)
    with ix.searcher() as s:
        results = s.search(q, limit=None)
        for r in results:
            print('\n', r)
            lst.append(r.fields())
        if(DEBUG):
            print('Search Results:\n', lst)
            print('\nFinished in search.py')
        return lst

currently it only ever gives results that exactly match what I typed in search bar, so If I type "document" but the source is actually stored as "DOCUMENT" I wouldnt get any results

A: I know this is an older issue but thought would reply in case somebody like me came here looking for a solution.
The CaseSensitivizer class needs to be used when you define your schema. This is how you would use it to create the schema from the quickstart example from the docs
>>> from whoosh.index import create_in
>>> from whoosh.fields import *
>>> from whoosh import analysis
>>> class CaseSensitivizer(analysis.Filter):
        def __call__(self, tokens):
            for t in tokens:
                yield t
                if t.mode == "index":
                    low = t.text.lower()
                    if low != t.text:
                        t.text = low
                        yield t
>>> myanalyzer = analysis.RegexTokenizer() | CaseSensitivizer()
>>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT(analyzer=myanalyzer))

Now you can use this schema to create your index and do what you were doing before to search. That worked for me.

A: instead of using lower() or upper(), you can use casefold() for string comparison.
A very good example given here.
In short, example is:
s1 = 'Apple'
s3 = 'aPPle'
s1.casefold() == s3.casefold()

returns True.


text:
Q: php change array format for url I have a weird project I'm working on. I'm totally new to php so it has been a struggle so far.
I have a form that gives an array and posts it:
...
return($keywords);
}

$keywordlist = explode("\r\n", $keywordlist);
foreach($keywordlist as $keyword){
print_r(mixer(strtolower($keyword)));
}

I get this:
Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six [6] => ....

But would like it to come out like this instead:
%28one%2Ctwo%2Cthree%2Cfour%2Cfive%2Csix%29

Ultimately hope to be able to attach it to the end of a url like ask.com search:
"http://www.ask.com/web?q=(put my keywords here)"

then navigate there
In theory it would be like I typed "(one,two,three,four,five,six)" into the search bar and pressed enter.
Hopefully that makes some sense.

A: Something like this:
$commaSeparated = implode(',', $array);
$withParens = '(' + $commaSeparated + ')';
$urlEncoded = urlencode($withParens);
print $urlEncoded;

A: Use the php implode() function.
So you could do this:
$array = new array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six );
$string = '%28'.implode( '%2C', $array ).'%29';

Now $string will be what you need

A: $keywordlist = explode("\r\n", $keywordlist);
array_walk($keywordlist, 'strtolower');
$keywords = '('.implode(",", $keywordList).')';

A: print_ris what prints your array like this.
http://php.net/manual/en/function.print-r.php
How to solve it depends on a few things. What does mixer()do? And is the keywords always in lowercase? If mixer doens't do much and the keywords are in lowercase you could do something like:

$string = '%28' . implode('%2C',
  $keyword) . '%29';

If it's URL encoding you are after you could use the function url_encode instead of manually adding encoded values as above.

A: This code:
$keywords = array('one', 'two', 'three');
$query = '(' . implode(',', $keywords) . ')';
echo('Search query: ' . $query . PHP_EOL);
$query = rawurlencode($query);
echo('Encoded: ' . $query . PHP_EOL);

Gives this output:

Search query: (one,two,three) Encoded:
  %28one%2Ctwo%2Cthree%29

A: Something like this?
$input = array('one', 'two', 'three');
$s = implode(',', $input);
$s = '('.$i.')';
print urlencode($s);

A: You could encode each part of the array using urlencode and then manually put it in your url (making a url string by yourself). http://php.net/manual/en/function.urlencode.php
Or you could use this function instead: http://php.net/manual/en/function.http-build-query.php


text:
Q: Как с помощью flask_sqlalchemy реализовать логическое ИЛИ? Возник такой вопрос: Во flask приложении нужно реализовать запрос к БД примерно следующего вида: SELECT ALL FROM table WHERE firstUserID LIKE X OR secondUserID LIKE X. Дело в том, что во flask версии sqlalchemy нет функции or_ (или я не знаю как ее импортировать/вызывать). Данная функция есть в полноценной версии sqlalchemy, однако с ней приложение не заводится, а через flask_sqlalchemy можно реализовать только логический AND. Если кто то сталкивался с подобным вопросом и смог его решить, прошу совета. Не очень хочется делать два запроса к БД вместо одного.
Запросы создаю примерно следующим образом:
User.query.filter(User.login == login).all()

где login - переменная строчного типа, а User - класс, наследующийся от SQLAlchemy.Model и задающий таблицу в БД.

A: Вместо функции or_ из sqlalchemy можете использовать оператор |:
User.query.filter((User.email == email) | (User.login == login)).all()

Пример:
# app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'url_or_path/to/database'
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50), unique=True)
    name = db.Column(db.String(30))

class UserQuery(object):
    @staticmethod
    def get_user_id_by_email_or_name(email=None, name=None):
        user = User.query.filter((User.email == email) | (User.name == name)).first()
        return user.id if hasattr(user, 'id') else None

Refs:
Using OR in SQLAlchemy
Flask SQLAlchemy filter by value OR another
Column Elements and Expressions


text:
Q: Is there a unit testing library for asserting dto-domain object "equality" via reflection? I want to automatically assert equality of all matching public get-set properties of a domain entity to it's respective DTO. Like AutoMapper but for comparison.
Ideally it should be a narrowly-focused small library rather than an extra feature of a larger one.

A: I have found something that works:
http://www.nuget.org/packages/CompareNETObjects
public static class AssertEx
{
    public static void PublicGetSetPropertiesAreEqual<TDto, TEntity>(TDto dto, TEntity entity)
    {
        var result = new CompareLogic(new ComparisonConfig{ IgnoreObjectTypes = true }).Compare(dto, entity);

        if (result.AreEqual)
            return;

        throw new AssertFailedException(result.DifferencesString);
    }
}


text:
Q: unable to get data from model class in swift 3? Here is the data for model class in which I got data from all dictionaries but unable to get ratingVotes from model class in which I need to get value key value pair to be used for displaying rating in my UI Can anyone help me how to resolve this ?
func ReviewApiDownloadJsonwithURL(reviewApi : String){
            print(reviewApi)
            let url = URL(string: reviewApi)!
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                if error != nil { print(error!); return }
                do {
                    if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
                        for item in jsonObj {
                             self.reviewModel = Review.init(dict: item)
                        }
                        DispatchQueue.main.async {
                            guard let obj = self.reviewModel else { return }
                            let itemsCount = obj.reviews
                            for i in 0..<itemsCount.count {
                                let customAttribute = obj.reviews[i].ratingVotes
//                                for j in 0..<customAttribute.count {
                                        self.ratingvalue.append(customAttribute[0].value!)
//                                }
                            }
                            print(self.ratingvalue)
                            self.reviewTableView.delegate = self
                            self.reviewTableView.dataSource = self
                            self.activityIndicator.stopAnimating()
                            self.activityIndicator.hidesWhenStopped = true
                            self.reviewTableView.reloadData()
                            self.initialCollectionData()
                        }
                    }
                } catch {
                    print(error)
                }
            }
            task.resume()
    }

Here is my Json data

Here is my model class code
struct Review  {

    let ratingPercent : Any?
    let count : Any?
    let reviews : [Reviews]

    init(dict : [String:Any]) {
        if let customAttribute = dict["reviews"] as? [[String: AnyObject]] {
            var result = [Reviews]()
            for obj in customAttribute {
                result.append(Reviews(dict: (obj as? [String : Any])!))
            }
            self.reviews = result
        } else {
            self.reviews = [Reviews]()
        }
        self.ratingPercent = dict["avg_rating_percent"]
        self.count = dict["count"]
    }
}

struct Reviews {

    let reviewId : Any?
    let createdAt : Any?
    let entityId : Any?
    let entityValue : Any?
    let statusId : Any?
    let detailId : Any?
    let title : String?
    let detail : String?
    let nickName : String?
    let customerId : Any?
    let entityCode : Any?
    let ratingVotes : [RatingVotes]

    init(dict : [String:Any]) {
        if let customAttribute = dict["rating_votes"] as? [[String: Any]] {
            var result = [RatingVotes]()
            for obj in customAttribute {
                result.append(RatingVotes(dict: (obj as? [String : Any])!))
            }
            self.ratingVotes = result
        } else {
            self.ratingVotes = [RatingVotes]()
        }
        self.reviewId = dict["review_id"]
        self.createdAt = dict["created_at"]
        self.entityId = dict["entity_id"]
        self.entityValue = dict["entity_pk_value"]
        self.statusId = dict["status_id"]
        self.detailId = dict["detail_id"]
        self.title = dict["title"] as? String
        self.detail = dict["detail"] as? String
        self.nickName = dict["nickname"] as? String
        self.customerId = dict["customer_id"]
        self.entityCode = dict["entity_code"]
    }
}

    struct  RatingVotes {
        let voteId : Int?
        let optionId : Int?
        let remoteIp : Any?
        let remoteIpLong : Int?
        let customerId : Any?
        let entityPkValue : Any?
        let ratingId : Int?
        let reviewId : Int?
        let percent : Int?
        let value: Int?
        let ratingCode : String?
        let storeId : Int?
        let code : Int?
        let postion : Int?

        init(dict : [String:Any]) {
            self.voteId = dict["vote_id"] as? Int
            self.optionId = dict["option_id"] as? Int
            self.remoteIp = dict["remote_ip"]
            self.remoteIpLong = dict["remote_ip_long"] as? Int
            self.customerId = dict["customer_id"]
            self.entityPkValue = dict["entity_pk_value"]
            self.ratingId = dict["rating_id"] as? Int
            self.reviewId = dict["review_id"] as? Int
            self.percent = dict["percent"] as? Int
            self.value = dict["value"] as? Int
            self.ratingCode = dict["rating_code"] as? String
            self.storeId = dict["store_id"] as? Int
            self.code = dict["code"] as? Int
            self.postion = dict["position"] as? Int

        }
}

A: It is just Typo mistake you might copy paste your code. You can easily find it by debug here is a  small mistake you made
Observe here in struct Reviews
   if let customAttribute = dict["reviews"] as? [[String: Any]] {
        var result = [RatingVotes]()
        for obj in customAttribute {
            result.append(RatingVotes(dict: (obj as? [String : Any])!))
        }
        self.ratingVotes = result
    } else {
        self.ratingVotes = [RatingVotes]()
    }

You are using key  reviews here  dict["reviews"]
it should be  rating_votes like  dict["rating_votes"]
Hope it is helpful to you

A: You have getting both time review dictionary same value.
if let customAttribute = dict["reviews"] as? [[String: Any] So change here 'review' to 'rating_votes'
Or follow below code may it help you!!
init(dict : [String:Any]) {
    if let customAttribute = dict["rating_votes"] as? [[String: Any]] {
        var result = [RatingVotes]()
        for obj in customAttribute {
            result.append(RatingVotes(dict: (obj as? [String : Any])!))
        }
        self.ratingVotes = result
    } else {
        self.ratingVotes = [RatingVotes]()
    }
    self.reviewId = dict["review_id"]
    self.createdAt = dict["created_at"]
    self.entityId = dict["entity_id"]
    self.entityValue = dict["entity_pk_value"]
    self.statusId = dict["status_id"]
    self.detailId = dict["detail_id"]
    self.title = dict["title"] as? String
    self.detail = dict["detail"] as? String
    self.nickName = dict["nickname"] as? String
    self.customerId = dict["customer_id"]
    self.entityCode = dict["entity_code"]
 }
}


text:
Q: angular js pass parameters without services I want to pass a single id to show a single user details. I can do this in the same page, who is a list of all users, I can click on the user to see the details in the same page, but I want to see the user detail in a separate page.
.when("/user", {
        controller  : "userCTRL",
        templateUrl : "/app/users/singleU.html"

at the end of the function:
$location.path('/user').search('id=' + id);

this is ok. In user page, the url is: user?id=1 but do not shows anything except text. With ng-repeat it works fine, but I want only one user detail. Is this possible without services and components?


text:
Q: Updating a mysql database using php via android I am trying to update a mysql database using php from an android application.  I have successfully been able to update the database and return data from the database using this tutorial I found here: http://www.helloandroid.com/tutorials/connecting-mysql-database
I am now trying to update a database using a location provider to obtain the latitude and longitude of a location fix that I am getting via the onLocationChanged callback.  My code looks like this:
public void onLocationChanged(Location location) {

double myLonDouble = location.getLongitude();
String myLon = Double.toString(myLonDouble);
double myLatDouble = location.getLatitude();
String myLat = Double.toString(myLatDouble);

sp = getSharedPreferences("MyPrefsFile", 0);
id = sp.getInt("id", 0);
String idString = Integer.toString(id);

DatabaseConnector db = new DatabaseConnector();

ArrayList<NameValuePair> latLon = new ArrayList<NameValuePair>();
latLon.add(new BasicNameValuePair("longitude", myLon));
latLon.add(new BasicNameValuePair("latitude", myLat));
latLon.add(new BasicNameValuePair("id", idString));
tv.setText(idString);
db.dbConnect(latLon, php);

}
The method dbConnect, which sends my data to a php file looks like this:
public void dbConnect(ArrayList<NameValuePair>  data, String phpFile) {

       InputStream is = null;

        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(phpFile);
                httppost.setEntity(new UrlEncodedFormEntity(data));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

     }// end dbConnect

The php file that I am using in the httppost object looks like this:
>><?php
>>$con = mysql_connect("localhost","********","*********");
>>if (!$con)
>>  {
>>  die('Could not connect: ' . mysql_error());
>>  }
>>
>>mysql_select_db("swizzle_practice", $con);
>>
>>$_SQL =
>>"UPDATE users
>>SET longitude = '$_REQUEST[longitude]', latitude = '$_REQUEST[latitude]'
>>WHERE id = '$_REQUEST[id]'";
>>
>>mysql_query($_SQL,$con) or die("error: " . mysql_error());
>>
>>mysql_close($con)
>>?>

My manifest looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.first_screen"
  android:versionCode="1"
  android:versionName="1.0">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-sdk android:minSdkVersion="7" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
        <uses-library android:name="com.google.android.maps" />

    <activity android:name=".First_screenActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Setup"
              android:label="@string/app_name">
    </activity>

    <activity android:name=".Map"
              android:label="@string/app_name">
    </activity>

</application>
</manifest>

I am not getting any errors in the log which leads me to think that it is my code in the
dbConnect method that is wrong.  I have looked over it and can't seem to find what I am doing wrong.
Any help you can give would be much appreciated.
Louis

A: Add '$_REQUEST['longitude']', how is now? Log the nameValuePairs to check if the pairs values are correct.
$_SQL =
"UPDATE users
SET longitude = '$_REQUEST['longitude']', latitude = '$_REQUEST['latitude']'
WHERE id = '$_REQUEST['id']';";

P.S: I suggest test your php code and your query with manually inputed values.
And you don't need response since you are doing operation which has nothing to do with your application after you send the key-values-pairs, i.e your query does not fetch any data. You can have it and you can use it for outputing if your query did the job or not.

A: You can check what data your script received using
foreach ($_POST as $var => $value) {
  echo "$var = $value<br>n";
}

In your php script.

A: Well, I'm not very good with PHP, but from what I see..you're accessing request variable from _REQUEST, but you're setting the request with HttpPost.
So to put it straight, you're setting a POST request, but retrieving the variable on the server end as a GET request.  To fix this, either make the client send a GET request or access request variable on the server side from _POST


text:
Q: I cannot log into the Minecraft launcher I can't log into the Minecraft launcher, because it tells me that the username or passowrd is incorrect. I have tried resetting my password and have even given the account to my freidn and he was able to sign in perfectly, i cannot. If I try to login in through the official website the login button just doesn't simply doesn't work. I have even tried waiting to login in later, restarting my computer, but it hasn't worked. I have used my email and username to login. I have contacted Minecraft support via email and it told me that it is currently reviewing cases for the 30th of April, so I'd  rather try to fix the issue here. Thanks for your help!

A: Just for completions sake. Press the Minecraft authenticator button as you did


text:
Q: Creating puzzle animation in WP7 Mango I am creating a puzzle app for kids, in that puzzle contains images of fruits, here the images of fruits will be splited  in to  3 or more pieces. what i need is, i need to drag this piece in to a specific area and if the position where i placed the image piece is correct   means the image must need to attach there otherwise the image will need to move back to its original position automatically. Please give me a initial guide line to start this app. I am new to this Silverlight game development and i dnt know where to start this proj. Pls help me...

A: With Wp7 you can develop in silverlight or XNA.  As this is a game you might find XNA an easier place to start from.  Please find a tutorial on creating a tic-tac-toe game in the link below.  IMHO your game concept sounds like it would have a similar layout and similar logic (you are placing pieces on a board) so perhaps if you follow this tutorial you will get some ideas:
http://mobile.tutsplus.com/tutorials/windows/windows-phone-7-game-development/


text:
Q: How do I remotely control another Ubuntu desktop from Ubuntu? How do I remotely control another desktop (both are Ubuntu 12.04) from my client machine?
Is it possible to use Remmina Remote Desktop Client?

A: Overview of Solution
You need to change some settings on your host machine (to enable desktop control) and create a Remote Desktop Client profile on your client machine in order to connect to the host machine and ultimately view and control the host machine's desktop.
And yes, it is possible to use Remmina Remote Desktop Client on your client machine.
Enable Remote Control of Host Machine
Do the following on the host machine:
vino-preferences

*

*vino-preferences also in Dash under Desktop Sharing

*

*Tick Allow other users to view your desktop

*Tick Allow other users to control your desktop

*Tick Require the user to enter this password

*Enter a difficult to guess passphrase

*Close

Create Remote Desktop Client profile on your Client Machine
Do the following on the client machine:
remmina

*

*remmina also in Dash under Remmina Remote Desktop Client
Ctrl+N or Connection > New

*

*Fill in your IP address [123.123.12.3] where it says Server

*Connect

View and Control Host Machine
On the client machine, when asked for the VNC password, enter the passphrase you previously entered into the host machine.
If successful at this step, you should now be viewing and controlling the host machine's desktop from your client machine.

A: First, you need to allow the compter you want to remotely control to be controlled. Launch Remote Control Preferences, and allow Ubuntu to be remotely controlled. You can also set a password if you want. You can now control that computer remotely from another Ubuntu computer. Make sure to choose the VNC protocol when connecting to the computer. If you would like to control Windows 7 from Ubuntu, you need to choose the RDP protocol (You will need to have remote control allowed on the Windows 7 computer).

A: Some machines will ask whether you want to allow connections on the server, during the client connection, live, such that if you don't actually see it happening, it might not work.
Secondly, if you plan to connect Ubuntu and Windows 7 machines, you must select the RDP option, otherwise, eg, Ubuntu to Ubuntu connections will use VNC.
Finally, depending on how your network is set up, you might have to use host names, IPs or FQDNs. Check them all before freaking out, as this will save you some time.
As an added bonus, there is also a trick to connect remote desktop connections behind networks where port forwards are needed to connect to machines behind the entry point. For example, if you have an access point of host.domain.com and it connects to a server on the network, you can set up a port forward using SSH, and then specify the RDP or VNC post like so (in putty for RDP on WIndows 7, this would be the example):
Source: 8585 (or whatever port you want)
Destination: 192.168.x.x:3389 (where x.x is your network)

Then, when using RDC in Windows, for example, you would use localhost:8585 as the server name and voila. This can work on Linux too, with a command like:
ssh -i /path/to/key -L 8585:192.168.x.x:3389 user@host.domain.com

A: I have been using Remmina, and I'm very happy with it.  Remmina is able to display and control a remote desktop session.  If you don't have it installed you can do so from the USC

Ubuntu remote desktop access is based on technology called (VNC)


text:
Q: How to use OnGetPassword send password for establishing SSL connection in Delphi 7 I'm trying to establish a SSL connection from Delphi to a Webservice. But to send the password, I could find that OnGetPassword function must be used. But I couldn't get any information on how to use this function. Saw the below function. But this just gives undeclared indentifier during compilation
procedure TForm1.IdSSLIOHandlerSocketOpenSSL1GetPassword(var Password: string);
begin
  Password := 'thepassword';
end;

Can anyone please shed some light on how should I use this function to send the password. Below is my code (just the SSL part)
        Id_HandlerSocket := TIdSSLIOHandlerSocketOpenSSL.create(nil);
        Id_HandlerSocket.SSLOptions.Mode := sslmClient;
        Id_HandlerSocket.SSLOptions.Method := sslvTLSv1_2;
        Id_HandlerSocket.SSLOptions.RootCertFile := 'CARootcert.pem';
        Id_HandlerSocket.SSLOptions.CertFile := 'clicert.pem';
        Id_HandlerSocket.SSLOptions.KeyFile := 'clikey.pem';
        Id_HandlerSocket.OnGetPassword := GetPassword; // Needs to be corrected

This is what I have tried so far.
type
  TForm1 = Class(TForm)
     function GetPassword : String;
  end;

function TForm1.GetPassword : String;
begin
  Result := 'Thepassword';
end;

Id_HandlerSocket.OnGetPassword := GetPassword; //Just the part calling the proc

But on compiling, I get the error - Undeclared identifier - GetPassword.
How should I access the function GetPassword ?


text:
Q: S3 browser upload via POST: unable to handle errors gracefully I am writing an app where I want the customer to be able to upload to Amazon S3 straight from the browser.  I can make this work just fine.  But when errors occur, I want to handle them more gracefully than splattering an XML document on the customer's screen.
I have a scheme that I think would work, but it's failing.  Here's what I'm trying:

*

*Create a form to do the upload, and store the form on S3 itself, in the same domain as the "action" attribute of the form.

*Redirect the customer to this form.  Now their browser is sitting on https://<bucket>.s3.amazonaws.com/something.

*The page contains a hidden iframe.  The form sets its target to the iframe.

*The load event handler looks at the contents of the iframe, and acts upon it.

So, something like this:

<form target="foo" action="https://<bucket>.s3.amazonaws.com/">
    <input type="hidden" name="..." value="..." />
    <input type="file" name="file" />
</form>

with this javascript (using jquery):
function handler() {
    var message = $("#foo").contents().find('message').text();
    alert(message);
}
$("#foo").load(handler);

Using firebug, I can see that the iframe contains an XML document, that contains a "message" node.  However, the .find('message') always fails to find anything within the XML document.
Notice that the action of the form has the same domain, port, and scheme as the document itself.  So, I don't think that I should be running afoul of the same-origin policy.  Right?  But it fails every time.  This is using Firefox and Google Chrome browsers.
Thanks for any advice!

A: This should be just a comment, but can you post the response XML code?
EDIT: Just to narrow down a little, i made a simple test and worked really fine:

    <error>
        AccessDenied
        <message>Invalid according to Policy: Policy expired.</message>
        <hostid> SZuQn5hTyf32j79AWUym1/si48oqjPifrx4goDVDLYYxc6cJVbbHroLJYcAM89+T</hostid>
    </error>

Then I did some jQuery code on my firebug:
$("#foo").find("message").text()
Maybe you can give an alert($("#foo").html()) and check the response..

A: There are a number of jQuery plugins that effectively implement exactly what you are trying to do. Do a Google search for "jQuery ajax-upload", you could just use one of these controls out of the box to capture the result of the post or examine their code and roll your own.
You may also want to look into some of the Flash based uploaders if you are uploading large files. The pure form method of uploading does not have any way of implementing an upload progress, at least not until the new file functions are wide spread in browsers, which Flash does offer. http://github.com/slaskis/s3upload#readme is a good flash based file uploader specifically designed for S3 and gives you call back functions in JavaScript to handle errors, progress and more.

A: I think that you're trying to solve the wrong problem. The problem is not a detail one, with iframes and such, but that you want to have finer control over the upload. Upload the file to your server, then submit a request to the Amazon server, and you'll have absolute control over what's going on.
Significantly more complex, of course, but that's the price of control.


text:
Q: Insert TIME into Oracle SQL, DATE field Is there anyway to insert only time (no date) into a SQL field of type 'Date'
I have tried inserting:
13:00

and
01:00

and
13:00pm

and
01:00pm

But keep getting the error:
Not A Valid Month

A: The problem is the literal.  For date/time values, Oracle expects values in the form ddMMMyyyy.  (Or, you can use the expression DATE '2001-01-01.  Literal values are explained here.)  There doesn't appear to be a default format for time without a date.
In other words, you can get the same error with cast('1/1/2001' as date).
Instead, use the to_date() function:
select to_date('10:00', 'hh:mi')
from dual

This gives you much more flexibility with formats.
Also, as Ben notes in the comments, this gives you the current date with the time specified.

A: Example of using EXTRACT and time only portion of a SYSDATE and some date...:
SELECT hh||':'||mi||':'||ss time_only_portion
  FROM
  (
  Select
    EXTRACT(hour   From Cast(SYSDATE as timestamp)) hh,
    EXTRACT(minute From Cast(SYSDATE as timestamp)) mi,
    EXTRACT(second From Cast(SYSDATE as timestamp)) ss
  From dual
 )
/

SELECT EXTRACT(HOUR From t_stamp) hh
  FROM
 (
 SELECT CAST(to_date('21/02/2012 06:10:00 am', 'dd/mm/yyyy  hh:mi:ss am') AS TIMESTAMP) t_stamp
   FROM dual
 )
/


text:
Q: JS сортировка массива объектов по двум свойства Есть массив. Как отсортировать его по убыванию? Сначала по score, а потом по time
[
   {time: '20', score: '10'},
   {time: '33', score: '55'},
   {time: '51', score: '41'},
   {time: '10', score: '10'},
   {time: '20', score: '10'},
];

A: Не уверен, что я правильно понял. В примере сделал так: сортировка по score более приоритетна.

var s = [
   {time: '20', score: '10'},
   {time: '33', score: '55'},
   {time: '51', score: '41'},
   {time: '10', score: '10'},
   {time: '20', score: '10'},
];
s.sort(function(x1,x2) {
  if (x1.score < x2.score) return -1;
  if (x1.score > x2.score) return 1;
  // при равных score сортируем по time
  if (x1.time < x2.time) return -1;
  if (x1.time > x2.time) return 1;
  return 0;
});

console.log(JSON.stringify(s));


text:
Q: Core data - NSFetchrequest fetching twice the actual count of data NSFetchRequest in the below code is fetching in multiples times count of the data.. Example I have 3 as array count 1st time the method is called, next time it become 6 next 9 and so on. But in the database, the count remains as 3. Why is this happening?
// the method is called in viewDidLoad

- (void) create {

[orderList removeAllObjects];
  NSError * error;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"OrderList"
                                          inManagedObjectContext:context];
for (int addOrd = 0; addOrd < orderMainArray.count; addOrd++) {

    GetOrders *getOrd = (GetOrders*)[NSEntityDescription insertNewObjectForEntityForName:@"GetOrders" inManagedObjectContext:context];
    OrderList *ordList = (OrderList*)[NSEntityDescription insertNewObjectForEntityForName:@"OrderList" inManagedObjectContext:context];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"orderId contains[cd] %@", [[orderMainArray objectAtIndex:addOrd] objectForKey:@"orderId"]];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setEntity:entity];

      NSLog(@"\n \n \n count for same data = %d", [context countForFetchRequest:fetchRequest error:&error]);

    if ([context countForFetchRequest:fetchRequest error:&error] ==0 ) {

        // all data is saved here

        [getOrd addOrderListObject:ordList];
        if ([context save:&error]) {
            NSLog(@"The save was successful! %@", ordList.orderId);

        }
        else {
            NSLog(@"The save wasn't successful: %@", [error userInfo]);
        }
        }
    }
    NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] init];
    [fetchRequest1 setEntity:entity];

    orderList = [[context executeFetchRequest:fetchRequest1 error:&error] mutableCopy]; // array count increases every time the method is called

}

A: Each time I call insertNewObjectForEntityForName:InManagedObjectContext: I was creating and adding new objects. So changed that and now works fine.

A: The code mixes fetch requests and inserts of new managed objects.
You insert one OrderList NSManagedObject and one GetOrder NSManagedObject in each iteration of the for-loop. Given your description, I would assume that orderMainArray.count has a value of 3.


text:
Q: a program about searching a point in or out a triangle I wrote a program in "dev-c++" about discussing about a point. We want to know that it is in or out a triangle. Why doesn't my program work correctly? What should I do?
This is my program:
#include <iostream>
#include <math.h>
int main()
{
    int n,a,b,c,d;
    int x[n];
    int y[n];
    n=1;
    while (n<=4)
    {
        std:: cin >> x[n];
        std:: cin >> y[n];
        n=n+1;
    }
    a= fabs((1/2)*((x[1]*(y[2]-y[3]))+(x[2]*(y[3]-y[1]))+(x[3]*(y[1]-y[2]))));
    b= fabs((1/2)*((x[1]*(y[2]-y[4]))+(x[2]*(y[4]-y[1]))+(x[4]*(y[1]-y[2]))));
    c= fabs((1/2)*((x[1]*(y[3]-y[4]))+(x[3]*(y[4]-y[1]))+(x[4]*(y[1]-y[3]))));
    d= fabs((1/2)*((x[2]*(y[3]-y[4]))+(x[3]*(y[4]-y[2]))+(x[4]*(y[2]-y[3]))));
        if ((b+c+d)!= a)
    {
        std:: cout<< "out of triangle\n";
    }
    if (b+c+d==a)
    {
        std:: cout <<"in triangle\n";
    }
}

A: The input of this program consists of integer coordinates only, but to check if a point lies inside a triangle this method needs to know the area of triangles. The area of a triangle is
A = width * height / 2

and because of that final division it may return a floating point number. Thus, the intermediate variables a, b, c, d need to be at least float.
As long as all of the constants and variables at the right hand side of an = are integer, C calculates the result as an integer as well. Only at the very last step the result gets converted to the destination type. Thus,
double x = 2*3/4;

will be calculated as 2*3/4 using integers and resulting in 6/4 -> 1, and only then converted to a double value: 1.000. Forcing the intermediates to a float type fixes it:
double x = 2.0*3/4;

and then x = 1.5.

Be aware that when using floating point numbers, you could have run into accuracy problems with the final comparison
if (b+c+d==a)
  ...

Fortunately, this will not be a problem with your divisions by 2. The decimal value 0.5 can be represented exactly in float and double formats, as long as the 'whole' part does not exceed the number of available digits. But it's a good thing to keep in mind nevertheless.


text:
Q: function<->variable dependency graph In Python, suppose that you have a file, or collection of files in a repo, containing the definitions (or at least the signatures) of a collection of functions f(),g(),h().., which interact with a collection of variables A,B,C,D..The names of the variables are preserved in function signatures and function return variables. For example:

*

*C   = f(A,B)      // function f() takes variables A and B and returns variable Cyour text
D,E = g(A,C)      // function g() takes variables A and C and returns variables D and E
F   = h(C,D)      // etc

Is there a way to produce a dependency graph that helps visualize all functions f,g,h the variables they take and produce?
E.g. for toy example above you would see something like the following, but in a graph

*

*
A,B  -> f() -> C -> g() -> D,E
               A -> g()    D   -> h() -> F
                           C   -> h()

I explored dependency analysis in Python, but all I found is about package dependencies, which has nothing to do with the above.


text:
Q: Log4perl: how to switch to other-named log file on the fly? I am the author of the
Log4perl::KISS
module, and I want to convert the log_open function so that it can switch the current log file on the fly at any time without full Log::Log4perl reinitialization.
I know that the file appender in Log4perl can switch to the file with the same name (this possibility was added to allow log rotation), but I need to switch to a different filename. I don't know how to change the filename used by the file appender before switching to another file handle.
How to change the appender's filename if it is possible?

A: There is a file_switch method in Log::Log4perl::Appender::File that's briefly touched upon in the Description section.

If you want to switch over to a different logfile, use the file_switch($newfile) method which will first close the old file handle and then open a one to the new file specified.

There's no further documentation on it, but I believe you can use that.


text:
Q: Can I load a domain in my iFrame and when you click a link, it opens in the parent window, not the iframe? Similar to Stumbleupon, if you load random domains (ones that I do not own) and want to have the links within that page not just change within the iframe, but change on the parent url.
If that's hard to understand here's more layman terms:
URL: mywebsite.com/reddit.com
opens iframe on my website showing: reddit.com
click link within the iframe (showing reddit.com).
rather than it loading the new page in the iframe, can it load in the parent window at mywebsite.com/reddit.com/newlink
which would then open the iframe in my website, but would allow me to track what URL is being view and thus allowing me to perform my site-specific functionality.
Thanks!

A: in short, it cant happen. external sites are made to open links relative to their sites. there is no way to accomplish this.

A: you can set the link target to _top. Link
edit: Sorry, mis-read something. You can not edit the page on the other site through the iframe to change the target of the links. This is why on places like google images or stumbleupon they have an "X" in the corner that takes you to the page in the iframe.
If you could modify external pages, that would be a major phishing security risk as anyone could then make a page that is just an iframe to your bank but collects whatever you type into the username/password boxes.

A: In the old days if you made a page with frames you could specify what section your links took you to. Modifying links that aren't under your control is possible but rather a task and a half.
To use frames you could specify your target= within your  tag. Each frame is named on creation to make it easy.
That's an old approach. Hope it helps


text:
Q: how to use node.js and php on the same port I've installed node.js, socket.io, and express.js on port 12234 and that works very nice. But now I want to use php on an page on that port (12234) but I don't know how I can do that. Has anybody a solution?
sorry for my bad english, I'm Netherlands and not really good in english.

A: You can't run two applications on the same port. The easiest thing to do is proxy HTTP requests to PHP, running on another port, and proxy other requests to Socket.IO, running on another port.
Here's an example using http-proxy. Do note that this won't work for things like flashsockets and XHR long polling.
var httpProxy = require('http-proxy')

var server = httpProxy.createServer(function (req, res, proxy) {
  proxy.proxyRequest(req, res, {
    host: 'localhost',
    port: // whatever port PHP is running on
  });
})

server.on('upgrade', function (req, socket, head) {
  server.proxy.proxyWebSocketRequest(req, socket, head, {
    host: 'localhost',
    port: // whatever port Socket.IO is running on
  });
});

server.listen(80);

Alternatively, you could route your Express routes to PHP. If PHP was running on port 8080 for example:
app.get('/', function(req, res) {
  // send a HTTP get request
  http.get({hostname: 'localhost', port: 8080, path:'/', function(res2) {
    // pipe the response stream
    res2.pipe(res);
  }).on('error', function(err) {
    console.log("Got error: " + err.message);
  });
});

A: You can have node.js running as an upstream through nginx. Providing you're using nginx and php5-fpm.
upstream node {
    server 127.0.0.1:8080;
}

location / {
    proxy_pass  http://node;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    proxy_redirect off;
    proxy_buffering off;
    proxy_set_header        Host            $host;
    proxy_set_header        X-Real-IP       $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}

location ~ \.php$ {
    index index.php;
    root   /var/www;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  /var/www/$fastcgi_script_name;
}