text:
Q: How to convert a multi dimensional HASH into a CSV file in PERL? Hello I'm retrieving data from a XMLRPC API via PERL and end up with an HASH (actually I believe the correct term here would be array within an array) which I partially want to convert into a CSV file.
As a basic overview here is what I am doing:
my $server = XMLRPC::Lite
    ->proxy('https://myhost/api');
my $session = $server->login(foo)
    ->result;
my @tempArr = $server->call(foobar)->result;

Afterwards a:
print @tempArr;

results in:
HASH(0x23c0330)

If I dump the HASH content via Data::Dumper:
print Dumper(\@tempArr);

then I receive the following structure of the array:
$VAR1 = [
      {
        'table' => [
                   [
                     'abc',
                     'def',
                     'ghi',
                     'jkl'
                   ],
                   [
                     'abc',
                     'def',
                     'fed',
                     'cba'
                   ],
                 ],
        'columns' => [
                     'field1',
                     'field2',
                     'field3',
                     'field4',
                   ]
      }
    ];

Now I would like to write all items from 'table' into a CSV formated file. So basically in this case:
abc,def,ghi,jkl
abc,def,fed,cba

I was playing around with Text::CSV::Slurp for a while, but didn't really understand how to handle it for arrays within arrays:
my $csv = Text::CSV::Slurp->create( input => \@tempArr);
my $file = "/path/output.csv";
open( FH, ">$file" ) || die "Couldn't open $file $!";
print FH $csv;
close FH;

I only came up with a csv file of the following content:
columns,table
ARRAY(0x23c01b0),ARRAY(0x25a944c)

Any suggestions on how to approach this issue would be appreciated. Currently I've decided to go back and read about arrays and hashes in PERL in general, as I seem to lack a lot of fundamental understanding on the matter.

A: Text::CSV::Slurp operates on arrayrefs of the following format (both for how it parses and for what it takes to write back to CSV:)
$VAR1 = [ { field1 => 'abc',
            field2 => 'def',
            field3 => 'ghi',
            field4 => 'jkl',
          },
          { field1 => 'abc',
            field2 => 'def',
            field3 => 'fed',
            field4 => 'cba',
          },
    ];

Transform your response into that type of format.
As it operates now, Text::CSV::Slurp is treating the table and columns first level keys as the data field names, then stringifying the contained arrayrefs and using them as a value.

A: It seems that result() is returning a hash reference not an array, so change that line to:
my $result = $server->call(foobar)->result;

Then transform the result into the format required by Text::CSV::Slurp
my $cols = $result->{'columns'};
my $rows = $result->{'table'};
my @idx  = 0 .. @$cols - 1;
my @array_of_hashes;
for my $row (@$rows) {
    my %hash = map { $cols->[$_] => $row->[$_] } @idx;
    push(@array_of_hashes,\%hash);
}
my $csv = Text::CSV::Slurp->create(
    input => \@array_of_hashes,
    field_order => $cols
);

A: This will produce your csv file directly from your data structure:
for my $arr (@{$$VAR1[0]{'table'}}) {
    my $last_elem = pop(@$arr);
    for my $elem (@$arr) { print("$elem,"); }
    print("$last_elem\n");
}


text:
Q: Chat tab not appearing on Microsoft Teams Browser version I have created an event for Micrsoft Teams via graph API. Sharing the list of steps below:
Create event method:

*

*I have created event.(online meeting)

*Event appeared on the Teams calendar

*Participant joined the call.

*Ended the meeting.

Problem: Chat Tab for the meeting is available for the desktop version with attendance report but the same chat tab could not be seen in web version. How do I get this right?
Chat Tab in Desktop version
Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Norm equivalent with supremum norm Let's consider functional $$\|f\| := \sum_{n=1}^\infty |f(q_n)|2^{-n}$$ for $f \in C([-1, 1])$ and $(q_n)$ is a sequence of rational numbers in $[-1, 1]$ i.e.  $\mathbb{Q} \cap [-1,1] = \{q_n:n \in \mathbb{N}\}$
I want to prove that this norm is not equivalent with supremum norm. It's obvious that
$$\exists_{C>0}:\|f\| \le C\|f\|_\infty$$
We just need to take $C = 1$ (it's because $\sum_{n=1}^\infty2^{-n} = 1$).
However I want to find counterexample of second inequality i.e. I want to prove that
$$\forall_{c>0}\exists_{f \in C([-1, 1])}: \|f\| < c \cdot \|f\|_\infty$$
I'm not sure which exactly $f$ should I pick. I was trying to pick $f(q_n) = q_n$, $f(q_n) = \frac c 2$, $f(q_n) = \frac c 2 + 1$ but each one of them is not suitable for our problem. Do I have good intuition that this inequality does not hold?
EDIT
I'm not sure if I understood correctly or I do something wrong but if we fix some $n_0 \in \mathbb{N}$ and define $f(q_n) = 1$ for $n \le n_0$ and $f(q_n) = 0$ for $n >n_0$, we obtain:
$$\|f\| = \sum_{n=1}^{n_0} 2^{-n}  = \frac 1 2 \cdot \frac{1 - (\frac{1}{2})^{n_0}}{1 - \frac 1 2} = 1 - (\frac 1 2)^{n_0}$$ And now $\|f\| < c \cdot \|f\|_\infty$ is in form $$1 - (\frac{1}{2})^{n_0} < c$$
which is not true for any $c>0$. Where is mistake in my justification?

A: For the other direction, choose $f$ such that $f(q_n)=1$ and $f(q_i)=0$ for all $i<n$.

A: For any $n$ there exists a continuous function $f$ such that $0 \leq f \leq 1$, $f(x)=1$ for some $x$ and $f(q_i)=0$ for $ 1\leq i \leq n$. Note that $\|f\| \leq \sum\limits_{k=n+1}^{\infty} \frac  1 {2^{k}}$. Can you finish?


text:
Q: How to write lossless WebP files with PerlMagick I'm trying to convert PNG files to lossless WebP in Perl with Graphics::Magick.  Command line for that is:
$ gm convert in.png -define webp:lossless=true out.webp

My Perl code looks something like that:
use Graphics::Magick;

my $image = Graphics::Magick->new();
$image->Read("in.png");
my $image_data = $image->ImageToBlock(magick => "webp");
print $out_fh $image_data;

This code writes lossy WebP files perfectly, but how can I express the "-define" thing in terms of Perl API?
Thanks,
Update: looks like I need to call AddDefiniton API function (http://www.graphicsmagick.org/api/image.html#adddefinition).  Looks like it's not exported via Perl API as of now.

A: I know it is of no help to you, but for those interested in how to do it in PHP, here is how:
$im = new \Gmagick($src);
$im->setimageformat('WEBP');

// Not completely sure if setimageoption() has always been there, so lets check first.
if (method_exists($im, 'setimageoption')) {
    $im->setimageoption('webp', 'lossless', 'true');
}
$imageBlob = $im->getImageBlob();
$success = @file_put_contents($destination, $imageBlob);

For more webp options, check out this code


text:
Q: log4j2 logs are not being written into file I'm using log4j2 and I have the following log4j2.xml file:
log4j2.xml Configuration File(below):
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="PropertiesConfig">
    <Properties>
        <Property name="baseDir">log/</Property>
        <Property name="logName">report</Property>
    </Properties>

    <Appenders>
        <Console name="Console"
                 target="SYSTEM_OUT"
                 immediateFlush="true">
            <PatternLayout pattern="[%highlight{%-5level] %d %c{1}.%M() - %msg%n}" />
        </Console>

        <RollingFile name="RollingFile"
                     fileName="${baseDir}${logName}.log"
                     filePattern="${baseDir}${logName}_%d{yyyy-MM-dd}.log"
                     immediateFlush="false">
            <PatternLayout pattern="[%-5level] %d %c{1}.%M() - %msg%n" />
            <Policies>
                <OnStartupTriggeringPolicy />
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console" level="info" />
            <AppenderRef ref="RollingFile" level="warn" />
        </Root>
    </Loggers>
</Configuration>

My project is a Web Application using Java. If I use the log system from a Serlvet, like:
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;

public class MySevlet {
   private static final Logger LOGGER = LogManager.getLogger(MyServlet.class);

   protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      LOGGER.warn("hello?");
      LOGGER.error("hello?");
      //...more stuff here...
   }
   //...more stuff here...
}

Project folder structure (below):

The problem I have is I can see the console logs, but no file is written, so Rolling file appender doesn't work.
If I run a local program (not using Servlets), both console and rolling file appender works.
Any idea why is this happening?
Thank you!
PS: I'm using Netbeans 8.2 + Tomcat 8.0


text:
Q: cannot insert into android sqlite database when creating database I created a SQLite database and I want to insert some initial data into it. so I put the insert "into query" in the "onCreate" method.
but it does not insert any values into database and it is empty after create!
here is my code:
package com.example.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_GAME_LIST = "steps";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_STATUS = "status";
  public static final String COLUMN_HELP_COUNT = "helpCount";
  public static final String COLUMN_EAREASED = "earased";
  public static final String COLUMN_SPEED = "speed";

  private static final String DATABASE_NAME = "earaser.db";
  private static final int DATABASE_VERSION = 1;

  // Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_GAME_LIST + "(" + COLUMN_ID
      + " integer, "
      + COLUMN_STATUS
      +" integer, "
      + COLUMN_HELP_COUNT
      +" integer, "
      + COLUMN_EAREASED
      +" string, "
      + COLUMN_SPEED
      +" integer"
      + " );";

  public MySQLiteHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase database) {
      database.execSQL(DATABASE_CREATE);

      database.execSQL("INSERT INTO "+TABLE_GAME_LIST+"("+COLUMN_ID + ","
                + COLUMN_STATUS + ","
                        + COLUMN_HELP_COUNT + ","
                                + COLUMN_EAREASED + ","
                                        + COLUMN_SPEED + ") VALUES(14, 1, 2, "+"third"+", 5)");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      Log.w(MySQLiteHelper.class.getName(),
        "Upgrading database from version " + oldVersion + " to "
            + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_GAME_LIST);
        onCreate(db);
  }

}

A: There are syntax errors in the SQL, such as string values that need to be 'quoted', such as third.
Since you didn't get an exception, the SQL wasn't run. Uninstall your app so that the old version of the database gets removed and onCreate() is run again. When is SQLiteOpenHelper onCreate() / onUpgrade() run?


text:
Q: Uploading shapefile onto Garmin GPS, and displaying it over basemap? I have a roads shapefile layer in ArcMap and I want to be able to view it on my Garmin64st. Ideally, it would be overlaid on a basemap so I would always be able to see it. It seems like that means I need to convert my .shp file to .img.
I'm finding various programs that claim to help with some step of this, but some of them are really expensive, and none of the free ones I've tried have gotten me to .img so far. I did download an ArcGIS Toolbox which converts .shp to .gpx, but I haven't been able to find a way to convert that to .img for free yet.
Am I missing something?
Does anyone know a simple and free way to convert a .shp to be viewed in a Garmin GPS like I've described?
If I absolutely must purchase a program, do you know of one that works?

A: I just wanted to let anyone know the best solution I found to this problem.
I got my roads uploaded through DNR GPS, which is the best program I've seen for uploading things to Garmin GPS. However, my original roads layer was much too large for it to process. It doesn't interpret roads as lines, but rather as "tracks" made up of hundreds of thousands of points, even in my relatively small area.
I just clipped my roads down to the ones I wanted most, in the most remote places not likely to be covered in the Garmin basemap. Then I split that into three separate files to make them even smaller and easier to process. Then I uploaded those one by one to the GPS through DNR GPS.
In the Garmin, they get saved as tracks, which can easily be turned on and shown on the map. I've since turned the GPS off and turned it back on, and the roads are still displayed.


text:
Q: Attempting To Find A Way To Block Internet Explorer Users From Opening My Page While I Fix Issues I've got a site that I just published and have just found a bunch of compatibility problems with Internet Explorer (surprise surprise!). I was on a time crunch and would like to keep the site up since it looks great on all other browsers but prevent people running Internet Explorer to see the site and give them a default splash page (if possible) while I work on the compatibility issues..
Is there a way to do this? I thought about using the conditional statements for the style sheets and maybe editing it that way but I thought I'd see if anyone knew of an easy way to do it.

A: you could use IE-only conditionals and display a overlay over the whole page, see here for conditionals . In your ie-only code you'd display something like this :
<!--[if IE]>
   <div style='position:absolute;top:0px;left:0px;width:100%;height:100%;background:white;padding-top:50%;text-align:center;'>
          <!-- add more styling or split it up in some separate stylesheet-->
          This site is currently disabled for IE users
   </div>
<![endif]-->

A: Off the top of my head, it would seem to be that you're going to have to query the client's browser user agent and redirect/load the appropriate page/CSS as per the result.  Seems like a conditional statement is the way I would go about it.

A: What you're looking to do is called "browser sniffing" and is generally thought of as a not-very-elegant way to attack this kind of problem. But it is useful.
Quirksmode has arguably the best library for this. You stick the big object below into a script and query it using these three attributes:
BrowserDetect.browser
BrowserDetect.version
BrowserDetect.OS

Full object source (see Quirksmode for more information):
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Chrome",
            identity: "Chrome"
        },
        {   string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            prop: window.opera,
            identity: "Opera",
            versionSearch: "Version"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {       // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {       // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
               string: navigator.userAgent,
               subString: "iPhone",
               identity: "iPhone/iPod"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();

A: place a ie detection before  like
this is for ie 6
<!--[if lte IE 6]>
<link href="css/disposeIE6.css" rel="stylesheet" type="text/css" />
<![endif]-->

then inside css/dispose.ie.css
body{
display:        block; width:1024px; height:768px;
background:     transparent url(../disposeIE6.jpg) 50% 50% no-repeat;
}

then make a 'disposeIE6.jpg' with your message. this will cover the site at the dimensions 1024px X 768px

A: If you are running Apache you could do this with a single .htaccess file in the root.
1) Make and IE.html file. -  saying something like "This site is current undergoing work, please try again later."
2) And create a .htaccess file in the root of your site and paste the text below.
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} "MSIE 6"  [OR]
RewriteCond %{HTTP_USER_AGENT} "MSIE 7"  [OR]
RewriteCond %{HTTP_USER_AGENT} "MSIE 8"  [OR]
RewriteCond %{HTTP_USER_AGENT} "MSIE 9"
RewriteRule (.*) IE.html


text:
Q: What are the different ways to say "I'm joking"? I can't recollect if I've ever heard a native speaker say, "I'm joking".
The ones I can remember are:

*

*I'm messing with ya

*I'm just messing/goofing around
What are the other popular ways to convey the same?

A: "I'm joking" (or "I'm only joking") is extremely common and probably the most idiomatic way to express this.
There are probably countless ways to say the same thing, most suggestions would be slang and these may be particular to dialects of English (British English, American English etc) or even more remotely to regional dialects.

*

*I'm only teasing

*I'm only fooling with you

*Psyche!

*I'm merely jesting

*Gotcha!

*Fooled you!

*Fished in!

This is by no means an exhaustive list.


text:
Q: Receive Location Files are picked up but not removed I have a receive Location which points to SFTP Port, the Files in the ports are picked up and sent to the destination(Send Port). But the files which are picked up still exists in the receive location and doesn't gets removed. So every time the receive location trying to pick up the same file which throws error. How can I deal with this.

A: There is an option on the SFTP receive location, where you can specify to delete the file after it has been received.


text:
Q: JavaScript - Wondering how can this be So I am learning JavaScript right now and I am making this calculator. Started it like any other JavaScript. Make html file, put in all the html tags and so on, make the special  tags into which I will write the code. Now my solution involved a lot of variables and if statements and so on..
But then I wondered how others have done it and i Stumbled upon this:
<FORM NAME="Calc">

<INPUT TYPE="text"   NAME="Input" Size="16">

    <INPUT TYPE="button" NAME="one"   VALUE="  1  " OnClick="Calc.Input.value += '1'">
    <INPUT TYPE="button" NAME="two"   VALUE="  2  " OnCLick="Calc.Input.value += '2'">
    <INPUT TYPE="button" NAME="three" VALUE="  3  " OnClick="Calc.Input.value += '3'">
    <INPUT TYPE="button" NAME="plus"  VALUE="  +  " OnClick="Calc.Input.value += ' + '">

    <INPUT TYPE="button" NAME="four"  VALUE="  4  " OnClick="Calc.Input.value += '4'">
    <INPUT TYPE="button" NAME="five"  VALUE="  5  " OnCLick="Calc.Input.value += '5'">
    <INPUT TYPE="button" NAME="six"   VALUE="  6  " OnClick="Calc.Input.value += '6'">
    <INPUT TYPE="button" NAME="minus" VALUE="  -  " OnClick="Calc.Input.value += ' - '">

    <INPUT TYPE="button" NAME="seven" VALUE="  7  " OnClick="Calc.Input.value += '7'">
    <INPUT TYPE="button" NAME="eight" VALUE="  8  " OnCLick="Calc.Input.value += '8'">
    <INPUT TYPE="button" NAME="nine"  VALUE="  9  " OnClick="Calc.Input.value += '9'">
    <INPUT TYPE="button" NAME="times" VALUE="  x  " OnClick="Calc.Input.value += ' * '">

    <INPUT TYPE="button" NAME="clear" VALUE="  c  " OnClick="Calc.Input.value = ''">
    <INPUT TYPE="button" NAME="zero"  VALUE="  0  " OnClick="Calc.Input.value += '0'">
    <INPUT TYPE="button" NAME="DoIt"  VALUE="  =  " OnClick="Calc.Input.value = eval(Calc.Input.value)">
    <INPUT TYPE="button" NAME="div"   VALUE="  /  " OnClick="Calc.Input.value += ' / '">

</FORM>

It's not indented really well but the point is that, it's javascript as I understand yes? And the person has not even used the script tags for it. Just putting the code randomly in a html file and bam it work. How can this be?

A: Its acceptable to have the javascript in the OnClick attribute of the INPUTs HTML, you don't need a script block unless you have either standalone code call, block of code or are importing another JS file

A: It's mostly HTML. It has onclick attributes which contain the body of a JavaScript function that is bound to the click event on the element.

A: It's just how embeded javascript works. According to O'Reilly's Java Guide:

Client-side JavaScript code is embedded within HTML documents in a
  number of ways:
Between a pair of  and  tags
From an external file specified by the src attribute of a  tag
In an event handler, specified as the value of an HTML attribute such
  as onclick or onmouseover
As the body of a URL that uses the special javascript: protocol

A: When a button is clicked, it calls the onClick function. You can place a simple piece of Javascript inside that parameter to be called when the button is clicked.
The Javascript eval function evaluates a string as Javascript code. That is what the button named "DoIt" does. The rest of the buttons simply append the numbers and operators to the Calc.Input.value string. Clicking "=" evaluates the Calc.Input.value string.
Calc.Input.value is referring to the value of the element named Input inside the form named Calc.

A: As I said, this is horrible code. If you are learning Javascript, this is a great example of how not to do it.
It works because they've put Javascript code in the event handlers and even without specifying most (all) browsers will interpret that as Javascript. They can access the various inputs by exploiting that most browsers will automatically create a variable for any named controls.
And then for bonus points they use eval which is evil.
Seriously, this is really bad code. You'd see a lot of code like this in the early 90's. Just move on and learn Javascript properly. Start here: JavaScript: The Good Parts

A: The onclick attribute (and other similar event handler attributes) is special, it's value is actually JavaScript - similarly to the value of the style attribute that is actually CSS.
For example onclick="Calc.Input.value = ''" would execute the JavaScript Calc.Input.value = ''. Due to automation by the browser, Calc references the Form element, then Input references the Input tag and .value is simply a property of Input.
That example you found looks very, very old and has poor coding style. I would stay away from it.


text:
Q: MongoError: text index required for $text query I am getting text index required for $text query where as i already did index before using that schema. Can someone tell me what could be the issue?. One more question Do we need to drop table in mongodb to create index? if yes then i will loose my current data. how can i do indexing without dropping the table?
const mongoose = require('mongoose');

let UserSchema = new mongoose.Schema({
    email: String,
    title: String,
});

UserSchema.indexes({ email: 'text', title: 'text' });

run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();

    const UserModel = mongoose.model('user', UserSchema);
    await UserModel.createIndexes();
    const newUser = [
        { email: 'test@test.com', title: 'r' },
        { email: 't@gmail.com', title: '@ro' },
    ];
    const user = await UserModel.create(newUser);
    console.log(user, 'user');
    const index = await UserModel.listIndexes();
    console.log(index);
    const data = await UserModel.find({ $text: { $search: 'test' } }).exec();
    console.log(data);
}

A: The function UserSchema.indexes returns the current indexes that are defined on the schema. You want UserSchema.index that defines a new index.


text:
Q: Lint rule: Find UClass based on qualified class name I am writing a lint rule to be used in Android Studio. I want to verify that the return type of certain Kotlin methods is a Class that implements a given Interface.
I can get the qualified name of the return type from the UCallExpression.
And I could get the list of Interfaces from a UClass object.
But I can't figure out how to get the UClass based on a qualified class name.
Thanks for your help!

A: I found that using the qualified name was not the right thing to do in this case.
UCallExpression.returnType gives me a PsiClassType. I then use the UAST context to find the matching UClass.


text:
Q: meaning of include file Hi I am trying to install the PETSc package on my Ubuntu 10.04 laptop. I am trying to configure it with the external solver SuperLU.
One of the instructions for the options to include while doing configure/make in the PETSc webpage is the following:
--with-PACKAGENAME-include=INCLUDEPATH --with-PACKAGENAME-lib=LIBRARYLIST: Usually a package is defined completely by its include file location - and library list. [If the package is already installed] - then one can use these two options to specify the package to configure.
I do not understand what the include file means. Is this some sort of header file? How does it look like?
I am new to installing and using numerical software so a detailed answer will be helpful.

A: I think this fits better on superuser (and I'm voting for migration), but yes, include files (in C) are header files.
You can recognize them by the .h (or rarely .hpp for C++ header files) extension. You usually find them in /usr/include or /usr/local/include, depending on your system.


text:
Q: Is it possible to move from one control to the other in an HTML form by pressing enter? Respected All,
I have an HTML form that contains different controls like text boxes and checkboxes. I want to move focus from one control to the next when the user presses the ENTER key, without using the tabindex property.
Is it possible?

A: You can do this by hooking keypress and looking for the Enter key, then navigating the DOM to find the next field. Vaguely like this (live copy):
window.onload = function() {

  var form,
      index;

  // Get the form
  form = document.getElementById('theForm')

  // Hook the keypress event on all its inputs
  for (index = 0; index < form.elements.length; ++index) {
    hookEvent(form.elements[index], 'keypress', elementKeypressHandler);
  }

  // Our handler for keypresses
  function elementKeypressHandler(event) {
    var keyCode,
        next,
        tryFirst;

    // Handle IE/standards variance
    event = event || window.event;

    // Get the keycode
    keyCode = event.keyCode || event.which;

    // If Enter...
    if (keyCode == 13) {
      // Find the next field; if we run out of fields, try
      // from the beginning
      tryFirst = true;
      next = this.nextSibling;
      while (next && (next.nodeType != 1 || next.tagName != "INPUT")) {
        next = next.nextSibling;
        if (!next && tryFirst) {
          tryFirst = false;
          next = this.parentNode.firstChild;
        }
      }

      // If we have one, focus it
      if (next && next !== this) {
        next.focus();
      }
    }
  }

  // Handle IE vs. standards for DOM2 event hookup
  function hookEvent(element, event, handler) {
    if (element.addEventListener) {
      element.addEventListener(event, handler, false);
    }
    else if (element.attachEvent) {
      element.attachEvent("on" + event, handler);
    }
    else {
      element["on" + event] = handler;
    }
    return element;
  }
};

Off-topic: This stuff is a lot easier if you use a library like jQuery, Prototype, YUI, Closure, or any of several others to iron out browser differences for you and to make it easier to traverse the DOM. For instance, in the above, I've had to account for no fewer than three differences between various browsers, and I've had to use a loop to find the next (or first) element to focus, skipping over non-Element nodes. Libraries will help you avoid writing that repetitive code and focus on what you actually want to do.

A: you could instead hook into the form's submit event and just focus() the next input if they weren't on a submit button. less effort if you're not using a 3rd party library.


text:
Q: Windows 2008 Server cannot access any network share I run a Windows 2008 server with SP2. This server acts as a desktop alone. Recently, I switched between two networks (corporate and other) using this system. Ever since, I am unable to access any network share on the original network from where I installed and configured the desktop. The message I get is "Network path was not found". Note that I am able to access the internet and my corporate mail server.
I am told this is a Vista and Windows 2008 specific problem and I have done everything I could think of:
a) Deleted the second network settings from the desktop
b) Installed a patch from MS that supposed took care of this problem (with MS clearly saying they had not tested this enough)
c) The SP2 install was after the problem occurred and I went ahead with it in the hope that SP2 may have something that would fix this
Some additional details:
a) A system admin can log into this system from a remote terminal
b) I cannot get into my own system using the hidden share C$ - for instance \mymachine\C$ gives me the same message as above - Network path not found
c) I can log into my system remotely using mstsc
d) I cannot create shares on this system - as an extension network printers are not detected
I have an update for you: The error message is as follows -
****Network Error****
Windows cannot access \\network_share
Check the spelling of the name. Otherwise there might a problem with your network. To try to identify and resolve network problems, click Diagnose.
Clicking Diagnose gives Error Code: 0x80070035
The network path was not found.
Any help will be appreciated
Thanks

A: In Vista/Server 2008, each network has its own profile, and you'll need to enable File and Print Services(netbios services) for each network.
For more help, try these two links:
Enable File and Printer Sharing and
File and Print Sharing in Vista
hth,
~H

A: For me :

*

*Server 2008 Standard (not R2)

*Firewall is off

*Computer browser service is on

*I am trying to access \\MYMACHINE\TFS-BUILDS because TFS requires a UNC share for drops

*(I am accessing both by typing in the name and double clicking the folder)

*Single network card

*Filesharing wizard says share was ok

*Share was showing under 'computer management'

*No obvious errors in eventlog

*Reboot didn't fix it

How did I fix it? I haven't :-(
I'll update this when I figure it out!
Edit: FIXED IT !!
Apparently 'File and printer Sharing for Microsoft Networks' is not installed for the network adapter by default. This is independent on whether or not file sharing is actually installed.
I'm not sure if this is a Windows 2008 default or the network card's default.
So here's what fixed it:

*

*Right click on 'Local Area Connection'

*Verify that 'File and Printer Sharing for Microsoft Networks' is NOT there

*Assuming you don't see it - Click 'Install'

*Double click on 'Service'

*Select 'File and Printer Sharing for Microsoft Networks'

*Click OK to install it

*Reboot machine

You should be able to see it now. Jees! (Answer from http://kadaitcha.cx/file_sharing.html)

A: You are not crazy I have this issue too and can replicate the following oddies that only seem to happen with win2k8 sp2 and vista sp2 clients whom are not joined to the domain but try to access a domain joined server.   They will get prompted for cred's but even when the creds are correct will not be allowed access.    Interestingly enough however if you attempt to connect via \ip\ or \ip\share you are prompted for creds and they work and access is granted but if you use the standard \machinename or \FQDN while you get prompted, it will never let you in.
This seems to have started with SP2.
I have found no solution to this other than rolling back to SP1 or using the IP.
Also interesting is once you have connected via IP successfully you can then use the \machinename etc methods and they work fine.  If you then say remove all connections to the box via net use /del on all connections then try the \machinename again the problem will return.  - Almost hilarious
Makes no logical sense to me why this is, but it is.

A: What worked for me was turning on "TCP/IP NetBIOS Helper" in services.  Somehow that was set to run automatically but was not turned on.  After i started the service I was able to connect to shares.

A: Did you check if the Windows firewall is blocking the ports needed by File Sharing? To enable the File and Printer Sharing option in Windows Firewall Configuration Settings:

*

*Start > Control Panel > Network and Intranet

*Under the Windows Firewall section heading, click the "Allow a program through Windows Firewall" link

*In the programs and ports list, check the "File and Printer Sharing option"
Check also in the Network and Sharing Center (from Control Panel), if "File Sharing" is "on".

A: From the servicess check the Computer Browser service...  I had the same problem and apparently this was the couse.  I think by default this servise is disabled

A: Fixing the winsock and TCP/IP worked for me. On the run command (as admin) I used the following commands:
for winsock run:
netsh winsock reset
to reset tcp/ip run:
netsh int ip reset c:\temp\resetlog.txt
Cheers,
Thomas

A: This Solution Fixed my problem:
You are not crazy I have this issue too and can replicate the following oddies that only seem to happen with win2k8 sp2 and vista sp2 clients whom are not joined to the domain but try to access a domain joined server. They will get prompted for cred's but even when the creds are correct will not be allowed access. Interestingly enough however if you attempt to connect via \ip\ or \ip\share you are prompted for creds and they work and access is granted but if you use the standard \machinename or \FQDN while you get prompted, it will never let you in.
This seems to have started with SP2. I have found no solution to this other than rolling back to SP1 or using the IP. Also interesting is once you have connected via IP successfully you can then use the \machinename etc methods and they work fine. If you then say remove all connections to the box via net use /del on all connections then try the \machinename again the problem will return. - Almost hilarious
Makes no logical sense to me why this is, but it is.
link|flag

A: *

*This combination of machines has run for some years without difficulty.

*I changed Internet service provider
(to a cable-based system). Everything
works fine. Noticed that time to log
into one Windows Server 2008 (of two)
on my small private network was
several minutes for each step
(Applying User Settings, etc). Domain
controller (the other server) could
be logged onto instantly.  An
Internet suggestion caused me to
remove the ailing server from the
domain, then    attempt to rejoin.
Failed consistently: "The network
path was not found." Tried various
things for a long time.  Decided to
clean install Windows Server 2008 R2
on the domain controller. This went
fine. Attempting to join the
untouched server #1 (IIS) to new DC
failed in exactly the same way:
"network path was not found."  Each
server can ping the other, even by
name. DC can sometimes see IIS in
network    browsing, but IIS can
never see DC (it does see one
non-domain-connected workstation).
DCDiag shows no problems.  Was able
to map DC on IIS as network location.
No effect on failure to join domain.
Windows Firewall currently off on
both servers.
Began following ServerFault suggestions.

*Network discovery is "Custom," and
File Sharing is On. Started the
disabled Computer Browser service.
More computers appeared in network
discovery but had no effect on
joining the domain.

Did the winsock and tcpip resets (via Thomas). This was scary, because it deleted all my NIC settings. But, lo and behold, restoring them yielded the long sought "Welcome to the ... domain!"
[I attempted several times to format most of the points above as bullets, but it all ran together. Other than that, ServerFault Rules!]

A: In order to get rid of the error code 0x80070035, I have a few methods that I would like to share. You can try them out and let us know as well.

*

*I am sure you will have got through this, but mentioning this just in case, firstly try disabling your firewall.

*Try reinstalling your network adapter drivers.

*Check your device manager, and in case you see a lot of 6to4 Adapters, delete all of them leaving just one behind.

*Enable NetBIOS over TCP/IP by going to the RUN dialogue box and typing in ncpa.cpl. After this select the properties by right clicking on the connection. Click Internet Protocol (TCP/IP), click Properties, and then click Advanced. After this go to "WINS" tab. Under NetBIOS setting, click "Enable NetBIOS over TCP/IP". Let us know how it goes.

A: I want you to know that for me solving this problem wat to tick Client for Microsoft Networks on the right NIC on my DC. Looks like when messing arround with Hyper-V this was disabled for some reason.
I didn't try to this (Did the winsock and tcpip resets (via Thomas). This was scary, because it deleted all my NIC settings. But, lo and behold, restoring them yielded the long sought "Welcome to the ... domain!") because of the warning in there. I would have done this as a last resort. If you have a another server, compare the settings between the two.


text:
Q: Handle Large File with PHP I have a file with the size of around 10 GB or more. The file contains only numbers ranging from 1 to 10 on each line and nothing else. Now the task is to read the data[numbers] from the file and then sort the numbers in ascending or descending order and create a new file with the sorted numbers.
Can anyone of you please help me with the answer?

A: I'm assuming this is somekind of homework and goal for this is to sort more data than you can hold in your RAM?
Since you only have numbers 1-10, this is not that complicated task. Just open your input file and count how many occourances of every specific number you have. After that you can construct simple loop and write values into another file. Following example is pretty self explainatory.
$inFile = '/path/to/input/file';
$outFile = '/path/to/output/file';
$input = fopen($inFile, 'r');
if ($input === false) {
    throw new Exception('Unable to open: ' . $inFile);
}
//$map will be array with size of 10, filled with 0-s
$map = array_fill(1, 10, 0);
//Read file line by line and count how many of each specific number you have
while (!feof($input)) {
    $int = (int) fgets($input);
    $map[$int]++;
}
fclose($input);
$output = fopen($outFile, 'w');
if ($output === false) {
    throw new Exception('Unable to open: ' . $outFile);
}
/*
 * Reverse array if you need to change direction between
 * ascending and descending order
 */
//$map = array_reverse($map);
//Write values into your output file
foreach ($map AS $number => $count) {
    $string = ((string) $number) . PHP_EOL;
    for ($i = 0; $i < $count; $i++) {
        fwrite($output, $string);
    }
}
fclose($output);

Taking into account the fact, that you are dealing with huge files, you should also check script execution time limit for your PHP environment, following example will take VERY long for 10GB+ sized files, but since I didn't see any limitations concerning execution time and performance in your question, I'm assuming it is OK.

A: I had a similar issue before. Trying to manipulate such a large file ended up being huge drain on resources and it couldn't cope. The easiest solution I ended up with was to try and import it into a MySQL database using a fast data dump function called LOAD DATA INFILE
http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Once it's in you should be able to manipulate the data.
Alternatively, you could just read the file line by line while outputting the result into another file line by line with the sorted numbers. Not too sure how well this would work though.
Have you had any previous attempts at it or are you just after a possible method of doing it?

A: If that's all you don't need PHP (if you have a Linux maschine at hand):
sort -n file > file_sorted-asc
sort -nr file > file_sorted-desc

Edit: OK, here's your solution in PHP (if you have a Linux maschine at hand):
<?php

// Sort ascending
`sort -n file > file_sorted-asc`;

// Sort descending
`sort -nr file > file_sorted-desc`;

?>

:)


text:
Q: inheritance - use parent's read method in child Can I use parent's read() function to read the first and last names, and then have child's read() read only the middle name? Or I have to read first, second, and middle in the child?
EDIT:The first answer seems to be working but when I read in child using strtok, I get the whole line, not just the third field. Is there a way around it, or I just have to read first two fields into dummy variables and then read third field?
class Parent
{
protected:
  char first[80], last[80];

  virtual istream& read(istream &is) {
    char temp[80];
    char *f, *l;
    is >> temp;
    f = strtok(temp, ",");
    strcpy(first, f);
    l = strtok(NULL, ",");
    strcpy(last, l);
    return is;
  }

public:
  friend istream& operator>> (istream &is, Parent &parent) {
    return parent.read(is);
  }
};

class Child: public Parent
{
  char middle[80];

  istream& read(istream &is) {
    /*inherit first and last from parent*/
    char temp[80];
    char *m;
    is >> temp;
    m = strtok(temp, ",");
    strcpy(middle, m);
  }
};

in main()

Parent *object;
ifstream inf("filename.csv");
object = new Child();
inf >> *object;

cat filename.csv
George,Bush,Walker

A: In the read function in the child class, you can call the parents read function like this:
class Child : public Parent
{
    // ...

    std::istream &read(std::istream &is)
    {
        Parent::read(is);
        // Read some more
    }
};

A: You can't use the Parent's read function from Child, because Parent::read() consumes the complete input (you can only do strtok() without NULL-ptr on a string once, because it actually replaces the delimiter).  The tricky part is that Child has to get information from the middle of the stream.
You could reuse Parent's functions if you declare a readName() function, but this doesn't work easily with strtok().  I would propose using an std::istringstream for this where you enter the line (instead of using strtok) and pass to readName() as parameter.  With strtok(), you could do a prepareRead() where you do the tokenizing and then read in the readName() function with strtok(NULL,","), but that depends heavily on side-effects inside functions.
Not compiled/tested/handled error-cases, so don't copy/paste this for your assignment:
class Parent {
protected:
  std::string first, last;
  std::istringstream readLine(istream& is)
  {
    std::string line;
    std::getline(is, line);
    return std::istringstream(line);
  }
  std::string readName(std::istringstream& iss)
  {
    std::string name;
    std::getline(iss, name, ',');
    return name;
  }

  virtual istream& read(istream &is)
  {
    std::istringstream iss = readLine(is);
    first = readFirstName(iss);
    last = readLastName(iss);
    return is;
  }
public:
  friend istream& operator>> (istream &is, Parent &parent)
  {
    return parent.read(is);
  }
};

class Child : public Parent
{
private:
  std::string middle;
  virtual istream& read(istream &is)
  {
    std::istringstream iss = readLine(is);
    first = readName(iss);
    middle = readName(iss)
    last = readName(iss);
    return is;
  }
};

Remark that you should avoid strcpy, especially with input: you're program will fail and can be hacked by passing a file containing names larger than 80 characters, which can be avoided by using std::string and std::istringstream.

A: 1) Don't declare the parent method as virtual and change the following code:
class Child: public Parent {
    char middle[80];
    istream& read(istream &is) {
    Parent::read(is);
    char temp[80];
    char *m;
    is >> temp;
    m = strtok(temp, ",");
    strcpy(middle, m); }
};

Without using virtual... parent method will be hidden.
Edit: thanks for cppcoder attention. this was wrong. see the next approach.
2) Or use using declaration, This is an example from C++ standard:
struct A {
    virtual void f();
};

struct B : virtual A {
    virtual void f();
};

struct C : B , virtual A {
    using A::f;
};

void foo() {
    C c;
    c.f(); // calls B::f, the final overrider
    c.C::f(); // calls A::f because of the using-declaration
}


text:
Q: Ubuntu 20.04 won't load, boot into initramfs Hi I'm new in the Ubuntu world and i recently updated some drivers. After the reboot it wont load my System. If anyone can help!

A: Fixed: while updating the software and bios a error acurred and it changed my boot into rsd something and changing it to htki something in bios it fixed it for me


text:
Q: PrimeFaces Tree scrollable fixed size I have a huge tree component in my primefaces application. The tree has hundreds of nodes and I want the tree to have fixed height in my UI with vertical scroll to navigate the nodees.
Can someone help me figure this out?
Thanks

A: Put that tree in a panel and then apply style to that panel. For example:

                    <h:outputText value="#{doc}" />

A: I use p:scrollPanel

A: p:scrollPanel does not work well.
Use: p:layout
Here an example:

                    <h:panelGrid id="catalogContent" style="width: 100%;">

                                <h:outputText value="#{doc.segPerNombre}" />

                                <h:outputText value="#{doc.segModNombre}" />

                                <h:outputText value="#{doc.segOpcNombre}" />

                    </h:panelGrid>

A:

          <h:outputText value="#{doc}" />

`

A: So I found a way to make this work. However, I will admit upfront it was not my dream solution.  But then I have only so much time to play around as this is a bit of a pet project for me:
I created two instances of the table with the same definitions and used fixed header widths.  I then placed each table one after the other in individual divs.  I then style those divs:
#header {
  height: 24px;
}
#body thead {
  display: none;
}

and then the I have a sample of simple tables and divs below:

      <ng-template let-row="rowData" pTemplate type="body">
        {{ row.data.key }}
      </ng-template>

      <ng-template let-row="rowData" pTemplate type="body">
        {{ row.data.big }}
      </ng-template>

      <ng-template let-row="rowData" pTemplate type="body">
        {{ row.data.key }}
      </ng-template>

      <ng-template let-row="rowData" pTemplate type="body">
        {{ row.data.big }}
      </ng-template>

What I think helped is ensuring I set the width on each column so I could ensure I got the same column width during display.  I also set the treedata to [] or empty for the header so I do not process the data two times.  This is a bit inelegant.  And I would sure have liked to add scrolling directly to the treetable but time is not available.
Also to have the table itself scroll. use something like:
.ui-treetable-tablewrapper {
   overflow-y: scroll;
   height: 290px;
}

NOTE:  I have no idea how to get the height so a row is not a bit clipped. As it seems the row height for expanded rows is not identical to that of unexpanded rows.
If you place this in a bootstrap panel with a footer and no padding it looks good, albeit not perfect:

     ...header...

     ...Table...

      ....footer...


text:
Q: Easier DynamoDB local testing I'm using DynamoDB local for unit testing. It's not bad, but has some drawbacks. Specifically:

*

*You have to somehow start the server before your tests run

*The server isn't started and stopped before each test so tests become inter-dependent unless you add code to delete all tables, etc. after each test

*All developers need to have it installed

What I want to do is something like put the DynamoDB local jar, and the other jars upon which it depends, in my test/resources directory (I'm writing in Java). Then before each test I'd start it up, running with -inMemory, and after the test I'd stop it. That way anyone pulling down the git repo gets a copy of everything they need to run the tests and each test is independent of the others.
I have found a way to make this work, but it's ugly, so I'm looking for alternatives. The solution I have is to put a .zip file of the DynamoDB local stuff in test/resources, then in the @Before method, I'd extract it to some temporary directory and start a new java process to execute it. That works, but it's ugly and has some drawbacks:

*

*Everyone needs the java executable on their $PATH

*I have to unpack a zip to the local disk. Using local disk is often dicey for testing, especially with continuous builds and such.

*I have to spawn a process and wait for it to start for each unit test, and then kill that process after each test. Besides being slow, the potential for left-over processes seems ugly.

It seems like there should be an easier way. DynamoDB Local is, after all, just Java code. Can't I somehow ask the JVM to fork itself and look inside the resources to build a classpath? Or, even better, can't I just call the main method of DynamoDB Local from some other thread so this all happens in a single process? Any ideas?
PS: I am aware of Alternator, but it appears to have other drawbacks so I'm inclined to stick with Amazon's supported solution if I can make it work.

A: In order to use DynamoDBLocal you need to follow these steps.

*

*Get Direct DynamoDBLocal Dependency

*Get Native SQLite4Java dependencies

*Set sqlite4java.library.path to show native libraries

1. Get Direct DynamoDBLocal Dependency
This one is the easy one. You need this repository as explained  here.
<!--Dependency:-->
<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>DynamoDBLocal</artifactId>
        <version>1.11.0.1</version>
        <scope></scope>
    </dependency>
</dependencies>
<!--Custom repository:-->
<repositories>
    <repository>
        <id>dynamodb-local</id>
        <name>DynamoDB Local Release Repository</name>
        <url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</url>
    </repository>
</repositories>

2. Get Native SQLite4Java dependencies
If you do not add these dependencies, your tests will fail with 500 internal error.
First, add these dependencies:
<dependency>
    <groupId>com.almworks.sqlite4java</groupId>
    <artifactId>sqlite4java</artifactId>
    <version>1.0.392</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.almworks.sqlite4java</groupId>
    <artifactId>sqlite4java-win32-x86</artifactId>
    <version>1.0.392</version>
    <type>dll</type>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.almworks.sqlite4java</groupId>
    <artifactId>sqlite4java-win32-x64</artifactId>
    <version>1.0.392</version>
    <type>dll</type>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.almworks.sqlite4java</groupId>
    <artifactId>libsqlite4java-osx</artifactId>
    <version>1.0.392</version>
    <type>dylib</type>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.almworks.sqlite4java</groupId>
    <artifactId>libsqlite4java-linux-i386</artifactId>
    <version>1.0.392</version>
    <type>so</type>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.almworks.sqlite4java</groupId>
    <artifactId>libsqlite4java-linux-amd64</artifactId>
    <version>1.0.392</version>
    <type>so</type>
    <scope>test</scope>
</dependency>

Then, add this plugin to get native dependencies to specific folder:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.10</version>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>test-compile</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <includeScope>test</includeScope>
                        <includeTypes>so,dll,dylib</includeTypes>
                        <outputDirectory>${project.basedir}/native-libs</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

3. Set sqlite4java.library.path to show native libraries
As last step, you need to set sqlite4java.library.path system property to native-libs directory. It is OK to do that just before creating your local server.
System.setProperty("sqlite4java.library.path", "native-libs");

After these steps you can use DynamoDBLocal as you want. Here is a Junit rule that creates local server for that.
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
import org.junit.rules.ExternalResource;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * Creates a local DynamoDB instance for testing.
 */
public class LocalDynamoDBCreationRule extends ExternalResource {

    private DynamoDBProxyServer server;
    private AmazonDynamoDB amazonDynamoDB;

    public LocalDynamoDBCreationRule() {
        // This one should be copied during test-compile time. If project's basedir does not contains a folder
        // named 'native-libs' please try '$ mvn clean install' from command line first
        System.setProperty("sqlite4java.library.path", "native-libs");
    }

    @Override
    protected void before() throws Throwable {

        try {
            final String port = getAvailablePort();
            this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory", "-port", port});
            server.start();
            amazonDynamoDB = new AmazonDynamoDBClient(new BasicAWSCredentials("access", "secret"));
            amazonDynamoDB.setEndpoint("http://localhost:" + port);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void after() {

        if (server == null) {
            return;
        }

        try {
            server.stop();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public AmazonDynamoDB getAmazonDynamoDB() {
        return amazonDynamoDB;
    }

    private String getAvailablePort() {
        try (final ServerSocket serverSocket = new ServerSocket(0)) {
            return String.valueOf(serverSocket.getLocalPort());
        } catch (IOException e) {
            throw new RuntimeException("Available port was not found", e);
        }
    }
}

You can use this rule like this
@RunWith(JUnit4.class)
public class UserDAOImplTest {

    @ClassRule
    public static final LocalDynamoDBCreationRule dynamoDB = new LocalDynamoDBCreationRule();
}

A: I have wrapped the answers above into two JUnit rules that does not require changes to the build script as the rules handles the native library stuff. I did this as I found that Idea did not like the Gradle/Maven solutions as it just went off and did its own thing anyhoos.
This means the steps are:

*

*Get the AssortmentOfJUnitRules version 1.5.32 or above dependency

*Get the Direct DynamoDBLocal dependency

*Add the LocalDynamoDbRule or HttpDynamoDbRule to your JUnit test.

Maven:
<!--Dependency:-->
<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>DynamoDBLocal</artifactId>
        <version>1.11.0.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.github.mlk</groupId>
      <artifactId>assortmentofjunitrules</artifactId>
      <version>1.5.36</version>
      <scope>test</scope>
    </dependency>
</dependencies>
<!--Custom repository:-->
<repositories>
    <repository>
        <id>dynamodb-local</id>
        <name>DynamoDB Local Release Repository</name>
        <url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</url>
    </repository>
</repositories>

Gradle:
repositories {
  mavenCentral()

   maven {
    url = "https://s3-us-west-2.amazonaws.com/dynamodb-local/release"
  }
}

dependencies {
    testCompile "com.github.mlk:assortmentofjunitrules:1.5.36"
    testCompile "com.amazonaws:DynamoDBLocal:1.+"
}

Code:
public class LocalDynamoDbRuleTest {
  @Rule
  public LocalDynamoDbRule ddb = new LocalDynamoDbRule();

  @Test
  public void test() {
    doDynamoStuff(ddb.getClient());
  }
}

A: Try out tempest-testing! It ships a JUnit4 Rule and a JUnit5 Extension. It also supports both AWS SDK v1 and SDK v2.
Tempest provides a library for testing DynamoDB clients
using DynamoDBLocal
. It comes with two implementations:

*

*JVM: This is the preferred option, running a DynamoDBProxyServer backed by sqlite4java,
which is available on most platforms.

*Docker: This runs dynamodb-local in a Docker
container.

Feature matrix:

Feature
tempest-testing-jvm
tempest-testing-docker

Start up time
~1s
~10s

Memory usage
Less
More

Dependency
sqlite4java native library
Docker

To use tempest-testing, first add this library as a test dependency:
For AWS SDK 1.x:
dependencies {
  testImplementation "app.cash.tempest:tempest-testing-jvm:1.5.2"
  testImplementation "app.cash.tempest:tempest-testing-junit5:1.5.2"
}
// Or
dependencies {
  testImplementation "app.cash.tempest:tempest-testing-docker:1.5.2"
  testImplementation "app.cash.tempest:tempest-testing-junit5:1.5.2"
}

For AWS SDK 2.x:
dependencies {
  testImplementation "app.cash.tempest:tempest2-testing-jvm:1.5.2"
  testImplementation "app.cash.tempest:tempest2-testing-junit5:1.5.2"
}
// Or
dependencies {
  testImplementation "app.cash.tempest:tempest2-testing-docker:1.5.2"
  testImplementation "app.cash.tempest:tempest2-testing-junit5:1.5.2"
}

Then in tests annotated with @org.junit.jupiter.api.Test, you may add TestDynamoDb as a test
extension. This extension spins up a
DynamoDB server. It shares the server across tests and keeps it running until the process exits. It
also manages test tables for you, recreating them before each test.
class MyTest {
  @RegisterExtension
  TestDynamoDb db = new TestDynamoDb.Builder(JvmDynamoDbServer.Factory.INSTANCE) // or DockerDynamoDbServer
      // `MusicItem` is annotated with `@DynamoDBTable`. Tempest recreates this table before each test.
      .addTable(TestTable.create(MusicItem.TABLE_NAME, MusicItem.class))
      .build();

  @Test
  public void test() {
    PutItemRequest request = // ...;
    // Talk to the local DynamoDB.
    db.dynamoDb().putItem(request);
  }

}

A: In August 2018 Amazon announced new Docker image with Amazon DynamoDB Local onboard. It does not require downloading and running any JARs as well as adding using third-party OS-specific binaries (I'm talking about sqlite4java).
It is as simple as starting a Docker container before the tests:
docker run -p 8000:8000 amazon/dynamodb-local

You can do that manually for local development, as described above, or use it in your CI pipeline. Many CI services provide an ability to start additional containers during the pipeline that can provide dependencies for your tests. Here is an example for Gitlab CI/CD:
test:
  stage: test
  image: openjdk:8-alpine
  services:
    - name: amazon/dynamodb-local
      alias: dynamodb-local
  script:
    - DYNAMODB_LOCAL_URL=http://dynamodb-local:8000 ./gradlew clean test

Or Bitbucket Pipelines:
definitions:
  services:
    dynamodb-local:
      image: amazon/dynamodb-local
…
step:
  name: test
  image:
    name: openjdk:8-alpine
  services:
    - dynamodb-local
  script:
    - DYNAMODB_LOCAL_URL=http://localhost:8000 ./gradlew clean test

And so on. The idea is to move all the configuration you can see in other answers out of your build tool and provide the dependency externally. Think of it as of dependency injection / IoC but for the whole service, not just a single bean.
After you've started the container you can create a client pointing to it:
private AmazonDynamoDB createAmazonDynamoDB(final DynamoDBLocal configuration) {
    return AmazonDynamoDBClientBuilder
        .standard()
        .withEndpointConfiguration(
            new AwsClientBuilder.EndpointConfiguration(
                "http://localhost:8000",
                Regions.US_EAST_1.getName()
            )
        )
        .withCredentials(
            new AWSStaticCredentialsProvider(
                // DynamoDB Local works with any non-null credentials
                new BasicAWSCredentials("", "")
            )
        )
        .build();
}

Now to the original questions:

You have to somehow start the server before your tests run

You can just start it manually, or prepare a developsers' script for it. IDEs usually provide a way to run arbitrary commands before executing a task, so you can make IDE to start the container for you. I think that running something locally should not be a top priority in this case, but instead you should focus on configuring CI and let the developers start the container as it's comfortable to them.

The server isn't started and stopped before each test so tests become inter-dependent unless you add code to delete all tables, etc. after each test

That's trueee, but… You should not start and stop such heavyweight things
and recreate tables before / after each test. DB tests are almost always inter-dependent and that's ok for them. Just use unique  values for each test case (e.g. set item's hash key to ticket id / specific test case id you're working on). As for the seed data, I'd recommend moving it from the build tool and test code as well. Either make your own image with all the data you need or use AWS CLI to create tables and insert data. Follow the single responsibility principle and dependency injection principles: your test code must not do anything but tests. All the environment (tables and data in this case should be provided for them). Creating a table in a test is wrong, because in a real life that table already exist (unless you're testing a method that actually creates a table, of course).

All developers need to have it installed

Docker should be a must for every developer in 2018, so that's not a problem.

And if you're using JUnit 5, it can be a good idea to use a DynamoDB Local extension that will inject the client in your tests (yes, I'm doing a self-promotion):

*

*Add a dependency on me.madhead.aws-junit5:dynamo-v1
pom.xml:
<dependency>
    <groupId>me.madhead.aws-junit5</groupId>
    <artifactId>dynamo-v1</artifactId>
    <version>6.0.1</version>
    <scope>test</scope>
</dependency>

build.gradle
dependencies {
    testImplementation("me.madhead.aws-junit5:dynamo-v1:6.0.1")
}

*Use the extension in your tests:
@ExtendWith(DynamoDBLocalExtension.class)
class MultipleInjectionsTest {
    @DynamoDBLocal(
        url = "http://dynamodb-local-1:8000"
    )
    private AmazonDynamoDB first;

    @DynamoDBLocal(
        urlEnvironmentVariable = "DYNAMODB_LOCAL_URL"
    )
    private AmazonDynamoDB second;

    @Test
    void test() {
        first.listTables();
        second.listTables();
    }
}

A: This is a restating of bhdrkn's answer for Gradle users (his is based on Maven).  It's still the same three steps:

*

*Get Direct DynamoDBLocal Dependency

*Get Native SQLite4Java dependencies

*Set sqlite4java.library.path to show native libraries

1. Get Direct DynamoDBLocal Dependency
Add to the dependencies section of your build.gradle file...
dependencies {
    testCompile "com.amazonaws:DynamoDBLocal:1.+"
}

2. Get Native SQLite4Java dependencies
The sqlite4java libraries will already be downloaded as a dependency of DynamoDBLocal, but the library files need to be copied to the right place.  Add to your build.gradle file...
task copyNativeDeps(type: Copy) {
    from(configurations.compile + configurations.testCompile) {
        include '*.dll'
        include '*.dylib'
        include '*.so'
    }
    into 'build/libs'
}

3. Set sqlite4java.library.path to show native libraries
We need to tell Gradle to run copyNativeDeps for testing and tell sqlite4java where to find the files.  Add to your build.gradle file...
test {
    dependsOn copyNativeDeps
    systemProperty "java.library.path", 'build/libs'
}

A:
It seems like there should be an easier way. DynamoDB Local is, after all, just Java code. Can't I somehow ask the JVM to fork itself and look inside the resources to build a classpath?

You can do something along these lines, but much simpler: programmatically search the classpath for the location of the native libraries, then set the sqlite4java.library.path property before starting DynamoDB. This is the approach implemented in tempest-testing, as well as in this answer (code here) which is why they just work as pure library/classpath dependency and nothing more.
In my case needed access to DynamoDB outside of a JUnit extension, but I still wanted something self-contained in library code, so I extracted the approach it takes:
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.local.shared.access.AmazonDynamoDBLocal;
import com.google.common.collect.MoreCollectors;
import java.io.File;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.api.condition.OS;

...

  public AmazonDynamoDBLocal embeddedDynamoDb() {
    final OS os = Stream.of(OS.values()).filter(OS::isCurrentOs)
        .collect(MoreCollectors.onlyElement());
    final String prefix;
    switch (os) {
      case LINUX:
        prefix = "libsqlite4java-linux-amd64-";
        break;
      case MAC:
        prefix = "libsqlite4java-osx-";
        break;
      case WINDOWS:
        prefix = "sqlite4java-win32-x64-";
        break;
      default:
        throw new UnsupportedOperationException(os.toString());
    }

    System.setProperty("sqlite4java.library.path",
        Arrays.asList(System.getProperty("java.class.path").split(File.pathSeparator))
            .stream()
            .map(File::new)
            .filter(file -> file.getName().startsWith(prefix))
            .collect(MoreCollectors.onlyElement())
            .getParent());
    return DynamoDBEmbedded.create();
  }

Not had a chance to test on a lot of platforms, and the error handling could likely be improved.
It's a pity AWS haven't taken the time to make the library more friendly, as this could easily be done in the library code itself.

A: You can use DynamoDB Local as a Maven test dependency in your test code, as is shown in this announcement. You can run over HTTP:
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;

final String[] localArgs = { "-inMemory" };
DynamoDBProxyServer server = ServerRunner.createServerFromCommandLineArgs(localArgs);
server.start();
AmazonDynamoDB dynamodb = new AmazonDynamoDBClient();
dynamodb.setEndpoint("http://localhost:8000");
dynamodb.listTables();
server.stop();

You can also run in embedded mode:
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;

AmazonDynamoDB dynamodb = DynamoDBEmbedded.create();
dynamodb.listTables();

A: For unit testing at work I use Mockito, then just mock the AmazonDynamoDBClient. then mock out the returns using when. like the following:
when(mockAmazonDynamoDBClient.getItem(isA(GetItemRequest.class))).thenAnswer(new Answer<GetItemResult>() {
        @Override
        public GetItemResult answer(InvocationOnMock invocation) throws Throwable {
            GetItemResult result = new GetItemResult();
            result.setItem( testResultItem );
            return result;
        }
    });

not sure if that is what your looking for but that's how we do it.

A: Shortest solution with fix for sqlite4java.SQLiteException UnsatisfiedLinkError if it is a java/kotlin project built with gradle (a changed $PATH is not needed).
repositories {
    // ... other dependencies
    maven { url 'https://s3-us-west-2.amazonaws.com/dynamodb-local/release' }
}

dependencies {
    testImplementation("com.amazonaws:DynamoDBLocal:1.13.6")
}

import org.gradle.internal.os.OperatingSystem
test {
    doFirst {
        // Fix for: UnsatisfiedLinkError -> provide a valid native lib path
        String nativePrefix = OperatingSystem.current().nativePrefix
        File nativeLib = sourceSets.test.runtimeClasspath.files.find {it.name.startsWith("libsqlite4java") && it.name.contains(nativePrefix) } as File
        systemProperty "sqlite4java.library.path", nativeLib.parent
    }
}

Straightforward usage in test classes (src/test):
private lateinit var db: AmazonDynamoDBLocal

@BeforeAll
fun runDb() { db = DynamoDBEmbedded.create() }

@AfterAll
fun shutdownDb() { db.shutdown() }

A: There are couple of node.js wrappers for DynamoDB Local. These allows to easily execute unit tests combining with task runners like gulp or grunt. Try dynamodb-localhost,
dynamodb-local

A: I have found that the amazon repo as no index file, so does not seem to function in a way that allows you to bring it in like this:
maven {
   url = "https://s3-us-west-2.amazonaws.com/dynamodb-local/release"
}

The only way I could get the dependencies to load is by downloading DynamoDbLocal as a jar and bringing it into my build script like this:
dependencies {
    ...
    runtime files('libs/DynamoDBLocal.jar')
    ...
}

Of course this means that all the SQLite and Jetty dependencies need to be brought in by hand - I'm still trying to get this right. If anyone knows of a reliable repo for DynamoDbLocal, I would really love to know.

A: You could also use this lightweight test container 'Dynalite'
https://www.testcontainers.org/modules/databases/dynalite/
From testcontainers:

Dynalite is a clone of DynamoDB, enabling local testing. It's light
  and quick to run.

A: The DynamoDB Gradle dependency already includes the SQLite libraries. You can pretty easily instruct the Java runtime to use it in your Gradle build script. Here's my build.gradle.kts as an example:
import org.apache.tools.ant.taskdefs.condition.Os

plugins {
    application
}

repositories {
    mavenCentral()
    maven {
        url = uri("https://s3-us-west-2.amazonaws.com/dynamodb-local/release")
    }
}

dependencies {
    implementation("com.amazonaws:DynamoDBLocal:[1.12,2.0)")
}

fun getSqlitePath(): String? {
    val dirName = when {
        Os.isFamily(Os.FAMILY_MAC) -> "libsqlite4java-osx"
        Os.isFamily(Os.FAMILY_UNIX) -> "libsqlite4java-linux-amd64"
        Os.isFamily(Os.FAMILY_WINDOWS) -> "sqlite4java-win32-x64"
        else -> throw kotlin.Exception("DynamoDB emulator cannot run on this platform")
    }
    return project.configurations.runtimeClasspath.get().find { it.name.contains(dirName) }?.parent
}

application {
    mainClass.set("com.amazonaws.services.dynamodbv2.local.main.ServerRunner")
    applicationDefaultJvmArgs = listOf("-Djava.library.path=${getSqlitePath()}")
}

tasks.named<JavaExec>("run") {
    args("-inMemory")
}


text:
Q: Check Browser Support for specific Mime Type? For a web application which allows in-browser preview of documents, I'd like to check whether the user's browser supports preview of the current document's mime type.
Is there a Javascript-based way to match the current mime type against the types supported by the browser?
Thanks!

A: In recent browsers there are navigatior.plugins array-like object. You can check each plugin for your mime type.
Here is the solution gist and jsfiddle.
var mimeCheck = function (type) {
    return Array.prototype.reduce.call(navigator.plugins, function (supported, plugin) {
        return supported || Array.prototype.reduce.call(plugin, function (supported, mime) {
            return supported || mime.type == type;
        }, supported);
    }, false);
};

A: You could make an AJAX call and check response headers for mimetype.
 $.ajax({
    type: "GET",
    url: 'http://..../thing.pdf',
    success: function (output, status, xhr) {
      alert("done!"+ xhr.getAllResponseHeaders());
      alert("done!"+ xhr.getResponseHeader("Content-Type"));
    }
  });

A: In this question there was the same question I think, try to check out it
Check if a browser supports a specific MIME type?

A: If you define which plugin is needed for specific document type, then you may try to look if needed plugin exists. Should work at least on Firefox and Chrome.
window.navigator.plugins


text:
Q: What's wrong with my simple insert? I'm using coldfusion to insert the contents of a struct (key-value pairs) into a database table. This is my code:
<cfloop collection="#results#" item="ID" >
    <cfquery name="insertStuff" datasource="myDataSource">
        INSERT INTO web..Stuff (ID, Name)
        VALUES (#ID#, #results[ID]#)
    </cfquery>
</cfloop>

This seems simple enough... but I'm getting the following error:
Incorrect syntax near 'VA'.

Any ideas?

A: I think I may have solved it... forgot the quotes, and they're both varchar fields :-/
<cfloop collection="#results#" item="ID" >
    <cfquery name="insertStuff" datasource="myDataSource">
        INSERT INTO web..Stuff (ID, Name)
        VALUES ('#ID#', '#results[ID]#')
    </cfquery>
</cfloop>

A: You really ought to think about parameterising your data too.
<cfloop collection="#results#" item="ID" >
    <cfquery name="insertStuff" datasource="myDataSource">
        INSERT INTO web..Stuff (ID, Name)
        VALUES (
            <cfqueryparam cfsqltype="cf_sql_varchar" value="#ID#">,
            <cfqueryparam cfsqltype="cf_sql_varchar" value="#results[ID]#">)
    </cfquery>
</cfloop>


text:
Q: Why won't my divs overlap? I'm trying to get these divs to overlap and have the text be inside the triangle but the text can only be moved around outside the triangle.
JSFiddle
This is the HTML+CSS:

        This is test

.tri {
    width: 0;
    height: 0;
    border-top: 100px solid black;
    border-left: 100px solid transparent;
    position:relative;
}

.test {
    display:inline-block;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
    zoom:1;
    margin-top:-80px;
    margin-left:-80px;
    color:red;
}

A: You can simply use position: relative; for the container element and than use position: absolute; for the child element, this way, your absolute positioned element won't flow out in the wild, and will be relative to the parent element, also it will be overlapped this way
Demo

Also it's a CSS triangle with borders and height and width set to 0 respectively, so you cannot expect an the child element to overlap the triangle

A: I'm not entirely sure of what you are trying to achive here.
If you want the text to be inside the black triangle, you could just edit out
display:inline-block;

Worked in JSFiddle, only tested in FireFox and Chrome though, might want to check more browsers.


text:
Q: Suitescript Netsuite create salesorder I am not a suitescript coder. I have JS knowledge. A while back i came across a script which would create an SO for me. The script was similar to the one attached, just that it had the else condition for when "Typeof Value=='object'
function getItems(datain) {
var err = new Object();

// Validate if mandatory record type is set in the request
if (!datain.recordtype)
{
    err.status = "failed";
    err.message= "missing recordtype";
    return err;
}

var record = nlapiCreateRecord(datain.recordtype);

for (var fieldname in datain)
{
 if (datain.hasOwnProperty(fieldname))
 {
     if (fieldname != 'recordtype' && fieldname != 'id')
     {
         var value = datain[fieldname];
        nlapiLogExecution('DEBUG', fieldname);
         // ignore other type of parameters
         if (value && typeof value != 'object')
         {
             record.setFieldValue(fieldname, value);
         }
     }
 }
}
var recordId = nlapiSubmitRecord(record);
nlapiLogExecution('DEBUG','id='+recordId);

// returns the created record in JSON format
 var nlobj = nlapiLoadRecord(datain.recordtype,recordId);
return nlobj;

}
Can someone help me fill the else section where I would process the Items array when the recordtype would be 'salesorder'
Greatly appreciate your help.
Thanks

A: Something like this:
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', 380, true, true);
nlapiSetCurrentLineItemValue('item', 'location', 102, true, true);
nlapiCommitLineItem('item');


text:
Q: How to align only some equations in an align environment? Here's what I got:
\begin{align*}
P[E_{m}] &= P[m] + P[2m] + P[3m] + \dots \\
&= \frac{1}{\varsigma(s)} \langle m^{-s} + (2m)^{-s} + (3m)^{-s} + \dots \rangle \\
&= \frac{1}{\varsigma(s)} \langle \underbrace{1^{-s} + 2^{-s} + 3^{-s} + \dots} \rangle m^{-s} \\
&= \frac{1}{\varsigma(s)} \langle \hspace{13mm} \varsigma(s) \hspace{13mm} \rangle m^{-s} \\
&= m^{-s}
\end{align*}

I now wish to align the last \rangle to the second to last \rangle perfectly and have the \varsigma(s) centered. This without aligning anything to the first \rangle (pretty much as it is now but with perfect and automatic alignment).
I have found this which seemed like what I needed at first but wasn't (as I don't want to align ALL equations to the braces).

A: You can measure the length of the contents within the \langle-\rangle and position \varsigma(s) accordingly:

\documentclass{article}
\usepackage{mathtools}% http://ctan.org/pkg/amsmath
\newlength{\templen}
\settowidth{\templen}{$1^{-s} + 2^{-s} + 3^{-s} + \cdots$}
\begin{document}
\begin{align*}
  P[E_{m}] &= P[m] + P[2m] + P[3m] + \cdots \\
        &= \frac{1}{\varsigma(s)} \langle m^{-s} + (2m)^{-s} + (3m)^{-s} + \cdots \rangle \\
        &= \frac{1}{\varsigma(s)} \langle
          \hspace*{.5\templen}\mathclap{\underbrace{1^{-s} + 2^{-s} + 3^{-s} + \cdots}}\hspace*{.5\templen} \rangle m^{-s} \\
        &= \frac{1}{\varsigma(s)} \langle
          \hspace*{.5\templen}\mathclap{\varsigma(s)}\hspace*{.5\templen} \rangle m^{-s} \\
        &= m^{-s}
\end{align*}
\end{document}

For consistency I've spaced the \underbrace inside a \mathclap as well, since there is otherwise a minor misalignment.
The idea behind this approach is to step halfway into the expected width, then use \mathclap to place content in math-mode, centered in a zero-width box, and then complete the width-adjustment with another step the remaining half-width.

You can also mark the position on the page and calculate distances using the savepos module of zref:
\documentclass{article}
\usepackage{mathtools}% http://ctan.org/pkg/amsmath
\usepackage{zref-savepos}% http://ctan.org/pkg/zref
\makeatletter
% \zsaveposx is defined since 2011/12/05 v2.23 of zref-savepos
\@ifundefined{zsaveposx}{\let\zsaveposx\zsavepos}{}
\makeatother
\newcounter{hposcnt}
\renewcommand*{\thehposcnt}{hpos\number\value{hposcnt}}
\newcommand*{\SPl}{% set left position
  \stepcounter{hposcnt}%
  \zsaveposx{\thehposcnt spl}%
}
\newcommand*{\SPr}{% set right position
  \zsaveposx{\thehposcnt spr}%
}

\makeatother
\begin{document}
\begin{align*}
  P[E_{m}] &= P[m] + P[2m] + P[3m] + \cdots \\
        &= \frac{1}{\varsigma(s)} \langle m^{-s} + (2m)^{-s} + (3m)^{-s} + \cdots \rangle \\
        &= \frac{1}{\varsigma(s)} \langle
          \SPl\underbrace{1^{-s} + 2^{-s} + 3^{-s} + \cdots}\SPr \rangle m^{-s} \\
        &= \frac{1}{\varsigma(s)} \langle
          \makebox[\dimexpr\zposx{\thehposcnt spr}sp-\zposx{\thehposcnt spl}sp]{$\varsigma(s)$} \rangle m^{-s} \\
        &= m^{-s}
\end{align*}
\end{document}

It requires you to mark the left and right position using \SPl and \SPr, and then immediately use it to calculate the difference between the points (before setting another left/right mark).

A: Getting your readers to figure out that the object that the \underbrace is supposed to be pointing to is the lonely \varsigma(s) term on the next line down may require some luck, even if the angle brackets are lined up perfectly. It may be wiser to write =\varsigma(s) directly below the underbrace and then provide just a little bit of redundancy in the next line:

\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align*}
P[E_{m}] &= P[m] + P[2m] + P[3m] + \dots \\
&= \frac{1}{\varsigma(s)} \langle m^{-s} + (2m)^{-s} + (3m)^{-s} + \dots \rangle \\
&= \frac{1}{\varsigma(s)} \langle\, \underbrace{1^{-s} + 2^{-s} + 3^{-s} + \dots}_{=\varsigma(s)}\, \rangle m^{-s} \\
&= \frac{1}{\varsigma(s)} \langle \varsigma(s) \rangle m^{-s} \\
&= m^{-s}
\end{align*}
\end{document}


text:
Q: Main Class Not Found I am to connect to a MySQL database from a Java application to store images taken from a scanned form. When I run the program I get a Could not find or load main class error.
I have tried setting the classpath but still get the same error: Could not find or load main class. By the way, another java file I created in the directory compiles. When I try to set the classpath I also get the same error. Here is the (EDITED)code:
java -cp "C:\Documents and Settings\xxx\Desktop\ttt_manual_yyy\mysql\mysql-connector-java-5.1.6-bin" ImageUploader C:\Documents and Settings\yyy\Desktop\IMAGES localhost uuu nnn

Where localhost is database address,uuu is username,nnn is password

A: You're not even specifying a class, and you need to put your classpath in quotes as it's got spaces. So it should be something like:
java -classpath "C:\Documents and Settings\...\ImageUpload" foo.ImageUploader

where foo.ImageUploader is the fully-qualified name of the class containing the main method.


text:
Q: How to build docker image to refer to the python library in venv I am trying to dockerise my Django web-application, which run on virtual environment venv.
This is my config for my Dockerfile:
FROM ppc64le/python:2.7

ENV PYTHONUNBUFFERED 1
ENV DJANGO_SETTINGS_MODULE=agricultureProj.settings.deploy
ENV UWSGI_VIRTUALENV=/venv
UWSGI_WSGI_FILE=agricultureProj/wsgi.py
UWSGI_HTTP=:8005
UWSGI_MASTER=1
UWSGI_WORKERS=2
UWSGI_THREADS=8
UWSGI_UID=1000
UWSGI_GID=2000
UWSGI_LAZY_APPS=1
UWSGI_WSGI_ENV_BEHAVIOR=holy

RUN virtualenv venv
RUN source /venv/bin/activate
RUN mkdir /code
WORKDIR /code

ADD requirements.txt /code/
RUN pip install -r requirements.txt

ADD . /code/

EXPOSE 8005

COPY ./docker-entrypoint.sh /
RUN chmod uog+rx ./docker-entrypoint.sh
ENTRYPOINT ["sh","/docker-entrypoint.sh"]

CMD ["/venv/bin/activate", "--http-auto-chunked", "--http-keepalive"

I would like to know how should I define my Dockerfile so that i can directly refer to the existing Python library and successful build and compose run my docker image for this.
**Append:
This is the error I have encountered after the successful docker image built.
Error:
Recreating agricultureproj_db_1
Recreating agricultureproj_web_1
Attaching to agricultureproj_db_1, agricultureproj_web_1
db_1   | /docker-entrypoint.sh: 3: /docker-entrypoint.sh: source: not found
web_1  | ----------
db_1   | ----------
web_1  | ['/home/ppt/Elephas2/agricultureProj_v6_723/agricultureProj',
db_1   | ['/home/ppt/Elephas2/agricultureProj_v6_723/agricultureProj',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/plat-powerpc64le-linux-gnu',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/plat-powerpc64le-linux-gnu',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-tk',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-tk',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-old',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-old',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-dynload',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-dynload',
web_1  |  '/usr/lib/python2.7',
db_1   |  '/usr/lib/python2.7',
web_1  |  '/usr/lib/python2.7/plat-powerpc64le-linux-gnu',
db_1   |  '/usr/lib/python2.7/plat-powerpc64le-linux-gnu',
web_1  |  '/usr/lib/python2.7/lib-tk',
db_1   |  '/usr/lib/python2.7/lib-tk',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/local/lib/python2.7/site-packages',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/local/lib/python2.7/site-packages',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/site-packages',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/site-packages',
web_1  |  '/usr/lib/python2.7/dist-packages',
db_1   |  '/usr/lib/python2.7/dist-packages',
web_1  |  '/usr/lib/python2.7/dist-packages/cv2.powerpc64le-linux-gnu.so']
db_1   |  '/usr/lib/python2.7/dist-packages/cv2.powerpc64le-linux-gnu.so']
web_1  | ----------
db_1   | ----------
web_1  | Traceback (most recent call last):
web_1  |   File "manage.py", line 37, in <module>
db_1   | Traceback (most recent call last):
web_1  |     "Couldn't import Django. Are you sure it's installed and "
db_1   |   File "manage.py", line 37, in <module>
web_1  | ImportError: Couldn't import Django. Are you sure it's installed and
available on your PYTHONPATH environment variable? Did you forget to activate
a virtual environment?
db_1   |     "Couldn't import Django. Are you sure it's installed and "
web_1  | ----------
db_1   | ImportError: Couldn't import Django. Are you sure it's installed and
available on your PYTHONPATH environment variable? Did you forget to activate
a virtual environment?
web_1  | ['/home/ppt/Elephas2/agricultureProj_v6_723/agricultureProj',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/plat-powerpc64le-linux-gnu',
db_1   | ----------
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-tk',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-old',
db_1   | ['/home/ppt/Elephas2/agricultureProj_v6_723/agricultureProj',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-dynload',
web_1  |  '/usr/lib/python2.7',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7',
web_1  |  '/usr/lib/python2.7/plat-powerpc64le-linux-gnu',
web_1  |  '/usr/lib/python2.7/lib-tk',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/plat-powerpc64le-linux-gnu',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/local/lib/python2.7/site-packages',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-tk',
web_1  |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/site-packages',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-old',
web_1  |  '/usr/lib/python2.7/dist-packages',
web_1  |  '/usr/lib/python2.7/dist-packages/cv2.powerpc64le-linux-gnu.so']
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/lib-dynload',
web_1  | ----------
db_1   |  '/usr/lib/python2.7',
db_1   |  '/usr/lib/python2.7/plat-powerpc64le-linux-gnu',
web_1  | Traceback (most recent call last):
web_1  |   File "manage.py", line 37, in <module>
web_1  |     "Couldn't import Django. Are you sure it's installed and "
db_1   |  '/usr/lib/python2.7/lib-tk',
web_1  | ImportError: Couldn't import Django. Are you sure it's installed and
available on your PYTHONPATH environment variable? Did you forget to activate
a virtual environment?
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/local/lib/python2.7/site-packages',
db_1   |  '/home/ppt/Elephas2/agricultureProj_v6_723
/agricultureProj/venv/lib/python2.7/site-packages',
db_1   |  '/usr/lib/python2.7/dist-packages',
db_1   |  '/usr/lib/python2.7/dist-packages/cv2.powerpc64le-linux-gnu.so']
db_1   | ----------
db_1   | Traceback (most recent call last):
db_1   |   File "manage.py", line 37, in <module>
db_1   |     "Couldn't import Django. Are you sure it's installed and "
db_1   | ImportError: Couldn't import Django. Are you sure it's installed and
available on your PYTHONPATH environment variable? Did you forget to activate
a virtual environment?
agricultureproj_web_1 exited with code 1
agricultureproj_db_1 exited with code 1
ppt@server:~/Elephas2/agricultureProj_v6_723/agricultureProj$ File
"manage.py", line 37, in <module>
-bash: syntax error near unexpected token `newline'
ppt@server:~/Elephas2/agricultureProj_v6_723/agricultureProj$ db_1   |
"Couldn't import Django. Are you sure it's installed and "
db_1: command not found
Couldn't import Django. Are you sure it's installed and : command not found
ppt@server:~/Elephas2/agricultureProj_v6_723/agricultureProj$ db_1   |
ImportError: Couldn't import Django. Are you sure it's installed and
available on
your PYTHONPATH environment variable? Did you forget to activate a virtual
environment?
db_1: command not found
ImportError:: command not found

When I try to docker-compose up the created image, the environment failed to import Django.

A: Don't activate the virtual environment, just add its bin directory to the start of PATH environment variable. That is generally sufficient.
You should also avoid running your image as root. Even in a container that is not a good practice.

A: You can use --system-site-packages to indicate venv to use the system libraries in precedence which means change this line and then indicate pip to ignore system installed libraries
RUN virtualenv --system-site-packages venv
RUN source /venv/bin/activate
RUN mkdir /code WORKDIR /code
ADD requirements.txt /code/
RUN pip install --ignore-installed -r requirements.txt


text:
Q: How to obtain utc time in jQuery datetimepicker I am using the trying this jQuery datetimepicker to obtain date and time data.
I am able to get most of the things out (format, display, etc). However, I wasn't able to get  the date and time in UTC format. I am only able to obtain the date and time in local format.
Does anyone know how to modify it to get the date and time?
or remove off the "Now" button in the popup?

A: I ran into the same issue today, and found this old thread. You can override $.datepicker._gotoToday to use UTC Time when you click the "now" button.
//make the now button go to "now" in utc, not local
$.datepicker._gotoToday = function(id) {
  var inst = this._getInst($(id)[0]),
      $dp = inst.dpDiv;
  this._base_gotoToday(id);
  var tp_inst = this._get(inst, 'timepicker');
  //removed -> selectLocalTimeZone(tp_inst);
  var now = new Date();
  var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
  this._setTime(inst, now_utc);
  $('.ui-datepicker-today', $dp).click();
};

A: Without any extra libs you can use the utility methods below to do the following:
var dateFromPicker = getDateFromPicker();
var dateUtc = localAsUtc(dateFromPicker);
var iso = dateUtc.toISOString(); // returns "2016-12-06T00:00:00.000Z"

/**
 * WARNING: This method should only be used in conjunction with components that handle local dates (i.e. date pickers).
 *
 * Returns a local date constructed from a UTC date (shifts the time by the local time zone). E.g.:
 *

2016-01-01T00:00Z (UTC) -> 2016-01-01T00:00-0100 (CVT)
 *
2016-01-01T00:00Z (UTC) -> 2016-01-01T00:00+0100 (CET)
 *

 * @param date a date in UTC time zone
 * @returns {Date} the same date & time in the local time zone
 */
function utcAsLocal(date) {
    if (isNotValidDate(date)) {
        return null;
    }

    return new Date(
        date.getUTCFullYear(),
        date.getUTCMonth(),
        date.getUTCDate(),
        date.getUTCHours(),
        date.getUTCMinutes(),
        date.getUTCSeconds(),
        date.getUTCMilliseconds()
    );
}

/**
 * WARNING: This method should only be used in conjunction with components that handle local dates (i.e. date pickers).
 *
 * Returns a UTC date constructed from a local date (shifts the time by the local time zone). E.g.:
 *

2016-01-01T00:00-0100 (CVT) -> 2016-01-01T00:00Z (UTC)
 *
2016-01-01T00:00+0100 (GMT) -> 2016-01-01T00:00Z (UTC)
 *

 * @param date a date in UTC time zone
 * @returns {Date} the same date & time in the UTC time zone
 */
function localAsUtc(date) {
    if (isNotValidDate(date)) {
        return null;
    }

    return new Date(Date.UTC(
        date.getFullYear(),
        date.getMonth(),
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    ));
}

function isValidDate (date) {
    return !isNotValidDate(date);
}

function isNotValidDate(date) {
    return date == null || isNaN(date.getTime());
}

Here are a few examples which simulate time zones before and after UTC:

var date;

// simulate a datepicker in (CET)
date = new Date("2016-12-06T00:00:00.000+0100");
date.toISOString(); // "2016-12-05T23:00:00.000Z"
date = localAsUtc(date);
date.toISOString(); // "2016-12-06T00:00:00.000Z" sent to server

// simulate a datepicker in (CVT)
date = new Date("2016-12-06T00:00:00.000-0100");
date.toISOString(); // "2016-12-06T01:00:00.000Z"
date = localAsUtc(date);
date.toISOString(); // "2016-12-06T00:00:00.000Z" sent to server

// setting the datepicker date (CET)
date = new Date("2016-12-06T00:00:00.000Z"); // received from server
date.toISOString(); // "2016-12-06T00:00:00.000Z"
date = utcAsLocal(date); // set datepicker with this date shows (06/12/2016)
date.toISOString(); // "2016-12-05T23:00:00.000Z"

// setting the datepicker date (CVT)
date = new Date("2016-12-06T00:00:00.000Z"); // received from server
date.toISOString(); // "2016-12-06T00:00:00.000Z"
date = utcAsLocal(date); // set datepicker with this date shows (06/12/2016)
date.toISOString(); // "2016-12-06T01:00:00.000Z"

but the answer wouldn't be complete without mentioning the moment.js which makes handling dates a heck of a lot easier.