Programs & Examples On #Arithmetic expressions

How do I use floating-point division in bash?

For those trying to calculate percentages with the accepted answer, but are losing precision:

If you run this:

echo "scale=2; (100/180) * 180" | bc

You get 99.00 only, which is losing precision.

If you run it this way:

echo "result = (100/180) * 180; scale=2; result / 1" | bc -l

Now you get 99.99.

Because you're scaling only at the moment of printing.

Refer to here

Is there an exponent operator in C#?

I'm surprised no one has mentioned this, but for the simple (and probably most encountered) case of squaring, you just multiply by itself.

float someNumber;

float result = someNumber * someNumber;

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

Merge / convert multiple PDF files into one PDF

If you want to convert all the downloaded images into one pdf then execute

convert img{0..19}.jpg slides.pdf

How to count instances of character in SQL Column

The easiest way is by using Oracle function:

SELECT REGEXP_COUNT(COLUMN_NAME,'CONDITION') FROM TABLE_NAME

How to open link in new tab on html?

If you would like to make the command once for your entire site, instead of having to do it after every link. Try this place within the Head of your web site and bingo.

<head>
<title>your text</title>
<base target="_blank" rel="noopener noreferrer">
</head>

hope this helps

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

Why both no-cache and no-store should be used in HTTP response?

Just to make things even worse, in some situations, no-cache can't be used, but no-store can:

http://faindu.wordpress.com/2008/04/18/ie7-ssl-xml-flex-error-2032-stream-error/

How do I pretty-print existing JSON data with Java?

I think for pretty-printing something, it's very helpful to know its structure.

To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.

Of course you can do similar with any JSON library you like.

How to create a temporary directory?

Here is a simple explanation about how to create a temp dir using templates.

  1. Creates a temporary file or directory, safely, and prints its name.
  2. TEMPLATE must contain at least 3 consecutive 'X's in last component.
  3. If TEMPLATE is not specified, it will use tmp.XXXXXXXXXX
  4. directories created are u+rwx, minus umask restrictions.

PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR

TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}

# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH

# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH

# create a tempdir in your systems default tmp path e.g. /tmp 
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH

# Do whatever you want with your generated temp dir and var holding its path

Reading a key from the Web.Config using ConfigurationManager

Also you can try this line to get string value from app.config file.

var strName= ConfigurationManager.AppSettings["stringName"];

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Traditionally PHP has been tolerant to bad practice and failures in code, which makes debugging quite hard. The problem in this specific case is that both mysqli and PDO by default don't tell you, when a query failed and just return FALSE. (I will not talk about the depricated mysql extention. The support for prepared statements is reason anough to switch either to PDO or mysqli.) But you can change the default behavior of PHP to always throw exceptions when a query fails.

For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

error_reporting(E_ALL);

$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$result = $pdo->query('select emal from users');
$data = $result->fetchAll();

This will show you the following:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8

As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.

Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); you will get

Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9

For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

error_reporting(E_ALL);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');

$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();

You will get

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8

mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8

Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you only get

Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10

Of course, you could manually check the MySQL errors. But I would go crazy if I had to do that every time I made a typo - or worse - every time I want to query the database.

How to enable Bootstrap tooltip on disabled button?

Here is some working code: http://jsfiddle.net/mihaifm/W7XNU/200/

$('body').tooltip({
    selector: '[rel="tooltip"]'
});

$(".btn").click(function(e) {
    if (! $(this).hasClass("disabled"))
    {
        $(".disabled").removeClass("disabled").attr("rel", null);

        $(this).addClass("disabled").attr("rel", "tooltip");
    }
});

The idea is to add the tooltip to a parent element with the selector option, and then add/remove the rel attribute when enabling/disabling the button.

plain count up timer in javascript

Just wanted to put my 2 cents in. I modified @Ajay Singh's function to handle countdown and count up Here is a snip from the jsfiddle.

var countDown = Math.floor(Date.now() / 1000)
runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
var t = setInterval(function(){
  runClock(function(){
    console.log('done');
    clearInterval(t);
  },function(timeElapsed, timeRemaining){
    console.log( timeElapsed.seconds );
  }, countDown);
}, 100);

https://jsfiddle.net/3g5xvaxe/

Pandas: sum DataFrame rows for given columns

You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

Global constants file in Swift

Constant.swift

import Foundation

let kBaseURL = NSURL(string: "http://www.example.com/")

ViewController.swift

var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)

Android Facebook integration with invalid key hash

Even though this question has been answered in alot of helpful ways I just wanted to add that when I followed Rafal Maleks answer (using the hash keys on Google Play Console) I was NOT able to use the App Signing SHA1 key, still got the generic error from Facebook. Instead I needed to use the SHA-1 certificate fingerprint from the Upload Certificate part (just below the App Signing part on Google Play Console). Same process otherwise;

  1. Copy the SHA-1 certificate fingerprint from Upload Certificate section in Google Play Console

  2. Convert the SHA-1 using: http://tomeko.net/online_tools/hex_to_base64.php and copy the output (base64)

  3. Paste it into the Key Hashes input on developer.facebook.com and save changes.

Hopefully this answer isn't to redundant and will help someone that can't get it to work with the App Signing certificate.

Now Facebook login works in my app both in debug and release mode.

How can I switch my git repository to a particular commit

To create a new branch (locally):

  • With the commit hash (or part of it)

    git checkout -b new_branch 6e559cb
    
  • or to go back 4 commits from HEAD

    git checkout -b new_branch HEAD~4
    

Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch


For discarding the last three commits, see Lunaryorn's answer below.


For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.

How to do case insensitive search in Vim

You can use in your vimrc those commands:

  • set ignorecase - All your searches will be case insensitive
  • set smartcase - Your search will be case sensitive if it contains an uppercase letter

You need to set ignorecase if you want to use what smartcase provides.

I wrote recently an article about Vim search commands (both built in command and the best plugins to search efficiently).

C# Iterating through an enum? (Indexing a System.Array)

Array values = Enum.GetValues(typeof(myEnum));

foreach( MyEnum val in values )
{
   Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}

Or, you can cast the System.Array that is returned:

string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));

for( int i = 0; i < names.Length; i++ )
{
    print(names[i], values[i]);
}

But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?

What does $1 mean in Perl?

The $number variables contain the parts of the string that matched the capture groups ( ... ) in the pattern for your last regex match if the match was successful.

For example, take the following string:

$text = "the quick brown fox jumps over the lazy dog.";

After the statement

$text =~ m/ (b.+?) /;

$1 equals the text "brown".

What is the best/simplest way to read in an XML file in Java application?

I've only used jdom. It's pretty easy.

Go here for documentation and to download it: http://www.jdom.org/

If you have a very very large document then it's better not to read it all into memory, but use a SAX parser which calls your methods as it hits certain tags and attributes. You have to then create a state machine to deal with the incoming calls.

How to resolve Value cannot be null. Parameter name: source in linq?

Value cannot be null. Parameter name: source

Above error comes in situation when you are querying the collection which is null.

For demonstration below code will result in such an exception.

Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();

Here is the output of the above code.

Hello World Run-time exception (line 11): Value cannot be null. Parameter name: source

Stack Trace:

[System.ArgumentNullException: Value cannot be null. Parameter name: source] at Program.Main(): line 11

In your case ListMetadataKor is null. Here is the fiddle if you want to play around.

Why use Redux over Facebook Flux?

You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks

Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.

Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.

Add timestamp column with default NOW() for new rows only

Try something like:-

ALTER TABLE table_name ADD  CONSTRAINT [DF_table_name_Created] 
DEFAULT (getdate()) FOR [created_at];

replacing table_name with the name of your table.

Javascript parse float is ignoring the decimals after my comma

For anyone arriving here wondering how to deal with this problem where commas (,) and full stops (.) might be involved but the exact number format may not be known - this is how I correct a string before using parseFloat() (borrowing ideas from other answers):

function preformatFloat(float){
   if(!float){
      return '';
   };

   //Index of first comma
   const posC = float.indexOf(',');

   if(posC === -1){
      //No commas found, treat as float
      return float;
   };

   //Index of first full stop
   const posFS = float.indexOf('.');

   if(posFS === -1){
      //Uses commas and not full stops - swap them (e.g. 1,23 --> 1.23)
      return float.replace(/\,/g, '.');
   };

   //Uses both commas and full stops - ensure correct order and remove 1000s separators
   return ((posC < posFS) ? (float.replace(/\,/g,'')) : (float.replace(/\./g,'').replace(',', '.')));
};
// <-- parseFloat(preformatFloat('5.200,75'))
// --> 5200.75

At the very least, this would allow parsing of British/American and European decimal formats (assuming the string contains a valid number).

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

How to receive JSON as an MVC 5 action method parameter

You are sending a array of string

var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
    usersRoles.push(jQuery(this).val());
});   

So change model type accordingly

 public ActionResult AddUser(List<string> model)
 {
 }

How can I inspect element in an Android browser?

Had to debug a site for native Android browser and came here. So I tried weinre on an OS X 10.9 (as weinre server) with Firefox 30.0 (weinre client) and an Android 4.1.2 (target). I'm really, really surprised of the result.

  1. Download and install node runtime from http://nodejs.org/download/
  2. Install weinre: sudo npm -g install weinre
  3. Find out your current IP address at Settings > Network
  4. Setup a weinre server on your machine: weinre --boundHost YOUR.IP.ADDRESS.HERE
  5. In your browser call: http://YOUR.IP.ADRESS.HERE:8080
  6. You'll see a script snippet, place it into your site: <script src="http://YOUR.IP.ADDRESS.HERE:8080/target/target-script-min.js"></script>
  7. Open the debug client in your local browser: http://YOUR.IP.ADDRESS.HERE:8080/client
  8. Finally on your Android: call the site you want to inspect (the one with the script inside) and see how it appears as "Target" in your local browser. Now you can open "Elements" or whatever you want.

Maybe 8080 isn't your default port. Then in step 4 you have to call weinre --httpPort YOURPORT --boundHost YOUR.IP.ADRESS.HERE.

And I don't remember exactly when it was, maybe somewhere after step 5, I had to accept incoming connections prompt, of course.

Happy debugging

P.S. I'm still overwhelmed how good that works. Even elements-highlighting work

Capture characters from standard input without waiting for enter to be pressed

On Linux (and other unix-like systems) this can be done in following way:

#include <unistd.h>
#include <termios.h>

char getch() {
        char buf = 0;
        struct termios old = {0};
        if (tcgetattr(0, &old) < 0)
                perror("tcsetattr()");
        old.c_lflag &= ~ICANON;
        old.c_lflag &= ~ECHO;
        old.c_cc[VMIN] = 1;
        old.c_cc[VTIME] = 0;
        if (tcsetattr(0, TCSANOW, &old) < 0)
                perror("tcsetattr ICANON");
        if (read(0, &buf, 1) < 0)
                perror ("read()");
        old.c_lflag |= ICANON;
        old.c_lflag |= ECHO;
        if (tcsetattr(0, TCSADRAIN, &old) < 0)
                perror ("tcsetattr ~ICANON");
        return (buf);
}

Basically you have to turn off canonical mode (and echo mode to suppress echoing).

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I had the same thing on my Windows 10 installation.

Anaconda3 would not open Anaconda Navigator before I copied libcrypto-1_1-x64.dll and libssl-1_1-x64.dll from Anaconda3\Library\bin to \Anaconda3\DLL.

Once I did that pip install in the base environment worked fine but not in another environment I created. I had to do the same as above in the new environment.

That is, copy libcrypto-1_1-x64.dll and libssl-1_1-x64.dll from \<env folder>\Library\bin to \<env folder>\DLL then it worked fine.

How do I get the domain originating the request in express.js?

Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

How to edit default.aspx on SharePoint site without SharePoint Designer

I was able to accomplish editing the default.aspx page by:

  • Opening the site in SharePoint Designer 2013
  • Then clicking 'All Files' to view all of the files,
  • Then right-click -> Edit file in Advanced Mode.

By doing that I was able to remove the tagprefix causing a problem on my page.

Auto refresh code in HTML using meta tags

It looks like you probably pasted this (or used a word processor like MS Word) using a kind of double-quotes that are not recognized by the browser. Please check that your code uses actual double-quotes like this one ", which is different from the following character:

Replace the meta tag with this one and try again:

<meta http-equiv="refresh" content="5" >

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Here's a modification of CMS's solution that can be called in multiple places in your code:

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

Usage:

$(window).resize(function () {
    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");
});

CMS's solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer variable.

With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.

c#: getter/setter

You can also use a lambda expression

public string Type
{
    get => _type;
    set => _type = value;
}

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Before Mongo 3.6:

You may start mongodb with

mongod --httpinterface

And access it on

http://localhost:28017

Since version 2.6: MongoDB disables the HTTP interface by default.

Update

HTTP Interface and REST API

MongoDB 3.6 removes the deprecated HTTP interface and REST API to MongoDB.

See Mongo http interface and rest api

Align div right in Bootstrap 3

The class pull-right is still there in Bootstrap 3 See the 'helper classes' here

pull-right is defined by

.pull-right {
  float: right !important;
}

without more info on styles and content, it's difficult to say.

It definitely pulls right in this JSBIN when the page is wider than 990px - which is when the col-md styling kicks in, Bootstrap 3 being mobile first and all.

Bootstrap 4

Note that for Bootstrap 4 .pull-right has been replaced with .float-right https://www.geeksforgeeks.org/pull-left-and-pull-right-classes-in-bootstrap-4/#:~:text=pull%2Dright%20classes%20have%20been,based%20on%20the%20Bootstrap%20Grid.

How to establish a connection pool in JDBC?

As answered by others, you will probably be happy with Apache Dbcp or c3p0. Both are popular, and work fine.

Regarding your doubt

Doesn't javax.sql or java.sql have pooled connection implementations? Why wouldn't it be best to use these?

They don't provide implementations, rather interfaces and some support classes, only revelant to the programmers that implement third party libraries (pools or drivers). Normally you don't even look at that. Your code should deal with the connections from your pool just as they were "plain" connections, in a transparent way.

how to align all my li on one line?

I think the NOBR tag might be overkill, and as you said, unreliable.

There are 2 options available depending on how you are displaying the text.

If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"

Hide Text with CSS, Best Practice?

I do it like this:

.hidden-text {
  left: 100%;
  display: inline-block;
  position: fixed;
}

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

This worked in my case:

brew uninstall postgresql
rm -fr /usr/local/var/postgres/
brew install postgresql

Find which commit is currently checked out in Git

If you want to extract just a simple piece of information, you can get that using git show with the --format=<string> option...and ask it not to give you the diff with --no-patch. This means you can get a printf-style output of whatever you want, which might often be a single field.

For instance, to get just the shortened hash (%h) you could say:

$ git show --format="%h" --no-patch
4b703eb

If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $() syntax:

$ GIT_COMMIT="$(git show --format="%h" --no-patch)"

$ echo $GIT_COMMIT
4b703eb

The full list of what you can do is in git show --help. But here's an abbreviated list of properties that might be useful:

  • %H commit hash
  • %h abbreviated commit hash
  • %T tree hash
  • %t abbreviated tree hash
  • %P parent hashes
  • %p abbreviated parent hashes
  • %an author name
  • %ae author email
  • %at author date, UNIX timestamp
  • %aI author date, strict ISO 8601 format
  • %cn committer name
  • %ce committer email
  • %ct committer date, UNIX timestamp
  • %cI committer date, strict ISO 8601 format
  • %s subject
  • %f sanitized subject line, suitable for a filename
  • %gD reflog selector, e.g., refs/stash@{1}
  • %gd shortened reflog selector, e.g., stash@{1}

How to query all the GraphQL type fields without writing a long query?

GraphQL query format was designed in order to allow:

  1. Both query and result shape be exactly the same.
  2. The server knows exactly the requested fields, thus the client downloads only essential data.

However, according to GraphQL documentation, you may create fragments in order to make selection sets more reusable:

# Only most used selection properties

fragment UserDetails on User {
    id,
    username
} 

Then you could query all user details by:

FetchUsers {
    users() {
        ...UserDetails
    }
}

You can also add additional fields alongside your fragment:

FetchUserById($id: ID!) {
    users(id: $id) {
        ...UserDetails
        count
    }
}

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

What does .class mean in Java?

That means a Class with a type of anything (unknown).

You should read java generics tutorial to get to understand it better

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

Datatables on-the-fly resizing

You should try this one.

var table = $('#example').DataTable();
table.columns.adjust().draw();

Link: column adjust in datatable

Why doesn't git recognize that my file has been changed, therefore git add not working

Sometimes depend and by git version and if you forget to do git add ..

To check about your change on repository use always git status that show all untracked and changed files. Because git diff show only added files.

Update some specific field of an entity in android Room

As of Room 2.2.0 released October 2019, you can specify a Target Entity for updates. Then if the update parameter is different, Room will only update the partial entity columns. An example for the OP question will show this a bit more clearly.

@Update(entity = Tour::class)
fun update(obj: TourUpdate)

@Entity
public class TourUpdate {
    @ColumnInfo(name = "id")
    public long id;
    @ColumnInfo(name = "endAddress")
    private String endAddress;
}

Notice you have to a create a new partial entity called TourUpdate, along with your real Tour entity in the question. Now when you call update with a TourUpdate object, it will update endAddress and leave the startAddress value the same. This works perfect for me for my usecase of an insertOrUpdate method in my DAO that updates the DB with new remote values from the API but leaves the local app data in the table alone.

SSH Key - Still asking for password and passphrase

I had to execute:

eval `ssh-agent -s`
ssh-add

Note: You will have to do this again after every restart. If you want to avoid it, then enter it in your ".bashrc" file which is in C:\Users\<<USERNAME>>\.bashrc on windows. It is probably hidden, so make sure that you can see hidden files.

Solution found here.

Get the element with the highest occurrence in an array

Here is my way to do it so just using .filter.

_x000D_
_x000D_
var arr = ['pear', 'apple', 'orange', 'apple'];

function dup(arrr) {
    let max = { item: 0, count: 0 };
    for (let i = 0; i < arrr.length; i++) {
        let arrOccurences = arrr.filter(item => { return item === arrr[i] }).length;
        if (arrOccurences > max.count) {
            max = { item: arrr[i], count: arrr.filter(item => { return item === arrr[i] }).length };
        }
    }
    return max.item;
}
console.log(dup(arr));
_x000D_
_x000D_
_x000D_

Making sure at least one checkbox is checked

if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
            || ($("#checkboxid3").is(":checked"))) {
 //Your Code here
}

You can use this code to verify that checkbox is checked at least one.

Thanks!!

S3 - Access-Control-Allow-Origin Header

First, activate CORS in your S3 bucket. Use this code as a guidance:

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>http://www.example1.com</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>http://www.example2.com</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

2) If it still not working, make sure to also add a "crossorigin" with a "*" value to your img tags. Put this in your html file:

  let imagenes = document.getElementsByTagName("img");
    for (let i = 0; i < imagenes.length; i++) {
      imagenes[i].setAttribute("crossorigin", "*");

Space between two divs

DIVs inherently lack any useful meaning, other than to divide, of course.

Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

Maven command to determine which settings.xml file Maven is using

If you are debugging and wasting time like me, this will give exact details including passwords. :P

mvn help:effective-settings -DshowPasswords=true

mean() warning: argument is not numeric or logical: returning NA

From R 3.0.0 onwards mean(<data.frame>) is defunct (and passing a data.frame to mean will give the error you state)

A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".

In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following

lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)

Why is it common to put CSRF prevention tokens in cookies?

Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.

The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.

The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.

How can I save application settings in a Windows Forms application?

If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.

Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings and Settings.Designer.settings that contain the singleton class Settings inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:

Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file

This technique is applicable both for console, Windows Forms, and other project types.

Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.

Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs

Sass - Converting Hex to RGBa for background opacity

The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

Checking Date format from a string in C#

You can use below IsValidDate():

 public static bool IsValidDate(string value, string[] dateFormats)
    {
        DateTime tempDate;
        bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
        if (validDate)
            return true;
        else
            return false;
    }

And you can pass in the value and date formats. For example:

var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}

if (IsValidDate(data, dateFormats))
{
    //Do something
}
else
{
    //Do something else
}

Any shortcut to initialize all array elements to zero?

    int a=7, b=7 ,c=0,d=0;
    int dizi[][]=new int[a][b];
    for(int i=0;i<a;i++){
        for(int q=d;q<b;q++){
            dizi[i][q]=c;               
            System.out.print(dizi[i][q]);
            c++;
        }

        c-=b+1;
        System.out.println();               
    }

result 0123456 -1012345 -2-101234 -3-2-10123 -4-3-2-1012 -5-4-3-2-101 -6-5-4-3-2-10

Java integer to byte array

The chunks below work at least for sending an int over UDP.

int to byte array:

public byte[] intToBytes(int my_int) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeInt(my_int);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

byte array to int:

public int bytesToInt(byte[] int_bytes) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    int my_int = ois.readInt();
    ois.close();
    return my_int;
}

How do I get textual contents from BLOB in Oracle SQL

Use TO_CHAR function.

select TO_CHAR(BLOB_FIELD) from TABLE_WITH_BLOB where ID = '<row id>'

Converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set. The value returned is always VARCHAR2.

How to get the children of the $(this) selector?

You may have 0 to many <img> tags inside of your <div>.

To find an element, use a .find().

To keep your code safe, use a .each().

Using .find() and .each() together prevents null reference errors in the case of 0 <img> elements while also allowing for handling of multiple <img> elements.

_x000D_
_x000D_
// Set the click handler on your div_x000D_
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {_x000D_
_x000D_
  // Find the image using.find() and .each()_x000D_
  $(this).find("img").each(function() {_x000D_
  _x000D_
        var img = this;  // "this" is, now, scoped to the image element_x000D_
        _x000D_
        // Do something with the image_x000D_
        $(this).animate({_x000D_
          width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"_x000D_
        }, 500);_x000D_
        _x000D_
  });_x000D_
  _x000D_
});
_x000D_
#mydiv {_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  background-color: #000000;_x000D_
  cursor: pointer;_x000D_
  padding: 50px;_x000D_
  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="mydiv">_x000D_
  <img src="" width="100" height="100"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

input file appears to be a text format dump. Please use psql

The answer above didn't work for me, this worked:

psql db_development < postgres_db.dump

What does "dereferencing" a pointer mean?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.

int a = 10;
int* ptr = &a;

printf("%d", *ptr); // With *ptr I'm dereferencing the pointer. 
                    // Which means, I am asking the value pointed at by the pointer.
                    // ptr is pointing to the location in memory of the variable a.
                    // In a's location, we have 10. So, dereferencing gives this value.

// Since we have indirect control over a's location, we can modify its content using the pointer. This is an indirect way to access a.

 *ptr = 20;         // Now a's content is no longer 10, and has been modified to 20.

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

This should not happen. Can you try doing this? Use the system properties and set the property as below:

Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", "10.101.3.229");

And if you have a port associated, then set this as well.

properties.setProperty("mail.smtp.port", "8080");

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

How to pass values across the pages in ASP.net without using Session

If it's just for passing values between pages and you only require it for the one request. Use Context.

Context

The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:

// Add item to
Context Context.Items["myKey"] = myValue;

// Read an item from the
 Context Response.Write(Context["myKey"]);

http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6

Using the above. If you then do a Server.Transfer the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.

How to Determine the Screen Height and Width in Flutter

MediaQuery.of(context).size.width and MediaQuery.of(context).size.height works great, but every time need to write expressions like width/20 to set specific height width.

I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.

Yes, flutter_screenutil plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!

Usage:

Add dependency:

Please check the latest version before installation.

dependencies:
  flutter:
    sdk: flutter
  # add flutter_ScreenUtil
  flutter_screenutil: ^0.4.2

Add the following imports to your Dart code:

import 'package:flutter_screenutil/flutter_screenutil.dart';

Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option

//fill in the screen size of the device in the design

//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);

//If the design is based on the size of the iPhone6 ??(iPhone6 ??750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

Use:

//for example:
//rectangle
Container(
           width: ScreenUtil().setWidth(375),
           height: ScreenUtil().setHeight(200),
           ...
            ),

////If you want to display a square:
Container(
           width: ScreenUtil().setWidth(300),
           height: ScreenUtil().setWidth(300),
            ),

Please refer updated documentation for more details

Note: I tested and using this plugin, which really works great with all devices including iPad

Hope this will helps someone

Sqlite or MySql? How to decide?

SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.

You should definitely go with MySQL or PostgreSQL.

If it is for a single-person project, SQLite will be easier to setup though.

How to abort makefile if variable not set?

TL;DR: Use the error function:

ifndef MY_FLAG
$(error MY_FLAG is not set)
endif

Note that the lines must not be indented. More precisely, no tabs must precede these lines.


Generic solution

In case you're going to test many variables, it's worth defining an auxiliary function for that:

# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
#   1. Variable name(s) to test.
#   2. (optional) Error message to print.
check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
      $(error Undefined $1$(if $2, ($2))))

And here is how to use it:

$(call check_defined, MY_FLAG)

$(call check_defined, OUT_DIR, build directory)
$(call check_defined, BIN_DIR, where to put binary artifacts)
$(call check_defined, \
            LIB_INCLUDE_DIR \
            LIB_SOURCE_DIR, \
        library path)


This would output an error like this:

Makefile:17: *** Undefined OUT_DIR (build directory).  Stop.

Notes:

The real check is done here:

$(if $(value $1),,$(error ...))

This reflects the behavior of the ifndef conditional, so that a variable defined to an empty value is also considered "undefined". But this is only true for simple variables and explicitly empty recursive variables:

# ifndef and check_defined consider these UNDEFINED:
explicitly_empty =
simple_empty := $(explicitly_empty)

# ifndef and check_defined consider it OK (defined):
recursive_empty = $(explicitly_empty)

As suggested by @VictorSergienko in the comments, a slightly different behavior may be desired:

$(if $(value $1) tests if the value is non-empty. It's sometimes OK if the variable is defined with an empty value. I'd use $(if $(filter undefined,$(origin $1)) ...

And:

Moreover, if it's a directory and it must exist when the check is run, I'd use $(if $(wildcard $1)). But would be another function.

Target-specific check

It is also possible to extend the solution so that one can require a variable only if a certain target is invoked.

$(call check_defined, ...) from inside the recipe

Just move the check into the recipe:

foo :
    @:$(call check_defined, BAR, baz value)

The leading @ sign turns off command echoing and : is the actual command, a shell no-op stub.

Showing target name

The check_defined function can be improved to also output the target name (provided through the $@ variable):

check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
        $(error Undefined $1$(if $2, ($2))$(if $(value @), \
                required by target `$@')))

So that, now a failed check produces a nicely formatted output:

Makefile:7: *** Undefined BAR (baz value) required by target `foo'.  Stop.

check-defined-MY_FLAG special target

Personally I would use the simple and straightforward solution above. However, for example, this answer suggests using a special target to perform the actual check. One could try to generalize that and define the target as an implicit pattern rule:

# Check that a variable specified through the stem is defined and has
# a non-empty value, die with an error otherwise.
#
#   %: The name of the variable to test.
#   
check-defined-% : __check_defined_FORCE
    @:$(call check_defined, $*, target-specific)

# Since pattern rules can't be listed as prerequisites of .PHONY,
# we use the old-school and hackish FORCE workaround.
# You could go without this, but otherwise a check can be missed
# in case a file named like `check-defined-...` exists in the root 
# directory, e.g. left by an accidental `make -t` invocation.
.PHONY : __check_defined_FORCE
__check_defined_FORCE :

Usage:

foo :|check-defined-BAR

Notice that the check-defined-BAR is listed as the order-only (|...) prerequisite.

Pros:

  • (arguably) a more clean syntax

Cons:

I believe, these limitations can be overcome using some eval magic and secondary expansion hacks, although I'm not sure it's worth it.

Retrieving a Foreign Key value with django-rest-framework serializers

this worked fine for me:

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.ReadOnlyField(source='category.name')
    class Meta:
        model = Item
        fields = "__all__"

How to delete a module in Android Studio

If you want to delete manually (for me it was easier), follow this:

Let's get this example with "teste".

1 - First change the explorer to "project" and open "settings.gradle";

enter image description here

2 - Delete the module you want;

enter image description here

3 - Go to your root folder of your project and delete the module folder.

enter image description here

Type of expression is ambiguous without more context Swift

As theEye's answer it is not an answer to this question, but as I also came here looking for the error im posting my case as others might find this also useful:

I got this error message when I was by error trying to calculate a value of two different types.

In my case I was trying to divide a CGFloat by a Double

GetFiles with multiple extensions

You can't do that, because GetFiles only accepts a single search pattern. Instead, you can call GetFiles with no pattern, and filter the results in code:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.GetFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

If you're working with .NET 4, you can use the EnumerateFiles method to avoid loading all FileInfo objects in memory at once:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.EnumerateFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

Docker is in volume in use, but there aren't any Docker containers

You should type this command with flag -f (force):

sudo docker volume rm -f <VOLUME NAME>

Text Editor which shows \r\n?

You can get this in Emacs by changing the mode. For example, here is what things look like in Whitespace mode.

alt text

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Try

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header.

Set JavaScript variable = null, or leave undefined?

Generally, I use null for values that I know can have a "null" state; for example

if(jane.isManager == false){
  jane.employees = null
}

Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

How is a CRC32 checksum calculated?

Then there is always Rosetta Code, which shows crc32 implemented in dozens of computer languages. https://rosettacode.org/wiki/CRC-32 and has links to many explanations and implementations.

Django: Get list of model fields?

Django versions 1.8 and later:

You should use get_fields():

[f.name for f in MyModel._meta.get_fields()]

The get_all_field_names() method is deprecated starting from Django 1.8 and will be removed in 1.10.

The documentation page linked above provides a fully backwards-compatible implementation of get_all_field_names(), but for most purposes the previous example should work just fine.


Django versions before 1.8:

model._meta.get_all_field_names()

That should do the trick.

That requires an actual model instance. If all you have is a subclass of django.db.models.Model, then you should call myproject.myapp.models.MyModel._meta.get_all_field_names()

Spark SQL: apply aggregate functions to a list of columns

There are multiple ways of applying aggregate functions to multiple columns.

GroupedData class provides a number of methods for the most common functions, including count, max, min, mean and sum, which can be used directly as follows:

  • Python:

    df = sqlContext.createDataFrame(
        [(1.0, 0.3, 1.0), (1.0, 0.5, 0.0), (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2)],
        ("col1", "col2", "col3"))
    
    df.groupBy("col1").sum()
    
    ## +----+---------+-----------------+---------+
    ## |col1|sum(col1)|        sum(col2)|sum(col3)|
    ## +----+---------+-----------------+---------+
    ## | 1.0|      2.0|              0.8|      1.0|
    ## |-1.0|     -2.0|6.199999999999999|      0.7|
    ## +----+---------+-----------------+---------+
    
  • Scala

    val df = sc.parallelize(Seq(
      (1.0, 0.3, 1.0), (1.0, 0.5, 0.0),
      (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2))
    ).toDF("col1", "col2", "col3")
    
    df.groupBy($"col1").min().show
    
    // +----+---------+---------+---------+
    // |col1|min(col1)|min(col2)|min(col3)|
    // +----+---------+---------+---------+
    // | 1.0|      1.0|      0.3|      0.0|
    // |-1.0|     -1.0|      0.6|      0.2|
    // +----+---------+---------+---------+
    

Optionally you can pass a list of columns which should be aggregated

df.groupBy("col1").sum("col2", "col3")

You can also pass dictionary / map with columns a the keys and functions as the values:

  • Python

    exprs = {x: "sum" for x in df.columns}
    df.groupBy("col1").agg(exprs).show()
    
    ## +----+---------+
    ## |col1|avg(col3)|
    ## +----+---------+
    ## | 1.0|      0.5|
    ## |-1.0|     0.35|
    ## +----+---------+
    
  • Scala

    val exprs = df.columns.map((_ -> "mean")).toMap
    df.groupBy($"col1").agg(exprs).show()
    
    // +----+---------+------------------+---------+
    // |col1|avg(col1)|         avg(col2)|avg(col3)|
    // +----+---------+------------------+---------+
    // | 1.0|      1.0|               0.4|      0.5|
    // |-1.0|     -1.0|3.0999999999999996|     0.35|
    // +----+---------+------------------+---------+
    

Finally you can use varargs:

  • Python

    from pyspark.sql.functions import min
    
    exprs = [min(x) for x in df.columns]
    df.groupBy("col1").agg(*exprs).show()
    
  • Scala

    import org.apache.spark.sql.functions.sum
    
    val exprs = df.columns.map(sum(_))
    df.groupBy($"col1").agg(exprs.head, exprs.tail: _*)
    

There are some other way to achieve a similar effect but these should more than enough most of the time.

See also:

Breaking out of a nested loop

Since I first saw break in C a couple of decades back, this problem has vexed me. I was hoping some language enhancement would have an extension to break which would work thus:

break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.

svn cleanup: sqlite: database disk image is malformed

First, open command/terminal at repository root (folder which has .svn as child folder):

cd /path/to/repository

Download sqlite3 and put executable sqlite3 at root of folder.

You do an integrity check on the sqlite database that keeps track of the repository (/path/to/repository/.svn/wc.db):

sqlite3 .svn/wc.db "pragma integrity_check"

That should report some errors.

Then you might be able to clean them up by doing:

sqlite3 .svn/wc.db "reindex nodes"
sqlite3 .svn/wc.db "reindex pristine"

If there are still errors after that, you still got the option to check out a fresh copy of the repository to a temporary folder and copy the .svn folder from the fresh copy to the old one. Then the old copy should work again and you can delete the temporary folder.

How to prevent favicon.ico requests?

In our experience, with Apache falling over on request of favicon.ico, we commented out extra headers in the .htaccess file.

For example we had Header set X-XSS-Protection "1; mode=block"

... but we had forgotten to sudo a2enmod headers beforehand. Commenting out extra headers being sent resolved our favicon.ico issue.

We also had several virtual hosts set up for development, and only failed out with 500 Internal Server Error when using http://localhost and fetching /favicon.ico. If you run "curl -v http://localhost/favicon.ico" and get a warning about the host name not being in the resolver cache or something to that effect, you might experience problems.

It could be as simple as not fetching (we tried that and it didn't work, because our root cause was different) or look around for directives in apache2.conf or .htaccess which might be causing strange 500 Internal Server Error messages.

We found it failed so quickly there was nothing useful in Apache's error logs whatsoever and spent an entire morning changing small things here and there until we resolved the problem of setting extra headers when we had forgotten to have mod_headers loaded!

Simple calculations for working with lat/lon and km distance?

Interesting that I didn't see a mention of UTM coordinates.

https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

At least if you want to add km to the same zone, it should be straightforward (in Python : https://pypi.org/project/utm/ )

utm.from_latlon and utm.to_latlon.

Align an element to bottom with flexbox

1. Style parent element: style="display:flex; flex-direction:column; flex:1;"

2. Style the element you want to stay at bottom: style="margin-top: auto;"

3. Done! Wow. That was easy.

Example:

enter image description here

<section style="display:flex; flex-wrap:wrap;"> // For demo, not necessary
    <div style="display:flex; flex-direction:column; flex:1;"> // Parent element
        <button style="margin-top: auto;"> I </button> // Target element
    </div>

    ... 5 more identical divs, for demo ...

</section>

Demo: https://codepen.io/ferittuncer/pen/YzygpWX

Jersey client: How to add a list as query parameter

i agree with you about alternative solutions which you mentioned above

1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.

and its true that you can't add List to MultiValuedMap because of its impl class MultivaluedMapImpl have capability to accept String Key and String Value. which is shown in following figure

enter image description here

still you want to do that things than try following code.

Controller Class

package net.yogesh.test;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.google.gson.Gson;

@Path("test")
public class TestController {
       @Path("testMethod")
       @GET
       @Produces("application/text")
       public String save(
               @QueryParam("list") List<String> list) {

           return  new Gson().toJson(list) ;
       }
}

Client Class

package net.yogesh.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class Client {
    public static void main(String[] args) {
        String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
        System.out.println(op);
    }

    private static String doGet(String url){
        List<String> list = new ArrayList<String>();
        list = Arrays.asList(new String[]{"string1,string2,string3"});

        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
        String lst = (list.toString()).substring(1, list.toString().length()-1);
        params.add("list", lst);

        ClientConfig config = new DefaultClientConfig();
        com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
        WebResource resource = client.resource(url);

        ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
        String en = response.getEntity(String.class);
        return en;
    }
}

hope this'll help you.

gradle build fails on lint task

if abortOnError false will not resolve your problem, you can try this.

lintOptions {
    checkReleaseBuilds false
}

ANTLR: Is there a simple example?

At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4

is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:

  1. parser grammar
  2. lexer grammar
  3. imported LexBasic grammar

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.

Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin

https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr

contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.

PHP PDO with foreach and fetch

foreach over a statement is just a syntax sugar for the regular one-way fetch() loop. If you want to loop over your data more than once, select it as a regular array first

$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO

PHP: HTTP or HTTPS?

This can get more complicated depending on where PHP sits in your environment, since your question is quite broad. This may depend on whether there's a load-balancer and how it's configured. Here are are a few related questions:

Python assigning multiple variables to same value? list behavior

Simply put, in the first case, you are assigning multiple names to a list. Only one copy of list is created in memory and all names refer to that location. So changing the list using any of the names will actually modify the list in memory.

In the second case, multiple copies of same value are created in memory. So each copy is independent of one another.

Warning: The method assertEquals from the type Assert is deprecated

You're using junit.framework.Assert instead of org.junit.Assert.

Which are more performant, CTE or temporary tables?

I'd say they are different concepts but not too different to say "chalk and cheese".

  • A temp table is good for re-use or to perform multiple processing passes on a set of data.

  • A CTE can be used either to recurse or to simply improved readability.
    And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query

  • A temp table is another table with some rules around scope

I have stored procs where I use both (and table variables too)

What is the best place for storing uploaded images, SQL database or disk file system?

Most implementations are option A.

With option B, you open a whole big can of whoop4ss when you marshall those bits from the database into something that can be displayed on a browser... Also, if the db is down, the images are not available.

I don't think that space is too much of an issue... Terabyte drives are a couple hundred bucks now.

We are implementing with option A because we don't have the time or resources to do option B.

Convert int to a bit array in .NET

Use Convert.ToString (value, 2)

so in your case

string binValue = Convert.ToString (3, 2);

Git error on commit after merge - fatal: cannot do a partial commit during a merge

After reading all comments. this was my resolution:
I had to "Add" it again than commit:

$ git commit -i -m support.html "doit once for all" [master 18ea92e] support.html

How to use sessions in an ASP.NET MVC 4 application?

U can store any value in session like Session["FirstName"] = FirstNameTextBox.Text; but i will suggest u to take as static field in model assign value to it and u can access that field value any where in application. U don't need session. session should be avoided.

public class Employee
{
   public int UserId { get; set; }
   public string EmailAddress { get; set; }
   public static string FullName { get; set; }
}

on controller - Employee.FullName = "ABC"; Now u can access this full Name anywhere in application.

-bash: export: `=': not a valid identifier

You cannot put spaces around the = sign when you do:

export foo=bar

Remove the spaces you have and you should be good to go.

If you type:

export foo = bar

the shell will interpret that as a request to export three names: foo, = and bar. = isn't a valid variable name, so the command fails. The variable name, equals sign and it's value must not be separated by spaces for them to be processed as a simultaneous assignment and export.

docker command not found even though installed with apt-get

IMPORTANT - on ubuntu package docker is something entirely different ( avoid it ) :

issue following to view what if any packages you have mentioning docker

dpkg -l|grep docker

if only match is following then you do NOT have docker installed below is an unrelated package

docker - System tray for KDE3/GNOME2 docklet applications

if you see something similar to following then you have docker installed

 dpkg -l|grep docker

ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

NOTE - ubuntu package docker.io is not getting updates ( obsolete do NOT use )


Instead do this : install the latest version of docker on linux by executing the following:

  sudo curl -sSL https://get.docker.com/ | sh
# sudo curl -sSL https://test.docker.com | sh  # get dev pipeline version
  

here is a typical output ( ubuntu 16.04 )

apparmor is enabled in the kernel and apparmor utils were already installed
+ sudo -E sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
Executing: /tmp/tmp.rAAGu0P85R/gpg.1.sh --keyserver
hkp://ha.pool.sks-keyservers.net:80
--recv-keys
58118E89F3A912897C070ADBF76221572C52609D
gpg: requesting key 2C52609D from hkp server ha.pool.sks-keyservers.net
gpg: key 2C52609D: "Docker Release Tool (releasedocker) <[email protected]>" 1 new signature
gpg: Total number processed: 1
gpg:         new signatures: 1
+ break
+ sudo -E sh -c apt-key adv -k 58118E89F3A912897C070ADBF76221572C52609D >/dev/null
+ sudo -E sh -c mkdir -p /etc/apt/sources.list.d
+ dpkg --print-architecture
+ sudo -E sh -c echo deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main > /etc/apt/sources.list.d/docker.list
+ sudo -E sh -c sleep 3; apt-get update; apt-get install -y -q docker-engine
Hit:1 http://repo.steampowered.com/steam precise InRelease
Hit:2 http://download.virtualbox.org/virtualbox/debian xenial InRelease                                                           
Ign:3 http://dl.google.com/linux/chrome/deb stable InRelease                                                                      
Hit:4 http://dl.google.com/linux/chrome/deb stable Release                                                                        
Hit:5 http://archive.canonical.com/ubuntu xenial InRelease                                                                        
Hit:6 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial InRelease                                                     
Hit:7 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-updates InRelease                                             
Hit:8 http://ppa.launchpad.net/me-davidsansome/clementine/ubuntu xenial InRelease                                                 
Ign:9 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 InRelease                                                         
Hit:10 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-backports InRelease                                          
Hit:11 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 Release                                                          
Hit:12 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-security InRelease                                           
Hit:14 http://ppa.launchpad.net/numix/ppa/ubuntu xenial InRelease                                                                 
Ign:15 http://linux.dropbox.com/ubuntu wily InRelease                                                                             
Ign:16 http://repo.vivaldi.com/stable/deb stable InRelease                                                                        
Hit:17 http://repo.vivaldi.com/stable/deb stable Release                                                                          
Get:18 http://linux.dropbox.com/ubuntu wily Release [6,596 B]            
Get:19 https://apt.dockerproject.org/repo ubuntu-xenial InRelease [20.6 kB]    
Ign:20 http://packages.amplify.nginx.com/ubuntu xenial InRelease                      
Hit:22 http://packages.amplify.nginx.com/ubuntu xenial Release
Hit:23 https://deb.opera.com/opera-beta stable InRelease
Hit:26 https://deb.opera.com/opera-developer stable InRelease
Get:28 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 Packages [1,719 B]
Hit:29 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Fetched 28.9 kB in 1s (17.2 kB/s)
Reading package lists... Done
W: http://repo.mongodb.org/apt/debian/dists/wheezy/mongodb-org/3.2/Release.gpg: Signature by key 42F3E95A2C4F08279C4960ADD68FA50FEA312927 uses weak digest algorithm (SHA1)
Reading package lists...
Building dependency tree...
Reading state information...
The following additional packages will be installed:
  aufs-tools cgroupfs-mount
The following NEW packages will be installed:
  aufs-tools cgroupfs-mount docker-engine
0 upgraded, 3 newly installed, 0 to remove and 17 not upgraded.
Need to get 14.6 MB of archives.
After this operation, 73.7 MB of additional disk space will be used.
Get:1 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 aufs-tools amd64 1:3.2+20130722-1.1ubuntu1 [92.9 kB]
Get:2 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 cgroupfs-mount all 1.2 [4,970 B]
Get:3 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 docker-engine amd64 1.11.2-0~xenial [14.5 MB]
Fetched 14.6 MB in 7s (2,047 kB/s)
Selecting previously unselected package aufs-tools.
(Reading database ... 427978 files and directories currently installed.)
Preparing to unpack .../aufs-tools_1%3a3.2+20130722-1.1ubuntu1_amd64.deb ...
Unpacking aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Selecting previously unselected package cgroupfs-mount.
Preparing to unpack .../cgroupfs-mount_1.2_all.deb ...
Unpacking cgroupfs-mount (1.2) ...
Selecting previously unselected package docker-engine.
Preparing to unpack .../docker-engine_1.11.2-0~xenial_amd64.deb ...
Unpacking docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu6) ...
Setting up aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Setting up cgroupfs-mount (1.2) ...
Setting up docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu6) ...
Processing triggers for ureadahead (0.100.0-19) ...
+ sudo -E sh -c docker version
Client:
 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker stens

Remember that you will have to log out and back in for this to take effect!

Here is the underlying detailed install instructions which as you can see comes bundled into above technique ... Above one liner gives you same as :

https://docs.docker.com/engine/installation/linux/ubuntulinux/

Once installed you can see what docker packages were installed by issuing

dpkg -l|grep docker
ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

now Docker updates will get installed going forward when you issue

sudo apt-get update
sudo apt-get upgrade

take a look at

 ls -latr /etc/apt/sources.list.d/*docker*
-rw-r--r-- 1 root root 202 Jun 23 10:01 /etc/apt/sources.list.d/docker.list.save
-rw-r--r-- 1 root root  71 Jul  4 11:32 /etc/apt/sources.list.d/docker.list


cat /etc/apt/sources.list.d/docker.list

deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main

or more generally

cd /etc/apt
grep -r docker *
sources.list.d/docker.list:deb [arch=amd64] https://download.docker.com/linux/ubuntu focal test

Relationship between hashCode and equals method in Java

The contract is that if obj1.equals(obj2) then obj1.hashCode() == obj2.hashCode() , it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.

Datagridview full row selection but get single cell value

I know, I'm a little late for the answer. But I would like to contribute.

DataGridView.SelectedRows[0].Cells[0].Value

This code is simple as piece of cake

How do you use a variable in a regular expression?

As Eric Wendelin mentioned, you can do something like this:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");

This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:

 RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
 };

Then you can do:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

yielding "pattern matching regex".

getting JRE system library unbound error in build path

I too faced the same issue. I followed the following steps to resolve my issue -

  • Right click on your project -> Properties
  • Select Java Build Path in the left menu
  • Select Libraries tab
  • Under the module path, select the troublesome JRE entry
  • Click on Edit button
  • Select Workspace default JRE.
  • Click on Finish button

If the above steps don't work for you, instead of Workspace default JRE, you can choose an Alternate JRE and give the path to the JRE that you want to point.

Set Focus After Last Character in Text Box

One can use these simple javascript within the input tag.

<input type="text" name="your_name" value="your_value"
     onfocus="this.setSelectionRange(this.value.length, this.value.length);" 
autofocus />

How to pass url arguments (query string) to a HTTP request on Angular?

In latest Angular 7/8, you can use the simplest approach:-

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}

What is the difference between a schema and a table and a database?

schema : database : table :: floor plan : house : room

How to solve npm error "npm ERR! code ELIFECYCLE"

This solution is for Windows users.

You can open the node.js installer and give the installer some time to compute space requirements and then click next and click remove. This will remove node.js from your computer and again reopen the installer and install it in this path - C:\Windows\System32

or

Cleaning Cache and Node_module will work. Follow this steps:

  • npm cache clean --force
  • delete node_modules folder
  • delete package-lock.json file
  • npm install

Copy data from another Workbook through VBA

There's very little reason not to open multiple workbooks in Excel. Key lines of code are:

Application.EnableEvents = False
Application.ScreenUpdating = False

...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...

Application.DisplayAlerts = False
Application.Calculation = xlManual

...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming

If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format

Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data

An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:

With Application.FileDialog(msoFileDialogFolderPicker)
.Show
     If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With

FName = VBA.Dir(InputFolder)

Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop

Hopefully some of the above will be of use

How to get the selected date value while using Bootstrap Datepicker?

There are many solutions here but probably the best one that works. Check the version of the script you want to use.

Well at least I can give you my 100% working solution for

version : 4.17.45

bootstrap-datetimejs https://github.com/Eonasdan/bootstrap-datetimepicker Copyright (c) 2015 Jonathan Peterson

JavaScript

var startdate = $('#startdate').val(); 

The output looks like: 12.09.2018 03:05

How to format date and time in Android?

This is my method, you can define and input and output format.

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

Redirect all to index.php using htaccess

just in case you were still wondering how to redirect all request either if the directory exists (for core framework folders and files) to the framework index handler, after some error/success attempts just noticed I just needed to change the RewriteCond in the .htaccess file

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

the above condition states "not found files" and "not found directories", ok, what if just remove "not found" (!-d) line, and ended with something like the below:

RewriteEngine on
RewriteBase /framework/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /framework/index.php [L,QSA]

It worked for me like a charm

Create multiple threads and wait all of them to complete

In my case, I could not instantiate my objects on the the thread pool with Task.Run() or Task.Factory.StartNew(). They would not synchronize my long running delegates correctly.

I needed the delegates to run asynchronously, pausing my main thread for their collective completion. The Thread.Join() would not work since I wanted to wait for collective completion in the middle of the parent thread, not at the end.

With the Task.Run() or Task.Factory.StartNew(), either all the child threads blocked each other or the parent thread would not be blocked, ... I couldn't figure out how to go with async delegates because of the re-serialization of the await syntax.

Here is my solution using Threads instead of Tasks:

using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.ManualReset))
{
  int outdex = mediaServerMinConnections - 1;
  for (int i = 0; i < mediaServerMinConnections; i++)
  {
    new Thread(() =>
    {
      sshPool.Enqueue(new SshHandler());
      if (Interlocked.Decrement(ref outdex) < 1)
        wh.Set();
    }).Start();
  }
  wh.WaitOne();
}

How to remove the Flutter debug banner?

how to remove debug banner in flutter

Just add debugShowCheckedModeBanner: false in MaterialApp.

3 ways - Remove Debug Banner In Flutter

Getting value of selected item in list box as string

If you want to retrieve your value from an list box you should try this:

String itemSelected = numberListBox.GetItemText(numberListBox.SelectedItem);

How to Convert UTC Date To Local time Zone in MySql Select Query

SELECT CONVERT_TZ() will work for that.but its not working for me.

Why, what error do you get?

SELECT CONVERT_TZ(displaytime,'GMT','MET');

should work if your column type is timestamp, or date

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_convert-tz

Test how this works:

SELECT CONVERT_TZ(a_ad_display.displaytime,'+00:00','+04:00');

Check your timezone-table

SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;

http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

If those tables are empty, you have not initialized your timezone tables. According to link above you can use mysql_tzinfo_to_sql program to load the Time Zone Tables. Please try this

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo

or if not working read more: http://dev.mysql.com/doc/refman/5.5/en/mysql-tzinfo-to-sql.html

What is the difference between . (dot) and $ (dollar sign)?

($) allows functions to be chained together without adding parentheses to control evaluation order:

Prelude> head (tail "asdf")
's'

Prelude> head $ tail "asdf"
's'

The compose operator (.) creates a new function without specifying the arguments:

Prelude> let second x = head $ tail x
Prelude> second "asdf"
's'

Prelude> let second = head . tail
Prelude> second "asdf"
's'

The example above is arguably illustrative, but doesn't really show the convenience of using composition. Here's another analogy:

Prelude> let third x = head $ tail $ tail x
Prelude> map third ["asdf", "qwer", "1234"]
"de3"

If we only use third once, we can avoid naming it by using a lambda:

Prelude> map (\x -> head $ tail $ tail x) ["asdf", "qwer", "1234"]
"de3"

Finally, composition lets us avoid the lambda:

Prelude> map (head . tail . tail) ["asdf", "qwer", "1234"]
"de3"

Static Initialization Blocks

It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.

E.g.

static {
    try {
        Class.forName("com.example.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
    }
}

Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff() here throws an Exception which really belongs in a catch block:

private static Object stuff = getStuff(); // Won't compile: unhandled exception.

then a static initializer is useful here. You can handle the exception there.

Another example is to do stuff afterwards which can't be done during assigning:

private static Properties config = new Properties();

static {
    try { 
        config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
    } catch (IOException e) {
        throw new ExceptionInInitializerError("Cannot load properties file.", e);
    }
}

To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static initializer to register itself in the DriverManager. Also see this and this answer.

How to put labels over geom_bar for each bar in R with ggplot2

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)

Android Studio 3.0 Execution failed for task: unable to merge dex

This error happens when you add an external library which may not be compatible with your compileSdkVersion .

Be careful when you are adding an external library.

I spent 2 days on this problem and finally it got solved following these steps.

  • Make sure all your support libraries are same as compileSdkVersion of your build.gradle(Module:app) in my case it is 26. enter image description here

  • In your defaultConfig category type multiDexEnabled true. This is the important part. multiDexEnabled True image

  • Go to File | Settings | Build, Execution, Deployment | Instant Run and try to Enable/Disable Instant Run to hot swap... and click okay Enable Instant Run to Hot swap... Image

  • Sync Your project.

  • Lastly, Go to Build | click on Rebuild Project.

  • Note: Rebuild Project first cleans and then builds the project.

How to get the Google Map based on Latitude on Longitude?

<script>
    function initMap() {
        //echo hiii;

        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(8.5241, 76.9366),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;

        // Change this depending on the name of your PHP or XML file
        downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('package');
            Array.prototype.forEach.call(markers, function(markerElem) {
                var id = markerElem.getAttribute('id');
                // var name = markerElem.getAttribute('name');
                // var address = markerElem.getAttribute('address');
                // var type = markerElem.getAttribute('type');
                // var latitude = results[0].geometry.location.lat();
                // var longitude = results[0].geometry.location.lng();
                var point = new google.maps.LatLng(
                    parseFloat(markerElem.getAttribute('latitude')),
                    parseFloat(markerElem.getAttribute('longitude'))
                );

                var infowincontent = document.createElement('div');
                var strong = document.createElement('strong');
                strong.textContent = name
                infowincontent.appendChild(strong);
                infowincontent.appendChild(document.createElement('br'));

                var text = document.createElement('text');
                text.textContent = address
                infowincontent.appendChild(text);
                var icon = customLabel[type] || {};
                var package = new google.maps.Marker({
                    map: map,
                    position: point,
                    label: icon.label
                });

                package.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, package);
                });
            });
        });
    }


    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

Datatable select method ORDER BY clause

Use

datatable.select("col1='test'","col1 ASC")

Then before binding your data to the grid or repeater etc, use this

datatable.defaultview.sort()

That will solve your problem.

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

You can't specify target table for update in FROM clause

You can make this in three steps:

CREATE TABLE test2 AS
SELECT PersId 
FROM pers p
WHERE (
  chefID IS NOT NULL 
  OR gehalt < (
    SELECT MAX (
      gehalt * 1.05
    )
    FROM pers MA
    WHERE MA.chefID = p.chefID
  )
)

...

UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE PersId
IN (
  SELECT PersId
  FROM test2
)
DROP TABLE test2;

or

UPDATE Pers P, (
  SELECT PersId
  FROM pers p
  WHERE (
   chefID IS NOT NULL 
   OR gehalt < (
     SELECT MAX (
       gehalt * 1.05
     )
     FROM pers MA
     WHERE MA.chefID = p.chefID
   )
 )
) t
SET P.gehalt = P.gehalt * 1.05
WHERE p.PersId = t.PersId

Please explain the exec() function and its family

Simplistically, in UNIX, you have the concept of processes and programs. A process is an environment in which a program executes.

The simple idea behind the UNIX "execution model" is that there are two operations you can do.

The first is to fork(), which creates a brand new process containing a duplicate (mostly) of the current program, including its state. There are a few differences between the two processes which allow them to figure out which is the parent and which is the child.

The second is to exec(), which replaces the program in the current process with a brand new program.

From those two simple operations, the entire UNIX execution model can be constructed.


To add some more detail to the above:

The use of fork() and exec() exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.

The fork() call makes a near duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations, but the idea is to create as close a copy as possible). Only one process calls fork() but two processes return from that call - sounds bizarre but it's really quite elegant

The new process (called the child) gets a different process ID (PID) and has the PID of the old process (the parent) as its parent PID (PPID).

Because the two processes are now running exactly the same code, they need to be able to tell which is which - the return code of fork() provides this information - the child gets 0, the parent gets the PID of the child (if the fork() fails, no child is created and the parent gets an error code).

That way, the parent knows the PID of the child and can communicate with it, kill it, wait for it and so on (the child can always find its parent process with a call to getppid()).

The exec() call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.

So, fork() and exec() are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find - the shell forks, then the child loads the find program into memory, setting up all command line arguments, standard I/O and so forth.

But they're not required to be used together. It's perfectly acceptable for a program to call fork() without a following exec() if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions).

This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening. For this situation, the program contains both the parent and the child code.

Similarly, programs that know they're finished and just want to run another program don't need to fork(), exec() and then wait()/waitpid() for the child. They can just load the child directly into their current process space with exec().

Some UNIX implementations have an optimized fork() which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork() until the program attempts to change something in that space. This is useful for those programs using only fork() and not exec() in that they don't have to copy an entire process space. Under Linux, fork() only makes a copy of the page tables and a new task structure, exec() will do the grunt work of "separating" the memory of the two processes.

If the exec is called following fork (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process, before modifications are allowed.

Linux also has a vfork(), even more optimised, which shares just about everything between the two processes. Because of that, there are certain restrictions in what the child can do, and the parent halts until the child calls exec() or _exit().

The parent has to be stopped (and the child is not permitted to return from the current function) since the two processes even share the same stack. This is slightly more efficient for the classic use case of fork() followed immediately by exec().

Note that there is a whole family of exec calls (execl, execle, execve and so on) but exec in context here means any of them.

The following diagram illustrates the typical fork/exec operation where the bash shell is used to list a directory with the ls command:

+--------+
| pid=7  |
| ppid=4 |
| bash   |
+--------+
    |
    | calls fork
    V
+--------+             +--------+
| pid=7  |    forks    | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash   |             | bash   |
+--------+             +--------+
    |                      |
    | waits for pid 22     | calls exec to run ls
    |                      V
    |                  +--------+
    |                  | pid=22 |
    |                  | ppid=7 |
    |                  | ls     |
    V                  +--------+
+--------+                 |
| pid=7  |                 | exits
| ppid=4 | <---------------+
| bash   |
+--------+
    |
    | continues
    V

How do I order my SQLITE database in descending order, for an android app?

you can do it with this

Cursor cursor = database.query(
            TABLE_NAME,
            YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");

Find the files existing in one directory but not in the other

This answer optimizes one of the suggestions from @Adail-Junior by adding the -D option, which is helpful when neither of the directories being compared are git repositories:

git diff -D --no-index dir1/ dir2/

If you use -D then you won't see comparisons to /dev/null: text Binary files a/whatever and /dev/null differ

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

Send a ping to each IP on a subnet

I would suggest the use of fping with the mask option, since you are not restricting yourself in ping.

fping -g 192.168.1.0/24

The response will be easy to parse in a script:

192.168.1.1 is alive
192.168.1.2 is alive
192.168.1.3 is alive
192.168.1.5 is alive
...
192.168.1.4 is unreachable
192.168.1.6 is unreachable
192.168.1.7 is unreachable
...

Note: Using the argument -a will restrict the output to reachable ip addresses, you may want to use it otherwise fping will also print unreachable addresses:

fping -a -g 192.168.1.0/24

From man:

fping differs from ping in that you can specify any number of targets on the command line, or specify a file containing the lists of targets to ping. Instead of sending to one target until it times out or replies, fping will send out a ping packet and move on to the next target in a round-robin fashion.

More info: http://fping.org/

Upgrading PHP on CentOS 6.5 (Final)

Steps for upgrading to PHP7 on CentOS 6 system. Taken from install-php-7-in-centos-6

To install latest PHP 7, you need to add EPEL and Remi repository to your CentOS 6 system

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-6.rpm

Now install yum-utils, a group of useful tools that enhance yum’s default package management features

yum install yum-utils

In this step, you need to enable Remi repository using yum-config-manager utility, as the default repository for installing PHP.

yum-config-manager --enable remi-php70

If you want to install PHP 7.1 or PHP 7.2 on CentOS 6, just enable it as shown.

yum-config-manager --enable remi-php71 
yum-config-manager --enable remi-php72

Then finally install PHP 7 on CentOS 6 with all necessary PHP modules using the following command.

yum install php php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-zip php-fileinfo

Double check the installed version of PHP on your system as follows.

php -V 

Android 8: Cleartext HTTP traffic not permitted

Upgrade to React Native 0.58.5 or higher version. They have includeSubdomain in their config files in RN 0.58.5.

ChangeLog

In Rn 0.58.5 they have declared network_security_config with their server domain. Network security configuration allows an app to permit cleartext traffic from a certain domain. So no need to put extra effort by declaring android:usesCleartextTraffic="true" in the application tag of your manifest file. It will be resolved automatically after upgrading the RN Version.

jQuery/JavaScript: accessing contents of an iframe

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

What are advantages of Artificial Neural Networks over Support Vector Machines?

One answer I'm missing here: Multi-layer perceptron is able to find relation between features. For example it is necessary in computer vision when a raw image is provided to the learning algorithm and now Sophisticated features are calculated. Essentially the intermediate levels can calculate new unknown features.

Is it possible to use jQuery to read meta tags

$("meta")

Should give you back an array of elements whose tag name is META and then you can iterate over the collection to pick out whatever attributes of the elements you are interested in.

Convert command line arguments into an array in Bash

Actually the list of parameters could be accessed with $1 $2 ... etc.
Which is exactly equivalent to:

${!i}

So, the list of parameters could be changed with set,
and ${!i} is the correct way to access them:

$ set -- aa bb cc dd 55 ff gg hh ii jjj kkk lll
$ for ((i=0;i<=$#;i++)); do echo "$#" "$i" "${!i}"; done
12 1 aa
12 2 bb
12 3 cc
12 4 dd
12 5 55
12 6 ff
12 7 gg
12 8 hh
12 9 ii
12 10 jjj
12 11 kkk
12 12 lll

For your specific case, this could be used (without the need for arrays), to set the list of arguments when none was given:

if [ "$#" -eq 0 ]; then
    set -- defaultarg1 defaultarg2
fi

which translates to this even simpler expression:

[ "$#" == "0" ] && set -- defaultarg1 defaultarg2

Where should I put the CSS and Javascript code in an HTML webpage?

You should put it in the <head>. I typically put style references above JS and I order my JS from top to bottom if some of them are dependent on others, but I beleive all of the references are loaded before the page is rendered.

Passing parameter to controller from route in laravel

    $ php artisan route:list
  +--------+--------------------------------+----------------------------+--    -----------------+----------------------------------------------------+---------  ---+
  | Domain | Method                         | URI                        |  Name              | Action                                             |    Middleware |
  +--------+--------------------------------+----------------------------+-------------------+----------------------------------------------------+------------+
  |        | GET|HEAD                       | /                          |                           
  |        | GET                            | campaign/showtakeup/{id}   | showtakeup         | App\Http\Controllers\campaignController@showtakeup | auth       |     |

routes.php

  Route::get('campaign/showtakeup/{id}', ['uses' =>'campaignController@showtakeup'])->name('showtakeup');

campaign.showtakeup.blade.php

 @foreach($campaign as $campaigns)


   //route parameters; you may pass them as the second argument to the method:

   <a href="{{route('showtakeup', ['id' => $campaigns->id])}}">{{ $campaigns->name }}</a>




            @endforeach

Hope this solves your problem. Thanks

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

Allowed characters in filename

On Windows OS create a file and give it a invalid character like \ in the filename. As a result you will get a popup with all the invalid characters in a filename.

enter image description here

Utility of HTTP header "Content-Type: application/force-download" for mobile?

Content-Type: application/force-download means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".

Use the correct mime type for whatever media you are using (e.g. audio/mpeg for mp3).

Use the Content-Disposition: attachment; etc etc header if you want to encourage the client to download it instead of following the default behaviour.

Double vs. BigDecimal?

BigDecimal is Oracle's arbitrary-precision numerical library. BigDecimal is part of the Java language and is useful for a variety of applications ranging from the financial to the scientific (that's where sort of am).

There's nothing wrong with using doubles for certain calculations. Suppose, however, you wanted to calculate Math.Pi * Math.Pi / 6, that is, the value of the Riemann Zeta Function for a real argument of two (a project I'm currently working on). Floating-point division presents you with a painful problem of rounding error.

BigDecimal, on the other hand, includes many options for calculating expressions to arbitrary precision. The add, multiply, and divide methods as described in the Oracle documentation below "take the place" of +, *, and / in BigDecimal Java World:

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

The compareTo method is especially useful in while and for loops.

Be careful, however, in your use of constructors for BigDecimal. The string constructor is very useful in many cases. For instance, the code

BigDecimal onethird = new BigDecimal("0.33333333333");

utilizes a string representation of 1/3 to represent that infinitely-repeating number to a specified degree of accuracy. The round-off error is most likely somewhere so deep inside the JVM that the round-off errors won't disturb most of your practical calculations. I have, from personal experience, seen round-off creep up, however. The setScale method is important in these regards, as can be seen from the Oracle documentation.

Remove empty elements from an array in Javascript

If you need to remove ALL empty values ("", null, undefined and 0):

arr = arr.filter(function(e){return e}); 

To remove empty values and Line breaks:

arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});

Example:

arr = ["hello",0,"",null,undefined,1,100," "]  
arr.filter(function(e){return e});

Return:

["hello", 1, 100, " "]

UPDATE (based on Alnitak's comment)

In some situations you may want to keep "0" in the array and remove anything else (null, undefined and ""), this is one way:

arr.filter(function(e){ return e === 0 || e });

Return:

["hello", 0, 1, 100, " "]

How to add an image in the title bar using html?

Use the following

1.) Choose the image you want to set in your title bar.
2.) Convert it to ".ico" format. (You can use the following link online) http://image.online-convert.com/convert-to-ico
3.) Save the file as "favicon.ico" in the same folder as your .html file
4.) Add this inside your head tag <link rel="shortcut icon" href="favicon.ico"/>

Trigger change event of dropdown

Try this:

$('#id').change();

Works for me.

On one line together with setting the value: $('#id').val(16).change();

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

Please remove all jar files of Http from 'libs' folder and add below dependencies in gradle file:

compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4.3'

or

useLibrary 'org.apache.http.legacy'

How to update parent's state in React?

As per your question, I understand that you need to display some conditional data in Component 3 which is based on state of Component 5. Approach :

  1. State of Component 3 will hold a variable to check whether Component 5's state has that data
  2. Arrow Function which will change Component 3's state variable.
  3. Passing arrow function to Component 5 with props.
  4. Component 5 has an arrow function which will change Component 3's state variable
  5. Arrow function of Component 5 called on loading itself

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Class Component3 extends React.Component {
    state = {
        someData = true
    }

    checkForData = (result) => {
        this.setState({someData : result})
    }

    render() {
        if(this.state.someData) {
            return(
                <Component5 hasData = {this.checkForData} />
                //Other Data
            );
        }
        else {
            return(
                //Other Data
            );
        }
    }
}

export default Component3;

class Component5 extends React.Component {
    state = {
        dataValue = "XYZ"
    }
    checkForData = () => {
        if(this.state.dataValue === "XYZ") {
            this.props.hasData(true);
        }
        else {
            this.props.hasData(false);
        }
    }
    render() {
        return(
            <div onLoad = {this.checkForData}>
                //Conditional Data
            </div>
        );
    }
}
export default Component5;
_x000D_
_x000D_
_x000D_

How to change the link color in a specific class for a div CSS

smaller-size version:

#register a:link {color: #fff}

Random word generator- Python

Solution for Python 3

For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

import urllib.request

word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

Output:

>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
 'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
 'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]

And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

import random
upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])

And some random names:

>>> for n in range(10):
        ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])

    'Semiramis Sicilian'
    'Julius Genevieve'
    'Rwanda Cohn'
    'Quito Sutherland'
    'Eocene Wheller'
    'Olav Jove'
    'Weldon Pappas'
    'Vienna Leyden'
    'Io Dave'
    'Schwartz Stromberg'

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Goto xampp folder in local drive c, click on mysql folder, then click on bin and finally click on "mysqladmin" application. Then go back and refresh your browser and the problem is solved.

How can I set the initial value of Select2 when using AJAX?

Hi was almost quitting this and go back to select 3.5.1. But finally I got the answer!

$('#test').select2({
    placeholder: "Select a Country",
    minimumResultsForSearch: 2,
    ajax: {
        url: '...',
        dataType: 'json',
        cache: false,
        data: function (params) {
                var queryParameters = {
                    q: params.term
                }
                return queryParameters;
        },
        processResults: function (data) {
            return {
                results: data.items
            };
        }
    }
});

var option1 = new Option("new",true, true);

$('#status').append(option1);

$('#status').trigger('change');

Just be sure that the new option is one of the select2 options. I get this by a json.

window.print() not working in IE

function printDiv() {
    var divToPrint = document.getElementById('printArea');
    newWin= window.open();
    newWin.document.write(divToPrint.innerHTML);
    newWin.location.reload();
    newWin.focus();
    newWin.print();
    newWin.close();
}

What is the (best) way to manage permissions for Docker shared volumes?

The same as you, I was looking for a way to map users/groups from host to docker containers and this is the shortest way I've found so far:

  version: "3"
    services:
      my-service:
        .....
        volumes:
          # take uid/gid lists from host
          - /etc/passwd:/etc/passwd:ro
          - /etc/group:/etc/group:ro
          # mount config folder
          - path-to-my-configs/my-service:/etc/my-service:ro
        .....

This is an extract from my docker-compose.yml.

The idea is to mount (in read-only mode) users/groups lists from the host to the container thus after the container starts up it will have the same uid->username (as well as for groups) matchings with the host. Now you can configure user/group settings for your service inside the container as if it was working on your host system.

When you decide to move your container to another host you just need to change user name in service config file to what you have on that host.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

Make selected block of text uppercase

At Sep 19 2018, these lines worked for me:

File-> Preferences -> Keyboard Shortcuts.

An editor will appear with keybindings.json file. Place the following JSON in there and save.

// Place your key bindings in this file to overwrite the defaults
[
    {
        "key": "ctrl+shift+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
    },
    {
        "key": "ctrl+shift+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
    },

]

How to loop through all elements of a form jQuery

I'm using:

$($('form').prop('elements')).each(function(){
    console.info(this)
});

It Seems ugly, but to me it is still the better way to get all the elements with jQuery.

How can I open a URL in Android's web browser from my application?

Try this..Worked for me!

    public void webLaunch(View view) {
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setVisibility(View.VISIBLE);
            View view1=findViewById(R.id.recharge);
            view1.setVisibility(View.GONE);
            myWebView.getSettings().setJavaScriptEnabled(true);
            myWebView.loadUrl("<your link>");

        }

xml code :-

 <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

--------- OR------------------

String url = "";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

How to detect if javascript files are loaded?

When they say "The bottom of the page" they don't literally mean the bottom: they mean just before the closing </body> tag. Place your scripts there and they will be loaded before the DOMReady event; place them afterwards and the DOM will be ready before they are loaded (because it's complete when the closing </html> tag is parsed), which as you have found will not work.

If you're wondering how I know that this is what they mean: I have worked at Yahoo! and we put our scripts just before the </body> tag :-)

EDIT: also, see T.J. Crowder's reply and make sure you have things in the correct order.

Return zero if no record is found

You could:

SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1
INTO res;

This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table.

Plain queries without aggregate would return no row in such a case. COALESCE would never be called and couldn't save you. While dealing with a single column we can wrap the whole query instead:

SELECT COALESCE( (SELECT columnA FROM my_table WHERE ID = 1), 0)
INTO res;

Works for your original query as well:

SELECT COALESCE( (SELECT SUM(columnA) FROM my_table WHERE columnB = 1), 0)
INTO res;

More about COALESCE() in the manual.
More about aggregate functions in the manual.
More alternatives in this later post:

How do you post to the wall on a facebook page (not profile)

Get PHP SDK from github and run the following code:

<?php
$attachment = array(
    'message' => 'this is my message',
    'name' => 'This is my demo Facebook application!',
    'caption' => "Caption of the Post",
    'link' => 'http://mylink.com',
    'description' => 'this is a description',
    'picture' => 'http://mysite.com/pic.gif',
    'actions' => array(
        array(
            'name' => 'Get Search',
            'link' => 'http://www.google.com'
        )
    )
);

$result = $facebook->api('/me/feed/', 'post', $attachment);

the above code will Post the message on to your wall... and if you want to post onto your friends or others wall then replace me with the Facebook User Id of that user..for further information look out the API Documentation.

TSQL select into Temp table from dynamic sql

Take a look at OPENROWSET, and do something like:

SELECT * INTO #TEMPTABLE FROM OPENROWSET('SQLNCLI'
     , 'Server=(local)\SQL2008;Trusted_Connection=yes;',
     'SELECT * FROM ' + @tableName)

What is the common header format of Python files?

Also see PEP 263 if you are using a non-ascii characterset

Abstract

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.

Proposed Solution

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given.

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

      # coding=<encoding name>

or (using formats recognized by popular editors)

      #!/usr/bin/python
      # -*- coding: <encoding name> -*-

or

      #!/usr/bin/python
      # vim: set fileencoding=<encoding name> :

...

Parsing GET request parameters in a URL that contains another URL

You may have to use urlencode on the string 'http://google.com/?var=234&key=234'

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

How to resolve TypeError: can only concatenate str (not "int") to str

instead of using " + " operator

print( "Alireza" + 1980)

Use comma " , " operator

print( "Alireza" , 1980)

What causes the Broken Pipe Error?

Maybe the 40 bytes fits into the pipe buffer, and the 40000 bytes doesn't?

Edit:

The sending process is sent a SIGPIPE signal when you try to write to a closed pipe. I don't know exactly when the signal is sent, or what effect the pipe buffer has on this. You may be able to recover by trapping the signal with the sigaction call.

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

How can I load storyboard programmatically from class?

In your storyboard go to the Attributes inspector and set the view controller's Identifier. You can then present that view controller using the following code.

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];

Is there any way I can define a variable in LaTeX?

add the following to you preamble:

\newcommand{\newCommandName}{text to insert}

Then you can just use \newCommandName{} in the text

For more info on \newcommand, see e.g. wikibooks

Example:

\documentclass{article}
\newcommand\x{30}
\begin{document}
\x
\end{document}

Output:

30

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How to get page content using cURL?

this is how:

   /**
     * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
     * array containing the HTTP server response header fields and content.
     */
    function get_web_page( $url )
    {
        $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';

        $options = array(

            CURLOPT_CUSTOMREQUEST  =>"GET",        //set request type post or get
            CURLOPT_POST           =>false,        //set to GET
            CURLOPT_USERAGENT      => $user_agent, //set user agent
            CURLOPT_COOKIEFILE     =>"cookie.txt", //set cookie file
            CURLOPT_COOKIEJAR      =>"cookie.txt", //set cookie jar
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['content'] = $content;
        return $header;
    }

Example

//Read a web page and check for errors:

$result = get_web_page( $url );

if ( $result['errno'] != 0 )
    ... error: bad url, timeout, redirect loop ...

if ( $result['http_code'] != 200 )
    ... error: no page, no permissions, no service ...

$page = $result['content'];

Python: most idiomatic way to convert None to empty string?

def xstr(s):
    return s if s else ''

s = "%s%s" % (xstr(a), xstr(b))

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

socket programming multiple client to one server

See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.

Pay attention that accept() is not thread safe, so the call is wrapped within synchronized.

64: synchronized(servSock) {
65:     clientSocket = servSock.accept();
66: }

How do I overload the square-bracket operator in C#?

Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded, 
                                    but only as pairs.

&&, ||                  They can't be overloaded

() (Conversion operator)        They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be 
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!

Source of the information

For bracket:

public Object this[int index]
{

}

BUT

The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).

From MSDN

How do I set proxy for chrome in python webdriver?

I had an issue with the same thing. ChromeOptions is very weird because it's not integrated with the desiredcapabilities like you would think. I forget the exact details, but basically ChromeOptions will reset to default certain values based on whether you did or did not pass a desired capabilities dict.

I did the following monkey-patch that allows me to specify my own dict without worrying about the complications of ChromeOptions

change the following code in /selenium/webdriver/chrome/webdriver.py:

def __init__(self, executable_path="chromedriver", port=0,
             chrome_options=None, service_args=None,
             desired_capabilities=None, service_log_path=None, skip_capabilities_update=False):
    """
    Creates a new instance of the chrome driver.

    Starts the service and then creates new instance of chrome driver.

    :Args:
     - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
     - port - port you would like the service to run, if left as 0, a free port will be found.
     - desired_capabilities: Dictionary object with non-browser specific
       capabilities only, such as "proxy" or "loggingPref".
     - chrome_options: this takes an instance of ChromeOptions
    """
    if chrome_options is None:
        options = Options()
    else:
        options = chrome_options

    if skip_capabilities_update:
        pass
    elif desired_capabilities is not None:
        desired_capabilities.update(options.to_capabilities())
    else:
        desired_capabilities = options.to_capabilities()

    self.service = Service(executable_path, port=port,
        service_args=service_args, log_path=service_log_path)
    self.service.start()

    try:
        RemoteWebDriver.__init__(self,
            command_executor=self.service.service_url,
            desired_capabilities=desired_capabilities)
    except:
        self.quit()
        raise 
    self._is_remote = False

all that changed was the "skip_capabilities_update" kwarg. Now I just do this to set my own dict:

capabilities = dict( DesiredCapabilities.CHROME )

if not "chromeOptions" in capabilities:
    capabilities['chromeOptions'] = {
        'args' : [],
        'binary' : "",
        'extensions' : [],
        'prefs' : {}
    }

capabilities['proxy'] = {
    'httpProxy' : "%s:%i" %(proxy_address, proxy_port),
    'ftpProxy' : "%s:%i" %(proxy_address, proxy_port),
    'sslProxy' : "%s:%i" %(proxy_address, proxy_port),
    'noProxy' : None,
    'proxyType' : "MANUAL",
    'class' : "org.openqa.selenium.Proxy",
    'autodetect' : False
}

driver = webdriver.Chrome( executable_path="path_to_chrome", desired_capabilities=capabilities, skip_capabilities_update=True )

jQuery.post( ) .done( ) and success:

Both .done() and .success() are callback functions and they essentially function the same way.

Here's the documentation. The difference is that .success() is deprecated as of jQuery 1.8. You should use .done() instead.

In case you don't want to click the link:

Deprecation Notice

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Suppose you have COMPANY and EMPLOYEE. COMPANY has many EMPLOYEES (i.e. EMPLOYEE has a field COMPANY_ID).

In some O/R configurations, when you have a mapped Company object and go to access its Employee objects, the O/R tool will do one select for every employee, wheras if you were just doing things in straight SQL, you could select * from employees where company_id = XX. Thus N (# of employees) plus 1 (company)

This is how the initial versions of EJB Entity Beans worked. I believe things like Hibernate have done away with this, but I'm not too sure. Most tools usually include info as to their strategy for mapping.

Call async/await functions in parallel

Update:

The original answer makes it difficult (and in some cases impossible) to correctly handle promise rejections. The correct solution is to use Promise.all:

const [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);

Original answer:

Just make sure you call both functions before you await either one:

// Call both functions
const somePromise = someCall();
const anotherPromise = anotherCall();

// Await both promises    
const someResult = await somePromise;
const anotherResult = await anotherPromise;

Compare 2 arrays which returns difference

/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                    difference.push(array1[i]);
        }
    }

    return difference;
}   

You can then call the function anywhere in your code.

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

Why is "cursor:pointer" effect in CSS not working

My problem was using cursor: 'pointer' mistakenly instead of cursor: pointer. So, make sure you are not adding single or double quotes around pointer.

C++ code file extension? .cc vs .cpp

Great advice on which to use for the makefile and other tools, considering non-compiler tools while deciding on which extension to use is a great approach to help find an answer that works for you.

I just wanted to add the following to help with some .cc vs .cpp info that I found. The following are extensions broken down by different environments (from the "C++ Primer Plus" book):

Unix uses: .C, .cc, .cxx, .c

GNU C++ uses: .C, .cc, .cxx, .cpp, .c++

Digital Mars uses: .cpp, .cxx

Borland C++ uses: .cpp

Watcom uses: .cpp

Microsoft Visual C++ uses: .cpp, .cxx, .cc

Metrowerks CodeWarrior uses: .cpp, .cp, .cc, .cxx, .c++

The different environments support different extensions. I too was looking to answer this question and found this post. Based on this post I think I might go with .hpp and .cpp for ease of cross-platform/cross-tool recognition.

Add Whatsapp function to website, like sms, tel

Use:

https://wa.me/YOURNUMBER

where YOURNUMBER is without the two leading 00.

For instance for +37061204312 you write:

https://wa.me/37061204312

This link seems to work on mobiles and on desktop computers.

To prefill the message with text you can use:

https://wa.me/YOURNUMBER/?text=urlencodedtext

More in the Whatsapp FAQ: https://faq.whatsapp.com/en/android/26000030/

How to script FTP upload and download?

Try manually:

$ ftp www.domainhere.com 
> useridhere
> passwordhere
> put test.txt
> bye
> pause

Change WPF window background image in C# code

The problem is the way you are using it in code. Just try the below code

public partial class MainView : Window
{
    public MainView()
    {
        InitializeComponent();

        ImageBrush myBrush = new ImageBrush();
        myBrush.ImageSource =
            new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
        this.Background = myBrush;
    }
}

You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx

Visual Studio: How to show Overloads in IntelliSense?

Ctrl+Shift+Space shows the Edit.ParameterInfo for the selected method, and by selected method I mean the caret must be within the method parentheses.

Here is the Visual Studio 2010 Keybinding Poster.

And for those still using 2008.

Make anchor link go some pixels above where it's linked to

Put this in style :

.hash_link_tag{margin-top: -50px; position: absolute;}

and use this class in separate div tag before the links, example:

<div class="hash_link_tag" id="link1"></div> 
<a href="#link1">Link1</a>

or use this php code for echo link tag:

function HashLinkTag($id)
{
    echo "<div id='$id' class='hash_link_tag'></div>";
}

How to get a context in a recycler view adapter

Create a constructor of FeedAdapter :

Context context; //global
public FeedAdapter(Context context)
{
   this.context = context;  
}

and in Activity

FeedAdapter obj = new FeedAdapter(this);

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();