text:
Q: NullPointException when calculating RasterZonalStatistics in geoserver I am trying to generate raster zonal statistics for a raster by providing a custom polygon in geoserver. When I make a ras:RasterZonalStatistics request, I get a NullPointException error.
Request:
<?xml version="1.0" encoding="UTF-8"?><wps:Execute version="1.0.0" service="WPS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.opengis.net/wps/1.0.0" xmlns:wfs="http://www.opengis.net/wfs" xmlns:wps="http://www.opengis.net/wps/1.0.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" xmlns:wcs="http://www.opengis.net/wcs/1.1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd">
  <ows:Identifier>ras:RasterZonalStatistics</ows:Identifier>
  <wps:DataInputs>
    <wps:Input>
      <ows:Identifier>data</ows:Identifier>
      <wps:Reference mimeType="image/tiff" xlink:href="http://geoserver/wcs" method="POST">
        <wps:Body>
          <wcs:GetCoverage service="WCS" version="1.1.1">
            <ows:Identifier>test:tc</ows:Identifier>
            <wcs:DomainSubset>
              <ows:BoundingBox crs="http://www.opengis.net/gml/srs/epsg.xml#32643">
                <ows:LowerCorner>277250.0 2738310.0</ows:LowerCorner>
                <ows:UpperCorner>720100.0 3383110.0</ows:UpperCorner>
              </ows:BoundingBox>
            </wcs:DomainSubset>
            <wcs:Output format="image/tiff"/>
          </wcs:GetCoverage>
        </wps:Body>
      </wps:Reference>
    </wps:Input>
    <wps:Input>
      <ows:Identifier>zones</ows:Identifier>
      <wps:Data>
        <wps:ComplexData mimeType="application/json"><![CDATA[{
  "type": "Polygon",
  "coordinates": [
    [
              [675053.524554,3321241.9569],
[702078.79277,3321703.3667],
[701600.100876,3347772.38452],
[674638.920767,3347308.80149],
[675053.524554,3321241.9569],

    ]
  ]
}]]></wps:ComplexData>
      </wps:Data>
    </wps:Input>
     </wps:DataInputs>
  <wps:ResponseForm>
    <wps:RawDataOutput mimeType="text/xml; subtype=wfs-collection/1.0">
      <ows:Identifier>statistics</ows:Identifier>
    </wps:RawDataOutput>
  </wps:ResponseForm>
</wps:Execute>

Stacktrace:
03 Feb 11:05:59 INFO [geoserver.wps] -
Request: getServiceInfo
03 Feb 11:05:59 ERROR [wps.executor] - Process execution failed
org.geotools.process.ProcessException: java.lang.NullPointerException
        at org.geotools.process.factory.AnnotationDrivenProcessFactory$InvokeMethodProcess.execute(AnnotationDrivenProcessFactory.java:637)
        at org.geoserver.wps.executor.ProcessStartupFilter$ProcessStartupWrapper.execute(ProcessStartupFilter.java:50)
        at org.geoserver.wps.executor.DefaultProcessManager$ProcessCallable.call(DefaultProcessManager.java:224)
        at org.geoserver.wps.executor.DefaultProcessManager$ProcessCallable.call(DefaultProcessManager.java:192)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
        at org.geotools.process.raster.RasterZonalStatistics$RasterZonalStatisticsCollection.<init>(RasterZonalStatistics.java:150)
        at org.geotools.process.raster.RasterZonalStatistics.execute(RasterZonalStatistics.java:122)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.geotools.process.factory.AnnotationDrivenProcessFactory$InvokeMethodProcess.execute(AnnotationDrivenProcessFactory.java:621)
        ... 7 more
03 Feb 11:05:59 INFO [geoserver.wps] -
Request: execute
    service = WPS
    version = 1.0.0
    baseUrl = http://localhost:8080/geoserver/
    identifier:
        value = ras:RasterZonalStatistics
    dataInputs:
        input[0]:
            identifier = net.opengis.ows11.impl.CodeTypeImpl@46d10fe7 (value: data, codeSpace: null)
            reference = net.opengis.wps10.impl.InputReferenceTypeImpl@3183800a (body: net.opengis.wcs11.impl.GetCoverageTypeImpl@26967a60 (service: WCS, version: 1.1.1, baseUrl: null, extendedProperties: {}), encoding: null, href: http://geoserver/wcs, method: POST, mimeType: image/tiff, schema: null)input[0]:
            identifier = net.opengis.ows11.impl.CodeTypeImpl@3774a5b2 (value: zones, codeSpace: null)
            data = net.opengis.wps10.impl.DataTypeImpl@79943a8c
    responseForm:
        rawDataOutput:
            identifier = net.opengis.ows11.impl.CodeTypeImpl@54ba6664 (value: statistics, codeSpace: null)
            mimeType = text/xml; subtype=wfs-collection/1.0

Further, If I try to change the polygon to CQL,
<wps:ComplexData mimeType="text/plain; subtype=cql"><![CDATA[<Intersects>
       <PropertyName>GEOMETRY</PropertyName>
         <gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates decimal="." cs="," ts=" ">76.76559448242188,30.051265218888904 77.05055236816406,30.051265218888904 77.05055236816406,30.268556249047727 76.76559448242188,30.268556249047727 76.76559448242188,30.051265218888904</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>
     </Intersects>]]></wps:ComplexData>

I get an error with stacktrace:
Request: getServiceInfo 03 Feb 11:09:57 ERROR [wps.executor] - Process execution failed org.geoserver.wps.WPSException: Failed to retrieve value for input zones
        at org.geoserver.wps.executor.LazyInputMap.parseInputs(LazyInputMap.java:97)
        at org.geoserver.wps.executor.LazyInputMap.get(LazyInputMap.java:49)
        at org.geotools.process.factory.AnnotationDrivenProcessFactory$InvokeMethodProcess.buildProcessArguments(AnnotationDrivenProcessFactory.java:736)
        at org.geotools.process.factory.AnnotationDrivenProcessFactory$InvokeMethodProcess.execute(AnnotationDrivenProcessFactory.java:616)
        at org.geoserver.wps.executor.ProcessStartupFilter$ProcessStartupWrapper.execute(ProcessStartupFilter.java:50)
        at org.geoserver.wps.executor.DefaultProcessManager$ProcessCallable.call(DefaultProcessManager.java:224)
        at org.geoserver.wps.executor.DefaultProcessManager$ProcessCallable.call(DefaultProcessManager.java:192)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748) Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 79; The prefix "gml" for element "gml:Polygon" is not bound.
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284)
        at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:284)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
        at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
        at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
        at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
        at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
        at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:327)
        at org.geotools.xsd.Parser.parse(Parser.java:184)
        at org.geotools.xsd.Parser.parse(Parser.java:139)
        at org.geoserver.wps.ppio.WFSPPIO.decode(WFSPPIO.java:91)
        at org.geoserver.wps.executor.SimpleInputProvider.getValueInternal(SimpleInputProvider.java:81)
        at org.geoserver.wps.executor.AbstractInputProvider.getValue(AbstractInputProvider.java:100)
        at org.geoserver.wps.executor.LazyInputMap.parseInputs(LazyInputMap.java:89)
        ... 10 more 03 Feb 11:09:57 INFO [geoserver.wps] - Request: execute
    service = WPS
    version = 1.0.0
    baseUrl = http://localhost:8080/geoserver/
    identifier:
        value = ras:RasterZonalStatistics
    dataInputs:
        input[0]:
            identifier = net.opengis.ows11.impl.CodeTypeImpl@38edacc (value: data, codeSpace: null)
            reference = net.opengis.wps10.impl.InputReferenceTypeImpl@78f2f6bf (body: net.opengis.wcs11.impl.GetCoverageTypeImpl@c087073 (service: WCS, version: 1.1.1, baseUrl: null, extendedProperties: {}), encoding: null, href: http://geoserver/wcs, method: POST, mimeType: image/tiff, schema: null)input[0]:
            identifier = net.opengis.ows11.impl.CodeTypeImpl@3f33892d (value: zones, codeSpace: null)
            data = net.opengis.wps10.impl.DataTypeImpl@4a1e7cbd
    responseForm:
        rawDataOutput:
            identifier = net.opengis.ows11.impl.CodeTypeImpl@25b62c4f (value: statistics, codeSpace: null)
            mimeType = text/xml; subtype=wfs-collection/1.0


text:
Q: Email Only showing code / text with Outlook I am having an issue with Outlook displaying email content and attachments correctly, the email content works fine on mail service providers such as Google Mail or Hotmail etc.
This is the email content outlook produces:
X-Mailer: simpleEmailClass v1.0

MIME-Version: 1.0

Content-Type: multipart/mixed; boundary="13406541204fe8c2284f5aa"

Message-Id: < - removed - >
Date: Mon, 25 Jun 2012 20:55:20 +0100 (BST)

--13406541204fe8c2284f5aa

Content-Type: multipart/alternative; boundary="13406541204fe8c2284f98f"

--13406541204fe8c2284f98f

Content-Type: text/plain; charset="ISO-8859-1"

Content-Transfer-Encoding: quoted-printable

Dear Rachel
Further to your recent enquiry please accept this email as confirmation of your booking.
Kind Regards
Hanna

--13406541204fe8c2284f98f

Content-Type: text/html; charset="ISO-8859-1"

Content-Transfer-Encoding: quoted-printable

    Dear Rachel

    Further to your recent enquiry please accept this email as confirmation of your booking.

    Kind Regards

    Hanna

--13406541204fe8c2284f98f--

--13406541204fe8c2284f5aa

Content-Type: application/pdf; name="invoice.pdf"

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename="invoice.pdf"

JVBERi0xLjMKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZwovT3V0bGluZXMgMiAwIFIKL1Bh

^^ This go on and on for a long time, thought it was best not to post it all.

--13406541204fe8c2284f5aa--

This email above is what is seen in outlook, in Google Mail, it shows as the HTML version.
This is the code im using for the email class.
<?php
class sec {
    var $secVersion = '1.0';
    var $to = '';
    var $Cc = array ();
    var $Bcc = array ();
    var $subject = '';
    var $message = '';
    var $attachment = array ();
    var $embed = array ();
    var $charset = 'ISO-8859-1';
    var $emailboundary = '';
    var $emailheader = '';
    var $textheader = '';
    var $errors = array ();

    function __construct($toname, $toemail, $fromname, $fromemail) {
        $this->emailboundary = uniqid ( time () );
        $this->to = "{$toname} <" . $this->validateEmail ( $toemail ) . ">";
        $email = $this->validateEmail ( $fromemail );
        $this->emailheader .= "From: {$fromname} <{$email}>\r\n";
    }

    function validateEmail($email) {
        if (! preg_match ( '/^[A-Z0-9._%-]+@(?:[A-Z0-9-]+\\.)+[A-Z]{2,4}$/i', $email ))
            die ( 'The Email ' . $email . ' is not Valid.' );

        return $email;
    }

    function Cc($email) {
        $this->Cc [] = $this->validateEmail ( $email );
    }

    function Bcc($email) {
        $this->Bcc [] = $this->validateEmail ( $email );
    }

    function buildHead($type) {
        $count = count ( $this->$type );
        if ($count > 0) {
            $this->emailheader .= "{$type}: ";
            $array = $this->$type;
            for($i = 0; $i < $count; $i ++) {
                if ($i > 0)
                    $this->emailheader .= ',';
                $this->emailheader .= $this->validateEmail ( $array [$i] );
            }
            $this->emailheader .= "\r\n";
        }
    }

    function buildMimeHead() {
        $this->buildHead ( 'Cc' );
        $this->buildHead ( 'Bcc' );

        $this->emailheader .= "X-Mailer: simpleEmailClass v{$this->secVersion}\r\n";
        $this->emailheader .= "MIME-Version: 1.0\r\n";
    }

    function buildMessage($subject, $message = '') {
        $textboundary = uniqid ( time () );
        $this->subject = strip_tags ( trim ( $subject ) );

        $this->textheader = "Content-Type: multipart/alternative; boundary=\"$textboundary\"\r\n\r\n";
        $this->textheader .= "--{$textboundary}\r\n";
        $this->textheader .= "Content-Type: text/plain; charset=\"{$this->charset}\"\r\n";
        $this->textheader .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
        $this->textheader .= strip_tags ( $message ) . "\r\n\r\n";
        $this->textheader .= "--$textboundary\r\n";
        $this->textheader .= "Content-Type: text/html; charset=\"$this->charset\"\r\n";
        $this->textheader .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
        $this->textheader .= "\n\n{$message}\n\n\r\n\r\n";
        $this->textheader .= "--{$textboundary}--\r\n\r\n";
    }

    function mime_type($file) {
        return (function_exists ( 'mime_content_type' )) ? mime_content_type ( $file ) : trim ( exec ( 'file -bi ' . escapeshellarg ( $file ) ) );
    }

    function attachment($file, $filename = NULL, $direct_input = FALSE, $mime = '') {
        if(!$direct_input)
        {
            if (is_file ( $file )) {
                $basename = $filename? $filename: basename ( $file );
                $attachmentheader = "--{$this->emailboundary}\r\n";
                $attachmentheader .= "Content-Type: " . $this->mime_type ( $file ) . "; name=\"{$basename}\"\r\n";
                $attachmentheader .= "Content-Transfer-Encoding: base64\r\n";
                $attachmentheader .= "Content-Disposition: attachment; filename=\"{$basename}\"\r\n\r\n";
                $attachmentheader .= chunk_split ( base64_encode ( fread ( fopen ( $file, "rb" ), filesize ( $file ) ) ), 72 ) . "\r\n";

                $this->attachment [] = $attachmentheader;
            } else {
                die ( 'The File ' . $file . ' does not exsist.' );
            }
        }
        else
        {
            $basename = $filename;
            $attachmentheader = "--{$this->emailboundary}\r\n";
            $attachmentheader .= "Content-Type: $mime; name=\"{$basename}\"\r\n";
            $attachmentheader .= "Content-Transfer-Encoding: base64\r\n";
            $attachmentheader .= "Content-Disposition: attachment; filename=\"{$basename}\"\r\n\r\n";
            $attachmentheader .= chunk_split ( base64_encode ( $file ), 72 ) . "\r\n";

            $this->attachment [] = $attachmentheader;
        }
    }

    function embed($file) {
        if (is_file ( $file )) {
            $basename = basename ( $file );
            $fileinfo = pathinfo ( $basename );
            $contentid = md5 ( uniqid ( time () ) ) . "." . $fileinfo ['extension'];
            $embedheader = "--{$this->emailboundary}\r\n";
            $embedheader .= "Content-Type: " . $this->mime_type ( $file ) . "; name=\"{$basename}\"\r\n";
            $embedheader .= "Content-Transfer-Encoding: base64\r\n";
            $embedheader .= "Content-Disposition: inline; filename=\"{$basename}\"\r\n";
            $embedheader .= "Content-ID: <{$contentid}>\r\n\r\n";
            $embedheader .= chunk_split ( base64_encode ( fread ( fopen ( $file, "rb" ), filesize ( $file ) ) ), 72 ) . "\r\n";

            $this->embed [] = $embedheader;

            return "";
        } else {
            die ( 'The File ' . $file . ' does not exsist.' );
        }
    }

    function sendmail() {
        $this->buildMimeHead ();

        $header = $this->emailheader;

        $attachcount = count ( $this->attachment );
        $embedcount = count ( $this->embed );

        if ($attachcount > 0 || $embedcount > 0) {
            $header .= "Content-Type: multipart/mixed; boundary=\"{$this->emailboundary}\"\r\n\r\n";
            $header .= "--{$this->emailboundary}\r\n";
            $header .= $this->textheader;

            if ($attachcount > 0)
                $header .= implode ( "", $this->attachment );
            if ($embedcount > 0)
                $header .= implode ( "", $this->embed );
            $header .= "--{$this->emailboundary}--\r\n\r\n";
        } else {
            $header .= $this->textheader;
        }

        return mail ( $this->to, $this->subject, $this->message, $header );
    }
}

What can i do so that the email in outlook will only show the plain text or html and the attachment, and not how it is currently showing.
Thanks

A: I can't be sure but I seem to recall coming across the same issue and turned out that using '\n' instead of '\r\n' helped, have you tried it?

A: I recently had a similar issue sending email to newer email clients.  I was using Thunderbird 3, and upon upgrade to v8 or whatever it was at the time (newer for sure) all the emails came thru with no attachment and some of the source code for the email.
The fix was changing to a single multipart/mixed container.  In the example, you have 2 containers.  Looked ok to me, but dropping the nested container solved the issue.
Also, I use \n not \r\n

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove all table rows from SQLite database table I want to remove all rows that i entered from my SQLite database table. The table name is tbltask.
I tried to drop the table and delete * from table, but those are giving me runtime errors.
I want to trigger this event in Button OnClickListner event.
Following code is what I tried:
String delete = "DELETE FROM "+DATABASE_TABLE;
db.rawQuery(delete, null);
db.delete(DATABASE_TABLE, null, null);

LogCat:
11-15 17:45:04.660: DEBUG/AndroidRuntime(300): Shutting down VM
11-15 17:45:04.660: WARN/dalvikvm(300): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): FATAL EXCEPTION: main
11-15 17:45:04.710: ERROR/AndroidRuntime(300): java.lang.NullPointerException
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at database.com.android.DatabaseAccess.drop(DatabaseAccess.java:258)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at com.android.ExtraActivity$3$1.onClick(ExtraActivity.java:61)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at android.os.Handler.dispatchMessage(Handler.java:99)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at android.os.Looper.loop(Looper.java:123)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at java.lang.reflect.Method.invoke(Method.java:521)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-15 17:45:04.710: ERROR/AndroidRuntime(300): at dalvik.system.NativeStart.main(Native Method)
11-15 17:45:04.781: WARN/ActivityManager(58): Force finishing activity com.android/.ExtraActivity
11-15 17:45:05.320: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{45061a70 com.android/.ExtraActivity}
11-15 17:45:14.857: WARN/ActivityManager(58): Launch timeout has expired, giving up wake lock!
11-15 17:45:15.402: WARN/ActivityManager(58): Activity idle timeout for HistoryRecord{450141d0 com.android/.WelcomActivity}
11-15 17:45:20.572: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{45061a70 com.android/.ExtraActivity}

This is the LogCat output I get for following query:
        String delete = "DELETE FROM taskTable";
    db.execSQL(delete);

A: Just do:
db.delete(DATABASE_TABLE, null, null);

Note that using rawQuery should work, but can be a potential security risk.
EDIT:
About the problem you have when you use
db.execSQL

Read the documentation, it says you should not use execSQL with INSERT, DELETE, UPDATE or SELECT

A: Consensus is to drop and recreate the table, or you can use DELETE FROM tbltask which uses a performance operation similar to a TRUNCATE on other dbs.

A:  getWritableDatabase().execSQL("DELETE FROM " + "contacts" + ";");

Here contacs is my table name.. Try it..It works for me..

A: Delete all values from database table use this method in database.
private SQLiteDatabase odb;
public void deleteallvalues(){
     odb.delete(TABLE_NAME,null,null)
}

this work fine.


text:
Q: disable kendo default grouping row selection How do I disable selection for the default grouping header? My grid has selectable: 'multiple' and grouping is set to false (i don't want to user to group, but i want to specify the grouping myself). This means the grouping header is also selectable. How do i make the grouping header row be not selectable?

A: You can simply state what the default grouping should be in the dataSource property of the Kendo grid:
dataSource: {
    ...
    group: {
       field: 'NameOfFieldYouWantToGroup'
    }
}

And ensure the groupable attribute is set on the top level grid intialisation:
$("#grid").kendoGrid({
    ...
    groupable: false
});

Here is a Dojo example of predetermined groupings (with the option to remove the grouping removed)


text:
Q: Similar numbers Say, I have two numbers which are almost equal:

A = 1.000000000000000000000001
  and
  B = 1.000000000000000000000002

What is the right way to say that they are "almost the same"?

*

*A is almost B

*A is almost the same as B

*A is similar to B

*A is like B

*A is alike B

*A and B are alike

*A is close to B

*?

A: The "right way" to say that A and B are "almost the same" is context dependent.  What works in ordinary conversation might not work in conversation among mathematicians, and almost certainly won't work in a mathematical journal paper.
As noted below, two of your forms are acceptable, but none of them are what I would say, which is:  "A is nearly equal to B" or "The difference of A and B is tiny".
In conversation, the forms "A is almost the same as B" and "A is close to B" are acceptable, but except in special contexts, none of the other forms are.  That is, for each phrase, one could construct a special or artificial context where that phrase works; but if we assume more-general contexts, we can rule out several of the phrases, as follows.  "A is almost B" suggests that A has been changing in value and now is almost B.   "A is similar to B", "A is like B", and "A and B are alike" suggest that A and B are being compared by some unstated measure of similarity.  (In general, "similar" and  "like" do not connote a small arithmetic difference, but instead similar bit or digit patterns or other properties.)   "A is alike B" isn't grammatical.
Mathematically, almost, almost all, and almost everywhere have specialized meanings; for example:

In set theory, when dealing with sets of infinite size, the term almost or nearly is used to mean all the elements except for finitely many.
"Almost all" is sometimes used synonymously with "all but [except] finitely many" ... or "all but a countable set" ...  When speaking about the reals, sometimes it means "all reals but a set of Lebesgue measure zero" ...
In measure theory (a branch of mathematical analysis), a property holds almost everywhere if the set of elements for which the property does not hold is a set of measure zero

Given those specialized meanings, it's reasonable to avoid using almost for almost all other purposes.

A: The difference between the values of A and B is insignificant.
There is no significant difference between A and B.
A and B are equal to 20 significant figures.

A: From your list, A is almost the same as B is the best choice. However, A is almost equal to B would be more 'mathematically' correct.

A: They approximate (to) (each other).
approximation [TFD]

4  (Mathematics) Maths
b  an expression in simpler terms than a given expression which approximates to it

[emphasis mine]
verb

approach, near;
  come close or be similar to something in quality, nature, or quantity:
a leasing agreement approximating to ownership
a child tries to approximate his parents' speech
I've finally found a vegetarian burger that approximates the taste of real beef.
      The colors in the pictures can only approximate the real thing.
      an Australian who can approximate a strong New York City accent
  syn
  approach, compare (with), measure up (to), stack up (against or with), hold a candle to

[var. sources]

A: Value of A is almost same as value of B will be right mathematically.
A is almost the same as B from your option list is a good one.
We can also say "Value of A is somewhat near to Value of B".


text:
Q: the correct way to Load Gif's in asp.net MVC I am trying to find a way to correctly load a gif... Apparently the way I am doing it now is causing a mixed content warning on the page.  I have tried using Url.Content(~/path/to/javascript/file) and ResolveClient(~/doesn't/work/either)... What can I do to circumvent this warning?  I will show you my code + the warning I get...
function DemoSearchInternals()
{
    //debugger;
    var form = $("#DemoGraphID");
    $div = $("#TabView1");
    var srlzdform = form.serialize();
    var PopID = <% =PopID %>;
    var options = [];
    var $url = $("#target").attr("action");
    //getSize();
    $('<div id="overlay">').css({
        position: 'absolute',
        opacity: 0.2,
        top : $div.offset().top,
        left : $div.offset().left,
        width : $div.width(),
        height : $div.outerHeight(),
        background: 'grey url(<%=ResolveClientUrl("~/images/indicator_web20_working.gif")%>) no-repeat center'
    }).hide().appendTo($div);//Url.Content("~/images/indicator_web20_working.gif")
    $("#overlay").fadeIn();
    $.post('<%:Url.Action("SearchByDemographic", "PatientACO")%>', srlzdform, function (data)
    {
        DisplayDemographicSearch(data);
        $("#overlay").fadeOut('slow', function () {
             $("#overlay").remove();
        });
    });
}

I am particularly concerned about the background section?  In an asp.net MVC2 app, is that the best way to call url?  This section:
background: 'grey url(<%=Url.Content("~/images/indicator_web20_working.gif")%>) no-repeat center'

You see where it says grey url(yadda yadd)  am I calling Url correctly?  Is there a better way to call it?


text:
Q: when set to auto, width of a block element not transitioning I have the following html structure

The width of .inner is auto and changes according the text I put in it using JQuery. I want the width of .outer, or .inner, to change smoothly when the text content inside .inner changes. I have written the following CSS code
.outer {
    transition: all 0.5s linear;
    position: absolute;
    top: 50%;
    left: 50%;
}

.inner {
        transition: all 0.5s linear; // just to be sure
        background-color: white;
        color: @body;
        display: block;
        padding: 18px 28px;
        position: relative;
        width: 100%;
}

Now the behavior is that the width changes instantly, without the slightest transition. I want the width to change smoothly. The transition is added via LESS, so I am ok with prefixes.

A: CSS transitions don't work on values such as auto since it has no meaning behind it except for using the default behaviour or resetting something however percentages can be animated.
I created an animated loader using just CSS and percentage widths for an inner element however my element has fixed dimensions as in it knows the minimum width in percent and the maximum width in percent so those two values can be calculated.
Animating from 100% to auto would require a little more effort, if you do not know the dimensions after manipulating the element (for instance it scales down automatically) you'd have to create an invisible element with a display so that you can find out how wide it is to then remove it again.
Instead of having an auto value you could use 100% for maximum width and a minimum percentage value to transition to.


text:
Q: GraphQL in Jmeter- Variables and Parameters I want to send variable as float but when I am trying like this
latitude:"${latitudeValue}"
where latitudeValue is user defined variable.
and in graphQl query value come as String.
and I get this error

{"errors":[{"message":"Variable "$latitude" got invalid value
"41.98240048026275F"; Float cannot represent non numeric value:
"41.98240048026275F"","locations":[{"line":1,"column":96}],"extensions":{"code":"INTERNAL_SERVER_ERROR"}},{"message":"Variable
"$longitude" got invalid value "-102.07540422677995F"; Float
cannot represent non numeric value:
"-102.07540422677995F"","locations":[{"line":1,"column":114}],"extensions":{"code":"INTERNAL_SERVER_ERROR"}}]}

Is there any solution for this?

A: There is "Variables" tab in the GraphQL HTTP Request sampler:

where you can define GraphQL variables like:
{
  "id": "${id}"
}

and this ${id} comes from a User-Defined Variable
Once you do this you can use it in the "Query" tab like:
query ($id: ID!){
  droid(id: $id){
    id
    name
    friends{
      name
    }
    appearsIn
    primaryFunction
  }
}

Without variables:

With variables:

More information:

*

*GraphQL Queries and Mutations

*GraphQL server instance used for demo:  apollographql /
starwars-server

A: I think you are looking at Bug 65108 which could be solved by PR 660 or PR 651
At the moment you can only insert variable values, that lead to a valid JSON structure.


text:
Q: Two-step git import over ssh Bitbucket has an importer tool for importing repositories from remote locations, but it only supports the git:// protocol. Our existing repositories are on a company controlled machine behind a firewall that I can't change, and git:// is not available. I need to move the repositories from our company machine to bitbucket, keeping all history and details from the original repository intact.
Is there some way I can accomplish this by cloning the original repository via ssh to a local machine, and then pushing that repository to a newly-bare-initted repository on bitbucket? Will I lose any history or data that way?
(I'm hoping for an answer that isn't bitbucket specific, but will work for "moving" a git repository in any case.)

A: From what I know cloning the entire repo and pushing it works. Bitbucket even has the command for you:
cd /path/to/my/repo
git remote add origin ssh://git@bitbucket.org/someuser/somerepo.git
git push -u origin --all   # to push changes for the first time

A: You'll want to be sure you have the entire history. You can do this by performing a full local bare clone first.
git clone --mirror git://LOCAL_URL/somerepo.git

Then add the remote and push as Timothy pointed out. Though, you probably want to use something other than origin for the remote alias.
git remote add bitbucket ssh://git@bitbucket.org/someuser/somerepo.git
git push -u bitbucket --all

This could be used for any Git hosting service. Simply replace the remote URL with anything you'd like.

A: What makes you think that we only support the git:// protocol? We support the smart http protocol and so for instance you can just import https://github.com/jquery/jquery
So if your repo is accessible from the Internet and does HTTP(S) then you should have no problem using the importer (which does a proper clone and do preserves history).


text:
Q: How can I run through a while loop until a new line is reached? I need to set a word coming in through std::cin as a vector of chars until a newline ('\n') character is reached.
Here is what I have done so far:
#include "stdafx.h"
#include <iostream>
#include <vector>

int main(){
std::vector<char> one1; //A char vector that holds the first 'word'
std::cout << "Type in the first set of charactors: " << std::endl;
char o;
std::cin >> o;
int i = 0;
while (std::cin >> o && o != '\n' && o != 0) {
    one1[i] = o;
    i++;
    std::cin >> o;
}
std::cout << "Done";

    return 0;
}

It keeps returning an error, not a compile error, but during run time, this error comes up:
Debug Assertian Failed!
Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: c:\program files (x86)\microsoft visual studio
14.0\vc\include\vector
Line: 1234
Expression: vector subscript out of range
I don't know whats wrong, or what is causing this to happen, what should I be doing?

A: You are reading a character at the end of the loop, and right away another one in the while condition. So every second character gets ignored, you might just miss the '\n'.
Also, [] accesses existing elements in the vector, you can't use it to add to it. You need to use push_back for that.

A: You have undefined behavior in your code. You access a element that does not exist.
std::vector<char> one1;

Your vector is empty. As such if you want to add to it you need to use push_back:
one1.push_back(o);

A: If you'd like to read a line, use the getline function.
Getline stores a line in a string, you then convert that string to a vector (Converting std::string to std::vector<char>)
#include <iostream>
#include <vector>
#include <string>

int main()
{
  std::cout << "Type in the first set of charactors: " << std::endl;
  std::string line;
  std::getline(std::cin, line);
  std::vector<char> one1(std::begin(line), std::end(line)); //A char vector that holds the first 'word'
  std::cout << "Done";
  return 0;
}


text:
Q: Changing src of only hovered ng-include element, where value of src is a $scope variable I have multiple ng-include elements that have src attribute set to $scope.template_url.
I want to change src of hovered element only to new template but changing it's value will change all of elements. How can i implement it?
Html code:

Javascript (in controller):
angular.element(document).on('mouseover', '.parent', function(){
  $scope.$apply(function () {
      $scope.template_url = "path/to/new/template.html";
  });
});

Writing jQuery dom manipulation is dirty and also don't works:
$(this).attr('data-src', "path/to/new/template.html");

A: I'd suggest making this a directive. Directives have their own scope, so you can still do the "on hover use a different template" idea, but for each individual one that is hovered.

var myApp = angular.module('myApp',[]);

myApp.directive('someDirective', function() {
    return {
        controller: function ($scope) {
            $scope.model = "Hello"
            $scope.mouseover = function () {
                $scope.model = "Hovered!";
            };
        },
        scope:{},
        restrict: 'AE',
        replace: true,
        template: '
<input ng-mouseover="mouseover()" ng-model="model">
',
    };
});

Heres a fiddle to see it in action.
Tweak the template variable in the directive to use a variable on your model for the include url.
By the way, angular already has a mouseover handler, so i've just linked that into the controller with ng-mouseover in the template.


text:
Q: Как занести в переменную рандомное значение в нужном диапазоне? Есть переменная byte x. В неё нужно внести рандомное значение от 1 до 5 включительно. Моя реализация поставленной задачи выдаёт ошибку. Код:
import java.util.Random;       // импортируем Random

Random random = new Random();  // создаём объект класса Random

byte x;                        // переменную x
x = 1+random.nextByte(4)       // ЗДЕСЬ ОШИБКА

ошибка: Error:(№строки) java: incompatible types: int cannot be converted to byte[]

A: у Random нет метода nextByte, но есть nextBytes. Однако с помощью него можно складывать сгенерированный байт только в массив.
byte[] b = new byte[20];
new Random().nextBytes(b);

Можно конечно из x сделать массив длиной в 1 и генерировать в него и потом брать по нулевому индексу. Извращение, да.
Но раз задача стоит всего лишь в генерации чисел от 1 до 5, то достаточно будет в данном случае применить nextInt, а результат скастовать к byte
x = (byte) (1 + random.nextInt(5));


text:
Q: Calculate $\int\limits_{-\infty}^{\infty}\frac{\sin^2(x)\cos(wx)}{x^2}dx$ using complex analysis technique In a complex analysis test an exercise asks to calculate ($w \in \Bbb{R}$): $$\displaystyle\int_{-\infty}^{\infty}\frac{\sin^2(x)\cos(wx)}{x^2}dx$$
Of course I need to solve it with complex analysis technique. I have used all the tricks I know such as integrate on a semi-circumference of radius $R$ in $\Bbb{C}$ and then let $R \to \infty$ but everything I have tried to do just seemed useless. Thank you for every hint or solution to this problem!

A: If I had to use complex methods in this, the place I'd do it is in proving$$\int_{\mathbb{R}}\frac{\sin^{2}x}{x^{2}}dx=\pi$$(e.g. by the residue theorem; see here for the gory details) so$$\left|k\right|\pi=\int_{\mathbb{R}}\frac{\sin^{2}kx}{x^{2}}dx=\int_{\mathbb{R}}\frac{1-\cos2kx}{2x^{2}}dx.$$Hence$$\int_{\mathbb{R}}\frac{\sin^{2}x\cos wx}{x^{2}}dx=\int_{\mathbb{R}}\frac{2\cos wx-\cos\left(w-2\right)x-\cos\left(w+2\right)x}{4x^{2}}dx\\=\frac{\pi}{4}\left(\left|w-2\right|+\left|w+2\right|-2\left|w\right|\right).$$As a sanity check, the case $w=0$ needs to give $\pi$, and lo and behold it does.

A: This is certainly not a complex analytic method, but Fourier inversion formula also can give you the result. It holds that
$$
\int_{-1}^1 e^{-i\xi x}dx=\frac{2\sin \xi}{\xi}.
$$ Let $f(x) = 1_{[-1,1]}(x)$. This shows $\widehat{f}(\xi)=\frac{2\sin \xi}{\xi}$ and therefore, $\widehat{(f*f)}(\xi)=f(\xi)^2=4\frac{2\sin^2 \xi}{\xi^2}$.
The given integral is
$$\begin{eqnarray}
\int_{-\infty}^{\infty}\frac{\sin^2(x)\cos(wx)}{x^2}dx&=&\int_{-\infty}^{\infty}\frac{\sin^2(x)e^{iwx}}{x^2}dx\\
&=&2\pi \mathcal{F}^{-1}\left[\frac{\sin^2 x}{x^2}\right](w)\\
&=&\frac{\pi}{2}(f*f)(w).
\end{eqnarray}$$ Finally, we have
$$\begin{eqnarray}
(f*f)(w)&=&\int f(w-y)f(y)dy\\
&=&\int_{|w-y|<1,|y|<1}dy\\
&=&\begin{cases}2-w,\quad w\in[0,2)\\2+w,\quad w\in(-2,0]\\0,\quad|w|>2\end{cases}\\
&=&(2-|w|)1_{|w|<2}.
\end{eqnarray}$$ This gives that the given integral is equal to
$$
\frac{\pi}{2}(2-|w|)1_{|w|<2}.
$$

A: $$I(w)=\int_{-\infty}^\infty\frac{\sin^2(x)\cos(wx)}{x^2}dx$$
$$I'(w)=-\int_{-\infty}^\infty\frac{\sin^2(x)\sin(wx)}{x}$$
$$I''(w)=-\int_{-\infty}^\infty\sin^2(x)\cos(wx)dx$$
$$I''(w)=-\Re\int_{-\infty}^\infty\sin^2(x)e^{iwx}dx$$
and then try integration by parts. Alternatively:
$$I(w)=\Re\int_{-\infty}^\infty\frac{\sin^2(x)e^{iwx}}{x^2}dx$$
$$I(w)=\Re\int_{-\infty}^\infty\sin^2(x)\sum_{n=0}^\infty\frac{(iw)^nx^{n-2}}{n!}dx$$


text:
Q: Sending an image from android client to a local server on windows made with NetBeans I'm trying to send an image from a client running on android to a local server that's running on Windows, made with NetBeans.
I'm sending text successfully, but i need to send an image.
I tried encoding the image in android using base64 like that :
private BufferedWriter OutPut;
.
.
OutPut = new BufferedWriter(new OutputStreamWriter(ConnectionSocket.getOutputStream(), "UTF-8"));
//Converting the image to a string where `AppBitmapIcon` is a Bitmap image and i'm getting the bytes array from the function `getBitmapBytes`
String ImgString = Base64.encodeToString(getBitmapBytes(AppBitmapIcon), Base64.NO_WRAP);
OutPut.write(ImgString);

public static byte[] getBitmapBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

But i couldn't finde a way in NetBeans to decode this string converting it to an image and setting it as a icon for a JLabel becasue NetBeans don't has a imageView to handle images.
Anyone can help me to display the image in NetBeans or maybe try another method than encoding it and decoding it?
Any help will appreciated.

A: You can decode base64 string to BufferedImage, then BufferedImage to ImageIcon, then set ImageIcon as icon of JLabel. Try the following code:-
String base64 = "[encoded data, 6324 characters]";
    byte[] btDataFile = Base64.decodeBase64(base64);
    try {
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(btDataFile));
        jLabel1.setIcon(new ImageIcon(image));
    } catch (IOException ex) {
        Logger.getLogger(Test_Frame.class.getName()).log(Level.SEVERE, null, ex);
    }

I am using a sample base64 string along with a sample jframe which contains a jlabel. jLabel1 is the variable name of the jLabel which is iconized by the base64 string. And a jlabel with imageicon is the way to display images in J2SE applications (in my knowledge). you can check this github repository for more details : Base64-String_Manipulation. Also i am using Apache commons-codec library for decoding purpose.


text:
Q: @EnableSpringConfigured import hi i am working with a spring mvc project and i want to be able to do this annotation

@EnableSpringConfigured

in the top of one of my classes like this
@Configuration
@EnableSpringConfigured  <---- this one gives me troubles
@ComponentScan( basePackages = {"com.abc.dom", "com.abc.repo", "com.abc.auth"})
@EnableJpaRepositories(basePackages="com.abc.repo")
public class ConfigJPA
{

....

}

what maven dependency should i have in my pom.xml to be able to do this import:
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;

my spring version is 4.0.6.RELEASE

A: this is how i added the dependency and it worked
 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>3.2.0.RELEASE</version>
    </dependency>

Reimeus the link to the page that you give the artifactId was added like this
<artifactId>org.springframework.aspects</artifactId>

instead like <artifactId>spring-aspects</artifactId> thats why it dont worked for me, but thanks anyway it helped me too


text:
Q: Javascript: finding a value from an object I have the following object:
var stuff = {};
stuff["jar"] = "biscuit";
stuff["cupboard"] = "food";

Iterating through the list with an For i loop and getting the value is easy, but how would I get the key?
for (var i in stuff) {
    var key = GET KEY SOMEHOW
    var val = stuff[i];
}

A: The key is i. However, make sure that the key is in your object, not part of the prototype chain.
for (var i in stuff) {
  var key = i;
  if (stuff.hasOwnProperty(i)) {
    var val = stuff[i];
  }
}

See also:

*

*https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in

*https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

A: var key = i;
In Javascript's for (foo in bar) if foo is the index of an object or array and happens to be a string, it should print or assign the string when called.

A: You already have it:
for (var key in stuff) {
    var val = stuff[key];
}

A: If you have the value already you may find the key by using this logic :
for (var i=0;i<numKeyValuePairs;i++)
{
if(val==key[i])
{
document.write(key[i];
}
}


text:
Q: Assert_called_once_with need to check if the instances in the call are with the same info I'm trying to use assert_called_once_with from unittest.mock https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_called_once_with
But I want to check if 2 instances of objects have been passed with te correct attributes.
So inside the class I overrided the __eq__ func:
    def __eq__(self, other):
        return (
            self.id == other.id
            and self.users == other.users
        )

And in the code I used like this
        mock_add_user.assert_called_once_with(context_fix, expected_user_obj1, expected_user_obj2, users)

But I keep getting an error and the teste keeps comparing the repr of the instance, like this
<app.domain.model.load_md.Load object at 0x10cb7d7d0>

E           AssertionError: Expected call: add_user(<app.infrastructure.context.Context object at 0x10cb7da50>, <app.domain.model.load_md.Load object at 0x10cb7d7d0>, <app.domain.model.load_md.Load object at 0x10cb7d550>, [1, 2, 3, 2])
E           Actual call: add_user(<app.infrastructure.context.Context object at 0x10cb7da50>, <app.domain.model.load_md.Load object at 0x10ca7f5d0>, <app.domain.model.load_md.Load object at 0x10cd1e650>, [1, 2, 3, 2])

I really need a way to assert if an instance of a object has being passed as an parameter of the function with the correct attributes filled.

A: You want to use the call_args attribute of the mock object:
from unittest.mock import ANY, Mock

class Foo:
    pass

def call(add_user):
    f = Foo()
    add_user(f)

def test_is_instance():
    mock_add_user = Mock()

    call(mock_add_user)

    # expected = Foo()
    # mock_add_user.assert_called_once_with(expected) # This would fail
    mock_add_user.assert_called_once_with(ANY)
    assert isinstance(mock_add_user.call_args.args[0], Foo)

Here is a slightly more complex example with args and kwargs assertions:
from unittest.mock import ANY, Mock

class Foo:
    pass

class Bar:
    pass

def call(add_user):
    f = Foo()
    b = Bar()
    add_user(f, bar=b)

def test_is_instance():
    mock_add_user = Mock()

    call(mock_add_user)

    mock_add_user.assert_called_once_with(ANY, bar=ANY)
    assert isinstance(mock_add_user.call_args.args[0], Foo)
    assert isinstance(mock_add_user.call_args.kwargs["bar"], Bar)


text:
Q: PYTHONPATH error when trying to activate a virtual environment UPDATE: I've now reset my .bash_profile to this (based on this blog post):
PYTHONPATH="${PYTHONPATH}:/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/:$PATH"
export PYTHONPATH

After that, I tried source activate again and received this error:
Failed to import the site module
Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python 3.x!
     PYTHONPATH is currently: ":/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/:/Users/name/anaconda/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Users/name/anaconda/bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/name/bin:/usr/local/git/bin:/Library/TeX/texbin"
     You should `unset PYTHONPATH` to fix this.

There is a major problem with this because that's not the PYTHONPATH set in my .bash_profile... Now, I proceeded to execute PYTHONPATH=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/
However, I'm still getting this error even though I'm pointing to a 3.4 directory:
Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python 3.x!
     PYTHONPATH is currently: "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/"
     You should `unset PYTHONPATH` to fix this.

Using unset PYTHONPATH puts me in the same position noted below...

I use a macbook pro and typically operate with Python 3.X. Sometimes I need to use Python 2.7 and I have created an anaconda virtual environment to make it easy for me to do so. Since yesterday, I've started receiving 5 instances of the below error when trying to source activate my Python 2 virtual env within the command line:
Error in sitecustomize; set PYTHONVERBOSE for traceback:
KeyError: 'PYTHONPATH'

I executed the same command again as PYTHONVERBOSE=1 source activate python2 and located the Traceback (it's the same for each instance of the error):
Traceback (most recent call last):
  File "/Users/name/anaconda/lib/python3.4/site.py", line 508, in execsitecustomize
    import sitecustomize
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/usr/local/lib/python2.7/site-packages/sitecustomize.py", line 15, in <module>
    str(sys.version_info[0]) + '.x!\n     PYTHONPATH is currently: "' + str(os.environ['PYTHONPATH']) + '"\n' +
  File "/Users/name/anaconda/lib/python3.4/os.py", line 635, in __getitem__
    raise KeyError(key) from None
KeyError: 'PYTHONPATH'

Does anyone know how I may go about fixing this? I don't want to adjust any files before I fully know what I'm doing.

A: it looks like your PYTHONPATH is no longer set on your system, and the code is assuming that there is -something- in the environment.
I believe you could set a blank path in mac using the following; keep in mind if your python3.4 relies on the system path this may be dangerous! WARNING!: I am not on a mac, so you might need to give some string on the right-hand side here, otherwise it might not save the key
export PYTHONPATH=

If you do not want to set anything system-wide, you could simply add the variable to the running python scripts before sitecustomize runs. Buildout allows you to do this with a pre-script (via zc.buildout or zc.recipes, I am sure Anaconda has something similar), and this would allow the PYTHONPATH to be different for 3.4 and 2.7, which is what you're trying to do in the first place:
import os
pypath = os.environ.get("PYTHONPATH", "")
os.environ["PYTHONPATH"] = pypath


text:
Q: Link Replacement With JavaScript I want to replace directory links with javascript. for example i want to change http://mysite.com/cdn/backup/Pic.jpg in to http://mysite.com/newcdn/folder/Pic.jpg.
My Code:
<!DOCTYPE html>

Using this tutorial: http://www.w3schools.com/jsref/jsref_replace.asp
So, this codes not working for me. please correct if there are any error in script. thanks in advance.

A: If you're trying to change the src of the  tag(which is what I'm supposing, reading the question) then you need to do something like this:
function changeSrc() {
    var img = document.getElementsByTagName('img')[0];
    img.src = img.src.replace('cdn/backup/', 'newcdn/folder/');
}

window.onload = changeSrc;

From the comments I read that you want to change ALL the srcs, so the code will look like this:
function changeAllSrcs() {
    var imgs = document.getElementsByTagName('img');
    for (var i = 0; i < imgs.length; i++) {
        var img = imgs[i];
        img.src = img.src.replace('cdn/backup/', 'newcdn/folder/');
    }
}

window.onload = changeAllSrcs;

I don't know if this is a good way to do this, but if you want to replace all the occurences with link then you should do something like this(I don't like this solution, and it is not totally safe too, anyway it should do the job):
function replaceLinks() {
    var bodyHtml = document.body.innerHTML,
        replaced = bodyHtml.replace(/cdn\/backup/g, 'newcdn/folder/');
    document.body.innerHTML = replaced;
}
window.onload = replaceLinks;

A: access element and replace src attribute.
to change src of all img elements:
var img = document.getElementsByTagName('img');
length = img.length;

while(length--) {
    img[length].src = img[length].src.replace('cdn/backup/', 'newcdn/folder/');
}

A: Assuming you can use JQuery you could do this:
$.each($("img"),function(key,value){
    value.src = value.src.replace("cdn/backup/","newcdn/folder/");
});

Same can be done for the iFrame if indeed necessary:
    $.each($("iframe"),function(key,value){
   value.src = value.src.replace("cdn/backup/","newcdn/folder/");
});

Most likely you will need to do this on document load. So
$(document).ready(function(){
    $.each($("img"),function(key,value){
        value.src = value.src.replace("cdn/backup/","newcdn/folder/");
    });
//AND/OR
    $.each($("iframe"),function(key,value){
        value.src = value.src.replace("cdn/backup/","newcdn/folder/");
    });
});

A: It should be
var n=str.replace(/cdn\/backup/ig,"newcdn/folder/");

A: This code does not do what you think it is doing.
This snippet
    var n=str.replace("Microsoft","W3Schools");
replaces the words Microsoft with W3Schools in the string str. You want this replacement to happen in the link text. You need to get the link text and replace it. One idea is to get all the elements in the DOM and replace their src attributes.
var elements=document.getElementsByTagName("*")
for (var i=0, max=all.length; i < max; i++) {
 // Do something with the element here
     str = elements[i].getAttribute("src")
     var newstr=str.replace("cdn/backup/","newcdn/folder/");
     elements[i].setAttribute("src",newstr)

}


text:
Q: How to change the type for only one field using the openapi-generator-maven-plugin? I have a schema that describes the data I get from the REST service. I can't change this scheme. There are two date-time type fields in the schema that have a different format:
"date1": {
    "type": "string",
    "description": "Date 1",
    "format": "date-time"
},
"date2": {
    "type": "string",
    "description": "Date 2",
    "format": "date-time"
}

{
    "date1": "2021-07-29T03:00:00",
    "date2": "2021-04-22T08:25:30.264Z"
}

By default, the open api-generator-maven-plugin creates the OffsetDateTime type for date-time type fields:
    @JsonProperty("date1")
    private OffsetDateTime date1;

    @JsonProperty("date2")
    private OffsetDateTime date2;

With typeMappings and importMappings I can replace OffsetDateTime to LocalDateTime:
<typeMappings>
    <typeMapping>OffsetDateTime=LocalDateTime</typeMapping>
</typeMappings>
<importMappings>
    <importMapping>java.time.OffsetDateTime=java.time.LocalDateTime</importMapping>
</importMappings>

But this replacement will happen for all fields:
    @JsonProperty("date1")
    private LocalDateTime date1;

    @JsonProperty("date2")
    private LocalDateTime date2;

Is there a way to replace OffsetDateTime with LocalDateTime for date1 only?
That's what I want to see in the generated class:
    @JsonProperty("date1")
    private LocalDateTime date1;

    @JsonProperty("date2")
    private OffsetDateTime date2;

I understand that I can fix the generated class and replace OffsetDateTime with LocalDateTime, but I don't want to change the generated class every time after generation.
Thanks in advance.

A: Here is the solution I eventually came to.
I am replacing OffsetDateTime with LocalDateTime using maven-replacer-plugin:
<replacements>
    <replacement>
        <token>import java.time.OffsetDateTime;</token>
        <value>import java.time.OffsetDateTime;\nimport java.time.LocalDateTime;</value>
    </replacement>
    <replacement>
        <token>OffsetDateTime date1</token>
        <value>LocalDateTime date1</value>
    </replacement>
</replacements>

Not very elegant, but it works )


text:
Q: ArgumentError: wrong number of arguments (given 1, expected 2) for Update_Attribute Method I am creating a recurring event app where certain users (streamers) can schedule recurring weekly events (streams) and other users (viewers) can follow them. The result is a personalized weekly calendar detailing when all followed streamers' events begin and end.

However, because viewers can follow an infinite number of streamers and therefore the resulting calendar would look like a hot mess. So I added a boolean attribute to the relationships table that indicates whether the relationship has been favorited.
  create_table "relationships", force: :cascade do |t|
    t.integer "follower_id"
    t.integer "followed_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "favorited", default: false
    t.index ["followed_id"], name: "index_relationships_on_followed_id"
    t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
    t.index ["follower_id"], name: "index_relationships_on_follower_id"
  end

This way, viewers will have a second personalized calendar that will show only favorited streamers' events.
I already have a follow and unfollow method that successfully create and destroy a relationship between viewer and streamer, but I'm having trouble successfully updating an existing relationship from unfavorited to favorited.
test "should favorite and unfavorite a streamer" do
    yennifer = users(:yennifer)
    cirilla = users(:cirilla)
    yennifer.follow(cirilla)
    yennifer.favorite(cirilla)     #user_test.rb:151
end

The testing suite returns the following error and I can't figure out what the missing argument is.
["test_should_favorite_and_unfavorite_a_streamer", #<Minitest::Reporters::Suite:0x0000000006125da8 @name="UserTest">, 0.16871719993650913]
 test_should_favorite_and_unfavorite_a_streamer#UserTest (0.17s)
ArgumentError:         ArgumentError: wrong number of arguments (given 1, expected 2)
            app/models/relationship.rb:11:in `favorite'
            app/models/user.rb:124:in `favorite'
            test/models/user_test.rb:151:in `block in <class:UserTest>'

  27/27: [=================================] 100% Time: 00:00:01, Time: 00:00:01

Finished in 1.82473s
27 tests, 71 assertions, 0 failures, 1 errors, 0 skips

User.rb
# Follows a user
def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
end

# Unfollows a user
def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
end

def favorite(other_user)
    active_relationships.find_by(followed_id: other_user.id).favorite     #user.rb:124
end

def unfavorite(other_user)
    active_relationships.find_by(followed_id: other_user.id).unfavorite
end

Relationships.rb
def favorite
    update_attribute(favorited: true)     #relationship.rb:11
end

def unfavorite
    update_attribute(favorited: false)
end

Can someone please help me in identifying the missing argument and fixing this problem. Thank you.

A: The first comment on this answer is correct, so I don't know why this person posted as a comment rather than an answer. update_attribute takes two arguments and you are passing it a single hash argument. Your "favorite" method is the equivalent of
update_attribute({favorited: true}) when you really want update_attribute(:favorited, true)


text:
Q: Why is $R[X,Y]/(X^2-Y^3)$ isomorphic to $\{\sum a_iT^i\in R[T] \; : \; a_1=0\}$? Let $R$ be a ring (commutative, with unit). Show that $A=\{\sum a_iT^i\in R[T] \; : \; a_1=0\}$ is a subring of $R[T]$ and isomorphic to $R[X][Y]/(X^2-Y^3)$.
Of course, I'm trying to find a ring homomorphism of $R[X][Y]$ into $R[T]$ with image $A$ and kernel $(X^2-Y^3)$. Can you give me a hint?

A: How about $X \mapsto T^3$ and $Y \mapsto T^2$?

A: If you choose a basis for $R[X][Y]/(X^2-Y^3)$ (as a free $R$-module), you will have a clearer image of what it looks like.
For example you can show that $(1,Y,Y^2,Y^3,\ldots,X,XY,XY^2,XY^3,\ldots)$ is one possible basis.
And then look at what is the image of the basis under the isomorphism.


text:
Q: iframe with lightbox (sorry for my english..)
I've got an iFrame that load some page when i click some button.
These pages contain some that open a zoom in a lightbox.
My problem: lightbox is inside the iFrame, and i need that it is in 100%.
the code here:

A: I think you mean you want the lightbox to take up the whole page not just the iframe within that page. It's not possible, the lightbox must exist in the main page.


text:
Q: Missing user principals when using EarlyExecutionFilter from Magnolia I have some problems with the EarlyExectionFilter from magnolia. When forwarding to the webpage which was given back from my executeEarly() method, the system can't forward to the given path since the user principals are not set to the subject. When i send a redirect, the Filter works fine. After two days of debugging I couldn't find the error, any ideas how to fix this problem?

A: Look in your filter chain. My guess would be that you have EarlyExecutionFilter before SecurityFilter so it is executed before authentication is done. It works with the redirect because filter chain is executed again after the redirect thus on second pass user is already authenticated and EEF will see it.
If this is indeed the case, solution is then to move EE filter after SecurityFilter.
HTH,
Jan


text:
Q: Linking to another web page using  tag, absolute and relative path concept, I guess I am trying to link my html files which are under the same folder called "templates". One of the file is called "home.html" which has a link to another html file called "page2.html". The following code works perfectly:
Click Me

But, this gives the url something link this: 127.0.0.1:8000/page2 instead of what I actually want. I want it to be something link this: 127.0.0.1:8000/home/page2. I am making a django web app, but I am new to linking the web pages in the desired form.
Is there a way in which I can achieve the above using html  tag or using javascript or something from the django app?
Is it related to absolute or relative path? If yes, how? Kindly help...

A: If your current path is for example 127.0.0.1:8000/home you can to this like that: Click me
That's becaust ./ is your current directory and ../ is upper directory
EDIT: You should check routing in Django

A: You can't have home/html in the path because home.html is a HTML file, not a folder. If you are really keen to have your path like 127.0.0.1:8000/home/page2 , then create a folder called home, move the page2.html into that folder and call it from there. Wouldn't recommend that, though.

A: There's nothing complicated about this. If you want your link to go to "/home/page2", then that's what you should use in the href.
However, there is a better way of doing this in Django; you should use the {% url %} tag. Assuming you have defined your URL in urls.py with the name "page2", then do


text:
Q: How to find a key by value of a child element? My JSON file (countries_numbers.json):
{
  "AF": {
    "countryName": "Afghanistan",
    "countryPrefix": "93"
  },
  "AL": {
    "countryName": "Albania",
    "countryPrefix": "355"
  },
  "DZ": {
    "countryName": "Algeria",
    "countryPrefix": "213"
  },
  "AS": {
    "countryName": "American Samoa",
    "countryPrefix": "1"
  },
  "AD": {
    "countryName": "Andorra",
    "countryPrefix": "376"
  },
  "AO": {
    "countryName": "Angola",
    "countryPrefix": "244"
  },
  "AI": {
    "countryName": "Anguilla",
    "countryPrefix": "1"
  },
  "AG": {
    "countryName": "Antigua",
    "countryPrefix": "1"
  },
  "AR": {
    "countryName": "Argentina",
    "countryPrefix": "54"
  },
  "AM": {
    "countryName": "Armenia",
    "countryPrefix": "374"
  },
  "AW": {
    "countryName": "Aruba",
    "countryPrefix": "297"
  },
  "AU": {
    "countryName": "Australia",
    "countryPrefix": "61"
  },
  "AT": {
    "countryName": "Austria",
    "countryPrefix": "43"
  },
  "AZ": {
    "countryName": "Azerbaijan",
    "countryPrefix": "994"
  },
  "BH": {
    "countryName": "Bahrain",
    "countryPrefix": "973"
  },
  "BD": {
    "countryName": "Bangladesh",
    "countryPrefix": "880"
  },
  "BB": {
    "countryName": "Barbados",
    "countryPrefix": "1"
  },
  "BY": {
    "countryName": "Belarus",
    "countryPrefix": "375"
  },
  "BE": {
    "countryName": "Belgium",
    "countryPrefix": "32"
  },
  "BZ": {
    "countryName": "Belize",
    "countryPrefix": "501"
  },
  "BJ": {
    "countryName": "Benin",
    "countryPrefix": "229"
  },
  "BM": {
    "countryName": "Bermuda",
    "countryPrefix": "1"
  },
  "BT": {
    "countryName": "Bhutan",
    "countryPrefix": "975"
  },
  "BO": {
    "countryName": "Bolivia",
    "countryPrefix": "591"
  },
  "BA": {
    "countryName": "Bosnia and Herzegovina",
    "countryPrefix": "387"
  },
  "BW": {
    "countryName": "Botswana",
    "countryPrefix": "267"
  },
  "BR": {
    "countryName": "Brazil",
    "countryPrefix": "55"
  },
  "IO": {
    "countryName": "British Indian Ocean Territory",
    "countryPrefix": "246"
  },
  "VG": {
    "countryName": "British Virgin Islands",
    "countryPrefix": "1"
  },
  "BN": {
    "countryName": "Brunei",
    "countryPrefix": "673"
  },
  "BG": {
    "countryName": "Bulgaria",
    "countryPrefix": "359"
  },
  "BF": {
    "countryName": "Burkina Faso",
    "countryPrefix": "226"
  },
  "MM": {
    "countryName": "Burma Myanmar",
    "countryPrefix": "95"
  }
}

Now I want search in this JSON file for a value. Something like that:

SEARCHING: countryPrefix = "226" ¦ WHEN FOUND RETURN: "BF" ELSE RETURN "false"

I hope you new what I want to do. Sry for the bad question, I'm absolute new to JavaScript.
PS: I already searched on Google and found nothing.

A: One possible approach:

const countries = {
  "AF": {
    "countryName": "Afghanistan",
    "countryPrefix": "93"
  },
  "AL": {
    "countryName": "Albania",
    "countryPrefix": "355"
  }
  // .. the rest cut for brevity
}

const getCodeByPrefix = prefix =>
  Object.keys(countries).find(code => countries[code].countryPrefix === prefix);

console.log(getCodeByPrefix('93')); // AF
console.log(getCodeByPrefix('193')); // undefined

Here, getCodeByPrefix is a function that takes prefix as argument; its return value is either the code - or undefined, if no value is found for given prefix.

What you're doing is here is called reverse lookup: trying to find a particular key by its value. The complexity of this operation is O(n), which means the more countries will be in your object, the harder it'll be to find the one.
Now, as we're still talking about hundreds of entries, and not thousands (let alone hundreds of thousands), it won't matter much. Still I'd suggest you to consider reversing the structure of your data to make prefixes keys - either single or duplicating ones.

A: While raina77ow probably answered your question, I thought I share another way of doing it.
for (var key in json) {
    if (json.hasOwnProperty(key)) {
                if(json[key]['countryPrefix'] == 226) {
                    // do stuff
        }
    }
}


text:
Q: E4 RCP How to set selection of ToolBarItem that contains Radio Buttons In Eclipse E4 (Luna), using the application model to create parts, handlers, commands, handled menu items etc, (these are not created programatically). I have a toolbar.  This contains a sub-Menu item called "Filter" that contains another sub-menu of two filters.  The two filters are two Handled Menu Items which are set up as "Radio" Buttons.
When I select the appropriate in the UI of my running app from the selection, the Radio button switches just fine to the selected Item.  However I would like this selection to update (deselecting one Radio button and selecting the appropriate radio button of the handled menu item) when my ViewPart changes through other UI selection.   Currently my ViewPart updates, but the Radio buttons are on the same previous selection through the UI.
Is there a way in which I get access both Handled Menu Item's IDs and set the selection (one to false, the other to true) when the viewer is updated.
Image of design is attached below:
Hierarchy of the application model is as follows:

Thanks in advance,
Marv

A: You can use the model service to find menu items. Use something like:
@Inject
EModelService modelService;

@Inject
MApplication app;

List<MMenuItem> items = modelService.findElements(app, "menu item id", MMenuItem.class, Collections.emptyList(), EModelService.IN_MAIN_MENU);

Once you have the MMenuItem you can call the setSelected(boolean) method to change the selection.
To find a menu item which is in a Part menu use:
modelService.findElements(app, "menu item id", MMenuItem.class, Collections.emptyList(), EModelService.IN_PART);

(IN_PART argument instead of IN_MAIN_MENU).
You could also specify the MPart rather than the Application as the first argument to findElements which may speed up the search.
For menus as a child of a Tool Bar Item it appears that the model services cannot find these directly. However you can find the Tool Bar Item and look at the menu yourself:
List<MToolItem> items = modelService.findElements(app, "tool bar item id", MToolItem.class, Collections.emptyList(), EModelService.IN_PART);

MToolItem item = items.get(0);

MMenu menu = item.getMenu();

List<MMenuElement> children = menu.getChildren();

... search menu elements

A: I solved this by starting with MPart PartID and drilling down to the HandledMenuItems on which I wanted to set the Radio Button selections, then setting the selection property for each individual HandledMenuItem.
This can probably be refactored to be more concise, but I've left the code with each step to have the solution easier to read.
BTW, in every instance / combination of the EModelService methods, the list returned a size of 0.  So I'm not certain if that will work for what I'm trying to achieve.  The following does work, although I'm not certain it is the most efficient means.
I hope this helps others.
    // Get view part
    MPart viewPart = _partService.findPart("part_id");

    //  get list of all menu items from the Part
    List<MMenu> viewPartMenu = viewPart.getMenus();

    // Get list of ViewMenus from viewPartMenu there is only one View Menu so it will be index 0
    MMenu viewMenu = viewPartMenu .get(0);

    // Get list of MMenuElements from the viewMenu - the children in the view menu
    List<MMenuElement> viewMenuElements = viewMenu.getChildren();

    // This gets me to the 2 HandledMenuItems
    // Upper Most HandledMenuItem Radio Button is at viewMenuElements index 0.  This is cast to MHandledMenuItem
    MHandledMenuItem upperHandledMenuItem = (MHandledMenuItem) viewMenuElements.get(0);

    // Set Selection
    upperHandledMenuItem.setSelected(false);

    // Lower Most HandledMenuItem Radio Button is at viewMenuElements index 1.  This is cast to MHandledMenuItem
    MHandledMenuItem lowerHandledMenuItem = (MHandledMenuItem) viewMenuElements.get(1);

    // Set selection
    lowerHandledMenuItem.setSelected(true);


text:
Q: Auto adjust background color to cover whole container I need to responsively show several images in a block container, how can I auto adjust and fill the whole container with specific color when screen size being narrowed. Below is the source code of HTML and CSS, demo can be viewed from http://jsfiddle.net/yckelvin/54v27shp/ Only the first few line are filled with the background-color, how can I fill the rest.

Smile Smile

        { rest content omitted }

Footer Footer

CSS
#container {
    background-color: rgba(0, 255, 0, 0.2);
    width:calc(100%);
    height: 100%;
    display: block;
}

img {
    width: 100px;
}

li {
    display: table-cell;
    float: left;
    padding: 10px;
}

A: The problem is that you don't clear your floats on your li tags. One way to fix that is to add clearfix snippet to your #container.
#container:after {
   content: " ";
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

You can read more at - What is a clearfix?
And you can check the working code here - http://jsfiddle.net/54v27shp/3/

A: You can add overflow:hidden to your container.
#container {
    background-color: rgba(0, 255, 0, 0.2);
    width:calc(100%);
    height: 100%;
    overflow:hidden;
}

Or set the display of your container to table or inline-block
#container {
    background-color: rgba(0, 255, 0, 0.2);
    width:calc(100%);
    height: 100%;
    display:table; // display: inline-block;
}

A: Add display: inline-block; to #container
JSFiddle - DEMO
#container {
    background-color: rgba(0, 255, 0, 0.2);
    width:calc(100%);
    height: 100%;
    display: inline-block; /* or float: left; */
}

OR:
Add display:inline-block; to li and remove display:table-cell; and float:left; from li
JSFiddle - DEMO
li {
    display: inline-block;
    padding: 10px;
}

A: JS Fiddle
add a clear div after closing of
 the issue is because of float left for

.clear{
  clear:both;
}

A: The problem you are experiencing is because the content of the #container is floated.
After your end UL-tag insert the following code:

Making the result:

    { rest content omitted }


text:
Q: Xampp not working after updating on mac os big sur 11.4 The error message keep poping up when click the start button... Im using a macbook air M1, MacOs Big Sur 11.4
cannot calculate MAC address: Using fd 9 for I/O notifications
hv_vm_create HV_ERROR (unspecified error)

A: Try downgrading from 8.0.8 to 7.3.29 / PHP 7.3.29, that should do the trick.


text:
Q: ElasticSearch filtering with geo distance I'm attempting to filter data with both geo distance and fields like 'has_cctv' or 'has_instant_bookings'.
{
  "query" : {
    "filtered" : {
      "filter" : {
        "geo_distance": {
          "distance": 10000,
          "lat_lng": {
            "lat": "51.5073509",
            "lon": "-0.1277583"
          }
        }
      }
    }
  }
}

I've tried many combinations of filtering using terms but can't seem to get past errors. For example:
{
  "query" : {
    "filtered" : {
      "filter" : {
        "terms": [
          {"term": {"has_cctv": 1}}
        ],
        "geo_distance": {
          "distance": 10000,
          "lat_lng": {
            "lat": "51.5073509",
            "lon": "-0.1277583"
          }
        }
      }
    }
  }
}

This gives me '[terms] filter does not support [has_cctv] within lookup element'. Could this be a problem with my query, or a problem with the way the data is stored?

A: Or you could use an and filter and group the two filters together. And a comparison between bool filter and and/or/not filters: http://www.elasticsearch.org/blog/all-about-elasticsearch-filter-bitsets/
{
  "query": {
    "filtered": {
      "filter": {
        "and": {
          "filters": [
            {
              "term": {
                "has_cctv": "1"
              }
            },
            {
              "geo_distance": {
                "distance": 10000,
                "lat_lng": {
                  "lat": "51.5073509",
                  "lon": "-0.1277583"
                }
              }
            }
          ]
        }
      }
    }
  }
}

A: Here goes the correct query:
POST _search
{
   "query": {
      "filtered": {
         "query": {
            "term": {
               "has_cctv": {
                  "value": 1
               }
            }
         },
         "filter": {
            "geo_distance": {
               "distance": 10000,
               "lat_lng": {
                  "lat": "51.5073509",
                  "lon": "-0.1277583"
               }
            }
         }
      }
   }
}

Just make sure that lat_lng is stored as geo_point
Thanks
Bharvi

A: Two errors.
As you have more than one filter, you need to add a bool filter and put each filter in a must clause.
Then you don't need a terms filter here but a term filter.


text:
Q: finding if two binary quadratic forms represent the same integers I am currently working with quadratic forms for a given discriminant D;
to get all primitive forms (one for each equivalence class) I found this website : http://www.numbertheory.org/php/classnoneg.html
For instance for the case D=-23, the three primitive forms are given by :
(1,1,6), (2,1,3), (2,-1,3); and I know that the two last ones represent the same integers.
I need now to work with some discriminant such that the class number is larger (h(D)=4,5..) and I need to know if two forms represent the same integers.
Would you know of a similar software where I can check this?
Thanks.

A: EDIT: most of what a beginner might need to know is in the first chapter of David A. Cox, Primes of the Form $x^2 + n y^2,$ which is still in print. I got more information, especially about Gauss composition, Pell equations, and how to write correct computer programs for everything, in Duncan A. Buell, Binary Quadratic Forms. Similar to this is Binary Quadratic Forms by  J. Buchmann and U. Vollmer, although it strikes me as being a little harder to read; it is still in print though. My favorite, Buell, is available used but perhaps a bit pricey.
The bad news is that this is pretty much solved by VOIGHT, item number 6, which appeared in Math. Comp. about 2007.
On the other hand, you are welcome to my C++ program for this, sample output below. As you can see, the program finds the whole class group and then finds the principal genus ("squares"). I can usually figure out the other genera myself, and always can if there are just one or two genera. Hmmm...I also have programs that show me the numbers represented by a positive form, up to a bound I type in, different program for just primes, third program for primitively represented numbers.

jagy@phobeusjunior:~/old drive/home/jagy/Cplusplus$ ./classGroup
Absolute value of discriminant?
56
  class  number  4

 all
( 1, 0, 14)
( 2, 0, 7)
( 3, -2, 5)
( 3, 2, 5)

 squares
( 1, 0, 14)
( 2, 0, 7)

 fourths
( 1, 0, 14)

Discriminant        -56     h :    4     Squares :    2     Fourths :    1
jagy@phobeusjunior:~/old drive/home/jagy/Cplusplus$

jagy@phobeusjunior:~/old drive/home/jagy/Cplusplus$ ./classGroup
Absolute value of discriminant?
47
  class  number  5

 all
( 1, 1, 12)
( 2, -1, 6)
( 2, 1, 6)
( 3, -1, 4)
( 3, 1, 4)

 squares
( 1, 1, 12)
( 2, -1, 6)
( 2, 1, 6)
( 3, -1, 4)
( 3, 1, 4)

 fourths
( 1, 1, 12)
( 2, -1, 6)
( 2, 1, 6)
( 3, -1, 4)
( 3, 1, 4)

Discriminant        -47     h :    5     Squares :    5     Fourths :    5
jagy@phobeusjunior:~/old drive/home/jagy/Cplusplus$


text:
Q: Grails tag not closed only detected when building WAR I forgot to close a <g:link> tag in one of my GSP files.
The application runs perfectly with grails run-app, but when I try to execute grails war, it says the tag is not closed.
What happens when building the WAR file that is different than when running the app?
Edit:
Due to lukelazarovic's answer, I looked a bit more in detail and found that the unclosed tag came form the layout GSP in a plugin that my app uses. The run-app command seems to be compiling only my GSP files and not the plugins'. So the compilation errors in layout GSPs come to light when you execute grails war.

A: When you run the app using grails run-app, GSPs are compiled on the fly when you access it.
So you would see the error if GSP with unclosed tag is accessed.
In case of grails war, all GSPs have to be compiled and put into resulting war file, therefore any error that prevents any GSP to be compiled is revealed.


text:
Q: Como criar uma trigger que armazena uma tupla em uma tabela quando outra tabela é atualizada? Preciso criar uma trigger para armazenar numa tabela de histórico as informações do empregado todas as vezes que ocorrer uma alteração de salário. A trigger deverá fazer a atualização do histórico, somente quando o salário for alterado.
A trigger que eu criei faz isso, porém preenche a tabela HISTORICO com outras tuplas iguais, diferindo apenas o atributo idEmpregado, ou seja, como se tivesse alterado o salário de todos os empregados.
Segue abaixo minha tentativa (deixei comentadas minhas tentativas para corrigir o erro).
SET TERM ^ ;

CREATE TRIGGER TRG_HISTORICO_UPDATE FOR EMPREGADO
 ACTIVE
 AFTER UPDATE
 POSITION 0
AS
BEGIN
    if(old.SALARIO != new.SALARIO) then
    begin
        if(old.SALARIO < new.SALARIO) then
        begin
            INSERT INTO HISTORICO (username, dataHoraLancamento, IDEMPREGADO, salarioAnterior, salarioAtual, situacao)
            SELECT  current_user, current_timestamp, IDEMPREGADO, old.SALARIO, new.SALARIO, 'Aumento'
            FROM    EMPREGADO;
            --WHERE   EMPREGADO.IDEMPREGADO = IDEMPREGADO;

            --DELETE FROM HISTORICO H WHERE H.IDEMPREGADO != IDEMPREGADO;

            --UPDATE HISTORICO H
            --SET H.IDEMPREGADO = IDEMPREGADO
            --WHERE H.DATAHORALANCAMENTO = current_timestamp;
        end
        else if(old.SALARIO > new.SALARIO) then
        begin
            INSERT INTO HISTORICO (username, dataHoraLancamento, IDEMPREGADO, salarioAnterior, salarioAtual, situacao)
            SELECT  current_user, current_timestamp, IDEMPREGADO, old.SALARIO, new.SALARIO, 'Redução'
            FROM    EMPREGADO;
            --WHERE   EMPREGADO.IDEMPREGADO = IDEMPREGADO;

            --DELETE FROM HISTORICO H WHERE H.IDEMPREGADO != IDEMPREGADO;

            --UPDATE HISTORICO H
            --SET H.IDEMPREGADO = IDEMPREGADO
            --WHERE H.DATAHORALANCAMENTO = current_timestamp;
        end
    end
END^

SET TERM ; ^

Agradeço desde já qualquer ajuda.

A: Acho que não é necessário o Select na tabela Empregado já que todos os valores para o Insert estão disponíveis, e acho que utilizando um Case é possível utilizar apenas um Insert:
if(old.SALARIO != new.SALARIO) then
begin
    INSERT INTO HISTORICO
        (username,
         dataHoraLancamento,
         IDEMPREGADO,
         salarioAnterior,
         salarioAtual,
         situacao)
    VALUES
        (current_user,
         current_timestamp,
         old.IDEMPREGADO,
         old.SALARIO,
         new.SALARIO,
         case when old.SALARIO < new.SALARIO then 'Aumento' else 'Redução' end);
end

Se por acaso for necessário o Select em alguma tabela, adicione um filtro para relacionar o resultado com a linha alterada utilizando os prefixos old ou new.


text:
Q: Does fewer bit representation of data improve training time of machine learning models? In a lot of notebooks on kaggle I see methods used to reduce memory usage of data, for example converting int64 columnns to int32.
Why do we want to reduce the memory usage if the data can fit in the memory? Does it make machine learning models train faster on the data ?

A: Yes. In a lot of models there will be numerous computations involving feature vectors.
For example in a MLP, we would do a weighted sum of the feature representations to produce output in each neuron .
Computations are much faster if feature vector components are 32 bit in comparison with 64 bit representations.
Let me illustrate with a simple example :
import timeit

mult64 = """
import numpy as np
arr64 = np.int64([3,4,5])
arr64*arr64
"""

mult32 = """
import numpy as np
arr32 = np.int32([3,4,5])
arr32*arr32
"""

mult64_time = timeit.timeit(mult64, number=100)/100
mult32_time = timeit.timeit(mult32, number=100)/100

print(mult64_time)
print(mult32_time)

Gives me the result as below. As can be seen, the time taken to do a simple multiplication on CPU is way faster for int32 than int64. Have generally found this transformation useful to save training time/prediction time.
0.00086965738
1.7849500000000074e-06


text:
Q: jQuery: Retrieving the id of DOM on click only returns id from first click I have the following HTML, which is appended sometime after the page is loaded.
I have the following JS, which I am attempting to retrieve the id of the clicked label or rather the input id that it is associated with.

function answerSelect(){
     $("body").on("click", "li label", function(){
      let selectedAnswer = $("input").attr("id");
      console.log(selectedAnswer);
     })
}
answerSelect();

    <form>

This is a question?

          <input id="first" type="radio" name="answer-choice" required>
          1

          <input id="second" type="radio" name="answer-choice">
          2

          <input id="third" type="radio" name="answer-choice">
          3

          <input id="fourth" type="radio" name="answer-choice">
          4

      <button class ="start submit btn">
Submit
</button>
    </form>

Currently, when inspecting the console within Chrome, it looks like it doesn't matter which label that I click; the console only prints the id "first" which is the first li. How can I make it so it retrieves the corresponding li clicked?

A: Use a change listener instead (so that both clicks on the input and clicks on the label will trigger the listener), and then use the :checked psuedo-selector to get to the input that's checked:

$("body").on("change", "li > input", function(e) {
  let selectedAnswer = $("input:checked").attr("id");
  console.log(selectedAnswer);
})

  <form>

This is a question?

        <input id="first" type="radio" name="answer-choice" required>
        1

        <input id="second" type="radio" name="answer-choice">
        2

        <input id="third" type="radio" name="answer-choice">
        3

        <input id="fourth" type="radio" name="answer-choice">
        4

    <button class="start submit btn">
Submit
</button>
  </form>

A: modify answerSelect() method:
function answerSelect() {
  $("body").on("click", "li input", function(e) {
    let selectedAnswer = e.target.id;
    console.log(selectedAnswer);
  });
}

A: Well if your Elelemt ordering doesnt change this will serve the purpose
$("body").on("click", "li label", function(){
        let selectedAnswer =$(this).prev().attr("id");
        console.log(selectedAnswer);
 });

Working Fiddle

A: replace your below code:
function answerSelect(){
    $("body").on("click", "li label", function(){
        let selectedAnswer = $("input").attr("id");
        console.log(selectedAnswer);
    })
}

with,
$(document).on("click", "input[type='radio']", function(){

        let selectedAnswer = $("input").attr("id");
        console.log(selectedAnswer);
    })


text:
Q: Handle Select().CopyToDatatable Is there any way to handle this method to not crash if there is no results.
Lets say i have something like this
  Dim _dtTemp As New DataTable
  _dtTemp = dtMain.Select("Nivo = 0").CopyToDataTable

     If _dtTemp.Rows.Count > 0 Then
       For Each row In _dtTemp.Rows
         ....
       Next
     End If

Every time when dtMain dont have results to query it crash and say's something like There is no rows .... and my app crash. How to handle it

A: Where does it crashes exactly? I would put a few breakpoints to find this out first.
If at the If statement, just write the condition:
If _dtTemp.Rows.Count == 0 Then
' nothing
elseIf _dtTemp.Rows.Count > 0 Then
'and carry on

A: You can't do this all on one line. Just assign the return value to the array of DataRow, test if you have some rows and finally call the CopyToDataTable
Dim rows As DataRow() = dtMain.Select("Nivo = 0")
if rows.Length > 0 Then
    Dim newTable = rows.CopyToDataTable()
    ......


text:
Q: Multidimensional integer In Excel VBA code, when defining the variables, what does it enable the code to do to define an integer variable with multiple ranges of values?
For example:
Dim iCount(a to b, x to y) as Integer

A: There are two types of Arrays in VBA. Fixed arrays where the limits are constants defined as
Dim A(1 to 100) as Long

and dynamic arrays defined as
N = 100
Dim A() as Long
ReDim(1 to N)
...
Erase A

Similarly for multi dimensional arrays
Dim A() as Long
ReDim(1 to N, 1 to M)
...
Erase A

Now for an example taking an array B of unknown size, and creating an array A by adding 1 to each value.
' Given a 1D array B() make a copy into A()
Dim A() as Long
Dim i_low as Long, i_high as Long, i as Long
' Discover array bounds of B
i_low = LBOUND(B,1) : i_high = UBOUND(B,1)
' Declare array size
ReDim A(i_low to i_high)
For i=i_low to i_high
  ' Calculate each element of the new array
  A(i) = B(i) + 1
Next i


text:
Q: drupal 6 programmatically log user in I'm trying to log in a user as part of a form submit, but why is the following not working:
$user = db_fetch_object(db_query("SELECT * FROM users WHERE mail = '%s' AND pass = '%s'", $mail, md5($pass)));

if ($user) {
    // Authenticate user and log in
    $params = array(
      'name' => $user->name,
      'pass' => trim($user->pass)
    );

    // Authenticate user
    $account = user_authenticate($params);
}

if I dump $user I can see the correct values, but if I dump the account it's empty.

A: You are passing the hashed password to ´user_authenticate()´, while the function expects the clear password (it will hash it itself indirectly when loading the account via ´user_load()´).
So changing your $params array declaration to
$params = array(
  'name' => $user->name,
  'pass' => $pass
);

should make your example work.

BTW, you could use user_load() yourself to avoid querying the database directly:
$user = user_load(array('mail' => $mail, 'pass' => trim($pass), 'status' => 1));

(The 'status' => 1 will restrict results to active users - you can leave that out, of course, if you really want to allow log ins to disabled accounts ;)


text:
Q: Can I migrate multiple SQL DBs into a single Babelfish instance and keep them segregated for different users? I am migrating multiple SQL DBs (say A and B) to a single Babelfish instance.
I have SQL instance A with tables x, y and z and instance B with tables x, y and z.
I want Babelfish to have some way to have them coexist as A.x, A.y, A.z, B.x, B.y and B.z.
The original idea was to prefix the table names (so A_x, A_y, etc.) but this is untenable because of the app changes required, so I need some way to make it transparent to the application as long as the connection points to A or does a "USE A" at the start.

A: Babelfish lets you migrate databases A and B while retaining the SQL server database structure as well as the references A.dbo.x, B.dbo.x , etc. (note that cross-DB queries with 3-part object names are not yet currently supported outside the current database, but these are in the works).  When you run "USE A" and then do "SELECT * FROM x", you'll touch A.dbo.x. When you do "USE B" first, you'll touch B.dbo.x.
So when you run the DDL for creating databases A and B against Babelfish, you'll get basically the same as what you had in SQL Server and there is no need to change any syntax (again, assuming cross-DB queries are not currently needed).
Now, if your question is how to merge databases A and B into a single database, then that is not different from how you would do that in SQL Server itself. In this case I would recommend actually performing that merge in SQL Server, then reverse-engineering  the resulting SQL Server database, and running that script against Babelfish to recreate that database.


text:
Q: Making a Web Page Zoom-Proof (Preventing Compression/Expansion of Elements) Is there a simple way to make sure all elements on a page remain in the same exact position regardless of how much one zooms in/zooms out? To clarify, I  don't want the elements compressing as one zooms in and expanding as one zooms out. A good example of what I'd prefer is stack itself! Try zooming in/out. The element's position relative to the original screen size remain totally unchanged - only the user's perspective has changed.

A: I have a very simple solution that worked for me. I just put a minimum width attribute to the main element of the HTML page and so now whenever someone zooms in beyond that minimum width value it does not affect the main body as it cannot be any smaller than that.Take a look at these images to see the result
 This is what it looked like before..
Then I inserted the min-width into the #main which is the id corresponding to the main tag in the html

#main {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  min-width: 1400px;
}

And the result is this
 After adding the CSS code
As you can see I have zoomed in a lot into the browser and where in the above image there are elements overlapping with each other,now  they stop coming closer after you zoom in a certain amount.
Hope this helps!


text:
Q: Dependency relationship I have a question on dependency relationship in a class diagram. Is it correct to show that a class has an attribute of an interface type by specifying a dependency relationship? Or  this can be done with association only? I've read that a dependency relationship is used only for method's parameters or local variables.

A: An association is just a particular form of dependency. So, to answer your question, yes it is correct (valid) to represent an association as a dependency, however using an association is more accurate.
In his book "UML Distilled", Martin Fowler defines dependencies like that:

A dependency exists between two elements if changes to the definition of one element [...] may cause changes to the other [...]. With classes, dependencies exist for various reasons: one class sends a message to another; one class has another as part of its data; one class mentions another as a parameter to an operation.

A: From Wikipedia

A dependency in the Unified Modeling
  Language exists between two defined
  elements  if a change to the
  definition of one may result in a
  change to the other. In UML this is
  indicated by a dashed line pointing
  from the dependent (or client) to the
  independent (or supplier) element.

So per the definition, it makes sense to show that a class has an attribute of an interface type by specifying a dependency relationship. I'm not 100% sure though.

A: It is not forbidden in UML therefore it is allowed :-)


text:
Q: Learning Swift and Trying to Create a String Loop in a Label In Swift I'm trying to loop an array of Strings in a label automatically on a  1-2 second interval.
For example, I have the following Strings in an array:

Red
Blue
Green

I want the label to scroll through these.
For a better idea, here is what I currently have;
import UIKit

class ViewController: UIViewController {

    @IBOutlet var Label: UILabel!

    @IBOutlet var Label2: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func RandomWord() {
        var RandomWord = arc4random_uniform(5)
        switch (RandomWord) {
        case 0:
            Label.text = "Blue"
            if Label.text == "Blue" {
                Label.textColor = UIColor.blueColor()
            }
            break;
        case 1:
            Label.text = "Red"
            if Label.text == "Red" {
                Label.textColor = UIColor.redColor()
            }
            break;
        case 2:
            Label.text = "Green"
            if Label.text == "Green" {
                Label.textColor = UIColor.greenColor()
            }
            break;
        case 3:
            Label.text = "Yellow"
            if Label.text == "Yellow" {
                Label.textColor = UIColor.yellowColor()
            }
            break;
        case 4:
            Label.text = "Orange"
            if Label.text == "Orange" {
                Label.textColor = UIColor.orangeColor()
            }
            break;
        default:
            break;

        }
    }

    @IBAction func RandomNumber() {
        var RandomNumber = arc4random_uniform(100)
        Label2.text = String(RandomNumber)
    }

}

I want to remove the need for a button and just have the label loop through the strings. Any ideas on the best solution?

A: This kind of text scrolling / crawling functionality is not built into UILabel automatically.  You could implement it yourself (which wouldn't be the most trivial thing), or you could take advantage of the work that somebody else did in some Open Source project.
For example, I just found MarqueeLabel which does have a Swift implementation you can use.
Try adding that to your project and see if that takes care of your need.

A: If I understand your question correctly, you're looking for something like the following where on a timed interval, a random color is selected an used to populate the text and text color of a label:
struct ColorData {
    let name: String
    let value: UIColor
}

class MyViewController: UIViewController {

    let data = [
        ColorData( name: "Blue", value: UIColor.blueColor() ),
        ColorData( name: "Red", value: UIColor.redColor() ),
        ColorData( name: "Green", value: UIColor.greenColor() )
    ]

    @IBOutlet weak var label: UILabel!

    var timer = NSTimer()

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear( animated )

        self.timer = NSTimer.scheduledTimerWithTimeInterval( 1.0, target: self, selector: "update", userInfo: nil, repeats: true )
    }

    func update() {
        let randomIndex = Int(arc4random() % UInt32(self.data.count))
        let colorData = data[ randomIndex ]
        self.label.text = colorData.name
        self.label.textColor = colorData.value
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear( animated )

        // Don't forget to invalidate, otherwise this instance of `MyViewController` will leak
        self.timer.invalidate()
    }

}