text:
Q: MySQL Case Statement for proper bucketing reposting this question as I am still struggling to find the right solution.
I was able to isolate the 'OA' only scenarios and flag them appropriately as NA. However I am having trouble isolating the 'I' only events as well as properly aging the EquipID's that have both I and OA events.
This is the logic I am using for aging right now and it works great for 'I' only events, but properly isolating the 'I' and 'OA' EquipID's and then getting the difference between the two dates is eluding me.
datediff(curdate(),concat(left(eventDateTime,4),'-',mid(eventDateTime,5,2),'-',mid(eventDateTime,7,2))) as age_in_depot
I tried grouping by the EquipID but of course that gives me only one eventDateTime result and it is always the first result, which in the case of an 'I' and 'OA' it's only the 'I' eventDateTime.
I also have logic to identify the 'I' and 'OA' events, but this only works correctly if I am intending on grouping the EquipmentID's together to one line, which noted above, drops the 2nd eventDateTime entry needed to properly age these EquipID's.
GROUP_CONCAT( DISTINCT StatusCD) as StatusCD

Any help or insight is greatly appreciated. Once I have this 'I' only event flagged and aging I can finally finish out this dashboard I am building for our team.
Thank you in advance.
J

A: Pivot the table so you get the in and out dates into separate columns for the same EquipID. Then you can subtract them, and apply appropriate defaults for the missing dates.
SELECT EquipID, InDate, OutDate, StatusCD_N,
    CASE WHEN InDate AND OutDate THEN DATEDIFF(OutDate, InDate)
         WHEN InDate THEN DATEDIFF(CURDATE(), InDate)
         ELSE 'N/A' -- only OutDate
    END AS AgeInDepot
FROM (
    SELECT EquipID, GROUP_CONCAT(StatusCD) AS StatsuCD_N,
        MAX(IF(StatusCD = 'I', DATE(STR_TO_DATE(eventDateTime, '%Y%m%d%H%i')), NULL) AS InDate,
        MAX(IF(StatusCD = 'OA', DATE(STR_TO_DATE(eventDateTime, '%Y%m%d%H%i')), NULL) AS OutDate
    FROM yourTable
    GROUP BY EquipID
) AS x


text:
Q: Transposing tables in place in Word using VBA I'm trying to write a method to transpose tables in Word using Visual Basic and the Excel object model. However, I'm having trouble using paste special with the copied Word object, since its not just plain text.
Is it possible to force a plain text paste with transpose? Is there a better way to do this?
My current code is as follows:
Public Sub transposeTable()

Selection.Copy
Dim oXlApp As New Excel.Application
Dim oXlBook As Excel.Workbook
Set oXlApp = CreateObject(Class:="Excel.Application")
Set oXlBook = oXlApp.Workbooks.Add
oXlBook.Sheets(1).Range("A1").Select
oXlApp.ActiveCell.PasteSpecial Transpose:=True
oXlBook.Sheets(1).Cells.SpecialCells(xlCellTypeConstants).Select
oXlApp.Selection.Copy
Selection.Paste
End Sub

The error I'm recieving is:
Run-time error '1004':
PasteSpecial method of Range class failed

A: Have you tried pasting without the formatting?
oXlApp.ActiveCell.PasteSpecial Paste:=xlPasteValues, Transpose:=True

A: I've managed to get it working now, using an intermediate paste step.
Public Sub transposeTable()

Selection.Cut
Dim oXlApp As New Excel.Application
Dim oXlBook As Excel.Workbook
Set oXlApp = CreateObject(Class:="Excel.Application")
Set oXlBook = oXlApp.Workbooks.Add
oXlBook.Sheets(1).Range("A1").Select
oXlApp.ActiveSheet.Paste
oXlBook.Sheets(1).Cells.SpecialCells(xlCellTypeConstants).Select
oXlApp.Selection.Copy
oXlBook.Sheets(2).Select
oXlBook.Sheets(2).Range("A1").Select
oXlApp.ActiveCell.PasteSpecial Transpose:=True
oXlBook.Sheets(2).Cells.SpecialCells(xlCellTypeConstants).Select
oXlApp.Selection.Copy
Selection.Paste
oXlBook.Close (False)
oXlApp.Quit
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flink SQL - How to parse a TIMESTAMP with custom pattern? From documentation it looks like Flink's SQL can only parse timestamps in a certain format, namely:

TIMESTAMP string: Parses a timestamp string in the form "yy-mm-dd hh:mm:ss.fff" to a SQL timestamp.

Is there any way to pass in a custom DateTimeFormatter to parse a different kind of timestamp format?

A: You can implement any parsing logic using a user-defined scalar function (UDF).
This would look in Scala as follows.
class TsParser extends ScalarFunction {
  def eval(s: String): Timestamp = {
    // your logic
  }
}

Once defined the function has to be registered at the TableEnvironment:
tableEnv.registerFunction("tsParser", new TsParser())

Now you can use the function tsParser just like any built-in function.
See the documentation for details.


text:
Q: Prism.js not showing markup I am using the Prism.js plugin. I have a text field where you can type/paste your code, click "Submit," and it will display it in a div below the textarea. I've also included a dropdown where you can pick the language you're using from a list. Everything works great, except that any < > tags do not show up (i.e. html tags, preprocessor directives in C/C++, etc). Does anyone know if I missed a plugin from the download page?
I've made it to where instead of specifying a specific language with

I've made it where the php will append the class name from the dropdown.
Here is my code. As I said, everything is working except those tags:
The HTML:
<select required name="language-select" class="form-control" id="language-selector">
            <option value="" selected disabled>Language</option>
            <option value="markup">Markup</option>
            <option value="apacheconf">Apache Conf</option>
            <option value="aspnet">ASP.NET</option>
            <option value="bash">Bash</option>
            <option value="c">C</option>
            <option value="csharp">C#</option>
            <option value="cpp">C++</option>
            <option value="css">CSS</option>
            <option value="java">Java</option>
            <option value="javascript">JavaScript</option>
            <option value="matlab">MatLab</option>
            <option value="objectivec">Objective C</option>
            <option value="perl">Perl</option>
            <option value="php">PHP</option>
            <option value="powershell">PowerShell</option>
            <option value="python">Python</option>
            <option value="ruby">Ruby</option>
            <option value="scala">Scala</option>
            <option value="smalltalk">Smalltalk</option>
            <option value="sql">SQL</option>
        </select>

        <button id="drive_submit_btn" class="btn btn-md" type="submit">Submit</button>

</form>

<code class="language-<?php echo $language?>"><?php echo $user_code; ?>

The relevant PHP:
$user_code = "";
$language = "";
if (!empty($_POST["code_input"])) { //get input from textarea and dropdown
$user_code = $_POST["code_input"];
$language = $_POST['language-select'];

}
Here is a screenshot to show that code works, except for the <> tags:
Before "Submit", I choose the C language:

And here is after submission. Notice how the #include is missing the <> tags? I don't know how to fix this. Any suggestions?

A: I discovered from this StackOverflow question that any '<' or '>' characters must be replaced with
< and >

respectively. Since the text is dynamic, this took some thinking.....
Here is what fixed my problem. I used the str_replace() function in php to find any occurrence of '<' or '>' and replace with those characters. Here is the code to do that in case anyone runs into the same problem in PHP:
$user_code = str_replace(array('<','>'), array('<', '>'), $_POST["code_input"]);

And to show how it looks visually, here is a screenshot of the result:

I could also do an associative array for better readability:
$user_code = strtr($_POST['code_input'], [
        '<' => '<',
        '>' => '>'
]);

Both produce the same result. Boom. :-)


text:
Q: Is the Verizon iPhone 5 (unlocked) compatible with Rogers? Would I get LTE from a Verizon iPhone 5 on Rogers?
According to Apple's LTE page I won't be getting LTE?

A: Yes, that's correct, Verizon's iPhone 5 won't work on the Rogers LTE network.
According to Rogers' iPhone 5 page, the specs include:

LTE Bands:700/1700

In the Apple iPhone 5 page you've quoted, you need to get model A1428 which supports LTE Band 17 (700 MHz). Rogers is explicitly listed there as one of the supported LTE networks. If you want to get an unlocked Verizon iPhone 5 (model A1429 CDMA), you won't be able to use LTE on the Rogers network. You'd be better off getting the unlocked AT&T version.

A: No, the LTE bands used by Rogers are different than those supported by the Verizon iPhone 5. You will be able to get 3G and voice access, but not LTE.


text:
Q: How do I get basic ProxyPass to work on Apache 2.2.17? I'm trying to get around the ERR_UNSAFE_PORT restriction in Chrome by making Apache reverse proxy other HTTP servers on the machine.

*

*I load mod_proxy with sudo e2enmod proxy

*I add ProxyPass /znc/ http://localhost:6667/ to my httpd.conf

*I restart Apache with sudo /etc/init.d/apache2 restart
When I open up /znc/, I get 500 Internal Server Error. I added LogLevel debug, restarted apache, tried again, and got nothing suspicous:
[Fri Oct 19 18:55:17 2012] [debug] proxy_util.c(1818): proxy: grabbed scoreboard slot 0 in child 21528 for worker http://localhost:6667/
[Fri Oct 19 18:55:17 2012] [debug] proxy_util.c(1934): proxy: initialized single connection worker 0 in child 21528 for (localhost)
[Fri Oct 19 18:55:17 2012] [debug] proxy_util.c(1818): proxy: grabbed scoreboard slot 1 in child 21528 for worker proxy:reverse
[Fri Oct 19 18:55:17 2012] [debug] proxy_util.c(1934): proxy: initialized single connection worker 1 in child 21528 for (*)
[Fri Oct 19 18:55:17 2012] [notice] Apache/2.2.17 (Ubuntu) PHP/5.3.8 configured -- resuming normal operations
[Fri Oct 19 18:55:17 2012] [info] Server built: Feb 14 2012 17:59:20
[Fri Oct 19 18:55:17 2012] [debug] prefork.c(1018): AcceptMutex: sysvsem (default: sysvsem)
[Fri Oct 19 18:55:22 2012] [debug] proxy_util.c(1818): proxy: grabbed scoreboard slot 0 in child 21532 for worker http://localhost:6667/
[Fri Oct 19 18:55:22 2012] [debug] proxy_util.c(1837): proxy: worker http://localhost:6667/ already initialized
[Fri Oct 19 18:55:22 2012] [debug] proxy_util.c(1934): proxy: initialized single connection worker 0 in child 21532 for (localhost)
[Fri Oct 19 18:55:22 2012] [debug] proxy_util.c(1818): proxy: grabbed scoreboard slot 1 in child 21532 for worker proxy:reverse
[Fri Oct 19 18:55:22 2012] [debug] proxy_util.c(1837): proxy: worker proxy:reverse already initialized
[Fri Oct 19 18:55:22 2012] [debug] proxy_util.c(1934): proxy: initialized single connection worker 1 in child 21532 for (*)

So I'm stumped at this point. What to do?
I'm running Ubuntu Server 11.10. ZNC responds with a correct 200 OK and HTML when queried directly both from the local machine and the Internet.

A: One must also enable mod_proxy_http with sudo a2enmod proxy_http.


text:
Q: The repository primary signature validity period has expired I am getting this error in the Build and Deploy job phase of an Azure Static Web Apps CI/CD check-in.  The first part of the error message is:
Run cd UnoPhotoViewer/UnoPhotoViewer.Wasm
Microsoft (R) Build Engine version 16.8.3+39993bd9d for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
/home/runner/work/PhotoViewer/PhotoViewer/UnoPhotoViewer/UnoPhotoViewer.Wasm/UnoPhotoViewer.Wasm.csproj : error NU3028: Package 'runtime.rhel.7-x64.runtime.native.System.Security.Cryptography.OpenSsl 4.3.0' from source 'https://api.nuget.org/v3/index.json': The repository primary signature's timestamp found a chain building issue: UntrustedRoot: self signed certificate in certificate chain
/home/runner/work/PhotoViewer/PhotoViewer/UnoPhotoViewer/UnoPhotoViewer.Wasm/UnoPhotoViewer.Wasm.csproj : error NU3037: Package 'runtime.rhel.7-x64.runtime.native.System.Security.Cryptography.OpenSsl 4.3.0' from source 'https://api.nuget.org/v3/index.json': The repository primary signature validity period has expired.

It appears that all project nuget dependencies are throwing similar messages.
My Nuget Package Manager has both Allow Nuget to download missing packages AND Automatically check for missing packages during build in Visual Studio CHECKED.
Does anyone know what is causing this and how to resolve?
Thanks


text:
Q: project publishing to windows web server 2008 I am working with a Visual Studio 2008 (C#) project on Windows XP Pro. I am trying to publish that application using "Publish Web" wizard to a remote server which is Windows Web Server 2008 OS.
But the publishing fails every time with following error:
 Connecting to http://XX.XXX.XXX.XX/...
 Unable to create the Web site
 'http://XX.XXX.XXX.XX/'. The Web
 server does not appear to have
 FrontPage Server Extensions installed.
 ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped
 ==========
 ========== Publish: 0 succeeded, 1 failed, 0 skipped ==========

I used these links:

*

*http://learn.iis.net/page.aspx/134/install-frontpage-server-extensions/

*http://www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1630

*http://www.rtr.com/fpse/
I have installed FrontPage Server extensions from above links without any problems on the remote server.
And extend the Virtual Server (the "Default Web Site").
However, the problem remains. I cannot find any solution to this issue.

A: ok problem is solved.
it was an user authorization issue. I set the user as admin for remote server.

A: I've had problems with the http publishing more often than not. I've worked around it by setting up an ftp directory that maps to the web app directory and using the ftp address from the wizard.


text:
Q: How many league Quidditch teams are there in Britain? In the Harry Potter books, how many Quidditch teams are there in Britain (professional ones - where players get paid for playing)?

A: According to Quidditch Through the Ages:

"While amateur games are permitted as long as the appropriate guidelines are followed, professional Quidditch teams have been limited in number since 1674 when the League was established. At that time, the thirteen best Quidditch teams in Britain were selected to join the League and all others were asked to disband. The thirteen teams continue to compete each year for the League cup.
Quidditch Through the Ages - pages 31-32 - US Edition

The thirteen British Quidditch teams are:

*

*Appleby Arrows (Northern England)

*Ballycastle Bats (Northern Ireland)

*Caerphilly Catapults (Wales)

*Chudley Cannons

*Falmouth Falcons

*Holyhead Harpies (Wales)

*Kenmare Kestrels (Ireland)

*Montrose Magpies

*Pride of Portree (Isle of Skye - Scotland)

*Puddlemere United

*Tutshill Tornadoes (England)

*Wigtown Wanderers

*Wimbourne Wasps

So there are thirteen professional Quidditch teams in Potterverse. As "Britain" refers to the United Kingdom, which includes England, Wales, Scotland, and Northern Ireland, I'm guessing technically the Kenmare Kestrels perhaps should not be counted as a British team, as they are Irish (as opposed to Northern Irish). That would technically make twelve British teams.
But JKR says there are thirteen!
ETA: Definition of what constitutes Britain. From the Wiki:

Although the United Kingdom, as a sovereign state, is a country, England, Scotland, Wales and Northern Ireland [all considered part of the UK] are also referred to as countries, whether or not they are sovereign states or have devolved or other self-government. The British Prime Minister's website has used the phrase "countries within a country" to describe the United Kingdom. With regard to Northern Ireland, the descriptive name used "can be controversial, with the choice often revealing one's political preferences." Other terms used for Northern Ireland include "region" and "province".
The United Kingdom is often referred to as Britain. British government sources frequently use the term as a short form for the United Kingdom, whilst media style guides generally allow its use but point out that the longer term Great Britain refers only to England, Scotland and Wales.

Both definitions exclude Ireland and the latter excludes Northern Ireland.

A: UPDATE 2: Wikia for British and Irish Quidditch League states that there are 13:

The British and Irish Quidditch League was established in 1674. Due to the need to maintain anti-Muggle security, the professional League was formed of the thirteen best teams at the time, and all others were asked to disband.

This is sourced from Quidditch Through the Ages

UPDATE: Actually, at least 12
Wikia (citing Daily Prophet Newsletters) states that "On October 1st the Chudley Cannons were in eleventh place in the League". Same source indicates that they were actually above Falmouth Falcons team in the league, who must have been then at least 12th

Seems to be at least 9.

"The Chudley Cannons," said Ron, pointing at the orange bedspread, which was emblazoned with two giant black C's and a speeding cannonball. "Ninth in the league." - Harry Potter & The Chamber Of Secrets, Ch 3


text:
Q: For loop doesn't print last substring I want to make a program which replaces a series of ascii codes to a string. Example input:
strin1 = "65 66 67 68 69"

But every time I run the program the result of the last ascii number is not produced. It just displays (note the missing 69):
65
66
67
68

This is my code:
cyfry = str(raw_input("put numbers here: "))
str = ""
length1 =  len(cyfry)

for a in range(0,length1,1):
   if (cyfry[a] != " "):
      str += cyfry[a]
   else:
      print str
      str = ""

Why is not the last substring not printed?

A: Your code only prints something when it arrives at a space. As your input does not end in a space, it does not print what str contains when you reach the end of the input.
A simple solution is to add print str at the very end of your program (outside of the loop).
Note that you can use cyfry.split(" ") to get the "words" into a list. And then you can use int() to convert such a word into an integer. chr() can be used to get the character for that numerical code. Finally, you can join those individual characters to a new string with ''.join():
cyfry = raw_input("put numbers here: ")

str = ''.join([chr(int(ch)) for ch in cyfry.split(" ")])
print str


text:
Q: mongodb. background index and lock collection? Please tell me if I will use background index
db.collection.ensureIndex({ a: 1 }, {background: true})

my collection not locked when several insert is doing?

A: There are no long-term locks held while building an index in background on the a single node. However on a replica-set you have to be careful on how the index build happens on different nodes of the replica-set.
MongoDB v2.4 or lower version
- Background build triggered on Primary replica results in foreground index build on the Secondary replica and will be blocking operation on the secondary
- To avoid the foreground build on the secondary, suggested way to build indices in replica-set is to do a rolling index build. You can find more details about it at http://docs.mongodb.org/v2.4/tutorial/build-indexes-on-replica-sets/
MongoDB 2.5 or higher version
On the latest available versions of MongoDB (v2.6) the background index build on Primary replica will be background on the Secondary replica as well.
Apart from locking, index building is RAM / CPU / Disk intensive operation and pressure on these resources may vary based on the dataset. I would recommend doing index builds at relatively quiet time in production environments.

A: This section from the Mongo manual provides direct answer, if your version is 4.2 or greater.
https://www.mongodb.com/docs/rapid/core/index-creation/#std-label-index-operations-replicated-build

Starting in MongoDB 4.2, index builds obtain an exclusive lock on only the collection being indexed during the start and end of the build process to protect metadata changes. The rest of the build process uses the yielding behavior of background index builds to maximize read-write access to the collection during the build. 4.2 index builds still produce efficient index data structures despite the more permissive locking behavior.

There's also a section covering previous versions

Previous versions of MongoDB supported building indexes either in the foreground or background. Foreground index builds were fast and produced more efficient index data structures, but required blocking all read-write access to the parent database of the collection being indexed for the duration of the build. Background index builds were slower and had less efficient results, but allowed read-write access to the database and its collections during the build process.


text:
Q: Force Vimeo HTML5 Video Embed I'm trying to embed a Vimeo video and force it to use HTML5 by default.
Here's a thread about doing the same thing I'm tying to do but with YouTube.
Here's another thread talking about getting the Vimeo HTML5 cookie
Here's a discussion of the issue on Vimeo's site. Basically, I would be doing it in response to a user's preference on my site so their concerns don't really apply.
Does anyone know a workaround or way to force HTML5 Vimeo embeds even when Flash is available?  (I know the cookie should work in Safari but I have many Chrome users.)
Thanks.

A: Currently there is no way to force HTML5 with the embed script. The "universal player" automatically chooses the format based on the device.
The old embed provides a way to force Flash, but that's the only other option.
Let's hope for the option in the future.

A: On a browser with flash the player loads in html5 mode with the following code. The sandbox prevents the iframe from accessing any plugins including flash.
<iframe sandbox="allow-same-origin allow-scripts allow-popups"
  id="foo" width="100%" height="90%"
  allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen=""
  src="http://player.vimeo.com/video/28544156?api=1">
</iframe>

To allow the vimeo button to open the vimeo web page for the video you need the 'allow-popups' permission. It's not needed to play the video.
Edit: adding complete example
If you had just a black view it's possible that the video had a size of zero because I had the iframe set to fill parent with width 100%, but if the parent was shrink to fit then that size would still be zero. Here is a whole web page with the CSS to make the video fill up most of the page. Additionally the -webkit-transform will mirror image the video, and then rotate it slightly. If it was displaying in flash this would produce a black screen as it can't handle rotations at all. I have since found out that this probably won't work on firefox at all because it doesn't natively support h.264 which is all vimeo serves, and disabling plugins will disable whatever plugin is making h.264 work on firefox.
<!DOCTYPE html>
<html>
  <head>
    <style>
div {
  display: inline-block;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  position: absolute;
}
iframe {
  -webkit-transform: scaleX(-1) rotate(2deg);
}
    </style>
  </head>
  <body>
    <div>
      <iframe sandbox="allow-same-origin allow-scripts allow-popups"
        id="foo" width="100%" height="90%"
        allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen=""
        src="http://player.vimeo.com/video/28544156?api=1">
      </iframe>
    </div>
  </body>
</html>


text:
Q: Get bits from a ByteBuffer I am working on a BitBuffer that will take x bits from a ByteBuffer as an int, long, etc, but I seem to be having a whole lot of problems.
I've tried loading a long at a time and using bit shifting, but the difficulty comes from rolling from one long into the next. I am wondering if there's just a better way. Anyone have any suggestions?
public class BitBuffer
{
    final private ByteBuffer bb;

    public BitBuffer(byte[] bytes)
    {
        this.bb = ByteBuffer.wrap(bytes);
    }

    public int takeInt(int bits)
    {
        int bytes = toBytes(bits);
        if (bytes > 4) throw new RuntimeException("Too many bits requested");

        int i=0;
        // take bits from bb and fill it into an int
        return i;
    }
}

More specifically, I am trying to take x bits from the buffer and return them as an int (the minimal case). I can access bytes from the buffer, but let's say I only want to take just the first 4 bits instead.
Example:
If my buffer is filled with "101100001111", if I run these in order:
takeInt(4) // should return 11    (1011)
takeInt(2) // should return 0     (00)
takeInt(2) // should return 0     (00)
takeInt(1) // should return 1     (1)
takeInt(3) // should return 7     (111)

I would like to use something like this for bit packed encoded data where an integer can be stored in just a few bits of a byte.

A: The BitSet and ByteBuffer ideas were a bit too difficult to control so instead, I went with a binary string approach that basically takes a whole lot of headache out of managing an intermediate buffer of bits.
public class BitBuffer
{
    final private String bin;
    private int start;

    public BitBuffer(byte[] bytes)
    {
        this.bin = toBinaryString(bytes); // TODO: create this function
        this.start = 0;
    }

    public int takeInt(int nbits)
    {
        // TODO: handle edge cases
        String bits = bin.substring(start, start+=nbits);
        return Integer.parseInt(bits, 2);
    }
}

Out of everything I've tried this was the cleanest and easiest approach, but I am open to suggestions!

A: You can convert the ByteBuffer into BitSet and then you'll have continuous access to the bits
public class BitBuffer
{
    final private BitSet bs;

    public BitBuffer(byte[] bytes)
    {
        this.bs = BitSet.valueOf(bytes);
    }

    public int takeInt(int bits)
    {
        int bytes = toBytes(bits);
        if (bytes > 4) throw new RuntimeException("Too many bits requested");

        int i=0;
        // take bits from bs and fill it into an int
        return i;
    }
}


text:
Q: OpenCV C# iterate Mat object like C++ I'm trying to follow a tutorial of OpenCV which is written in C++ but I need to write it in C#. This works quite ok so far.
As I'm not a C++ developer and not. familiar with the language I came to a point now where I struggle a bit and where I'm not sure if what I did is the equivalent to the C++ version.
This is the code in C++
vector<Point> pointsOfInterest;
Mat_<uchar>::iterator itMask = mask.begin<uchar>();
Mat_<uchar>::iterator end = mask.end<uchar>();
for( ; itMask!=end; ++itMask)
    if(*itMask==255)
        pointsOfInterest.push_back(itMask.pos());

What I read here is a loop, that iterates over the whole Mat and checks if the value at position is 255 and if so, it adds the point to the end of the pointsOfInterest list.
So I guess this means every x,y pixel in the Mat is checked for the value. My equivalent in C# looks like this:
List<Point> pointsOfInterest = new List<Point>();
for(int x = 0;x<mask.Cols;x++)
{
    for(int y=0;y<mask.Rows; y++)
    {
        if (mask.At<int>(x, y) == 255)
            pointsOfInterest.Add(new Point(x, y));
    }
}

but the result I'm getting is not as expected that's why I wonder if this part is really correct? Sometimes the mask.At throws a NullPointer as well which is strange. I'm also wondering that the C++ just iterates a one dimensional array (I think at least) meanwhile C# would need 2-Dimensions.
Can someone confirm that it is the same or does someone know what is wrong and needs to be adjusted?

A: I have also found out that changing the x and y, for the img.At(y,x) , will solve the exception and you will get the points in your list.


text:
Q: Difference between get() and onSnapshot() in Cloud Firestore I am reading some data from Firebase's Cloud Firestore but I've seen several ways to do it. The example I saw used the get and onSnapshot function like this:
db.collection("cities").doc("SF")
 .onSnapshot(doc => {
      console.log(doc.data());
 });

or this
var docRef = db.collection("cities").doc("SF");

docRef.get().then(doc => {
    if (doc.exists) {
         console.log("Document data:", doc.data());
    } else {
         console.log("No such document!");
    }
}).catch(function(error) {
   console.log("Error getting document:", error);
        });

Is there any difference between them?

A: As explained in the doc:

There are two ways to retrieve data stored in Cloud Firestore. Either
of these methods can be used with documents, collections of documents,
or the results of queries:

*

*Call a method to get the data.

*Set a listener to receive data-change events.

When you set a listener, Cloud Firestore sends your listener an
initial snapshot of the data, and then another snapshot each time the
document changes.

When you use get() you "retrieve the content of a single document" only once. It's a kind of "get and forget": If the document changes in the (back-end) Firestore database you will need to call get() again to see the change.
On the opposite, if you use the onSnapshot() method you constantly listen to a document as explained in the doc:

You can listen to a document with the onSnapshot() method. An initial
call using the callback you provide creates a document snapshot
immediately with the current contents of the single document. Then,
each time the contents change, another call updates the document
snapshot.

As explained in these docs, these two methods apply to one document or to a collection of documents (including a query).


text:
Q: Div margin to equal another div's height - JS So my content div is basically hidden behind the header and footer, and has 100% height.
On some pages I want to have a JS script to tell the content div move below the header and I tried it like so but it's not working:
document.getElementById('content').style.marginTop = document.getElementById('header').height + 55;
}

Any ideas?

A: var height = document.getElementById('header').offsetHeight;
document.getElementById('content').style.marginTop = height + "px";


text:
Q: How to Change Summation Expression $\sum_{i=1}^N \mathbf{X}_i^{\top}\mathbf{\Omega}^{-1}\mathbf{X}_i$ into Matrix Expression Let $\mathbf{X}_i$ be a $G \times K$ matrix, and suppose are $i=1,...,N$ of these matrices. Note that
\begin{align}
\sum_{i=1}^N \mathbf{X}_i^{\top}\mathbf{X}_i
&=
\begin{bmatrix}
\mathbf{X}_1^{\top} & \mathbf{X}_2^{\top} & \cdots & \mathbf{X}_N^{\top}
\end{bmatrix}
\begin{bmatrix}
\mathbf{X}_1 \\
\mathbf{X}_2 \\
\vdots \\
\mathbf{X}_N
\end{bmatrix} \\
&=\begin{bmatrix}
\mathbf{X}_1 \\
\mathbf{X}_2 \\
\vdots \\
\mathbf{X}_N
\end{bmatrix}^{\top}
\begin{bmatrix}
\mathbf{X}_1 \\
\mathbf{X}_2 \\
\vdots \\
\mathbf{X}_N
\end{bmatrix} \\
&=\mathbf{X}_{\bullet}^{\top}\mathbf{X}_{\bullet}
\end{align}
where $\mathbf{X}_{\bullet}$ is an $NG \times K$ matrix whose $i^{th}$ row is $\mathbf{X}_i$.
I'd like to do something similar with this summation:
\begin{equation}
\sum_{i=1}^N \mathbf{X}_i^{\top}\mathbf{\Omega}^{-1}\mathbf{X}_i
\end{equation}
where $\mathbf{\Omega}$ is some arbitrary symmetric $G \times G$ matrix, say for illustration
\begin{equation}
\mathbf{\Omega}
=\begin{bmatrix}
g_{11} & g_{12} & \cdots & g_{1G} \\
g_{12} & g_{22} & \cdots & g_{2G} \\
\vdots & \vdots & \ddots & \vdots \\
g_{1G} & g_{2G} & \cdots & g_{GG}
\end{bmatrix}
\end{equation}
This problem is not so simple as the first one, because now I have some $\mathbf{\Omega}^{-1}$ matrix in the middle of the sum. However, I think it can still be expressed in matrix notation.
For those curious, this matrix algebra is behind the theory of Generalized Least Squares. Thanks very much for your help!
Edit I think I have figured it out. I have posted an answer below -- please let me know if you think it's correct!

A: Let's try this.
\begin{align}
\sum_{i=1}^N \mathbf{X}_i^{\top}\mathbf{\Omega}^{-1}\mathbf{X}_i&=\mathbf{X}_1\mathbf{\Omega}^{-1}\mathbf{X}_1+\mathbf{X}_2\mathbf{\Omega}^{-1}\mathbf{X}_2+\cdots+\mathbf{X}_N\mathbf{\Omega}^{-1}\mathbf{X}_N \\
&=\begin{bmatrix}
\mathbf{X}_1^{\top} & \mathbf{X}_2^{\top} & \cdots & \mathbf{X}_N^{\top}
\end{bmatrix}
\begin{bmatrix}
\mathbf{\Omega}^{-1}\mathbf{X}_1 \\
\mathbf{\Omega}^{-1}\mathbf{X}_2 \\
\vdots \\
\mathbf{\Omega}^{-1}\mathbf{X}_N
\end{bmatrix} \\
&=\begin{bmatrix}
\mathbf{X}_1^{\top} & \mathbf{X}_2^{\top} & \cdots & \mathbf{X}_N^{\top}
\end{bmatrix}
\begin{bmatrix}
\mathbf{\Omega}^{-1} & \mathbf{0} & \cdots & \mathbf{0} \\
\mathbf{0} & \mathbf{\Omega}^{-1} & \cdots & \mathbf{0} \\
\vdots & \vdots & \ddots & \vdots \\
\mathbf{0} & \mathbf{0} & \cdots & \mathbf{\Omega}^{-1}
\end{bmatrix}
\begin{bmatrix}
\mathbf{X}_1 \\
\mathbf{X}_2 \\
\vdots \\
\mathbf{X}_N
\end{bmatrix} \\
&=\begin{bmatrix}
\mathbf{X}_1 \\
\mathbf{X}_2 \\
\vdots \\
\mathbf{X}_N
\end{bmatrix}^{\top}
\begin{bmatrix}
\mathbf{\Omega}^{-1} & \mathbf{0} & \cdots & \mathbf{0} \\
\mathbf{0} & \mathbf{\Omega}^{-1} & \cdots & \mathbf{0} \\
\vdots & \vdots & \ddots & \vdots \\
\mathbf{0} & \mathbf{0} & \cdots & \mathbf{\Omega}^{-1}
\end{bmatrix}
\begin{bmatrix}
\mathbf{X}_1 \\
\mathbf{X}_2 \\
\vdots \\
\mathbf{X}_N
\end{bmatrix} \\
&=\mathbf{X}_\bullet^{\top}\left(\mathbf{I}_N \otimes \mathbf{\Omega}^{-1}\right)\mathbf{X}_\bullet
\end{align}
where "$\otimes$" denotes the Kronecker Product.

A: Put  $\mathbf{X}_i$'s next to each other to form a matrix. Oh, in fact you did. Yes, it is $X$.
Notice that
$$\mathbf{X}_i^{\top}\mathbf{\Omega}^{-1}\mathbf{X}_i$$
is the $i$'th element on the diagonal of
$$\mathbf{X}^{\top}\mathbf{\Omega}^{-1}\mathbf{X}$$
So, since you're summing these up,
$$\begin{equation}
\sum_{i=1}^N \mathbf{X}_i^{\top}\mathbf{\Omega}^{-1}\mathbf{X}_i
\end{equation} = trace(\mathbf{X}^{\top}\mathbf{\Omega}^{-1}\mathbf{X}).$$
Done!


text:
Q: how to write a function that calculates the age category I need to write a function that calculates the age category, so this is the function :
def age_category(dob_years):
    if dob_years < 0 or pd.isna(dob_years):
        return 'NA'
    elif dob_years < 20:
        return '10-19'
    elif dob_years < 30:
        return '20-29'
    elif dob_years < 40:
        return '30-39'
    elif dob_years < 50:
        return '40-49'
    elif dob_years < 60:
        return '50-59'
    elif dob_years < 70:
        return '60-69'
    else:
        return '70+'

I checked the function it works
but when I try to create a new column :
credit_scoring['age_group']= credit_scoring.apply(age_category, axis=1)

I have this error :
TypeError: '<' not supported between instances of 'str' and 'int'

actually, i am new in python i don't know what to do
pls help what is wrong with the code ?
thanks for your time :)

A: def age_category(dob_years):
    if not isinstance(dob_years, (float, int)):
        try:
            dob_years = int(dob_years)
        except ValueError:
            return 'NA'

    if dob_years < 0:
        return 'NA'

    return {
        0: '0-9',
        10: '10-19',
        20: '20-29',
        30: '30-39',
        40: '40-49',
        50: '50-59',
        60: '60-69',
        70: '70+',
    }[10 * int(dob_years // 10)]

A: You can achieve your goal more easily using pd.cut.
First of all, the sample data:
>>> df = pd.DataFrame([0, 18, -3, 73, 17, 88, 60,  1, 20, 14], columns=["age"])
>>> df
    age
0   0
1   18
2   -3
3   73
4   17
5   88
6   60
7   1
8   20
9   14

Then you need to prepare the bins and their labels:
>>> from math import inf
>>> bins = list(range(0, 80, 10))
>>> bins.append(inf)
>>> bins
[0, 10, 20, 30, 40, 50, 60, 70, inf]
>>> labels = [f"{i}-{i + 9}" for i in bins[:-2]]
>>> labels.append(f"{bins[-2]}+")
>>> labels
['0-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70+']

Once you have them, use pd.cut with right=True so it will assign labels according to your example.
>>> df["age group"] = pd.cut(df["age"], bins=bins, labels=labels, right=False)
>>> df
    age age group
0   0   0-9
1   18  10-19
2   -3  NaN
3   73  70+
4   17  10-19
5   88  70+
6   60  60-69
7   1   0-9
8   20  20-29
9   14  10-19


text:
Q: AWS Step Functions States.DataLimitExceeded Error I am currently creating a Step Functions workflow which contains some Lambdas and other services that share states between one task and other.
Mainly I am doing some external requests on my Lambda and sharing between tasks to process this data.
When I am trying to test my Step Functions workflow I am receiving the following error: States.DataLimitExceeded, but when I test on the Lambda console everything works properly.
Error:

Can anyone help me to understand what I am doing wrong in Step Functions workflow?

A: The Step Functions service has a limit for the inputs/payloads of 256KB (more necessarily 262,144 bytes) of data as a UTF-8 encoded string. This quota affects tasks (activity, Lambda function, or integrated service), state or execution output, and input data when scheduling a task, entering a state, or starting an execution.
In your case looks like you are sending more than this limit between states, this is not a problem for the Lambda functions because the Lambda limit is 6MB for events.
To work with this, you need will to share these huge payloads in another service like S3 and then send this reference between your functions/states.
For example, if you decide to use S3 for this case we can do something like this:
-> Lambda do the request
-> Save on S3 the data
-> Send the response with the S3 object ARN
-> Get this file on the Lambda function and process the data

This is preventing you to send the payload directly in your Step functions and you will not need to worry with this 256Kb input limit.
For understand more about the Step Functions quotas/limits take a look here:
Step Functions - Quotas


text:
Q: XML DOM Namespaces If I'm having an in-memory DOM of:
<root xmlns="NS1" xmlns:a="NSA">
    <outer>
        <a:inner>Text</a:inner>
    </outer>
</root>

and have a reference to the outer node.
After I call outer.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:a", "NSB") and traverse to inner it looks like the DOM specs say that inner.getNamespaceURI() still returns NSA.
Somebody knows how to get from inner to NSB?

A: Hmm, sometimes it hits you just after pressing the "Ask Question" button ...
inner.lookupNamespaceURI(inner.getPrefix()) looks to be the way to go.


text: Q: Proving positive definiteness of inner product If M is a real, invertible n x n matrix, how do I show that ${\langle a,b\rangle}=a^TM^TMb$ defines an inner product ($a$ and $b$ are column vectors in $\mathbb{R}^n$). I've proven that it satisfies the linearity and symmetry axioms, but I'm struggling to prove the positive definiteness axiom, where I need to prove that ${\langle a,a\rangle} > 0\ {\text{ if }}a\neq \mathbf {0}$.


text:
Q: System.NullReferenceException: Object reference not set to an instance of an object Estoy realizando una consulta simple a DB y me da el error del título.
Me indica que el error está en el if(reader.Read())
Tengo esto en el aspx:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" `
SelectCommand="SELECT [Articulos].[codigo], [Articulos].[descripcion], [Articulos].[precio], [Articulos].[codigoRubro], [Rubros].[descripcion]
FROM [Articulos] JOIN [Rubros] ON [Articulos].[codigoRubro] = [Rubros].[codigo] WHERE [Articulos].[descripcion]=@descripcion">
        <SelectParameters>
            <asp:Parameter Name="codigo" />
            <asp:Parameter Name="descripcion" />
            <asp:Parameter Name="precio" />
            <asp:Parameter Name="codigoRubro" />
            <asp:Parameter Name="descripcionRubro" />
        </SelectParameters>
    </asp:SqlDataSource>

y esto en el cs:
try
{
    SqlDataSource1.SelectParameters["descripcion"].DefaultValue = txbxArticleName.Text.ToUpper().Trim();
    SqlDataSource1.DataSourceMode = SqlDataSourceMode.DataReader;
    SqlDataReader reader = (SqlDataReader)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

    **if (!reader.Read())
    {**
        panelResult.Visible = true;

        txbxNameResult.Text = reader["descripcion"].ToString().Trim();
        txbxCodeResult.Text = reader["codigo"].ToString().Trim();
        txbxPriceResult.Text = reader["precio"].ToString().Trim();
        txbxProductCodeResult.Text = reader["codigoRubro"].ToString().Trim();
    }

Obviamente, esto se debe a que reader es null. Por eso, mi pregunta es: ¿por qué es null y cómo puedo solucionarlo?

A: Si revisas la documentacion
SqlDataSource.Select Method
podrias obtener un DataView, usando:
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

if (dv.Table.Rows.Count > 0){
   var row = dv.Table.Rows[0];

   txbxNameResult.Text = row["descripcion"].ToString().Trim();
   //resto
}

de esta forma validas si el command y los datos puedes recuperarse, o si el problema es algo mas general


text:
Q: Loopback getting only one Object from property Array of Object I'm use loopback and mongodb. Right now I have a Model and one of its property type is array of object. The document in mongo will look like this
{
    "_id" : "sgG6G9XTvvjj7uxwQ",
    "name" : "test",
    subscription: [
        {
             "id":3324,
             "state":"Currently",
             "type": "A",
             "startDate": "Date"

        },
        {
             "id":5465,
             "state":"Futuristic",
             "type": "A",
             "startDate": "Date"
        },
        {
             "id":6575,
             "state":"Futuristic",
             "type": "A",
             "startDate": "Date"
        }
    ]
}

I have already tried
 await this.clientsRepository.find({ where: { _id:'5d07ee4515741e0fbcfdbad1',
'subscription.state': 'Currently' },fields: { 'subscription.$': true } } })

I do expect only one object like this
{
   "id":3324,
    "state":"Currently",
    "type": "A",
    "startDate": "Date"
}


text:
Q: frame add doesn't work to another java file test.java
import javax.swing.JFrame;

public class test {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(600, 600);

    }

}

My Other java File test2.java
import javax.swing.JButton;

public class test2 {

    public static void main(String[] args) {
        JButton Button = new JButton();
        frame.add(Button);

    }

}

am trying to call frame to test2.java

A: The reason you are getting this problem:
When you run a java application, the application's main function will be called. Therefore you should really only have one main function per application.
In your scenario you had 2 main functions. Think of this as 2 different applications. The following scenarios were happening:

*

*When you run the Test class, your application was creating a new JFrame object. That's pretty much it, it ended there. It had no idea that the Test2 class existed.

*When you run the Test2 class, your application was creating a new JButton object. Although, your Test2 class had no reference to the frame variable (that is why you were getting an error). It didn't even know there was a Test class.

In order to fix this in your situation, try this:
Test.java
public class Test
{
     public static void main(String[] args)
     {
        JFrame frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(600, 600);

        // By passing the frame as a reference, the function
        // will be able to add the button to this frame.
        Test2.addButton(frame);
    }
}

Test2.java
public class Test2
{
    public static void addButton(JFrame frame)
    {
        JButton button = new JButton();
        frame.add(button);
    }
}

A more OOP approach:
Here, I made a Driver class that would connect the Test2 and MyFrame classes together.
Driver.java
public class Driver
{
    public static void main(String[] args)
    {
        MyFrame frame = new MyFrame();
        Test2.addButton(frame);
    }
}

MyFrame.java
public class MyFrame extends JFrame
{
    public MyFrame()
    {
        this.setSize(600, 600);
        this.setVisible(true);
    }
}

Test2.java
public class Test2
{
    public static void addButton(JFrame frame)
    {
        JButton button = new JButton();
        frame.add(button);
    }
}

A: I assume you're trying to add Button to the JFrame frame you created in test To do this, you'll need to make frame visible to what is essentially the global scope, as such:
import javax.swing.JFrame;
public class test {
    public static JFrame frame;
    public static void main(String[] args) {
        frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(600, 600);
        test2.main(args)
    }
}

and then, to add the button in test2, you need to access test by name
import javax.swing.JButton;
public class test2 {
    public static void main(String[] args) {
        JButton Button = new JButton();
        test.frame.add(Button);
    }
}


text:
Q: how to group jQuery plugins together? In css you can import a stylesheet in another stylesheet. How do you do this for javascript files? most specialy jquery plugins?
I searched first and found different similar questions but I'm not sure about the answer provided. (http://stackoverflow.com/questions/1618351/loading-js-files-dynamically-via-another-js-file)
I'm just looking for a way to limit http requests.

A: You can just append them one after another in a single file, or better, minify them alltogether, with either the YUI Compressor or Google Closure compiler....both will combine all files passed in and minify them as well.  Then, you just serve that one file to your users that contains all your file you want to combine.

A: You can look at google's javascript compiler, closure.
I've been using it in my Rails projects for some time now, through a tool called Jammit, and it does do wonders compressing JS to ridiculous sizes.


text:
Q: query confusion create query without create view Here is the question
we have 3 database variable(Person, event,invited)
Person(pid,passwd,fname,lname),
Event(eid, start_time,duration,description,pid)
Invited(pid,eid,response,visibility)

I want to make a query witch will do
show all people each event user X create.
For example Person David create the event  with eid=  1 and 3. (2events)
and if Jany and Will invited to the eid =1 , and Mike invited to event 3
it should show
EID PID
1   Jany
1   will
3   mike

The part I confused is  Person and Event 's PID is a creater of the event
and invited's PID is for person who invited. so its different PID value.
so i can not just natural join them
I can solve this problem with create view mysql command but I'm writing this code
on PHP form so I want to finish this command in one command.
what i tried is this
select *
from invited
where  eid
in (SELECT eid
from person natural join event
where pid = 'DD')

But it does not give what I expected.
How to write the code in One command without 'create view' command for this problem?

A: Are you looking for this?
SELECT e.eid, i.pid, p.fname
  FROM event e JOIN invited i
    ON e.eid = i.eid JOIN person p
    ON i.pid = p.pid
 WHERE e.pid = ?

Sample output:

| EID | PID | FNAME |
|-----|-----|-------|
|   1 |   2 |  Jany |
|   1 |   3 |  Will |
|   3 |   4 |  Mike |

Here is SQLFiddle demo
Recommended reading

*

*A Visual Explanation of SQL Joins


text:
Q: regular expression which does not match specific string in a line I have been trying for hours to get this working, can anyone assist me with a regex that will match the string "map" and "brand" in the text below. It should not match "reverse_map" line. So the first two lines are OK but not the third.
map             brand
map             brand
reverse_map     brand

A: If "map brand" is always the only string in the line, just use ^ and $ to tell where are, respectively, the beginning and the end of the line:
^map[[:space:]]+brand$

A: Use a word boundary to require the m in map not have a word character before it:
/\bmap brand/

https://regex101.com/r/wE9spT/1/
If you need something similar for brand to ensure, for example, map brandfoo doesn't get matched, add another word boundary at the end:
/\bmap brand\b/

A: Something like
(?:\bmap\b.*\bbrand\b|\bbrand\b.*\bmap\b)


text:
Q: JVM Out of Memory Causes Questions are based on Oracle Hotspot JDK8.
When applicaton come across java.lang.OutOfMemory: Java heap space exception, I suppose, where are two possible reasons.

*

*Allocated JVM heap size reaches -Xmx specified size and GC system cann't squeeze out enough space.

*Allocated JVM heap doesn't reach -Xmx, but there are not enough physical memory for JVM heap to grow. Suppose -Xms < -Xmx.

I know 1 is a reason for JVM to throw out java.lang.OutOfMemory: Java heap space exception. Is 2 a reasonable one cause?
I find some articles mentioned java.lang.OutOfMemoryError: native memory exhausted, but they are all limited to IBM website. Is this expetion limited to IBM implemented JVM or it is a standard expetion in JVM Specification?

I did some experiments with code supplied by @Eugene in answer. As @Holger noted the result varies in different environments. I tested in on both CentOS x64 and Win7 x64, with Hotspot JDK8 x64.
For simplicity swap and virtual memory are disabled.
I increase memory bound (-Xmx and -Xms) step by step.
I. -Xmx < available logic memory

*

*On both CentOS and Windows it shows OutOfMemoryError: Java heap space
II. available logic memory < -Xmx < max physical memory

*

*CentOS: The GC try to Full GC serveral times, with Allocation Failure, and process be killed by system, leaving a message Killed.

*Windows: The GC try to Full GC serveral times, with Allocation Failure, and throw out  OutOfMemoryError: Java heap space
III. -Xmx > max physical memory

*

*CentOS: same as in II

*Windows: same as in II

IV. -Xms > max physical memory

*

*CentOS: JVM seems fail to start. Error message is like:

Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00000000e62a0000, 349569024, 0) failed; error='Cannot allocate memory' (errno=12)

*

*Windows: JVM failed to start. Error message is like:

Error occurred during initialization of VM
Could not reserve enough space for object heap

So, the same JVM behave differently in different OS.

*

*On windows, the OS doesn't kill JVM.  And JVM always throw out OutOfMemoryError: Java heap space when memory usage grow exceeds.

*On Linux, the OS kill processes when there is not enough memory.

*On both OS JVM failed to start when available memory doesn't satisfy JVM minimal requirement.

A: First of all there are more reasons for a GC to fail with "out of memory" as the comment under your question explains.
Proving point number (2) is easy, just create some code that always allocates:
public static void main(String[] args) {
    test(1);
}

static void test(int x){
    List<byte[]> list = new ArrayList<>();
    while(x == 1){
        byte [] b =new byte[1 * 1024 * 1024];
        b[100] = 42;
        list.add(b);
    }

    System.out.println(list.hashCode());
}

And run this with -Xms1g -Xmx100g, on a system that has less then 100g of RAM. You can enable GC logs (I did with "-Xlog:heap*=debug" "-Xlog:gc*=debug" in java-9 flags for example) and see how hard GC is trying to cope with this constant allocation, ultimately failing.


text:
Q: Printing dictionary key-value pairs with placeholder string I am trying to write a program which will outputs as shown below:
father is repeated 2 times
where is repeated 1 time
art is repeated 1 time
are is repeated 1 time
thou is repeated 1 time

This is what I have for now:
x = input('Please enter a string: ').lower()
def counter():
    counts = dict()
    words = str.split(x)

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1
            print(counts)
    return counts

counter()

It prints out like this:
   Please enter a string:  father father where art are thou
   {'father': 2, 'where': 1, 'art': 1, 'are': 1, 'thou': 1}

How can I print out the data in the format as shown above?

A: Addressing your original question, use a placeholder string and insert values using str.format. The return value of counter() must be captured in a variable, say counts.
placeholder = '{} is repeated {} time{}'

counts = counter()
for k, v in counts.items():
    print(placeholder.format(k, v, 's' if v > 1 else ''))

father is repeated 2 times
where  is repeated 1 time
art    is repeated 1 time
are    is repeated 1 time
thou   is repeated 1 time

(The output isn't actually aligned like this, I just fixed it here so it preys less on my OCD.)
As an improvement, you can use the collections.Counter object to do this quite simply:
from collections import Counter
counts = Counter(x.lower().split())

Now, repeat the loop as above.

A: from collections import Counter
string = "Father father where art are thou"
new_list = string.lower().split()
get_value = Counter(new_list)
get_char_s = lambda x :'s' if x > 1 else ''
for k, v in get_value.items():
    print '%s is repeated %d time%s' % (k,v, get_char_s(v))
>>>thou is repeated 1 time
   where is repeated 1 time
   art is repeated 1 time
   father is repeated 2 times
   are is repeated 1 time

A: You could use OrderedDict in order to sort the dict object as per your requirement.
As this:
from collections import OrderedDict
from operator import itemgetter

x = raw_input('Please enter a string: ').lower()#raw input for string to improve parsing.
def counter():
    counts = dict()
    words = str.split(x)

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1
    print(counts)
    d = OrderedDict(sorted(counts.items(), key=itemgetter(1),reverse =True))#Ordered Dict for sorting in reverse of keys like you like.
    print d
    return d

counter()

Output:
OrderedDict([('father', 2), ('thou', 1), ('where', 1), ('art', 1), ('are', 1)])

A: i think give some modification on the code should also works using string format, ike this :
def counter():
    ...:     counts = dict()
    ...:     words = str.split(x)
    ...:     for word in words:
    ...:         if word in counts:
    ...:             counts[word] += 1
    ...:         else:
    ...:             counts[word] = 1
    ...:     print('father is repeated {counts[father]}\n \
    ...:             art is repeated {counts[art]}\n \
    ...:             are is repeated {counts[are]}\n \
    ...:             thou is repeated {counts[thou]}\n'.format(counts=counts))


text:
Q: Add percentage symbol to all list elements Hi I have a list like this: [1,2,3,4,5,6]
I want to add "%" to all these elements in the list for a result of [1%,2%,3%,4%,5%,6%].
I know that I can do it with +"%" but how can i do it with .format or another thing?

A: This PyFormat help
['{:d}%'.format(elm) for elm in l]

Output :
['1%', '2%', '3%', '4%', '5%', '6%']

A: Sure you can do it with format, your results of course need to be strings:
l = [1,2,3,4,5,6]
r = list(map("{}%".format, l))

now, r is:
['1%', '2%', '3%', '4%', '5%', '6%']

Alternatively you could do it with a list-comp as in the other answer or, in place, by looping:
for ind, i in enumerate(l):
    l[ind] = "{}%".format(i)

A: Since you've asked: or another thing? I'll give you another thing.
Sometimes, you'd desire something, which seems little bad, like this:
# add method to built-in int class to render ints as percents
as_percent = lambda x: str(x) + '%'
# and then monkey patch it
int.as_percent = as_percent

However you'd end up with this Exception:
TypeError: can't set attributes of built-in/extension type 'int'

But, there is a way..
Before you'd will try the following a little disclaimer:

I've never used this in any actual code, but I find this very fun, and generaly good to know it exists. Having code a little bit in Ruby, I like the idea of monkey patching built-ins. But it is not default behaviour in Python. So, be aware. But at least, try it!

First you need this module forbiddenfruit (see, the name is quite self-explanatory!). Simply pip it.
Then it is quite easy. We'll use the exact same lambda function as_percent as before.
>>> from forbiddenfruit import curse
>>> # again, do you see the name of the function?!
>>> curse(int, 'as_percent', as_percent)
>>> print((1).as_percent())
1%
>>> [x.as_percent() for x in range(10)]
>>> ['0%', '1%', '2%', '3%', '4%', '5%', '6%', '7%', '8%', '9%']

I've come across it here.


text:
Q: will + be + verb ing meaning I see one of my friends posted this status:
"Halloween celebration @ MBC - One of the last shots I'll be taking here"
Anyone could explain why she uses "I'll be taking" but not "I will take"? any difference between these two uses

A: "Will be [verb]-ing is future continuous tense.  It is used to describe a future, action that will occur over some period of time:

All day tomorrow I will be studying for the big exam.

As you know, it's often grammatical to substitute the simple future for the continuous, without changing the meaning:

All day tomorrow I will study for the big exam.

There is a slight difference in nuance, though.  Any continuous tense describes ongoing action, as if you are watching it happen.  For example:

Tomorrow the Packers will be facing the Patriots to determine who goes to the championship.

In the above sentence there is little difference between "will be facing" and "will face", but if a sports announcer were to say this sentence, the feeling is that we could be watching the game as it happens.  There's a kind of dramatic immediacy when we use the future continuous.
(BTW the verb "to face" or "to face off", in sports, means "to compete against, face-to-face".  See verb definition 3)
In the same way, your friend says "I'll be taking shots" because she expects you to be there, and possibly join her in taking the shots.  She could have said "I will take" but that is more matter-of-fact, and doesn't include the suggestion of personal invitation.


text:
Q: Creating a "DWH like" Star Schema in MySQL I am pretty new to databases and SQL in general and have a pretty important task that I do not know how to solve.
Given that I have a Company (Company A) with three different subsidiaries (Sub A, Sub B, Sub C). All three subsidiaries produce the same products which can be divided into three product categories:

*

*Product Category A

*Product Category B

*Product Category C

My task is to create a star scheme that allows me to get the following information: Total Revenues of Sub A and Sub B for every Product from Product Category B.
The needed format of the result is a table containing three columns "Subsidiary Name", "Product Name" and "Revenue".
What I have been trying to do so far, is to create the following Fact Table, Dimension and Keys.
The Primary Keys of the Dimensions are connected to the Foreign Keys of my Fact Table.

So my questions are:

*

*Am I even on the right track or is this approach completely wrong?

*How would I actually "fill" my tables with example data to be able to write a query that answers the given question above?

*How would such a query look like?
For now, I am using a local MySQL server created with XAMPP and am connecting to this using IntelliJ IDEA Ultimate 2016. The diagramm above has also bee created using this software.
I hope that someone is able and willing to help me.
Also, please forgive any mistakes (or please tell me what I did wrong) as I am both new to SQL and especially new to Stackoverflow.
Kind regards
Edit:
I have used a different tool to create and visualize my tables. Also, as fenix mentioned, I have added several different Dimensions such as a Time/Date Table. However, in order to solve my task, I suppose I only need the two Dimensions dimCompany (Which represents the different subsidiaries) and dimProduct.

A: *

*You are on the track to it proper. School example of how data mart should be structured. Real-life example will possibly contain native keys of companyID, productID and salesID. Please add PK_sales or PK_fact (whatever you prefer). Event (one sale) without date or time-stamp is rarely to happen but if this is just some proof of concept, maybe you can go without it.

*Do you have some data or you want to made up some data?

*

*You can create some example data inside excel using RANDBETWEENfunction.

*Many MySQL client tools have option to import data from excel, csv or txt files.

*Or you can use some of free data integration tools like Pentaho Kettle and Talend Open Studio. If it is too much at this moment avoid this step. However, it will give you good insight what DI tools are and how DWH could be populated (in real-life example).

*It would be something like this:

SELECT dp.ProductName,sum(fs.revenue) as total_revenue
FROM fact_sales fs
JOIN dim_product dp ON fs.FK_Product = dp.PK_Product
JOIN dim_company dc ON fs.FK_Company = dc.PK_Company
WHERE dp.Product_Type = 'Product Category B'
AND dc.CompanyName IN ('Sub A','Sub B')
GROUP BY dp.PK_Product;
Unfortunately, some of Data Marts are not well structured so it doesn't contain referential integrity (anti-pattern), so you would have to go with LEFT JOIN instead of INNER JOIN. Note that INNER JOIN is same as JOIN. A bit about JOIN you can visualise here.
Edit:
Regarding your comment, it's hard to make good balance not to make this answer too broad because this QA site should serve for specific questions and answers.
Since DWH is still a databases, it inherited most of databases principles. One of those are table keys. Primary Key is unique row identifier, and when database design allows (in DWH world it always should be) keys are integers (big integers exactly). See this for more info.
Purpose? You can have two companies with same names but different states, so you need some key to distinct them.
Why it should be integer? It's more technical question, and one of the answers is of query optimisation. CPU will match two integers (4 or 8 bytes) much faster rather than strings (VARCHARin database world) with 100+ bytes (or however you specify).
Why someone uses VARCHAR as primary key? Well, sometimes, being as native as possible is good approach. So, VARCHAR primary key for product could be combination of product brand and counter (from supplier), and if you are re-seller, ERP could give Microsoft Office 2016 key like MCR-OFF-123. In DWH it is recommended to store native key (whatever it is, int or varchar) and to assign surrogate primary key.

Sub A has the key '1', Sub B has the key '2

quote from your comment.
Yes, you're right.


text:
Q: XSLT how to sort inside a  Hello im studying XML from w3schools and now im studying this example above.
I learned that we can use  inside a for-each and understood this.
But now im trying to use  inside  but its not working.
I already tested in many ways but nothing works, can anyone give a little help?
 <?xml version="1.0" encoding="ISO-8859-1"?>

    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">

My CD Collection

      <xsl:apply-templates/>

    </xsl:template>

    <xsl:template match="cd">

        <xsl:apply-templates select="title">
          <xsl:sort select="title" order="descending" />
        </xsl:apply-templates>
        <xsl:apply-templates select="artist"/>

    </xsl:template>

    <xsl:template match="title">
      Title:
      <xsl:value-of select="."/>

    </xsl:template>

    <xsl:template match="artist">
      Artist:
      <xsl:value-of select="."/>

    </xsl:template>

    </xsl:stylesheet>

XML
 <?xml version="1.0" encoding="UTF-8"?>

    <catalog>
        <cd>
            <title>Empire Burlesque</title>
            <artist>Bob Dylan</artist>
            <country>USA</country>
            <company>Columbia</company>
            <price>10.90</price>
            <year>1985</year>
        </cd>
        <cd>
            <title>Hide your heart</title>
            <artist>Bonnie Tyler</artist>
            <country>UK</country>
            <company>CBS Records</company>
            <price>9.90</price>
            <year>1988</year>
        </cd>
        <cd>
            <title>Greatest Hits</title>
            <artist>Dolly Parton</artist>
            <country>USA</country>
            <company>RCA</company>
            <price>9.90</price>
            <year>1982</year>
        </cd>

    </catalog>

A: It looks like you want to sort cds by artist - not titles by artist. You cannot sort titles (directly) by artist anyway, because artist is not a child of title. And it wouldn't matter anyway, unless you had more than one title in a cd.

A: you've got to sort "cd"s based on "title", and this is the way I think you were looking for:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

My CD Collection

          <xsl:apply-templates select="catalog/cd">
                <xsl:sort select="title" order="descending"/>
          </xsl:apply-templates>

</xsl:template>

<xsl:template match="cd">

    <xsl:apply-templates select="title" />
    <xsl:apply-templates select="artist"/>

</xsl:template>

<xsl:template match="title">
  Title:
  <xsl:value-of select="."/>

</xsl:template>

<xsl:template match="artist">
  Artist:
  <xsl:value-of select="."/>

</xsl:template>
</xsl:stylesheet>


text: Q: Session not timing out on Asp .Net MVC I am working on a web application integrated with web API. I need to add session timeout, I am using <sessionState timeout="60"></sessionState> in web.config But it is only working when the user is idle, and not working while he is working and switching pages within application.


text:
Q: Write string variable to the clipboard I'm going to admit, right off the bat, that I'm Pascal-inexperienced, to say the least. So, any help I can get will be greatly appreciated. :)
As part of a larger program, I need to write a string variable to the clipboard. I've created a new project in Lazarus (version 1.0.12) so I can try to figure out how to do so without the complications caused by extra, unnecessary code, which I have included below:
program varToClipboard;

uses Clipbrd;

var
    textToCopy:string;

begin
    textToCopy := 'Test text from Pascal';

    Clipboard.AsText := textToCopy;
end.

Using the above code, along with a required LCLBase dependency, I'm getting the following error in CMD when running the compiled EXE:
An unhandled exception occurred at $000000000043D45E :
EAccessViolation : Access violation
  $000000000043D45E  CLIPBOARDREGISTERFORMAT,  line 98 of ./include/lclintf.inc
  $000000000043C35B  PREDEFINEDCLIPBOARDFORMAT,  line 185 of lclintf.pas
  $0000000000415B0C  TCLIPBOARD__SETASTEXT,  line 452 of ./include/clipbrd.inc
  $0000000000401802  main,  line 12 of varToClipboard.lpr

According to the documentation, I seem to be doing everything right. Although, I have found the documentation to be... lacking on more than on occasion.

Also, what do I have to do so that I can run the compiled EXE (which will just generate and write a string to the clipboard) without the console window popping up?

A: You were doing it right. The problem here is that clipboard class doesn't somehow encount to be used in console applications. Your application failed on the following line from the lclintf.inc file, where the WidgetSet object is going to be accessed. That fails because the WidgetSet variable is nil while you're in console application just because console application doesn't need any widgets:
function ClipboardRegisterFormat(const AMimeType: string): TClipboardFormat;
begin
  Result := WidgetSet.ClipboardRegisterFormat(AMimeType);
end;

To workaround this you may add the Interfaces unit to your uses clause and add the LCL package dependency to your project:
program Project1;

uses
  Clipbrd,
  Interfaces;

begin
  Clipboard.AsText := 'Hello, I''m a text from clipboard!';
end.

But according to your additional question it seems that you want to make the application, which will just copy certain text to the clipboard and terminates. That's what the console application type is not a right choice because of that console window shown for a short time. For that sort of application I would make the formless window application (please note that I know this trick only from Windows platform):

*

*Create a new application through menu File / New..., select Project / Application in the dialog's tree view and create a new project by clicking OK

*Now let's remove the only unit (with a form) from your project; go to the menu Project / Remove from Project and in the newly opened dialog select unit1.pas and click OK

*Now you have a unitless (and formless) application, so what remains is to write a code to copy the text to the clipboard; so now let's open the project source from menu Project / View Project Source and as the project source paste a code like this (this is the shortest possible form):

program Project1;

uses
  Interfaces, Forms, Clipbrd;

begin
  Application.Initialize;
  Clipboard.AsText := 'Hello, I''m a text from clipboard!';
end.


text:
Q: Creating a Pivot table in C# In my c# program I have someone input production for the whole day and I calculate machine usage (MU) like so:
Date      | Part Number | Mold Num | Machine Num |  MU
2/12/2016 | 1185-5B8    |  6580    | 12          |  .428
2/12/2016 | 2249300     |  7797    | 36          |  .271
2/12/2016 | 146865      |  5096789 | 12          |  .260
2/16/2016 | 123456      |  7787    | 56          |  .354
2/16/2016 | 123456      |  787     | 54          |  .45
2/16/2016 | 123456      |  777     | 56          |  .799
2/16/2016 | 123456      |  87      | 54          |  .611

All of this data is in my SQL server and what I want to do is to make something like a pivot table and it takes all similar dates/Mold Numbers/Machine Numbers and makes an average the MU and display it in any way that the user wants. Example:
Date      |  MU
2/12/2016 |  32.0%
2/16/2016 |  55.4%

or
Machine Num. | MU
12       | 34.4%
36       | 27.1%
54       | 53.0%
56       | 57.6%

etc. Basically I want it to be variable and to show whatever the person that is looking at it needs. I want to keep it in my c# program but I can use LINQ to SQL. Please keep in mind that I am very new to c# and LINQ to SQL.
I did try to do this but it was not exactly what I wanted to do. I also could not figure out how I was going to display it on the windows form nor how to change what was in each column.

A: It seems you need to build pivot table with row dimension (Date, Machine Num), without column dimension and with average by MU.
You can easily do that with help of NReco PivotData library:
var pivotData = new PivotData(
    new string[] {"Date","Machine Num"},
    new AverageAggregatorFactory("MU"),
    new DataTableReader(t) );  // just a sample - you can use DB data reader
var pivotTable = new PivotTable(
    new []{"Date"}, // row dimension(s)
    new [0], // column dimension(s)
    pivotData );
// use pivotTable.RowKeys and indexer for accessing pivot table values

PivotData library can be used for free (I'm an author), and you can download examples package on the component's page. Also you may check advanced PivotData Toolkit components (for rendering pivot table to HTML/CSV/Excel/PDF, aggregating data on DB level with GROUP BY and many others), but they are not free.

A: According to your description, what you want isn't a pivot table, as already mentioned by @juharr.
For sqlite, this sould be accomplished with the following statement. (I assume the table name is tmp, and what you want is the sum of MU with each MachineNUm, naming it with SMU).
SELECT MachineNum,SUM(MU) AS SMU From tmp GROUP BY MachineNum ORDER BY MachineNum;

Hope it helps.


text:
Q: Laravel app using Symfony to execute a Python script on LEMP stack - Permission denied I have just uploaded my laravel app to the web using Digital Ocean (LEMP stack), however when I try to run a python process I am getting permission denied. This worked on local with no permission issues.
I have tried giving access to the Find/process.py file and folder with the following but no progress:

sudo find /var/www/sync/Find/*.py -type d -exec chmod 755 {} \;
sudo find /var/www/sync/Find/*.py -exec chmod 644 {} \;
sudo find /var/www/sync/Find/*.py -type d -exec chmod u+x {} \;

Error Output:
================
sh: 1: /usr/lib/python3.5: Permission denied
 {"userId":1,"email":"admin@admin.com","exception":"[object] (Symfony\\Component\\Process\\Exception\\ProcessFailedException(code: 0): The command \"/usr/lib/python3.5 Find/process.py\" failed.

Exit Code: 126(Invoked command cannot execute)

Working directory: /var/www/sync

Output:
================

Error Output:
================
sh: 1: /usr/lib/python3.5: Permission denied
 at /var/www/sync/App/Find/process.php:51)

I do not believe it to be the php file as it works local and the error clearly says permission denied however I am not sure how else to troubleshoot this and any help is useful. Thanks

A: I changed the python bin path from "/usr/lib/python3.5" to just "python3.5" and its now working.


text:
Q: jquery: using uploadify invisibly i am using the uploadify plugin and was wondering, can it be used as invisible object?
which means keeping it invisible and controlling it by jquery code only, like opening the file dialog, starting the upload - or does it need to be visible for clicking on it?

A: If you want it hidden then is uploadify necessary? You can take a look at this "ajax" like file upload with iframes which can be easily hidden
http://www.openjs.com/articles/ajax/ajax_file_upload/

A: No – the File Dialog can only be opened as a result of a user event (in this case click) inside the Flash document. You cannot trigger this from JavaScript. – This is due to the Flash security model surrounding the File System.


text:
Q: Getting the following error org.hibernate.MappingException: No Dialect mapping for JDBC type: -1 I am getting following exception at query.can you please tell mw whats wrong is in my code?
org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:79)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:104)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
at org.hibernate.loader.custom.CustomLoader$Metadata.getHibernateType(CustomLoader.java:582
    at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.performDiscovery(Custom Loader.java:508)
    at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:524)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1821)
    at org.hibernate.loader.Loader.doQuery(Loader.java:697)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2232)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
    at org.hibernate.loader.Loader.list(Loader.java:2124)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
    at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
    at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
    at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)
    at com.bdisys.promorphics.dao.impl.BlogDaoImpl.getTopBlogsQuesByDate(BlogDaoImpl.java:126)
    at org.apache.jsp.Mydetails_jsp._jspService(Mydetails_jsp.java:935)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
    at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
    at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
    at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at        org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    at java.lang.Thread.run(Unknown Source)

Blog.java :
@SuppressWarnings("serial")
    @Entity
    @Table(name="blog")
    public class Blog extends BaseDomain {

    @Column(name="blog_title")
    private String blogTitle;

    @Column(name="blog_text",columnDefinition="TEXT")
    private String blogText;

    @Enumerated(EnumType.STRING)
    @Column(name="blog_status")
    private Status blogStatus;

    @OneToOne
    @JoinColumn(name="created_by", nullable=false)
    private User createdBy;

    @OneToOne
    @JoinColumn(name="blog_category", nullable=false)
    private BlogCategory blogCategory;

    @Temporal(TemporalType.DATE)
    @Column(name="created_date")
    private Date createdDate;

    @Column(name="likes")
    private Long likes;

    @Column(name="uploads")
    private String uploads;

    @Column(name="youtube_link")
    private String youTubeLik;

    @Column(name="moderator_comment")
    private String moderatorComment;

    @Lob
    @Column(name="blog_description")
    private String blog_desc;

    @ManyToOne
    @JoinColumn(name="users")
    private User users;

    public User getUsers() {
    return users;
    }

    public void setUsers(User users) {
     this.users = users;
    }

    public String getBlog_desc() {
    return blog_desc;
    }

    public void setBlog_desc(String blog_desc) {
    this.blog_desc = blog_desc;
    }

    public String getBlogTitle() {
    return blogTitle;
    }

    public void setBlogTitle(String blogTitle) {
    this.blogTitle = blogTitle;
    }

    public String getBlogText() {
    return blogText;
    }

    public void setBlogText(String blogText) {
    this.blogText = blogText;
    }

    public Status getBlogStatus() {
    return blogStatus;
    }

    public void setBlogStatus(Status blogStatus) {
    this.blogStatus = blogStatus;
    }

    public User getCreatedBy() {
    return createdBy;
    }

    public void setCreatedBy(User createdBy) {
    this.createdBy = createdBy;
    }

    public BlogCategory getBlogCategory() {
    return blogCategory;
    }

    public void setBlogCategory(BlogCategory blogCategory) {
    this.blogCategory = blogCategory;
    }

    public Date getCreatedDate() {
    return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
    this.createdDate = createdDate;
    }

    public Long getLikes() {
    return likes;
    }

    public void setLikes(Long likes) {
    this.likes = likes;
    }

    public String getUploads() {
    return uploads;
    }

    public void setUploads(String uploads) {
    this.uploads = uploads;
    }

    public String getYouTubeLik() {
    return youTubeLik;
    }

    public void setYouTubeLik(String youTubeLik) {
    this.youTubeLik = youTubeLik;
    }

    public String getModeratorComment() {
    return moderatorComment;
    }

    public void setModeratorComment(String moderatorComment) {
    this.moderatorComment = moderatorComment;
    }

    }

Askquestions.java :
 @SuppressWarnings("serial")
    @Entity
     @Table(name="askquestions")
    public class Askquestions extends BaseDomain {

@Column(length = 100, name = "id_subscribers")
private String idSubscribers;

@Column(length = 100, name = "is_anonymous")
private String isAnonymous;

@Column(length = 100, name = "display_name")
private String displayName;

@Temporal(TemporalType.DATE)
    @Column(length = 100, name = "created_on")
private Date createdQuesOn;

@Lob
@Column(name = "ask_question")
private String askQuestion;

@Column(length = 100, name = "ask_to_whom")
private String askToWhom;

@Lob
@Column(name="question_of_day")
private String questionOfDay;

@ManyToOne
 @JoinColumn(name="ask_category")
 private Askcategory askcategory;

 @ManyToOne
    @JoinColumn(name="users")
    private User users;

public User getUsers() {
    return users;
}

public void setUsers(User users) {
    this.users = users;
}

public Askcategory getAskcategory() {
    return askcategory;
}

public void setAskcategory(Askcategory askcategory) {
    this.askcategory = askcategory;
}

public String getQuestionOfDay() {
        return questionOfDay;
    }

    public void setQuestionOfDay(String questionOfDay) {
        this.questionOfDay = questionOfDay;
    }

public String getIdSubscribers() {
    return idSubscribers;
}

public void setIdSubscribers(String idSubscribers) {
    this.idSubscribers = idSubscribers;
}

public String getIsAnonymous() {
    return isAnonymous;
}

public void setIsAnonymous(String isAnonymous) {
    this.isAnonymous = isAnonymous;
}

public String getDisplayName() {
    return displayName;
}

public void setDisplayName(String displayName) {
    this.displayName = displayName;
}

public String getAskQuestion() {
    return askQuestion;
}

public void setAskQuestion(String askQuestion) {
    this.askQuestion = askQuestion;
}

public String getAskToWhom() {
    return askToWhom;
}

public void setAskToWhom(String askToWhom) {
    this.askToWhom = askToWhom;
}

public Date getCreatedQuesOn() {
    return createdQuesOn;
}

public void setCreatedQuesOn(Date createdQuesOn) {
    this.createdQuesOn = createdQuesOn;
}

    }

BlogDaoimpl Method:this query is not getting executed while other small queries are getting executed.why is it    happening????
     String sql = "  select title , date from (select blog_title as title ,created_date          as date from  blog  union select ask_question as title , created_on as date from askquestions ) as aa order by date desc";

   SQLQuery query = getSession().createSQLQuery(sql);

    return query.list();

hibrnate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     <hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
  <!-- <property name="hibernate.connection.password">websitebdi</property>
    <property    name="hibernate.connection.url">jdbc:mysql://184.172.182.251:3306/bdiwebsite</property>
    <property name="hibernate.connection.username">bdiwebsite</property>  -->

    <property name="hibernate.connection.password">MAYbdiSYS2008</property>
    <property name="hibernate.connection.url">jdbc:mysql://115.119.114.10:3306/bdisystems</property>
    <property name="hibernate.connection.username">admin</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="current_session_context_class">thread</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.show_sql">false</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">true</property>

    <property name="hibernate.connection.provider_class">
        org.hibernate.connection.C3P0ConnectionProvider
    </property>
    <!--  The maximum number of connections  -->
    <property name="hibernate.c3p0.max_size">20</property>
    <!--  The minimum number of connections  -->
    <property name="hibernate.c3p0.min_size">5</property>
    <!--  Get a connection timeout  , If you exceed this time  , Throws an exception, in milliseconds  -->
    <property name="hibernate.c3p0.timeout">120</property>
    <!--  The maximum number of PreparedStatement  -->
    <property name="hibernate.c3p0.max_statements">100</property>
    <!--  Every 120 seconds checking connection idle connection in the pool, the unit is in seconds  -->
    <property name="hibernate.c3p0.idle_test_period">120</property>
    <!--  When connection pooling connections inside out, look at the new C3P0     get the number of connections  -->
    <property name="hibernate.c3p0.acquire_increment">2</property>
    <!--  Always verify the connection  -->
    <property name="hibernate.c3p0.validate">true</property>
    <!--
        <property name="hibernate.c3p0.max_size">100</property>
        <property name="hibernate.c3p0.min_size">0</property>
        <property name="hibernate.c3p0.acquire_increment">1</property>
        <property name="hibernate.c3p0.idle_test_period">300</property>
        <property name="hibernate.c3p0.max_statements">0</property>
        <property name="hibernate.c3p0.timeout">100</property>
    -->

    <!-- Mapping Classes -->

    <mapping class="com.bdisys.promorphics.domain.BlogCategory"/>
    <mapping class="com.bdisys.promorphics.domain.Blog"/>

    <mapping class="com.bdisys.promorphics.domain.Career"/>
    <mapping class="com.bdisys.promorphics.domain.Partners"/>
    <mapping class="com.bdisys.promorphics.domain.Askcategory"/>
    <mapping class="com.bdisys.promorphics.domain.Askquestions"/>
    <mapping class="com.bdisys.promorphics.domain.Askanswers"/>

</session-factory>
    </hibernate-configuration>

A: Create a custom Dialect (extending MySQLDialect) and in your constructor add
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());

public class MySQLDialect extends MySQLDialect {
  public AGOSQLServerDialect() {
    super();
    registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
  }
}

Remember to change dialect class into Hibernate config file
<property name="hibernate.dialect">path.to.YourDialect</property>


text:
Q: android getActionBar() returns null Hello I am working on an android App. I am trying to create activity with tabs that swap. I am working with following tutorial http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
The problem is that in Main Activity it shows Null pointer exception at
 actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);

Does anyone knows why happens this?
My code:
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initilization
        actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowCustomEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.pager);

        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

A: Instead of
actionBar = getActionBar();

Use
actionBar = getSupportActionBar();


text:
Q: Multiset without Compare? I want to use multiset to count some custom defined keys. The keys are not comparable numerically, comparing two keys does not mean anything, but their equality can be checked.
I see that multiset template wants a Compare to order the multiset. The order is not important to me, only the counts are important. If I omit Compare completely what happens? Does multiset work without any problems for my custom keys? If I cannot use std::multiset what are my alternatives?

A: If you can only compare keys for equality then you cannot use std::multiset. For associative containers your key type must have a strict weak ordering imposed by a comparison operation.
The strict weak ordering doesn't necessarily have to be numerical.
[For use in an associative container, you don't actually need an equality comparison. Key equivalence is determined by !compare(a, b) && !compare(b, a).]
If you really can't define an ordering for your keys then your only option is to use an sequence container of key-value pairs and use an linear search for lookup. Needless to say this will be less efficient for set like operations than a multiset so you should probably try hard to create an ordering if at all possible.

A: If you omit the Compare completely, it will get the default value, which is less (which gives the result of the < operator applied to your key) - which may or may not even compile for your key.
The reason for having an ordering is that it allows the implementation to look up elements more quickly by their key (when inserting, deleting etc), To understand why, imagine looking words up in a dictionary. Traditional dictionaries use alphabetical order, which makes words easy to look up. If you were preparing a dictionary for a language that isn't easily ordered  - say a pictographic language - then either it would be very hard to find words in it at all (you'd have to search the whole dictionary), or you'd try to find a logical way to order them (e.g. by putting all the pictures that can be drawn with one pen stroke first, then two lines, etc...) - because even if this order was completely arbitrary, it would make finding entries in the dictionary far more efficient.
Similarly, even if your keys don't need to be ordered for your own purposes, and don't have any natural order, you can usually define an ordering that is good enough to address these concerns. The ordering must be transitive (if a<b and b<c then a<c), and strict (never return true for a<a), asymmetric (a<b and b>a never both true). Ideally it should order all elements (if a & b are different then either a<b or b<a), though you can get away with that not being true (ie a strict weak ordering) - though that's rather technical.
Indeed, perhaps the most obvious use for it is the rare case where it is completely impossible to order the items - in which case you can supply a comparison operator which always returns false. This will very likely result in poor performance, but will at least function correctly.

A: You cannot use std::multiset if you don't have a strict weak ordering. Your options are:

*

*Impose a strict-weak ordering on your data. If your key is a "linear" data structure, it is usually a good idea to compare it lexicographically.

*Use an unordered container equivalent, e.g., boost::unordered_multiset. For that, you will need to make your custom data-type hash-able, which is often-times easier than imposing some kind of order.

A: So you have two important criteria which you listed.

*

*You don't care about order

*comparison of keys do not mean anything

and one assumed,

*

*the fact that you are using multiset implies that there are many instances

So, why not use std::vector or std::deque or std::list? then you can take advantage of the various algorithms that can use the equality check (such as count_if etc.)


text:
Q: How do I get the caller SID in kernel mode hook? (windows) I'm developing a driver that hooks some functions in windows (hardening driver that will block some actions). The problem is, that I want to log which was the user who attempted to run those actions.
For example, I've put an hook on ZwSetValueKey in order to filter registry writing.
The hook works perfectly, But I don't know how to get the caller SID. I've found out that I can determine whether the mode of the caller(i.e. user mode or kernel mode) using ExGetPreviousMode. But I'm not really sure how to determine the SID if the caller was in user mode.
Thanks.

A: If this were user mode, you'd start with GetCurrentProcess or GetCurrentThread, and then call GetProcessToken or GetThreadToken. This would get you an access token, from which the SID can be extracted directly. In kernel model, there's PsGetCurrentProcess and ZwOpenProcessTokenEx, and the like for threads.
Here's the equivalent question for user space: How to get Calling-Process Windows User Access Token.
I haven't tested this, but I hope it gets you started.

A: VOID SeCaptureSubjectContext(Out PSECURITY_SUBJECT_CONTEXT) is probably the kernel-mode API you're looking for, at least if you have ntifs.h available.


text:
Q: Connecting to Remote Advantage Database server from Java We are migrating a project from Dotnet to Java. The connection string in dot net is as follows
Data Source=\\ip:port\timesoft$\TP8\COMPANY\KCLMAIN\KCLMAIN.add;ServerType=REMOTE;User ID=ITUSER;SecurityMode=IGNORERIGHTS;Password=123456;

In Java we have written a test program to check the connectivity, which is a follows
I have added the adsjdbc.jar (v8.1)
Class.forName("com.extendedsystems.jdbc.advantage.ADSDriver");
    connection = DriverManager.getConnection("jdbc:extendedsystems:" +
    advantage://ip:port/timesoft$/TP8/COMPANY/
    KCLMAIN/KCLMAIN.add;user=ITUSER;password=123456");

or with catalog
Class.forName("com.extendedsystems.jdbc.advantage.ADSDriver");
connection = DriverManager.getConnection("jdbc:extendedsystems:" +
advantage://ip:port;catalog=//ip:port/timesoft$/TP8/COMPANY/
KCLMAIN/KCLMAIN.add;user=ITUSER;password=123456");

But it throws connection reset error, please suggest what is wrong.
Also, I'm not able to set the SecurityMode=IGNORERIGHTS; and ServerType=REMOTE; in drivermanager.getconnection. if we pass these it says unknown parameter.


text:
Q: js Split array add space between words (not first) I have a string Topic: Computer Science
And want to strip out topic: (but in fact I want this to work with any header on the string line) and return Computer Science.
I thought about splitting the components and then adding the spaces back in:
var subjectLine = thisLine.split(" ");

var subjectString = "";

for (i = 1; i < subjectLine.length; i++) {
    subjectString += subjectLine[i] + " ";
  }

But then I need to remove the last space from the string.
For each doesn't work as I need to NOT have the first element appended.
I'm not sure how to do this in js so it is reusable for many different lines and topic names that can come from the subjectLine

A: After splitting the line, remove the first element from the array, then join the rest back together.

var thisLine = "Topic: Computer Science";
var subjectLine = thisLine.split(" ");
subjectLine.splice(0, 1);
var subjectString = subjectLine.join(" ");
console.log(subjectString);

A: You might consider using a regular expression, it'll probably be a lot easier than working with arrays: match the non-space characters at the beginning of the string, followed by at least one space, and .replace with the empty string:
const subjectString = thisLine.replace(/^\S+\s+/, '');

const transform = line => line.replace(/^\S+\s+/, '');

console.log(transform('Topic: Computer Science'));

A: You need to know where the heading stops and the real data starts. Then delete all characters up to that point.
So, for instance, if you know that the heading ends with a colon, then do:

var line = "this is the topic: Computer Science";

var topic = line.replace(/^.*:\s*/, "");
console.log(topic);