Programs & Examples On #Apache flex

Apache Flex [NOT CSS FLEXBOX] is a framework for developing Rich Internet Applications that run in Flash Player or Adobe Air. Originally designed by Adobe, Flex was donated to the Apache Software Foundation in 2011 and became a top level Apache project in December 2012.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

Tomcat in Eclipse does not use catalina.sh or bat. To setup memory for managed Tomcat use VM settings in server run configuration

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Tracking it down

At first I thought this was a coercion bug where null was getting coerced to "null" and a test of "null" == null was passing. It's not. I was close, but so very, very wrong. Sorry about that!

I've since done lots of fiddling on wonderfl.net and tracing through the code in mx.rpc.xml.*. At line 1795 of XMLEncoder (in the 3.5 source), in setValue, all of the XMLEncoding boils down to

currentChild.appendChild(xmlSpecialCharsFilter(Object(value)));

which is essentially the same as:

currentChild.appendChild("null");

This code, according to my original fiddle, returns an empty XML element. But why?

Cause

According to commenter Justin Mclean on bug report FLEX-33664, the following is the culprit (see last two tests in my fiddle which verify this):

var thisIsNotNull:XML = <root>null</root>;
if(thisIsNotNull == null){
    // always branches here, as (thisIsNotNull == null) strangely returns true
    // despite the fact that thisIsNotNull is a valid instance of type XML
}

When currentChild.appendChild is passed the string "null", it first converts it to a root XML element with text null, and then tests that element against the null literal. This is a weak equality test, so either the XML containing null is coerced to the null type, or the null type is coerced to a root xml element containing the string "null", and the test passes where it arguably should fail. One fix might be to always use strict equality tests when checking XML (or anything, really) for "nullness."

Solution

The only reasonable workaround I can think of, short of fixing this bug in every damn version of ActionScript, is to test fields for "null" and escape them as CDATA values.

CDATA values are the most appropriate way to mutate an entire text value that would otherwise cause encoding/decoding problems. Hex encoding, for instance, is meant for individual characters. CDATA values are preferred when you're escaping the entire text of an element. The biggest reason for this is that it maintains human readability.

What is the best way to get the minimum or maximum value from an Array of numbers?

If you want to find both the min and max at the same time, the loop can be modified as follows:

int min = int.maxValue;
int max = int.minValue;

foreach num in someArray {
  if(num < min)
    min = num;
  if(num > max)
    max = num;
}

This should get achieve O(n) timing.

How do I get a HttpServletRequest in my spring beans?

@eeezyy's answer didn't work for me, although I'm using Spring Boot (2.0.4) and it may differ, but a variation here in 2018 works thus:

@Autowired
private HttpServletRequest request;

Failed to load JavaHL Library

Check out this blog. It has a ton of information. Also if installing through brew don´t miss this note:

You may need to link the Java bindings into the Java Extensions folder:

 $ sudo mkdir -p /Library/Java/Extensions
 $ sudo ln -s /usr/local/lib/libsvnjavahl-1.dylib /Library/Java/Extensions/libsvnjavahl-1.dylib

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

var formatedDate = DateTime.Now.ToString("yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture);

To ensure the user's local settings don't affect it

Call an overridden method from super class in typescript

The key is calling the parent's method using super.methodName();

class A {
    // A protected method
    protected doStuff()
    {
        alert("Called from A");
    }

    // Expose the protected method as a public function
    public callDoStuff()
    {
        this.doStuff();
    }
}

class B extends A {

    // Override the protected method
    protected doStuff()
    {
        // If we want we can still explicitly call the initial method
        super.doStuff();
        alert("Called from B");
    }
}

var a = new A();
a.callDoStuff(); // Will only alert "Called from A"

var b = new B()
b.callDoStuff(); // Will alert "Called from A" then "Called from B"

Try it here

Heap vs Binary Search Tree (BST)

As mentioned by others, Heap can do findMin or findMax in O(1) but not both in the same data structure. However I disagree that Heap is better in findMin/findMax. In fact, with a slight modification, the BST can do both findMin and findMax in O(1).

In this modified BST, you keep track of the the min node and max node everytime you do an operation that can potentially modify the data structure. For example in insert operation you can check if the min value is larger than the newly inserted value, then assign the min value to the newly added node. The same technique can be applied on the max value. Hence, this BST contain these information which you can retrieve them in O(1). (same as binary heap)

In this BST (Balanced BST), when you pop min or pop max, the next min value to be assigned is the successor of the min node, whereas the next max value to be assigned is the predecessor of the max node. Thus it perform in O(1). However we need to re-balance the tree, thus it will still run O(log n). (same as binary heap)

I would be interested to hear your thought in the comment below. Thanks :)

Update

Cross reference to similar question Can we use binary search tree to simulate heap operation? for more discussion on simulating Heap using BST.

Getting Unexpected Token Export

In case you get this error, it might also be related to how you included the JavaScript file into your html page. When loading modules, you have to explicitly declare those files as such. Here's an example:

//module.js:
function foo(){
   return "foo";
}

var bar = "bar";

export { foo, bar };

When you include the script like this:

<script src="module.js"></script>

You will get the error:

Uncaught SyntaxError: Unexpected token export

You need to include the file with a type attribute set to "module":

<script type="module" src="module.js"></script>

then it should work as expected and you are ready to import your module in another module:

import { foo, bar } from  "./module.js";

console.log( foo() );
console.log( bar );

Commit only part of a file in Git

Adding on a previous answer, if you prefer using the command line, entering git add -e myfile gives you the choice to choose line by line what you want to commit because this command will open an editor with the differences, like so:

enter image description here

As you may known lines that start with + are addtions, lines that start with - are deletions. So:

  • To not stage an addition just delete that line.
  • To not stage a deletion just replace - with space .

This is what git add -h says about adding files this way (patching files):

added content Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them.

removed content: Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).

modified content: Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+" lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index.

Caution: do not change the content of the file, this is not a good place to do so. Just change the operators of deleted or added lines.

no sqljdbc_auth in java.library.path

For easy fix follow these steps:

  1. goto: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
  2. Download the JDBC file and extract to your preferred location
  3. open the auth folder matching your OS x64 or x86
  4. copy sqljdbc_auth.dll file
  5. paste in: C:\Program Files\Java\jdk_version\bin
  6. restart either eclipse or netbeans

Why am I getting ImportError: No module named pip ' right after installing pip?

The ensurepip module was added in version 3.4 and then backported to 2.7.9.

So make sure your Python version is at least 2.7.9 if using Python 2, and at least 3.4 if using Python 3.

C++ terminate called without an active exception

As long as your program die, then without detach or join of the thread, this error will occur. Without detaching and joining the thread, you should give endless loop after creating thread.

int main(){

std::thread t(thread,1);

while(1){}

//t.detach();
return 0;}

It is also interesting that, after sleeping or looping, thread can be detach or join. Also with this way you do not get this error.

Below example also shows that, third thread can not done his job before main die. But this error can not happen also, as long as you detach somewhere in the code. Third thread sleep for 8 seconds but main will die in 5 seconds.

void thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));}

int main() {
std::cout << "Start main\n";
std::thread t(thread,1);
std::thread t2(thread,3);
std::thread t3(thread,8);
sleep(5);

t.detach();
t2.detach();
t3.detach();
return 0;}

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Access parent's parent from javascript object

With the following code you can access the parent of the object:

var Users = function(parent) {
    this.parent = parent;
};
Users.prototype.guys = function(){ 
    this.parent.nameAndDestroy(['test-name-and-destroy']);
};
Users.prototype.girls = function(){ 
    this.parent.kiss(['test-kiss']);
};

var list = {
    users : function() {
        return new Users(this);
    },
    nameAndDestroy : function(group){ console.log(group); },
    kiss : function(group){ console.log(group); }
};

list.users().guys(); // should output ["test-name-and-destroy"]
list.users().girls(); // should output ["test-kiss"]

I would recommend you read about javascript Objects to get to know how you can work with Objects, it helped me a lot. I even found out about functions that I didn't even knew they existed.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

In my case I forgot to change the database from postgres (on my production) back to sqlite3 which I was using for development.

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

Run -> Edit configurations -> Select your build configuration -> JRE - change Default to one of actual JDK paths

How to ping a server only once from within a batch file?

if you want to use the name "ping.bat", a small trick is to use this code:

@echo off
cd\ 
ping google.com -t

Just add that "cd\" and you are fine... ;)

Parse strings to double with comma and point

Make two static cultures, one for comma and one for point.

    var commaCulture = new CultureInfo("en")
    {
        NumberFormat =
        {
            NumberDecimalSeparator = ","
        }
    };

    var pointCulture = new CultureInfo("en")
    {
        NumberFormat =
        {
            NumberDecimalSeparator = "."
        }
    };

Then use each one respectively, depending on the input (using a function):

    public double ConvertToDouble(string input)
    {
        input = input.Trim();

        if (input == "0") {
            return 0;
        }

        if (input.Contains(",") && input.Split(',').Length == 2)
        {
            return Convert.ToDouble(input, commaCulture);
        }

        if (input.Contains(".") && input.Split('.').Length == 2)
        {
            return Convert.ToDouble(input, pointCulture);
        }

        throw new Exception("Invalid input!");
    }

Then loop through your arrays

    var strings = new List<string> {"0,12", "0.122", "1,23", "00,0", "0.00", "12.5000", "0.002", "0,001"};
    var doubles = new List<double>();

    foreach (var value in strings) {
        doubles.Add(ConvertToDouble(value));
    }

This should work even though the host environment and culture changes.

How to update std::map after using the find method?

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

Matplotlib tight_layout() doesn't take into account figure suptitle

The only thing that worked for me was modifying the call to suptitle:

fig.suptitle("title", y=.995)

Display an array in a readable/hierarchical format

I assume one uses print_r for debugging. I would then suggest using libraries like Kint. This allows displaying big arrays in a readable format:

$data = [['Natural Child 1', 'Natural Child 2', 'Natural Child 3']];
Kint::dump($data, $_SERVER);

enter image description here

How do I echo and send console output to a file in a bat script?

No, you can't with pure redirection.
But with some tricks (like tee.bat) you can.

I try to explain the redirection a bit.

You redirect one of the ten streams with > file or < file
It is unimportant, if the redirection is before or after the command, so these two lines are nearly the same.

dir > file.txt
> file.txt dir

The redirection in this example is only a shortcut for 1>, this means the stream 1 (STDOUT) will be redirected.
So you can redirect any stream with prepending the number like 2> err.txt and it is also allowed to redirect multiple streams in one line.

dir 1> files.txt 2> err.txt 3> nothing.txt

In this example the "standard output" will go into files.txt, all errors will be in err.txt and the stream3 will go into nothing.txt (DIR doesn't use the stream 3).
Stream0 is STDIN
Stream1 is STDOUT
Stream2 is STDERR
Stream3-9 are not used

But what happens if you try to redirect the same stream multiple times?

dir > files.txt > two.txt

"There can be only one", and it is always the last one!
So it is equal to dir > two.txt

Ok, there is one extra possibility, redirecting a stream to another stream.

dir 1>files.txt 2>&1 

2>&1 redirects stream2 to stream1 and 1>files.txt redirects all to files.txt.
The order is important here!

dir ... 1>nul 2>&1
dir ... 2>&1 1>nul

are different. The first one redirects all (STDOUT and STDERR) to NUL,
but the second line redirects the STDOUT to NUL and STDERR to the "empty" STDOUT.

As one conclusion, it is obvious why the examples of Otávio Décio and andynormancx can't work.

command > file >&1
dir > file.txt >&2

Both try to redirect stream1 two times, but "There can be only one", and it's always the last one.
So you get

command 1>&1
dir 1>&2

And in the first sample redirecting of stream1 to stream1 is not allowed (and not very useful).

Hope it helps.

Timestamp Difference In Hours for PostgreSQL

Get fields where a timestamp is greater than date in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > to_date('05 Dec 2000', 'DD Mon YYYY');

Subtract minutes from timestamp in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > current_timestamp - interval '5 minutes'

Subtract hours from timestamp in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > current_timestamp - interval '5 hours'

Function vs. Stored Procedure in SQL Server

Stored Procedures are used as scripts. They run a series of commands for you and you can schedule them to run at certain times. Usually runs multiples DML statements like INSERT, UPDATE, DELETE, etc. or even SELECT.

Functions are used as methods. You pass it something and it returns a result. Should be small and fast - does it on the fly. Usually used in a SELECT statement.

Display date/time in user's locale format and time offset

The .getTimezoneOffset() method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)

To the get a normal time-zone offset in hours, you need to use:

var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60

Important detail:
Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset.

Filter element based on .data() key/value

Two things I noticed (they may be mistakes from when you wrote it down though).

  1. You missed a dot in the first example ( $('.navlink').click )
  2. For filter to work, you have to return a value ( return $(this).data("selected")==true )

How to provide a mysql database connection in single file in nodejs

From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:

    const mysql = require('mysql');

    var connection;

    module.exports = {

    dbConnection: function () {

        connection = mysql.createConnection({
            host: "127.0.0.1",
            user: "Your_user",
            password: "Your_password",
            database: 'Your_bd'
        });
        connection.connect();
        return connection;
    }

    };

Then, the file where you are going to use the connection could be like useDb.js:

const dbConnection = require('./db');

var connection;

function callDb() {

    try {

        connection = dbConnectionManager.dbConnection();

        connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
            if (!error) {

                let response = "The solution is: " + results[0].solution;
                console.log(response);

            } else {
                console.log(error);
            }
        });
        connection.end();


    } catch (err) {
        console.log(err);
    }
}

Create view with primary key?

I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.

CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM  dbo.MyTable

How do I get JSON data from RESTful service using Python?

Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .

https://github.com/scastillo/siesta

However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

From http://docs.python.org/library/csv.html#csv.writer:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with statement to close the file when you're done writing to it.
Tested example below:

from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
    output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
    output.writerow(dict((fn,fn) for fn in headers))
    output.writerows(rows)

Powershell: convert string to number

I demonstrate how to receive a string, for example "-484876800000" and tryparse the string to make sure it can be assigned to a long. I calculate the Date from universaltime and return a string. When you convert a string to a number, you must decide the numeric type and precision and test if the string data can be parse, otherwise, it will throw and error.

function universalToDate
{
 param (
    $paramValue
  )
    $retVal=""


    if ($paramValue)
    {
        $epoch=[datetime]'1/1/1970'
        [long]$returnedLong = 0
        [bool]$result = [long]::TryParse($paramValue,[ref]$returnedLong)
        if ($result -eq 1)
        {
            $val=$returnedLong/1000.0
            $retVal=$epoch.AddSeconds($val).ToString("yyyy-MM-dd")
        }
    }
    else
    {
        $retVal=$null
    }
    return($retVal)
 }

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

I handle the ajax request by using Selenium and the Firefox web driver. It is not that fast if you need the crawler as a daemon, but much better than any manual solution. I wrote a short tutorial here for reference

How can I convert an HTML element to a canvas element?

Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:

rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>' 
                     + '<img src="local_img.png"/>', canvas);

Source code and a more extensive example is here.

Centering elements in jQuery Mobile

An overkill approach: in inline css in the div did the trick:

style="margin:0 auto;
margin-left:auto;
margin-right:auto;
align:center;
text-align:center;"

Centers like a charm!

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='') 
BEGIN
   SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
   INSERT INTO TABLE(FieldValue) VALUES('')
   SELECT SCOPE_IDENTITY() AS TableID
END

See here for more information on IF ELSE

Note: written without a SQL Server install handy to double check this but I think it is correct

Also, I've changed the EXISTS bit to do SELECT 1 rather than SELECT * as you don't care what is returned within an EXISTS, as long as something is I've also changed the SCOPE_IDENTITY() bit to return just the identity assuming that TableID is the identity column

Where is localhost folder located in Mac or Mac OS X?

For posterity

I never use PHP so I completely forgot where apache was installed on my mac as it was running on port 8080 mocking me, installed in a non-standard path. After giving up on the internet, I tried this...

httpd -t -D DUMP_INCLUDES

Because httpd was running it produced the httpd.config path and then the clouds parted and the sun shown brightly on my face. Victory! as within it lies the path to localhost.

ServerRoot "/your/path"

How to convert answer into two decimal point

If you have a Decimal or similar numeric type, you can use:

Math.Round(myNumber, 2)

EDIT: So, in your case, it would be:

Public Class Form1
  Private Sub btncalc_Click(ByVal sender As System.Object,
                            ByVal e As System.EventArgs) Handles btncalc.Click
    txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
    txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
  End Sub
End Class

Warning: The method assertEquals from the type Assert is deprecated

this method also encounter a deprecate warning:

org.junit.Assert.assertEquals(float expected,float actual) //deprecated

It is because currently junit prefer a third parameter rather than just two float variables input.

The third parameter is delta:

public static void assertEquals(double expected,double actual,double delta) //replacement

this is mostly used to deal with inaccurate Floating point calculations

for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values

Running multiple commands in one line in shell

Note that cp A B; rm A is exactly mv A B. It'll be faster too, as you don't have to actually copy the bytes (assuming the destination is on the same filesystem), just rename the file. So you want cp A B; mv A C

WPF chart controls

You can get the Silverlight Chart Controls running on WPF, they're quite nice (and free).

Get ASCII value at input word

simply do

int a = ch

(also this has nothing to do with android)

How do I find the current directory of a batch file, and then use it for the path?

There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt

And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:

@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit

Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit

How to set encoding in .getJSON jQuery

Use encodeURI() in client JS and use URLDecoder.decode() in server Java side works.


Example:

  • Javascript:

    $.getJSON(
        url,
        {
            "user": encodeURI(JSON.stringify(user))
        },
        onSuccess
    );
    
  • Java:

    java.net.URLDecoder.decode(params.user, "UTF-8");

Embed YouTube Video with No Ads

From the YouTube help:

You will automatically be opted into showing ads on embedded videos if you've associated your YouTube and AdSense accounts and have enabled your videos for embedding.

If you don't want to show overlay ads on your embedded videos, you can opt your videos out of showing overlay ads, though this will also disable overlay ads on your videos on YouTube.com. You may also disable your videos for embedding.

https://support.google.com/youtube/answer/132596?hl=en

Another technical solution could be to use a custom video player, and streamline the youtube video with that one. Have not tried but guess that the ads cannot be displayed in a custom player. However, could be forbidden.

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

How to clear Route Caching on server: Laravel 5.2.37

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan cache:clear

php artisan route:cache

It should work.

How to Rotate a UIImage 90 degrees?

If you want to add a photo rotate button that'll keep rotating the photo in 90 degree increments, here you go. (finalImage is a UIImage that's already been created elsewhere.)

- (void)rotatePhoto {
    UIImage *rotatedImage;

    if (finalImage.imageOrientation == UIImageOrientationRight)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationDown];
    else if (finalImage.imageOrientation == UIImageOrientationDown)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationLeft];
    else if (finalImage.imageOrientation == UIImageOrientationLeft)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationUp];
    else
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                                     scale: 1.0
                                               orientation: UIImageOrientationRight];
    finalImage = rotatedImage;
}

Run bash script as daemon

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

sudo nano /etc/rc.local

Add the following and save:

#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf

add the following:

description "My Daemon Job"
author "Your Name"
start on runlevel [2345]    

pre-start script
  echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script

exec /bin/sh TheNameOfYourScript.sh > /dev/null &

Save this.

Confirm that it looks ok:

init-checkconf /etc/init/TheNameOfYourDaemon.conf

Now reboot the machine:

sudo reboot

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat  /var/log/TheNameOfYourDaemonJobLog.log

• Now you may start/stop/restart/get the status of your Daemon via:

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status

Determining if Swift dictionary contains key and obtaining any of its values

Here is what works for me on Swift 3

let _ = (dict[key].map { $0 as? String } ?? "")

Adding placeholder text to textbox

txtUsuario.Attributes.Add("placeholder", "Texto");

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Put the select statement in a dynamic PL/SQL block.

CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2) 
RETURN NUMBER
IS
  v_query_str VARCHAR2(1000);
  v_num_of_employees NUMBER;
BEGIN
  v_query_str := 'begin SELECT COUNT(*) INTO :into_bind FROM emp_' 
                 || p_loc
                 || ' WHERE job = :bind_job; end;';
  EXECUTE IMMEDIATE v_query_str
    USING out v_num_of_employees, p_job;
  RETURN v_num_of_employees;
END;
/

Randomize a List<T>

A simple modification of the accepted answer that returns a new list instead of working in-place, and accepts the more general IEnumerable<T> as many other Linq methods do.

private static Random rng = new Random();

/// <summary>
/// Returns a new list where the elements are randomly shuffled.
/// Based on the Fisher-Yates shuffle, which has O(n) complexity.
/// </summary>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) {
    var source = list.ToList();
    int n = source.Count;
    var shuffled = new List<T>(n);
    shuffled.AddRange(source);
    while (n > 1) {
        n--;
        int k = rng.Next(n + 1);
        T value = shuffled[k];
        shuffled[k] = shuffled[n];
        shuffled[n] = value;
    }
    return shuffled;
}

A terminal command for a rooted Android to remount /System as read/write

Instead of

mount -o rw,remount /system/

use

mount -o rw,remount /system

mind the '/' at the end of the command. you ask why this matters? /system/ is the directory under /system while /system is the volume name.

Is there a decent wait function in C++?

Syntax:

void sleep(unsigned seconds);

sleep() suspends execution for an interval (seconds). With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.

This example should make it clear:

#include <dos.h>
#include <stdio.h>
#include <conio.h>

int main()
{
   printf("Message 1\n");
   sleep(2); //Parameter in sleep is in seconds
   printf("Message 2 a two seconds after Message 1");
   return 0;
}

Remember you have to #include dos.h

EDIT:

You could also use winAPI.

VOID WINAPI Sleep(
DWORD dwMilliseconds
);

Sleep Function(Windows)

Just a note,the parameter in the function provided by winapi is in milliseconds ,so the sleep line at the code snippet above would look like this "Sleep(2000);"

How do you initialise a dynamic array in C++?

Maybe use std::fill_n()?

char* c = new char[length];
std::fill_n(c,length,0);

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

#!/usr/bin/env python
#-*- coding: utf-8 -*-
u = u'moçambique'
print u.encode("utf-8")
print u

chmod +x test.py
./test.py
moçambique
moçambique

./test.py > output.txt
Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    print u
UnicodeEncodeError: 'ascii' codec can't encode character 
u'\xe7' in position 2: ordinal not in range(128)

on shell works , sending to sdtout not , so that is one workaround, to write to stdout .

I made other approach, which is not run if sys.stdout.encoding is not define, or in others words , need export PYTHONIOENCODING=UTF-8 first to write to stdout.

import sys
if (sys.stdout.encoding is None):            
    print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." 
    exit(1)


so, using same example:

export PYTHONIOENCODING=UTF-8
./test.py > output.txt

will work

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

How to make (link)button function as hyperlink?

The best way to accomplish this is by simply adding "href" to the link button like below.

<asp:LinkButton runat="server" id="SomeLinkButton" href="url" CssClass="btn btn-primary btn-sm">Button Text</asp:LinkButton>

Using javascript, or doing this programmatically in the page_load, will work as well but is not the best way to go about doing this.

You will get this result:

<a id="MainContent_ctl00_SomeLinkButton" class="btn btn-primary btn-sm" href="url" href="javascript:__doPostBack(&#39;ctl00$MainContent$ctl00$lSomeLinkButton&#39;,&#39;&#39;)">Button Text</a>

You can also get the same results by using using a regular <a href="" class=""></a>.

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

In .NET4.5, MVC 5 no need for widgets.

Javascript:

object in JS: enter image description here

mechanism that does post.

    $('.button-green-large').click(function() {
        $.ajax({
            url: 'Quote',
            type: "POST",
            dataType: "json",
            data: JSON.stringify(document.selectedProduct),
            contentType: 'application/json; charset=utf-8',
        });
    });

C#

Objects:

public class WillsQuoteViewModel
{
    public string Product { get; set; }

    public List<ClaimedFee> ClaimedFees { get; set; }
}

public partial class ClaimedFee //Generated by EF6
{
    public long Id { get; set; }
    public long JourneyId { get; set; }
    public string Title { get; set; }
    public decimal Net { get; set; }
    public decimal Vat { get; set; }
    public string Type { get; set; }

    public virtual Journey Journey { get; set; }
}

Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}

Object received:

enter image description here

Hope this saves you some time.

How to set image width to be 100% and height to be auto in react native?

"resizeMode" isn't style property. Should move to Image component's Props like below code.

const win = Dimensions.get('window');

const styles = StyleSheet.create({
    image: {
        flex: 1,
        alignSelf: 'stretch',
        width: win.width,
        height: win.height,
    }
});

...
    <Image 
       style={styles.image}
       resizeMode={'contain'}   /* <= changed  */
       source={require('../../../images/collection-imag2.png')} /> 
...

Image's height won't become automatically because Image component is required both width and height in style props. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.

There are a lot of useful open source libraries -

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

MassAssignmentException in Laravel

if you have table and fields on database you can simply use this command :

php artisan db:seed --class=UsersTableSeeder --database=YOURDATABSE

Different ways of clearing lists

There are two cases in which you might want to clear a list:

  1. You want to use the name old_list further in your code;
  2. You want the old list to be garbage collected as soon as possible to free some memory;

In case 1 you just go on with the assigment:

    old_list = []    # or whatever you want it to be equal to

In case 2 the del statement would reduce the reference count to the list object the name old list points at. If the list object is only pointed by the name old_list at, the reference count would be 0, and the object would be freed for garbage collection.

    del old_list

What is an undefined reference/unresolved external symbol error and how do I fix it?

In my case, The syntax was correct, yet I had that error when a class calls a second class within the same DLL. the CPP file of the second class had the wrong Properties->Item Type inside visual studio, in my case it was set to C/C++ Header instead of the correct one C/C++ compiler so the compiler didn't compile the CPP file while building it and cause the Error LNK2019

here's an example, Assuming the syntax is correct you should get the error by changing the item type in properties

//class A header file 
class ClassB; // FORWARD DECLERATION
class ClassA
{
public:
ClassB* bObj;
ClassA(HINSTANCE hDLL) ;
//  member functions
}
--------------------------------
//class A cpp file   
ClassA::ClassA(HINSTANCE hDLL) 
{
    bObj = new ClassB();// LNK2019 occures here 
    bObj ->somefunction();// LNK2019 occures here
}
/*************************/

//classB Header file
struct mystruct{}
class ClassB{
public:
ClassB();
mystruct somefunction();
}

------------------------------
//classB cpp file  
/* This is the file with the wrong property item type in visual studio --C/C++ Header-*/
ClassB::somefunction(){}
ClassB::ClassB(){}

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

Jquery DatePicker Set default date

First you need to get the current date

var currentDate = new Date();

Then you need to place it in the arguments of datepicker like given below

$("#datepicker").datepicker("setDate", currentDate);

Check the following jsfiddle.

Increase max_execution_time in PHP?

Add this to an htaccess file (and see edit notes added below):

<IfModule mod_php5.c>
   php_value post_max_size 200M
   php_value upload_max_filesize 200M
   php_value memory_limit 300M
   php_value max_execution_time 259200
   php_value max_input_time 259200
   php_value session.gc_maxlifetime 1200
</IfModule>

Additional resources and information:


2021 EDIT:

As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:

  • PHP can be run as a module or as CGI. It is not recommended to run as CGI as it creates a lot of opportunities for attack vectors [Read More]. Running as a module (the safer option) will trigger the settings to be used if the specific module from <IfModule is loaded.
  • The answer indicates to write mod_php5.c in the first line. If you are using PHP 7, you would replace that with mod_php7.c.
  • Sometimes after you make changes to your .htaccess file, restarting Apache or NGINX will not work. The most common reason for this is you are running PHP-FPM, which runs as a separate process. You need to restart that as well.
  • Remember these are settings that are normally defined in your php.ini config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.
  • Finally, it's important to note that not all php.ini settings can be configured via an .htaccess file. A file list of php.ini directives can be found here, and the only ones you can change are the ones in the changeable column with the modes PHP_INI_ALL or PHP_INI_PERDIR.

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Finding non-numeric rows in dataframe in pandas?

I'm thinking something like, just give an idea, to convert the column to string, and work with string is easier. however this does not work with strings containing numbers, like bad123. and ~ is taking the complement of selection.

df['a'] = df['a'].astype(str)
df[~df['a'].str.contains('0|1|2|3|4|5|6|7|8|9')]
df['a'] = df['a'].astype(object)

and using '|'.join([str(i) for i in range(10)]) to generate '0|1|...|8|9'

or using np.isreal() function, just like the most voted answer

df[~df['a'].apply(lambda x: np.isreal(x))]

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, because pseudo-elements, as the name implies, are not real elements, and therefore you can't select and manipulate them directly with jQuery (or any JavaScript APIs for that matter, not even the Selectors API). This applies to any pseudo-elements whose styles you're trying to modify with a script, and not just ::before and ::after.

You can only access pseudo-element styles directly at runtime via the CSSOM (think window.getComputedStyle()), which is not exposed by jQuery beyond .css(), a method that doesn't support pseudo-elements either.

You can always find other ways around it, though, for example:

  • Applying the styles to the pseudo-elements of one or more arbitrary classes, then toggling between classes (see seucolega's answer for a quick example) — this is the idiomatic way as it makes use of simple selectors (which pseudo-elements are not) to distinguish between elements and element states, the way they're intended to be used

  • Manipulating the styles being applied to said pseudo-elements, by altering the document stylesheet, which is much more of a hack

Objects inside objects in javascript

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};

then:

pause_menu.pause_button.someProperty //evaluates to "prop1"

etc etc.

How do I get the XML root node with C#?

I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.

  using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
    while (reader.Read()) {
      // first element is the root element
      if (reader.NodeType == XmlNodeType.Element) {
        System.Console.WriteLine(reader.Name);
        break;
      }
    }
  }

What's the safest way to iterate through the keys of a Perl hash?

Using the each syntax will prevent the entire set of keys from being generated at once. This can be important if you're using a tie-ed hash to a database with millions of rows. You don't want to generate the entire list of keys all at once and exhaust your physical memory. In this case each serves as an iterator whereas keys actually generates the entire array before the loop starts.

So, the only place "each" is of real use is when the hash is very large (compared to the memory available). That is only likely to happen when the hash itself doesn't live in memory itself unless you're programming a handheld data collection device or something with small memory.

If memory is not an issue, usually the map or keys paradigm is the more prevelant and easier to read paradigm.

How to show image using ImageView in Android

shoud be @drawable/image where image could have any extension like: image.png, image.xml, image.gif. Android will automatically create a reference in R class with its name, so you cannot have in any drawable folder image.png and image.gif.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

How can I load the contents of a text file into a batch file variable?

You can use:

set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i

No module named 'openpyxl' - Python 3.4 - Ubuntu

In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:

conda install openpyxl

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

What does ECU units, CPU core and memory mean when I launch a instance

ECUs (EC2 Computer Units) are a rough measure of processor performance that was introduced by Amazon to let you compare their EC2 instances ("servers").

CPU performance is of course a multi-dimensional measure, so putting a single number on it (like "5 ECU") can only be a rough approximation. If you want to know more exactly how well a processor performs for a task you have in mind, you should choose a benchmark that is similar to your task.

In early 2014, there was a nice benchmarking site comparing cloud hosting offers by tens of different benchmarks, over at CloudHarmony benchmarks. However, this seems gone now (and archive.org can't help as it was a web application). Only an introductory blog post is still available.

Also useful: ec2instances.info, which at least aggregates the ECU information of different EC2 instances for comparison. (Add column "Compute Units (ECU)" to make it work.)

SQL JOIN, GROUP BY on three tables to get totals

Thank you very much for the replies!

Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:

1   39.00   9.00

You'll end up with:

1   78.00   48.00

Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.

After much struggling, I think that the following query returns what I need it to:

SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
  SELECT invoiceid, SUM(p.amount) amount
  FROM invoicepayments ip 
  LEFT JOIN payments p ON ip.paymentid = p.paymentid
  GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'

Would you guys concur?

How do emulators work and how are they written?

Emulation may seem daunting but is actually quite easier than simulating.

Any processor typically has a well-written specification that describes states, interactions, etc.

If you did not care about performance at all, then you could easily emulate most older processors using very elegant object oriented programs. For example, an X86 processor would need something to maintain the state of registers (easy), something to maintain the state of memory (easy), and something that would take each incoming command and apply it to the current state of the machine. If you really wanted accuracy, you would also emulate memory translations, caching, etc., but that is doable.

In fact, many microchip and CPU manufacturers test programs against an emulator of the chip and then against the chip itself, which helps them find out if there are issues in the specifications of the chip, or in the actual implementation of the chip in hardware. For example, it is possible to write a chip specification that would result in deadlocks, and when a deadline occurs in the hardware it's important to see if it could be reproduced in the specification since that indicates a greater problem than something in the chip implementation.

Of course, emulators for video games usually care about performance so they don't use naive implementations, and they also include code that interfaces with the host system's OS, for example to use drawing and sound.

Considering the very slow performance of old video games (NES/SNES, etc.), emulation is quite easy on modern systems. In fact, it's even more amazing that you could just download a set of every SNES game ever or any Atari 2600 game ever, considering that when these systems were popular having free access to every cartridge would have been a dream come true.

Redis: How to access Redis log file

vi /usr/local/etc/redis.conf

Look for dir, logfile

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/



# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null 
logfile "redis_log"

So the log file is created at /usr/local/var/db/redis/redis_log with the name redis_log

You can also try MONITOR command from redis-cli to review the number of commands executed.

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

Use and meaning of "in" in an if statement?

Maybe these examples will help illustrate what in does. It basically translate to Is this item in this other item?

listOfNums = [ 1, 2, 3, 4, 5, 6, 45, 'j' ]

>>> 3 in listOfNums:
>>> True

>>> 'j' in listOfNums:
>>> True

>>> 66 in listOfNums:
>>> False

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I solved this issue by doing the following:

When using ECMAScript 6 modules from the browser, use the .js extension in your files and in the script tag add type = "module".

When using ECMAScript 6 modules from a Node.js environment, use the extension .mjs in your files and use this command to run the file:

node --experimental-modules filename.mjs

How to make a form close when pressing the escape key?

You can set a property on the form to do this for you if you have a button on the form that closes the form already.

Set the CancelButton property of the form to that button.

Gets or sets the button control that is clicked when the user presses the Esc key.

If you don't have a cancel button then you'll need to add a KeyDown handler and check for the Esc key in that:

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}

You will also have to set the KeyPreview property to true.

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the ProcessDialogKey method as follows:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

"getaddrinfo failed", what does that mean?

Make sure you pass a proxy attribute in your command forexample - pip install --proxy=http://proxyhost:proxyport pixiedust

Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.

You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings

Uncheck - Use automatic configuration script Check - Use a proxy server for your LAN. Ensure you have given the right address and port.

Click Ok Come back to anaconda terminal and you can try install commands

TypeError: 'int' object is not callable

In my case I changed:

return <variable>

with:

return str(<variable>)

try with the following and it must work:

str(round((a/b)*0.9*c))

How to place and center text in an SVG rectangle

If you are creating the SVG programmatically you can simplify it and do something like this:

  <g>
      <rect x={x} y={y} width={width} height={height} />
      <text
          x={x + width / 2}
          y={y + height / 2}
          dominant-baseline="middle"
          text-anchor="middle"
      >
          {label}
      </text>
  </g>

How can I tell jackson to ignore a property for which I don't have control over the source code?

I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowExceptions. For instance, if I had these objects

public class A{
  Long id;
  String name;
  List<B> children;
}

public class B{
  Long id;
  A parent;
}

I would want to programmatically ignore the parent field in B if I were looking at A, and ignore the children field in A if I were looking at B.

I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way: https://github.com/monitorjbl/json-view.

It allows you programmatically specify what fields to ignore:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);

List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(B.class, match()
        .exclude("parent")));

It also lets you easily specify very simplified views through wildcard matchers:

String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(A.class, match()
        .exclude("*")
         .include("id", "name")));

In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.

All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:

@Controller
public class JsonController {
  private JsonResult json = JsonResult.instance();
  @Autowired
  private TestObjectService service;

  @RequestMapping(method = RequestMethod.GET, value = "/bean")
  @ResponseBody
  public List<TestObject> getTestObject() {
    List<TestObject> list = service.list();

    return json.use(JsonView.with(list)
        .onClass(TestObject.class, Match.match()
            .exclude("int1")
            .include("ignoredDirect")))
        .returnValue();
  }
}

Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

I had this issue while using Python installed with sudo make altinstall on Opensuse linux. It seems that the compiled libraries are installed in /usr/local/lib64 but Python is looking for them in /usr/local/lib.

I solved it by creating a dynamic link to the relevant directory in /usr/local/lib

sudo ln -s /usr/local/lib64/python3.8/lib-dynload/ /usr/local/lib/python3.8/lib-dynload

I suspect the better thing to do would be to specify libdir as an argument to configure (at the start of the build process) but I haven't tested it that way.

How to correctly use "section" tag in HTML5?

You can definitely use the section tag as a container. It is there to group content in a more semantically significant way than with a div or as the html5 spec says:

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. http://www.w3.org/TR/html5/sections.html#the-section-element

How to write inside a DIV box with javascript

I would suggest Jquery:

$("#log").html("Type what you want to be shown to the user");   

What is the best way to trigger onchange event in react js

If you are using Backbone and React, I'd recommend one of the following,

They both help integrate Backbone models and collections with React views. You can use Backbone events just like you do with Backbone views. I've dabbled in both and didn't see much of a difference except one is a mixin and the other changes React.createClass to React.createBackboneClass.

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

are there dictionaries in javascript like python?

An old question but I recently needed to do an AS3>JS port, and for the sake of speed I wrote a simple AS3-style Dictionary object for JS:

http://jsfiddle.net/MickMalone1983/VEpFf/2/

If you didn't know, the AS3 dictionary allows you to use any object as the key, as opposed to just strings. They come in very handy once you've found a use for them.

It's not as fast as a native object would be, but I've not found any significant problems with it in that respect.

API:

//Constructor
var dict = new Dict(overwrite:Boolean);

//If overwrite, allows over-writing of duplicate keys,
//otherwise, will not add duplicate keys to dictionary.

dict.put(key, value);//Add a pair
dict.get(key);//Get value from key
dict.remove(key);//Remove pair by key
dict.clearAll(value);//Remove all pairs with this value
dict.iterate(function(key, value){//Send all pairs as arguments to this function:
    console.log(key+' is key for '+value);
});


dict.get(key);//Get value from key

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

PHP string "contains"

PHP 8 or newer:

Use the str_contains function.

if (str_contains($str, "."))
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

PHP 7 or older:

if (strpos($str, '.') !== FALSE)
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.

Cannot read property 'push' of undefined when combining arrays

I fixed in the below way with typescript

  1. Define and initialize firest

pageNumbers: number[] = [];

  1. than populate it

    for (let i = 1; i < 201; i++) {
        this.pageNumbers.push(i);
    }
    

Android emulator-5554 offline

Simply delete and created gear avd again.It will work.

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

In my case this code did'n work until I move apply plugin: 'kotlin-android' from bottom to top.

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }
}

How to download dependencies in gradle

A slightly lighter task that doesn't unnecessarily copy files to a dir:

task downloadDependencies(type: Exec) {
    configurations.testRuntime.files
    commandLine 'echo', 'Downloaded all dependencies'
}

Updated for kotlin & gradle 6.2.0, with buildscript dependency resolution added:

fun Configuration.isDeprecated() = this is DeprecatableConfiguration && resolutionAlternatives != null

fun ConfigurationContainer.resolveAll() = this
  .filter { it.isCanBeResolved && !it.isDeprecated() }
  .forEach { it.resolve() }

tasks.register("downloadDependencies") {
  doLast {
    configurations.resolveAll()
    buildscript.configurations.resolveAll()
  }
}

How to read lines of a file in Ruby

I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.

To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:

line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
  print "#{line_num += 1} #{line}"
end

Of course this could be a bad idea on very large files since it means loading the whole file into memory.

What's the difference between Visual Studio Community and other, paid versions?

Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

how to show only even or odd rows in sql server 2008?

To select an odd id from a table:

select * from Table_Name where id%2=1;

To select an even id from a table:

select * from Table_Name where id%2=0;

How do I see the extensions loaded by PHP?

You asked where do you see loaded extensions in phpinfo() output.

Answer:

They are listed towards the bottom as separate sections/tables and ONLY if they are loaded. Here is an example of extension Curl loaded.

enter image description here ...

... enter image description here

I installed it on Linux Debian with

sudo apt-get install php7.4-curl

HTTP Error 404 when running Tomcat from Eclipse

Check the server configuration and folders' routes:

  1. Open servers view (Window -> Open view... -> Others... -> Search for 'servers'.

  2. Right click on server (mine is Tomcat v6.0) -> properties -> Click on 'Swicth Location' (check that location's like /servers...

  3. Double click on the server. This will open a new servers page. In the 'Servers Locations' area, check the 'Use Tomcat Installation (takes control of Tomcat Installation)' option.

  4. Restart your server.

  5. Enjoy!

How to get the mysql table columns data type?

The query below returns a list of information about each field, including the MySQL field type. Here is an example:

SHOW FIELDS FROM tablename
/* returns "Field", "Type", "Null", "Key", "Default", "Extras" */

See this manual page.

SFTP in Python? (platform independent)

fsspec is a great option for this, it offers a filesystem like implementation of sftp.

from fsspec.implementations.sftp import SFTPFileSystem
fs = SFTPFileSystem(host=host, username=username, password=password)

# list a directory
fs.ls("/")

# open a file
with fs.open(file_name) as file:
    content = file.read()

Also worth noting that fsspec uses paramiko in the implementation.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

The accounts property is defined like this:

"accounts":{"github":"sergiotapia"}

Your POCO states this:

public List<Account> Accounts { get; set; }

Try using this Json:

"accounts":[{"github":"sergiotapia"}]

An array of items (which is going to be mapped to the list) is always enclosed in square brackets.

Edit: The Account Poco will be something like this:

class Account {
    public string github { get; set; }
}

and maybe other properties.

Edit 2: To not have an array use the property as follows:

public Account Accounts { get; set; }

with something like the sample class I've posted in the first edit.

Change the background color of a row in a JTable

The call to getTableCellRendererComponent(...) includes the value of the cell for which a renderer is sought.

You can use that value to compute a color. If you're also using an AbstractTableModel, you can provide a value of arbitrary type to your renderer.

Once you have a color, you can setBackground() on the component that you're returning.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

Check whether your config string is okay:

Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999

I just had this issue today, and in my case it was because there was an invisible character in the jpda config parameter.

To be precise, I had dos line endings in my setenv.sh file on tomcat, causing a carriage-return character right after 'dt_socket'

Why does make think the target is up to date?

It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.

enter image description here

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

When you installed composer pretty sure you used $ sudo command because of that the ~/.composer folder was created by the root.

Run this to fix the issue:

$ sudo chown -R $USER $HOME/.composer

Table cell widths - fixing width, wrapping/truncating long words

<style type="text/css">
td { word-wrap: break-word;max-width:50px; }            
</style>

Error Running React Native App From Terminal (iOS)

None of these solutions worked for me. These two similar problems offer temporary solutions that worked, it seems the simulator process isn't being shutdown correctly:

Killing Simulator Processes

From https://stackoverflow.com/a/52533391/11279823

  1. Quit the simulator & Xcode.
  2. Opened Activity monitor, selected cpu option and search for sim, killing all the process shown as result.
  3. Then fired up the terminal and run sudo xcrun simctl erase all. It will delete all content of all simulators. By content if you logged in somewhere password will be gone, all developer apps installed in that simulator will be gone.

Opening Simulator before starting the package

From https://stackoverflow.com/a/55374768/11279823

open -a Simulator; npm start

Hopefully a permanent solution is found.

Unsafe JavaScript attempt to access frame with URL

I was getting the same error message when I tried to change the domain for iframe.src.

For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.

Worked like a charm.:)

Why I cannot cout a string?

You do not have to reference std::cout or std::endl explicitly.
They are both included in the namespace std. using namespace std instead of using scope resolution operator :: every time makes is easier and cleaner.

#include<iostream>
#include<string>
using namespace std;

How to click a browser button with JavaScript automatically?

setInterval(function () {document.getElementById("myButtonId").click();}, 1000);

fatal: Not a valid object name: 'master'

First off, when you create a "bare repository", you're not going to be doing any work with it (it doesn't contain a working copy, so the git branch command is not useful).

Now, the reason you wouldn't have a master branch even after doing a git init is that there are no commits: when you create your first commit, you will then have a master branch.

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

How to call external JavaScript function in HTML

In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-

caller.html

<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">

external.js

function letMeCallYou()
{
    alert("Bazinga!!!  you called letMeCallYou")
}

Result : enter image description here

How to drop all tables from the database with manage.py CLI in Django?

Using Python to make a flushproject command, you use :

from django.db import connection
cursor = connection.cursor()
cursor.execute(“DROP DATABASE %s;”, [connection.settings_dict['NAME']])
cursor.execute(“CREATE DATABASE %s;”, [connection.settings_dict['NAME']])

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

You don't have permission to access / on this server

Try to use the following: chmod +rx /home/*

MySQL timezone change?

The easiest way to do this, as noted by Umar is, for example

mysql> SET GLOBAL time_zone = 'America/New_York';

Using the named timezone is important for timezone that has a daylights saving adjustment. However, for some linux builds you may get the following response:

#1298 - Unknown or incorrect time zone

If you're seeing this, you may need to run a tzinfo_to_sql translation... it's easy to do, but not obvious. From the linux command line type in:

mysql_tzinfo_to_sql /usr/share/zoneinfo/|mysql -u root mysql -p

Provide your root password (MySQL root, not Linux root) and it will load any definitions in your zoneinfo into mysql. You can then go back and run your

mysql> SET GLOBAL time_zone = timezone;

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

sudo nginx -t should test all files and return errors and warnings locations

Detecting Back Button/Hash Change in URL

HTML5 has included a much better solution than using hashchange which is the HTML5 State Management APIs - https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history - they allow you to change the url of the page, without needing to use hashes!

Though the HTML5 State Functionality is only available to HTML5 Browsers. So you probably want to use something like History.js which provides a backwards compatible experience to HTML4 Browsers (via hashes, but still supports data and titles as well as the replaceState functionality).

You can read more about it here: https://github.com/browserstate/History.js

How to use JavaScript source maps (.map files)?

Just to add to how to use map files. I use chrome for ubuntu and if I go to sources and click on a file, if there is a map file a message comes up telling me that I can view the original file and how to do it.

For the Angular files that I worked with today I click

Ctrl-P and a list of original files comes up in a small window.

I can then browse through the list to view the file that I would like to inspect and check where the issue might be.

Get the latest date from grouped MySQL data

This should work:

SELECT model, date FROM doc GROUP BY model ORDER BY date DESC

It just sort the dates from last to first and by grouping it only grabs the first one.

Unit Testing: DateTime.Now

We were using a static SystemTime object, but ran into problems running parallel unit tests. I attempted to use Henk van Boeijen's solution but had problems across spawned asynchronous threads, ended up using using AsyncLocal in a manner similar to this below:

public static class Clock
{
    private static Func<DateTime> _utcNow = () => DateTime.UtcNow;

    static AsyncLocal<Func<DateTime>> _override = new AsyncLocal<Func<DateTime>>();

    public static DateTime UtcNow => (_override.Value ?? _utcNow)();

    public static void Set(Func<DateTime> func)
    {
        _override.Value = func;
    }

    public static void Reset()
    {
        _override.Value = null;
    }
}

Sourced from https://gist.github.com/CraftyFella/42f459f7687b0b8b268fc311e6b4af08

Adding an item to an associative array

I think you want $data[$category] = $question;

Or in case you want an array that maps categories to array of questions:

$data = array();
foreach($file_data as $value) {
    list($category, $question) = explode('|', $value, 2);

    if(!isset($data[$category])) {
        $data[$category] = array();
    }
    $data[$category][] = $question;
}
print_r($data);

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

The problem happens because in same hibernate session you are trying to save two objects with same identifier.There are two solutions:-

  1. This is happening because you have not configured your mapping.xml file correctly for id fields as below:-

    <id name="id">
      <column name="id" sql-type="bigint" not-null="true"/>
      <generator class="hibernateGeneratorClass"</generator>
    </id>
    
  2. Overload the getsession method to accept a Parameter like isSessionClear, and clear the session before returning the current session like below

    public static Session getSession(boolean isSessionClear) {
        if (session.isOpen() && isSessionClear) {
            session.clear();
            return session;
        } else if (session.isOpen()) {
            return session;
        } else {
            return sessionFactory.openSession();
        }
    }
    

This will cause existing session objects to be cleared and even if hibernate doesn't generate a unique identifier ,assuming you have configured your database properly for a primary key using something like Auto_Increment,it should work for you.

Div show/hide media query

 Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { 
  #my-content{
   width:100%;
 }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { 
  #my-content{
   width:100%;
 }
 }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { 
display: none;
 }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) {
// Havent code only get for more informations 
 } 

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How do I check if file exists in jQuery or pure JavaScript?

I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:

function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
    return true;
}).bind('error', function() {
    return false;
});
}

It seems to work great, hope this helps someone!

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

How to share data between different threads In C# using AOP?

You can pass an object as argument to the Thread.Start and use it as a shared data storage between the current thread and the initiating thread.

You can also just directly access (with the appropriate locking of course) your data members, if you started the thread using the instance form of the ThreadStart delegate.

You can't use attributes to create shared data between threads. You can use the attribute instances attached to your class as a data storage, but I fail to see how that is better than using static or instance data members.

Aligning a button to the center

For me it worked using flexbox, which is in my opinion the cleanest solution.

Add a css class around the parent div / element with :

.parent {
display: flex;
}

and for the button use:

.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

If this is not working, try :

#wrapper {
    display:flex;
    justify-content: center;
}

CSS: Set Div height to 100% - Pixels

100vh works for me, but at first I had used javascript (actually jQuery, but you can adapt it), to tackle a similar problw.

HTML

<body>
  <div id="wrapper">
    <div id="header">header</div>
    <div id="content">content</div>
  </div>
</body>

js/jQuery

var innerWindowHeight = $(window).height();
var headerHeight = $("#header").height();
var contentHeight = innerWindowHeight - headerHeight;
$(".content").height(contentHeight + "px");

Alternately, you can just use 111px if you don't want to calculate headerHeight.

Also, you may want to put this in a window resize event, to rerun the script if the window height increases for example.

MVC controller : get JSON object from HTTP body?

Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...

public ActionResult Post([FromBody]MyDTOClass inputData){
 ... do something with input data ...
}

Thx to Julias:

Parsing Json .Net Web Api

Make sure your request is sent with the http header:

Content-Type: application/json

Java, Simplified check if int array contains int

You could simply use ArrayUtils.contains from Apache Commons Lang library.

public boolean contains(final int[] array, final int key) {     
    return ArrayUtils.contains(array, key);
}

How can I check if an InputStream is empty without reading from it?

Based on the suggestion of using the PushbackInputStream, you'll find an exemple implementation here:

/**
 * @author Lorber Sebastien <i>([email protected])</i>
 */
public class NonEmptyInputStream extends FilterInputStream {

  /**
   * Once this stream has been created, do not consume the original InputStream 
   * because there will be one missing byte...
   * @param originalInputStream
   * @throws IOException
   * @throws EmptyInputStreamException
   */
  public NonEmptyInputStream(InputStream originalInputStream) throws IOException, EmptyInputStreamException {
    super( checkStreamIsNotEmpty(originalInputStream) );
  }


  /**
   * Permits to check the InputStream is empty or not
   * Please note that only the returned InputStream must be consummed.
   *
   * see:
   * http://stackoverflow.com/questions/1524299/how-can-i-check-if-an-inputstream-is-empty-without-reading-from-it
   *
   * @param inputStream
   * @return
   */
  private static InputStream checkStreamIsNotEmpty(InputStream inputStream) throws IOException, EmptyInputStreamException {
    Preconditions.checkArgument(inputStream != null,"The InputStream is mandatory");
    PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
    int b;
    b = pushbackInputStream.read();
    if ( b == -1 ) {
      throw new EmptyInputStreamException("No byte can be read from stream " + inputStream);
    }
    pushbackInputStream.unread(b);
    return pushbackInputStream;
  }

  public static class EmptyInputStreamException extends RuntimeException {
    public EmptyInputStreamException(String message) {
      super(message);
    }
  }

}

And here are some passing tests:

  @Test(expected = EmptyInputStreamException.class)
  public void test_check_empty_input_stream_raises_exception_for_empty_stream() throws IOException {
    InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
    new NonEmptyInputStream(emptyStream);
  }

  @Test
  public void test_check_empty_input_stream_ok_for_non_empty_stream_and_returned_stream_can_be_consummed_fully() throws IOException {
    String streamContent = "HELLooooô wörld";
    InputStream inputStream = IOUtils.toInputStream(streamContent, StandardCharsets.UTF_8);
    inputStream = new NonEmptyInputStream(inputStream);
    assertThat(IOUtils.toString(inputStream,StandardCharsets.UTF_8)).isEqualTo(streamContent);
  }

How to use `@ts-ignore` for a block

If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx

Compile Views in ASP.NET MVC

The answer given here works for some MVC versions but not for others.

The simple solution worked for MVC1 but on upgrading to MVC2 the views were no longer being compliled. This was due to a bug in the website project files. See this Haacked article.

See this: http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx

"use database_name" command in PostgreSQL

When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.

Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.

How to change the Text color of Menu item in Android?

Thanks for the code example. I had to modify it go get it to work with a context menu. This is my solution.

    static final Class<?>[] constructorSignature = new Class[] {Context.class, AttributeSet.class};

class MenuColorFix implements LayoutInflater.Factory {
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if (name.equalsIgnoreCase("com.android.internal.view.menu.ListMenuItemView")) {
            try {
                Class<? extends ViewGroup> clazz = context.getClassLoader().loadClass(name).asSubclass(ViewGroup.class);
                Constructor<? extends ViewGroup> constructor = clazz.getConstructor(constructorSignature);
                final ViewGroup view = constructor.newInstance(new Object[]{context,attrs});

                new Handler().post(new Runnable() {
                    public void run() {
                        try {
                            view.setBackgroundColor(Color.BLACK);
                            List<View> children = getAllChildren(view);
                            for(int i = 0; i< children.size(); i++) {
                                View child = children.get(i);
                                if ( child instanceof TextView ) {
                                    ((TextView)child).setTextColor(Color.WHITE);
                                }
                            }
                        }
                        catch (Exception e) {
                            Log.i(TAG, "Caught Exception!",e);
                        }

                    }
                });
                return view;
            }
            catch (Exception e) {
                Log.i(TAG, "Caught Exception!",e);
            }
        }
        return null;
    }       
}

public List<View> getAllChildren(ViewGroup vg) {
    ArrayList<View> result = new ArrayList<View>();
    for ( int i = 0; i < vg.getChildCount(); i++ ) {
        View child = vg.getChildAt(i);
        if ( child instanceof ViewGroup) {
            result.addAll(getAllChildren((ViewGroup)child));
        }
        else {
            result.add(child);
        }
    }
    return result;
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    LayoutInflater lInflater = getLayoutInflater();
    if ( lInflater.getFactory() == null ) {
        lInflater.setFactory(new MenuColorFix());
    }
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.myMenu, menu);
}

For me this works with Android 1.6, 2.03 and 4.03.

Java: Insert multiple rows into MySQL with PreparedStatement

@Ali Shakiba your code needs some modification. Error part:

for (int i = 0; i < myArray.length; i++) {
     myStatement.setString(i, myArray[i][1]);
     myStatement.setString(i, myArray[i][2]);
}

Updated code:

String myArray[][] = {
    {"1-1", "1-2"},
    {"2-1", "2-2"},
    {"3-1", "3-2"}
};

StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");

for (int i = 0; i < myArray.length - 1; i++) {
    mySql.append(", (?, ?)");
}

mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());

for (int i = 0; i < myArray.length; i++) {
    myStatement.setString((2 * i) + 1, myArray[i][1]);
    myStatement.setString((2 * i) + 2, myArray[i][2]);
}

myStatement.executeUpdate();

parseInt with jQuery

var test = parseInt($("#testid").val());

Maximum length of the textual representation of an IPv6 address?

Watch out for certain headers such as HTTP_X_FORWARDED_FOR that appear to contain a single IP address. They may actually contain multiple addresses (a chain of proxies I assume).

They will appear to be comma delimited - and can be a lot longer than 45 characters total - so check before storing in DB.

How to loop through all elements of a form jQuery

$('#new_user_form').find('input').each(function(){
   //your code here
});

Using grep to search for hex strings in a file

grep has a -P switch allowing to use perl regexp syntax the perl regex allows to look at bytes, using \x.. syntax.

so you can look for a given hex string in a file with: grep -aP "\xdf"

but the outpt won't be very useful; indeed better do a regexp on the hexdump output;

The grep -P can be useful however to just find files matrching a given binary pattern. Or to do a binary query of a pattern that actually happens in text (see for example How to regexp CJK ideographs (in utf-8) )

What’s the best way to load a JSONObject from a json text file?

With java 8 you can try this:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}

Unable to specify the compiler with CMake

Using with FILEPATH option might work:

set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)

Move UIView up when the keyboard appears in iOS

Based on Daniel Krom's solution. This is version in swift 3.0. Works great with AutoLayout, and moves whole view when keyboard appears.

extension UIView {

    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func unbindFromKeyboard(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc
    func keyboardWillChange(notification: NSNotification) {

        guard let userInfo = notification.userInfo else { return }

        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        })
    }  
}

How to use it: Add bindToKeyboard function in viewDidLoad like:

override func viewDidLoad() {
    super.viewDidLoad()

    view.bindToKeyboard()
}

And add unbindFromKeyboard function in deinit:

deinit {
    view.unbindFromKeyboard()
}

Angular ng-repeat add bootstrap row every 3 or 4 cols

I've just made a solution of it working only in template. The solution is

    <span ng-repeat="gettingParentIndex in products">
        <div class="row" ng-if="$index<products.length/2+1">    <!-- 2 columns -->
            <span ng-repeat="product in products">
                <div class="col-sm-6" ng-if="$index>=2*$parent.$index && $index <= 2*($parent.$index+1)-1"> <!-- 2 columns -->
                    {{product.foo}}
                </div>
            </span>
        </div>
    </span>

Point is using data twice, one is for an outside loop. Extra span tags will remain, but it depends on how you trade off.

If it's a 3 column layout, it's going to be like

    <span ng-repeat="gettingParentIndex in products">
        <div class="row" ng-if="$index<products.length/3+1">    <!-- 3 columns -->
            <span ng-repeat="product in products">
                <div class="col-sm-4" ng-if="$index>=3*$parent.$index && $index <= 3*($parent.$index+1)-1"> <!-- 3 columns -->
                    {{product.foo}}
                </div>
            </span>
        </div>
    </span>

Honestly I wanted

$index<Math.ceil(products.length/3)

Although it didn't work.

ASP.NET MVC - passing parameters to the controller

you can change firstItem to id and it will work

you can change the routing on global.asax (i do not recommed that)

and, can't believe no one mentioned this, you can call :

http://localhost:2316/Inventory/ViewStockNext?firstItem=11

In a @Url.Action would be :

@Url.Action("ViewStockNext", "Inventory", new {firstItem=11});

depending on the type of what you are doing, the last will be more suitable. Also you should consider not doing ViewStockNext action and instead a ViewStock action with index. (my 2cents)

Pointer vs. Reference

My rule of thumb is:

Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.

Use references otherwise.

How to make div appear in front of another?

In order an element to appear in front of another you have to give higher z-index to the front element, and lower z-index to the back element, also you should indicate position: absolute/fixed...

Example:

<div style="z-index:100; position: fixed;">Hello</div>
<div style="z-index: -1;">World</div>

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is:

public override void Close()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

And StreamReader is:

public override void Close()
{
    this.Dispose(true);
}

The Dispose(bool disposing) override in StreamReader is:

protected override void Dispose(bool disposing)
{
    try
    {
        if ((this.Closable && disposing) && (this.stream != null))
        {
            this.stream.Close();
        }
    }
    finally
    {
        if (this.Closable && (this.stream != null))
        {
            this.stream = null;
            /* deleted for brevity */
            base.Dispose(disposing);
        }
    }
}

The StreamWriter method is similar.

So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way.

So it comes down to whether or not it is more readable to use Dispose(), Close() and/or using ( ... ) { ... }.

My personal preference is that using ( ... ) { ... } should always be used when possible as it helps you to "not run with scissors".

But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream?

So I think it is best to do this:

using (var stream = ...)
{
    /* code */

    stream.Close();
}

It doesn't affect the behaviour of the code, but it does aid readability.

Best way to convert text files between character sets?

Under Linux you can use the very powerful recode command to try and convert between the different charsets as well as any line ending issues. recode -l will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.

Formatting PowerShell Get-Date inside string

You can use the -f operator

$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)

Spécificator    Type                                Example (with [datetime]::now)
d   Short date                                        26/09/2002
D   Long date                                       jeudi 26 septembre 2002
t   Short Hour                                      16:49
T   Long Hour                                       16:49:31
f   Date and hour                                   jeudi 26 septembre 2002 16:50
F   Long Date and hour                              jeudi 26 septembre 2002 16:50:51
g   Default Date                                    26/09/2002 16:52
G   Long default Date and hour                      26/09/2009 16:52:12
M   Month Symbol                                    26 septembre
r   Date string RFC1123                             Sat, 26 Sep 2009 16:54:50 GMT
s   Sortable string date                            2009-09-26T16:55:58
u   Sortable string date universal local hour       2009-09-26 16:56:49Z
U   Sortable string date universal GMT hour         samedi 26 septembre 2009 14:57:22 (oups)
Y   Year symbol                                     septembre 2002

Spécificator    Type                       Example      Output Example
dd              Jour                       {0:dd}       10
ddd             Name of the day            {0:ddd}      Jeu.
dddd            Complet name of the day    {0:dddd}     Jeudi
f, ff, …        Fractions of seconds       {0:fff}      932
gg, …           position                   {0:gg}       ap. J.-C.
hh              Hour two digits            {0:hh}       10
HH              Hour two digits (24 hours) {0:HH}       22
mm              Minuts 00-59               {0:mm}       38
MM              Month 01-12                {0:MM}       12
MMM             Month shortcut             {0:MMM}      Sep.
MMMM            complet name of the month  {0:MMMM}     Septembre
ss              Seconds 00-59              {0:ss}       46
tt              AM or PM                   {0:tt}       ““
yy              Years, 2 digits            {0:yy}       02
yyyy            Years                      {0:yyyy}     2002
zz              Time zone, 2 digits        {0:zz}       +02
zzz             Complete Time zone         {0:zzz}      +02:00
:               Separator                  {0:hh:mm:ss}     10:43:20
/               Separator                  {0:dd/MM/yyyy}   10/12/2002

Is there a way to use SVG as content in a pseudo element :before or :after

<div class="author_">Lord Byron</div>

_x000D_
_x000D_
.author_ {  font-family: 'Playfair Display', serif; font-size: 1.25em; font-weight: 700;letter-spacing: 0.25em; font-style: italic;_x000D_
  position:relative;_x000D_
  margin-top: -0.5em;_x000D_
  color: black;_x000D_
  z-index:1;_x000D_
  overflow:hidden;_x000D_
  text-align:center;_x000D_
 _x000D_
}_x000D_
_x000D_
_x000D_
.author_:after{_x000D_
   left:20px;_x000D_
  margin:0 -100% 0 0;_x000D_
  display: inline-block;_x000D_
  height: 10px;_x000D_
  content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20200%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M1145%2085c17%2C7%208%2C24%20-4%2C29%20-12%2C4%20-40%2C6%20-48%2C-8%20-9%2C-15%209%2C-34%2026%2C-42%2017%2C-7%2045%2C-6%2062%2C2%2017%2C9%2019%2C18%2020%2C27%201%2C9%200%2C29%20-27%2C52%20-28%2C23%20-52%2C34%20-102%2C33%20-49%2C0%20-130%2C-31%20-185%2C-50%20-56%2C-18%20-74%2C-21%20-96%2C-23%20-22%2C-2%20-29%2C-2%20-56%2C7%20-27%2C8%20-44%2C17%20-44%2C17%20-13%2C5%20-15%2C7%20-40%2C16%20-25%2C9%20-69%2C14%20-120%2C11%20-51%2C-3%20-126%2C-23%20-181%2C-32%20-54%2C-9%20-105%2C-20%20-148%2C-23%20-42%2C-3%20-71%2C1%20-104%2C5%20-34%2C5%20-65%2C15%20-98%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}_x000D_
.author_:before {_x000D_
  right:20px;_x000D_
  margin:0 0 0 -100%;_x000D_
  display: inline-block;_x000D_
  height: 10px;_x000D_
  content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20130%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M55%2068c-17%2C6%20-8%2C23%204%2C28%2012%2C5%2040%2C7%2048%2C-8%209%2C-15%20-9%2C-34%20-26%2C-41%20-17%2C-8%20-45%2C-7%20-62%2C2%20-18%2C8%20-19%2C18%20-20%2C27%20-1%2C9%200%2C29%2027%2C52%2028%2C23%2052%2C33%20102%2C33%2049%2C-1%20130%2C-31%20185%2C-50%2056%2C-19%2074%2C-21%2096%2C-23%2022%2C-2%2029%2C-2%2056%2C6%2027%2C8%2043%2C17%2043%2C17%2014%2C6%2016%2C7%2041%2C16%2025%2C9%2069%2C15%20120%2C11%2051%2C-3%20126%2C-22%20181%2C-32%2054%2C-9%20105%2C-20%20148%2C-23%2042%2C-3%2071%2C1%20104%2C6%2034%2C4%2065%2C14%2098%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}
_x000D_
 <div class="author_">Lord Byron</div>
_x000D_
_x000D_
_x000D_

Convenient tool for SVG encoding url-encoder

How to delete a stash created with git stash create?

Git stash clear will clear complete stash,

cmd: git stash clear

If you want to delete a particular stash with a stash index, you can use the drop.

cmd: git stash drop 4

(4 is stash id or stash index)

Write to text file without overwriting in Java

For some reason, none of the other methods worked for me...So i tried this and worked. Hope it helps..

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file\n hi \n hello \n hola";
try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    System.out.println(e);
}

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

How to set JAVA_HOME environment variable on Mac OS X 10.9?

Set $JAVA_HOME environment variable on latest or older Mac OSX.

Download & Install install JDK

  1. First, install JDK
  2. Open terminal check java version

$ java -version

Set JAVA_HOME environment variable

  1. Open .zprofile file

$ open -t .zprofile

Or create . zprofile file

$ open -t .zprofile

  1. write in .zprofile

export JAVA_HOME=$(/usr/libexec/java_home)

Save .zprofile and close the bash file & then write in the terminal for work perfectly.

$ source .zprofile

Setup test in terminal

$ echo $JAVA_HOME  
/Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home

How to convert a Java String to an ASCII byte array?

The problem with other proposed solutions is that they will either drop characters that cannot be directly mapped to ASCII, or replace them with a marker character like ?.

You might desire to have for example accented characters converted to that same character without the accent. There are a couple of tricks to do this (including building a static mapping table yourself or leveraging existing 'normalization' defined for unicode), but those methods are far from complete.

Your best bet is using the junidecode library, which cannot be complete either but incorporates a lot of experience in the most sane way of transliterating Unicode to ASCII.

Should I put #! (shebang) in Python scripts, and what form should it take?

Should I put the shebang in my Python scripts?

Put a shebang into a Python script to indicate:

  • this module can be run as a script
  • whether it can be run only on python2, python3 or is it Python 2/3 compatible
  • on POSIX, it is necessary if you want to run the script directly without invoking python executable explicitly

Are these equally portable? Which form is used most?

If you write a shebang manually then always use #!/usr/bin/env python unless you have a specific reason not to use it. This form is understood even on Windows (Python launcher).

Note: installed scripts should use a specific python executable e.g., /usr/bin/python or /home/me/.virtualenvs/project/bin/python. It is bad if some tool breaks if you activate a virtualenv in your shell. Luckily, the correct shebang is created automatically in most cases by setuptools or your distribution package tools (on Windows, setuptools can generate wrapper .exe scripts automatically).

In other words, if the script is in a source checkout then you will probably see #!/usr/bin/env python. If it is installed then the shebang is a path to a specific python executable such as #!/usr/local/bin/python (NOTE: you should not write the paths from the latter category manually).

To choose whether you should use python, python2, or python3 in the shebang, see PEP 394 - The "python" Command on Unix-Like Systems:

  • ... python should be used in the shebang line only for scripts that are source compatible with both Python 2 and 3.

  • in preparation for an eventual change in the default version of Python, Python 2 only scripts should either be updated to be source compatible with Python 3 or else to use python2 in the shebang line.

How can I check if an element exists in the visible DOM?

Check if the element is a child of <html> via Node::contains():

const div = document.createElement('div');
document.documentElement.contains(div); //-> false

document.body.appendChild(div);
document.documentElement.contains(div); //-> true

I've covered this and more in is-dom-detached.

HTTP POST with Json on Body - Flutter/Dart

OK, finally we have an answer...

You are correctly specifying headers: {"Content-Type": "application/json"}, to set your content type. Under the hood either the package http or the lower level dart:io HttpClient is changing this to application/json; charset=utf-8. However, your server web application obviously isn't expecting the suffix.

To prove this I tried it in Java, with the two versions

conn.setRequestProperty("content-type", "application/json; charset=utf-8"); // fails
conn.setRequestProperty("content-type", "application/json"); // works

Are you able to contact the web application owner to explain their bug? I can't see where Dart is adding the suffix, but I'll look later.

EDIT Later investigation shows that it's the http package that, while doing a lot of the grunt work for you, is adding the suffix that your server dislikes. If you can't get them to fix the server then you can by-pass http and use the dart:io HttpClient directly. You end up with a bit of boilerplate which is normally handled for you by http.

Working example below:

import 'dart:convert';
import 'dart:io';
import 'dart:async';

main() async {
  String url =
      'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
  Map map = {
    'data': {'apikey': '12345678901234567890'},
  };

  print(await apiRequest(url, map));
}

Future<String> apiRequest(String url, Map jsonMap) async {
  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();
  // todo - you should check the response.statusCode
  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

Depending on your use case, it may be more efficient to re-use the HttpClient, rather than keep creating a new one for each request. Todo - add some error handling ;-)

Where is Xcode's build folder?

I wondered the same myself. I found that under File(menu) there is an item "Project Settings". It opens a dialog box with 3 choices: "Default Location", "Project-relative Location", and "Custom location" "Project-relative" puts the build products in the project folder, like before. This is not in the Preferences menu and must be set every time a project is created. Hope this helps.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

To resolve the Could not load file or assembly 'System.Web.Http' error use NuGet to install the Web API 2.1 WebHost.

In solution explorer in the references right click and select manage nuget packages. (if not there install nuget)

enter image description here

In the manage NuGet Packages window on the left side click online then in top right search for Web Host and install Microsoft ASP.NET Web API 2.1 Web Host. (Once installed the install button will change to a green check)

After that the project will reload and when it's build again the error will be resolved and the project will debug and run. The error will be gone and you may be 'The resource cannot be found. Just append the url ( ex from localhost:52088/ to localhost:52088api/products )

Your question was good and helped me.

Hope this answer helps!

How can I record a Video in my Android App.?

Check out this Sample Camera Preview code, CameraPreview. This would help you in devloping video recording code for video preview, create MediaRecorder object, and set video recording parameters.

What is the !! (not not) operator in JavaScript?

It is important to remember the evaluations to true and false in JavaScript:

  • Everything with a "Value" is true (namely truthy), for example:

    • 101,
    • 3.1415,
    • -11,
    • "Lucky Brain",
    • new Object()
    • and, of course, true
  • Everything without a "Value" is false (namely falsy), for example:

    • 0,
    • -0,
    • "" (empty string),
    • undefined,
    • null,
    • NaN (not a number)
    • and, of course, false

Applying the "logical not" operator (!) evaluates the operand, converting it to boolean and then negating it. Applying it twice will negate the negation, effectively converting the value to boolean. Not applying the operator will just be a regular assignment of the exact value. Examples:

var value = 23; // number
var valueAsNegatedBoolean = !value; // boolean falsy (because 23 is truthy)
var valueAsBoolean = !!value; // boolean truthy
var copyOfValue = value; // number 23

var value2 = 0;
var value2AsNegatedBoolean = !value2; // boolean truthy (because 0 is falsy)
var value2AsBoolean = !!value2; // boolean falsy
var copyOfValue2 = value2; // number 0
  • value2 = value; assigns the exact object value even if it is not boolean hence value2 won't necessarily end up being boolean.
  • value2 = !!value; assigns a guaranteed boolean as the result of the double negation of the operand value and it is equivalent to the following but much shorter and readable:

_x000D_
_x000D_
if (value) {
  value2 = true;
} else {
  value2 = false;
}
_x000D_
_x000D_
_x000D_

How can I submit a form using JavaScript?

It works perfectly in my case.

document.getElementById("form1").submit();

Also, you can use it in a function as below:

function formSubmit()
{
    document.getElementById("form1").submit();
}

scroll image with continuous scrolling using marquee tag

I think you set the marquee width related to 5 images total width. It works fine

ex: <marquee style="width:700px"></marquee>

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

I had this issue and fixed it by adding README.md file

How can I check if a value is a json object?

You should return json always, but change its status, or in following example the ResponseCode property:

if(callbackResults.ResponseCode!="200"){
    /* Some error, you can add a message too */
} else {
    /* All fine, proceed with code */
};

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

fatal: The current branch master has no upstream branch

You fixed the push, but, independently of that push issue (which I explained in "Why do I need to explicitly push a new branch?": git push -u origin master or git push -u origin --all), you need now to resolve the authentication issue.

That depends on your url (ssh as in '[email protected]/yourRepo, or https as in https://github.com/You/YourRepo)

For https url:

If your account is protected by the two-factor authentication, your regular password won't work (for https url), as explained here or here.

Same problem if your password contains special character (as in this answer)

If https doesn't work (because you don't want to generate a secondary key, a PAT: personal Access Token), then you can switch to ssh, as I have shown here.


As noted by qwerty in the comments, you can automatically create the branch of same name on the remote with:

git push -u origin head 

Why?

  • HEAD (see your .git\HEAD file) has the refspec of the currently checked out branch (for example: ref: refs/heads/master)
  • the default push policy is simple

Since the refpec used for this push is head: (no destination), a missing :<dst> means to update the same ref as the <src> (head, which is a branch).

That won't work if HEAD is detached though.

jquery onclick change css background image

You need to use background-image instead of backgroundImage. For example:

$(function() {
  $('.home').click(function() {
    $(this).css('background-image', 'url(images/tabs3.png)');
  });
}):

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

Label on the left side instead above an input field

You can create such form where label and form control are side using two method -

1. Inline form layout

<form class="form-inline" role="form">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="email" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="reset" class="btn btn-default">Reset</button>
    <button type="submit" class="btn btn-primary">Login</button>
</form>

2. Horizontal Form Layout

<form class="form-horizontal">
    <div class="row">
        <div class="col-sm-4">
            <div class="form-group">
                <label for="inputEmail" class="control-label col-xs-3">Email</label>
                <div class="col-xs-9">
                    <input type="email" class="form-control" id="inputEmail" placeholder="Email">
                </div>
            </div>
        </div>
        <div class="col-sm-5">
            <div class="form-group">
                <label for="inputPassword" class="control-label col-xs-3">Password</label>
                <div class="col-xs-9">
                    <input type="password" class="form-control" id="inputPassword" placeholder="Password">
                </div>
            </div>
        </div>
        <div class="col-sm-3">
            <button type="reset" class="btn btn-default">Reset</button>
            <button type="submit" class="btn btn-primary">Login</button>
        </div>
    </div>
</form>

You can check out this page for more information and live demo - http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-forms.php

How to decompile a whole Jar file?

Something like:

jar -xf foo.jar && find . -iname "*.class" | xargs /opt/local/bin/jad -r

maybe?

How to remove single character from a String

public static String removechar(String fromString, Character character) {
    int indexOf = fromString.indexOf(character);
    if(indexOf==-1) 
        return fromString;
    String front = fromString.substring(0, indexOf);
    String back = fromString.substring(indexOf+1, fromString.length());
    return front+back;
}

How is AngularJS different from jQuery

Jquery :-

jQuery is a lightweight and feature-rich JavaScript Library that helps web developers
by simplifying the usage of client-side scripting for web applications using JavaScript.
It extensively simplifies using JavaScript on a website and it’s lightweight as well as fast.

So, using jQuery, we can:

easily manipulate the contents of a webpage
apply styles to make UI more attractive
easy DOM traversal
effects and animation
simple to make AJAX calls and
utilities and much more… 

AngularJS :-

AngularJS is a product by none other the Search Engine Giant Google and it’s an open source
MVC-based framework(considered to be the best and only next generation framework). AngularJS
is a great tool for building highly rich client-side web applications.

As being a framework, it dictates us to follow some rules and a structured approach. It’s
not just a JavaScript library but a framework that is perfectly designed (framework tools
are designed to work together in a truly interconnected way).

In comparison of features jQuery Vs AngularJS, AngularJS simply offers more features:

Two-Way data binding
REST friendly
MVC-based Pattern
Deep Linking
Template
Form Validation
Dependency Injection
Localization
Full Testing Environment
Server Communication

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Source - http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/

Pros

  • Fixed-width layouts are much easier to use and easier to customize in terms of design.
  • Widths are the same for every browser, so there is less hassle with images, forms, video and other content that are fixed-width.
  • There is no need for min-width or max-width, which isn’t supported by every browser anyway.
  • Even if a website is designed to be compatible with the smallest screen resolution, 800×600, the content will still be wide enough at a larger resolution to be easily legible.

Cons

  • A fixed-width layout may create excessive white space for users with larger screen resolutions, thus upsetting “divine proportion,” the “Rule of Thirds,” overall balance and other design principles.
  • Smaller screen resolutions may require a horizontal scroll bar, depending the fixed layout’s width.
  • Seamless textures, patterns and image continuation are needed to accommodate those with larger resolutions.
  • Fixed-width layouts generally have a lower overall score when it comes to usability.

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

How do I get the object if it exists, or None if it does not exist?

I use Django 2.2.16. And this is how I solve this problem:

from typing import Any

from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.base import ModelBase
from django.db.models.manager import Manager


class SManager(Manager):
    def get_if_exist(self, *args: Any, **kwargs: Any):
        try:
            return self.get(*args, **kwargs)
        except ObjectDoesNotExist:
            return None


class SModelBase(ModelBase):
    def _prepare(cls):
        manager = SManager()
        manager.auto_created = True
        cls.add_to_class("objects", manager)

        super()._prepare()

    class Meta:
        abstract = True


class SModel(models.Model, metaclass=SModelBase):
    managers = False

    class Meta:
        abstract = True

And after that, in every models, you just need to import in:

from custom.models import SModel


class SUser(SModel):
    pass

And in views, you can call like this:

SUser.objects.get_if_exist(id=1)

How to get RegistrationID using GCM in android

Here I have written a few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find a complete tutorial here:

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snippet to get Registration ID (Device Token for Push Notification).

Configure project for GCM


Update AndroidManifest file

To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml and add this code: Add Permissions

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

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

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration in your application tag:

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>
     
<application/>

Add GCM Service declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);
    context = getApplicationContext();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = getRegistrationId(context);

        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.d(TAG, "No valid Google Play Services APK found.");
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    checkPlayServices();
}


// # Implement GCM Required methods(Add below methods in LaunchActivity)

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
            finish();
        }
        return false;
    }
    return true;
}

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.d(TAG, "Registration ID not found.");
        return "";
    }
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
        Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Could not get package name: " + e);
    }
}


private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Log.d(TAG, "########################################");
                Log.d(TAG, "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return null;
        }
        protected void onPostExecute(Object result) {
            //to do here
        };
    }.execute(null, null, null);
}

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY only.

PHP function ssh2_connect is not working

I am running CentOS 5.6 as my development environment and the following worked for me.

su -
pecl install ssh2
echo "extension=ssh2.so" > /etc/php.d/ssh2.ini

/etc/init.d/httpd restart

Find elements inside forms and iframe using Java and Selenium WebDriver

Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.

Try this before searching for the elements within the iframe:

driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));