Programs & Examples On #Built in types

What Ruby IDE do you prefer?

Redcar has been getting some attention lately, as well. Still early in its life, but it shows promise.

How to take MySQL database backup using MySQL Workbench?

In Workbench 6.3 it is supereasy:

  1. On the "HOME"-view select one of the MySQL Connections: (localhost)
  2. In the "Localhost" view click on "Server"--> "Data export"
  3. In the "Data Export" view select the table(s) and whether you want to export only their structure, or structure and data,...
  4. Click "Start Export"

SQL Query for Logins

@allain, @GateKiller your query selects users not logins
To select logins you can use this query:

SELECT name FROM master..sysxlogins WHERE sid IS NOT NULL

In MSSQL2005/2008 syslogins table is used insted of sysxlogins

Oracle: How to find out if there is a transaction pending?

you can check if your session has a row in V$TRANSACTION (obviously that requires read privilege on this view):

SQL> SELECT COUNT(*)
       FROM v$transaction t, v$session s, v$mystat m
      WHERE t.ses_addr = s.saddr
        AND s.sid = m.sid
        AND ROWNUM = 1;

  COUNT(*)
----------
         0

SQL> insert into a values (1);

1 row inserted

SQL> SELECT COUNT(*)
       FROM v$transaction t, v$session s, v$mystat m
      WHERE t.ses_addr = s.saddr
        AND s.sid = m.sid
        AND ROWNUM = 1;

  COUNT(*)
----------
         1

SQL> commit;

Commit complete

SQL> SELECT COUNT(*)
       FROM v$transaction t, v$session s, v$mystat m
      WHERE t.ses_addr = s.saddr
        AND s.sid = m.sid
        AND ROWNUM = 1;

  COUNT(*)
----------
         0

How does `scp` differ from `rsync`?

scp is best for one file.
OR a combination of tar & compression for smaller data sets like source code trees with small resources (ie: images, sqlite etc).


Yet, when you begin dealing with larger volumes say:

  • media folders (40 GB)
  • database backups (28 GB)
  • mp3 libraries (100 GB)

It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.

As an exercise, you can do some gymnastics like piping tar into ssh and redirecting the results into a remote file. (saving the need to build a swap or temporary clone aka zip or tar.gz)

However,

rsync simplify's this process and allows you to transfer data without consuming any additional disc space.

Also,

Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.

tl;dr
scp == small scale (with room to build compressed files on the same drive)
rsync == large scale (with the necessity to backup large data and no room left)

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

jQuery - Fancybox: But I don't want scrollbars!

I had I guess the same issue. It wasnt what the fancybox properties or CSS was, but the main css for my site.

if you have something like

div {overflow:auto;height:auto;} 

for a inheritable/root in your site css then it will cause scroll bar issues in the fancy box. Remove and make your HTML and CSS more precise with IDs and classes

How to Pass data from child to parent component Angular

Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.

The easiest way is to pass "startdate" and "endDate" as input

<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>

In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks

How to access global js variable in AngularJS directive

Copy the global variable to a variable in the scope in your controller.

function MyCtrl($scope) {
   $scope.variable1 = variable1;
}

Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).

But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.

PDOException SQLSTATE[HY000] [2002] No such file or directory

Step 1

Find the path to your unix_socket, to do that just run netstat -ln | grep mysql

You should get something like this

unix  2      [ ACC ]     STREAM     LISTENING     17397    /var/run/mysqld/mysqld.sock

Step 2

Take that and add it in your unix_socket param

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => '67.25.71.187',
            'database'  => 'dbname',
            'username'  => 'username',
            'password'  => '***',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'unix_socket'    => '/var/run/mysqld/mysqld.sock' <-----
            ),
        ),

Hope it helps !!

no debugging symbols found when using gdb

The application has to be both compiled and linked with -g option. I.e. you need to put -g in both CPPFLAGS and LDFLAGS.

How do we change the URL of a working GitLab install?

Actually, this is NOT totally correct. I arrived at this page, trying to answer this question myself, as we are transitioning production GitLab server from http:// to https:// and most stuff is working as described above, but when you login to https://server and everything looks fine ... except when you browse to a project or repository, and it displays the SSH and HTTP instructions... It says "http" and the instructions it displays also say "http".

I found some more things to edit though:

/home/git/gitlab/config/gitlab.yml
  production: &base
    gitlab:
      host: git.domain.com

      # Also edit these:
      port: 443
      https: true
...

and

/etc/nginx/sites-available/gitlab
  server {
    server_name git.domain.com;

    # Also edit these:
    listen 443 ssl;
    ssl_certificate     /etc/ssl/certs/somecert.crt;
    ssl_certificate_key /etc/ssl/private/somekey.key;

...

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

I have come to point out the answer nobody seems to see here. You can fullfill all requests you have made with pure CSS and it's very simple. Just use Media Queries. Media queries can check the orientation of the user's screen, or viewport. Then you can style your images depending on the orientation.

Just set your default CSS on your images like so:

img {
   width:auto;
   height:auto;
   max-width:100%;
   max-height:100%;
}

Then use some media queries to check your orientation and that's it!

@media (orientation: landscape) { img { height:100%; } }
@media (orientation: portrait) { img { width:100%; } }

You will always get an image that scales to fit the screen, never loses aspect ratio, never scales larger than the screen, never clips or overflows.

To learn more about these media queries, you can read MDN's specs.

Centering

To center your image horizontally and vertically, just use the flex box model. Use a parent div set to 100% width and height, like so:

div.parent {
   display:flex;
   position:fixed;
   left:0px;
   top:0px;
   width:100%;
   height:100%;
   justify-content:center;
   align-items:center;
}

With the parent div's display set to flex, the element is now ready to use the flex box model. The justify-content property sets the horizontal alignment of the flex items. The align-items property sets the vertical alignment of the flex items.

Conclusion

I too had wanted these exact requirements and had scoured the web for a pure CSS solution. Since none of the answers here fulfilled all of your requirements, either with workarounds or settling upon sacrificing a requirement or two, this solution really is the most straightforward for your goals; as it fulfills all of your requirements with pure CSS.

EDIT: The accepted answer will only appear to work if your images are large. Try using small images and you will see that they can never be larger than their original size.

navbar color in Twitter Bootstrap

If you havent got time to learn "less" or do it properly, here's a dirty hack...

Add this above where you render the bootstrap nav bar HTML - update the colours as required..

<style type="text/css">   

.navbar-inner {
    background-color: red;
    background-image: linear-gradient(to bottom, blue, green);
    background-repeat: repeat-x;
    border: 1px solid yellow;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.067);
    min-height: 40px;
    padding-left: 20px;
    padding-right: 20px;
}

.dropdown-menu {
    background-clip: padding-box;
    background-color: red;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 6px 6px 6px 6px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    display: none;
    float: left;
    left: 0;
    list-style: none outside none;
    margin: 2px 0 0;
    min-width: 160px;
    padding: 5px 0;
    position: absolute;
    top: 100%;
    z-index: 1000;
}

.btn-group.open .btn.dropdown-toggle {
  background-color: red;
}

.btn-group.open .btn.dropdown-toggle {
  background-color:lime;
}

.navbar .nav li.dropdown.open > .dropdown-toggle,
.navbar .nav li.dropdown.active > .dropdown-toggle,
.navbar .nav li.dropdown.open.active > .dropdown-toggle {
  color:white;
  background-color:Teal;
}

.navbar .nav > li > a {
    color: white;
    float: none;
    padding: 10px 15px;
    text-decoration: none;
    text-shadow: 0 0px 0 #ffffff;
}

.navbar .brand {
  display: block;
  float: left;
  padding: 10px 20px 10px;
  margin-left: -20px;
  font-size: 20px;
  font-weight: 200;
  color: white;
  text-shadow: 0 0px 0 #ffffff;
}

.navbar .nav > li > a:focus,
.navbar .nav > li > a:hover {
  color: white;
  text-decoration: none;
  background-color: transparent;
}

.navbar-text {
  margin-bottom: 0;
  line-height: 40px;
  color: white;
}

.dropdown-menu li > a {
  display: block;
  padding: 3px 20px;
  clear: both;
  font-weight: normal;
  line-height: 20px;
  color: white;
  white-space: nowrap;
}

.navbar-link {
  color: white;
}

.navbar-link:hover {
  color: white;
}

</style>

What are the "spec.ts" files generated by Angular CLI for?

if you generate new angular project using "ng new", you may skip a generating of spec.ts files. For this you should apply --skip-tests option.

ng new ng-app-name --skip-tests

Cannot access wamp server on local network

Wamp server share in local network

Reference Link: http://forum.aminfocraft.com/blog/view/141/wamp-server-share-in-local-netword

Edit your Apache httpd.conf:

Options FollowSymLinks
AllowOverride None
Order deny,allow
Allow from all
#Deny from all

and

#onlineoffline tag - don't remove
Order Deny,Allow
Allow from all
#Deny from all

to share mysql server:

edit wamp/alias/phpmyadmin.conf

<Directory "E:/wamp/apps/phpmyadmin3.2.0.1/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order Deny,Allow
    #Deny from all
    Allow from all


html div onclick event

Try this

$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
    alert('123');
});

$('#ancherComplaint').click(function (event) {
    alert($(this).attr("id"));
    event.stopPropagation()
})

DEMO

What is the best way to access redux store outside a react component?

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.

MyStore.js

const store = createStore(myReducer);
export store;

or

const store = createStore(myReducer);
export default store;

MyClient.js

import {store} from './MyStore'
store.dispatch(...)

or if you used default

import store from './MyStore'
store.dispatch(...)

For Multiple Store Use Cases

If you need multiple instances of a store, export a factory function. I would recommend making it async (returning a promise).

async function getUserStore (userId) {
   // check if user store exists and return or create it.
}
export getUserStore

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

On Selenium WebDriver how to get Text from Span Tag

Pythonic way to get text from Span tags:

driver.find_element_by_xpath("//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel clear')]").text

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

You could use RAISE_APPLICATION_ERROR like this:

DECLARE
    ex_custom       EXCEPTION;
BEGIN
    RAISE ex_custom;
EXCEPTION
    WHEN ex_custom THEN
        RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/

That will raise an exception that looks like:

ORA-20001: My exception was raised

The error number can be anything between -20001 and -20999.

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You'll need AJAX if you want to update a part of your page without reloading the entire page.

main cshtml view

<div id="refTable">
     <!-- partial view content will be inserted here -->
</div>

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>

<script>
    $(document).ready(function() {
        $("#pY").on("click", function() {
            var val = $('#yearSelect3').val();
            $.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });
        });
    });
</script>

You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.

The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.

HolidayController Update action

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.

view model

public class HolidayViewModel
{
    IEnumerable<DateTime> Dates { get; set; }
}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;

<table class="tblHoliday">
    @foreach(var date in Model.Dates)
    {
        <tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
    }
</table>

This is the stuff that gets inserted into your div.

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

Find all zero-byte files in directory and subdirectories

As addition to the answers above:

If you would like to delete those files

find $dir -size 0 -type f -delete

Display HTML snippets in HTML

Ultimately the best (though annoying) answer is "escape the text".

There are however a lot of text editors -- or even stand-alone mini utilities -- that can do this automatically. So you never should have to escape it manually if you don't want to (Unless it's a mix of escaped and un-escaped code...)

Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html

Update UI from Thread in Android

Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).

Easy way to get a test file into JUnit

You can try doing:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

How to install lxml on Ubuntu

Since you're on Ubuntu, don't bother with those source packages. Just install those development packages using apt-get.

apt-get install libxml2-dev libxslt1-dev python-dev

If you're happy with a possibly older version of lxml altogether though, you could try

apt-get install python-lxml

and be done with it. :)

How to cherry-pick multiple commits

Here's a script that will allow you to cherry-pick multiple commits in a row simply by telling the script which source and target branches for the cherry picks and the number of commits:

https://gist.github.com/nickboldt/99ac1dc4eb4c9ff003a1effef2eb2d81

To cherry-pick from your branch to master (uses the current branch as source):

./gcpl.sh -m

To cherry-pick the latest 5 commits from your 6.19.x branch to master:

./gcpl.sh -c 5 -s 6.19.x -t master

Browser Timeouts

It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827

Firefox is around the same value I think as well.

Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.

You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

Generating random numbers with normal distribution in Excel

Take a loot at the Wikipedia article on random numbers as it talks about using sampling techniques. You can find the equation for your normal distribution by plugging into this one

pdf for normal distro

(equation via Wikipedia)

As for the second issue, go into Options under the circle Office icon, go to formulas, and change calculations to "Manual". That will maintain your sheet and not recalculate the formulas each time.

PHP string "contains"

PHP 8 or newer:

Use the str_contains function.

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

else
{
    echo 'Not found.';
}

PHP 7 or older:

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

else
{
    echo 'Not found.';
}

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

Read entire file in Scala?

you can also use Path from scala io to read and process files.

import scalax.file.Path

Now you can get file path using this:-

val filePath = Path("path_of_file_to_b_read", '/')
val lines = file.lines(includeTerminator = true)

You can also Include terminators but by default it is set to false..

How can I get city name from a latitude and longitude point?

There are many tools available

  1. google maps API as like all had written
  2. use this data "https://simplemaps.com/data/world-cities" download free version and convert excel to JSON with some online converter like "http://beautifytools.com/excel-to-json-converter.php"
  3. use IP address which is not good because using IP address of someone may not good users think that you can hack them.

other free and paid tools are available also

Oracle date function for the previous month

The trunc() function truncates a date to the specified time period; so trunc(sysdate,'mm') would return the beginning of the current month. You can then use the add_months() function to get the beginning of the previous month, something like this:

select count(distinct switch_id)   
  from [email protected]  
 where dealer_name =  'XXXX'    
   and creation_date >= add_months(trunc(sysdate,'mm'),-1) 
   and creation_date < trunc(sysdate, 'mm')

As a little side not you're not explicitly converting to a date in your original query. Always do this, either using a date literal, e.g. DATE 2012-08-31, or the to_date() function, for example to_date('2012-08-31','YYYY-MM-DD'). If you don't then you are bound to get this wrong at some point.

You would not use sysdate - 15 as this would provide the date 15 days before the current date, which does not seem to be what you are after. It would also include a time component as you are not using trunc().


Just as a little demonstration of what trunc(<date>,'mm') does:

select sysdate
     , case when trunc(sysdate,'mm') > to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as gt
     , case when trunc(sysdate,'mm') < to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as lt
     , case when trunc(sysdate,'mm') = to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as eq
  from dual
       ;

SYSDATE                   GT         LT         EQ
----------------- ---------- ---------- ----------
20120911 19:58:51                                1

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also

// 24 = 192 bits
    private const int SaltByteSize = 24;
    private const int HashByteSize = 24;
    private const int HasingIterationsCount = 10101;


    public static string HashPassword(string password)
    {
        // http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing

        byte[] salt;
        byte[] buffer2;
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
        {
            salt = bytes.Salt;
            buffer2 = bytes.GetBytes(HashByteSize);
        }
        byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
        Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
        Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
        return Convert.ToBase64String(dst);
    }

    public static bool VerifyHashedPassword(string hashedPassword, string password)
    {
        byte[] _passwordHashBytes;

        int _arrayLen = (SaltByteSize + HashByteSize) + 1;

        if (hashedPassword == null)
        {
            return false;
        }

        if (password == null)
        {
            throw new ArgumentNullException("password");
        }

        byte[] src = Convert.FromBase64String(hashedPassword);

        if ((src.Length != _arrayLen) || (src[0] != 0))
        {
            return false;
        }

        byte[] _currentSaltBytes = new byte[SaltByteSize];
        Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);

        byte[] _currentHashBytes = new byte[HashByteSize];
        Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);

        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
        {
            _passwordHashBytes = bytes.GetBytes(SaltByteSize);
        }

        return AreHashesEqual(_currentHashBytes, _passwordHashBytes);

    }

    private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
    {
        int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
        var xor = firstHash.Length ^ secondHash.Length;
        for (int i = 0; i < _minHashLength; i++)
            xor |= firstHash[i] ^ secondHash[i];
        return 0 == xor;
    }

In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.

JavaScript: function returning an object

You can simply do it like this with an object literal:

function makeGamePlayer(name,totalScore,gamesPlayed) {
    return {
        name: name,
        totalscore: totalScore,
        gamesPlayed: gamesPlayed
    };
}

How to get a reversed list view on a list in Java?

Guava provides this: Lists.reverse(List)

List<String> letters = ImmutableList.of("a", "b", "c");
List<String> reverseView = Lists.reverse(letters); 
System.out.println(reverseView); // [c, b, a]

Unlike Collections.reverse, this is purely a view... it doesn't alter the ordering of elements in the original list. Additionally, with an original list that is modifiable, changes to both the original list and the view are reflected in the other.

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<input type="text" value="default!" id="myInput" />

JavaScript

$(document).ready(function (){
    $('#myInput').keyup(function(event) {
        // 27 is key code of ESC
        if (event.keyCode == 27) {
            $('#myInput').val('default!');
            // Loose focus on input field
            $('#myInput').blur();
        }
    });
});

Working source can be found here: http://jsfiddle.net/S3N5H/1/

Please let me know if you meant something different, I can adjust the code later.

Extract column values of Dataframe as List in Apache Spark

An updated solution that gets you a list:

dataFrame.select("YOUR_COLUMN_NAME").map(r => r.getString(0)).collect.toList

Bootstrap select dropdown list placeholder

Try this:

<select class="form-control" required>
<option value="" selected hidden>Select...</option>

when using required + value="" then user can not select it using hidden will make it hidden from the options list, when the user open the options box

MySQL parameterized queries

Here is another way to do it. It's documented on the MySQL official website. https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

In the spirit, it's using the same mechanic of @Trey Stout's answer. However, I find this one prettier and more readable.

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

And to better illustrate any need for variables:

NB: note the escape being done.

employee_id = 2
first_name = "Jane"
last_name = "Doe"

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (employee_id, conn.escape_string(first_name), conn.escape_string(last_name), datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

Reload child component when variables on parent component changes. Angular2

You can use @input with ngOnChanges, to see the changes when it happened.

reference: https://angular.io/api/core/OnChanges

(or)

If you want to pass data between multiple component or routes then go with Rxjs way.

Service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MessageService {
  private subject = new Subject<any>();

  sendMessage(message: string) {
    this.subject.next({ text: message });
  }

  clearMessages() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }
}

Component.ts

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

import { MessageService } from './_services/index';

@Component({
  selector: 'app',
  templateUrl: 'app.component.html'
})

export class AppComponent implements OnDestroy {
  messages: any[] = [];
  subscription: Subscription;

  constructor(private messageService: MessageService) {
    // subscribe to home component messages
    this.subscription = this.messageService.getMessage().subscribe(message => {
      if (message) {
        this.messages.push(message);
      } else {
        // clear messages when empty message received
        this.messages = [];
      }
    });
  }

  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }
}

Reference: http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject

jQuery ajax success error

You did not provide your validate.php code so I'm confused. You have to pass the data in JSON Format when when mail is success. You can use json_encode(); PHP function for that.

Add json_encdoe in validate.php in last

mail($to, $subject, $message, $headers); 
echo json_encode(array('success'=>'true'));

JS Code

success: function(data){ 
     if(data.success == true){ 
       alert('success'); 
    } 

Hope it works

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

For me it wasn't an angular problem. Was a field of type DateTime in the DB that has a value of (0000-00-00) and my model cannot bind that property correct so I changed to a valid value like (2019-08-12).

I'm using .net core, OData v4 and MySql (EF pomelo connector)

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

In case the remote repository is not empty (this is the case if you are using IBM DevOps on hub.jazz.net) then you need to use the following sequence:

cd <localDir>
git init
git add -A .
git pull <url> master
git commit -m "message"
git remote add origin <url>
git push

EDIT 30th Jan 17: Please see comments below, make sure you are on the correct repo!

const to Non-const Conversion in C++

Changing a constant type will lead to an Undefined Behavior.

However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.

Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.

HTML: Changing colors of specific words in a string of text

use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>

SQLite3 database or disk is full / the database disk image is malformed

During app development I found that the messages come from the frequent and massive INSERT and UPDATE operations. Make sure to INSERT and UPDATE multiple rows or data in one single operation.

var updateStatementString : String! = ""

for item in cardids {
    let newstring = "UPDATE "+TABLE_NAME+" SET pendingImages = '\(pendingImage)\' WHERE cardId = '\(item)\';"
    updateStatementString.append(newstring)
}

print(updateStatementString)

let results = dbManager.sharedInstance.update(updateStatementString: updateStatementString)

return Int64(results)

How can I trigger an onchange event manually?

For those using jQuery there's a convenient method: http://api.jquery.com/change/

How to save a bitmap on internal storage

private static void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();

    String fname = "Image-"+ o +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

What is %timeit in python?

I would just like to add another useful advantage of using %timeit to answer by mu ? that:

  • You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit to built the variable that is built in an another enviroment that timeit works.

PS: I know this should be a comment to answer above but I currently don't have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.

"unmappable character for encoding" warning in Java

Use the "\uxxxx" escape format.

According to Wikipedia, the copyright symbol is unicode U+00A9 so your line should read:

String copyright = "\u00a9 2003-2008 My Company. All rights reserved.";

Use Excel pivot table as data source for another Pivot Table

As @nutsch implies, Excel won't do what you need directly, so you have to copy your data from the pivot table to somewhere else first. Rather than using copy and then paste values, however, a better way for many purposes is to create some hidden columns or a whole hidden sheet that copies values using simple formulae. The copy-paste approach isn't very useful when the original pivot table gets refreshed.

For instance, if Sheet1 contains the original pivot table, then:

  • Create Sheet2 and put =Sheet1!A1 into Sheet2!A1
  • Copy that formula around as many cells in Sheet2 as required to match the size of the original pivot table.
  • Assuming that the original pivot table could change size whenever it is refreshed, you could copy the formula in Sheet2 to cover the whole of the potential area the original pivot table could ever take. That will put lots of zeros in cells where the original cells are currently empty, but you could avoid that by using the formula =IF(Sheet1!A1="","",Sheet1!A1) instead.
  • Create your new pivot table based on a range within Sheet2, then hide Sheet2.

Matrix multiplication using arrays

My code is super easy and works for any order of matrix

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter No. of rows in matrix 1 : ");
    int arows = sc.nextInt();
    System.out.println(" Enter No. of columns in matrix 1 : ");
    int acols = sc.nextInt();
    System.out.println(" Enter No. of rows in matrix 2 : ");
    int brows = sc.nextInt();
    System.out.println(" Enter No. of columns in matrix 2 : ");
    int bcols = sc.nextInt();
    if (acols == brows) {
        System.out.println(" Enter elements of matrix 1 ");
        int a[][] = new int[arows][acols];
        int b[][] = new int[brows][bcols];
        for (int i = 0; i < arows; i++) {
            for (int j = 0; j < acols; j++) {
                a[i][j] = sc.nextInt();
            }
        }
        System.out.println(" Enter elements of matrix 2 ");
        for (int i = 0; i < brows; i++) {
            for (int j = 0; j < bcols; j++) {
                b[i][j] = sc.nextInt();
            }
        }
        System.out.println(" The Multiplied matrix is : ");
        int sum = 0;
        int c[][] = new int[arows][bcols];
        for (int i = 0; i < arows; i++) {
            for (int j = 0; j < bcols; j++) {
                for (int k = 0; k < brows; k++) {
                    sum = sum + a[i][k] * b[k][j];
                    c[i][j] = sum;
                }

                System.out.print(c[i][j] + " ");
                sum = 0;
            }
            System.out.println();
        }
    } else {
        System.out.println("Order of matrix in invalid");
    }
}

Delete all but the most recent X files in bash

Ignoring newlines is ignoring security and good coding. wnoise had the only good answer. Here is a variation on his that puts the filenames in an array $x

while IFS= read -rd ''; do 
    x+=("${REPLY#* }"); 
done < <(find . -maxdepth 1 -printf '%T@ %p\0' | sort -r -z -n )

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

A valid provisioning profile for this executable was not found for debug mode

I got this error while following a guide to create a separate target for development mode and production mode.

The mistake I made was creating a Distribution provisioning profile, and assigning that to the production mode target. Distribution profiles are not associated with debug devices, so of course the error appeared.

The solution was to create a second development provisioning profile and using that instead.

Circle button css

For div tag there is already default property display:block given by browser. For anchor tag there is not display property given by browser. You need to add display property to it. That's why use display:block or display:inline-block. It will work.

_x000D_
_x000D_
.btn {_x000D_
  display:block;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  border-radius: 50%;_x000D_
  border: 1px solid red;_x000D_
  _x000D_
}
_x000D_
<a class="btn" href="#"><i class="ion-ios-arrow-down"></i></a>
_x000D_
_x000D_
_x000D_

Where's the DateTime 'Z' format specifier?

Round tripping dates through strings has always been a pain...but the docs to indicate that the 'o' specifier is the one to use for round tripping which captures the UTC state. When parsed the result will usually have Kind == Utc if the original was UTC. I've found that the best thing to do is always normalize dates to either UTC or local prior to serializing then instruct the parser on which normalization you've chosen.

DateTime now = DateTime.Now;
DateTime utcNow = now.ToUniversalTime();

string nowStr = now.ToString( "o" );
string utcNowStr = utcNow.ToString( "o" );

now = DateTime.Parse( nowStr );
utcNow = DateTime.Parse( nowStr, null, DateTimeStyles.AdjustToUniversal );

Debug.Assert( now == utcNow );

ImportError: DLL load failed: The specified module could not be found

Quick note: Check if you have other Python versions, if you have removed them, make sure you did that right. If you have Miniconda on your system then Python will not be removed easily.

What worked for me: removed other Python versions and the Miniconda, reinstalled Python and the matplotlib library and everything worked great.

What is the difference between Cygwin and MinGW?

Cygwin uses a compatibility layer, while MinGW is native. That is one of the main differences.

How do I make a PHP form that submits to self?

Try this

<form method="post" id="reg" name="reg" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"

Works well :)

What is default list styling (CSS)?

You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.

The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.

How can I use an array of function pointers?

The above answers may help you but you may also want to know how to use array of function pointers.

void fun1()
{

}

void fun2()
{

}

void fun3()
{

}

void (*func_ptr[3])() = {fun1, fun2, fun3};

main()
{
    int option;


    printf("\nEnter function number you want");
    printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
    scanf("%d",&option);

    if((option>=0)&&(option<=2))
    { 
        (*func_ptr[option])();
    }

    return 0;
}

You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.

You can also pass arguments like below if all the above functions are having the same number of arguments of same type.

  (*func_ptr[option])(argu1);

Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1 can be called if option=0, fun2 can be called if option=1 and fun3 can be called if option=2.

Pass in an array of Deferreds to $.when()

As a simple alternative, that does not require $.when.apply or an array, you can use the following pattern to generate a single promise for multiple parallel promises:

promise = $.when(promise, anotherPromise);

e.g.

function GetSomeDeferredStuff() {
    // Start with an empty resolved promise (or undefined does the same!)
    var promise;
    var i = 1;
    for (i = 1; i <= 5; i++) {
        var count = i;

        promise = $.when(promise,
        $.ajax({
            type: "POST",
            url: '/echo/html/',
            data: {
                html: "<p>Task #" + count + " complete.",
                delay: count / 2
            },
            success: function (data) {
                $("div").append(data);
            }
        }));
    }
    return promise;
}

$(function () {
    $("a").click(function () {
        var promise = GetSomeDeferredStuff();
        promise.then(function () {
            $("div").append("<p>All done!</p>");
        });
    });
});

Notes:

  • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
  • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested inside additional objects). For what you want though it is short and simple.
  • The upside is it requires no array or array management.

How to reset a select element with jQuery

If you want to reset by id

$('select[id="baba"]').empty();

If you want to reset by name


$('select[name="baba"]').empty();

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

How to do error logging in CodeIgniter (PHP)

In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';

Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/

jQuery select change show/hide div event

Nothing new but caching your jQuery collections will have a small perf boost

$(function() {

    var $typeSelector = $('#type');
    var $toggleArea = $('#row_dim');

    $typeSelector.change(function(){
        if ($typeSelector.val() === 'parcel') {
            $toggleArea.show(); 
        }
        else {
            $toggleArea.hide(); 
        }
    });
});

And in vanilla JS for super speed:

(function() {

    var typeSelector = document.getElementById('type');
    var toggleArea = document.getElementById('row_dim');

    typeSelector.onchange = function() {
        toggleArea.style.display = typeSelector.value === 'parcel'
            ? 'block'
            : 'none';
    };

});

The declared package does not match the expected package ""

I had have this sort situations when I copied classes from other packages/projects.

Menu->Project->Clean usually helps.

This Activity already has an action bar supplied by the window decor

Add single line android:theme="@style/AppTheme.NoActionBar" to activity in AndroidManifest and you've done.


AndroidManifest.xml:

<activity android:name=".activity.YourActivity"
          android:theme="@style/AppTheme.NoActionBar"><!-- ADD THIS LINE -->

styles.xml

<style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
</style>

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

In my case was facing the same issue, especially the first pull request trying after remotely adding a Git repository. The following error was facing.

fatal: refusing to merge unrelated histories on every try

Use the --allow-unrelated-histories command. It works perfectly.

git pull origin branchname --allow-unrelated-histories

Using Get-childitem to get a list of files modified in the last 3 days

I wanted to just add this as a comment to the previous answer, but I can't. I tried Dave Sexton's answer but had problems if the count was 1. This forces an array even if one object is returned.

([System.Object[]](gci c:\pstback\ -Filter *.pst | 
    ? { $_.LastWriteTime -gt (Get-Date).AddDays(-3)})).Count

It still doesn't return zero if empty, but testing '-lt 1' works.

XSLT equivalent for JSON

XSLT equivalents for JSON - a list of candidates (tools and specs)

Tools

1. XSLT

You can use XSLT for JSON with the aim of fn:json-to-xml.

This section describes facilities allowing JSON data to be processed using XSLT.

2. jq

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text. There are install packages for different OS.

3. jj

JJ is a command line utility that provides a fast and simple way to retrieve or update values from JSON documents. It's powered by GJSON and SJSON under the hood.

4. fx

Command-line JSON processing tool - Don't need to learn new syntax - Plain JavaScript - Formatting and highlighting - Standalone binary

5. jl

jl ("JSON lambda") is a tiny functional language for querying and manipulating JSON.

6. JOLT

JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document.

7. gron

Make JSON greppable! gron transforms JSON into discrete assignments to make it easier to grep for what you want and see the absolute 'path' to it. It eases the exploration of APIs that return large blobs of JSON but have terrible documentation.

8. json-e

JSON-e is a data-structure parameterization system for embedding context in JSON objects. The central idea is to treat a data structure as a "template" and transform it, using another data structure as context, to produce an output data structure.

9. JSLT

JSLT is a complete query and transformation language for JSON. The language design is inspired by jq, XPath, and XQuery.

10. JSONata

JSONata is a lightweight query and transformation language for JSON data. Inspired by the 'location path' semantics of XPath 3.1, it allows sophisticated queries to be expressed in a compact and intuitive notation.

11. JSONPath Plus

Analyse, transform, and selectively extract data from JSON documents (and JavaScript objects). jsonpath-plus expands on the original specification to add some additional operators and makes explicit some behaviors the original did not spell out.

12. json-transforms Last Commit Dec 1, 2017

Provides a recursive, pattern-matching approach to transforming JSON data. Transformations are defined as a set of rules which match the structure of a JSON object. When a match occurs, the rule emits the transformed data, optionally recursing to transform child objects.

13. json Last commit Jun 23, 2018

json is a fast CLI tool for working with JSON. It is a single-file node.js script with no external deps (other than node.js itself).

14. jsawk Last commit Mar 4, 2015

Jsawk is like awk, but for JSON. You work with an array of JSON objects read from stdin, filter them using JavaScript to produce a results array that is printed to stdout.

15. yate Last Commit Mar 13, 2017

Tests can be used as docu https://github.com/pasaran/yate/tree/master/tests

16. jsonpath-object-transform Last Commit Jan 18, 2017

Pulls data from an object literal using JSONPath and generate a new objects based on a template.

17. Stapling Last Commit Sep 16, 2013

Stapling is a JavaScript library that enables XSLT formatting for JSON objects. Instead of using a JavaScript templating engine and text/html templates, Stapling gives you the opportunity to use XSLT templates - loaded asynchronously with Ajax and then cached client side - to parse your JSON datasources.

Specs:

JSON Pointer defines a string syntax for identifying a specific value within a JavaScript Object Notation (JSON) document.

JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document

JSPath for JSON is like XPath for XML."

The main source of inspiration behind JSONiq is XQuery, which has been proven so far a successful and productive query language for semi-structured data

WPF ListView - detect when selected item is clicked

I would also suggest deselecting an item after it has been clicked and use the MouseDoubleClick event

private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    try {
        //Do your stuff here
        listBox.SelectedItem = null;
        listBox.SelectedIndex = -1;
    } catch (Exception ex) {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}

Android and setting width and height programmatically in dp units

simplest way(and even works from api 1) that tested is:

getResources().getDimensionPixelSize(R.dimen.example_dimen);

From documentations:

Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.

BASH Syntax error near unexpected token 'done'

Might help someone else : I encountered the same kind of issues while I had done some "copy-paste" from a side Microsoft Word document, where I took notes, to my shell script(s).

Re-writing, manually, the exact same code in the script just solved this.

It was quite un-understandable at first, I think Word's hidden characters and/or formatting were the issue. Obvious but not see-able ... I lost about one hour on this (I'm no shell expert, as you might guess ...)

Lua - Current time in milliseconds

You can use C function gettimeofday : http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html

Here C library 'ul_time', function sec_usec resides in 'time' global table and returns seconds, useconds. Copy DLL to Lua folder, open it with require 'ul_time'.

http://depositfiles.com/files/3g2fx7dij

How to create permanent PowerShell Aliases

Just to add to this list of possible locations...

This didn't work for me: \Users\{ME}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

However this did: \Users\{ME}\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

If you don't have a profile or you're looking to set one up, run the following command, it will create the folder/files necessary and even tell you where it lives! New-Item -path $profile -type file -force

How do you make an element "flash" in jQuery

Create two classes, giving each a background color:

.flash{
 background: yellow;
}

.noflash{
 background: white;
}

Create a div with one of these classes:

<div class="noflash"></div>

The following function will toggle the classes and make it appear to be flashing:

var i = 0, howManyTimes = 7;
function flashingDiv() {
    $('.flash').toggleClass("noFlash")
    i++;
    if( i <= howManyTimes ){
        setTimeout( f, 200 );
    }
}
f();

Where is HttpContent.ReadAsAsync?

I have the same problem, so I simply get JSON string and deserialize to my class:

HttpResponseMessage response = await client.GetAsync("Products");
//get data as Json string 
string data = await response.Content.ReadAsStringAsync();
//use JavaScriptSerializer from System.Web.Script.Serialization
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
//deserialize to your class
products = JSserializer.Deserialize<List<Product>>(data);

Various ways to remove local Git changes

I think git has one thing that isn't clearly documented. I think it was actually neglected.

git checkout .

Man, you saved my day. I always have things I want to try using the modified code. But the things sometimes end up messing the modified code, add new untracked files etc. So what I want to do is, stage what I want, do the messy stuff, then cleanup quickly and commit if I'm happy.

There's git clean -fd works well for untracked files.

Then git reset simply removes staged, but git checkout is kinda too cumbersome. Specifying file one by one or using directories isn't always ideal. Sometimes the changed files I want to get rid of are within directories I want to keep. I wished for this one command that just removes unstaged changes and here you're. Thanks.

But I think they should just have git checkout without any options, remove all unstaged changes and not touch the the staged. It's kinda modular and intuitive. More like what git reset does. git clean should also do the same.

Difference between jQuery .hide() and .css("display", "none")

see http://api.jquery.com/show/

With no parameters, the .show() method is the simplest way to display an element:

$('.target').show();

The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

How do I update a Python package?

You might want to look into a Python package manager like pip. If you don't want to use a Python package manager, you should be able to download M2Crypto and build/compile/install over the old installation.

What is meant by the term "hook" in programming?

Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.

As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.

How can I join elements of an array in Bash?

Here's one that most POSIX compatible shells support:

join_by() {
    # Usage:  join_by "||" a b c d
    local arg arr=() sep="$1"
    shift
    for arg in "$@"; do
        if [ 0 -lt "${#arr[@]}" ]; then
            arr+=("${sep}")
        fi
        arr+=("${arg}") || break
    done
    printf "%s" "${arr[@]}"
}

error: invalid type argument of ‘unary *’ (have ‘int’)

Barebones C program to produce the above error:

#include <iostream>
using namespace std;
int main(){
    char *p;
    *p = 'c';

    cout << *p[0];  
    //error: invalid type argument of `unary *'
    //peeking too deeply into p, that's a paddlin.

    cout << **p;    
    //error: invalid type argument of `unary *'
    //peeking too deeply into p, you better believe that's a paddlin.
}

ELI5:

The master puts a shiny round stone inside a small box and gives it to a student. The master says: "Open the box and remove the stone". The student does so.

Then the master says: "Now open the stone and remove the stone". The student said: "I can't open a stone".

The student was then enlightened.

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Because booleans have two values: true or false. Note that these are not strings, but actual boolean literals.

1 and 0 are integers, and there is no reason to confuse things by making them "alternative true" and "alternative false" (or the other way round for those used to Unix exit codes?). With strong typing in Java there should only ever be exactly two primitive boolean values.

EDIT: Note that you can easily write a conversion function if you want:

public static boolean intToBool(int input)
{
   if (input < 0 || input > 1)
   {
      throw new IllegalArgumentException("input must be 0 or 1");
   }

   // Note we designate 1 as true and 0 as false though some may disagree
   return input == 1;
}

Though I wouldn't recommend this. Note how you cannot guarantee that an int variable really is 0 or 1; and there's no 100% obvious semantics of what one means true. On the other hand, a boolean variable is always either true or false and it's obvious which one means true. :-)

So instead of the conversion function, get used to using boolean variables for everything that represents a true/false concept. If you must use some kind of primitive text string (e.g. for storing in a flat file), "true" and "false" are much clearer in their meaning, and can be immediately turned into a boolean by the library method Boolean.valueOf.

Core dump file is not generated

In centos,if you are not root account to generate core file: you must be set the account has a root privilege or login root account:

vim /etc/security/limits.conf

account soft core unlimited
account hard core unlimited

then if you in login shell with securecrt or other:

logout and then relogin

Why do people write #!/usr/bin/env python on the first line of a Python script?

That is called the shebang line. As the Wikipedia entry explains:

In computing, a shebang (also called a hashbang, hashpling, pound bang, or crunchbang) refers to the characters "#!" when they are the first two characters in an interpreter directive as the first line of a text file. In a Unix-like operating system, the program loader takes the presence of these two characters as an indication that the file is a script, and tries to execute that script using the interpreter specified by the rest of the first line in the file.

See also the Unix FAQ entry.

Even on Windows, where the shebang line does not determine the interpreter to be run, you can pass options to the interpreter by specifying them on the shebang line. I find it useful to keep a generic shebang line in one-off scripts (such as the ones I write when answering questions on SO), so I can quickly test them on both Windows and ArchLinux.

The env utility allows you to invoke a command on the path:

The first remaining argument specifies the program name to invoke; it is searched for according to the PATH environment variable. Any remaining arguments are passed as arguments to that program.

Get all object attributes in Python?

Use the built-in function dir().

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

I'm a bit late to the game, but I noticed some key points that were left out, particularly regarding Java 8 and the efficiency of Arrays.asList.

1. How does the for-each loop work?

As Ciro Santilli ???? ??? ??? pointed out, there's a handy utility for examining bytecode that ships with the JDK: javap. Using that, we can determine that the following two code snippets produce identical bytecode as of Java 8u74:

For-each loop:

int[] arr = {1, 2, 3};
for (int n : arr) {
    System.out.println(n);
}

For loop:

int[] arr = {1, 2, 3};

{  // These extra braces are to limit scope; they do not affect the bytecode
    int[] iter = arr;
    int length = iter.length;
    for (int i = 0; i < length; i++) {
        int n = iter[i];
        System.out.println(n);
    }
}

2. How do I get an iterator for an array in Java?

While this doesn't work for primitives, it should be noted that converting an array to a List with Arrays.asList does not impact performance in any significant way. The impact on both memory and performance is nearly immeasurable.

Arrays.asList does not use a normal List implementation that is readily accessible as a class. It uses java.util.Arrays.ArrayList, which is not the same as java.util.ArrayList. It is a very thin wrapper around an array and cannot be resized. Looking at the source code for java.util.Arrays.ArrayList, we can see that it's designed to be functionally equivalent to an array. There is almost no overhead. Note that I have omitted all but the most relevant code and added my own comments.

public class Arrays {
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable {
        private final E[] a;

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size() {
            return a.length;
        }

        @Override
        public E get(int index) {
            return a[index];
        }

        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }
    }
}

The iterator is at java.util.AbstractList.Itr. As far as iterators go, it's very simple; it just calls get() until size() is reached, much like a manual for loop would do. It's the simplest and usually most efficient implementation of an Iterator for an array.

Again, Arrays.asList does not create a java.util.ArrayList. It's much more lightweight and suitable for obtaining an iterator with negligible overhead.

Primitive arrays

As others have noted, Arrays.asList can't be used on primitive arrays. Java 8 introduces several new technologies for dealing with collections of data, several of which could be used to extract simple and relatively efficient iterators from arrays. Note that if you use generics, you're always going to have the boxing-unboxing problem: you'll need to convert from int to Integer and then back to int. While boxing/unboxing is usually negligible, it does have an O(1) performance impact in this case and could lead to problems with very large arrays or on computers with very limited resources (i.e., SoC).

My personal favorite for any sort of array casting/boxing operation in Java 8 is the new stream API. For example:

int[] arr = {1, 2, 3};
Iterator<Integer> iterator = Arrays.stream(arr).mapToObj(Integer::valueOf).iterator();

The streams API also offers constructs for avoiding the boxing issue in the first place, but this requires abandoning iterators in favor of streams. There are dedicated stream types for int, long, and double (IntStream, LongStream, and DoubleStream, respectively).

int[] arr = {1, 2, 3};
IntStream stream = Arrays.stream(arr);
stream.forEach(System.out::println);

Interestingly, Java 8 also adds java.util.PrimitiveIterator. This provides the best of both worlds: compatibility with Iterator<T> via boxing along with methods to avoid boxing. PrimitiveIterator has three built-in interfaces that extend it: OfInt, OfLong, and OfDouble. All three will box if next() is called but can also return primitives via methods such as nextInt(). Newer code designed for Java 8 should avoid using next() unless boxing is absolutely necessary.

int[] arr = {1, 2, 3};
PrimitiveIterator.OfInt iterator = Arrays.stream(arr);

// You can use it as an Iterator<Integer> without casting:
Iterator<Integer> example = iterator;

// You can obtain primitives while iterating without ever boxing/unboxing:
while (iterator.hasNext()) {
    // Would result in boxing + unboxing:
    //int n = iterator.next();

    // No boxing/unboxing:
    int n = iterator.nextInt();

    System.out.println(n);
}

If you're not yet on Java 8, sadly your simplest option is a lot less concise and is almost certainly going to involve boxing:

final int[] arr = {1, 2, 3};
Iterator<Integer> iterator = new Iterator<Integer>() {
    int i = 0;

    @Override
    public boolean hasNext() {
        return i < arr.length;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        return arr[i++];
    }
};

Or if you want to create something more reusable:

public final class IntIterator implements Iterator<Integer> {
    private final int[] arr;
    private int i = 0;

    public IntIterator(int[] arr) {
        this.arr = arr;
    }

    @Override
    public boolean hasNext() {
        return i < arr.length;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        return arr[i++];
    }
}

You could get around the boxing issue here by adding your own methods for obtaining primitives, but it would only work with your own internal code.

3. Is the array converted to a list to get the iterator?

No, it is not. However, that doesn't mean wrapping it in a list is going to give you worse performance, provided you use something lightweight such as Arrays.asList.

What is the difference between Cloud, Grid and Cluster?

Cloud: the hardware running the application scales to meet the demand (potentially crossing multiple machines, networks, etc).

Grid: the application scales to take as much hardware as possible (for example in the hope of finding extra-terrestrial intelligence).

Cluster: this is an old term referring to one OS instance or one DB instance installed across multiple machines. It was done with special OS handling, proprietary drivers, low latency network cards with fat cables, and various hardware bedfellows.

(We love you SGI, but notice that "Cloud" and "Grid" are available to the little guy and your NUMAlink never has been...)

VBA Date as integer

Date is not an Integer in VB(A), it is a Double.

You can get a Date's value by passing it to CDbl().

CDbl(Now())      ' 40877.8052662037 

From the documentation:

The 1900 Date System

In the 1900 date system, the first day that is supported is January 1, 1900. When you enter a date, the date is converted into a serial number that represents the number of elapsed days starting with 1 for January 1, 1900. For example, if you enter July 5, 1998, Excel converts the date to the serial number 35981.

So in the 1900 system, 40877.805... represents 40,876 days after January 1, 1900 (29 November 2011), and ~80.5% of one day (~19:19h). There is a setting for 1904-based system in Excel, numbers will be off when this is in use (that's a per-workbook setting).

To get the integer part, use

Int(CDbl(Now())) ' 40877

which would return a LongDouble with no decimal places (i.e. what Floor() would do in other languages).

Using CLng() or Round() would result in rounding, which will return a "day in the future" when called after 12:00 noon, so don't do that.

Updating user data - ASP.NET Identity

Excellent!!!

IdentityResult result = await UserManager.UpdateAsync(user);

Mockito How to mock and assert a thrown exception?

Make the exception happen like this:

when(obj.someMethod()).thenThrow(new AnException());

Verify it has happened either by asserting that your test will throw such an exception:

@Test(expected = AnException.class)

Or by normal mock verification:

verify(obj).someMethod();

The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

for visual studio 2019 need change MSBuild path

npm config set msvs_version 2017

npm config set msbuild_path "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"

npm rebuild node-sass

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

How to set HttpResponse timeout for Android in Java

you can creat HttpClient instance by the way with Httpclient-android-4.3.5,it can work well.

 SSLContext sslContext = SSLContexts.createSystemDefault();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
                RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCircularRedirectsAllowed(false).setConnectionRequestTimeout(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000);
        CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfigBuilder.build()).build();

How to send a "multipart/form-data" with requests in python?

You need to use the name attribute of the upload file that is in the HTML of the site. Example:

autocomplete="off" name="image">

You see name="image">? You can find it in the HTML of a site for uploading the file. You need to use it to upload the file with Multipart/form-data

script:

import requests

site = 'https://prnt.sc/upload.php' # the site where you upload the file
filename = 'image.jpg'  # name example

Here, in the place of image, add the name of the upload file in HTML

up = {'image':(filename, open(filename, 'rb'), "multipart/form-data")}

If the upload requires to click the button for upload, you can use like that:

data = {
     "Button" : "Submit",
}

Then start the request

request = requests.post(site, files=up, data=data)

And done, file uploaded succesfully

change image opacity using javascript

In fact, you need to use CSS.

document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

It works on FireFox, Chrome and IE.

Given URL is not allowed by the Application configuration

I ran into this with the IBM BlueMix SSO service and had to use the BlueMix provided redirect URL as my "site" URL instead of my actually web application site URL to fix it. Once I made that change the problem went away.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.

The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.

To prevent CodeIgniter from doing this "favor" automatically, use the set() method with a third parameter of false.

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows();  // this is expected to return the integer: 1

The generated query (depending on your database adapter) would be like this:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0

In this case, Last and Current ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.

If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().

How do I use Apache tomcat 7 built in Host Manager gui?

Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in

/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf (its called Catalina Base and is often hidden)

instead of the apacahe installation directory.

open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.

    <user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>

restart the server . That's all

Using mysql concat() in WHERE clause?

SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'

...is probably what you want.

How to set up Android emulator proxy settings

nothin of that worked i am using eclipse on windows 64-bit: do the folllowing steps... it worked for me: Window -> Preferences -> Android -> Launch -> Default Emulator Options -http-proxy="http://10.1.8.30:8080"

in your eclipse window

How to detect my browser version and operating system using JavaScript?

I'm sad to say: We are sh*t out of luck on this one.

I'd like to refer you to the author of WhichBrowser: Everybody lies.

Basically, no browser is being honest. No matter if you use Chrome or IE, they both will tell you that they are "Mozilla Netscape" with Gecko and Safari support. Try it yourself on any of the fiddles flying around in this thread:

hims056's fiddle

Hariharan's fiddle

or any other... Try it with Chrome (which might still succeed), then try it with a recent version of IE, and you will cry. Of course, there are heuristics, to get it all right, but it will be tedious to grasp all the edge cases, and they will very likely not work anymore in a year's time.

Take your code, for example:

<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>

Chrome says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

IE says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

At least Chrome still has a string that contains "Chrome" with the exact version number. But, for IE you must extrapolate from the things it supports to actually figure it out (who else would boast that they support .NET or Media Center :P), and then match it against the rv: at the very end to get the version number. Of course, even such sophisticated heuristics might very likely fail as soon as IE 12 (or whatever they want to call it) comes out.

Returning JSON response from Servlet to Javascript/JSP page

I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

Add line break to ::after or ::before pseudo-element content

The content property states:

Authors may include newlines in the generated content by writing the "\A" escape sequence in one of the strings after the 'content' property. This inserted line break is still subject to the 'white-space' property. See "Strings" and "Characters and case" for more information on the "\A" escape sequence.

So you can use:

#headerAgentInfoDetailsPhone:after {
  content:"Office: XXXXX \A Mobile: YYYYY ";
  white-space: pre; /* or pre-wrap */
}

http://jsfiddle.net/XkNxs/

When escaping arbitrary strings, however, it's advisable to use \00000a instead of \A, because any number or [a-f] character followed by the new line may give unpredictable results:

function addTextToStyle(id, text) {
  return `#${id}::after { content: "${text.replace(/"/g, '\\"').replace(/\n/g, '\\00000a')} }"`;
}

A column-vector y was passed when a 1d array was expected

use below code:

model = forest.fit(train_fold, train_y.ravel())

if you are still getting slap by error as identical as below ?

Unknown label type: %r" % y

use this code:

y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)

How to detect a route change in Angular?

In Angular 10, you can do something like the following...

    import { Component, OnInit } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';
    import { filter } from 'rxjs/operators';
    
    @Component({
      selector: 'app-my-class',
      templateUrl: './my-class.component.html',
      styleUrls: ['./my-class.component.scss']
    })
    export class MyClassComponent implements OnInit {
      constructor(private router: Router) {}
    
      ngOnInit(): void {
        this.router.events
        .pipe(filter(event => event instanceof NavigationEnd))  
        .subscribe((event: NavigationEnd) => {
          // code goes here...
        });
      }
    }

'tuple' object does not support item assignment

Tuples, in python can't have their values changed. If you'd like to change the contained values though I suggest using a list:

[1,2,3] not (1,2,3)

jQuery click not working for dynamically created items

You have to add click event to an exist element. You can not add event to dom elements dynamic created. I you want to add event to them, you should bind event to an existed element using ".on".

$('p').on('click','selector_you_dynamic_created',function(){...});

.delegate should work,too.

Validate email with a regex in jQuery

This : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i is not working for below Gmail case

[email protected] [email protected]

Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex

I found this Solution from this URL:

Regex Solution link

/(?:((?:[\w-]+(?:\.[\w-]+)*)@(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g

How to get the number of threads in a Java process

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

Vim autocomplete for Python

Try Jedi! There's a Vim plugin at https://github.com/davidhalter/jedi-vim.

It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).

C# declare empty string array

Your syntax is invalid.

string[] arr = new string[5];

That will create arr, a referenced array of strings, where all elements of this array are null. (Since strings are reference types)

This array contains the elements from arr[0] to arr[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to null.

Single-Dimensional Arrays (C# Programming Guide)

How to serialize Object to JSON?

The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.

Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.

import javax.json.*;

JsonObject value = Json.createObjectBuilder()
 .add("firstName", "John")
 .add("lastName", "Smith")
 .add("age", 25)
 .add("address", Json.createObjectBuilder()
     .add("streetAddress", "21 2nd Street")
     .add("city", "New York")
     .add("state", "NY")
     .add("postalCode", "10021"))
 .add("phoneNumber", Json.createArrayBuilder()
     .add(Json.createObjectBuilder()
         .add("type", "home")
         .add("number", "212 555-1234"))
     .add(Json.createObjectBuilder()
         .add("type", "fax")
         .add("number", "646 555-4567")))
 .build();

JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();

But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.

Set inputType for an EditText Programmatically?

To only allow numbers:

password1.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);

To transform (hide) the password:

password1.setTransformationMethod(PasswordTransformationMethod.getInstance());

Chrome extension id - how to find it

You get an extension ID when you upload your extension to Google Web Store. Ie. Adblock has URL https://chrome.google.com/webstore/detail/cfhdojbkjhnklbpkdaibdccddilifddb and the last part of this URL is its extension ID cfhdojbkjhnklbpkdaibdccddilifddb.


If you wish to read installed extension IDs from your extension, check out the managment module. chrome.management.getAll allows to fetch information about all installed extensions.

Can I hide the HTML5 number input’s spin box?

This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):

_x000D_
_x000D_
input::-webkit-outer-spin-button,_x000D_
input::-webkit-inner-spin-button {_x000D_
    /* display: none; <- Crashes Chrome on hover */_x000D_
    -webkit-appearance: none;_x000D_
    margin: 0; /* <-- Apparently some margin are still there even though it's hidden */_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
    -moz-appearance:textfield; /* Firefox */_x000D_
}
_x000D_
<input type="number" step="0.01" />
_x000D_
_x000D_
_x000D_

You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":

Inspector for input type=number (Chrome)

How to delete a cookie using jQuery?

To delete a cookie with JQuery, set the value to null:

$.cookie("name", null, { path: '/' });

Edit: The final solution was to explicitly specify the path property whenever accessing the cookie, because the OP accesses the cookie from multiple pages in different directories, and thus the default paths were different (this was not described in the original question). The solution was discovered in discussion below, which explains why this answer was accepted - despite not being correct.

For some versions jQ cookie the solution above will set the cookie to string null. Thus not removing the cookie. Use the code as suggested below instead.

$.removeCookie('the_cookie', { path: '/' });

What is the difference between #import and #include in Objective-C?

In may case I had a global variable in one of my .h files that was causing the problem, and I solved it by adding extern in front of it.

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.

Why does CSS not support negative padding?

I would like to describe a very good example of why negative padding would be useful and awesome.

As all of us CSS developers know, vertically aligning a dynamically sizing div within another is a hassle, and for the most part, viewed as being impossible only using CSS. The incorporation of negative padding could change this.

Please review the following HTML:

<div style="height:600px; width:100%;">
    <div class="vertical-align" style="width:100%;height:auto;" >
        This DIV's height will change based the width of the screen.
    </div>
</div>

With the following CSS, we would be able to vertically center the content of the inner div within the outer div:

.vertical-align {
    position: absolute;
    top:50%;
    padding-top:-50%;
    overflow: visible;
}

Allow me to explain...

Absolutely positioning the inner div's top at 50% places the top edge of the inner div at the center of the outer div. Pretty simple. This is because percentage based positioning is relative to the inner dimensions of the parent element.

Percentage based padding, on the other hand, is based on the inner dimensions of the targeted element. So, by applying the property of padding-top: -50%; we have shifted the content of the inner div upward by a distance of 50% of the height of the inner div's content, therefore centering the inner div's content within the outer div and still allowing the height dimension of the inner div to be dynamic!

If you ask me OP, this would be the best use-case, and I think it should be implemented just so I can do this hack. lol. Or, they should just fix the functionality of vertical-align and give us a version of vertical-align that works on all elements.

How to know the git username and email saved during configuration?

Inside your git repository directory, run git config user.name.

Why is running this command within your git repo directory important?

If you are outside of a git repository, git config user.name gives you the value of user.name at global level. When you make a commit, the associated user name is read at local level.

Although unlikely, let's say user.name is defined as foo at global level, but bar at local level. Then, when you run git config user.name outside of the git repo directory, it gives bar. However, when you really commits something, the associated value is foo.


Git config variables can be stored in 3 different levels. Each level overrides values in the previous level.

1. System level (applied to every user on the system and all their repositories)

  • to view, git config --list --system (may need sudo)
  • to set, git config --system color.ui true
  • to edit system config file, git config --edit --system

2. Global level (values specific personally to you, the user. )

  • to view, git config --list --global
  • to set, git config --global user.name xyz
  • to edit global config file, git config --edit --global

3. Repository level (specific to that single repository)

  • to view, git config --list --local
  • to set, git config --local core.ignorecase true (--local optional)
  • to edit repository config file, git config --edit --local (--local optional)

How to view all settings?

  • Run git config --list, showing system, global, and (if inside a repository) local configs
  • Run git config --list --show-origin, also shows the origin file of each config item

How to read one particular config?

  • Run git config user.name to get user.name, for example.
  • You may also specify options --system, --global, --local to read that value at a particular level.

Reference: 1.6 Getting Started - First-Time Git Setup

Modal width (increase)

For responsive answer.

@media (min-width: 992px) {
  .modal-dialog {
    max-width: 80%;
  }
}

What is the best algorithm for overriding GetHashCode?

Most of my work is done with database connectivity which means that my classes all have a unique identifier from the database. I always use the ID from the database to generate the hashcode.

// Unique ID from database
private int _id;

...    
{
  return _id.GetHashCode();
}

What is apache's maximum url length?

The official length according to the offical Apache docs is 8,192, but many folks have run into trouble at ~4,000.

MS Internet Explorer is usually the limiting factor anyway, as it caps the maximum URL size at 2,048.

How to run .NET Core console app from the command line

Go to ...\bin\Debug\net5.0 (net5.0 can also be something like "netcoreapp2.2" depending on the framework you use.)

enter image description here

Open the power shell by clicking on it like shown in the picture.

Type in powershell: .\yourApp.exe

You don't need dotnet publish just make sure you build it before to include all changes.

c# open a new form then close the current form?

                     this.Visible = false;
                        //or                         // will make LOgin Form invisivble
                        //this.Enabled = false;
                         //  or
                       // this.Hide(); 



                        Form1 form1 = new Form1();
                        form1.ShowDialog();

                        this.Dispose();

PHP how to get local IP of system

In windows

$exec = 'ipconfig | findstr /R /C:"IPv4.*"';
exec($exec, $output);
preg_match('/\d+\.\d+\.\d+\.\d+/', $output[0], $matches);
print_r($matches[0]);

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

Unsupported major.minor version 52.0 in my app

I am on cordova, here's what I've done:

- rename your android project, so that there's space for new one
- update JAVA Development Kit to 1.8 (latest one in time of writing this)
- run cordova platform add android

Should work without problems now. Your app hash will change, so if you are using it f.e. for facbeook login, you will need to update it

Automatically size JPanel inside JFrame

You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.

Simply adding the following line of code should fix your problems:

mainFrame.setLayout(new BorderLayout());

(Do this before adding components to the JFrame)

Convert double to Int, rounded down

double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

The double value is 420.5 and the application prints out the integer value of 420

How to kill MySQL connections

mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id  | User | Host            | db   | Command | Time | State | Info      |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds  | Query   |    0 | init  | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds  | Sleep   |    4 |       | NULL      |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)

mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)

USER 192 :

mysql> SELECT * FROM exept;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query

How to call another controller Action From a controller in Mvc

I know it's old, but you can:

  • Create a service layer
  • Move method there
  • Call method in both controllers

Android sample bluetooth code to send a simple string via bluetooth

I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.

multiplayerConnect.java

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class multiplayerConnect extends AppCompatActivity {

public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;


String bluetooth_message="00";




@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
    @Override
    public void handleMessage(Message msg_type) {
        super.handleMessage(msg_type);

        switch (msg_type.what){
            case MESSAGE_READ:

                byte[] readbuf=(byte[])msg_type.obj;
                String string_recieved=new String(readbuf);

                //do some task based on recieved string

                break;
            case MESSAGE_WRITE:

                if(msg_type.obj!=null){
                    ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
                    connectedThread.write(bluetooth_message.getBytes());

                }
                break;

            case CONNECTED:
                Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
                break;

            case CONNECTING:
                Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
                break;

            case NO_SOCKET_FOUND:
                Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
                break;
        }
    }
};



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.multiplayer_bluetooth);
    initialize_layout();
    initialize_bluetooth();
    start_accepting_connection();
    initialize_clicks();

}

public void start_accepting_connection()
{
    //call this on button click as suited by you

    AcceptThread acceptThread = new AcceptThread();
    acceptThread.start();
    Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
    lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Object[] objects = set_pairedDevices.toArray();
            BluetoothDevice device = (BluetoothDevice) objects[position];

            ConnectThread connectThread = new ConnectThread(device);
            connectThread.start();

            Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
        }
    });
}

public void initialize_layout()
{
    lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
    adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
    lv_paired_devices.setAdapter(adapter_paired_devices);
}

public void initialize_bluetooth()
{
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        // Device doesn't support Bluetooth
        Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
        finish();
    }

    //Add these permisions before
//        <uses-permission android:name="android.permission.BLUETOOTH" />
//        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
//        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    else {
        set_pairedDevices = bluetoothAdapter.getBondedDevices();

        if (set_pairedDevices.size() > 0) {

            for (BluetoothDevice device : set_pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address

                adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
            }
        }
    }
}


public class AcceptThread extends Thread
{
    private final BluetoothServerSocket serverSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
        } catch (IOException e) { }
        serverSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                break;
            }

            // If a connection was accepted
            if (socket != null)
            {
                // Do work to manage the connection (in a separate thread)
                mHandler.obtainMessage(CONNECTED).sendToTarget();
            }
        }
    }
}


private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        bluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mHandler.obtainMessage(CONNECTING).sendToTarget();

            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
//            bluetooth_message = "Initial message"
//            mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[2];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

multiplayer_bluetooth.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Challenge player"/>

    <ListView
        android:id="@+id/lv_paired_devices"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </ListView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Make sure Device is paired"/>

</LinearLayout>

Count table rows

As mentioned by Santosh, I think this query is suitably fast, while not querying all the table.

To return integer result of number of data records, for a specific tablename in a particular database:

select TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA = 'database' 
AND table_name='tablename';

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

For me the issue appeared after i created a signed APK. To fix it, i generated a new, debug apk using Run / Build APK. After that, Run(cmd+r) works again without this error.

Extract data from log file in specified range of time

I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:

$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"

Spring Boot @Value Properties

To read the values from application.properties we need to just annotate our main class with @SpringBootApplication and the class where you are reading with @Component or variety of it. Below is the sample where I have read the values from application.properties and it is working fine when web service is invoked. If you deploy the same code as is and try to access from http://localhost:8080/hello you will get the value you have stored in application.properties for the key message.

package com.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

    @Value("${message}")
    private String message;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @RequestMapping("/hello")
    String home() {
        return message;
    }

}

Try and let me know

Alter table to modify default value of column

ALTER TABLE {TABLE NAME}
ALTER COLUMN {COLUMN NAME} SET DEFAULT '{DEFAULT VALUES}'

example :

ALTER TABLE RESULT
ALTER COLUMN STATUS SET DEFAULT 'FAIL'

Can I delete a git commit but keep the changes?

One more way to do it.

Add commit on the top of temporary commit and then do:

git rebase -i

To merge two commits into one (command will open text file with explicit instructions, edit it).

Show/Hide Div on Scroll

$.fn.scrollEnd = function(callback, timeout) {          
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

$(window).scroll(function(){
    $('.main').fadeOut();
});

$(window).scrollEnd(function(){
    $('.main').fadeIn();
}, 700);

That should do the Trick!

Apply vs transform on a group object

you can use zscore to analyze the data in column C and D for outliers, where zscore is the series - series.mean / series.std(). Use apply too create a user defined function for difference between C and D creating a new resulting dataframe. Apply uses the group result set.

from scipy.stats import zscore

columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],     
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
print(df)

standardize=df.groupby('A')['C','D'].transform(zscore)
print(standardize)
outliersC= (standardize['C'] <-1.1) | (standardize['C']>1.1)
outliersD= (standardize['D'] <-1.1) | (standardize['D']>1.1)

results=df[outliersC | outliersD]
print(results)

   #Dataframe results
   A      B         C         D
   0  foo    one  0.162003  0.087469
   1  bar    one -1.156319 -1.526272
   2  foo    two  0.833892 -1.666304
   3  bar  three -2.026673 -0.322057
   4  foo    two  0.411452 -0.954371
   5  bar    two  0.765878 -0.095968
   6  foo    one -0.654890  0.678091
   7  foo  three -1.789842 -1.130922
 #C and D transformed Z score
           C         D
 0  0.398046  0.801292
 1 -0.300518 -1.398845
 2  1.121882 -1.251188
 3 -1.046514  0.519353
 4  0.666781 -0.417997
 5  1.347032  0.879491
 6 -0.482004  1.492511
 7 -1.704704 -0.624618

 #filtering using arbitrary ranges -1 and 1 for the z-score
      A      B         C         D
 1  bar    one -1.156319 -1.526272
 2  foo    two  0.833892 -1.666304
 5  bar    two  0.765878 -0.095968
 6  foo    one -0.654890  0.678091
 7  foo  three -1.789842 -1.130922


 >>>>>>>>>>>>> Part 2

 splitting = df.groupby('A')

 #look at how the data is grouped
 for group_name, group in splitting:
     print(group_name)

 def column_difference(gr):
      return gr['C']-gr['D']

 grouped=splitting.apply(column_difference)
 print(grouped)

 A     
 bar  1    0.369953
      3   -1.704616
      5    0.861846
 foo  0    0.074534
      2    2.500196
      4    1.365823
      6   -1.332981
      7   -0.658920

How to check if a variable is null or empty string or all whitespace in JavaScript?

if (addr == null || addr.trim() === ''){
  //...
}

A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).

Download a file from HTTPS using download.file()

127 means command not found

In your case, curl command was not found. Therefore it means, curl was not found.

You need to install/reinstall CURL. That's all. Get latest version for your OS from http://curl.haxx.se/download.html

Close RStudio before installation.

link button property to open in new tab?

  1. LinkButton executes HTTP POST operation, you cant change post target here.
  2. Not all the browsers support posting form to a new target window.
  3. In order to have it post, you have to change target of your "FORM".
  4. You can use some javascript workaround to change your POST target, by changing form's target attribute, but browser will give a warning to user (IE Does), that this page is trying to post data on a new window, do you want to continue etc.

Try to find out ID of your form element in generated aspx, and you can change target like...

getElementByID('theForm').target = '_blank' or 'myNewWindow'

How to get a random number in Ruby

You can simply use random_number.

If a positive integer is given as n, random_number returns an integer: 0 <= random_number < n.

Use it like this:

any_number = SecureRandom.random_number(100) 

The output will be any number between 0 and 100.

Moment js get first and last day of current month

I ran into some issues because I wasn't aware that moment().endOf() mutates the input date, so I used this work around.

_x000D_
_x000D_
let thisMoment = moment();
let endOfMonth = moment(thisMoment).endOf('month');
let startOfMonth = moment(thisMoment).startOf('month');
_x000D_
_x000D_
_x000D_

Edit seaborn legend

Took me a while to read through the above. This was the answer for me:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=False
)

plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)

Reference this for more arguments: matplotlib.pyplot.legend

enter image description here

What is the use of the square brackets [] in sql statements?

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space)--but then you'd need to use brackets every time you referred to that column.

The newer tools add them everywhere just in case or for consistency.

Using node.js as a simple web server

The simpler version which I've came across is as following. For education purposes, it is best, because it does not use any abstract libraries.

var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');

var mimeTypes = {
  "html": "text/html",
  "mp3":"audio/mpeg",
  "mp4":"video/mp4",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "js": "text/javascript",
  "css": "text/css"};

http.createServer(function(req, res) {
    var uri = url.parse(req.url).pathname;
    var filename = path.join(process.cwd(), uri);
    fs.exists(filename, function(exists) {
        if(!exists) {
            console.log("not exists: " + filename);
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write('404 Not Found\n');
            res.end();
            return;
        }
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        res.writeHead(200, {'Content-Type':mimeType});

        var fileStream = fs.createReadStream(filename);
        fileStream.pipe(res);

    }); //end path.exists
}).listen(1337);

Now go to browser and open following:

http://127.0.0.1/image.jpg

Here image.jpg should be in same directory as this file. Hope this helps someone :)

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

Try casting the ints to varchar, before adding them to a string:

SET @ActualWeightDIMS = cast(@Actual_Dims_Lenght as varchar(8)) + 
   'x' + cast(@Actual_Dims_Width as varchar(8)) + 
   'x' + cast(@Actual_Dims_Height as varhcar(8))

How to align form at the center of the page in html/css

I would just use table and not the form. Its done by using margin.

table {
  margin: 0 auto;
}

also try using something like

table td {
    padding-bottom: 5px;
}

instead of <br />

and also your input should end with /> e.g:

<input type="password" name="cpwd" />

Programmatically set image to UIImageView with Xcode 6.1/Swift

OK, got it working with this (creating the UIImageView programmatically):

var imageViewObject :UIImageView

imageViewObject = UIImageView(frame:CGRectMake(0, 0, 600, 600))

imageViewObject.image = UIImage(named:"afternoon")

self.view.addSubview(imageViewObject)

self.view.sendSubviewToBack(imageViewObject)

How is length implemented in Java Arrays?

Yes, it should be a field. And I think this value is assigned when you create your array (you have to choose the length of array while creating, for example: int[] a = new int[5];).

How do I unload (reload) a Python module?

You can reload a module when it has already been imported by using the reload builtin function (Python 3.4+ only):

from importlib import reload  
import foo

while True:
    # Do some things.
    if is_changed(foo):
        foo = reload(foo)

In Python 3, reload was moved to the imp module. In 3.4, imp was deprecated in favor of importlib, and reload was added to the latter. When targeting 3 or later, either reference the appropriate module when calling reload or import it.

I think that this is what you want. Web servers like Django's development server use this so that you can see the effects of your code changes without restarting the server process itself.

To quote from the docs:

Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time. As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

As you noted in your question, you'll have to reconstruct Foo objects if the Foo class resides in the foo module.

400 vs 422 response to POST of data

Firstly this is a very good question.

400 Bad Request - When a critical piece of information is missing from the request

e.g. The authorization header or content type header. Which is absolutely required by the server to understand the request. This can differ from server to server.

422 Unprocessable Entity - When the request body can't be parsed.

This is less severe than 400. The request has reached the server. The server has acknowledged the request has got the basic structure right. But the information in the request body can't be parsed or understood.

e.g. Content-Type: application/xml when request body is JSON.

Here's an article listing status codes and its use in REST APIs. https://metamug.com/article/status-codes-for-rest-api.php

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

What is referencedColumnName used for in JPA?

"referencedColumnName" property is the name of the column in the table that you are making reference with the column you are anotating. Or in a short manner: it's the column referenced in the destination table. Imagine something like this: cars and persons. One person can have many cars but one car belongs only to one person (sorry, I don't like anyone else driving my car).

Table Person
name char(64) primary key
age int

Table Car
car_registration char(32) primary key
car_brand (char 64)
car_model (char64)
owner_name char(64) foreign key references Person(name)

When you implement classes you will have something like

class Person{
   ...
}

class Car{
    ...
    @ManyToOne
    @JoinColumn([column]name="owner_name", referencedColumnName="name")
    private Person owner;
}

EDIT: as @searchengine27 has commented, columnName does not exist as a field in persistence section of Java7 docs. I can't remember where I took this property from, but I remember using it, that's why I'm leaving it in my example.

Reading entire html file to String?

There's the IOUtils.toString(..) utility from Apache Commons.

If you're using Guava there's also Files.readLines(..) and Files.toString(..).

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

The following will fit the image to 100% of container width while the height is constant. For local assets, use AssetImage

Container(
  width: MediaQuery.of(context).size.width,
  height: 100,
  decoration: BoxDecoration(
    image: DecorationImage(
      fit: BoxFit.fill,
      image: NetworkImage("https://picsum.photos/250?image=9"),
    ),
  ),
)

Image fill modes:

  • Fill - Image is stretched

    fit: BoxFit.fill
    

    enter image description here


  • Fit Height - image kept proportional while making sure the full height of the image is shown (may overflow)

    fit: BoxFit.fitHeight
    

    enter image description here


  • Fit Width - image kept proportional while making sure the full width of the image is shown (may overflow)

    fit: BoxFit.fitWidth
    

    enter image description here


  • Cover - image kept proportional, ensures maximum coverage of the container (may overflow)

    fit: BoxFit.cover
    

    enter image description here


  • Contain - image kept proportional, minimal as possible, will reduce it's size if needed to display the entire image

    fit: BoxFit.contain
    

    enter image description here

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

How to split a string in Haskell?

Without importing anything a straight substitution of one character for a space, the target separator for words is a space. Something like:

words [if c == ',' then ' ' else c|c <- "my,comma,separated,list"]

or

words let f ',' = ' '; f c = c in map f "my,comma,separated,list"

You can make this into a function with parameters. You can eliminate the parameter character-to-match my matching many, like in:

 [if elem c ";,.:-+@!$#?" then ' ' else c|c <-"my,comma;separated!list"]

History or log of commands executed in Git

I found out that in my version of git bash "2.24.0.windows.2" in my "home" folder under windows users, there will be a file called ".bash-history" with no file extension in that folder. It's only created after you exit from bash.

Here's my workflow:

  1. before exiting bash type "history >> history.txt" [ENTER]
  2. exit the bash prompt
  3. hold Win+R to open the Run command box
  4. enter shell:profile
  5. open "history.txt" to confirm that my text was added
  6. On a new line press [F5] to enter a timestamp
  7. save and close the history textfile
  8. Delete the ".bash-history" file so the next session will create a new history

If you really want points I guess you could make a batch file to do all this but this is good enough for me. Hope it helps someone.

How to change xampp localhost to another folder ( outside xampp folder)?

@Hooman: actually with the latest versions of Xampp you don't need to know where the configuration or log files are; in the Control panel you have log and config buttons for each tool (php, mysql, tomcat...) and clicking them offers to open all the relevant file (you can even change the default editing application with the general Config button at the top right). Well done for whoever designed it!

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

RestClientException: Could not extract response. no suitable HttpMessageConverter found

You need to create your own converter and implement it before making a GET request.

RestTemplate  restTemplate = new RestTemplate();

List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();        

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));         
messageConverters.add(converter);  
restTemplate.setMessageConverters(messageConverters);    

How can I show/hide component with JSF?

One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.

private boolean switchComponents;

public boolean isSwitchComponents() {
    return switchComponents;
}

public void setSwitchComponents(boolean switchComponents) {
    this.switchComponents = switchComponents;
}

When the switch is true, one set of components will be shown and when it is false the other set will be shown.

 <h:selectOneRadio value="#{backbean.switchValue}">
   <f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
   <f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
   <f:ajax event="change" execute="@this" render="componentsRoot"/>
 </h:selectOneRadio>


<H:panelGroup id="componentsRoot">
     <h:panelGroup rendered="#{backbean.switchValue}">
       <!--switchValue to be shown on switch value == true-->
     </h:panelGroup>

   <h:panelGroup rendered="#{!backbean.switchValue}">
      <!--switchValue to be shown on switch value == false-->
   </h:panelGroup>
</H:panelGroup>

Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.

Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).

How to remove focus around buttons on click

I found no solid answers that didn't either break accessibility or subvert functionality.

Perhaps combining a few will work better overall.

<h1
  onmousedown="this.style.outline='none';"
  onclick="this.blur(); runFn(this);"
  onmouseup="this.style.outline=null;"
>Hello</h1>

function runFn(thisElem) { console.log('Hello: ', thisElem); }

How to do an INNER JOIN on multiple columns

You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:

SELECT 
    airline, flt_no, fairport, tairport, depart, arrive, fare
FROM 
    flights
INNER JOIN 
    airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
    airports to_port ON (to_port.code = flights.tairport)
WHERE 
    from_port.code = '?' OR to_port.code = '?' OR airports.city='?'

Note that the to_port and from_port are aliases for the first and second copies of the airports table.

Excel VBA Loop on columns

Just use the Cells function and loop thru columns. Cells(Row,Column)

Stop node.js program from command line

Though this is a late answer, I found this from NodeJS docs:

The 'exit' event is emitted when the REPL is exited either by receiving the .exit command as input, the user pressing <ctrl>-C twice to signal SIGINT, or by pressing <ctrl>-D to signal 'end' on the input stream. The listener callback is invoked without any arguments.

So to summarize you can exit by:

  1. Typing .exit in nodejs REPL.
  2. Pressing <ctrl>-C twice.
  3. pressing <ctrl>-D.
  4. process.exit(0) meaning a natural exit from REPL. If you want to return any other status you can return a non zero number.
  5. process.kill(process.pid) is the way to kill using nodejs api from within your code or from REPL.

What is 0x10 in decimal?

Notice that '10' is the representation of the base in that base:

10 is 2(decimal) in base-2

10 is 3(decimal) in base-3

...

10 is 10(decimal) in base-10

...

10 is 16(decimal) in base-16 (hexadecimal)

...

10 is 1024(decimal) in base-1024

...and so on

TypeError: 'list' object cannot be interpreted as an integer

Error messages usually mean precisely what they say. So they must be read very carefully. When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is. It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.

So the question is: why does the interpreter seem to want to interpret your list as an integer? The answer is that you are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in myList instead.

How do I run Selenium in Xvfb?

The easiest way is probably to use xvfb-run:

DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar

xvfb-run does the whole X authority dance for you, give it a try!

Is there a way to iterate over a dictionary?

Yes, NSDictionary supports fast enumeration. With Objective-C 2.0, you can do this:

// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator:

NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

what is numeric(18, 0) in sql server 2008 r2

This page explains it pretty well.

As a numeric the allowable range that can be stored in that field is -10^38 +1 to 10^38 - 1.

The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.

The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.

So the range that can be stored in this particular field is -(10^18 - 1) to (10^18 - 1)

Or -999999999999999999 to 999999999999999999 Integers only

Check If array is null or not in php

Corrected;

/*
 return true if the array is not empty
 return false if it is empty
*/
function is_array_empty($arr){
  if(is_array($arr)){     
      foreach($arr as $key => $value){
          if(!empty($value) || $value != NULL || $value != ""){
              return true;
              break;//stop the process we have seen that at least 1 of the array has value so its not empty
          }
      }
      return false;
  }
}

How to make sure that a certain Port is not occupied by any other process

You can use "netstat" to check whether a port is available or not.

Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

You have to put : before port number to get the actual output

Ex netstat -anp | find ":8080"

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

Abstract Class vs Interface in C++

Pure Virtual Functions are mostly used to define:

a) abstract classes

These are base classes where you have to derive from them and then implement the pure virtual functions.

b) interfaces

These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.

JavaScript alert not working in Android WebView

Check this link , and last comment , You have to use WebChromeClient for your purpose.

.gitignore for Visual Studio Projects and Solutions

I use the following .gitignore for C# projects. Additional patterns are added as and when they are needed.

[Oo]bj
[Bb]in
*.user
*.suo
*.[Cc]ache
*.bak
*.ncb
*.log 
*.DS_Store
[Tt]humbs.db 
_ReSharper.*
*.resharper
Ankh.NoLoad

How does the modulus operator work?

in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:

5 % 2 = 1
13 % 5 = 3

With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).

To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).

pycharm running way slow

It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:

-Xms2048m
-Xmx2048m

Error Importing SSL certificate : Not an X.509 Certificate

This seems like an old thread, but I'll add my experience here. I tried to install a cert as well and got that error. I then opened the cer file with a txt editor, and noticed that there is an extra space (character) at the end of each line. Removing those lines allowed me to import the cert.

Hope this is worth something to someone else.

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

How to redirect 404 errors to a page in ExpressJS?

I think you should first define all your routes and as the last route add

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.status(404).send('what???');
});

An example app which does work:

app.js:

var express = require('express'),
    app = express.createServer();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.send('hello world');
});

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.send('what???', 404);
});

app.listen(3000, '127.0.0.1');

alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt 

.
./app.js
./public
./public/README.txt

alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?

What are the differences between ArrayList and Vector?

There are 2 major differentiation's between Vector and ArrayList.

  1. Vector is synchronized by default, and ArrayList is not. Note : you can make ArrayList also synchronized by passing arraylist object to Collections.synchronizedList() method. Synchronized means : it can be used with multiple threads with out any side effect.

  2. ArrayLists grow by 50% of the previous size when space is not sufficient for new element, where as Vector will grow by 100% of the previous size when there is no space for new incoming element.

Other than this, there are some practical differences between them, in terms of programming effort:

  1. To get the element at a particular location from Vector we use elementAt(int index) function. This function name is very lengthy. In place of this in ArrayList we have get(int index) which is very easy to remember and to use.
  2. Similarly to replace an existing element with a new element in Vector we use setElementAt() method, which is again very lengthy and may irritate the programmer to use repeatedly. In place of this ArrayList has add(int index, object) method which is easy to use and remember. Like this they have more programmer friendly and easy to use function names in ArrayList.

When to use which one?

  1. Try to avoid using Vectors completely. ArrayLists can do everything what a Vector can do. More over ArrayLists are by default not synchronized. If you want, you can synchronize it when ever you need by using Collections util class.
  2. ArrayList has easy to remember and use function names.

Note : even though arraylist grows by 100%, you can avoid this by ensurecapacity() method to make sure that you are allocating sufficient memory at the initial stages itself.

Hope it helps.

How can I extract substrings from a string in Perl?

You could do something like this:

my $data = <<END;
1) Scheme ID: abc-456-hu5t10 (High priority) *
2) Scheme ID: frt-78f-hj542w (Balanced)
3) Scheme ID: 23f-f974-nm54w (super formula run) *
END

foreach (split(/\n/,$data)) {
  $_ =~ /Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?/ || next;
  my ($id,$word,$star) = ($1,$2,$3);
  print "$id $word $star\n";
}

The key thing is the Regular expression:

Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?

Which breaks up as follows.

The fixed String "Scheme ID: ":

Scheme ID: 

Followed by one or more of the characters a-z, 0-9 or -. We use the brackets to capture it as $1:

([a-z0-9-]+)

Followed by one or more whitespace characters:

\s+

Followed by an opening bracket (which we escape) followed by any number of characters which aren't a close bracket, and then a closing bracket (escaped). We use unescaped brackets to capture the words as $2:

\(([^)]+)\)

Followed by some spaces any maybe a *, captured as $3:

\s*(\*)?

When to encode space to plus (+) or %20?

Its better to always encode spaces as %20, not as "+".

It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".

I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Intellij idea cannot resolve anything in maven

Keep in mind that IntelliJ adds your local Maven installation's classes to its own classpath, so keep it up to date.

In my case IntelliJ tried to call method org.eclipse.aether.util.ConfigUtils.getFloat(). This caused a java.lang.NoSuchMethodError, because my years old Maven version didn't contain this method yet. Due to the exception IntelliJ stopped resolving dependencies.

After updating Maven, you have to change the "Maven home directory" setting in "Build, Execution, Deployment" -> "Maven". After that you must restart IntelliJ, because the classpath of IntelliJ's JVM won't change while running.

It took me some time to solve this problem, as I didn't expect IntelliJ to use the classes of my local Maven installation. I thought it uses it's own bundled JARs. So hopefully this information is helpful for others.

Change the color of a checked menu item in a navigation drawer

Here's how you can do it in your Activity's onCreate method:

NavigationView navigationView = findViewById(R.id.nav_view);
ColorStateList csl = new ColorStateList(
    new int[][] {
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_checked}  // checked
    },
    new int[] {
        Color.BLACK,
        Color.RED
    }
);
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl);