Programs & Examples On #Jtree

Java Swing component that displays a set of hierarchical data as an outline.

Get JSON data from external URL and display it in a div as plain text

Here is one without using JQuery with pure JavaScript. I used javascript promises and XMLHttpRequest You can try it here on this fiddle

HTML

<div id="result" style="color:red"></div>

JavaScript

var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        reject(status);
      }
    };
    xhr.send();
  });
};

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan').then(function(data) {
    alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
  alert('Something went wrong.');
});

"No resource identifier found for attribute 'showAsAction' in package 'android'"

remove android:showAsAction="never" from res/menu folder from every xml file.

How to comment out a block of code in Python

The only mechanism to comment out Python code (understood as code ignored by the interpreter) is the #.

As you say, you can also use string literals, that are not ignored by the interpreter, but can be completely irrelevant for the program execution.

SQL select join: is it possible to prefix all columns as 'prefix.*'?

In postgres, I use the json functions to instead return json objects.... then, after querying, I json_decode the fields with a _json suffix.

IE:

select row_to_json(tab1.*),tab1_json, row_to_json(tab2.*) tab2_json 
 from tab1
 join tab2 on tab2.t1id=tab1.id

then in PHP (or any other language), I loop through the returned columns and json_decode() them if they have the "_json" suffix (also removing the suffix. In the end, I get an object called "tab1" that includes all tab1 fields, and another called "tab2" that includes all tab2 fields.

How to rename array keys in PHP?

Very simple approach to replace keys in a multidimensional array, and maybe even a bit dangerous, but should work fine if you have some kind of control over the source array:

$array = [ 'oldkey' => [ 'oldkey' => 'wow'] ];
$new_array = json_decode(str_replace('"oldkey":', '"newkey":', json_encode($array)));
print_r($new_array); // [ 'newkey' => [ 'newkey' => 'wow'] ]

Get git branch name in Jenkins Pipeline/Jenkinsfile

Just getting the name from scm.branches is not enough if you've used a build parameter as a branch specifier, e.g. ${BRANCH}. You need to expand that string into a real name:

scm.branches.first().getExpandedName(env.getEnvironment())

Note that getEnvironment() must be an explicit getter otherwise env will look up for an environment variable called environment.

Don't forget that you need to approve those methods to make them accessible from the sandbox.

SystemError: Parent module '' not loaded, cannot perform relative import

If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

I think I have a better answer.

new Timestamp(longEpochTime).toLocalDateTime();

Remove all html tags from php string

use this regex: /<[^<]+?>/g

$val = preg_replace('/<[^<]+?>/g', ' ', $row_get_Business['business_description']);

$businessDesc = substr(val,0,110);

from your example should stay: Ref no: 30001

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

Exporting data In SQL Server as INSERT INTO

Here is an example of creating a data migration script using a cursor to iterate the source table.

SET NOCOUNT ON;  
DECLARE @out nvarchar(max) = ''
DECLARE @row nvarchar(1024)
DECLARE @first int = 1

DECLARE cur CURSOR FOR 
    SELECT '(' + CONVERT(CHAR(1),[Stage]) + ',''' + [Label] + ''')'
    FROM CV_ORDER_STATUS
    ORDER BY [Stage]

PRINT 'SET IDENTITY_INSERT dbo.CV_ORDER_STATUS ON'
PRINT 'GO'

PRINT 'INSERT INTO dbo.CV_ORDER_STATUS ([Stage],[Label]) VALUES';

OPEN cur
FETCH NEXT FROM cur
    INTO @row

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @first = 1
        SET @first = 0
    ELSE
        SET @out = @out + ',' + CHAR(13);

    SET @out = @out + @row

    FETCH NEXT FROM cur into @row
END

CLOSE cur
DEALLOCATE cur

PRINT @out

PRINT 'SET IDENTITY_INSERT dbo.CV_ORDER_STATUS OFF'
PRINT 'GO'

Change Oracle port from port 8080

Just open Run SQL Command Line and login as sysadmin and then enter below command

Exec DBMS_XDB.SETHTTPPORT(8181);

That's it. You are done.....

How to remove list elements in a for loop in Python?

As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).

If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.

This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.

TL;DR:

>>> a = list(range(5))
>>> for b in reversed(a):
    if b == 3:
        a.remove(b)
>>> a
[0, 1, 2, 4]

However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

How to add data to DataGridView

first you need to add 2 columns to datagrid. you may do it at design time. see Columns property. then add rows as much as you need.

this.dataGridView1.Rows.Add("1", "XX");

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

Bootstrap4 adding scrollbar to div

Yes, It is possible, Just add a class like anyclass and give some CSS style. Live

.anyClass {
  height:150px;
  overflow-y: scroll;
}

_x000D_
_x000D_
.anyClass {_x000D_
  height:150px;_x000D_
  overflow-y: scroll;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class=" col-md-2">_x000D_
  <ul class="nav nav-pills nav-stacked anyClass">_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link active" href="#">Active</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link disabled" href="#">Disabled</a>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.

Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.

Monad in plain English? (For the OOP programmer with no FP background)

In terms that an OOP programmer would understand (without any functional programming background), what is a monad?

What problem does it solve and what are the most common places it's used?are the most common places it's used?

In terms of OO programming, a monad is an interface (or more likely a mixin), parameterized by a type, with two methods, return and bind that describe:

  • How to inject a value to get a monadic value of that injected value type;
  • How to use a function that makes a monadic value from a non-monadic one, on a monadic value.

The problem it solves is the same type of problem you'd expect from any interface, namely, "I have a bunch of different classes that do different things, but seem to do those different things in a way that has an underlying similarity. How can I describe that similarity between them, even if the classes themselves aren't really subtypes of anything closer than 'the Object' class itself?"

More specifically, the Monad "interface" is similar to IEnumerator or IIterator in that it takes a type that itself takes a type. The main "point" of Monad though is being able to connect operations based on the interior type, even to the point of having a new "internal type", while keeping - or even enhancing - the information structure of the main class.

Eclipse and Windows newlines

To recursively remove the carriage returns (\r) from the CVS/* files in all child directories, run the following in a unix shell:

find ./ -wholename "\*CVS/[RE]\*" -exec dos2unix -q -o {} \;

How can I add JAR files to the web-inf/lib folder in Eclipse?

  • Add the jar file to your WEB-INF/lib folder.
  • Right-click your project in Eclipse, and go to "Build Path > Configure Build Path"
  • Add the "Web App Libraries" library

This will ensure all WEB-INF/lib jars are included on the classpath.

How to convert a string from uppercase to lowercase in Bash?

The correct way to implement your code is

y="HELLO"
val=$(echo "$y" | tr '[:upper:]' '[:lower:]')
string="$val world"

This uses $(...) notation to capture the output of the command in a variable. Note also the quotation marks around the string variable -- you need them there to indicate that $val and world are a single thing to be assigned to string.

If you have bash 4.0 or higher, a more efficient & elegant way to do it is to use bash builtin string manipulation:

y="HELLO"
string="${y,,} world"

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

comparing strings in vb

If String.Compare(string1,string2,True) Then

    'perform operation

EndIf

How to place two divs next to each other?

This is the right CSS3 answer. Hope this helps you somehow now :D I really recommend you to read the book: https://www.amazon.com/Book-CSS3-Developers-Future-Design/dp/1593272863 Actually I have made this solution from reading this book now. :D

_x000D_
_x000D_
#wrapper{_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#first{_x000D_
  width: 300px;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#second{_x000D_
  border: 1px solid green;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
    <div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
    <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

New Line Issue when copying data from SQL Server 2012 to Excel

In order to be able to copy and paste results from SQL Server Management Studio 2012 to Excel or to export to Csv with list separators you must first change the query option.

  1. Click on Query then options.

  2. Under Results click on the Grid.

  3. Check the box next to:

    Quote strings containing list separators when saving .csv results.

This should solve the problem.

Convert command line argument to string

#include <iostream>

std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));

startsWith() and endsWith() functions in PHP

Here's a multi-byte safe version of the accepted answer, it works fine for UTF-8 strings:

function startsWith($haystack, $needle)
{
    $length = mb_strlen($needle, 'UTF-8');
    return (mb_substr($haystack, 0, $length, 'UTF-8') === $needle);
}

function endsWith($haystack, $needle)
{
    $length = mb_strlen($needle, 'UTF-8');
    return $length === 0 ||
        (mb_substr($haystack, -$length, $length, 'UTF-8') === $needle);
}

How do I pass a variable to the layout using Laravel' Blade templating?

Simplest way to solve:

view()->share('title', 'My Title Here');

Or using view Facade:

use View;

...

View::share('title', 'My Title Here');

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?

In L2S you can add

public partial class NWDataContext
{
    partial void InsertCategory(Category instance)
    {
        if(Instance.Date == null)
            Instance.Data = DateTime.Now;

        ExecuteDynamicInsert(instance);
    }
}

EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.

Android Layout Right Align

This is an example for a RelativeLayout:

RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                relativeLayout.setLayoutParams(params);

With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.

How to fetch JSON file in Angular 2

_x000D_
_x000D_
public init() {_x000D_
    return from(_x000D_
      fetch("assets/server-config.json").then(response => {_x000D_
        return response.json();_x000D_
      })_x000D_
    )_x000D_
      .pipe(_x000D_
        map(config => {_x000D_
          return config;_x000D_
        })_x000D_
      )_x000D_
      .toPromise();_x000D_
  }
_x000D_
_x000D_
_x000D_

Get everything after the dash in a string in JavaScript

For those trying to get everything after the first occurance:

Something like "Nic K Cage" to "K Cage".

You can use slice to get everything from a certain character. In this case from the first space:

const delim = " "
const name = "Nic K Cage"

const end = name.split(delim).slice(1).join(delim) // prints: "K Cage"

Or if OP's string had two hyphens:

const text = "sometext-20202-03"
// Option 1
const op1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const op2 = text.split('-').slice(1).join("-")     // prints: 20202-03

Ruby: Merging variables in to a string

You can use it with your local variables, like this:

@animal = "Dog"
@action = "licks"
@second_animal = "Bird"

"The #{@animal} #{@action} the #{@second_animal}"

the output would be: "The Dog licks the Bird"

MomentJS getting JavaScript Date in UTC

A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.

Here's some code to illustrate. A point is time is captured in three different ways.

var moment = require( 'moment' );

var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );

//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );

//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate  = ' + utcDate );

//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );

Which outputs this:

localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate  = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570

In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).

As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!

Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.

Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate ), and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log calls in the example.

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Unix ls command: show full path when using options

simply use find tool.

find absolute_path

displays full paths on my Linux machine, while

find relative_path

will not.

Eclipse : Failed to connect to remote VM. Connection refused.

when you have Failed to connect to remote VM Connection refused error, restart your eclipse

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

One more possible solution: I have a staging server that serves the site and the Cloudfront assets over HTTP. I had my origin set to "Match Viewer" instead of "HTTP Only". I also use the HTTPS Everywhere extension, which redirected all the http://*.cloudfront.net URLs to the https://* version. Since the staging server isn't available over SSL and Cloudfront was matching the viewer, it couldn't find the assets at https://example.com and cached a bunch of 502s instead.

react-router - pass props to handler component

Just a follow-up to ColCh's answer. It is quite easy to abstract the wrapping of a component:

var React = require('react');

var wrapComponent = function(Component, props) {
  return React.createClass({
    render: function() {
      return React.createElement(Component, props);
    }
  });
};

<Route path="comments" handler={wrapComponent(Comments, {myprop: value})}/>

I haven't tested this solution yet so any feedback is important.

It's important to note that with this method, any props sent via the Router (such as params) get overwritten / removed.

How to print like printf in Python3?

Python 3.6 introduced f-strings for inline interpolation. What's even nicer is it extended the syntax to also allow format specifiers with interpolation. Something I've been working on while I googled this (and came across this old question!):

print(f'{account:40s} ({ratio:3.2f}) -> AUD {splitAmount}')

PEP 498 has the details. And... it sorted my pet peeve with format specifiers in other langs -- allows for specifiers that themselves can be expressions! Yay! See: Format Specifiers.

Use multiple css stylesheets in the same html page

The one you include last will be the one that is used. Note however that if any rules has !important in the first stylesheet they will take priority.

Bootstrap row class contains margin-left and margin-right which creates problems

To remove the margins on all rows:

.row {
    margin: 0px !important;
}

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

add csrf token and your issue will be solved . {{csrf_token}} or @csrf

How to build an APK file in Eclipse?

Right click on the project in Eclipse -> Android tools -> Export without signed key. Connect your device. Mount it by sdk/tools.

Display SQL query results in php

You need to do a while loop to get the result from the SQL query, like this:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

Using group by and having clause

1.Get supplier numbers and names for suppliers of parts supplied to at least two different projects.

 SELECT S.SID, S.NAME
 FROM SUPPLIES SP
 JOIN SUPPLIER S
 ON SP.SID = S.SID
 WHERE PID IN
 (SELECT PID FROM SUPPPLIES GROUP BY PID, JID HAVING COUNT(*) >= 2)

I am not slear about your second question

Java multiline string

Using this library

https://github.com/alessio-santacroce/multiline-string-literals

it is possible to write things like this

System.out.println(newString(/*
      Wow, we finally have
      multiline strings in
      Java! HOOO!
*/));

Very nice and easy, but works only for unit tests

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Thanks to this thread, and especially budidino because his code is what drove it home for me. Just wanted to contribute how to retrieve the JSON data from a request. Make changes to "//create request" request array part of the code to perform different requests. Ultimately, this will output the JSON onto the browser screen

<?php
    function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

function returnTweet(){
    $oauth_access_token         = "2602299919-lP6mgkqAMVwvHM1L0Cplw8idxJzvuZoQRzyMkOx";
    $oauth_access_token_secret  = "wGWny2kz67hGdnLe3Uuy63YZs4nIGs8wQtCU7KnOT5brS";
    $consumer_key               = "zAzJRrPOj5BvOsK5QhscKogVQ";
    $consumer_secret            = "Uag0ujVJomqPbfdoR2UAWbRYhjzgoU9jeo7qfZHCxR6a6ozcu1";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'burownrice',
            'count'             => '3'
        );

    $oauth = array(
        'oauth_consumer_key'        => $consumer_key,
        'oauth_nonce'               => time(),
        'oauth_signature_method'    => 'HMAC-SHA1',
        'oauth_token'               => $oauth_access_token,
        'oauth_timestamp'           => time(),
        'oauth_version'             => '1.0'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
        $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
        $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature']   = $oauth_signature;

    //  make request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        curl_close($feed);

    return $json;
}

$tweet = returnTweet();
echo $tweet;

?>

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

How to add a ScrollBar to a Stackpanel

Stackpanel doesn't have built in scrolling mechanism but you can always wrap the StackPanel in a ScrollViewer

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <StackPanel ... />
</ScrollViewer>

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I've just had an email from a github.com admin stating the following: "We normally advise people to use the HTTPS URL unless they have a specific reason to be using the SSH protocol. HTTPS is secure and easier to set up, so we default to that when a new repository is created."

The password prompt does indeed accept the normal github.com login details. A tutorial on how to set up password caching can be found here. I followed the steps in the tutorial, and it worked for me.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How to convert NSDate into unix timestamp iphone sdk?

You can create a unix timestamp date from a date this way:

NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];

CSS way to horizontally align table

Steven is right, in theory:

the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:

table
{ 
    margin-left: auto;
    margin-right: auto;
}

But the article mentioned in the beginning of this answer gives you all the other way to center a table.

An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:

div.centered 
{
    text-align: center;
}

div.centered table 
{
    margin: 0 auto; 
    text-align: left;
}


<div class="centered">
    <table>
    …
    </table>
</div>

How does JavaScript .prototype work?

It's just that you already have an object with Object.new but you still don't have an object when using the constructor syntax.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

map function for objects (instead of arrays)

you can use map method and forEach on arrays but if you want to use it on Object then you can use it with twist like below:

Using Javascript (ES6)

var obj = { 'a': 2, 'b': 4, 'c': 6 };   
Object.entries(obj).map( v => obj[v[0]] *= v[1] );
console.log(obj); //it will log as {a: 4, b: 16, c: 36}

var obj2 = { 'a': 4, 'b': 8, 'c': 10 };
Object.entries(obj2).forEach( v => obj2[v[0]] *= v[1] );
console.log(obj2); //it will log as {a: 16, b: 64, c: 100}

Using jQuery

var ob = { 'a': 2, 'b': 4, 'c': 6 };
$.map(ob, function (val, key) {
   ob[key] *= val;
});
console.log(ob) //it will log as {a: 4, b: 16, c: 36}

Or you can use other loops also like $.each method as below example:

$.each(ob,function (key, value) {
  ob[key] *= value;
});
console.log(ob) //it will also log as {a: 4, b: 16, c: 36}

Git: How to squash all commits on branch

Since I had some trouble with the solutions proposed here, I want to share a really simple solution (which really works regardless):

git merge origin/master && git reset --soft origin/master

The preceding merge cmd ensures, that no recent changes from master will go on your head (inverted) when committing! After that, just commit the changes and do git push -f

Distinct by property of class with LINQ

Another way to accomplish the same thing...

List<Car> distinticBy = cars
    .Select(car => car.CarCode)
    .Distinct()
    .Select(code => cars.First(car => car.CarCode == code))
    .ToList();

It's possible to create an extension method to do this in a more generic way. It would be interesting if someone could evalute performance of this 'DistinctBy' against the GroupBy approach.

NHibernate.MappingException: No persister for: XYZ

I my case I fetched an entity without await:

var company = _unitOfWork.Session.GetAsync<Company>(id);

and then I tried to delete it:

await _unitOfWork.Session.DeleteAsync(company);

I could not decipher the error message that I'm deleting a Task<Company> instead of Company:

MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]

Java Web Service client basic authentication

If you use JAX-WS, the following works for me:

    //Get Web service Port
    WSTestService wsService = new WSTestService();
    WSTest wsPort = wsService.getWSTestPort();

    // Add username and password for Basic Authentication
    Map<String, Object> reqContext = ((BindingProvider) 
         wsPort).getRequestContext();
    reqContext.put(BindingProvider.USERNAME_PROPERTY, "username");
        reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password");

How to check if a string contains a substring in Bash

I like sed.

substr="foo"
nonsub="$(echo "$string" | sed "s/$substr//")"
hassub=0 ; [ "$string" != "$nonsub" ] && hassub=1

Edit, Logic:

  • Use sed to remove instance of substring from string

  • If new string differs from old string, substring exists

Angular 2: import external js file into component

Instead of including your js file extension in index.html, you can include it in .angular-cli-json file.

These are the steps I followed to get this working:

  1. First include your external js file in assets/js
  2. In .angular-cli.json - add the file path under scripts: [../app/assets/js/test.js]
  3. In the component where you want to use the functions of the js file.

Declare at the top where you want to import the files as

declare const Test:any;

After this you can access its functions as for example Test.add()

Django - Static file not found

TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')

STATICFILES_DIRS=[STATIC_DIR]

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How to filter object array based on attributes?

You can use jQuery.grep() since jQuery 1.0:

$.grep(homes, function (h) {
  return h.price <= 1000
    && h.sqft >= 500
    && h.num_of_beds >= 2
    && h.num_of_baths >= 2.5
});

Cannot use string offset as an array in php

I was able to reproduce this once I upgraded to PHP 7. It breaks when you try to force array elements into a string.

$params = '';
foreach ($foo) {
  $index = 0;
  $params[$index]['keyName'] = $name . '.' . $fileExt;
}

After changing:

$params = '';

to:

$params = array();

I stopped getting the error. I found the solution in this bug report thread. I hope this helps.

How to show uncommitted changes in Git and some Git diffs in detail

How to show uncommitted changes in Git

The command you are looking for is git diff.

git diff - Show changes between commits, commit and working tree, etc


Here are some of the options it expose which you can use

git diff (no parameters)
Print out differences between your working directory and the index.

git diff --cached:
Print out differences between the index and HEAD (current commit).

git diff HEAD:
Print out differences between your working directory and the HEAD.

git diff --name-only
Show only names of changed files.

git diff --name-status
Show only names and status of changed files.

git diff --color-words
Word by word diff instead of line by line.

Here is a sample of the output for git diff --color-words:

enter image description here


enter image description here

Finding the index of an item in a list

All indexes with the zip function:

get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]

print get_indexes(2, [1, 2, 3, 4, 5, 6, 3, 2, 3, 2])
print get_indexes('f', 'xsfhhttytffsafweef')

Can't concatenate 2 arrays in PHP

Both will have a key of 0, and that method of combining the arrays will collapse duplicates. Try using array_merge() instead.

$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')

// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);

If the elements in your array used different keys, the + operator would be more appropriate.

$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');

// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;

Edit: Added a code snippet to clarify

Overlaying histograms with ggplot2 in R

Your current code:

ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)

is telling ggplot to construct one histogram using all the values in f0 and then color the bars of this single histogram according to the variable utt.

What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram, where each one gets it's own data frame and fill:

ggplot(histogram, aes(f0)) + 
    geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
    geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
    geom_histogram(data = highf0, fill = "green", alpha = 0.2) +

Here's a concrete example with some output:

dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))

ggplot(dat,aes(x=xx)) + 
    geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)

which produces something like this:

enter image description here

Edited to fix typos; you wanted fill, not colour.

MySQL - Rows to Columns

I edit Agung Sagita's answer from subquery to join. I'm not sure about how much difference between this 2 way, but just for another reference.

SELECT  hostid, T2.VALUE AS A, T3.VALUE AS B, T4.VALUE AS C
FROM TableTest AS T1
LEFT JOIN TableTest T2 ON T2.hostid=T1.hostid AND T2.ITEMNAME='A'
LEFT JOIN TableTest T3 ON T3.hostid=T1.hostid AND T3.ITEMNAME='B'
LEFT JOIN TableTest T4 ON T4.hostid=T1.hostid AND T4.ITEMNAME='C'

JSON Stringify changes time of date because of UTC

JSON uses the Date.prototype.toISOString function which does not represent local time -- it represents time in unmodified UTC -- if you look at your date output you can see you're at UTC+2 hours, which is why the JSON string changes by two hours, but if this allows the same time to be represented correctly across multiple time zones.

sequelize findAll sort order in nodejs

If you are using MySQL, you can use order by FIELD(id, ...) approach:

Company.findAll({
    where: {id : {$in : companyIds}},
    order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})

Keep in mind, it might be slow. But should be faster, than manual sorting with JS.

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

How to convert/parse from String to char in java?

You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String. If the string is 1 character long, just take that character by calling .charAt(0) (or .First() in C#).

What is a good alternative to using an image map generator?

I have found Adobe Dreamweaver to be quite good at that. However, it's not free.

Adding devices to team provisioning profile

After adding UDID in developer.apple.com, do the following steps:

1, Go to Xcode, open Preferences (cmd + ,) -> Accounts -> Click your Apple ID -> View Details enter image description here

2, In the new window, click on "Refresh", then "Request" enter image description here

3, Now try to run your app on the new device, if you get an error saying "unfound provisioning profile", keep reading

4, Click on your project enter image description here

6, Find "Fix It" button in Identity section, click it enter image description here

7, Now try to run again, it should work

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

Passing command line arguments from Maven as properties in pom.xml

I used the properties plugin to solve this.

Properties are defined in the pom, and written out to a my.properties file, where they can then be accessed from your Java code.

In my case it is test code that needs to access this properties file, so in the pom the properties file is written to maven's testOutputDirectory:

<configuration>
    <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>

Use outputDirectory if you want properties to be accessible by your app code:

<configuration>
    <outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>

For those looking for a fuller example (it took me a bit of fiddling to get this working as I didn't understand how naming of properties tags affects ability to retrieve them elsewhere in the pom file), my pom looks as follows:

<dependencies>
     <dependency>
      ...
     </dependency>
</dependencies>

<properties>
    <app.env>${app.env}</app.env>
    <app.port>${app.port}</app.port>
    <app.domain>${app.domain}</app.domain>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20</version>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0.0</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>write-project-properties</goal>
                    </goals>
                    <configuration>
                        <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

And on the command line:

mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901

So these properties can be accessed from the Java code:

 java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
 java.util.Properties properties = new Properties();
 properties.load(inputStream);
 appPort = properties.getProperty("app.port");
 appDomain = properties.getProperty("app.domain");

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

I was also getting the same error --> "[PDOException] could not find driver "

I realized that the php was pointing to /usr/bin/php instead of the lampp /opt/lampp/bin/php so i simply created and alias

alias php="/opt/lampp/bin/php"

also had to make update to the .env file to ensure the database access credentials were updated.

And guess what, it Worked!

List<Map<String, String>> vs List<? extends Map<String, String>>

As you mentioned, there could be two below versions of defining a List:

  1. List<? extends Map<String, String>>
  2. List<?>

2 is very open. It can hold any object type. This may not be useful in case you want to have a map of a given type. In case someone accidentally puts a different type of map, for example, Map<String, int>. Your consumer method might break.

In order to ensure that List can hold objects of a given type, Java generics introduced ? extends. So in #1, the List can hold any object which is derived from Map<String, String> type. Adding any other type of data would throw an exception.

Cannot push to GitHub - keeps saying need merge

This problem is usually caused by creating a readme.md file, which is counted as a commit, is not synchronized locally on the system, and is lacking behind the head, hence, it shows a git pull request. You can try avoiding the readme file and then try to commit. It worked in my case.

jQuery: Selecting by class and input type

Try this:

$("input:checkbox").hasClass("myClass");

How to detect when facebook's FB.init is complete

While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.

It can be used like so:

f52.fb.ready(function() {
    // safe to use FB here
});

Here's the source file (note that it's defined within a 'f52.fb' namespace).

if (typeof(f52) === 'undefined') { f52 = {}; }
f52.fb = (function () {

    var fbAppId = f52.inputs.base.fbAppId,
        fbApiInit = false;

    var awaitingReady = [];

    var notifyQ = function() {
        var i = 0,
            l = awaitingReady.length;
        for(i = 0; i < l; i++) {
            awaitingReady[i]();
        }
    };

    var ready = function(cb) {
        if (fbApiInit) {
            cb();
        } else {
            awaitingReady.push(cb);
        }
    };

    window.fbAsyncInit = function() {
        FB.init({
            appId: fbAppId,
            xfbml: true,
            version: 'v2.0'
        });

        FB.getLoginStatus(function(response){
            fbApiInit = true;
            notifyQ();
        });
    };

    return {
        /**
         * Fires callback when FB is initialized and ready for api calls.
         */
        'ready': ready
    };

})();

Split a large dataframe into a list of data frames based on common value in column

You can just as easily access each element in the list using e.g. path[[1]]. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply functions to further operate on each element in the list. Example below.

#  For reproducibile data
set.seed(1)

#  Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )

#  Split on userid
out <- split( df , f = df$userid )
#$`1`
#  userid data1 data2
#1      1   gjn     3
#3      1   yqp     1
#5      1   rjs     6
#7      1   jtw     5

#$`2`
#  userid data1 data2
#2      2   xfv     4
#4      2   bfe    10
#6      2   mrx     2
#8      2   fqd     9

Access each element using the [[ operator like this:

out[[1]]
#  userid data1 data2
#1      1   gjn     3
#3      1   yqp     1
#5      1   rjs     6
#7      1   jtw     5

Or use an *apply function to do further operations on each list element. For instance, to take the mean of the data2 column you could use sapply like this:

sapply( out , function(x) mean( x$data2 ) )
#   1    2 
#3.75 6.25 

How to compute the similarity between two text documents?

For Syntactic Similarity There can be 3 easy ways of detecting similarity.

  • Word2Vec
  • Glove
  • Tfidf or countvectorizer

For Semantic Similarity One can use BERT Embedding and try a different word pooling strategies to get document embedding and then apply cosine similarity on document embedding.

An advanced methodology can use BERT SCORE to get similarity. BERT SCORE

Research Paper Link: https://arxiv.org/abs/1904.09675

Apache giving 403 forbidden errors

You can try disabling selinux and try once again using the following command

setenforce 0

How can I specify a [DllImport] path at runtime?

Even better than Ran's suggestion of using GetProcAddress, simply make the call to LoadLibrary before any calls to the DllImport functions (with only a filename without a path) and they'll use the loaded module automatically.

I've used this method to choose at runtime whether to load a 32-bit or 64-bit native DLL without having to modify a bunch of P/Invoke-d functions. Stick the loading code in a static constructor for the type that has the imported functions and it'll all work fine.

Round up to Second Decimal Place in Python

Extrapolating from Edwin's answer:

from math import ceil, floor
def float_round(num, places = 0, direction = floor):
    return direction(num * (10**places)) / float(10**places)

To use:

>>> float_round(0.21111, 3, ceil)  #round up
>>> 0.212
>>> float_round(0.21111, 3)        #round down
>>> 0.211
>>> float_round(0.21111, 3, round) #round naturally
>>> 0.211

Virtual Serial Port for Linux

Use socat for this:

For example:

socat PTY,link=/dev/ttyS10 PTY,link=/dev/ttyS11

How to print a groupby object

Simply do:

grouped_df = df.groupby('A')

for key, item in grouped_df:
    print(grouped_df.get_group(key), "\n\n")

This also works,

grouped_df = df.groupby('A')    
gb = grouped_df.groups

for key, values in gb.iteritems():
    print(df.ix[values], "\n\n")

For selective key grouping: Insert the keys you want inside the key_list_from_gb, in following, using gb.keys(): For Example,

gb = grouped_df.groups
gb.keys()

key_list_from_gb = [key1, key2, key3]

for key, values in gb.items():
    if key in key_list_from_gb:
        print(df.ix[values], "\n")

How to center an iframe horizontally?

In my case solution was on iframe class adding:

    display: block;
    margin-right: auto;
    margin-left: auto;

How to capture the "virtual keyboard show/hide" event in Android?

I solve this by overriding onKeyPreIme(int keyCode, KeyEvent event) in my custom EditText.

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
        //keyboard will be hidden
    }
}

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

Activity has leaked window that was originally added

I was having the same problem and found this page, and while my situation was different I called finish from a if block before it defined the alert box.

So, simply calling dismiss wouldn't work (as it hasn't been made yet) but after reading Alex Volovoy's answer and realizing it was the alert box causing it. I tried to add a return statement right after the finish inside that if block and that fixed the issue.

I thought once you called finish it stopped everything and finished right there, but it doesn't. It seem to go to the end of the block of code it's in then finishes.

So, if you want to implement a situation where sometimes it'll finish before doing some code you do gotta put a return statement right after the finish or it'll keep on going and and act like the finish was called at the end of the block of code not where you called it. Which is why I was getting all those weird errors.

private picked(File aDirectory){
     if(aDirectory.length()==0){
        setResult(RESULT_CANCELED, new Intent()); 
        finish(); 
        return;
    }
     AlertDialog.Builder alert= new AlertDialog.Builder(this); // Start dialog builder
     alert
        .setTitle("Question")
        .setMessage("Do you want to open that file?"+aDirectory.getName());
    alert
        .setPositiveButton("OK", okButtonListener)
        .setNegativeButton("Cancel", cancelButtonListener);
    alert.show();
}

If you don't put the return right after I called finish in there, it will act as if you have called it after the alert.show(); and hence it would say that the window is leaked by finishing just after you made the dialog appear, even though that's not the case, it still think it is.

I thought I'd add this as here as this shows the finish command acted differently then I thought it did and I'd guess there are other people who think the same as I did before I discovered this.

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

phpmailer - The following SMTP Error: Data not accepted

Over a certain message of size, it messes up the content when setting through $mail->Body.

You can test it, if it works well with small messages, but doesn't work with larger (over 4-6 kB), then this is the problem.

It seems to be the problem of $mail->Body, so you can get around this by setting the HTML body manually via $mail->MsgHTML($message). And then you can try to only add the non-html body by $mail->AltBody.

Hope that I could help, feel free to provide more details, information.

Simple timeout in java

Nowadays you can use

try {
    String s = CompletableFuture.supplyAsync(() -> br.readLine())
                                .get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
    // Handle
}

What is Python buffer type for?

An example usage:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

PHP foreach loop through multidimensional array

$last = count($arr_nav) - 1;

foreach ($arr_nav as $i => $row)
{
    $isFirst = ($i == 0);
    $isLast = ($i == $last);

    echo ... $row['name'] ... $row['url'] ...;
}

Java recursive Fibonacci sequence

Most of solutions offered here run in O(2^n) complexity. Recalculating identical nodes in recursive tree is inefficient and wastes CPU cycles.

We can use memoization to make fibonacci function run in O(n) time

public static int fibonacci(int n) {
    return fibonacci(n, new int[n + 1]);
}

public static int fibonacci(int i, int[] memo) {

    if (i == 0 || i == 1) {
        return i;
    }

    if (memo[i] == 0) {
        memo[i] = fibonacci(i - 1, memo) + fibonacci(i - 2, memo);
    }
    return memo[i];
}

If we follow Bottom-Up Dynamic Programming route, below code is simple enough to compute fibonacci:

public static int fibonacci1(int n) {
    if (n == 0) {
        return n;
    } else if (n == 1) {
        return n;
    }
    final int[] memo = new int[n];

    memo[0] = 0;
    memo[1] = 1;

    for (int i = 2; i < n; i++) {
        memo[i] = memo[i - 1] + memo[i - 2];
    }
    return memo[n - 1] + memo[n - 2];
}

What is mapDispatchToProps?

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component.

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read.

https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments

Linq to Entities - SQL "IN" clause

You need to turn it on its head in terms of the way you're thinking about it. Instead of doing "in" to find the current item's user rights in a predefined set of applicable user rights, you're asking a predefined set of user rights if it contains the current item's applicable value. This is exactly the same way you would find an item in a regular list in .NET.

There are two ways of doing this using LINQ, one uses query syntax and the other uses method syntax. Essentially, they are the same and could be used interchangeably depending on your preference:

Query Syntax:

var selected = from u in users
               where new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights)
               select u

foreach(user u in selected)
{
    //Do your stuff on each selected user;
}

Method Syntax:

var selected = users.Where(u => new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights));

foreach(user u in selected)
{
    //Do stuff on each selected user;
}

My personal preference in this instance might be method syntax because instead of assigning the variable, I could do the foreach over an anonymous call like this:

foreach(User u in users.Where(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}

Syntactically this looks more complex, and you have to understand the concept of lambda expressions or delegates to really figure out what's going on, but as you can see, this condenses the code a fair amount.

It all comes down to your coding style and preference - all three of my examples do the same thing slightly differently.

An alternative way doesn't even use LINQ, you can use the same method syntax replacing "where" with "FindAll" and get the same result, which will also work in .NET 2.0:

foreach(User u in users.FindAll(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}

How to invoke the super constructor in Python?

With Python 2.x old-style classes it would be this:

class A: 
 def __init__(self): 
   print "world" 

class B(A): 
 def __init__(self): 
   print "hello" 
   A.__init__(self)

How to disable Google Chrome auto update?

  1. On your Chrome browser's address bar, type in 'about:plugins' and hit ENTER.

  2. Find the plugin called 'Google Update' and click disable.

  3. Restart your browser for the changes to take effect.

Delayed function calls

It sounds like the control of the creation of both these objects and their interdependence needs to controlled externally, rather than between the classes themselves.

How can I dynamically switch web service addresses in .NET without a recompile?

open solition explorer

right click the webservice change URL Behavior to Dynamic

click the 'show all files' icon in solution explorer

in the web reference edit the Reference.cs file

change constructer

public Service1() {
        this.Url = "URL"; // etc. string  variable this.Url = ConfigClass.myURL
      }

Disable color change of anchor tag when visited

I think if I set a color for a:visited it is not good: you must know the default color of tag a and every time synchronize it with a:visited.

I don't want know about the default color (it can be set in common.css of your application, or you can using outside styles).

I think it's nice solution:

HTML:

<body>
    <a class="absolute">Test of URL</a>
    <a class="unvisited absolute" target="_blank" href="google.ru">Test of URL</a>
</body>

CSS:

.absolute{
    position: absolute;
}
a.unvisited, a.unvisited:visited, a.unvisited:active{
    text-decoration: none;
    color: transparent;
}

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object

redirect while passing arguments

I found that none of the answers here applied to my specific use case, so I thought I would share my solution.

I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:

/app/4903294/my-great-car?email=coolguy%40gmail.com to

/public/4903294/my-great-car?email=coolguy%40gmail.com

Here's the solution that worked for me.

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))

Hope this helps someone!

How do I compile C++ with Clang?

The command clang is for C, and the command clang++ is for C++.

Program to find prime numbers

You can do this faster using a nearly optimal trial division sieve in one (long) line like this:

Enumerable.Range(0, Math.Floor(2.52*Math.Sqrt(num)/Math.Log(num))).Aggregate(
    Enumerable.Range(2, num-1).ToList(), 
    (result, index) => { 
        var bp = result[index]; var sqr = bp * bp;
        result.RemoveAll(i => i >= sqr && i % bp == 0); 
        return result; 
    }
);

The approximation formula for number of primes used here is p(x) < 1.26 x / ln(x). We only need to test by primes not greater than x = sqrt(num).

Note that the sieve of Eratosthenes has much better run time complexity than trial division (should run much faster for bigger num values, when properly implemented).

Is JavaScript a pass-by-reference or pass-by-value language?

My two cents... This is the way I understand it. (Feel free to correct me if I'm wrong)

It's time to throw out everything you know about pass by value / reference.

Because in JavaScript, it doesn't matter whether it's passed by value or by reference or whatever. What matters is mutation vs assignment of the parameters passed into a function.

OK, let me do my best to explain what I mean. Let's say you have a few objects.

var object1 = {};
var object2 = {};

What we have done is "assignment"... We've assigned 2 separate empty objects to the variables "object1" and "object2".

Now, let's say that we like object1 better... So, we "assign" a new variable.

var favoriteObject = object1;

Next, for whatever reason, we decide that we like object 2 better. So, we do a little re-assignment.

favoriteObject = object2;

Nothing happened to object1 or to object2. We haven't changed any data at all. All we did was re-assign what our favorite object is. It is important to know that object2 and favoriteObject are both assigned to the same object. We can change that object via either of those variables.

object2.name = 'Fred';
console.log(favoriteObject.name) // Logs Fred
favoriteObject.name = 'Joe';
console.log(object2.name); // Logs Joe

OK, now let's look at primitives like strings for example

var string1 = 'Hello world';
var string2 = 'Goodbye world';

Again, we pick a favorite.

var favoriteString = string1;

Both our favoriteString and string1 variables are assigned to 'Hello world'. Now, what if we want to change our favoriteString??? What will happen???

favoriteString = 'Hello everyone';
console.log(favoriteString); // Logs 'Hello everyone'
console.log(string1); // Logs 'Hello world'

Uh oh.... What has happened. We couldn't change string1 by changing favoriteString... Why?? Because we didn't change our string object. All we did was "RE ASSIGN" the favoriteString variable to a new string. This essentially disconnected it from string1. In the previous example, when we renamed our object, we didn't assign anything. (Well, not to the variable itself, ... we did, however, assign the name property to a new string.) Instead, we mutated the object which keeps the connections between the 2 variables and the underlying objects. (Even if we had wanted to modify or mutate the string object itself, we couldn't have, because strings are actually immutable in JavaScript.)

Now, on to functions and passing parameters.... When you call a function, and pass a parameter, what you are essentially doing is an "assignment" to a new variable, and it works exactly the same as if you assigned using the equal (=) sign.

Take these examples.

var myString = 'hello';

// Assign to a new variable (just like when you pass to a function)
var param1 = myString;
param1 = 'world'; // Re assignment

console.log(myString); // Logs 'hello'
console.log(param1);   // Logs 'world'

Now, the same thing, but with a function

function myFunc(param1) {
    param1 = 'world';

    console.log(param1);   // Logs 'world'
}

var myString = 'hello';
// Calls myFunc and assigns param1 to myString just like param1 = myString
myFunc(myString);

console.log(myString); // logs 'hello'

OK, now let’s give a few examples using objects instead... first, without the function.

var myObject = {
    firstName: 'Joe',
    lastName: 'Smith'
};

// Assign to a new variable (just like when you pass to a function)
var otherObj = myObject;

// Let's mutate our object
otherObj.firstName = 'Sue'; // I guess Joe decided to be a girl

console.log(myObject.firstName); // Logs 'Sue'
console.log(otherObj.firstName); // Logs 'Sue'

// Now, let's reassign the variable
otherObj = {
    firstName: 'Jack',
    lastName: 'Frost'
};

// Now, otherObj and myObject are assigned to 2 very different objects
// And mutating one object has no influence on the other
console.log(myObject.firstName); // Logs 'Sue'
console.log(otherObj.firstName); // Logs 'Jack';

Now, the same thing, but with a function call

function myFunc(otherObj) {

    // Let's mutate our object
    otherObj.firstName = 'Sue';
    console.log(otherObj.firstName); // Logs 'Sue'

    // Now let's re-assign
    otherObj = {
        firstName: 'Jack',
        lastName: 'Frost'
    };
    console.log(otherObj.firstName); // Logs 'Jack'

    // Again, otherObj and myObject are assigned to 2 very different objects
    // And mutating one object doesn't magically mutate the other
}

var myObject = {
    firstName: 'Joe',
    lastName: 'Smith'
};

// Calls myFunc and assigns otherObj to myObject just like otherObj = myObject
myFunc(myObject);

console.log(myObject.firstName); // Logs 'Sue', just like before

OK, if you read through this entire post, perhaps you now have a better understanding of how function calls work in JavaScript. It doesn't matter whether something is passed by reference or by value... What matters is assignment vs mutation.

Every time you pass a variable to a function, you are "Assigning" to whatever the name of the parameter variable is, just like if you used the equal (=) sign.

Always remember that the equals sign (=) means assignment. Always remember that passing a parameter to a function in JavaScript also means assignment. They are the same and the 2 variables are connected in exactly the same way (which is to say they aren't, unless you count that they are assigned to the same object).

The only time that "modifying a variable" affects a different variable is when the underlying object is mutated (in which case you haven't modified the variable, but the object itself.

There is no point in making a distinction between objects and primitives, because it works the same exact way as if you didn't have a function and just used the equal sign to assign to a new variable.

The only gotcha is when the name of the variable you pass into the function is the same as the name of the function parameter. When this happens, you have to treat the parameter inside the function as if it was a whole new variable private to the function (because it is)

function myFunc(myString) {
    // myString is private and does not affect the outer variable
    myString = 'hello';
}

var myString = 'test';
myString = myString; // Does nothing, myString is still 'test';

myFunc(myString);
console.log(myString); // Logs 'test'

How to use cURL in Java?

The Runtime object allows you to execute external command line applications from Java and would therefore allow you to use cURL however as the other answers indicate there is probably a better way to do what you are trying to do. If all you want to do is download a file the URL object will work great.

Creating an instance of class

  1. Allocates some dynamic memory from the free store, and creates an object in that memory using its default constructor. You never delete it, so the memory is leaked.
  2. Does exactly the same as 1; in the case of user-defined types, the parentheses are optional.
  3. Allocates some automatic memory, and creates an object in that memory using its default constructor. The memory is released automatically when the object goes out of scope.
  4. Similar to 3. Notionally, the named object foo4 is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.
  5. Allocates a dynamic object, then initialises a second by copying the first. Both objects are leaked; and there's no way to delete the first since you don't keep a pointer to it.
  6. Does exactly the same as 5.
  7. Does not compile. Foo foo5 is a declaration, not an expression; function (and constructor) arguments must be expressions.
  8. Creates a temporary object, and initialises a dynamic object by copying it. Only the dynamic object is leaked; the temporary is destroyed automatically at the end of the full expression. Note that you can create the temporary with just Foo() rather than the equivalent Foo::Foo() (or indeed Foo::Foo::Foo::Foo::Foo())

When do I use each?

  1. Don't, unless you like unnecessary decorations on your code.
  2. When you want to create an object that outlives the current scope. Remember to delete it when you've finished with it, and learn how to use smart pointers to control the lifetime more conveniently.
  3. When you want an object that only exists in the current scope.
  4. Don't, unless you think 3 looks boring and what to add some unnecessary decoration.
  5. Don't, because it leaks memory with no chance of recovery.
  6. Don't, because it leaks memory with no chance of recovery.
  7. Don't, because it won't compile
  8. When you want to create a dynamic Bar from a temporary Foo.

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

How to discard local commits in Git?

As an aside, apart from the answer by mipadi (which should work by the way), you should know that doing:

git branch -D master
git checkout master

also does exactly what you want without having to redownload everything (your quote paraphrased). That is because your local repo contains a copy of the remote repo (and that copy is not the same as your local directory, it is not even the same as your checked out branch).

Wiping out a branch is perfectly safe and reconstructing that branch is very fast and involves no network traffic. Remember, git is primarily a local repo by design. Even remote branches have a copy on the local. There's only a bit of metadata that tells git that a specific local copy is actually a remote branch. In git, all files are on your hard disk all the time.

If you don't have any branches other than master, you should:

git checkout -b 'temp'
git branch -D master
git checkout master
git branch -D temp

javax.persistence.NoResultException: No entity found for query

Yes. You need to use the try/catch block, but no need to catch the Exception. As per the API it will throw NoResultException if there is no result, and its up to you how you want to handle it.

DrawUnusedBalance drawUnusedBalance = null;
try{
drawUnusedBalance = (DrawUnusedBalance)query.getSingleResult()
catch (NoResultException nre){
//Ignore this because as per your logic this is ok!
}

if(drawUnusedBalance == null){
 //Do your logic..
}

google maps v3 marker info window on mouseover

var icon1 = "imageA.png";
var icon2 = "imageB.png";

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: icon1,
    title: "some marker"
});

google.maps.event.addListener(marker, 'mouseover', function() {
    marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
    marker.setIcon(icon1);
});

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

Setting the character encoding in form submit for Internet Explorer

I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.

Looks like IE can't handle ISO-8859-1. But it can handle ISO-8859-15.

<form accept-charset="ISO-8859-15">
  ...
</form>

So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.

bash "if [ false ];" returns true instead of false -- why?

Adding context to hopefully help provide a bit of additional clarity on this subject. To a BaSH newbie, it's sense of true/false statements is rather odd. Take the following simple examples and their results.

This statement will return "true":

foo=" "; if [ "$foo" ]; then echo "true"; else echo "false"; fi

But this will return "false":

foo=" "; if [ $foo ]; then echo "true"; else echo "false"; fi

Do you see why? The first example has a quoted "" string. This causes BaSH to treat it literally. So, in a literal sense, a space is not null. While in a non-literal sense (the 2nd example above), a space is viewed by BaSH (as a value in $foo) as 'nothing' and therefore it equates to null (interpreted here as 'false').

These statements will all return a text string of "false":

foo=; if [ $foo ]; then echo "true"; else echo "false"; fi
foo=; if [ "$foo" ]; then echo "true"; else echo "false"; fi
foo=""; if [ $foo ]; then echo "true"; else echo "false"; fi
foo=""; if [ "$foo" ]; then echo "true"; else echo "false"; fi

Interestingly, this type of conditional will always return true:

These statements will all return a result of "true":

foo=""; if [ foo ]; then echo "true"; else echo "false"; fi

Notice the difference; the $ symbol has been omitted from preceding the variable name in the conditional. It doesn't matter what word you insert between the brackets. BaSH will always see this statement as true, even if you use a word that has never been associated with a variable in the same shell before.

if [ sooperduper ]; then echo "true"; else echo "false"; fi

Likewise, defining it as an undeclared variable ensures it will always return false:

if [ $sooperduper ]; then echo "true"; else echo "false"; fi

As to BaSH it's the same as writing:

sooperduper="";if [ $sooperduper ]; then echo "true"; else echo "false"; fi

One more tip....

Brackets vs No Brackets

Making matters more confusing, these variations on the IF/THEN conditional both work, but return opposite results.

These return false:

if [ $foo ]; then echo "true"; else echo "false"; fi
if [ ! foo ]; then echo "true"; else echo "false"; fi

However, these will return a result of true:

if $foo; then echo "true"; else echo "false"; fi
if [ foo ]; then echo "true"; else echo "false"; fi
if [ ! $foo ]; then echo "true"; else echo "false"; fi

And, of course this returns a syntax error (along with a result of 'false'):

if foo; then echo "true"; else echo "false"; fi

Confused yet? It can be quite challenging to keep it straight in your head in the beginning, especially if you're used to other, higher level programming languages.

Select first empty cell in column F starting from row 1. (without using offset )

If all you're trying to do is select the first blank cell in a given column, you can give this a try:

Code:

Public Sub SelectFirstBlankCell()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 6   'column F has a value of 6
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
        End If
    Next
End Sub

Before Selection - first blank cell to select:

enter image description here

After Selection:

enter image description here

Executing <script> elements inserted with .innerHTML

Here is my solution in a recent project.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Sample</title>_x000D_
</head>_x000D_
<body>_x000D_
<h1 id="hello_world">Sample</h1>_x000D_
<script type="text/javascript">_x000D_
 var div = document.createElement("div");_x000D_
  var t = document.createElement('template');_x000D_
  t.innerHTML =  "Check Console tab for javascript output: Hello world!!!<br/><script type='text/javascript' >console.log('Hello world!!!');<\/script>";_x000D_
  _x000D_
  for (var i=0; i < t.content.childNodes.length; i++){_x000D_
    var node = document.importNode(t.content.childNodes[i], true);_x000D_
    div.appendChild(node);_x000D_
  }_x000D_
 document.body.appendChild(div);_x000D_
</script>_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Configuring RollingFileAppender in log4j

Toolbear74 is right log4j.XML is required. In order to get the XML to validate the <param> tags need to be BEFORE the <rollingPolicy> I suggest setting a logging threshold <param name="threshold" value="info"/>

When Creating a Log4j.xml file don't forget to to copy the log4j.dtd into the same location.

Here is an example:

<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<!-- Daily Rolling File Appender that compresses old files -->
  <appender name="file" class="org.apache.log4j.rolling.RollingFileAppender" >
     <param name="threshold" value="info"/>
     <rollingPolicy name="file"  
                      class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" 
               value="${catalina.base}/logs/myapp.log.%d{yyyy-MM-dd}.gz"/>
        <param name="ActiveFileName" value="${catalina.base}/logs/myapp.log"/>
     </rollingPolicy>
     <layout class="org.apache.log4j.EnhancedPatternLayout" >
        <param name="ConversionPattern" 
               value="%d{ISO8601} %-5p - %-26.26c{1} - %m%n" />
    </layout>
  </appender>

  <root>
    <priority value="debug"></priority>
    <appender-ref ref="file" />
  </root>
</log4j:configuration>

Considering that your setting a FileNamePattern and an ActiveFileName I think that setting a File property is redundant and possibly even erroneous

Try renaming your log4j.properties and dropping in a log4j.xml similar to my example and see what happens.

Convert a RGB Color Value to a Hexadecimal String

A one liner but without String.format for all RGB colors:

Color your_color = new Color(128,128,128);

String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);

You can add a .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

When you have ARGB colors you can use:

Color your_color = new Color(128,128,128,128);

String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);

A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format():

enter image description here

Oracle comparing timestamp with date

You can truncate the date

SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')

Look at the SQL Fiddle for more examples.

How can I know if a process is running?

Maybe (probably) I am reading the question wrongly, but are you looking for the HasExited property that will tell you that the process represented by your Process object has exited (either normally or not).

If the process you have a reference to has a UI you can use the Responding property to determine if the UI is currently responding to user input or not.

You can also set EnableRaisingEvents and handle the Exited event (which is sent asychronously) or call WaitForExit() if you want to block.

Stretch child div height to fill parent that has dynamic height

You can do it easily with a bit of jQuery

$(document).ready(function(){
  var parentHeight = $("#parentDiv").parent().height();
  $("#childDiv").height(parentHeight);
});

Why does Java's hashCode() in String use 31 as a multiplier?

In latest version of JDK, 31 is still used. https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html#hashCode()

The purpose of hash string is

  • unique (Let see operator ^ in hashcode calculation document, it help unique)
  • cheap cost for calculating

31 is max value can put in 8 bit (= 1 byte) register, is largest prime number can put in 1 byte register, is odd number.

Multiply 31 is <<5 then subtract itself, therefore need cheap resources.

MVC 4 Data Annotations "Display" Attribute

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
    [Display(Name = "Basic Name")]
    public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
    [Display(Name = "Customized Inherited Name")]
    public override string Name { get; set; }
}

I'll admit that that example is pretty contrived...

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

How to properly add cross-site request forgery (CSRF) token using PHP

The variable $token is not being retrieved from the session when it's in there

Custom checkbox image android

If you use androidx.appcompat:appcompat and want a custom drawable (of type selector with android:state_checked) to work on old platform versions in addition to new platform versions, you need to use

    <CheckBox
        app:buttonCompat="@drawable/..."

instead of

    <CheckBox
        android:button="@drawable/..."

split string in two on given index and return both parts

Try this

_x000D_
_x000D_
function split_at_index(value, index)
{
 return value.substring(0, index) + "," + value.substring(index);
}

console.log(split_at_index('3123124', 2));
_x000D_
_x000D_
_x000D_

Google Maps Android API v2 Authorization failure

Just Add this into your manifest file:

**<uses-library android:name="com.google.android.maps" />**

For Example...

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name" >
    <uses-library android:name="com.google.android.maps" />

    <activity
        android:name=".California"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And please update your google play service lib...Go to Window -> Android sdk manager->update google play service...installed it..delete old one and keep this one. Take this from ANDROID-SDK-DIRECTORY/extras/google/google_play_services/

Thanks..Please vote up

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

If you are using Visual Studio 2017, 2019, you can:

  1. open the main .gitignore (update or remove anothers .gitignore files in others projects in the solution)
  2. paste the below code:
[core]
 autocrlf = false
[filter "lfs"]
 required = true
 clean = git-lfs clean -- %f
 smudge = git-lfs smudge -- %f
 process = git-lfs filter-process

How can I detect browser type using jQuery?

Try to use it

$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){ 
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});

How do I check/uncheck all checkboxes with a button using jQuery?

I know this question is old but, I noticed most people are using a checkbox. The accepted answer uses a button, but cannot work with several buttons (ex. one at top of page one at bottom). So here is a modification that does both.

HTML

<a href="#" class="check-box-machine my-button-style">Check All</a>

jQuery

var ischecked = false;
$(".check-box-machine").click(function(e) {
    e.preventDefault();
    if (ischecked == false) {
        $("input:checkbox").attr("checked","checked");
        $(".check-box-machine").html("Uncheck All");
        ischecked = true;
    } else {
        $("input:checkbox").removeAttr("checked");
        $(".check-box-machine").html("Check All");
        ischecked = false;
    }
});

This will allow you to have as many buttons as you would like with changing text and checkbox values. I included an e.preventDefault() call because this will stop the page from jumping to the top due to the href="#" part.

set initial viewcontroller in appdelegate - swift

I find this answer helpful and works perfectly for my case when i needed to change the rootviewcontroller if my app user already exist in the keychain or userdefault.

https://stackoverflow.com/a/58413582/6596443

Using 24 hour time in bootstrap timepicker

"YYYY-MM-DD HH:mm:ss" => 24 hours format;

"YYYY-MM-DD hh:mm:ss" => 12 hours format;

the difference is letter 'H'

Deep copy an array in Angular 2 + TypeScript

The only solution I've found (almost instantly after posting the question), is to loop through the array and use Object.assign()

Like this:

public duplicateArray() {
  let arr = [];
  this.content.forEach((x) => {
    arr.push(Object.assign({}, x));
  })
  arr.map((x) => {x.status = DEFAULT});
  return this.content.concat(arr);
}

I know this is not optimal. And I wonder if there's any better solutions.

MongoDB: Is it possible to make a case-insensitive query?

I had faced a similar issue and this is what worked for me:

  const flavorExists = await Flavors.findOne({
    'flavor.name': { $regex: flavorName, $options: 'i' },
  });

How to disable Hyper-V in command line?

you can use my script. paste code lines to notepad and save as vbs(for example switch_hypervisor.vbs)

Option Explicit

Dim backupfile
Dim record
Dim myshell
Dim appmyshell
Dim myresult
Dim myline
Dim makeactive
Dim makepassive
Dim reboot
record=""
Set myshell = WScript.CreateObject("WScript.Shell")

If WScript.Arguments.Length = 0 Then
    Set appmyshell  = CreateObject("Shell.Application")
    appmyshell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
    WScript.Quit
End if




Set backupfile = CreateObject("Scripting.FileSystemObject")
If Not (backupfile.FileExists("C:\bcdedit.bak")) Then
    Set myresult = myshell.Exec("cmd /c bcdedit /export c:\bcdedit.bak")
End If

Set myresult = myshell.Exec("cmd /c bcdedit")
Do While Not myresult.StdOut.AtEndOfStream
    myline = myresult.StdOut.ReadLine()

    If myline="The boot configuration data store could not be opened." Then
        record=""
        exit do
    End If
    If Instr(myline, "identifier") > 0 Then
        record=""
        If Instr(myline, "{current}") > 0 Then
            record="current"
        End If
    End If
    If Instr(myline, "hypervisorlaunchtype") > 0 And record = "current" Then
        If Instr(myline, "Auto") > 0 Then
            record="1"
            Exit Do
        End If
        If Instr(myline, "On") > 0 Then
            record="1"
            Exit Do
        End If
        If Instr(myline, "Off") > 0 Then
            record="0"
            Exit Do
        End If
    End If
Loop

If record="1" Then
    makepassive = MsgBox ("Hypervisor status is active, do you want set to passive? ", vbYesNo, "Hypervisor")
    Select Case makepassive
    Case vbYes
        myshell.run "cmd.exe /C  bcdedit /set hypervisorlaunchtype off"
        reboot = MsgBox ("Hypervisor chenged to passive; Computer must reboot. Reboot now? ", vbYesNo, "Hypervisor")
        Select Case reboot
            Case vbYes
                myshell.run "cmd.exe /C  shutdown /r /t 0"
        End Select
    Case vbNo
        MsgBox("Not Changed")
    End Select
End If

If record="0" Then
    makeactive = MsgBox ("Hypervisor status is passive, do you want set active? ", vbYesNo, "Hypervisor")
    Select Case makeactive
    Case vbYes
        myshell.run "cmd.exe /C  bcdedit /set hypervisorlaunchtype auto"
        reboot = MsgBox ("Hypervisor changed to active;  Computer must reboot. Reboot now?", vbYesNo, "Hypervisor")
        Select Case reboot
            Case vbYes
                myshell.run "cmd.exe /C  shutdown /r /t 0"
        End Select
    Case vbNo
        MsgBox("Not Changed")
    End Select
End If

If record="" Then
        MsgBox("Error: record can't find")
End If

How to select last two characters of a string

You should use substring, not jQuery, to do this.

Try something like this:

member.substring(member.length - 2, member.length)

W3Schools (not official, but occasionally helpful): http://www.w3schools.com/jsref/jsref_substring.asp

Adding MDN link as requested by commenter: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

Setting the selected attribute on a select list using jQuery

This can be a solution

$(document).on('change', 'select', function () {
            var value = $(this).val();
            $(this).find('option[value="' + value + '"]').attr("selected", "selected");
        })

Getting cursor position in Python

This could be a possible code for your problem :

# Note you  need to install PyAutoGUI for it to work


import pyautogui
w = pyautogui.position()
x_mouse = w.x
y_mouse = w.y
print(x_mouse, y_mouse)

How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   

Django database query: How to get object by id?

In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404 importing by from django.shortcuts import get_object_or_404.

Use example:

def myFunc(request, my_pk):
    my_var = get_object_or_404(CLASS_NAME, pk=my_pk)

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

Print a list of space-separated elements in Python 3

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)

Result:

Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

How do I address unchecked cast warnings?

The obvious answer, of course, is not to do the unchecked cast.

If it's absolutely necessary, then at least try to limit the scope of the @SuppressWarnings annotation. According to its Javadocs, it can go on local variables; this way, it doesn't even affect the entire method.

Example:

@SuppressWarnings("unchecked")
Map<String, String> myMap = (Map<String, String>) deserializeMap();

There is no way to determine whether the Map really should have the generic parameters <String, String>. You must know beforehand what the parameters should be (or you'll find out when you get a ClassCastException). This is why the code generates a warning, because the compiler can't possibly know whether is safe.

How to add buttons dynamically to my form?

I had the same doubt and came up with the following contribution:

 int height = this.Size.Height;
 int width = this.Size.Width;

 int widthOffset = 10;
 int heightOffset = 10;

 int btnWidth = 100;  // Button Widht
 int btnHeight = 40;  // Button Height

 for (int i = 0; i < 50; ++i)
 {
     if ((widthOffset + btnWidth) >= width)
     {                    
         widthOffset = 10;
         heightOffset = heightOffset + btnHeight

         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
     }

     else
     {                        
         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
      }
  }

Expected Behaviour:
This will generate the buttons dinamically and using the current window size, "break a line" when the button exceeds the right margin of your window.

Setting background color for a JFrame

Resurrecting a thread from stasis.

In 2018 this solution works for Swing/JFrame in NetBeans (should work in any IDE :):

this.getContentPane().setBackground(Color.GREEN);

How to reset / remove chrome's input highlighting / focus border?

You should be able to remove it using

outline: none;

but keep in mind this is potentially bad for usability: It will be hard to tell whether an element is focused, which can suck when you walk through all a form's elements using the Tab key - you should reflect somehow when an element is focused.

Reading a binary file with python

You could use numpy.fromfile, which can read data from both text and binary files. You would first construct a data type, which represents your file format, using numpy.dtype, and then read this type from file using numpy.fromfile.

how to align img inside the div to the right?

You can give the surrounding div a

text-align: right

this will leave white space to the left of the image. (= the image will occupy the whole line).

If you want content to be shown to the left hand side of the image, use

float: right

on the image. However, the surrounding div will then need overflow: auto to stretch to the needed height.

How to get the date and time values in a C program?

Use time() and localtime() to get the time:

#include <stdio.h>
#include <time.h>

int main()
{
  time_t t = time(NULL);
  struct tm tm = *localtime(&t);
  printf("now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}

How to pull specific directory with git

After much looking for an answer, not finding, giving up, trying again and so on, I finally found a solution to this in another SO thread:

How to git-pull all but one folder

To copy-paste what's there:

git init
git remote add -f origin <url>
git config core.sparsecheckout true
echo <dir1>/ >> .git/info/sparse-checkout
echo <dir2>/ >> .git/info/sparse-checkout
echo <dir3>/ >> .git/info/sparse-checkout
git pull origin master

To do what OP wants (work on only one dir), just add that one dir to .git/info/sparse-checkout, when doing the steps above.

Many many thanks to @cforbish !

How do I remove the passphrase for the SSH key without having to create a new key?

On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.

How to count no of lines in text file and store the value into a variable using batch script?

Try this:

@Echo off
Set _File=file.txt
Set /a _Lines=0
For /f %%j in ('Find "" /v /c ^< %_File%') Do Set /a _Lines=%%j
Echo %_File% has %_Lines% lines.

It eliminates the extra FindStr and doesn't need expansion.


- edited to use ChrisJJ's redirect suggestion. Removal of the TYPE command makes it three times faster.

Access restriction on class due to restriction on required library rt.jar?

Sorry for updating an old POST. I got the reported problem and I solved it as said below.

Assuming you are using Eclipse + m2e maven plugin, if you get this access restriction error, right click on the project/module in which you have the error --> Properties --> Build Path --> Library --> Replace JDK/JRE to the one that is used in eclipse workspace.

I followed the above steps and the issue is resolved.

How to make fixed header table inside scrollable div?

This code works form me. Include the jquery.js file.

<!DOCTYPE html>
<html>

<head>
<script src="jquery.js"></script>
<script>
var headerDivWidth=0;
var contentDivWidth=0;
function fixHeader(){

var contentDivId = "contentDiv";
var headerDivId = "headerDiv";

var header = document.createElement('table');
var headerRow = document.getElementById('tableColumnHeadings'); 

/*Start : Place header table inside <DIV> and place this <DIV> before content table*/
var headerDiv = "<div id='"+headerDivId+"' style='width:500px;overflow-x:hidden;overflow-y:scroll' class='tableColumnHeadings'><table></table></div>";
$(headerRow).wrap(headerDiv);
$("#"+headerDivId).insertBefore("#"+contentDivId);
/*End : Place header table inside <DIV> and place this <DIV> before content table*/

fixColumnWidths(headerDivId,contentDivId);
}
function fixColumnWidths(headerDivId,contentDivId){
 /*Start : Place header row cell and content table first row cell inside <DIV>*/ 
            var contentFirstRowCells = $('#'+contentDivId+' table tr:first-child td');
            for (k = 0; k < contentFirstRowCells.length; k++) {
                $( contentFirstRowCells[k] ).wrapInner( "<div ></div>");
            }
            var headerFirstRowCells = $('#'+headerDivId+' table tr:first-child td');
            for (k = 0; k < headerFirstRowCells.length; k++) {
                $( headerFirstRowCells[k] ).wrapInner( "<div></div>");
            }
 /*End : Place header row cell and content table first row cell inside <DIV>*/ 

 /*Start : Fix width for columns of header cells and content first ror cells*/
            var headerColumns = $('#'+headerDivId+' table tr:first-child td div:first-child');
            var contentColumns = $('#'+contentDivId+' table tr:first-child td div:first-child');
            for (i = 0; i < contentColumns.length; i++) {
                if (i == contentColumns.length - 1) {
                    contentCellWidth = contentColumns[i].offsetWidth;
                }
                else {
                    contentCellWidth = contentColumns[i].offsetWidth;
                }
                headerCellWidth = headerColumns[i].offsetWidth;
                if(contentCellWidth>headerCellWidth){
                $(headerColumns[i]).css('width', contentCellWidth+"px");
                $(contentColumns[i]).css('width', contentCellWidth+"px");
                }else{
                $(headerColumns[i]).css('width', headerCellWidth+"px");
                $(contentColumns[i]).css('width', headerCellWidth+"px");
                }
            }
/*End : Fix width for columns of header and columns of content table first row*/
}   

    function OnScrollDiv(Scrollablediv) {
    document.getElementById('headerDiv').scrollLeft = Scrollablediv.scrollLeft;
    }
function radioCount(){
    alert(document.form.elements.length);

}   
</script>
<style>
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
th,td
{
padding:5px;
}
</style>

</head>

<body onload="fixHeader();">
<form id="form" name="form">
<div id="contentDiv" style="width:500px;height:100px;overflow:auto;" onscroll="OnScrollDiv(this)">
<table>
<!--tr id="tableColumnHeadings" class="tableColumnHeadings">
  <td><div>Firstname</div></td>
  <td><div>Lastname</div></td>      
  <td><div>Points</div></td>
  </tr>

<tr>
  <td><div>Jillsddddddddddddddddddddddddddd</div></td>
  <td><div>Smith</div></td>     
  <td><div>50</div></td>
  </tr-->

  <tr id="tableColumnHeadings" class="tableColumnHeadings">
  <td>&nbsp;</td>

  <td>Firstname</td>
  <td>Lastname</td>     
  <td>Points</td>
  </tr>

<tr style="height:0px">
<td></td>
  <td></td>
  <td></td>     
  <td></td>
  </tr>

<tr >
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID" onclick="javascript:radioCount();"/></td>
  <td>Jillsddddddddddddddddddddddddddd</td>
  <td>Smith</td>        
  <td>50</td>
  </tr>

<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>

  <td>Eve</td>
  <td>Jackson</td>      
  <td>9400000000000000000000000000000</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>

  <td>John</td>
  <td>Doe</td>      
  <td>80</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>

  <td><div>Jillsddddddddddddddddddddddddddd</div></td>
  <td><div>Smith</div></td>     
  <td><div>50</div></td>
  </tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>

  <td>Eve</td>
  <td>Jackson</td>      
  <td>9400000000000000000000000000000</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>

  <td>John</td>
  <td>Doe</td>      
  <td>80</td>
</tr>
</table>
</div>

</form>
</body>

</html>

How do I validate a date in this format (yyyy-mm-dd) using jquery?

Working Demo fiddle here Demo

Changed your validation function to this

function isDate(txtDate)
{
return txtDate.match(/^d\d?\/\d\d?\/\d\d\d\d$/);
}

How to make a whole 'div' clickable in html and css without JavaScript?

It is possible to make a link fill the entire div which gives the appearance of making the div clickable.

CSS:

#my-div {
    background-color: #f00;
    width: 200px;
    height: 200px;
}
a.fill-div {
    display: block;
    height: 100%;
    width: 100%;
    text-decoration: none;
}

HTML:

<div id="my-div">
    <a href="#" class="fill-div"></a>
</div>

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Onclick event to remove default value in a text input field

u can use placeholder and when u write a text on the search box placeholder will hidden. Thanks

<input placeholder="Search" type="text" />

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

How to make for loops in Java increase by increments other than 1

The "increment" portion of a loop statement has to change the value of the index variable to have any effect. The longhand form of "++j" is "j = j + 1". So, as other answers have said, the correct form of your increment is "j = j + 3", which doesn't have as terse a shorthand as incrementing by one. "j + 3", as you know by now, doesn't actually change j; it's an expression whose evaluation has no effect.

How do I access (read, write) Google Sheets spreadsheets with Python?

I think you're looking at the cell-based feeds section in that API doc page. Then you can just use the PUT/ GET requests within your Python script, using either commands.getstatusoutput or subprocess.

Selecting last element in JavaScript array

In case you are using ES6 you can do:

const arr = [ 1, 2, 3 ];
[ ...arr ].pop(); // 3
arr; // [ 1, 2, 3 ] (wasn't changed)

Is it better practice to use String.format over string Concatenation in Java?

I haven't done any specific benchmarks, but I would think that concatenation may be faster. String.format() creates a new Formatter which, in turn, creates a new StringBuilder (with a size of only 16 chars). That's a fair amount of overhead especially if you are formatting a longer string and StringBuilder keeps having to resize.

However, concatenation is less useful and harder to read. As always, it's worth doing a benchmark on your code to see which is better. The differences may be negligible in server app after your resource bundles, locales, etc are loaded in memory and the code is JITted.

Maybe as a best practice, it would be a good idea to create your own Formatter with a properly sized StringBuilder (Appendable) and Locale and use that if you have a lot of formatting to do.

Count number of days between two dates

to get the number of days in a time range (just a count of all days)

(start_date..end_date).count
(start_date..end_date).to_a.size
#=> 32

to get the number of days between 2 dates

(start_date...end_date).count
(start_date...end_date).to_a.size
#=> 31

parsing JSONP $http.jsonp() response in angular.js

This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:

var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
    $http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
        $scope.data = data;
    });
});

Then display or manipulate {{ data }} in your Angular template.

require_once :failed to open stream: no such file or directory

this will work as well

 require_once(realpath($_SERVER["DOCUMENT_ROOT"]) .'/mysite/php/includes/dbconn.inc');

What does "exited with code 9009" mean during this build?

Happened with a colleague. If development environment is windows and visual studio project is on C: drive.. Than make sure that visual studio is run with administrator right.. simply right click and 'Run as administrator'. You can also go to the properties of visual studio project -> Advance -> and enable 'Run as administrator'.

How do I pass a list as a parameter in a stored procedure?

I solved this problem through the following:

  1. In C # I built a String variable.

string userId="";

  1. I put my list's item in this variable. I separated the ','.

for example: in C#

userId= "5,44,72,81,126";

and Send to SQL-Server

 SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);
  1. I Create Separated Function in SQL-server For Convert my Received List (that it's type is NVARCHAR(Max)) to Table.
CREATE FUNCTION dbo.SplitInts  
(  
   @List      VARCHAR(MAX),  
   @Delimiter VARCHAR(255)  
)  
RETURNS TABLE  
AS  
  RETURN ( SELECT Item = CONVERT(INT, Item) FROM  
      ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')  
        FROM ( SELECT [XML] = CONVERT(XML, '<i>'  
        + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.')  
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y  
      WHERE Item IS NOT NULL  
  );
  1. In the main Store Procedure, using the command below, I use the entry list.

SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');

The "backspace" escape character '\b': unexpected behavior?

Your result will vary depending on what kind of terminal or console program you're on, but yes, on most \b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there.

So for the hello worl part, the code outputs

hello worl
          ^

...(where ^ shows where the cursor is) Then it outputs two \b characters which moves the cursor backward two places without erasing (on your terminal):

hello worl
        ^

Note the cursor is now on the r. Then it outputs d, which overwrites the r and gives us:

hello wodl
         ^

Finally, it outputs \n, which is a non-destructive newline (again, on most terminals, including apparently yours), so the l is left unchanged and the cursor is moved to the beginning of the next line.

What is the Auto-Alignment Shortcut Key in Eclipse?

The answer that the OP accepted is wildly different from the question I thought was asked. I thought the OP wanted a way to auto-align = signs or + signs, similar to the tabularize plugin for vim.

For this task, I found the Columns4Eclipse plugin to be just what I needed.

Visual Studio C# IntelliSense not automatically displaying

Deleted the .suo file in solution folder to solve the problem.

JavaScript seconds to time string with format hh:mm:ss

You can use Momement.js with moment-duration-format plugin:

_x000D_
_x000D_
var seconds = 3820;_x000D_
var duration = moment.duration(seconds, 'seconds');_x000D_
var formatted = duration.format("hh:mm:ss");_x000D_
console.log(formatted); // 01:03:40
_x000D_
<!-- Moment.js library -->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>_x000D_
_x000D_
<!-- moment-duration-format plugin -->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
_x000D_
_x000D_
_x000D_

See also this Fiddle

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Java: convert seconds to minutes, hours and days

It should be like:

    public static void calculateTime(long seconds) {
            int day = (int)TimeUnit.SECONDS.toDays(seconds);        
            long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
            long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
            long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);

            System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);

        }

Explanation:

TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e, day*24. You now got remaining hours. Same for minute and second. You need to minus the already got hour and minutes respectively.

Smooth scrolling when clicking an anchor link

Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;

    $('.a-parent-div').find('a').click(function(event){
        event.preventDefault();
        $('.scroll-div').animate({
     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       
  });

The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.

CMake not able to find OpenSSL library

Same problem, and fixed it on my centos 6.5 using the following command.

yum install openssl-devel

How to redirect in a servlet filter?

If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):

String uri = request.getRequestURI();

String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());

if(redirectMap.containsKey(path)) {
    response.sendRedirect(redirectMap.get(path) + rest);
} else {
    chain.doFilter(request, response);
}

What is the difference between Normalize.css and Reset CSS?

Normalize.css is mainly a set of styles, based on what its author thought would look good, and make it look consistent across browsers. Reset basically strips styling from elements so you have more control over the styling of everything.

I use both.

Some styles from Reset, some from Normalize.css. For example, from Normalize.css, there's a style to make sure all input elements have the same font, which doesn't occur (between text inputs and textareas). Reset has no such style, so inputs have different fonts, which is not normally wanted.

So bascially, using the two CSS files does a better job 'Equalizing' everything ;)

regards!

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

SSIS Excel Connection Manager failed to Connect to the Source

After researching everywhere finally i have found out temporary solution. Because i have try all the solution installing access drivers but still i am facing same issues.

For excel source, Before this step you need to change the setting. Save excel file as 2010 format.xlsx

Also set Project Configuration Properties for Debugging Run64BitRuntime = False

  1. Drag and drop the excel source
  2. Double click on the excel source and connect excel. Any way you will get an same error no table or view cannot load....
  3. Click ok
  4. Right click on excel source, click on show advanced edit.
  5. In that click on component properties.
  6. You can see openrowset. In that right side you need to enter you excel sheet name example: if in excel sheet1 then you need to enter sheet1$. I.e end with dollar symbol. And click ok.
  7. Now you can do other works connecting to destination.

I am using visual studio 2017, sql server 2017, office 2016, and Microsoft access database 2010 engine 32bit. Os windows 10 64 bit.

This is temporary solution. Because many peoples are searching for this type of question. Finally I figured out and this solution is not available in any of the website.

Python:Efficient way to check if dictionary is empty or not

As far as I know the for loop uses the iter function and you should not mess with a structure while iterating over it.

Does it have to be a dictionary? If you use a list something like this might work:

while len(my_list) > 0:
    #get last item from list
    key, value = my_list.pop()
    #do something with key and value
    #maybe
    my_list.append((key, value))

Note that my_list is a list of the tuple (key, value). The only disadvantage is that you cannot access by key.

EDIT: Nevermind, the answer above is mostly the same.

how to redirect to external url from c# controller

Try this:

return Redirect("http://www.website.com");

End-line characters from lines read from text file, using Python

Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that:

if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1)) 
  line input #1 a$
  print a$
wend
close

Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:

def line_input (file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line_input(f):
    # do something with line

I am induced to think that something has gone the wrong way somewhere...