Programs & Examples On #Jyaml

YAML library for Java

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

In case someone else runs into this problem, I just did using Eclipse; running the project via the right click action. This error occurred in the J2EE view, but did NOT occur in the Java view. Not sure - assuming something with adding libraries to the correct 'lib' directory.

I am also using a Maven project, allowing m2eclipse to manage dependancies.

PHP Check for NULL

Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero):

if (!$result['column']>0){

}

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

Can't you just change working directory within the python script using os.chdir(target)? I agree, I can't see any way of doing it from the jar command itself.

If you don't want to permanently change directory, then store the current directory (using os.getcwd())in a variable and change back afterwards.

C: How to free nodes in the linked list?

An iterative function to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

What the function is doing is the follow:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

UILabel with text of two different colors

Swift 4

// An attributed string extension to achieve colors on text.
extension NSMutableAttributedString {

    func setColor(color: UIColor, forText stringValue: String) {
       let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
       self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

// Try it with label
let label = UILabel()
label.frame = CGRect(x: 70, y: 100, width: 260, height: 30)
let stringValue = "There are 5 results."
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: "5")
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

Result

enter image description here


Swift 3

func setColoredLabel() {
        var string: NSMutableAttributedString = NSMutableAttributedString(string: "redgreenblue")
        string.setColor(color: UIColor.redColor(), forText: "red")
        string.setColor(color: UIColor.greenColor(), forText: "green")
        string.setColor(color: UIColor.blueColor(, forText: "blue")
        mylabel.attributedText = string
    }


func setColor(color: UIColor, forText stringValue: String) {
        var range: NSRange = self.mutableString.rangeOfString(stringValue, options: NSCaseInsensitiveSearch)
        if range != nil {
            self.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
        }
    }

Result:

enter image description here

Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]


<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

How to check if a MySQL query using the legacy API was successful?

If your query failed, you'll receive a FALSE return value. Otherwise you'll receive a resource/TRUE.

$result = mysql_query($query);

if(!$result){
    /* check for error, die, etc */
}

Basically as long as it's not false, you're fine. Afterwards, you can continue your code.

if(!$result)

This part of the code actually runs your query.

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

How to trace the path in a Breadth-First Search?

I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.

In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour will have to be the end, and once that happens the shortest path is found and program can return.

I would modify the the method as follow, pay close attention to the for loop

graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}


    def bfs(graph_to_search, start, end):
        queue = [[start]]
        visited = set()

    while queue:
        # Gets the first path in the queue
        path = queue.pop(0)

        # Gets the last node in the path
        vertex = path[-1]

        # Checks if we got to the end
        if vertex == end:
            return path
        # We check if the current node is already in the visited nodes set in order not to recheck it
        elif vertex not in visited:
            # enumerate all adjacent nodes, construct a new path and push it into the queue
            for current_neighbour in graph_to_search.get(vertex, []):
                new_path = list(path)
                new_path.append(current_neighbour)
                queue.append(new_path)

                #No need to visit other neighbour. Return at once
                if current_neighbour == end
                    return new_path;

            # Mark the vertex as visited
            visited.add(vertex)


print bfs(graph, 1, 13)

The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.

Importing project into Netbeans

If there is already a nbproject folder it means you can open it straight ahead without importing it as a project with existing sources (ctrl+shift+o) or (cmd+shift+o)

Splitting dataframe into multiple dataframes

You can use the groupby command, if you already have some labels for your data.

 out_list = [group[1] for group in in_series.groupby(label_series.values)]

Here's a detailed example:

Let's say we want to partition a pd series using some labels into a list of chunks For example, in_series is:

2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00    1.16
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 5, dtype: float64

And its corresponding label_series is:

2019-07-01 08:00:00   1
2019-07-01 08:02:00   1
2019-07-01 08:04:00   2
2019-07-01 08:06:00   2
2019-07-01 08:08:00   2
Length: 5, dtype: float64

Run

out_list = [group[1] for group in in_series.groupby(label_series.values)]

which returns out_list a list of two pd.Series:

[2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00   1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 3, dtype: float64]

Note that you can use some parameters from in_series itself to group the series, e.g., in_series.index.day

How do I copy a string to the clipboard?

import wx

def ctc(text):

    if not wx.TheClipboard.IsOpened():
        wx.TheClipboard.Open()
        data = wx.TextDataObject()
        data.SetText(text)
        wx.TheClipboard.SetData(data)
    wx.TheClipboard.Close()

ctc(text)

Display last git commit comment

I did this

git reflog -1 | sed 's/^.*: //'

How to check if a table is locked in sql server

You can use the sys.dm_tran_locks view, which returns information about the currently active lock manager resources.

Try this

 SELECT 
     SessionID = s.Session_id,
     resource_type,   
     DatabaseName = DB_NAME(resource_database_id),
     request_mode,
     request_type,
     login_time,
     host_name,
     program_name,
     client_interface_name,
     login_name,
     nt_domain,
     nt_user_name,
     s.status,
     last_request_start_time,
     last_request_end_time,
     s.logical_reads,
     s.reads,
     request_status,
     request_owner_type,
     objectid,
     dbid,
     a.number,
     a.encrypted ,
     a.blocking_session_id,
     a.text       
 FROM   
     sys.dm_tran_locks l
     JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
     LEFT JOIN   
     (
         SELECT  *
         FROM    sys.dm_exec_requests r
         CROSS APPLY sys.dm_exec_sql_text(sql_handle)
     ) a ON s.session_id = a.session_id
 WHERE  
     s.session_id > 50

Linux Process States

Generally the process will block. If the read operation is on a file descriptor marked as non-blocking or if the process is using asynchronous IO it won't block. Also if the process has other threads that aren't blocked they can continue running.

The decision as to which process runs next is up to the scheduler in the kernel.

SQL Server: use CASE with LIKE

One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.

You should create another table and store one value per row.

This will make your querying easier, and your database structure better.

select 
    case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end
from yourtable

Running MSBuild fails to read SDKToolsPath

One of your projects use sgen.exe (Server Generator) to generate web service. you need install SDKs to Build Server or remove Web Service references from the project.

Joda DateTime to Timestamp conversion

It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".

An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).

Their perception is different but the moment is the same.

You can find more details in this answer.

UPDATE

OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".

Let's look at your original question code broken down like this:

// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");

// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));

// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());

I haven't run this code but I am certain it will print true and the same number of milliseconds each time:

System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));

System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());

But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].

In your own answer you are artificially adding an offset and creating a "wrong" time. If you use that timestamp to create another DateTime and print it out it will be offset twice.

// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));

P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.

JUnit Test as proof

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;


public class WorldTimeTest {
    private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
    private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private TimeZone londonTimeZone;
    private TimeZone newYorkTimeZone;
    private TimeZone sydneyTimeZone;
    private long nowInMillis;
    private Date now;

    public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
        SimpleDateFormat result = new SimpleDateFormat(pattern);
        // Must explicitly set the time zone with "setCalendar()".
        result.setCalendar(Calendar.getInstance(timeZone));
        return result;
    }

    public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
        return createDateFormat(pattern, TimeZone.getDefault());
    }

    public static SimpleDateFormat createDateFormat() throws Exception {
        return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
    }

    public void printSystemInfo() throws Exception {
        final String[] propertyNames = {
                "java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
                "os.name", "os.version", "os.arch",
                "user.language", "user.country", "user.script", "user.variant",
                "user.language.format", "user.country.format", "user.script.format",
                "user.timezone" };

        System.out.println();
        System.out.println("System Information:");
        for (String name : propertyNames) {
            if (name == null || name.length() == 0) {
                continue;
            }
            String value = System.getProperty(name);
            if (value != null && value.length() > 0) {
                System.out.println("  " + name + " = " + value);
            }
        }

        final TimeZone defaultTZ = TimeZone.getDefault();
        final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final int userOffset = TimeZone.getTimeZone(System
                .getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final Locale defaultLocale = Locale.getDefault();

        System.out.println("  default.timezone-offset (hours) = " + userOffset);
        System.out.println("  default.timezone = " + defaultTZ.getDisplayName());
        System.out.println("  default.timezone.id = " + defaultTZ.getID());
        System.out.println("  default.timezone-offset (hours) = " + defaultOffset);
        System.out.println("  default.locale = "
                + defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
                + " (" + defaultLocale.getDisplayLanguage()
                + "," + defaultLocale.getDisplayCountry() + ")");
        System.out.println("  now = " + nowInMillis + " [ms] or "
                + createDateFormat().format(now));
        System.out.println();
    }

    @Before
    public void setUp() throws Exception {
        // Remember this moment.
        now = new Date();
        nowInMillis = now.getTime(); // == System.currentTimeMillis();

        // Print out some system information.
        printSystemInfo();

        // "Europe/London" time zone is DST aware, we'll use fixed offset.
        londonTimeZone = TimeZone.getTimeZone("GMT");
        // The same applies to "America/New York" time zone ...
        newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
        // ... and for the "Australia/Sydney" time zone.
        sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
    }

    @Test
    public void testDateFormatting() throws Exception {
        int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
        Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
        londonCalendar.setTime(now);

        int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
        newYorkCalendar.setTime(now);

        int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
        sydneyCalendar.setTime(now);

        // Check each time zone offset.
        assertThat(londonOffset, equalTo(0));
        assertThat(newYorkOffset, equalTo(-5));
        assertThat(sydneyOffset, equalTo(10));

        // Check that calendars are not equals (due to time zone difference).
        assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
        assertThat(londonCalendar, not(equalTo(sydneyCalendar)));

        // Check if they all point to the same moment in time, in milliseconds.
        assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));

        // Check if they all point to the same moment in time, as Date.
        assertThat(londonCalendar.getTime(), equalTo(now));
        assertThat(newYorkCalendar.getTime(), equalTo(now));
        assertThat(sydneyCalendar.getTime(), equalTo(now));

        // Check if hours are all different (skip local time because
        // this test could be executed in those exact time zones).
        assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
        assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));


        // Display London time in multiple forms.
        SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + londonOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfLondonNoTZ.format(londonCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfLondonWithTZ.format(londonCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + londonCalendar.getTime() + " / " + londonCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
                + " / " + createDateFormat().format(londonCalendar.getTime()));


        // Display New York time in multiple forms.
        SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + newYorkOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
                + " / " + createDateFormat().format(newYorkCalendar.getTime()));


        // Display Sydney time in multiple forms.
        SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
        SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
        System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + sydneyOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfSydneyNoTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfSydneyWithTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
                + " / " + createDateFormat().format(sydneyCalendar.getTime()));
    }

    @Test
    public void testDateParsing() throws Exception {
        // Create date parsers that look for time zone information in a date-time string.
        final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);

        // Create date parsers that ignore time zone information in a date-time string.
        final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);

        // We are looking for the moment this millenium started, the famous Y2K,
        // when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
        // Which of these is the right one?
        // a) "2000-01-01T00:00:00.000-00:00"
        // b) "2000-01-01T00:00:00.000-05:00"
        // c) "2000-01-01T00:00:00.000+10:00"
        // None of them? All of them?
        // For those who guessed it - yes, it is a trick question because we didn't specify
        // the "where" part, or what kind of time (local/global) we are looking for.
        // The first (a) is the local Y2K moment in London, which is at the same time global.
        // The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
        // The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
        // The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
        // The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.

        // These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
        final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
        final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);

        // Check if they all point to the same moment in time.
        // And that parser ignores its own configured time zone and uses the information from the date-time string.
        assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
        assertThat(milleniumInSydney, equalTo(milleniumInLondon));


        // These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
        final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
        final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
        final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
        final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
        final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
        final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
        assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // These are also local Y2K moments, just withouth the time zone information.
        final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
        final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);

        // Check if these are the same as the local moments with time zone information.
        assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
        assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
        assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
        assertThat(midnightInSydney, not(equalTo(midnightInLondon)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // Final check - if Y2K moment is in London ..
        final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
        // .. New York local time would be still 5 hours in 1999 ..
        final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
        // .. and Sydney local time would be 10 hours in 2000.
        final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";

        final String londonTime = londonFormatTZ.format(milleniumInLondon);
        final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
        final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);

        // WHat do you think, will the test pass?
        assertThat(londonTime, equalTo(Y2K_LONDON));
        assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
        assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
    }
}

SQL query to find third highest salary in company

I found a very good explanation in

http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/

This query should give nth highest salary

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
    SELECT COUNT(DISTINCT(Emp2.Salary))
    FROM Employee Emp2
    WHERE Emp2.Salary > Emp1.Salary)

Find a line in a file and remove it

This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.

File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = "bbb";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close(); 
reader.close(); 
boolean successful = tempFile.renameTo(inputFile);

Java 8: Difference between two LocalDateTime in multiple units

Joda-Time

Since many of the answers required API 26 support and my min API was 23, I solved it by below code :

import org.joda.time.Days

LocalDate startDate = Something
LocalDate endDate = Something
// The difference would be exclusive of both dates, 
// so in most of use cases we may need to increment it by 1
Days.daysBetween(startDate, endDate).days

Laravel check if collection is empty

I prefer

(!$mentor)

Is more effective and accurate

How do I get the value of text input field using JavaScript?

One can use the form.elements to get all elements in a form. If an element has id it can be found with .namedItem("id"). Example:

var myForm = document.getElementById("form1");
var text = myForm.elements.namedItem("searchTxt").value;
var url = "http://www.myurl.com/search/" + text;

Source: w3schools

Why can't C# interfaces contain fields?

Others have given the 'Why', so I'll just add that your interface can define a Control; if you wrap it in a property:

public interface IView {
    Control Year { get; }
}


public Form : IView {
    public Control Year { get { return uxYear; } } //numeric text box or whatever
}

cURL POST command line on WINDOWS RESTful service

Alternative solution: A More Userfriendly solution than command line:

If you are looking for a user friendly way to send and request data using HTTP Methods other than simple GET's probably you are looking for a chrome extention just like this one http://goo.gl/rVW22f called AVANCED REST CLIENT

For guys looking to stay with command-line i recommend cygwin:

I ended up installing cygwin with CURL which allow us to Get that Linux feeling - on Windows!

Using Cygwin command line this issues have stopped and most important, the request syntax used on 1. worked fine.

Useful links:

Where i was downloading the curl for windows command line?

For more information on how to install and get curl working with cygwin just go here

I hope it helps someone because i spent all morning on this.

How to remove components created with Angular-CLI

This is the NPM known Issue for windows that NPM is pretty much unusable under Windows. This is of course related to the path size limitations.

https://github.com/npm/npm/issues/5641

My main concern here is that there are no mention of these issues when installing node or npm via the website. Not being able to install prime packages makes npm fundamentally unusable for windows.

Purpose of ESI & EDI registers?

There are a few operations you can only do with DI/SI (or their extended counterparts, if you didn't learn ASM in 1985). Among these are

REP STOSB
REP MOVSB
REP SCASB

Which are, respectively, operations for repeated (= mass) storing, loading and scanning. What you do is you set up SI and/or DI to point at one or both operands, perhaps put a count in CX and then let 'er rip. These are operations that work on a bunch of bytes at a time, and they kind of put the CPU in automatic. Because you're not explicitly coding loops, they do their thing more efficiently (usually) than a hand-coded loop.

Just in case you're wondering: Depending on how you set the operation up, repeated storing can be something simple like punching the value 0 into a large contiguous block of memory; MOVSB is used, I think, to copy data from one buffer (well, any bunch of bytes) to another; and SCASB is used to look for a byte that matches some search criterion (I'm not sure if it's only searching on equality, or what – you can look it up :) )

That's most of what those regs are for.

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

how to set the query timeout from SQL connection string

You can only set the connection timeout on the connection string, the timeout for your query would normally be on the command timeout. (Assuming we are talking .net here, I can't really tell from your question).

However the command timeout has no effect when the command is executed against a context connection (a SqlConnection opened with "context connection=true" in the connection string).

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

How to filter by string in JSONPath?

Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.

The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:

e.g., given:

{
    "store":
    {
        "book":
        [ 
            { "category": "reference",
              "author": "Nigel Rees",
              "title": "Sayings of the Century",
              "price": 8.95
            },
            { "category": "fiction",
              "author": "Evelyn Waugh",
              "title": "Sword of Honour",
              "price": 12.99
            },
            { "category": "fiction",
              "author": "Herman Melville",
              "title": "Moby Dick",
              "isbn": "0-553-21311-3",
              "price": 8.99
            },
            { "category": "fiction",
              "author": "J. R. R. Tolkien",
              "title": "The Lord of the Rings",
              "isbn": "0-395-19395-8",
              "price": 22.99
            }
        ],
        "bicycle":
        {
            "color": "red",
            "price": 19.95
        }
    }
}

And the expression: $.store.book[?(@.length-1)].title, the tool returns a list of all titles.

How to write an ArrayList of Strings into a text file?

I would suggest using FileUtils from Apache Commons IO library.It will create the parent folders of the output file,if they don't exist.while Files.write(out,arrayList,Charset.defaultCharset()); will not do this,throwing exception if the parent directories don't exist.

FileUtils.writeLines(new File("output.txt"), encoding, list);

enable or disable checkbox in html

The HTML parser simply doesn't interpret the inlined javascript like this.

You may do this :

<td><input type="checkbox" id="repriseCheckBox" name="repriseCheckBox"/></td>

<script>document.getElementById("repriseCheckBox").disabled=checkStat == 1 ? true : false;</script>

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

Rails: How can I set default values in ActiveRecord?

We put the default values in the database through migrations (by specifying the :default option on each column definition) and let Active Record use these values to set the default for each attribute.

IMHO, this approach is aligned with the principles of AR : convention over configuration, DRY, the table definition drives the model, not the other way around.

Note that the defaults are still in the application (Ruby) code, though not in the model but in the migration(s).

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

On Debian (Wheezy, 7.8) with MySQL 5.5.40, I found SELECT * FROM mysql.user WHERE User='root'\G showed the Event_priv and 'Trigger_priv` fields were present but not set to Y.

Running mysql_upgrade (with or without --force) made no difference; I needed to do a manual:

update user set Event_priv = 'Y',Trigger_priv = 'Y' where user = 'root'

Then finally I could use:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION

…and then use it more precisely on an individual database/user account.

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

Regex empty string or email

Don't match an email with a regex. It's extremely ugly and long and complicated and your regex parser probably can't handle it anyway. Try to find a library routine for matching them. If you only want to solve the practical problem of matching an email address (that is, if you want wrong code that happens to (usually) work), use the regular-expressions.info link someone else submitted.

As for the empty string, ^$ is mentioned by multiple people and will work fine.

How to convert current date to epoch timestamp?

Use strptime to parse the time, and call time() on it to get the Unix timestamp.

How can I specify the required Node.js version in package.json?

A Mocha test case example:

describe('Check version of node', function () {
    it('Should test version assert', async function () {

            var version = process.version;
            var check = parseFloat(version.substr(1,version.length)) > 12.0;
            console.log("version: "+version);
            console.log("check: " +check);         
            assert.equal(check, true);
    });});

How to include js file in another js file?

You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:

var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);

There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // script is now loaded and executed.
    // put your dependent JS here.
});

How do I make a transparent canvas in html5?

Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:

#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas

I'm not sure but it looks like that the background-color is inherited as transparent from the body.

Can't bind to 'formGroup' since it isn't a known property of 'form'

A LITTLE NOTE: Be careful about loaders and minimize (Rails env.):

After seeing this error and trying every solution out there, i realised there was something wrong with my html loader.

I've set my Rails environment up to import HTML paths for my components successfully with this loader (config/loaders/html.js.):

module.exports = {
  test: /\.html$/,
  use: [ {
    loader: 'html-loader?exportAsEs6Default',
    options: {
      minimize: true
    }
  }]
}

After some hours efforts and countless of ReactiveFormsModule imports i saw that my formGroup was small letters: formgroup.

This led me to the loader and the fact that it downcased my HTML on minimize.

After changing the options, everything worked as it should, and i could go back to crying again.

I know that this is not an answer to the question, but for future Rails visitors (and other with custom loaders) i think this could be helpfull.

Retrofit 2.0 how to get deserialised error response.body

In Kotlin:

val call = APIClient.getInstance().signIn(AuthRequestWrapper(AuthRequest("1234567890z", "12341234", "nonce")))
call.enqueue(object : Callback<AuthResponse> {
    override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
        if (response.isSuccessful) {

        } else {
            val a = object : Annotation{}
            val errorConverter = RentalGeekClient.getRetrofitInstance().responseBodyConverter<AuthFailureResponse>(AuthFailureResponse::class.java, arrayOf(a))
            val authFailureResponse = errorConverter.convert(response.errorBody())
        }
    }

    override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
    }
})

How do I concatenate text in a query in sql server?

If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

When should I use Kruskal as opposed to Prim (and vice versa)?

Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).

Retrieve a Fragment from a ViewPager

Easy way to iterate over fragments in fragment manager. Find viewpager, that has section position argument, placed in public static PlaceholderFragment newInstance(int sectionNumber).

public PlaceholderFragment getFragmentByPosition(Integer pos){
    for(Fragment f:getChildFragmentManager().getFragments()){
        if(f.getId()==R.id.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
            return (PlaceholderFragment) f;
        }
    }
    return null;
}

How to get annotations of a member variable?

You can get annotations on the getter method:

propertyDescriptor.getReadMethod().getDeclaredAnnotations();

Getting the annotations of a private field seems like a bad idea... what if the property isn't even backed by a field, or is backed by a field with a different name? Even ignoring those cases, you're breaking abstraction by looking at private stuff.

Hibernate dialect for Oracle Database 11g?

We had a problem with the (deprecated) dialect org.hibernate.dialect.Oracledialect and Oracle 11g database using hibernate.hbm2ddl.auto = validate mode.

With this dialect Hibernate was unable to found the sequences (because the implementation of the getQuerySequencesString() method, that returns this query:

"select sequence_name from user_sequences;"

for which the execution returns an empty result from database).

Using the dialect org.hibernate.dialect.Oracle9iDialect , or greater, solves the problem, due to a different implementation of getQuerySequencesString() method:

"select sequence_name from all_sequences union select synonym_name from all_synonyms us, all_sequences asq where asq.sequence_name = us.table_name and asq.sequence_owner = us.table_owner;"

that returns all the sequences if executed, instead.

How to sort in-place using the merge sort algorithm?

It really isn't easy or efficient, and I suggest you don't do it unless you really have to (and you probably don't have to unless this is homework since the applications of inplace merging are mostly theoretical). Can't you use quicksort instead? Quicksort will be faster anyway with a few simpler optimizations and its extra memory is O(log N).

Anyway, if you must do it then you must. Here's what I found: one and two. I'm not familiar with the inplace merge sort, but it seems like the basic idea is to use rotations to facilitate merging two arrays without using extra memory.

Note that this is slower even than the classic merge sort that's not inplace.

Scala list concatenation, ::: vs ++

A different point is that the first sentence is parsed as:

scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)

Whereas the second example is parsed as:

scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)

So if you are using macros, you should take care.

Besides, ++ for two lists is calling ::: but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.

Micro-Benchmarks after warming up.

scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100

scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46

As Daniel C. Sobrai said, you can append the content of any collection to a list using ++, whereas with ::: you can only concatenate lists.

Remove all whitespace from C# string with regex

No need for regex. This will also remove tabs, newlines etc

var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));

WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000.

Do I commit the package-lock.json file created by npm 5?

Yes, package-lock.json is intended to be checked into source control. If you're using npm 5+, you may see this notice on the command line: created a lockfile as package-lock.json. You should commit this file. According to npm help package-lock.json:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

This file is intended to be committed into source repositories, and serves various purposes:

  • Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.

  • Provide a facility for users to "time-travel" to previous states of node_modules without having to commit the directory itself.

  • To facilitate greater visibility of tree changes through readable source control diffs.

  • And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages.

One key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the toplevel package. It shares a format with npm-shrinkwrap.json, which is essentially the same file, but allows publication. This is not recommended unless deploying a CLI tool or otherwise using the publication process for producing production packages.

If both package-lock.json and npm-shrinkwrap.json are present in the root of a package, package-lock.json will be completely ignored.

Spring: How to get parameters from POST body?

You can get param from request.

@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
            HttpServletResponse response, Model model){
   String jsonString = request.getParameter("json");
}

Inner text shadow with CSS

Here's my best try:

_x000D_
_x000D_
    .inner_shadow {_x000D_
    color:transparent;_x000D_
    background-color:white;_x000D_
    text-shadow: 0 0 20px rgba(198,28,39,0.8), 0 0 0 black;_x000D_
    font-family:'ProclamateHeavy';  // Or whatever floats your boat_x000D_
    font-size:150px;_x000D_
    }
_x000D_
   _x000D_
    <span class="inner_shadow">Inner Shadow</span>_x000D_
   
_x000D_
_x000D_
_x000D_

The problem is how to clip the shadow that bleeds around the edges!!! I tried in webkit using background-clip:text, but webkit renders the shadow above the background so it doesn't work.

Making a Text Mask with CSS?

Without a top mask layer it is impossible to do a true inner shadow on text.

Perhaps someone should recommend that the W3C add background-clip: reverse-text, that would cut a mask through the background instead of cutting the background to fit inside the text.

Either that or render the text-shadow as part of the background and clip it with background-clip: text.

I tried absolutely positioning an identical text element above it, but the problem is background-clip: text crops the background to fit inside the text, but we need the reverse of that.

I tried using text-stroke: 20px white; on both this element and the one above it, but the text stroke goes in as well as out.

Alternate Methods

Since there is currently no way to make an inverted-text mask in CSS, you could turn to SVG or Canvas and make a text replacement image with the three layers to get your effect.

Since SVG is a subset of XML, SVG text would still be select-able and searchable, and the effect can be produced with less code than Canvas.

It would be harder to achieve this with Canvas because it doesn't have a dom with layers like SVG does.

You could produce the SVG either server-side, or as a javascript text-replacement method in the browser.

Further Reading:

SVG versus Canvas:

http://dev.opera.com/articles/view/svg-or-canvas-choosing-between-the-two/

Clipping and Masking with SVG Text:

http://www.w3.org/TR/SVG/text.html#TextElement

Cannot find the '@angular/common/http' module

Beware of auto imports. my HTTP_INTERCEPTORS was auto imported like this:

import { HTTP_INTERCEPTORS } from '@angular/common/http/src/interceptor';

instead of

import { HTTP_INTERCEPTORS } from '@angular/common/http';

which caused this error

What is the best way to update the entity in JPA

Using executeUpdate() on the Query API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.

Consider the following example :

 Employee employee= (Employee)entityManager.find(Employee.class , 1);
 entityManager
     .createQuery("update Employee set name = \'xxxx\' where id=1")
     .executeUpdate();

After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee) to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.

Normally , executeUpdate() is used in the bulk update process as it is faster due to bypassing the persistent context

The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.

   Employee employee= (Employee)entityManager.find(Employee.class ,1);
   employee.setName("Updated Name");

What Java FTP client library should I use?

Apache commons-nets get updates more frequently recently, while Enterprise DT library seems to update even more frequently.

How to search if dictionary value contains certain string with Python

You can do it like this:

#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
      'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(values, searchFor):
    for k in values:
        for v in values[k]:
            if searchFor in v:
                return k
    return None

#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName

Python write line by line to a text file

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)

In Angular, how do you determine the active route?

let's say you want to add CSS to my active state/tab. Use routerLinkActive to activate your routing link.

note : 'active' is my class name here

<style>
   .active{
       color:blue;
     }
</style>

  <a routerLink="/home" [routerLinkActive]="['active']">Home</a>
  <a routerLink="/about" [routerLinkActive]="['active']">About</a>
  <a routerLink="/contact" [routerLinkActive]="['active']">Contact</a>

Split string into individual words Java

A regex can also be used to split words.

\w can be used to match word characters ([A-Za-z0-9_]), so that punctuation is removed from the results:

String s = "I want to walk my dog, and why not?";
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Outputs:

I
want
to
walk
my
dog
and
why
not

See Java API documentation for Pattern

Using StringWriter for XML Serialization

When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.

SQL Server works on a similar principle; any string passed into an xml column must be encoded as UTF-16. SQL Server will reject any string where the XML declaration does not specify UTF-16. If the XML declaration is not present, then the XML standard requires that it default to UTF-8, so SQL Server will reject that as well.

Bearing this in mind, here are some utility methods for doing the conversion.

public static string Serialize<T>(T value) {

    if(value == null) {
        return null;
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new UnicodeEncoding(false, false), // no BOM in a .NET string
        Indent = false,
        OmitXmlDeclaration = false
    };

    using(StringWriter textWriter = new StringWriter()) {
        using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
            serializer.Serialize(xmlWriter, value);
        }
        return textWriter.ToString();
    }
}

public static T Deserialize<T>(string xml) {

    if(string.IsNullOrEmpty(xml)) {
        return default(T);
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlReaderSettings settings = new XmlReaderSettings();
    // No settings need modifying here

    using(StringReader textReader = new StringReader(xml)) {
        using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
            return (T) serializer.Deserialize(xmlReader);
        }
    }
}

How do you check if a variable is an array in JavaScript?

You could also use:

if (value instanceof Array) {
  alert('value is Array!');
} else {
  alert('Not an array');
}

This seems to me a pretty elegant solution, but to each his own.

Edit:

As of ES5 there is now also:

Array.isArray(value);

But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).

convert double to int

Yeah, why not?

double someDouble = 12323.2;
int someInt = (int)someDouble;

Using the Convert class works well too.

int someOtherInt = Convert.ToInt32(someDouble);

How to make a JFrame button open another JFrame class in Netbeans?

Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)

btnLogin.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) {
        this.setVisible(false);
        new FrmMain().setVisible(true); // Main Form to show after the Login Form..
    }
});

FFmpeg: How to split video efficiently?

one simple way is to use trim option with publitio url-based api.

once you get your video uploaded, just set start offset and end offset in url (so_2,eo_2) like so:

    https://media.publit.io/file/so_2,eo_2/tummy.mp4

this will create instantly new videos starting from 2nd second and 2 seconds in length. you can split videos this way anyway you like.

Import JSON file in React

With json-loader installed, you can use

import customData from '../customData.json';

or also, even more simply

import customData from '../customData';

To install json-loader

npm install --save-dev json-loader

How can I count the number of matches for a regex?

This should work for matches that might overlap:

public static void main(String[] args) {
    String input = "aaaaaaaa";
    String regex = "aa";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    int from = 0;
    int count = 0;
    while(matcher.find(from)) {
        count++;
        from = matcher.start() + 1;
    }
    System.out.println(count);
}

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

You are on share environment and cannot find error log, always check if cPanel has option Errors on your cPanel dashboard. If you are not being able to find error log, then you can find it there .

On cPanel search bar, search Error, it will show Error Pages which are basically lists of different http error pages and other Error is where the error logs are displayed.

Other places to look on shared environment: /home/yourusername/logs /home/yourusername/public_html/error_log

How to align text below an image in CSS?

Instead of images i choose background option:

HTML:

  <div class="class1">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>    
  <div class="class2">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>
  <div class="class3">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>        

CSS:

  .class1 {

    background: url("Some.png") no-repeat top center;
    text-align: center;

   }

  .class2 {

    background: url("Some2.png") no-repeat top center;
    text-align: center;

   }

  .class3 {

    background: url("Some3.png") no-repeat top center;
    text-align: center;

   }

Why use def main()?

Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.

How to add a "confirm delete" option in ASP.Net Gridview?

This is my method and it works perfectly.

asp

 <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="5%" HeaderStyle-Width="5%" HeaderStyle-CssClass="color" HeaderText="Edit"
                                EditText="<span style='font-size: 20px; color: #27ae60;'><span class='glyphicons glyph-edit'></span></span>"
                                DeleteText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-bin'></span></span>"
                                CancelText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-remove-2'></span></span>" 
                                UpdateText="<span style='font-size: 20px; color: #2980b9;'><span class='glyphicons glyph-floppy-saved'></span></span>" />

C# (replace 5 with the column number of the button)

        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {

        }
        else {
            ((LinkButton)e.Row.Cells[5].Controls[2]).OnClientClick = "return confirm('Do you really want to delete?');";

        }

How to fix: Error device not found with ADB.exe

On my G2 I had to select PTP instead of MTP mode to get the connection to work.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

In my weird scenario, I had a different column that didn't always return a value in the 'render' function. return null solved my issue.

Creating a new user and password with Ansible

Neither of the solutions worked directly on my Mac controlling Ubuntu. So for others' sake, combining Mxx and JoelB answers, here is the current Python 3 solution:

pip3 install passlib

python3 -c 'from passlib.hash import md5_crypt; \
      print(md5_crypt.encrypt("This is my Password", salt="SomeSalt"))'

The result will be $1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI., as in Mxx' answer.

Better still, use SHA512 instead of MD5:

python3 -c 'from passlib.hash import sha512_crypt; \
      print(sha512_crypt.encrypt("This is my Password", salt="SomeSalt"))' 

Result:

$6$rounds=656000$SomeSalt$oYpmnpZahIsvn5FK8g4bDFEAmGpEN114Fe6Ko4HvinzFaz5Rq2UXQxoJZ9ZQyQoi9zaBo3gBH/FEAov3FHv48

TypeError: 'dict' object is not callable

The syntax for accessing a dict given a key is number_map[int(x)]. number_map(int(x)) would actually be a function call but since number_map is not a callable, an exception is raised.

Angular 2 : No NgModule metadata found

I finally found the solution.

  1. Remove webpack by using following command.
npm remove webpack
  1. Install cli by using following command.
npm install --save-dev @angular/cli@latest

after successfully test app, it will work :)

If not then follow below steps:

  1. Delete node_module folder.
  2. Clear cache by using following command.
npm cache clean --force
  1. Install node packages by using following command.
npm install
  1. Install angular@cli by using following command.
npm install --save-dev @angular/cli@latest

Note: If failed, try step 4 again. It will work.

Private Variables and Methods in Python

Because thats coding convention. See here for more.

Mongoose, update values in array of objects

There is a mongoose way for doing it.

const itemId = 2;
const query = {
  item._id: itemId 
};
Person.findOne(query).then(doc => {
  item = doc.items.id(itemId );
  item["name"] = "new name";
  item["value"] = "new value";
  doc.save();

  //sent respnse to client
}).catch(err => {
  console.log('Oh! Dark')
});

How many bits is a "word"?

I'm not familiar with either of these books, but the second is closer to current reality. The first may be discussing a specific processor.

Processors have been made with quite a variety of word sizes, not always a multiple of 8.

The 8086 and 8087 processors used 16 bit words, and it's likely this is the machine the first author was writing about.

More recent processors commonly use 32 or 64 bit words.

In the 50's and 60's there were machines with words sizes that seem quite strange to us now, such as 4, 9 and 36. Since about the 70's word size has commonly been a power of 2 and a multiple of 8.

Apache and Node.js on the Same Server

ProxyPass /node http://localhost:8000/     
  • this worked for me when I made above entry in httpd-vhosts.conf instead of httpd.conf
  • I have XAMPP installed over my environment & was looking to hit all the traffic at apache on port 80 with NodeJS applicatin running on 8080 port i.e. http://localhost/[name_of_the_node_application]

Android SDK location

The default location for Android sdk(s) on a Mac is:

/Users/*username*/Library/Android/sdk

Jquery asp.net Button Click Event via ajax

In the client side handle the click event of the button, use the ClientID property to get he id of the button:

$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(

    function() {
     $.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
       // do something with the data
     return false;
     }
    });
 });

In your page on the server:

protected void Page_Load(object sender,EventArgs e) {
 // check if it is an ajax request
 if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
  if (Request.QueryString["id"]==myButton.ClientID) {
    // call the click event handler of the myButton here
    Response.End();
  }
  if (Request.QueryString["id"]==mySecondButton.ClientID) {
    // call the click event handler of the mySecondButton here
    Response.End();
  }
 }
}

How to control size of list-style-type disc in CSS?

Since I don't know how to control only the list marker size with CSS and no one's offered this yet, you can use :before content to generate the bullets:

li {
    list-style: none;
    font-size: 20px;
}

li:before {
    content:"·";
    font-size:120px;
    vertical-align:middle;
    line-height:20px;
}

Demo: http://jsfiddle.net/4wDL5/

The markers are limited to appearing "inside" with this particular CSS, although you could change it. It's definitely not the best option (browser must support generated content, so no IE6 or 7), but it might be the easiest - plus you can choose any character you want for the marker.

If you go the image route, see list-style-image.

Get city name using geolocation

_x000D_
_x000D_
$.ajax({_x000D_
  url: "https://geolocation-db.com/jsonp",_x000D_
  jsonpCallback: "callback",_x000D_
  dataType: "jsonp",_x000D_
  success: function(location) {_x000D_
    $('#country').html(location.country_name);_x000D_
    $('#state').html(location.state);_x000D_
    $('#city').html(location.city);_x000D_
    $('#latitude').html(location.latitude);_x000D_
    $('#longitude').html(location.longitude);_x000D_
    $('#ip').html(location.IPv4);_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div>Country: <span id="country"></span></div>_x000D_
  <div>State: <span id="state"></span></div>_x000D_
    <div>City: <span id="city"></span></div>_x000D_
      <div>Latitude: <span id="latitude"></span></div>_x000D_
        <div>Longitude: <span id="longitude"></span></div>_x000D_
          <div>IP: <span id="ip"></span></div>
_x000D_
_x000D_
_x000D_

Using html5 geolocation requires user permission. In case you don't want this, go for an external locator like https://geolocation-db.com IPv6 is supported. No restrictions and unlimited requests allowed.

Example

For a pure javascript example, without using jQuery, check out this answer.

JavaScript - Get minutes between two dates

This problem is solved easily with moment.js, like this example:

var difference = mostDate.diff(minorDate, "minutes");

The second parameter can be changed for another parameters, see the moment.js documentation.

e.g.: "days", "hours", "minutes", etc.

http://momentjs.com/docs/

The CDN for moment.js is available here:

https://cdnjs.com/libraries/moment.js

Thanks.

EDIT:

mostDate and minorDate should be a moment type.

EDIT 2:

For those who are reading my answer in 2020+, momentjs is now a legacy project.

If you are still looking for a well-known library to do this job, I would recommend date-fns.

// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
  new Date(2014, 6, 2, 12, 20, 0),
  new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

Automatically open Chrome developer tools when new tab/new window is opened

Anyone looking to do this inside Visual Studio, this Code Project article will help. Just add "--auto-open-devtools-for-tabs" in the arguments box. Works on 2017.

bootstrap popover not showing on top of all elements

Many years later, but like me, others may search for this. All updates taking into consideration, all this can be solved with correct initialization options, in JavaScript.

$('.tip').tooltip({
    boundary: 'viewport',
    placement: 'top',
    container:'body',
    sanitize: true,
    appendToBody: true
});

Those settings solved all may issues. I had tooltips flickering, showing corectly only for half of the items on page, jumping from top to left continously, all kinds of wierdness. But with those settings everything is solved. Hope it help anyone looking.

Difference between "while" loop and "do while" loop

do {
    printf("Word length... ");
    scanf("%d", &wdlen);
} while(wdlen<2);

A do-while loop guarantees the execution of the loop at least once because it checks the loop condition AFTER the loop iteration. Therefore it'll print the string and call scanf, thus updating the wdlen variable.

while(wdlen<2){
    printf("Word length... ");
    scanf("%d", &wdlen);
} 

As for the while loop, it evaluates the loop condition BEFORE the loop body is executed. wdlen probably starts off as more than 2 in your code that's why you never reach the loop body.

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You could use THROW (available in SQL Server 2012+):

THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>

MSDN THROW (Transact-SQL)

Differences Between RAISERROR and THROW in Sql Server

What is the use of ByteBuffer in Java?

In Android you can create shared buffer between C++ and Java (with directAlloc method) and manipulate it in both sides.

How to properly override clone method?

Sometimes it's more simple to implement a copy constructor:

public MyObject (MyObject toClone) {
}

It saves you the trouble of handling CloneNotSupportedException, works with final fields and you don't have to worry about the type to return.

jQuery Button.click() event is triggered twice

This can be caused for following reasons:

  1. You have included the script more than once in the same html file
  2. You have added the event listener twice (eg: using onclick attribute on the element and also with jquery
  3. The event is bubbled up to some parent element. (you may consider using event.stopPropagation).
  4. If you use template inheritance like extends in Django, most probably you have included the script in more than one file which are combined together by include or extend template tags
  5. If you are using Django template, you have wrongly placed a block inside another.

So, you should either find them out and remove the duplicate import. It is the best thing to do.

Another solution is to remove all click event listeners first in the script like:

$("#myId").off().on("click", function(event) {
event.stopPropagation();
});

You can skip event.stopPropagation(); if you are sure that the event is not bubbled.

How many parameters are too many?

For me , when the list crosses one line on my IDE, then it's one parameter too many. I want to see all the parameters in one line without breaking eye contact. But that's just my personal preference.

How can I use the python HTMLParser library to extract data from a specific div tag?

class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

self.recording counts the number of nested div tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data.

The data at the end of the parse are left in self.data (a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.

The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div', 'id', and 'remository', instance attributes self.tag, self.attname and self.attvalue, set by __init__ from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).

jQuery select2 get value of select tag?

Try this :

$('#input_id :selected').val(); //for getting value from selected option
$('#input_id :selected').text(); //for getting text from selected option

Which to use <div class="name"> or <div id="name">?

ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...

How do you convert WSDLs to Java classes using Eclipse?

The Eclipse team with The Open University have prepared the following document, which includes creating proxy classes with tests. It might be what you are looking for.

http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf

Everything is included in the Dynamic Web Project template.

In the project create a Web Service Client. This starts a wizard that has you point out a wsdl url and creates the client with tests for you.

The user guide (targeted at indigo though) for this task is found at http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jst.ws.cxf.doc.user%2Ftasks%2Fcreate_client.html.

iterating over each character of a String in ruby 1.8.6 (each_char)

Extending la_f0ka's comment, esp. if you also need the index position in your code, you should be able to do

s = 'ABCDEFG'
for pos in 0...s.length
    puts s[pos].chr
end

The .chr is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.

How can I find script's directory?

Try this:

def get_script_path(for_file = None):
    path = os.path.dirname(os.path.realpath(sys.argv[0] or 'something'))
    return path if not for_file else os.path.join(path, for_file)

Git log to get commits only for a specific branch

I needed to export log in one line for a specific branch.

So I probably came out with a simpler solution.
When doing git log --pretty=oneline --graph we can see that all commit not done in the current branch are lines starting with |

So a simple grep -v do the job:
git log --pretty=oneline --graph | grep -v "^|"

Of course you can change the pretty parameter if you need other info, as soon as you keep it in one line.

You probably want to remove merge commit too.
As the message start with "Merge branch", pipe another grep -v and you're done.

In my specific ase, the final command was:
git log --pretty="%ad : %an, %s" --graph | grep -v "^|" | grep -v "Merge branch"

How to pass a value from Vue data to href?

If you want to display links coming from your state or store in Vue 2.0, you can do like this:

<a v-bind:href="''"> {{ url_link }} </a>

How To limit the number of characters in JTextField?

If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:

public class JTextFieldLimit extends JTextField {
    private int limit;

    public JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }

    @Override
    protected Document createDefaultModel() {
        return new LimitDocument();
    }

    private class LimitDocument extends PlainDocument {

        @Override
        public void insertString( int offset, String  str, AttributeSet attr ) throws BadLocationException {
            if (str == null) return;

            if ((getLength() + str.length()) <= limit) {
                super.insertString(offset, str, attr);
            }
        }       

    }

}

Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.

What are the differences between LDAP and Active Directory?

Active directory is a directory service provider, where you can add new user to a directory, remove or modify, specify privilages, assign policy etc. Its just like a phone directory where every person have a unique contact number. Every thing in AD(Active Directory) are considered as Objects and every object is given a Unique ID.(similar to a unique contact number in a phone directory.

Ldap is a protocol specially designed for directory service providers. Windows server OS uses AD as a directory server, AIX which is a UNIX version by IBM uses Tivoli directory server. Both of them uses LDAP protocol for interacting with directory.

Apart from protocol there are LDAP servers, LDAP browsers too.

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

css width: calc(100% -100px); alternative using jquery

If you want to use calc in your CSS file use a polyfill like PolyCalc. Should be light enough to work on mobile browsers (e.g. below iOS 6 and below Android 4.4 phones).

jQuery to loop through elements with the same class

You could use the jQuery $each method to loop through all the elements with class testimonial. i => is the index of the element in collection and val gives you the object of that particular element and you can use "val" to further access the properties of your element and check your condition.

$.each($('.testimonal'), function(i, val) { 
    if(your condition){
       //your action
    }
});

Running Facebook application on localhost

You can also edit 'hosts' file and create local variation of your domain.

Example

If your real facebook application address is "example.com" you can create "localhost.example.com" (accessible only from your pc) domain in your "hosts" file pointing to "localhost" and run your local website under this domain. You can trick Facebook this way.

How do I correctly upgrade angular 2 (npm) to the latest version?

UPDATE:
Starting from CLI v6 you can just run ng update in order to get your dependencies updated automatically to a new version.

With ng update sometimes you might want to add --force flag. If you do so make sure that the version of typescript you got installed this way is supported by your current angular version, otherwise you might need to downgrade the typescript version.

Also checkout this guide Updating your Angular projects


For bash users only

If you are on are on Mac/Linux or running bash on Windows(that wont work in default Windows CMD) you can run that oneliner:

npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5 --save

yarn add @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5

Just specify version you wan't e.g @4.4.5 or put @latest to get the latest

Check your package.json just to make sure you are updating all @angular/* packages that you app is relying on

  • To see exact @angular version in your project run:
    npm ls @angular/compiler or yarn list @angular/compiler
  • To check the latest stable @angular version available on npm run:
    npm show @angular/compiler version

Can I force a page break in HTML printing?

Just wanted to put an update. page-break-after is a legacy property now.

Official page states

This property has been replaced by the break-after property.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

SWT by itself is pretty low-level, and it uses the platform's native widgets through JNI. It is not related to Swing and AWT at all. The Eclipse IDE and all Eclipse-based Rich Client Applications, like the Vuze BitTorrent client, are built using SWT. Also, if you are developing Eclipse plugins, you will typically use SWT.
I have been developing Eclipse-based applications and plugins for almost 5 years now, so I'm clearly biased. However, I also have extensive experience in working with SWT and the JFace UI toolkit, which is built on top of it. I have found JFace to be very rich and powerful; in some cases it might even be the main reason for choosing SWT. It enables you to whip up a working UI quite quickly, as long as it is IDE-like (with tables, trees, native controls, etc). Of course you can integrate your custom controls as well, but that takes some extra effort.

Get screenshot on Windows with Python?

If you want to snap particular running Windows app you’ll have to acquire a handle by looping over all open windows in your system.

It’s easier if you can open this app from Python script. Then you can convert process pid into window handle.

Another challenge is to snap the app that runs in particular monitor. I have 3 monitor system and I had to figure out how to snap display 2 and 3.

This example will take multiple application snapshots and save them into JPEG files.

import wx

print(wx.version())
app=wx.App()  # Need to create an App instance before doing anything
dc=wx.Display.GetCount()
print(dc)
#e(0)
displays = (wx.Display(i) for i in range(wx.Display.GetCount()))
sizes = [display.GetGeometry().GetSize() for display in displays]

for (i,s) in enumerate(sizes):
    print("Monitor{} size is {}".format(i,s))   
screen = wx.ScreenDC()
#pprint(dir(screen))
size = screen.GetSize()

print("Width = {}".format(size[0]))
print("Heigh = {}".format(size[1]))

width=size[0]
height=size[1]
x,y,w,h =putty_rect

bmp = wx.Bitmap(w,h)
mem = wx.MemoryDC(bmp)

for i in range(98):
    if 1:
        #1-st display:

        #pprint(putty_rect)
        #e(0)

        mem.Blit(-x,-y,w+x,h+y, screen, 0,0)

    if 0:
        #2-nd display:
        mem.Blit(0, 0, x,y, screen, width,0)
    #e(0)

    if 0:
        #3-rd display:
        mem.Blit(0, 0, width, height, screen, width*2,0)

    bmp.SaveFile(os.path.join(home,"image_%s.jpg" % i), wx.BITMAP_TYPE_JPEG)    
    print (i)
    sleep(0.2)
del mem

Details are here

How to do multiple arguments to map function where one remains the same in python?

def func(a, b, c, d):
 return a + b * c % d
map(lambda x: func(*x), [[1,2,3,4], [5,6,7,8]])

By wrapping the function call with a lambda and using the star unpack, you can do map with arbitrary number of arguments.

Cannot use object of type stdClass as array?

Have same problem today, solved like this:

If you call json_decode($somestring) you will get an Object and you need to access like $object->key , but if u call json_decode($somestring, true) you will get an dictionary and can access like $array['key']

How to change Label Value using javascript

very simple

$('#label-ID').text("label value which you want to set");

If hasClass then addClass to parent

Alternatively you could use:

if ($('#navigation a').is(".active")) {
    $(this).parent().addClass("active");
}

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

GitLab remote: HTTP Basic: Access denied and fatal Authentication

Create a new access token from gitlab ->setting --> access token

How I can check whether a page is loaded completely or not in web driver?

You can take a screenshot and save the rendered page in a location and you can check the screenshot if the page loaded completely without broken images

PostgreSQL: role is not permitted to log in

The role you have created is not allowed to log in. You have to give the role permission to log in.

One way to do this is to log in as the postgres user and update the role:

psql -U postgres

Once you are logged in, type:

ALTER ROLE "asunotest" WITH LOGIN;

Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

How to open spss data files in excel?

You can do it via ODBC. The steps to do it:

  1. Install IBM SPSS Statistics Data File Driver. Standalone Driver is enough.
  2. Create DNS via ODBC manager.
  3. Use the data importer in Excel via ODBC by selecting created DNS.

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

The foo.bar reference should not contain the braces:

<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>

Angular expressions need to be within the curly-brace bindings, where as Angular directives do not.

See also Understanding Angular Templates.

Only variables should be passed by reference

save the array from explode() to a variable, and then call end() on this variable:

$tmp = explode('.', $file_name);
$file_extension = end($tmp);

btw: I use this code to get the file extension:

$ext = substr( strrchr($file_name, '.'), 1);

where strrchr extracts the string after the last . and substr cuts off the .

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

change the date format in laravel view page

I suggest using isoFormat for better appearance on the web pages.

{{ \Carbon\Carbon::parse($blog->created_at)->isoFormat('MMM Do YYYY')}}

The result is

Jan 21st 2021

Carbon Extension

How do I look inside a Python object?

pprint and dir together work great

Dynamically create Bootstrap alerts box through JavaScript

Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.

In html:

<div id="form_errors" class="alert alert-danger fade in" style="display:none">

In JS:

<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
function bootstrap_alert(elem, message, timeout) {
  $(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');

  if (timeout || timeout === 0) {
    setTimeout(function() { 
      $(elem).alert('close');
    }, timeout);    
  }
};
</script>?

Then you can invoke this either as:

bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')

Double % formatting question for printf in Java

Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

System.out.printf("%s \r\n",String.valueOf(d));

or

System.out.printf("%s \r\n",Double.toString(d));

This is what println do by default:

System.out.println(d) 

(and terminates the line)

Sample settings.xml

A standard Maven settings.xml file is as follows:

<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>

  <proxies>
    <proxy>
      <active/>
      <protocol/>
      <username/>
      <password/>
      <port/>
      <host/>
      <nonProxyHosts/>
      <id/>
    </proxy>
  </proxies>

  <servers>
    <server>
      <username/>
      <password/>
      <privateKey/>
      <passphrase/>
      <filePermissions/>
      <directoryPermissions/>
      <configuration/>
      <id/>
    </server>
  </servers>

  <mirrors>
    <mirror>
      <mirrorOf/>
      <name/>
      <url/>
      <layout/>
      <mirrorOfLayouts/>
      <id/>
    </mirror>
  </mirrors>

  <profiles>
    <profile>
      <activation>
        <activeByDefault/>
        <jdk/>
        <os>
          <name/>
          <family/>
          <arch/>
          <version/>
        </os>
        <property>
          <name/>
          <value/>
        </property>
        <file>
          <missing/>
          <exists/>
        </file>
      </activation>
      <properties>
        <key>value</key>
      </properties>

      <repositories>
        <repository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </pluginRepository>
      </pluginRepositories>
      <id/>
    </profile>
  </profiles>

  <activeProfiles/>
  <pluginGroups/>
</settings>

To access a proxy, you can find detailed information on the official Maven page here:

Maven-Settings - Settings

I hope it helps for someone.

How to find when a web page was last updated

No, you cannot know when a page was last updated or last changed or uploaded to a server (which might, depending on interpretation, be three different things) just by accessing the page.

A server may, and should (according to the HTTP 1.1 protocol), send a Last-Modified header, which you can find out in several ways, e.g. using Rex Swain’s HTTP Viewer. However, according to the protocol, this is just

“the date and time at which the origin server believes the variant was last modified”.

And the protocol realistically adds:

“The exact meaning of this header field depends on the implementation of the origin server and the nature of the original resource. For files, it may be just the file system last-modified time. For entities with dynamically included parts, it may be the most recent of the set of last-modify times for its component parts. For database gateways, it may be the last-update time stamp of the record. For virtual objects, it may be the last time the internal state changed.”

In practice, web pages are very often dynamically created from a Content Management System or otherwise, and in such cases, the Last-Modified header typically shows a data stamp of creating the response, which is normally very close to the time of the request. This means that the header is practically useless in such cases.

Even in the case of a “static” page (the server simply picks up a file matching the request and sends it), the Last-Modified date stamp normally indicates just the last write access to the file on the server. This might relate to a time when the file was restored from a backup copy, or a time when the file was edited on the server without making any change to the content, or a time when it was uploaded onto the server, possibly replacing an older identical copy. In these cases, assuming that the time stamp is technically correct, it indicates a time after which the page has not been changed (but not necessarily the time of last change).

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

Annotation based approach is better. But sometimes manual operation is needed. For this purpose you can use without method of ObjectWriter.

ObjectMapper mapper   = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
ObjectWriter writer   = mapper.writer().withoutAttribute("property1").withoutAttribute("property2");
String       jsonText = writer.writeValueAsString(sourceObject);

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

You mention the certificate is self-signed (by you)? Then you have two choices:

  • add the certificate to your trust store (fetching cacert.pem from cURL website won't do anything, since it's self-signed)
  • don't bother verifying the certificate: you trust yourself, don't you?

Here's a list of SSL context options in PHP: https://secure.php.net/manual/en/context.ssl.php

Set allow_self_signed if you import your certificate into your trust store, or set verify_peer to false to skip verification.

The reason why we trust a specific certificate is because we trust its issuer. Since your certificate is self-signed, no client will trust the certificate as the signer (you) is not trusted. If you created your own CA when signing the certificate, you can add the CA to your trust store. If your certificate doesn't contain any CA, then you can't expect anyone to connect to your server.

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Select a random sample of results from a query result

The SAMPLE clause will give you a random sample percentage of all rows in a table.

For example, here we obtain 25% of the rows:

SELECT * FROM emp SAMPLE(25)

The following SQL (using one of the analytical functions) will give you a random sample of a specific number of each occurrence of a particular value (similar to a GROUP BY) in a table.

Here we sample 10 of each:

SELECT * FROM (
SELECT job, sal, ROW_NUMBER()
OVER (
PARTITION BY job ORDER BY job
) SampleCount FROM emp
)
WHERE SampleCount <= 10

How to suppress "unused parameter" warnings in C?

In MSVC to suppress a particular warning it is enough to specify the it's number to compiler as /wd#. My CMakeLists.txt contains such the block:

If (MSVC)
    Set (CMAKE_EXE_LINKER_FLAGS "$ {CMAKE_EXE_LINKER_FLAGS} / NODEFAULTLIB: LIBCMT")
    Add_definitions (/W4 /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127)
    Add_definitions (/D_CRT_SECURE_NO_WARNINGS)
Elseif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUC)
    Add_definitions (-Wall -W -pedantic)
Else ()
    Message ("Unknown compiler")
Endif ()

Now I can not say what exactly /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127 mean, because I do not pay any attention to MSVC for three years, but they suppress superpedantic warnings that does not influence the result.

How can I add a volume to an existing Docker container?

Unfortunately the switch option to mount a volume is only found in the run command.

docker run --help

-v, --volume list Bind mount a volume (default [])

There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.

  1. Export your container docker container export -o ./myimage.docker mycontainer
  2. Import as an image docker import ./myimage.docker myimage
  3. Then docker run -i -t -v /somedir --name mycontainer myimage /bin/bash

HTML5 - mp4 video does not play in IE9

for IE9 I found that a meta tag was required to set the mode

<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>

<video width="400" height="300" preload controls>
<source src="movie.mp4" type="video/mp4" />
Your browser does not support the video tag
</video>

how to measure running time of algorithms in python

I am not 100% sure what is meant by "running times of my algorithms written in python", so I thought I might try to offer a broader look at some of the potential answers.

  • Algorithms don't have running times; implementations can be timed, but an algorithm is an abstract approach to doing something. The most common and often the most valuable part of optimizing a program is analyzing the algorithm, usually using asymptotic analysis and computing the big O complexity in time, space, disk use and so forth.

    A computer cannot really do this step for you. This requires doing the math to figure out how something works. Optimizing this side of things is the main component to having scalable performance.

  • You can time your specific implementation. The nicest way to do this in Python is to use timeit. The way it seems most to want to be used is to make a module with a function encapsulating what you want to call and call it from the command line with python -m timeit ....

    Using timeit to compare multiple snippets when doing microoptimization, but often isn't the correct tool you want for comparing two different algorithms. It is common that what you want is asymptotic analysis, but it's possible you want more complicated types of analysis.

  • You have to know what to time. Most snippets aren't worth improving. You need to make changes where they actually count, especially when you're doing micro-optimisation and not improving the asymptotic complexity of your algorithm.

    If you quadruple the speed of a function in which your code spends 1% of the time, that's not a real speedup. If you make a 20% speed increase on a function in which your program spends 50% of the time, you have a real gain.

    To determine the time spent by a real Python program, use the stdlib profiling utilities. This will tell you where in an example program your code is spending its time.

How to assign an action for UIImageView object in Swift

Swift 4 Code


Step 1 In ViewdidLoad()

   let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
       userImageView.addGestureRecognizer(pictureTap)
       userImageView.isUserInteractionEnabled = true

Step 2 Add Following Function

@objc func imageTapped() {

        let imageView = userImageView
        let newImageView = UIImageView(image: imageView?.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = UIColor.black
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)

        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true

    }

It's Tested And Working Properly

IsNull function in DB2 SQL?

I'm not familiar with DB2, but have you tried COALESCE?

ie:


SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product

Identifier is undefined

From the update 2 and after narrowing down the problem scope, we can easily find that there is a brace missing at the end of the function addWord. The compiler will never explicitly identify such a syntax error. instead, it will assume that the missing function definition located in some other object file. The linker will complain about it and hence directly will be categorized under one of the broad the error phrases which is identifier is undefined. Reasonably, because with the current syntax the next function definition (in this case is ac_search) will be included under the addWord scope. Hence, it is not a global function anymore. And that is why compiler will not see this function outside addWord and will throw this error message stating that there is no such a function. A very good elaboration about the compiler and the linker can be found in this article

Bin size in Matplotlib (Histogram)

I had the same issue as OP (I think!), but I couldn't get it to work in the way that Lastalda specified. I don't know if I have interpreted the question properly, but I have found another solution (it probably is a really bad way of doing it though).

This was the way that I did it:

plt.hist([1,11,21,31,41], bins=[0,10,20,30,40,50], weights=[10,1,40,33,6]);

Which creates this:

image showing histogram graph created in matplotlib

So the first parameter basically 'initialises' the bin - I'm specifically creating a number that is in between the range I set in the bins parameter.

To demonstrate this, look at the array in the first parameter ([1,11,21,31,41]) and the 'bins' array in the second parameter ([0,10,20,30,40,50]):

  • The number 1 (from the first array) falls between 0 and 10 (in the 'bins' array)
  • The number 11 (from the first array) falls between 11 and 20 (in the 'bins' array)
  • The number 21 (from the first array) falls between 21 and 30 (in the 'bins' array), etc.

Then I'm using the 'weights' parameter to define the size of each bin. This is the array used for the weights parameter: [10,1,40,33,6].

So the 0 to 10 bin is given the value 10, the 11 to 20 bin is given the value of 1, the 21 to 30 bin is given the value of 40, etc.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

; always_populate_raw_post_data = -1 in php.init remove comment of this line .. always_populate_raw_post_data = -1

Get the number of rows in a HTML table

The following code assumes that your table has the ID 'MyTable'

<script language="JavaScript">
<!--
var oRows = document.getElementById('MyTable').getElementsByTagName('tr');
var iRowCount = oRows.length;

alert('Your table has ' + iRowCount + ' rows.');
//-->
</script>

Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)

AngularJS - Attribute directive input value change

There's a great example in the AngularJS docs.

It's very well commented and should get you pointed in the right direction.

A simple example, maybe more so what you're looking for is below:

jsfiddle


HTML

<div ng-app="myDirective" ng-controller="x">
    <input type="text" ng-model="test" my-directive>
</div>

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('value changed, new value is: ' + v);
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}


Edit: Same thing, doesn't require ngModel jsfiddle:

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: {
            myDirective: '='
        },
        link: function (scope, element, attrs) {
            // set the initial value of the textbox
            element.val(scope.myDirective);
            element.data('old-value', scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective', function (val) {
                element.val(scope.myDirective);
            });

            // on blur, update the value in scope
            element.bind('propertychange keyup paste', function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed, new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value', element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

laravel 5 : Class 'input' not found

Declaration in config/app.php under aliases:-

'Input' => Illuminate\Support\Facades\Input::class,

Or You can import Input facade directly as required,

use Illuminate\Support\Facades\Input;

or

use Illuminate\Support\Facades\Input as input;

Convert object string to JSON

Using new Function() is better than eval, but still should only be used with safe input.

const parseJSON = obj => Function('"use strict";return (' + obj + ')')();

console.log(parseJSON("{a:(4-1), b:function(){}, c:new Date()}"))
// outputs: Object { a: 3, b: b(), c: Date 2019-06-05T09:55:11.777Z }

Sources: MDN, 2ality

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

I tried the solution xcode-select --install but it don't help me, I update from Sierra to High and happened this, my solution:

sudo xcode-select --reset

Download File Using Javascript/jQuery

These functions are used in stacktrace.js:

/**
 * Try XHR methods in order and store XHR factory.
 *
 * @return <Function> XHR function or equivalent
 */
var createXMLHTTPObject = function() {
    var xmlhttp, XMLHttpFactories = [
        function() {
            return new XMLHttpRequest();
        }, function() {
            return new ActiveXObject('Msxml2.XMLHTTP');
        }, function() {
            return new ActiveXObject('Msxml3.XMLHTTP');
        }, function() {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    ];
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
            // Use memoization to cache the factory
            createXMLHTTPObject = XMLHttpFactories[i];
            return xmlhttp;
        } catch (e) {
        }
    }
}

/**
 * @return the text from a given URL
 */
function ajax(url) {
    var req = createXMLHTTPObject();
    if (req) {
        try {
            req.open('GET', url, false);
            req.send(null);
            return req.responseText;
        } catch (e) {
        }
    }
    return '';
}

JQuery addclass to selected div, remove class if another div is selected

**This can be achived easily using two different ways:**

1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery

**1)First Way**

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').removeClass('active class or your class name which you want to    remove').addClass('active class or your class name which you want to add');     
});
});

**2) Second Way**

i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)

<div id="dvId" class="ActiveClassname ">
</div

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').toggleClass('ActiveClassname InActiveClassName');     
});
});


Enjoy.....:)

If you any doubt free to ask any time...

Reading value from console, interactively

Blocking readline unblocked behaviour

Imagine you have three questions to be answered from the console, as you now know this code will not run because readline standard module has 'unblocked' behaviour say each rl.question is an independent thread so this code will not run.

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

function askaquestion(question) {
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(question[0], function(answer) {
    console.log(answer);
    question[1] = answer;
    rl.close();
  });
};

var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i]);
}

console.log('Results:',questionaire );

Running output:

node test.js
Third Question: Results: [ [ 'First Question: ', '' ],
  [ 'Second Question: ', '' ],
  [ 'Third Question: ', '' ] ]        <--- the last question remain unoverwritten and then the final line of the program is shown as the threads were running waiting for answers (see below)
aaa        <--- I responded with a single 'a' that was sweeped by 3 running threads
a        <--- Response of one thread

a        <--- Response of another thread

a        <--- Response of another thread (there is no order on threads exit)

The proposed solution uses an event emitter to signal the end of an unblocking thread, and includes the loop logic and end of program into its listener function.

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

// Introduce EventEmitter object
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {};

const myEmitter = new MyEmitter();
myEmitter.on('continue', () => {
  console.log('continue...');
  i++; if (i< questionaire.length) askaquestion(questionaire[i],myEmitter);    // add here relevant loop logic
           else console.log('end of loop!\nResults:',questionaire );
});
//

function askaquestion(p_question,p_my_Emitter) { // add a parameter to include my_Emitter
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(p_question[0], function(answer) {
    console.log(answer);
    p_question[1] = answer;
    rl.close();
    myEmitter.emit('continue');    // Emit 'continue' event after the question was responded (detect end of unblocking thread)
  });
};

/*var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i],myEmitter);
}*/

var i=0;
askaquestion(questionaire[0],myEmitter);        // entry point to the blocking loop


// console.log('Results:',questionaire )    <- moved to the truly end of the program

Running output:

node test2.js
First Question: 1
1
continue...
Second Question: 2
2
continue...
Third Question: 3
3
continue...
done!
Results: [ [ 'First Question: ', '1' ],
  [ 'Second Question: ', '2' ],
  [ 'Third Question: ', '3' ] ]

How do I check if a directory exists? "is_dir", "file_exists" or both?

$save_folder = "some/path/" . date('dmy');

if (!file_exists($save_folder)) {
   mkdir($save_folder, 0777);
}

How can I convert JSON to a HashMap using Gson?

I know this is a fairly old question, but I was searching for a solution to generically deserialize nested JSON to a Map<String, Object>, and found nothing.

The way my yaml deserializer works, it defaults JSON objects to Map<String, Object> when you don't specify a type, but gson doesn't seem to do this. Luckily you can accomplish it with a custom deserializer.

I used the following deserializer to naturally deserialize anything, defaulting JsonObjects to Map<String, Object> and JsonArrays to Object[]s, where all the children are similarly deserialized.

private static class NaturalDeserializer implements JsonDeserializer<Object> {
  public Object deserialize(JsonElement json, Type typeOfT, 
      JsonDeserializationContext context) {
    if(json.isJsonNull()) return null;
    else if(json.isJsonPrimitive()) return handlePrimitive(json.getAsJsonPrimitive());
    else if(json.isJsonArray()) return handleArray(json.getAsJsonArray(), context);
    else return handleObject(json.getAsJsonObject(), context);
  }
  private Object handlePrimitive(JsonPrimitive json) {
    if(json.isBoolean())
      return json.getAsBoolean();
    else if(json.isString())
      return json.getAsString();
    else {
      BigDecimal bigDec = json.getAsBigDecimal();
      // Find out if it is an int type
      try {
        bigDec.toBigIntegerExact();
        try { return bigDec.intValueExact(); }
        catch(ArithmeticException e) {}
        return bigDec.longValue();
      } catch(ArithmeticException e) {}
      // Just return it as a double
      return bigDec.doubleValue();
    }
  }
  private Object handleArray(JsonArray json, JsonDeserializationContext context) {
    Object[] array = new Object[json.size()];
    for(int i = 0; i < array.length; i++)
      array[i] = context.deserialize(json.get(i), Object.class);
    return array;
  }
  private Object handleObject(JsonObject json, JsonDeserializationContext context) {
    Map<String, Object> map = new HashMap<String, Object>();
    for(Map.Entry<String, JsonElement> entry : json.entrySet())
      map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class));
    return map;
  }
}

The messiness inside the handlePrimitive method is for making sure you only ever get a Double or an Integer or a Long, and probably could be better, or at least simplified if you're okay with getting BigDecimals, which I believe is the default.

You can register this adapter like:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();

And then call it like:

Object natural = gson.fromJson(source, Object.class);

I'm not sure why this is not the default behavior in gson, since it is in most other semi-structured serialization libraries...

The thread has exited with code 0 (0x0) with no unhandled exception

Stop this error you have to follow this simple steps

  1. Open Visual Studio
  2. Select option debug from the top
  3. Select Options
  4. In Option Select debugging under debugging select General
  5. In General Select check box "Automatically close the console when debugging stop"
  6. Save it

Then Run the code by using Shortcut key Ctrl+f5

**Other wise it still show error when you run it direct

Why does printf not flush after the call unless a newline is in the format string?

by default, stdout is line buffered, stderr is none buffered and file is completely buffered.

How line ending conversions work with git core.autocrlf between different operating systems

Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:

A new config setting core.eol is being added/evolved:

This is a replacement for the 'Add "core.eol" config variable' commit that's currently in pu (the last one in my series).
Instead of implying that "core.autocrlf=true" is a replacement for "* text=auto", it makes explicit the fact that autocrlf is only for users who want to work with CRLFs in their working directory on a repository that doesn't have text file normalization.
When it is enabled, "core.eol" is ignored.

Introduce a new configuration variable, "core.eol", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native", which means CRLF on Windows and LF everywhere else. Note that "core.autocrlf" overrides core.eol.
This means that:

[core]
  autocrlf = true

puts CRLFs in the working directory even if core.eol is set to "lf".

core.eol:

Sets the line ending type to use in the working directory for files that have the text property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value is native.


Other evolutions are being considered:

For 1.8, I would consider making core.autocrlf just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.


git 2.8 (March 2016) improves the way core.autocrlf influences the eol:

See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi).
(Merged by Junio C Hamano -- gitster -- in commit c6b94eb, 26 Feb 2016)

convert.c: refactor crlf_action

Refactor the determination and usage of crlf_action.
Today, when no "crlf" attribute are set on a file, crlf_action is set to CRLF_GUESS. Use CRLF_UNDEFINED instead, and search for "text" or "eol" as before.

Replace the old CRLF_GUESS usage:

CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT

Make more clear, what is what, by defining:

- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
                   and core.eol is evaluated and one of CRLF_BINARY,
                   CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY    : No processing of line endings.
- CRLF_TEXT      : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO      : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true  (no attributes)

As torek adds in the comments:

all these translations (any EOL conversion from eol= or autocrlf settings, and "clean" filters) are run when files move from work-tree to index, i.e., during git add rather than at git commit time.
(Note that git commit -a or --only or --include do add files to the index at that time, though.)

For more on that, see "What is difference between autocrlf and eol".

Java Try Catch Finally blocks without Catch

how does the try block work if it encounters an exception or anything throwable

The exception is thrown out of the block, just as in any other case where it's not caught.

The finally block is executed regardless of how the try block is exited -- regardless whether there are any catches at all, regardless of whether there is a matching catch.

The catch blocks and the finally are orthogonal parts of the try block. You can have either or both. With Java 7, you'll be able to have neither!

How to create a POJO?

A POJO is a Plain Old Java Object.

From the wikipedia article I linked to:

In computing software, POJO is an acronym for Plain Old Java Object. The name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean

Your class appears to already be a POJO.

Shell script not running, command not found

There have been a few good comments about adding the shebang line to the beginning of the script. I'd like to add a recommendation to use the env command as well, for additional portability.

While #!/bin/bash may be the correct location on your system, that's not universal. Additionally, that may not be the user's preferred bash. #!/usr/bin/env bash will select the first bash found in the path.

AES Encryption for an NSString on the iPhone

Since you haven't posted any code, it's difficult to know exactly which problems you're encountering. However, the blog post you link to does seem to work pretty decently... aside from the extra comma in each call to CCCrypt() which caused compile errors.

A later comment on that post includes this adapted code, which works for me, and seems a bit more straightforward. If you include their code for the NSData category, you can write something like this: (Note: The printf() calls are only for demonstrating the state of the data at various points — in a real application, it wouldn't make sense to print such values.)

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *key = @"my password";
    NSString *secret = @"text to encrypt";

    NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *cipher = [plain AES256EncryptWithKey:key];
    printf("%s\n", [[cipher description] UTF8String]);

    plain = [cipher AES256DecryptWithKey:key];
    printf("%s\n", [[plain description] UTF8String]);
    printf("%s\n", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] UTF8String]);

    [pool drain];
    return 0;
}

Given this code, and the fact that encrypted data will not always translate nicely into an NSString, it may be more convenient to write two methods that wrap the functionality you need, in forward and reverse...

- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}

- (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
    return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
                                  encoding:NSUTF8StringEncoding] autorelease];
}

This definitely works on Snow Leopard, and @Boz reports that CommonCrypto is part of the Core OS on the iPhone. Both 10.4 and 10.5 have /usr/include/CommonCrypto, although 10.5 has a man page for CCCryptor.3cc and 10.4 doesn't, so YMMV.


EDIT: See this follow-up question on using Base64 encoding for representing encrypted data bytes as a string (if desired) using safe, lossless conversions.

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Use a LIKE statement on SQL Server XML Datatype

Another option is to search the XML as a string by converting it to a string and then using LIKE. However as a computed column can't be part of a WHERE clause you need to wrap it in another SELECT like this:

SELECT * FROM
    (SELECT *, CONVERT(varchar(MAX), [COLUMNA]) as [XMLDataString] FROM TABLE) x
WHERE [XMLDataString] like '%Test%'

Handling MySQL datetimes and timestamps in Java

BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.

Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.

When writing datetime value to sql db

    //Convert the time into UTC and build Timestamp object.
    Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
    //use setTimestamp on preparedstatement
    preparedStatement.setTimestamp(1, ts);

When reading the value back from DB into java,

  1. Read it as it is in java.sql.Timestamp type.
  2. Decorate the DateTime value as time in UTC timezone using atZone method in LocalDateTime class.
  3. Then, change it to your desired timezone. Here I am changing it to Toronto timezone.

    ResultSet resultSet = preparedStatement.executeQuery();
    resultSet.next();
    Timestamp timestamp = resultSet.getTimestamp(1);
    ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
    LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
    

sql use statement with variable

try this:

DECLARE @Query         varchar(1000)
DECLARE @DatabaseName  varchar(500)

SET @DatabaseName='xyz'
SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table1'
EXEC (@Query)

SET @DatabaseName='abc'
SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table2'
EXEC (@Query)

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Your for loop looks good.

A possible while loop to accomplish the same thing:

int sum = 0;
int i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("The sum is " + sum);

A possible do while loop to accomplish the same thing:

int sum = 0;
int i = 1;
do {
    sum += i;
    i++;
} while (i <= 100);
System.out.println("The sum is " + sum);

The difference between the while and the do while is that, with the do while, at least one iteration is sure to occur.

C - determine if a number is prime

OK, so forget about C. Suppose I give you a number and ask you to determine if it's prime. How do you do it? Write down the steps clearly, then worry about translating them into code.

Once you have the algorithm determined, it will be much easier for you to figure out how to write a program, and for others to help you with it.

edit: Here's the C# code you posted:

static bool IsPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0 && i != number) return false;
    }
    return true;
}

This is very nearly valid C as is; there's no bool type in C, and no true or false, so you need to modify it a little bit (edit: Kristopher Johnson correctly points out that C99 added the stdbool.h header). Since some people don't have access to a C99 environment (but you should use one!), let's make that very minor change:

int IsPrime(int number) {
    int i;
    for (i=2; i<number; i++) {
        if (number % i == 0 && i != number) return 0;
    }
    return 1;
}

This is a perfectly valid C program that does what you want. We can improve it a little bit without too much effort. First, note that i is always less than number, so the check that i != number always succeeds; we can get rid of it.

Also, you don't actually need to try divisors all the way up to number - 1; you can stop checking when you reach sqrt(number). Since sqrt is a floating-point operation and that brings a whole pile of subtleties, we won't actually compute sqrt(number). Instead, we can just check that i*i <= number:

int IsPrime(int number) {
    int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

One last thing, though; there was a small bug in your original algorithm! If number is negative, or zero, or one, this function will claim that the number is prime. You likely want to handle that properly, and you may want to make number be unsigned, since you're more likely to care about positive values only:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

This definitely isn't the fastest way to check if a number is prime, but it works, and it's pretty straightforward. We barely had to modify your code at all!

Double decimal formatting in Java

Use String.format:

String.format("%.2f", 4.52135);

As per docs:

The locale always used is the one returned by Locale.getDefault().

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

Set icon for Android application

Goto File->new->ImageAsset.

From their you can create Image Assets for your icon.

After that we will get icon image in mipmap different formats like hdpi,mdpi,xhdpi,xxhdpi,xxxhdpi.

Now goto AndroidManifest.xml

<application android:icon="@mipmap/your_Icon"> ....</application>

Get class name of object as string in Swift

Try reflect().summary on Class self or instance dynamicType. Unwrap optionals before getting dynamicType otherwise the dynamicType is the Optional wrapper.

class SampleClass { class InnerClass{} }
let sampleClassName = reflect(SampleClass.self).summary;
let instance = SampleClass();
let instanceClassName = reflect(instance.dynamicType).summary;
let innerInstance = SampleClass.InnerClass();
let InnerInstanceClassName = reflect(innerInstance.dynamicType).summary.pathExtension;
let tupleArray = [(Int,[String:Int])]();
let tupleArrayTypeName = reflect(tupleArray.dynamicType).summary;

The summary is a class path with generic types described. To get a simple class name from the summary try this method.

func simpleClassName( complexClassName:String ) -> String {
    var result = complexClassName;
    var range = result.rangeOfString( "<" );
    if ( nil != range ) { result = result.substringToIndex( range!.startIndex ); }
    range = result.rangeOfString( "." );
    if ( nil != range ) { result = result.pathExtension; }
    return result;
}

ResourceDictionary in a separate assembly

An example, just to make this a 15 seconds answer -

Say you have "styles.xaml" in a WPF library named "common" and you want to use it from your main application project:

  1. Add a reference from the main project to "common" project
  2. Your app.xaml should contain:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/Common;component/styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Linux/Unix command to determine if process is running?

The simpliest way is to use ps and grep:

command="httpd"
running=`ps ax | grep -v grep | grep $command | wc -l`
if [ running -gt 0 ]; then
    echo "Command is running"
else
    echo "Command is not running"
fi

If your command has some command arguments, then you can also put more 'grep cmd_arg1' after 'grep $command' to filter out other possible processes that you are not interested in.

Example: show me if any java process with supplied argument:

-Djava.util.logging.config.file=logging.properties

is running

ps ax | grep -v grep | grep java | grep java.util.logging.config.file=logging.properties | wc -l

Tests not running in Test Explorer

I had this issue and for me it was caused by having multiple Test Projects with different versions of :

  • MSTest.TestAdapter
  • MSTest.TestFramework

Consolidating the nuget packages for the projects so they were the same resolved the issue for me.

How I can filter a Datatable?

For anybody who work in VB.NET (just in case)

Dim dv As DataView = yourDatatable.DefaultView

dv.RowFilter ="query" ' ex: "parentid = 0"

Python: How to keep repeating a program until a specific input is obtained?

There are two ways to do this. First is like this:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_input with input.

How to scale an Image in ImageView to keep the aspect ratio

This is how it worked for me inside a ConstraintLayout:

<ImageView
    android:id="@+id/myImg"
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"/>

Then in code, I set the drawable as:

ImageView imgView = findViewById(R.id.myImg);
imgView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.image_to_show, null));

This fits the image nicely according to its aspect ratio and keeps it in centre.

How to read embedded resource text file

In Visual Studio you can directly embed access to a file resource via the Resources tab of the Project properties ("Analytics" in this example). visual studio screen shot - Resources tab

The resulting file can then be accessed as a byte array by

byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter;

Should you need it as a stream, then ( from https://stackoverflow.com/a/4736185/432976 )

Stream stream = new MemoryStream(jsonSecrets)

How can I export data to an Excel file

MS provides the OpenXML SDK V 2.5 - see https://msdn.microsoft.com/en-us/library/bb448854(v=office.15).aspx

This can read+write MS Office files (including Excel)...

Another option see http://www.codeproject.com/KB/office/OpenXML.aspx

IF you need more like rendering, formulas etc. then there are different commercial libraries like Aspose and Flexcel...

Using jQuery to test if an input has focus

What I wound up doing is creating an arbitrary class called .elementhasfocus which is added and removed within the jQuery focus() function. When the hover() function runs on mouse out, it checks for .elementhasfocus:

if(!$("#quotebox").is(".boxhasfocus")) $(this).removeClass("box_border");

So if it doesn't have that class (read: no elements within the div have focus) the border is removed. Otherwise, nothing happens.

How do I run a terminal inside of Vim?

Split the screen and run command term ++curwin to run the terminal inside the Vim buffer. Following command does both and worked for me:

:bo 10sp | term ++curwin

text-overflow: ellipsis not working

word-wrap: break-word;

this and only this did the job for me for a

<pre> </pre> 

tag

everthing else failed to do the ellipsis....

How can I remove a commit on GitHub?

if you want to remove do interactive rebase,

git rebase -i HEAD~4

4 represents total number of commits to display count your commit andchange it accordingly

and delete commit you want from list...

save changes by Ctrl+X(ubuntu) or :wq(centos)

2nd method, do revert,

git revert 29f4a2 #your commit ID

this will revert specific commit

Algorithm to find Largest prime factor of a number

Similar to @Triptych answer but also different. In this example list or dictionary is not used. Code is written in Ruby

def largest_prime_factor(number)
  i = 2
  while number > 1
    if number % i == 0
      number /= i;
    else
      i += 1
    end
  end
  return i
end

largest_prime_factor(600851475143)
# => 6857

How can I render HTML from another file in a React component?

If your template.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.

However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.

Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop.

var __html = require('./template.html');
var template = { __html: __html };

React.module.exports = React.createClass({
  render: function() {
    return(
      <div dangerouslySetInnerHTML={template} />
    );
  }
});

This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.

If your template.html file looked something like this

<div class='foo'>
  <h1>Hello</h1>
  <p>Some paragraph text</p>
  <button>Click</button>
</div>

Then you could convert it instead to a JSX file that looked like this.

module.exports = function(props) {
  return (
    <div className='foo'>
      <h1>Hello</h1>
      <p>Some paragraph text</p>
      <button>Click</button>
    </div>
  );
};

Then you can require and use it without needing stringify.

var Template = require('./template');

module.exports = React.createClass({
  render: function() {
    var bar = 'baz';
    return(
      <Template foo={bar}/>
    );
  }
});

It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.

Split pandas dataframe in two if it has more than 10 rows

This will return the split DataFrames if the condition is met, otherwise return the original and None (which you would then need to handle separately). Note that this assumes the splitting only has to happen one time per df and that the second part of the split (if it is longer than 10 rows (meaning that the original was longer than 20 rows)) is OK.

df_new1, df_new2 = df[:10, :], df[10:, :] if len(df) > 10 else df, None

Note you can also use df.head(10) and df.tail(len(df) - 10) to get the front and back according to your needs. You can also use various indexing approaches: you can just provide the first dimensions index if you want, such as df[:10] instead of df[:10, :] (though I like to code explicitly about the dimensions you are taking). You can can also use df.iloc and df.ix to index in similar ways.

Be careful about using df.loc however, since it is label-based and the input will never be interpreted as an integer position. .loc would only work "accidentally" in the case when you happen to have index labels that are integers starting at 0 with no gaps.

But you should also consider the various options that pandas provides for dumping the contents of the DataFrame into HTML and possibly also LaTeX to make better designed tables for the presentation (instead of just copying and pasting). Simply Googling how to convert the DataFrame to these formats turns up lots of tutorials and advice for exactly this application.

In PHP, what is a closure and why does it use the "use" identifier?

Until very recent years, PHP has defined its AST and PHP interpreter has isolated the parser from the evaluation part. During the time when the closure is introduced, PHP's parser is highly coupled with the evaluation.

Therefore when the closure was firstly introduced to PHP, the interpreter has no method to know which which variables will be used in the closure, because it is not parsed yet. So user has to pleased the zend engine by explicit import, doing the homework that zend should do.

This is the so-called simple way in PHP.

clearing a char array c

Use:

memset(my_custom_data, 0, sizeof(my_custom_data));

Or:

memset(my_custom_data, 0, strlen(my_custom_data));

return query based on date

If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...

First create an index on the property you want to match on (include sort direction -1 for descending and 1 for ascending)

db.things.createIndex({ createdAt: -1 }) // descending order on .createdAt

Then query for documents created in the last 5 minutes (60 seconds * 5 minutes)....because javascript's .getTime() returns milliseconds you need to mulitply by 1000 before you use it as input to the new Date() constructor.

db.things.find({
        createdAt: {
            $gte: new Date(new Date().getTime()-60*5*1000).toISOString()
         }
     })
     .count()

Explanation for new Date(new Date().getTime()-60*5*1000).toISOString() is as follows:

First we calculate "5 minutes ago":

  1. new Date().getTime() gives us current time in milliseconds
  2. We want to subtract 5 minutes (in ms) from that: 5*60*1000 -- I just multiply by 60 seconds so its easy to change. I can just change 5 to 120 if I want 2 hours (120 minutes).
  3. new Date().getTime()-60*5*1000 gives us 1484383878676 (5 minutes ago in ms)

Now we need to feed that into a new Date() constructor to get the ISO string format required by MongoDB timestamps.

  1. { $gte: new Date(resultFromAbove).toISOString() } (mongodb .find() query)
  2. Since we can't have variables we do it all in one shot: new Date(new Date().getTime()-60*5*1000)
  3. ...then convert to ISO string: .toISOString()
  4. new Date(new Date().getTime()-60*5*1000).toISOString() gives us 2017-01-14T08:53:17.586Z

Of course this is a little easier with variables if you're using the node-mongodb-native driver, but this works in the mongo shell which is what I usually use to check things.

how to get javaScript event source element?

You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Activity class is the basic class. (The original) It supports Fragment management (Since API 11). Is not recommended anymore its pure use because its specializations are far better.

ActionBarActivity was in a moment the replacement to the Activity class because it made easy to handle the ActionBar in an app.

AppCompatActivity is the new way to go because the ActionBar is not encouraged anymore and you should use Toolbar instead (that's currently the ActionBar replacement). AppCompatActivity inherits from FragmentActivity so if you need to handle Fragments you can (via the Fragment Manager). AppCompatActivity is for ANY API, not only 16+ (who said that?). You can use it by adding compile 'com.android.support:appcompat-v7:24:2.0' in your Gradle file. I use it in API 10 and it works perfect.

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.