text:
Q: White spaces are required between publicId and systemId I am trying to make a ajax call to other domain locally from my computer by writing some proxy code in jsp. And this is my jQuery AJAX code that is calling proxy.jsp page.
 var metadata = 'https://rest-search.host.com/machine/search/meta?id=';

var on_show_info= function() {

    var AjaxCall = data + current_doc_info.id;
    alert(AjaxCall);
                request_meta_info = $.ajax({
                url: "proxy.jsp?url=" + AjaxCall,
                type: 'GET',
                success: check,
                error: error
        });
    };

And my JSP file is:-
<%@ page language="java" import="org.w3c.dom.*,javax.xml.parsers.DocumentBuilder,javax.xml.parsers.DocumentBuilderFactory,java.net.*,java.io.*" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%

String urlToQuery = request.getParameter("url");
System.out.println("rj   " +urlToQuery);
URL url = new URL(urlToQuery);
final String login ="user";
final String password ="pass";

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication (login, password.toCharArray());
    }
});
URLConnection conn = url.openConnection();

InputStream in = conn.getInputStream();

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db =dbf.newDocumentBuilder();
Document doc=db.parse(urlToQuery);

NodeList nl= doc.getElementsByTagName("attr");
%>

<%= nl.item(0).getFirstChild().getNodeValue() %>

And When I check the response, I am getting this error for the XML file it is parsing:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 500 White spaces are required between publicId and systemId.</title>

HTTP ERROR 500

Problem accessing /proxy.jsp. Reason:

    White spaces are required between publicId and systemId.

Caused by:

org.xml.sax.SAXParseException: White spaces are required between publicId and systemId.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:180)
    at org.apache.jsp.proxy_jsp._jspService(org.apache.jsp.proxy_jsp:70)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:109)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:389)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:486)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:380)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:327)
    at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:126)
    at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213)
    at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171)
    at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
    at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
    at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:67)
    at com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:122)
    at com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:110)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
    at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:536)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:915)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:539)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:405)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

Powered by Jetty://

And the XMl file is this:-
<results><result><attr value="HW/SW" name="Line"/><attr value="ASIC" name="Description"/><attr value="CD" name="Number"/><attr value="AS" name="DocumentType"/><attr value="" name="Date"/><</result></results>

What wrong I am doing here.. Any suggestions will be appreciated..

A: I just found my self with this Exception, I was trying to consume a JAX-WS, with a custom URL like this:
String WSDL_URL= <get value from properties file>;
Customer service = new Customer(new URL(WSDL_URL));
ExecutePtt port = service.getExecutePt();
return port.createMantainCustomers(part);

and Java threw:
XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,63]
Message: White spaces are required between publicId and systemId.

Turns out that the URL string used to construct the service was missing the "?wsdl" at the end.
For instance:
Bad:
http://www.host.org/service/Customer

Good:
http://www.host.org/service/Customer?wsdl

A: The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.
You'll get the error with (for instance):
<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

You won't with:
<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">

Notice "" at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.
By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.

A: I just found this post: http://forum.springsource.org/showthread.php?68949-White-spaces-are-required-between-publicId-and-systemId./page2&s=c69fe19798f5a071d22eaf681ca84a56
A couple people here had success by switching the lines around in an XML file.

A: Change the order of statments.
For me, changing the block of code
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/beans/spring-beans.xsd"

with
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context"

is valid.

A: If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it.  I had the same issue and adding the proxy configs to the network settings solved it.

*

*Go to your preferences (Eclipse -> Preferences on a Mac, or Window -> Preferences on a Windows)

*Then -> General -> expand to view the list underneath -> Select Network Connections (don't expand)

*At the top of the page that appears there is a drop down, select "Manual."

*Then select "HTTP" in the list directly below the drop down (which now should have all it's options checked) and then click the "Edit" button to the right of the list.

*Enter in the proxy url and port you need to connect to the internet in your web browser normally.

*Repeat for "HTTPS."

If you don't know the proxy url and port, talk to your network admin.

A: It may not be related to the mistake of the person who opened the title, but I wanted to share it because it is the same error as the title.
It was an error I got in one of my runs jsf primeface on glassfish server with netbeans and maven.
This was the way of give me fail:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

But I returned this way and I didn't get any error:

<!DOCTYPE html>


text:
Q: Android Bitmap remove white margin I've got a question regarding Bitmaps in Android: I 've got a Bitmap with white margins [size unknown] around. Is it possible to create a new Bitmap with all the white margins removed (rectangular shape)?
Bitmap bmp = Bitmap.createBitmap(width, bmpheigth, Config.ARGB_8888);
    Canvas canvas = new Canvas(bmp);
    canvas.setBitmap(bmp);
    canvas.drawColor(Color.WHITE);
// draw here things!

It is asumed to be unknown where are things painted.
What is a good way to do that?
thanks!

A: Thanks @Maxim Efimov &  @StackOverflowException
Just in Case Someone will need a snippet for this kind of problems:
this method returns a cut out smaller Bitmap with Margins removed. passing the pixels to a int-array first and then working with the array is a bit faster than the Bitmap.getPixel method
just call the method indicating Source Bitmap and Background color.
Bitmap bmp2 = removeMargins(bmp, Color.WHITE);

private static Bitmap removeMargins2(Bitmap bmp, int color) {
    // TODO Auto-generated method stub

    long dtMili = System.currentTimeMillis();
    int MTop = 0, MBot = 0, MLeft = 0, MRight = 0;
    boolean found1 = false, found2 = false;

    int[] bmpIn = new int[bmp.getWidth() * bmp.getHeight()];
    int[][] bmpInt = new int[bmp.getWidth()][bmp.getHeight()];

    bmp.getPixels(bmpIn, 0, bmp.getWidth(), 0, 0, bmp.getWidth(),
            bmp.getHeight());

    for (int ii = 0, contX = 0, contY = 0; ii < bmpIn.length; ii++) {
        bmpInt[contX][contY] = bmpIn[ii];
        contX++;
        if (contX >= bmp.getWidth()) {
            contX = 0;
            contY++;
            if (contY >= bmp.getHeight()) {
                break;
            }
        }
    }

    for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
        // looking for MTop
        for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
            if (bmpInt[wP][hP] != color) {
                Log.e("MTop 2", "Pixel found @" + hP);
                MTop = hP;
                found2 = true;
                break;
            }
        }
    }
    found2 = false;

    for (int hP = bmpInt[0].length - 1; hP >= 0 && !found2; hP--) {
        // looking for MBot
        for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
            if (bmpInt[wP][hP] != color) {
                Log.e("MBot 2", "Pixel found @" + hP);
                MBot = bmp.getHeight() - hP;
                found2 = true;
                break;
            }
        }
    }
    found2 = false;

    for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
        // looking for MLeft
        for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
            if (bmpInt[wP][hP] != color) {
                Log.e("MLeft 2", "Pixel found @" + wP);
                MLeft = wP;
                found2 = true;
                break;
            }
        }
    }
    found2 = false;

    for (int wP = bmpInt.length - 1; wP >= 0 && !found2; wP--) {
        // looking for MRight
        for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
            if (bmpInt[wP][hP] != color) {
                Log.e("MRight 2", "Pixel found @" + wP);
                MRight = bmp.getWidth() - wP;
                found2 = true;
                break;
            }
        }

    }
    found2 = false;

    int sizeY = bmp.getHeight() - MBot - MTop, sizeX = bmp.getWidth()
            - MRight - MLeft;

    Bitmap bmp2 = Bitmap.createBitmap(bmp, MLeft, MTop, sizeX, sizeY);
    dtMili = (System.currentTimeMillis() - dtMili);
    Log.e("Margin   2",
            "Time needed " + dtMili + "mSec\nh:" + bmp.getWidth() + "w:"
                    + bmp.getHeight() + "\narray x:" + bmpInt.length + "y:"
                    + bmpInt[0].length);
    return bmp2;
}

A: Use Bitmap.createBitmap(source, x, y, width, height) so knowing the white margin size you can do what you want.

A: My solution:
private Bitmap trim(Bitmap bitmap, int trimColor){
        int minX = Integer.MAX_VALUE;
        int maxX = 0;
        int minY = Integer.MAX_VALUE;
        int maxY = 0;

        for(int x = 0; x < bitmap.getWidth(); x++){
            for(int y = 0; y < bitmap.getHeight(); y++){
                if(bitmap.getPixel(x, y) != trimColor){
                    if(x < minX){
                        minX = x;
                    }
                    if(x > maxX){
                        maxX = x;
                    }
                    if(y < minY){
                        minY = y;
                    }
                    if(y > maxY){
                        maxY = y;
                    }
                }
            }
        }
        return Bitmap.createBitmap(bitmap, minX, minY, maxX - minX + 1, maxY - minY + 1);
    }

It isn't very fast, for 1280 x 576 px bitmap execution took 2965ms on Xiaomi Redmi 3S.
If it possible scale down image before triming:
private Bitmap scaleDown(Bitmap bitmap, float maxImageSize, boolean filter) {
        float ratio = Math.min(maxImageSize / bitmap.getWidth(), maxImageSize / bitmap.getHeight());
        int width = Math.round(ratio * bitmap.getWidth());
        int height = Math.round(ratio * bitmap.getHeight());

        return Bitmap.createScaledBitmap(bitmap, width, height, filter);
    }

A: Late to the party, but this variation is a bit faster and perhaps easier to read:
    public static Bitmap imageWithMargin(Bitmap bitmap, int color, int maxMargin) {
    int maxTop = 0, maxBottom = 0, maxLeft = 0, maxRight = 0;
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int[] bitmapArray = new int[width * height];
    bitmap.getPixels(bitmapArray, 0, width, 0, 0, width, height);

    // Find first non-color pixel from top of bitmap
    searchTopMargin:
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            if (bitmapArray[width * y + x] != color) {
                maxTop = y > maxMargin ? y - maxMargin : 0;
                break searchTopMargin;
            }
        }
    }

    // Find first non-color pixel from bottom of bitmap
    searchBottomMargin:
    for (int y = height - 1; y >= 0; y--) {
        for (int x = width - 1; x >= 0; x--) {
            if (bitmapArray[width * y + x] != color) {
                maxBottom = y < height - maxMargin ? y + maxMargin : height;
                break searchBottomMargin;
            }
        }
    }

    // Find first non-color pixel from left of bitmap
    searchLeftMargin:
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            if (bitmapArray[width * y + x] != color) {
                maxLeft = x > maxMargin ? x - maxMargin : 0;
                break searchLeftMargin;
            }
        }
    }

    // Find first non-color pixel from right of bitmap
    searchRightMargin:
    for (int x = width - 1; x >= 0; x--) {
        for (int y = height - 1; y >= 0; y--) {
            if (bitmapArray[width * y + x] != color) {
                maxRight = x < width - maxMargin ? x + maxMargin : width;
                break searchRightMargin;
            }
        }
    }

    return Bitmap.createBitmap(bitmap, maxLeft, maxTop, maxRight - maxLeft, maxBottom - maxTop);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: MVC Localization I'm trying to do localization in MVC3, and I want to use a database to store the resources. I've read up on resource providers, but I haven't found a way of using a resource provider without losing the strongly-typed access that a regular resource file has.
So, what is the best way to do localization, while maintaining strongly-typed access? (Ideally with a database too)

A: If you want to store the entries in a database you can do the same trick as the normal resource files in Visual Studio are doing for you.
Normally the resource file is parsed and a static class is generated from it. In your case you could us a T4 template(Code Generation and T4) to connect to the database and build a resource class from the 'Id' columns in your database you have the same resource class.
On startup you could load the translated strings from the database and initialize your T4 resource class with it.

A: The simple and effective way to do it, is just to use the NuGet package dedicated for storing resources in database and generating the Strongly Typed Resources.
NuGet Package: http://www.nuget.org/packages/Globsite.Globalization.Mvc
Project Site: http://globsite.net/GlobsiteGlobalizationLibrary
This package contains the ready to use and complex infrastructure for database stored resources, which implements .NET Resource-Provider Model.
Generated classes can be synchronized with a database with the T4 Template run, what can be done, for example, on each build.
You can use the resources like this:
@using MyResources.SampleSet
@Resources.SampleKey


text:
Q: How to use configuration files(or variables) in js file which are defined under public directory in zend I want to use some important variables in some of my js files like fb, twitter access keys so I defined a config.ini file under config folder in zend. I am able to read these config variables in all my controller and models using INI reader but I don't know how to read these variables in my js files. Is there any other method to define config variables for js files ?
My js files are located under public folder. To read these variables in index.phtml of any module I am using view model to return these variables from controller and then use php to read these vaiables in phtml file. Is there any better method to read these vaiables in phtml file ?
$reader = new Ini();
$data   = $reader->fromFile('config/config/config.ini');

I am using this code to read my config.ini file and its working fine.

A: Using Ajax
ZF2 (PHP) Side:

*

*Create new Controller/Ajax

*

*Set it to empty layout

*Enable Json Strategy

*Add new action to Ajax cotroller e.g AjaxAction

*Write code

public function AjaxAction(){
//maybe create service for that?

    $reader = new Ini();

        $reader = new Ini();

        $data = $reader->fromFile('config/config/config.ini');

        return new JsonModel(['Data' => $data]);

    }

Jquery
jQuery(document).ready(function($){
var url = "http://urlToyourSite.com/ajax/ajax";
$.get(url).done(function(databack){
var data = databack.Data(); // here is your ini object
});

});

InsertData to layout

*

*Create new Controller/Ini

*

*Add new action to Ajax cotroller e.g AddToLayoutAction

*Write code

public function __constuct(){
self::__construct(); //for parent
//maybe create service for that?

    $reader = new Ini();

    $data = $reader->fromFile('config/config/config.ini');

    $this->layout()->setVariable("Data",$data);

}

in layout:
//code
$data = $this->Data;


text:
Q: How to check which field raised a ValidationError in Django REST Framework I'm using self.assertRaisesMessage(rest_framework_exceptions.ValidationError, expected_message) to test my custom validators. Is there some way to use that or something similar to also assert which field caused the validation error to be raised?
The use case is that I have two validators which raise the same error for different fields, and because of the relation between them (start and end date) it's not possible to write a test which will fail before introducing the end date and which will also succeed for the right reason after introducing the end date.

A: Can you assert the error by testing the whole form? Like:
class FooSerializer(Serializer):
    start_date = DateField()
    end_date = DateField()

foo = FooSerializer(data={'start_date': '2018-01-01', 'end_date': 'incorrect value'})
self.assertFalse(foo.is_valid())
self.assertNotIn('start_date', foo.errors)
self.assertIn('end_date', foo.errors)


text:
Q: How to install over existing installation on an encrypted filesystem? Is there a way to configure the Ubuntu installer to re-install over an existing Ubuntu installation on an encrypted filesystem?
# lsblk
nvme0n1             259:0    0   1.8T  0 disk
├─nvme0n1p1         259:1    0   731M  0 part  /boot
├─nvme0n1p2         259:2    0     1K  0 part
└─nvme0n1p5         259:3    0   1.8T  0 part
  └─nvme0n1p5_crypt 253:0    0   1.8T  0 crypt
    ├─z--vg-root    253:1    0   1.8T  0 lvm   /
    └─z--vg-swap_1  253:2    0   976M  0 lvm   [SWAP]

I've seen plenty of guides on how to re-install Ubuntu over an existing installation, but none of those were encrypted.


text:
Q: jQuery Window Load in iOS 8 I recently updated my phone to iOS 8 and now I am experiencing really unusual behavior.
Here is a demo of the problem:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
alert("A");
jQuery(window).load(function(){
    alert("B");
});
</script>

In Safari iOS 7, this brings up the dialog boxes "A" and "B". But when viewed in Safari iOS 8, only dialog box "A" shows up.
Any ideas on why window load would not be working in iOS 8?

A: I don't have a real solution for this, but if you have any  or  in your page, Safari on iOs8 do not trigger the load event.
So you have at least 2 solutions:

*

*count your externals files like images, css, scripts and attach a
load event on them and wait for the last .load of those files

*write your tag video/audio after the load events

//EDIT:
So I write this that helped me to still use video:
var $video = $('.player');
$video.each(function(){
    this.outerHTML = this.outerHTML.replace('div', 'video')
});
$video = $('.player');

See Browser compatibility here to see if outerHTML fits with your compatibility https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML#Browser_compatibility

A: Use window.onload = function(){ }; on the behalf of jQuery(window).load(function(){ }); I am able to fix this issue on my project.


text:
Q: Facebook login returns loginCancelled in Corona SDK facebook.login("6230773377xxxxx", fbListener, {"publish_actions"})

in the listener the event.phase is always loginCancelled and i don't know why. can anybody help?

A: You likely have something misconfigured.  If you're on Android, it's very likely the keyhash. But without more information about what device, your build.settings, Corona SDK version, it's going to be hard to answer.
You might want to study this tutorial/blog post closely and make sure you've followed it and see if that solves the problem.
http://coronalabs.com/blog/2013/07/30/understanding-facebook-authentication/
Rob

A: Update to the latest build, this was a problem that was found in the G2.0 engine and has since been resolve :)


text:
Q: display distinct records sqlite android My cursor is returning records twice even though I set the distinct to true:
return myDataBase.query(true, DB_TABLE, new String[]
                {"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null);
FYI,
   public Cursor getData(String[] symptoms) {
    String where = KEY_SYMPTOMS + "= ?";
    String orStr = " OR ";

    StringBuilder builder = new StringBuilder(where);
    for(int i = 1; i < symptoms.length; i++)
        builder.append(orStr).append(where);

    return myDataBase.query(true, DB_TABLE, new String[]
            {"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null);

}

Or I tried to change to rawQuery
    return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM "
    + DB_TABLE + " " + builder.toString() + symptoms.toString(), null);

My LogCat says:
  03-02 22:57:02.634: E/AndroidRuntime(333): FATAL EXCEPTION: main
  03-02 22:57:02.634: E/AndroidRuntime(333): android.database.sqlite.SQLiteException: near "=": syntax error: , while compiling: SELECT DISTINCT conditions FROM tblSymptoms symptoms= ? OR symptoms= ?[Ljava.lang.String;@405550f8

Please help me identify what seems to be missing in here. Any help is truly appreciated.

A: Solution
You want DISTINCT conditions but Android requires the _id column which is a problem because you cannot mix and match: SELECT _id, DISTINCT condition....  However you can use the GROUP BY clause instead:
return myDataBase.query(DB_TABLE, new String[] {"rowid as _id", KEY_CONDITIONS},
        builder.toString(), symptoms, KEY_CONDITIONS, null, null);

Explanations
This query:
return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM "
    + DB_TABLE + " " + builder.toString() + symptoms.toString(), null);

Failed because you are passing String[] symptoms in the wrong parameter, try:
return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM "
    + DB_TABLE + " " + builder.toString(), symptoms);

This query:
return myDataBase.query(true, DB_TABLE, new String[] {"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null);

Failed because DISTINCT is looking at both the id and condition columns. It is the equivalent of: SELECT DISTINCT(_id, conditions) ... You, obviously, only want distinct conditions...

A: you have two general option two do this Task
use row query **and
**use DISTINCT keyword
for using row query you can directly use function of mr.Sam
and for using DISTINCT keyword you can use
public Cursor query (boolean distinct, String table, String[] columns,
                 String selection, String[] selectionArgs, String groupBy,
                 String having, String orderBy, String limit)

because query stucher is retunsthis:
query(false, table, columns, selection, selectionArgs, groupBy,
            having, orderBy, null /* limit */);

in this code first arg is for DISTINCT so provide it as true.
so your query will like this
Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN1 ,COLUMN2, COLUMN_NAME_3 }, null, null, COLUMN2, null, null, null);

BasicallyDISTINCT keyword returns a column name only once if it apperase more then one time.


text:
Q: Create a model attribute from checkbox input This creates and saves a new row to my database.  The problem is that I have a checkbox in my view file for a boolean value, but no matter whether the box is checked or not, the new row is always false. I also can't get any of the other attributes to show up as anything other than nil. Any ideas?
This is my view is:
<%= form_for(@setting) do |s| %>

    <%= s.label :my_setting_attribute %>
    <%= s.check_box(:my_setting_attribute) %>

    <%= s.submit "Submit" %>

<% end %>

And my controller:
def new
  @setting = Setting.new
end

def create
  @setting = Setting.new(params[:setting])
  if @setting.save
    redirect_to :action => 'index', :id => @setting.id
  else
    redirect_to :action => 'error'
  end
end

I think I have my route file set correctly:
resources :settings do
  collection do
    get :index
    post 'settings/new'
    get 'settings/show'
  end
end

Here's the development log excerpt:
Started POST "/settings" for 10.7.94.191 at 2011-07-25 20:30:11 -0400
  Processing by SettingsController#create as HTML
  Parameters: {"utf8"=>"â", "authenticity_token"=>"xxxxxxxxxxx=", "setting"=>{"my_setting_attribute"=>"1", "other_setting_attribute"=>"hello"}, "commit"=>"Submit"}
ESC[1mESC[36mUser Load (0.1ms)ESC[0m  ESC[1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1ESC[0m
  ESC[1mESC[35mSQL (0.1ms)ESC[0m  BEGIN
  ESC[1mESC[36mSQL (1.0ms)ESC[0m  ESC[1mdescribe `settings`ESC[0m
  ESC[1mESC[35mAREL (0.3ms)ESC[0m  INSERT INTO `settings` (`facebook_token`, `twitter`, `user_id`, `created_at`, `updated_at`, `image_id`) VALUES (NULL, NULL, NULL, '2011-07-26 00:30:12', '2011-07-26 00:30:12', NULL)
ESC[1mESC[36mSQL (57.1ms)ESC[0m  ESC[1mCOMMITESC[0m
Redirected to http://3000/settings?id=12

A: May not be the "correct" way of doing it but you could probably do this:
In your controller for the update and create method, check what the value of params[:my_setting_attribute] is. You may need to conditionally set the attribute to either "true" or "false".
e.g. perhaps it is returning "1" instead of true (which your log seems to indicuate), then you can set it yourself with something like @my_object.my_setting_attribute = true if params[:my_setting_attribute] == "1". Then probably add an else clause to set everything else to false, just to be safe.


text:
Q: Models of a Propositional Logic Program I'm new to answer sets and logic, and struggle to understand the definition of a model in the book I'm reading. Given the propositional logic Program
$a \leftarrow \\
c \leftarrow \sim b, \sim d \\
d \leftarrow a, \sim c$
where ~x is the default negation ("x is possibly false"). The book claims there are six models to this program with the following definition:
A set X $\subseteq$ A of ground atoms is a model of a propositional logic program P, if head(r) $\in$ X whenever body(r)+ $\subseteq$ X and body(r)- $\cap$ X = $\emptyset$ for every r $\in$ P.
body(r)+ are the positive atoms of the body, body(r)- the default negated ones.
I have come up with two possible models: {a, c} and {a, d}, but they also claim {a, b, c, d} to be a model, which I don't understand.

A: The program may be rewritten in propositional logic as :

$a$
$(\lnot b \land \lnot d) \to c$
$(a \land \lnot c) \to d$

and we have to find its models, i.e. the truth-assignements that simultaneously satisfy them.
As you correctly said, both $\{ a, c \}$ and $\{ a, d \}$ are models.
We will check the first one. With a truth-assignement $v$ such that :

$v(a)=v(c)=$ T

we have $v(a \land \lnot c)=$ F and thus : $v((a \land \lnot c) \to d)$= T : a conditional with a false antecedent is true.
We have $v(c)=$ T and thus : $v((\lnot b \land \lnot d) \to c)$= T :  a conditional with a true consequent is true.
And obviously $v(a)=$ T.
Consider now : $\{ a, b, c, d \}$.
Again : $v(a)=$ T and with $v(c)=$ T we have : $v(a \land \lnot c)=$ F and so : $v((a \land \lnot c) \to d)$= T.
Finally : $v(d)=$ T, and thus : $v((a \land \lnot c) \to d)$= T.

We may "generalise" the above argument and conclude that :

every set that includes one of the models $\{ a, c \}$ and $\{ a, d \}$ must also be a model.

This is why they are six :

$\{ a, c \} , \{ a, d \} , \{ a, c, b \} , \{ a, c, d \} , \{ a, d, b \} , \{ a, b, c, d \}.$


text:
Q: issue with grid using ng-repeat I'm trying to implement a grid like layout using ng-repeat.
When the list is having empty data grid is getting alignment issues. I'm not getting where I've gone wrong.
please help me solve this. JS Fidlle
HTML

                {{goals}}

JS
var n = [
["Empty","Jan","Feb","Mar","APR","MAY"],["person1",".",".",".",".","."],["person2",".",".",".",".","."],["person3",".",".",".",".","."],["person4",".",".",".",".","."],["person5","","","","",""]
]

function MyCtrl($scope) {
    $scope.items = n;
}

A: This is a styling issue with inline-block elements. To fix, add vertical-align: bottom style.

   {{goals}}


text:
Q: Identity theorem in complex analysis The 2nd paragraph of the entry for Identity theorem in wikipedia states that
"Thus a holomorphic function is completely determined by its values on a single open neighborhood in D, or even a countable subset of D (provided this contains a converging sequence). This is not true for real-differentiable functions."
What are some examples where it fails to hold in real variable theory ? Also, how can an identity being true for real numbers is true for complex numbers by the identity theorem ? Thank you for any help.

A: For example, let $f(x)$ be $0$ if $x < 0$ and $e^\frac{-1}{x^2}$ if $x \geqslant 0$, and let $g(x) = 0$. Then $f(x)$ and $g(x)$ are both smooth, have the same values on negative half-line, but differ on positive half-line.

A: There are "bump functions" non zero infinite differentiable functions that are compactly supported (that vanish outside a compact subset).

A: To give a counterexample with functions differentiable as functions of two real variables, let's first agree that there exist real-valued functions, $f(x,y)$, that are infinitely smooth on the whole $xy$-plane, are $\equiv 1$ in some disc $D$ centered at the origin, and are $\equiv 0$ outside a bigger disc $D'$ centered at the origin.  (Related concept: mollifiers.)  Such a function coincides on $D$ with the function $g \equiv 1$ (the function constantly equal to 1 in the whole $xy$-plane), but is not identical to $g$: they clearly disagree outside of $D'$.
To understand why this fails for two real variables, but holds for the complex variable, the key is the following fact from linear algbera: a transformation from ${\mathbb R}^2$ to ${\mathbb R}^2$ that is linear over the reals can fail to be linear over the complex numbers if we try to write $(x, y)$ as $x + iy$.
For a complex-valued function $f(z)$ of a complex variable to be holomorphic at a point $z_{0}$, the total derivative $f'(z_0)$ has to be a linear transformation over the complex scalars, and--according to the boldfaced statement above--this is a much stronger requirement than that $f$ should be differentiable w.r.t. each of: $\Re(z), \Im(z)$.
If we make the variable change
$$
(x, y) \mapsto (z = x + iy, \overline{z} = x - iy),
$$
it can be shown that for a function $f(z)$ of a complex variable to be homolorphic, it is necessary that
$$
{\partial f \over \partial \overline{z}} = 0,
$$
which is just another form of the Cauchy-Riemann equations: see Theory of analytic functions.  The latter book also contains a pretty transparent and short proof of what you call the Identity Theorem by using some facts from topology.

A: If you want an example where the function is a real differentiable function (not necessarily infinitely differentiable) then $f(x)=x^{2}\sin (\frac 1 x)$ for $x \neq 0$, $f(0)=0$ is one such function. Note that $f(\frac 1 {n\pi})=0$ for all $n \in \mathbb N$.


text:
Q: Xamarin.forms Navigation Drawer on button click How to display navigation drawer in xamarin forms on button / icon click.
I have a button in my detail page and on click i want navigation drawer ISPresented to be true. how can this be done? Thanks in advance

A: There are multiple options here, the most obvious and simple to implement is to use the MessagingCenter. Since you can't access the MasterDetailPage directly and you want to avoid coupling.
At the point where you create your MasterDetailPage, subscribe to an event like this:
MessagingCenter.Subscribe<MainPage> (this, "OpenMaster", (sender) => {
    masterPage.IsPresented = !masterPage.IsPresented;
});

Now on the button that you want to trigger your functionality with, implement sending this message like this:
MessagingCenter.Send<MainPage> (this, "OpenMaster");.
Now, I don't know any details about your code, so I can't help you with where to put this exactly and you probably need to replace some things like MainPage to correspond with your code. But this should give you an idea.

A: Gerald It worked
At the point where you create your MasterDetailPage, subscribe to an event like this:
MessagingCenter.Subscribe<MainPage> (this, "OpenMaster", (sender) => {
    masterPage.IsPresented = !masterPage.IsPresented;
});

Now on the button that you want to trigger your functionality with, implement sending this message like this:
MessagingCenter.Send<MainPage> (this, "OpenMaster");.

A: try this simplest solution
((MasterDetailPage)App.Current.Mainpage).Master.IsPresented = true;


text:
Q: Reading information from Memory array into excel sheet formula I'd like to use data from an array that I've got stored in my VBA memory directly into a formula in my sheet. As an example, I'd like to avoid using Application.vlookup() to print to each cell individually as this is slow. And instead do something like the following
Sub MySub()
    Dim MyArrayStoredInVBaMemory() As Variant
    MyArrayStoredInVBaMemory = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
    Cells(1, 1).Value = 1
    Cells(1, 2).FormulaR1C1 = "=vlookup(RC1,MyArrayStoredInVBaMemory,1,0)"
    Cells(1, 2).Copy
    Cells(1, 2).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
End Sub

Your help is appreciated.

A: One way is to make a String from the Array
Sub qwerty()
    ary = Array(1, 2, 3)
    Dim st As String
    st = ary(0) & "," & ary(1) & "," & ary(2)
    Range("A1").Formula = "=SUM(" & st & ")"
End Sub


text:
Q: Umbraco: Property Querying (archetype) I have an Archetype property editor set up with multiple fieldsets, each fieldset with 2 fields: a text box, and a media picker for image.
In a GetImage(string imgId){} method I'm trying to get the fieldset with the image url and text box value based on the imgId parameter from the media picker, and to return a htmlString. Not sure if this the best idea, I'm open to suggestions.
public static string GetIcon(string imgId)
{
    var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
    var myProperty = (IPublishedContent)umbracoHelper.Content(5369).GetPropertyValue<ArchetypeModel>("myProperty");
    return "";
}

To get all the items from property I would do:
foreach (var item in myProperty)
{
    var imgId = item.GetValue("img") //get the image id
    var img = umbracoHelper.TypedMedia(imgId);

    @item.GetValue("imgTitle")
}

I noticed while debugging that fieldsets within archetype property don't have built in unique ID's ???
How can I get the image and textBox value by comparing the image Id from media picker?
Something like: ??
var icon = myProperty.Where(x => x.icon == iconId); //wrong

A: I just played with this too. What I did was:
var helper = new UmbracoHelper(UmbracoContext.Current);
var media = helper.TypedMedia(iconId);
var imageUrl = media.GetPropertyValue<string>("umbracoFile");

This will return a URL like this: "/media/1001/1.jpg". This way you can have a much cleaner view with:
foreach (var item in myProperty)
{

    @item.GetValue("imgTitle")
}


text:
Q: CheckMarx is giving the variable should be sanitized and validated We have below code in nodejs
int i = _.get(req.body, "i")
res.send(i);

When checkmarx finds above code, it says i should be sanitized and validated.  Can anyone please help on how to resolve this issue?
Thanks in advance

A: If you meant this:
int i = _.get(req.body, "i");
res.send(i);

Then it seems Checkmarx managed to find a Reflected XSS vulnerabilty.
When you get untrusted input in a request from a user it may contain a malicious script that might be sent in the response and run on the client side. This is called Reflected Cross Site Scripting (XSS).
Prevention depends on many factors. OWASP wrote a pretty good guide:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

A: int i = _.get(req.body, "i") res.send(i);
Issue :
Here you are setting your response fetching value from request body, which embeds untrusted data in the generated output with send. This untrusted data is embedded straight into the output without proper sanitization.

Solution :
Sanitize request body attributes before setting it to response
requestSanitizer.setOptions({
    body :{
        name : [validator.escape,validator.ltrim],
        test : [validator.ltrim]
    }
});

you must first import these packages :
var requestSanitizer = require('request-sanitizer')();
var validator = requestSanitizer.validator;

and then finally set requestSanitizer  as an additional param to API call


text:
Q: JText string input, then display output to JList I am pretty new in Java programming, I have been trying to solve this simple program
it reads user input, then the ADD button will simply display the typed string on the JList.
The remove button will simply remove the desired item in the JList.
I am quite confused how to put the action listener thing in the code, or get text whatever
it is. I'd really appreciate if you can help me solve this simple GUI.
It reads user input in JText (String) and when I click the add button (maybe action performed?) the String will be basically populated in JList. and the Remove button will
simply remove the selected String in JList.

A:  Step 1
Bind the code to the specific event, using the addActionListener method.
button.addActionListener(new ActionListener({
       public void actionPerformed(ActionEvent e)
       {
            // Bind the method to the button.
       }
});

 Step 2
Populate that method with the relevant code.
 String value = jTextBox.getText();
 // Grab the String value.
 jListModel.addElement(value);
 // And add it to the list model that informs the JList.

 Altogether
button.addActionListener(new ActionListener({
       public void actionPerformed(ActionEvent e)
       {
              String value = jTextBox.getText();
              // Grab the String value.
              jListModel.addElement(value);
              // And add it to the list.
       }
});

 Useful Links
Here is a very good tutorial from Oracle detailing how to manipulate lists a million and one different ways.


text:
Q: CanActivate does not work AngularDart 4 I recently had a problem with the CanActivate annotation since I migrated from version 4 of AngularDart. Indeed, the CanActivate annotation does not run.
My Code :
import 'dart:html' as html;

import 'package:angular/angular.dart';
import 'package:angular_router/angular_router.dart';
import 'package:maho_enterprise/app_component.dart';
// Others import

@Component(selector: "view-main"
  ,templateUrl: "main_component.html"
  ,styleUrls: const ["main_component.css"]
  ,directives: const [TopBarComponent,SideBarComponent])
@CanActivate(verifyIfUserIfAuthenticate)
class MainComponent {

}

bool verifyIfUserIfAuthenticate(ComponentInstruction next, ComponentInstruction prev) {
  html.window.console.info("CanActivate works correctly");
  AuthenticationService service = new AuthenticationService.empty();
  bool connected = service.isConnected();
  html.window.console.info("Value connected : "+connected.toString());
  if(!connected) {
    Router router = myInjector.get(Router);
    router.navigateByUrl("/login");
    return false;
  }
  return true;
}

Has anyone encountered this problem with version 4 of AngularDart?
thanks for the help.

A: Unfortunately CanActivate is no longer supported in AngularDart 4.0.0. It required very special compiler code that can't be supported long-term, and the router is changing in 5.x.x. As a workaround I suggest using the OnActivate lifecycle method.
I'll add a bug to remove the API and document this change.


text:
Q: django admin foreign key to file field and many to many field I have a model Teacher which has following data:
class Teacher(models.Model):
    name = models.CharField(max_length=100)
    thumbnail = models.ForeignKey(Thumbnail)

class Thumbnail(models.Model):
    thumbnail = models.FileField(upload_to=upload_to)

class TeacherAdmin(admin.ModelAdmin):
    list_display = ('name',)

Here I want to relate all the thumbnail in my project to Thumbnail field. In my admin it shows me a dropdown of thumbnail while I want to add the thumbnail from admin.
Is it possible that I can upload from admin too?
Also what can I do in the case like :
class Teacher(models.Model):
    name = models.CharField(max_length=100)
    thumbnail = models.ManyToManyField(Thumbnail)

If I want to add multiple Images.
The only issue I am having is on admin side. Client side can be handles from regular forms.
Need suggestions and Ideas


text:
Q: Getting 'unsupported method, fql.multiquery' when fetching data from Facebook I'm trying to fetch data in my Android-App from Facebook via FQL multiquery like discribed here: http://www.kanatorn.info/2011/12/31/fql-multiple-query-android-sdk-example/
here's my code:
        Bundle params = new Bundle();
        JSONObject multiquery = new JSONObject();
        try {
            multiquery.put("query1", "SELECT eid, name, start_time, is_date_only, pic_square, pic_big, location FROM event WHERE eid IN" +
                "(SELECT eid FROM event_member WHERE uid=me() AND start_time >= now()) ORDER BY start_time");
            multiquery.put("query2", "SELECT eid, rsvp_status, start_time FROM event_member WHERE uid=me() AND start_time >= now() ORDER BY start_time");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        params.putString("method", "fql.multiquery");
        params.putString("queries", multiquery.toString());

        Session session = Session.getActiveSession();

        Request request = new Request(session,
            "/fql",
            params,
            HttpMethod.GET,
            new Request.Callback(){
                public void onCompleted(Response response) {
                    ...
                }
            });
        Request.executeAndWait(request);

the result I'm getting is the following:
{Response:  responseCode: 500, graphObject: null, error: {HttpStatus: 500, errorCode: -1, errorType: Exception, errorMessage: Unsupported method, fql.multiquery}, isFromCache:false}

I can't figure out where my mistake is. It says unsupported method, multiquery, but this actually should be a valid method, right? I looked everywhere for a similiar problem but it seems that I'm alone with that issue.
I have the feeling that I'm missing something simple...
Would be cool if someone can help me out. Thanks!
btw. with normal queries everything works fine.

A: The linked Kanatorn page says method should be fql.multiquery, but you have just multiquery.

A: To solve this
have you read this developers page.
http://developers.facebook.com/docs/howtos/androidsdk/3.0/run-fql-queries/
Updated url
https://developers.facebook.com/docs/android/graph/#fql


text:
Q: android cordova-plugin-camera adds black background on PNG Tested on: Android 4.2 & Android 5.1.1
Plugin:    https://github.com/apache/cordova-plugin-camera
When we import a PNG with an alpha (transparent) layer from library it adds a black background automatically.
Do you know how to replace that black background to a white one in base64 string returned by the plugin?
Code used:
var options = {
                        quality: 95,
                        destinationType: Camera.DestinationType.DATA_URL,
                        sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                        allowEdit: true,
                        encodingType: Camera.EncodingType.PNG,
                        saveToPhotoAlbum: false
                    };

A: I found a way to do it reading Android Bitmap: Convert transparent pixels to a color
Then applied to our code you have to update CameraLauncher.java:
Add libs to edit:
import android.graphics.Canvas;
import android.graphics.Color;

Then add around line 595 (if you have added the two imports) this code taken and adapted from the other thread:
Bitmap imageWithBG = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),bitmap.getConfig());  // Create another image the same size
imageWithBG.eraseColor(Color.WHITE);  // set its background to white, or whatever color you want
Canvas canvas = new Canvas(imageWithBG);  // create a canvas to draw on the new image
canvas.drawBitmap(bitmap, 0f, 0f, null); // draw old image on the background
bitmap.recycle();  // clear out old image
bitmap = imageWithBG;

I made a pull request, maybe it will be integrated in next updates.


text:
Q: When i make my screen smaller my website formats doesnt fit i am making a website when i am om full screen the website looks good but when i am making the screen smaller the divs come out etc.
Here is a printscreen of it:

How do i fix this?
This is the HTML and CSS im using:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Jari Rengeling</title>
        <link rel="stylesheet" href="../CSS/StyleSheet.css" type="text/css">

                    Jari Rengeling

Home

Over mij

Ervaringen

Contact

Welkom

Mijn naam is Jari Rengeling, ik ben een beginnend Applicatieontwikkelaar. Neem gerust een kijkje op mijn eigen portfolio.

Navigatie

Home

Over mij

Ervaringen

Contact

Projecten

Geen huidge projecten...

Sociale Media

Contact

Klik hier om mijn contact gegevens te bekijken!

CSS
body
{
    margin: 0px;
    padding: 0px;
    background-color: rgba(154, 135, 100, 1.0);
    width: auto;
}

#menu
{
    width: 100%;
    height: 100px;
    z-index: 1;
    background-color: rgba(154, 135, 100, 0.80);
}

#nav1
{
    margin: 0px;
    text-align: right;
    margin-right: 400px;
}

.li1
{
    display: inline;
    padding-left: 2%;
    font-size: 19px;
    line-height: 100px;
    font-family: Champagne;
    color: white;
}

#wood
{
    position: absolute;
    z-index: -1;
    height: 800px;
    width: 100%;
}

#naam
{
    font-family: Champagne;
    font-size: 40px;
    color: white;
    line-height: 100px;
    margin: 0px;
    position: absolute;
    margin-left: 400px;
}

.space
{
    margin: 0px;
    color: white;
    padding-top: 20px;
    text-align: right;
    font-family: Caviar;
}

#headerp
{
    max-width: 480px;
    display: inline-block;
    font-size: 25px;
}

#headertext h1
{
    font-size: 50px;
}

#headertext
{
    float: right;
    margin-right: 400px;
    margin-top: 240px;
}

#footer
{
    background-color: rgba(154, 135, 100, 0.80);
    height: 210px;
    width: 100%;
    margin-top: 700px;
}

#h21
{
    font-family: Caviar;
    margin-left: 400px;
    color: white;
    border-bottom: 1px solid white;
    max-width: 230px;
    padding-top: 10px;
}

#project1
{
    border: 1px solid black;
    width: 100px;
    height: 100px;
    margin-left: 400px;
    background-color: rgba(128, 128, 128, 0.15);
    position: absolute;
    padding-top: 0px;
}

#project2
{
    border: 1px solid black;
    width: 100px;
    height: 100px;
    margin-left: 530px;
    background-color: rgba(128, 128, 128, 0.15);
    padding-top: 0px;
    position: absolute;
}

p
{
    font-family: Caviar;
    color: #ebebeb;
}

#projecten p
{
    margin-left: 400px;
    margin-top: 120px;
    position: absolute;
}

#projecten
{
    margin-left: 200px;
    margin-top: 0px;
    padding-top: 0px;
}

#navigatie
{
    margin-left: 400px;
    position: absolute;
}

.li2
{
    list-style-type: none;
}

#ul2
{
    position: absolute;
    margin: 0px;
    padding: 0px;
    padding-top: 10px;
    font-family: Caviar;
    color: #ebebeb;
}

#h22
{
    font-family: Caviar;
    color: white;
    padding-top: 10px;
    border-bottom: 1px solid white;
    margin: 0px;
}

a:hover
{
    color: black;
}

#h23
{
    font-family: Caviar;
    color: white;
    padding-top: 10px;
    border-bottom: 1px solid white;
    margin: 0px;
}

#socialmedia
{
    position: relative;
    margin-left: 900px;
    top: -56px;
    padding: 0px;
    max-width: 214px;
}

.miniaturen
{
    padding-right: 5px;
    padding-top: 20px;
}

#contact
{
    position: absolute;
    margin-left: 1200px;
    top: 802px;
    padding: 0px;
    max-width: 100px;
}

#h24
{
    font-family: Caviar;
    color: white;
    padding-top: 10px;
    border-bottom: 1px solid white;
    margin: 0px;
}

a
{
    text-decoration: none;
    color: white;
    font-family: Champagne;
}

A: There is a rule in css known as @media rule.
@media is used for creating responsive webpage.
example of @media rule :
 <!DOCTYPE html>

Resize the browser window to see the effect!

The media query will only apply if the media type is screen and the viewport is 480px wide or wider.

A: Seeing your CSS code, I noticed you are almost always using pixels as a measure. You shouldn't do that unless you know exactly the size of the screen were your website will be open. Otherwise, using percentages is always a good thing. You can control the style like with pixels and when you resize, since everything has it's size according their parent elements, everything will resize.
I changed a bit of your CSS and HTML code for you to see it. It's not perfect but you can understand the power of using percentages instead of pixels (:
http://jsbin.com/tacayaweya/edit?html,css,output
You could use @media queries (just like it was said here) to control the style your website based on the screen size. The example of @Advaith is a good example of how to use it.
As also mentioned in the comments, using frameworks like Bootstrap can help you with the design of your website.


text:
Q: Can I make an activity to Bitmap? I want to make Bitmap data from activity's output. Activity contains a fragment, and I can't modify it.
I don't want to activity to real screen and just want to make bitmap data. How can I do it.

A: I assume you want something like a screenshot of your activity.
In order to get the root view of your activity (what you're currently seeing), do this:
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheEnabled(false);

and then you'll have a Bitmap of your activity, referenced by the bitmap variable.
Do what you want with that Bitmap, like saving it to a file.

A: If you wan to capture the Activity's View hierarchy to a Bitmap, try this:
View view = findViewById(android.R.id.content);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);


text:
Q: Python2.6 XML reading I want to migrate my system from Active Python 2.4 to Python 2.6.5. However I face some problem in parsing XML files. The I/O is very slow.
My sample xml file
<config><dicts><dictName>EnvDict</dictName><dictElems><key>AppServerIP</key>  <value>localhost</value><key>DBServerIP</key>   <value>localhost</value><key>DBServerName</key> <value>DB1</value></dictElems></dicts></config>

My log shows this xml parsing took 25s.
My system is structure as below
Publisher-Subr is used to redirect request to different modules
ClntMgrFact is attached to PubSubr and listen to pre-defined ports. It will spawn a new process for login from client.
ClntMgr(process) is spawned by ClntMgrFact and also attached to PubSubr.
ClntMgr will generate a ClntWorker(thread) to process workflow.
ClntWorker need to read some static XML file from local. But the parsing is extremely slow. My XML file is around 500 - 700k.
Any one can help on this without changing the system structure? Thanks in advance.

A: I'm very perplexed...:
$ py26 -mtimeit -s'import rex' 'rex.t()'
10000 loops, best of 3: 103 usec per loop

100 microseconds seems more reasonable than 25 seconds to read in, and parse, such a small XML file as you're giving (even on the old laptop I'm using for the timing!) -- but how to explain the fact that my parsing is being 250,000 times faster than yours?!
This is rex.py, btw...:
import xml.etree.cElementTree as et

def t(fn='static.xml'):
  return et.parse(fn)

and static.xml is the file where I wrote your XML example (223 characters).
So what's your platform, OS, Python version, chosen XML parser, etc...?  I'm on a macbook pro laptop, OSX 10.5.8, 2.4 GHz Intel Core Duo, 667 MHz DDR2 RAM -- as I said, a pretty old machine indeed! -- with Python 2.6.4 straight from python.org.


text:
Q: SVG Elements not in view on page load do not display I have an SVG image (with code generated by Adobe Illustrator CS6) embedded in a web page. I've isolated the SVG code in this jsFiddle (it is also embedded below).
In Chrome (but not Firefox), when the bottom part of the SVG isn't in view, it doesn't render. Shrink the window and scroll to the top of the HTML section on the jsFiddle and then reload to see what I'm talking about. Once you click the section, it appears.
What can I do to fix this?
Edit: WebKit bug filed, as it appears to be a WebKit bug. View bug report
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" x="0px" y="0px" width="690px" height="420px" viewBox="0 43 690 420" enable-background="new 0 43 690 420" xml:space="preserve">
<defs></defs>
<filter id="fullblur" x="0" y="0">
    <feGaussianBlur in="SourceGraphic" stdDeviation="2" />
</filter>

<filter id="halfblur" x="0" y="0">
    <feGaussianBlur in="SourceGraphic" stdDeviation="1" />
</filter>

<filter id="noblur" x="0" y="0">
    <feGaussianBlur in="SourceGraphic" stdDeviation="0" />
</filter>

<!-- BACKGROUND (hidden) -->
<rect y="43" display="none" fill="#D1DBBB" width="690" height="420"/>

<!-- STAGE -->
<ellipse fill="#CC3333" stroke="#000000" cx="339.5" cy="43" rx="169.5" ry="42.5"/>

<!-- SEATS -->
<g>

    <!-- STUDENT SECTIONS -->
    <g id="studhover">
        <g filter="url(#halfblur)" id="studchart" class="chartsection">

        <g id="s1">
                <path class="sFill" fill="#FECB2F" d="M90.75,136c0,2.761,2.239,5,5,5h150c2.761,0,5-2.239,5-5V90.5c0-2.761-2.239-5-5-5h-150
            c-2.761,0-5,2.239-5,5V136z"/>
        <path class="sStroke" fill="none" stroke="#000000" d="M90.75,136c0,2.761,2.239,5,5,5h150c2.761,0,5-2.239,5-5V90.5c0-2.761-2.239-5-5-5h-150
            c-2.761,0-5,2.239-5,5V136z"/>
    </g>

            <g id="s2">
            <path class="sFill" fill="#FECB2F" d="M265.75,150c0,2.761,2.239,5,5,5h150c2.762,0,5-2.239,5-5v-45.5c0-2.761-2.238-5-5-5h-150
        c-2.761,0-5,2.239-5,5V150z"/>
            <path class="sStroke" fill="none" stroke="#000000" d="M265.75,150c0,2.761,2.239,5,5,5h150c2.762,0,5-2.239,5-5v-45.5c0-2.761-2.238-5-5-5h-150
        c-2.761,0-5,2.239-5,5V150z"/>
        </g>

            <g id="s3">
            <path class="sFill" fill="#FECB2F" d="M439.25,136c0,2.761,2.238,5,5,5h150c2.762,0,5-2.239,5-5V90.5c0-2.761-2.238-5-5-5h-150c-2.762,0-5,2.239-5,5V136z"/>
            <path class="sStroke" fill="none" stroke="#000000" d="M439.25,136c0,2.761,2.238,5,5,5h150c2.762,0,5-2.239,5-5V90.5c0-2.761-2.238-5-5-5h-150
            c-2.762,0-5,2.239-5,5V136z"/>
        </g>

            <g id="s4">
            <path class="sFill" fill="#FECB2F" d="M90.75,205.5c0,2.761,2.239,5,5,5h150c2.761,0,5-2.239,5-5V160c0-2.761-2.239-5-5-5h-150
            c-2.761,0-5,2.239-5,5V205.5z"/>
            <path class="sStroke" fill="none" stroke="#000000" d="M90.75,205.5c0,2.761,2.239,5,5,5h150c2.761,0,5-2.239,5-5V160c0-2.761-2.239-5-5-5h-150
            c-2.761,0-5,2.239-5,5V205.5z"/>
            </g>

            <g id="s5">
            <path class="sFill" fill="#FECB2F" d="M265.75,218c0,2.761,2.239,5,5,5h150c2.762,0,5-2.239,5-5v-45.5c0-2.761-2.238-5-5-5h-150
        c-2.761,0-5,2.239-5,5V218z"/>
            <path class="sStroke" fill="none" stroke="#000000" d="M265.75,218c0,2.761,2.239,5,5,5h150c2.762,0,5-2.239,5-5v-45.5c0-2.761-2.238-5-5-5h-150
        c-2.761,0-5,2.239-5,5V218z"/>
        </g>

            <g id="s6">
            <path class="sFill" fill="#FECB2F" d="M439.25,205.5c0,2.761,2.238,5,5,5h150c2.762,0,5-2.239,5-5V160c0-2.761-2.238-5-5-5h-150
        c-2.762,0-5,2.239-5,5V205.5z"/>
            <path class="sStroke" fill="none" stroke="#000000" d="M439.25,205.5c0,2.761,2.238,5,5,5h150c2.762,0,5-2.239,5-5V160c0-2.761-2.238-5-5-5h-150
        c-2.762,0-5,2.239-5,5V205.5z"/>
        </g>

        </g>

        <!-- Filling in the gaps -->
        <g>
            <rect x="251" y="84" fill="transparent" width="15" height="140" id="sVertLine1" />
            <rect x="425" y="84" fill="transparent" width="15" height="140" id="sVertLine2" />

            <rect x="266" y="84" fill="transparent" width="159" height="15" id="sHorizLine1" />
            <rect x="90" y="140" fill="transparent" width="161" height="15" id="sHorizLine2a" />
            <rect x="440" y="140" fill="transparent" width="161" height="15" id="sHorizLine2b" />
            <rect x="266" y="153" fill="transparent" width="161" height="15" id="sHorizLine3" />
            <rect x="90" y="210" fill="transparent" width="161" height="12" id="sHorizLine4a" />
            <rect x="440" y="210" fill="transparent" width="161" height="12" id="sHorizLine4b" />
        </g>

    </g>

    <!-- GUEST SECTIONS -->
    <g id="guesthover">
        <g filter="url(#halfblur)" id="guestchart" class="chartsection">
            <g>
        <path class="gFill" fill="#3333CC" d="M91.5,273c0,2.762,2.239,5,5,5h150c2.761,0,5-2.238,5-5v-45.5c0-2.761-2.239-5-5-5h-150
            c-2.761,0-5,2.239-5,5V273z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M91.5,273c0,2.762,2.239,5,5,5h150c2.761,0,5-2.238,5-5v-45.5c0-2.761-2.239-5-5-5h-150
            c-2.761,0-5,2.239-5,5V273z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M440,273c0,2.762,2.238,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.761-2.238-5-5-5H445c-2.762,0-5,2.239-5,5
            V273z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M440,273c0,2.762,2.238,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.761-2.238-5-5-5H445
            c-2.762,0-5,2.239-5,5V273z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M91.5,342.5c0,2.762,2.239,5,5,5h150c2.761,0,5-2.238,5-5V297c0-2.762-2.239-5-5-5h-150
            c-2.761,0-5,2.238-5,5V342.5z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M91.5,342.5c0,2.762,2.239,5,5,5h150c2.761,0,5-2.238,5-5V297c0-2.762-2.239-5-5-5h-150
            c-2.761,0-5,2.238-5,5V342.5z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M440,342.5c0,2.762,2.238,5,5,5h150c2.762,0,5-2.238,5-5V297c0-2.762-2.238-5-5-5H445c-2.762,0-5,2.238-5,5
            V342.5z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M440,342.5c0,2.762,2.238,5,5,5h150c2.762,0,5-2.238,5-5V297c0-2.762-2.238-5-5-5H445
            c-2.762,0-5,2.238-5,5V342.5z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M266.5,287c0,2.762,2.239,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.761-2.238-5-5-5h-150
            c-2.761,0-5,2.239-5,5V287z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M266.5,287c0,2.762,2.239,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.761-2.238-5-5-5h-150
            c-2.761,0-5,2.239-5,5V287z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M266.5,355c0,2.762,2.239,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.762-2.238-5-5-5h-150
            c-2.761,0-5,2.238-5,5V355z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M266.5,355c0,2.762,2.239,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.762-2.238-5-5-5h-150
            c-2.761,0-5,2.238-5,5V355z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M91.5,410.5c0,2.762,2.239,5,5,5h150c2.761,0,5-2.238,5-5V365c0-2.762-2.239-5-5-5h-150
            c-2.761,0-5,2.238-5,5V410.5z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M91.5,410.5c0,2.762,2.239,5,5,5h150c2.761,0,5-2.238,5-5V365c0-2.762-2.239-5-5-5h-150
            c-2.761,0-5,2.238-5,5V410.5z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M440,410.5c0,2.762,2.238,5,5,5h150c2.762,0,5-2.238,5-5V365c0-2.762-2.238-5-5-5H445c-2.762,0-5,2.238-5,5
            V410.5z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M440,410.5c0,2.762,2.238,5,5,5h150c2.762,0,5-2.238,5-5V365c0-2.762-2.238-5-5-5H445
            c-2.762,0-5,2.238-5,5V410.5z"/>
    </g>
            <g>
        <path class="gFill" fill="#3333CC" d="M266.5,423c0,2.762,2.239,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.762-2.238-5-5-5h-150
            c-2.761,0-5,2.238-5,5V423z"/>
        <path class="gStroke" fill="none" stroke="#000000" d="M266.5,423c0,2.762,2.239,5,5,5h150c2.762,0,5-2.238,5-5v-45.5c0-2.762-2.238-5-5-5h-150
            c-2.761,0-5,2.238-5,5V423z"/>
    </g>
        </g>

        <!-- Filling in the gaps -->
        <g>
            <rect x="251" y="224" fill="transparent" width="15" height="206" id="gVertLine1" />
            <rect x="425" y="224" fill="transparent" width="15" height="206" id="gVertLine2" />

            <rect x="266" y="222" fill="transparent" width="159" height="15" id="gHorizLine1" />
            <rect x="90" y="278" fill="transparent" width="161" height="15" id="gHorizLine2a" />
            <rect x="440" y="278" fill="transparent" width="161" height="15" id="gHorizLine2b" />
            <rect x="266" y="291" fill="transparent" width="161" height="15" id="gHorizLine3" />
            <rect x="90" y="348" fill="transparent" width="161" height="15" id="gHorizLine4a" />
            <rect x="440" y="348" fill="transparent" width="161" height="15" id="gHorizLine4b" />
            <rect x="266" y="360" fill="transparent" width="161" height="15" id="gHorizLine5" />
            <rect x="90" y="417" fill="transparent" width="161" height="13" id="gHorizLine4a" />
            <rect x="440" y="417" fill="transparent" width="161" height="13" id="gHorizLine4b" />
        </g>

    </g>
</g>
</svg>

A: This is a Webkit bug caused by the use of filters. I removed the <filter> sections and the flter="url(...)" tags to stop the filters from running and it now works.


text:
Q: Encriptar datos enviados por url Estoy enviando un id por url a la pagina index.php que carga ciertos datos respectivamente del id que obtuvo a traves una variables de sesion, el detalle es que si el usuario 1 con id 1 cambia el id 1 por id 2 en la url consultaria datos que no le corresponden, por eso quiero encriptar un poco el id que se muestra en la url.
function(){
        var id_e=document.getElementById('input').value;
        window.location.href='http://localhost/index.php?id_e='+id_e;
        return;

    }

A: Por lo que entiendo, quieres impedir que un usuario, manipulando la url (cuyo parámetro es un id numérico) pueda ver datos de otro usuario.
Si el id_e se genera en el backend
En el código que nos mostraste no queda claro de donde proviene el parámetro id_e, pero suponiendo que está generado en el backend, y se pasa al browser en tiempo de ejecución (derechamente con PHP o por ajax), entonces hay dos flujos posibles.
En un flujo, el más tradicional, tienes una tabla de tokens, en la cual existe el campo id_e y el campo hash. En vez de pasarle directamente el id_e al browser, le pasas el hash.
function(){
    var hash=document.getElementById('input').value;
    window.location.href='http://localhost/index.php?hash='+hash;
    return;
}

El usuario eventualmente visitará una url que en vez de un id numérico tiene un hash, y cuando recibes la petición a index.php, realizas una búsqueda en tu tabla de tokens para ver a qué id_e corresponde el hash que te mandaron.
<?php

  $hash = $_GET['hash'];
  $id_e = buscar_en_tabla_de_tokens($hash);

La generación del hash se puede hacer de muchas maneras. En el fondo es un string alfanumérico al azar que podría componerse, por ejemplo, del resultado de hashear el id:
$hash = password_hash($id_e, PASSWORD_DEFAULT);

Lo importante es que sólo el lado del servidor sepa con qué algoritmo estás encriptando y qué le pasas a ese algoritmo.
Hay una segunda manera que son los json Web Tokens, que no requiere utilizar una tabla de tokens, sino que ocurre entre el browser y el código del backend. Sin embargo, esa manera requiere que envíes una petición con headers y payload, lo cual no vas a poder hacer usando  window.location.href
Significa que en el mejor de los casos, tendrás que crear tu tabla de tokens y añadir la lógica para consultar esa tabla para saber el id_e
Si el id_e se genera en el browser
Si el id_e se genera enteramente del lado del cliente, cualquier encriptación que le pongas va a poder revertirse simplemente mirando el código js del frontend. En ese caso no hay mucho que hacer salvo oscurecer un poco el ID, por ejemplo usando base64.
function(){
    var id_e=document.getElementById('input').value;
    id_e = window.btoa(id_e);
    window.location.href='http://localhost/index.php?id_e='+id_e;
    return;
}

y luego en index.php
<?php
  $id_e = base64decode($_GET['id']);

Pero repito, eso no es seguridad sino simplemente oscurecimiento. Cualquiera que vea tu código js sabrá cómo generar el id_e de otros valores numéricos.

A: Yo tengo la misma duda uso el function asi
function mostrarnoticia (id){
    window.location.href='noticiacompleta.php?noticias='+id;
}

Y el id lo capturo de un href de una tabla de esta manera
<a href="" data-toggle="modal"  data-target="#myModal" id="<?php echo $row['noticias_id']; ?>" >

Entonces mi url sale

http://localhost/musica/noticiacompleta.php?noticias=2


text:
Q: Не могу передать изображения на сервер Есть несколько полей такого типа <input type="file" name="file1">в которых я выбираю изображения. Мне нужно с помощью ajax залить их на imgur, а ссылку вернуть в ответе. Проблема в том, что не знаю как правильно передать изображения в $_FILES['img'].
JS
$.each($("[name=file"+i+"]"), function(i, obj){
            $.each(obj.files,function(i,file){
                $.ajax({
                    url: 'imgur.php',
                    data: file,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(data){
                        if(data != '') {
                            arr.push(data); // записываю ответ в массив
                        }
                    }
                })

PHP
<?php
    if (isset($_FILES['img'])) {
        $file = $_FILES['img'];
        if ($file['name'] != '') {
            $filename = $file['tmp_name'];
            $client_id = "***************";
            $handle = fopen($filename, "r");
            $data = fread($handle, filesize($filename));
            $pvars   = array('image' => base64_encode($data));
            $timeout = 30;
            $curl    = curl_init();
            curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
            $out = curl_exec($curl);
            curl_close ($curl);
            $pms = json_decode($out,true);
            $url=$pms['data']['link'];
            if ($url!="") {
                $url = str_replace('http://', 'https://', $url );
                $imgname = preg_replace('/\.[^.]+$/','',$file['name']);
                echo $url;
            }
        }
    }
?>

A: Сделай через Guzzle, вот пример

https://stackoverflow.com/questions/38133244/upload-file-using-guzzle-6-to-api-endpoint

A: Сделайте так:
   <form id="upload">
   <input type="file" name="file">
   <button type="submit">Upload</button>
   </form>

<script>
$( document ).ready(function() {
    $("#upload").submit(function(e){
        e.preventDefault();
        var form=($(this)[0]);
        var formdata=new FormData(form);
        $.ajax({
                    url:'url.php',//обработчик
                    type:'POST',
                    data:formdata,
                    enctype:'multipart/form-data',
                    processData:false,
                    contentType:false,
                    success:function(data){
                    //в случае успешной загрузки
                    },

                    error: function (data) {
                    //в случае ошибки
                    }
        });
    });
    });
</script>

В обработчике проверяться с помощью $_POST['file']


text:
Q: What is the simplest way to implement "weakness table" (usually in game)? For example, I have a game with some characters have 5 elements:fire,water,wood,light,dark.
the element has weakness which attack power will increase for some elements:
fire>wood
water>fire
wood>water
light>dark
dark>light
eg:
fire hit wood,the power is *2
fire hit water,the power is *0.5
I have a function to get the relation between element and factor:
float getFactor(string me,string enemy){
    if(me=="fire"){
        if(enemy=="fire"){
            return 1;
        }else if(enemy=="water"){
            return 0.5;
        }else if(enemy=="wood"){
            return 2;
        }else if(enemy=="light"){
            return 1;
        }else{
        return 1;
        }
    }else if(me=="water"){
        if(enemy=="fire"){
            return 2;
        }else if(enemy=="water"){
            return 1;
        }else if(enemy=="wood"){
            return 0.5;
        }else if(enemy=="light"){
            return 1;
        }else{
            return 1;
        }
    }else if(me=="wood"){
        if(enemy=="fire"){
            return 0.5;
        }else if(enemy=="water"){
            return 2;
        }else if(enemy=="wood"){
            return 1;
        }else if(enemy=="light"){
            return 1;
        }else{
            return 1;
        }
    }else if(me=="light"){
        if(enemy=="fire"){
            return 1;
        }else if(enemy=="water"){
            return 1;
        }else if(enemy=="wood"){
            return 1;
        }else if(enemy=="light"){
            return 1;
        }else{
            return 2;
        }
    }else{
        if(enemy=="fire"){
            return 1;
        }else if(enemy=="water"){
            return 1;
        }else if(enemy=="wood"){
            return 1;
        }else if(enemy=="light"){
            return 2;
        }else{
            return 1;
        }
    }
}

which getFactor("fire","water") will return 0.5;
this function works, but it has too much lines and too much if else statement,also it seems very hard to maintain if I add a new element to it.
is there any method to implement the table but in more maintainable code style and less line of codes?

A: If you want a table, use a table:
enum Elements { ELEM_FIRE, ELEM_WATER, ELEM_WOOD, ELEM_LIGHT, ELEM_DARK, NUM_ELEM };

float attack_factor[NUM_ELEM][NUM_ELEM] = {
    {1, .5f, 2, 1, 1}, // fire vs ...
    {2, 1, .5f, 1, 1}, // water vs ...
    ...
};

Now you just do
attack_factor[my_elem][enemy_elem]

to get the attack power. This approach requires that you store the element type as an enum value instead of as a string, but that's better coding style anyway for C++ since it limits the space of possible elements to the ones that are actually defined, and makes lots of functions really easy.
Another example of tables being useful:
const char *element_names[] = { "fire", "water", "wood", "light", "dark" };

A: In your development environment, can you use the STD?
If so, then perhaps a map may best suit you. http://www.cplusplus.com/reference/map/map/.
You can set as the map input a pair of elements (an enumerated int), and the attack factor as the output. You only need to define an output for the possible combinations.


text:
Q: How to let Rails tell mobile applications that users signed in or not? I'm developing a Rails application that use devise as the authentication solution. For web applications, users enter username and password in a form, Rails can render different pages after users signed in.
Now I'd like to use this framework to support mobile app. In this case, the mobile app needs to know whether the user enters correct username and password.
How should devise response to the mobile application, response headers or JSON inside body? Does devise support it?

A: More tutorials:
http://blog.joshsoftware.com/2011/12/23/designing-rails-api-using-rabl-and-devise/
http://www.strukturedkaos.com/2011/09/19/soup-to-nuts-token-authentication-for-android-using-rails-3-devise/
Make sure to enable/uncomment the following line in devise configuration:
config.token_authentication_key = :auth_token

A: You need token authentication. Mobile client should have a login form and access the REST API for authentication. If authentication was successful, you will get a token which you need to send with all the subsequent requests in the same session.
http://zyphdesignco.com/blog/simple-auth-token-example-with-devise
http://matteomelani.wordpress.com/2011/10/17/authentication-for-mobile-devices/


text:
Q: Jquery datepcker I am using this code to disable today if time is past 2 pm. It works but I sometimes disable dates along the way. And currently, if tomorrow is disabled it enables it and makes it available. I don't want that to be the case. It should skip the already disabled dates until it finds an enabled date.
FIDDLE
My code so far:
jQuery(document).ready(function($) {
    $(".wccpf-datepicker-delivery_date" ).datepicker({
    minDate: +0,
    beforeShow : function(){
        var dateTime = new Date();
        var hour = dateTime.getHours();
        if(hour  >= 14){
            $(this).datepicker( "option", "minDate", "+1" );
        }
    }
});

Any Ideas?


text:
Q: officeHome doesn't exist or is not a directory I've installed document-viewer on Plone.
When I upoad a document I receive this error:
Exception in thread "main" java.lang.IllegalStateException: officeHome doesn't exist or is not a directory:
    at org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration.buildOfficeManager(DefaultOfficeManagerConfiguration.java:165)
    at org.artofsolving.jodconverter.cli.Convert.main(Convert.java:111)

My openoffice installation is in /opt/openoffice4
I'm using docsplit v 0.6.4
how can I solve this?

A: As I've read on JODConverter configuration here,
"/opt/openoffice.org3"
"/opt/libreoffice"
"/usr/lib/openoffice"
"/usr/lib/libreoffice"

so, I've created a symbolic link:
ln -s <path OpenOffice installation> <path required>

solved.


text:
Q: If $E,F$ are measurable is it true that $m(E\cap (F+t))$ is a continuous function in $t$. So I know that $t\mapsto m(E\cap (-\infty,t])$ is a continuous function if $E$ is measurable as $\bigcap(-\infty,t_n] = (-\infty,t]$ if $t_n\downarrow t$, but I'm wondering if $t\mapsto m(E\cap (F+t))$ is continuous.

A: I think that you can firstly assume that $F$ is contained in compact set, and $F$ can not contained in an interval $I$, Then we have $$(t_2+F)\Delta(t_1+F)\subset (t_2+I)\Delta(t_1+I)$$
It implies that
$$m((t_2+F)\Delta(t_1+F))\leq m((t_2+I)\Delta(t_1+I))$$
which implies that your function is continuous.
For general case. we first prove that $m(F\cap K^c)$ under the assumption that $m(F)< \infty$. And then we argue it on $F\cap K$. Here $K$ is a compact set you choose.


text:
Q: Why it previews blank page after added CSS? When I add css style in to my code at printWindow.document.write, the preview will show the blank page. So I remove css out, then my content is appeared. I don't know how to fix this problem. So, if anyone know please tell me that solution. Thanks :)

form, div, table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

th, td {
    padding: 5px;
    text-align: left;
}
table#t01 {
    width: 80%;
    background-color: #f1f1c1;
}
table#t02 {
    width: 80%;
    background-color: #d35400;
}
#btnPrint {
  width: 84px;
  height: 45px;
  background: white;
  border: none;
  color: black;
  font-size:14px;
  font-weight:700;
  display: block;
  margin: auto;
}

.table-content {
  width:50%;
}

.table-content th {
  padding:5px 20px;
  background: #F0F0F0;
  vertical-align:middle;
}

.table-content td {
  padding:5px 20px;
  vertical-align:middle;
}

Mypage

    My page

    Start date
    End date
    Unit
    Multiplier
    Total

    <?php echo $post_at; ?>
    <?php echo $post_at_to_date; ?>
    <?php echo round($sum, 2); ?>
    <?php echo $_POST["name"]; ?>
    <?php echo round($Total, 2); ?>

</form>

</form>

    <input type="button" value="Print bill" id="btnPrint">

A: Your JavaScript code must be triggered in order to run.
This is typically done in the following manner:
$('document').ready(function(){
    $("#btnPrint").live("click", function(){
        ...
    });
});

A: OK, I can solve the problem now. This is the solution.
Just edit my js.

$("#btnPrint").live("click", function () {
            var divContents = $("#dvContainer").html();
            var printWindow = window.open('', '', 'height=500,width=1000');
            printWindow.document.write('');
            printWindow.document.write('<link rel="stylesheet" type="text/css" href="./src/style/print.css">');
            printWindow.document.write('');
            printWindow.document.write('<title>Electricity Bill    Floor 1: Room 2</title>');
            printWindow.document.write('');
            printWindow.document.write('');
            printWindow.document.write(divContents);
            printWindow.document.write('');
            printWindow.document.write('');
            printWindow.document.close();
            setTimeout(function () {
              printWindow.print();
            }, 500);
        });

A: You have to wait for the sheet to be loaded
....
var string = '<link rel="stylesheet" href="print.css">'
    + divContents +'';
var printWindow = window.open('', '', 'height=500,width=1000');
    printWindow.document.write(string);
window.setTimeout(function() {
  printWindow.print();
  printWindow.close();
}, 3);
 ...


text:
Q: How to perform a calculation with conditionals in pandas? I am trying to write a conditional where I want to get the average cost per visit in a new column. However, if the visit count is 0, then I want to use '1' instead so that the Visit_cost is not infinity.
My approach is throwing an error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

df
id    Cost          Visit
2     52            1
3     85            0
4     853           10

df['VISIT_COST'] = [df['Cost']/df['Visit'] if df['Visit'] != 0 else df['Cost']/1]

final df:
id    Cost          Visit    VISIT_COST
2     52            1        52
3     85            0        85
4     853           10       85.3

A: I think best here is use numpy.where, because very fast:
df['VISIT_COST'] = np.where(df['Visit'] != 0, df['Cost']/df['Visit'], df['Cost'])
print (df)
   id  Cost  Visit  VISIT_COST
0   2    52      1        52.0
1   3    85      0        85.0
2   4   853     10        85.3

Out of box solution - for replace 0 to 1 add boolean mask converted to integer:
df['VISIT_COST'] = df['Cost'].div(df['Visit'].eq(0).astype(int).add(df['Visit']))
print (df)
   id  Cost  Visit  VISIT_COST
0   2    52      1        52.0
1   3    85      0        85.0
2   4   853     10        85.3

Detail:
print (df['Visit'].eq(0).astype(int))
0    0
1    1
2    0
Name: Visit, dtype: int32

print (df['Visit'].eq(0).astype(int).add(df['Visit']))
0     1
1     1
2    10
Name: Visit, dtype: int64

A: I think we should using mask
#df['VISIT_COST'] = np.where(df['Visit'] != 0,df['Cost']/df['Visit'] , df['Cost']/1)

df['VISIT_COST']=df.Cost.mask(df['Visit'] != 0,df['Cost']/df['Visit'])


text:
Q: Django view templates filter database Whats is the best approach to filter context. I want to view on my index page last three objects from Roslina and related to them all Images with the same nazwa_polska(foreign_key)
my model.py
**class Roslina(models.Model):
    id_rosliny = models.AutoField(primary_key=True)
    nazwa_polska = models.CharField(max_length=256)
    nazwa_lacinska = models.CharField(max_length=256)
    opis = models.TextField()
    data = models.DateField()
    def __str__(self):
        return self.nazwa_polska
class Images(models.Model):
    nazwa_polska = models.ForeignKey(Roslina, related_name='image', on_delete=models.CASCADE)
    image = models.ImageField(max_length=255, upload_to=generate_filename);
    def __str__(self):
        return self.nazwa_polska.nazwa_polska**

views.py
from django.shortcuts import render
from django.views.generic import ListView,TemplateView
from . import models
# Create your views here.
class IndexView(TemplateView):
    template_name='index.html'
    def get_context_data(self, **kwargs):
         context = super(IndexView, self).get_context_data(**kwargs)
         context['zdjecia'] = models.Images.objects.all()
         context['rosliny'] = models.Roslina.objects.all()
         return context
class WyborAtlasu(TemplateView):
    template_name='basic_app/wyborAtlasu.html'

A:
I want to view on my index page last three objects from Roslina

"last" according to which criteria ? But anyway, the solution is to sort your queryset on the desired field(s) - using a descendant sort to get the "last" records first (reverse sort) - then slice it to get the first three records. This is better done in the view itself.
def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    last_rosliny =  models.Roslina.objects.order_by("-date")[:3]
    context['rosliny'] = last_rosliny
    # you don't need this one, cf below
    # context['zdjecia'] = models.Images.objects.all()
    return context

and related to them all Images with the same nazwa_polska(foreign_key)

Given your models definition, you can get a Roslina's related images through it's "image" related descriptor (in your case it is named "image" because you explicitely named it so: models.ForeignKey(Roslina, related_name='image'...) - images would have been a better name but anyway), ie:
r = Roslina.objects.get(id_rosliny=<id_of_a_rosliny_here>)
for image in r.image.all():
    print(image.pk, image.image)

Now since Django template language allow for attribute lookup and method calls (for methods that don't take any parameter at least) you don't need to add images to your view's context, you can access them from the Roslina directly in the template:
# yourtemplate.html

  {% for roslina in rosliny %}

    {{ roslina.nazwa_polska }}

      {% for image in roslina.image.all %}

{{ image.pk }} - {{ image.image.url }}

      {% endfor %}

  {% endfor %}

PS : hope I got the singular / plural forms right, sorry but I'm afraid I don't speak your language ;)


text:
Q: Easy Admin panel with Rails I have created a web page with RoR and i am using auth system that i wrote. Now i would like to create an admin panel, where i can see the user info etc..
I am not sure but what i though is to add a column name to auth system like admin? giving a default name false. Then if the admin? is true admin panel opens instead of the web page login.
I wonder if i can use the same auth system so in order to login to page it logs in to admin panel.
But in the controller it will check if admin? is true for every user, i am not sure about the burden in terms of the system requirments as it will check every user.
And i know there are other gems for admin panel but its fine i can design it. I am just not sure which way is the efficient way.

A: The burden on the system will be negligible. It depends a little bit upon how your auth system is configured, but I am assuming that you give the user a token when he/she is properly logged in.
When the user first tries to sign in, you should check if they are an admin. At this point, if they are, then you can sign them in as an admin, also storing that information in the session. You should perform this check on the controller actions where they need to be an admin. It will not affect performance to any noticeable degree and is important for the security of your site.
Also, you may want to check out the CanCanCan gem, which is a fork of CanCan built by Ryan Bates, for an example of how this works. Unless you're building the application for educational purposes, I highly recommend the CanCanCan gem.
Hope this helps!

A: In addition to that, you may try Rails_Admin, which provides an easy-to-use interface for managing your data.
And I've considered to use this gem for my project, which is a huge database, so it seems to very helpful.


text:
Q: Error to call a rest web service on spring : HTTP Status 406 I new with spring framework and I'm trying to do a web service with rest over spring, then I've the following controller that return a  List of Customer object.
@RestController
@RequestMapping(RestURIConstants.SERVICES_ROUTE + "customer")
public class CustomerService
{
    @RequestMapping(value="/getCustomers",method = RequestMethod.GET)
    @ResponseBody
    public  ResponseEntity<List<Customer>> getCustomers()
    {
        System.out.println("calling get customers service");
        JpaGenericController<Customer> customerDao = new JpaGenericController<Customer>( Customer.class );
        List<Customer> customers = customerDao.findAll();
        return new ResponseEntity<List<Customer>>(customers,HttpStatus.OK);
    }
}

My class Customer is the following:
@Entity
@Table(name = "Customer")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c"),
    @NamedQuery(name = "Customer.findByCode", query = "SELECT c FROM Customer c WHERE c.code = :code"),
    @NamedQuery(name = "Customer.findByName", query = "SELECT c FROM Customer c WHERE c.name = :name"),
    @NamedQuery(name = "Customer.findByAddress", query = "SELECT c FROM Customer c WHERE c.address = :address"),
    @NamedQuery(name = "Customer.findByPhoneOne", query = "SELECT c FROM Customer c WHERE c.phoneOne = :phoneOne"),
    @NamedQuery(name = "Customer.findByPhoneTwo", query = "SELECT c FROM Customer c WHERE c.phoneTwo = :phoneTwo"),
    @NamedQuery(name = "Customer.findByCreditLimit", query = "SELECT c FROM Customer c WHERE c.creditLimit = :creditLimit"),
    @NamedQuery(name = "Customer.findByCurrentCredit", query = "SELECT c FROM Customer c WHERE c.currentCredit = :currentCredit")})

public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "code")
    private String code;
    @Size(max = 255)
    @Column(name = "name")
    private String name;
    @Size(max = 45)
    @Column(name = "address")
    private String address;
    @Size(max = 45)
    @Column(name = "phoneOne")
    private String phoneOne;
    @Size(max = 45)
    @Column(name = "phoneTwo")
    private String phoneTwo;
    @Column(name = "creditLimit")
    private Short creditLimit;
    @Column(name = "currentCredit")
    private Short currentCredit;

    public Customer() {
    }

    public Customer(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhoneOne() {
        return phoneOne;
    }

    public void setPhoneOne(String phoneOne) {
        this.phoneOne = phoneOne;
    }

    public String getPhoneTwo() {
        return phoneTwo;
    }

    public void setPhoneTwo(String phoneTwo) {
        this.phoneTwo = phoneTwo;
    }

    public Short getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(Short creditLimit) {
        this.creditLimit = creditLimit;
    }

    public Short getCurrentCredit() {
        return currentCredit;
    }

    public void setCurrentCredit(Short currentCredit) {
        this.currentCredit = currentCredit;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (code != null ? code.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Customer)) {
            return false;
        }
        Customer other = (Customer) object;
        if ((this.code == null && other.code != null) || (this.code != null && !this.code.equals(other.code))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.dev.model.Customer[ code=" + code + " ]";
    }

}

I used jackson mapper
<!-- JACKSON Mapper-->
<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
</dependency>

But when I try to acces to the web services I get the following mistake:
HTTP Status 406 -

type Status report

message

description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

So, what am I doing wrong?
I need to setup something in the applicationContext?
Aplication Context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <!--Scan all application except the controllers  -->
    <context:component-scan base-package="com.gteam.dev" >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <bean id="jdbcPropertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="classpath:project.properties"/>

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}"/>

    <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="persistenceXmlLocations">
            <list>
                <value>classpath*:META-INF/persistence.xml</value>
            </list>
        </property>
        <property name="defaultDataSource" ref="dataSource"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitManager" ref="persistenceUnitManager"/>
        <property name="persistenceUnitName" value="entityManager"/>
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider">
            </bean>
        </property>
    </bean>

     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

UPDATE
I try to put the file type that produce the services, but not works
    @RequestMapping(
            value="/getCustomers",
            method = RequestMethod.GET,
            produces={"application/json"}
    )
    @ResponseBody
    public  ResponseEntity<List<Customer>> getCustomers()
    {
        System.out.println("calling get customers service");
        JpaGenericController<Customer> customerDao = new JpaGenericController<Customer>( Customer.class );
        List<Customer> customers = customerDao.findAll();
        return new ResponseEntity<List<Customer>>(customers,HttpStatus.OK);
    }

And the headers generated by firefox:
http://localhost:9080/controller/services/test/getCustomers

GET /controller/services/test/getCustomers HTTP/1.1
Host: localhost:9080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:34.0) Gecko/20100101 Firefox/34.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive

HTTP/1.1 406 Not Acceptable
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 1067
Date: Mon, 29 Dec 2014 23:09:15 GMT

A: You need to add  to your spring xml to make spring resolve sensible defaults


text:
Q: Flutter Bundle Identifier minus (-) and underscore(_) The domain of our company is company-name.com
So i wanted to name the bundle com.company-name.flutter-app
At the apple app store we are allowed to use minus (-) but not underscore (_) for the bundle id.
But on android in regards to this question we are not allowed to use minus.
Valid name for Android Package Name
Also a project name with minus (-) is not allowed for flutter.
On other projects i had different bundle identifiers but this time i wanted to clean it up at the beginning to have less problems later on.
My plan was to keep it simple because it is a new project and i wanted to have the same name.
So what is the best practice here to keept it in line on both plattforms or do i have to use different bundle identifiers for android and apple?
I did not find any guidelines on handling this issue within the flutter documentation.