Programs & Examples On #Certificate revocation

Certification Revocation is a process through which we make sure that certificates that are no longer valid are not used by the relying clients

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Try this:

location / {
    root /path/to/root;
    expires 30d;
    access_log off;
}

location ~* ^.*\.php$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php should be forwared to Apache if only a corresponding .php file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.

Best way to list files in Java, sorted by Date Modified?

There is a very easy and convenient way to handle the problem without any extra comparator. Just code the modified date into the String with the filename, sort it, and later strip it off again.

Use a String of fixed length 20, put the modified date (long) into it, and fill up with leading zeros. Then just append the filename to this string:

String modified_20_digits = ("00000000000000000000".concat(Long.toString(temp.lastModified()))).substring(Long.toString(temp.lastModified()).length()); 

result_filenames.add(modified_20_digits+temp.getAbsoluteFile().toString());

What happens is this here:

Filename1: C:\data\file1.html Last Modified:1532914451455 Last Modified 20 Digits:00000001532914451455

Filename1: C:\data\file2.html Last Modified:1532918086822 Last Modified 20 Digits:00000001532918086822

transforms filnames to:

Filename1: 00000001532914451455C:\data\file1.html

Filename2: 00000001532918086822C:\data\file2.html

You can then just sort this list.

All you need to do is to strip the 20 characters again later (in Java 8, you can strip it for the whole Array with just one line using the .replaceAll function)

Sample random rows in dataframe

You could do this:

library(dplyr)

cols <- paste0("a", 1:10)
tab <- matrix(1:1000, nrow = 100) %>% as.tibble() %>% set_names(cols)
tab
# A tibble: 100 x 10
      a1    a2    a3    a4    a5    a6    a7    a8    a9   a10
   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
 1     1   101   201   301   401   501   601   701   801   901
 2     2   102   202   302   402   502   602   702   802   902
 3     3   103   203   303   403   503   603   703   803   903
 4     4   104   204   304   404   504   604   704   804   904
 5     5   105   205   305   405   505   605   705   805   905
 6     6   106   206   306   406   506   606   706   806   906
 7     7   107   207   307   407   507   607   707   807   907
 8     8   108   208   308   408   508   608   708   808   908
 9     9   109   209   309   409   509   609   709   809   909
10    10   110   210   310   410   510   610   710   810   910
# ... with 90 more rows

Above I just made a dataframe with 10 columns and 100 rows, ok?

Now you can sample it with sample_n:

sample_n(tab, size = 800, replace = T)
# A tibble: 800 x 10
      a1    a2    a3    a4    a5    a6    a7    a8    a9   a10
   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
 1    53   153   253   353   453   553   653   753   853   953
 2    14   114   214   314   414   514   614   714   814   914
 3    10   110   210   310   410   510   610   710   810   910
 4    70   170   270   370   470   570   670   770   870   970
 5    36   136   236   336   436   536   636   736   836   936
 6    77   177   277   377   477   577   677   777   877   977
 7    13   113   213   313   413   513   613   713   813   913
 8    58   158   258   358   458   558   658   758   858   958
 9    29   129   229   329   429   529   629   729   829   929
10     3   103   203   303   403   503   603   703   803   903
# ... with 790 more rows

How can I use iptables on centos 7?

With RHEL 7 / CentOS 7, firewalld was introduced to manage iptables. IMHO, firewalld is more suited for workstations than for server environments.

It is possible to go back to a more classic iptables setup. First, stop and mask the firewalld service:

systemctl stop firewalld
systemctl mask firewalld

Then, install the iptables-services package:

yum install iptables-services

Enable the service at boot-time:

systemctl enable iptables

Managing the service

systemctl [stop|start|restart] iptables

Saving your firewall rules can be done as follows:

service iptables save

or

/usr/libexec/iptables/iptables.init save

What is the maximum size of a web browser's cookie's key?

Not completely entirely a direct answer to the original question, but relevant for the curious quickly trying to visually understand their cookie information storage planning without implementing a complex limiter algorithm, this string is 4096 ASCII character bytes:

"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn"

How to use BeginInvoke C#

I guess your code relates to Windows Forms.
You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)

If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously.
(Invoke for the sync version.)

If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task with the according context. (TaskScheduler.FromCurrentSynchronizationContext())

And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var with lambdas: compiler needs a hint.

UPDATE:

this requires .Net v4.0 and higher

// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);

// also can be called anywhere. Task  will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked) 
task.Start(scheduler);

If you started the task from other thread and need to wait for its completition task.Wait() will block calling thread till the end of the task.

Read more about tasks here.

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

How to vertically center content with variable height within a div?

Using the child selector, I've taken Fadi's incredible answer above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the contentCentered class name to elements I want to center:

_x000D_
_x000D_
.contentCentered {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.contentCentered::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -.25em; /* Adjusts for spacing */_x000D_
}_x000D_
_x000D_
.contentCentered > * {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div class="contentCentered">_x000D_
  <div>_x000D_
    <h1>Some text</h1>_x000D_
    <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
      shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
      towards that ship a while ago?"</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Forked CodePen: http://codepen.io/dougli/pen/Eeysg

How do I split a string into an array of characters?

You can split on an empty string:

var chars = "overpopulation".split('');

If you just want to access a string in an array-like fashion, you can do that without split:

var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
    console.log(s.charAt(i));
}

You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

var s = "overpopulation";

console.log(s[3]); // logs 'r'

What is a regex to match ONLY an empty string?

I believe Python is the only widely used language that doesn't support \z in this way (yet). There are Python bindings for Russ Cox / Google's super fast re2 C++ library that can be "dropped in" as a replacement for the bundled re.

There's an excellent discussion (with workarounds) for this at Perl Compatible Regular Expression (PCRE) in Python, here on SO.

python
Python 2.7.11 (default, Jan 16 2016, 01:14:05) 
[GCC 4.2.1 Compatible FreeBSD Clang 3.4.1 on freebsd10
Type "help", "copyright", "credits" or "license" for more information.
>>> import re2 as re
>>> 
>>> re.match(r'\A\z', "")
<re2.Match object at 0x805d97170>

@tchrist's answer is worth the read.

Why is my CSS style not being applied?

For me, it was the local overrides in Sources -> Overrides. A file gets saved locally whenever you change the styling of a page and chrome uses that file to override the server's css.

How to trim a string in SQL Server before 2017?

I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.

ALTER TABLE Customer ADD
   CONSTRAINT customer_names__whitespace
      CHECK (
             Names NOT LIKE ' %'
             AND Names NOT LIKE '% '
             AND Names NOT LIKE '%  %'
            );

Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.

It may also be a good time to split those Names into family_name, first_name, etc :)

How to change active class while click to another link in bootstrap use jquery?

You can use cookies for save postback data from one page to another page.After spending a lot time finally i was able to make this happen. I am suggesting my answer to you(this is fully working since I also needed this).

first give your li tag to valid id name like

_x000D_
_x000D_
<ul class="nav nav-list">_x000D_
    <li id="tab1" class="active"><a href="/">Link 1</a></li>_x000D_
    <li id="tab2"><a href="/link2">Link 2</a></li>_x000D_
    <li id="tab3"><a href="/link3">Link 3</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

After that copy and paste this script. since I have written some javascript for reading, deleting and creating cookies.

_x000D_
_x000D_
 $('.nav li a').click(function (e) {_x000D_
  _x000D_
        var $parent = $(this).parent();_x000D_
        document.cookie = eraseCookie("tab");_x000D_
        document.cookie = createCookie("tab", $parent.attr('id'),0);_x000D_
 });_x000D_
_x000D_
    $().ready(function () {_x000D_
        var $activeTab = readCookie("tab");_x000D_
        if (!$activeTab =="") {_x000D_
        $('#tab1').removeClass('ActiveTab');_x000D_
          }_x000D_
       // alert($activeTab.toString());_x000D_
       _x000D_
        $('#'+$activeTab).addClass('active');_x000D_
    });_x000D_
_x000D_
function createCookie(name, value, days) {_x000D_
    if (days) {_x000D_
        var date = new Date();_x000D_
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));_x000D_
        var expires = "; expires=" + date.toGMTString();_x000D_
    }_x000D_
    else var expires = "";_x000D_
_x000D_
    document.cookie = name + "=" + value + expires + "; path=/";_x000D_
}_x000D_
_x000D_
function readCookie(name) {_x000D_
    var nameEQ = name + "=";_x000D_
    var ca = document.cookie.split(';');_x000D_
    for (var i = 0; i < ca.length; i++) {_x000D_
        var c = ca[i];_x000D_
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);_x000D_
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);_x000D_
    }_x000D_
    return null;_x000D_
}_x000D_
_x000D_
function eraseCookie(name) {_x000D_
    createCookie(name, "", -1);_x000D_
}
_x000D_
_x000D_
_x000D_

Note: Make sure you have implmeted according to your requirement. I have written this script according to my implementation and its working fine for me.

How to add Options Menu to Fragment in Android

on your onCreate method add setHasOptionMenu()

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

Then override your onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.add("Menu item")
            .setIcon(android.R.drawable.ic_delete)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}

Specifying content of an iframe instead of the src attribute to a page

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

Unsupported major.minor version 52.0 in my app

I had the same problem and tried to change the version, sometimes is for the version of Android Studio in Project> Gradle Scripts> build.gradle(Module:app) you can change the version. For example:

android {
    compileSdkVersion **23**
    buildToolsVersion **"23.0.3"**

    defaultConfig {
        applicationId "com.example.android.myapplication"
        minSdkVersion **19**
        targetSdkVersion **23**
        versionCode **1**
        versionName **"1.0"**
    }

Laravel check if collection is empty

You can always count the collection. For example $mentor->intern->count() will return how many intern does a mentor have.

https://laravel.com/docs/5.2/collections#method-count

In your code you can do something like this

foreach($mentors as $mentor)
    @if($mentor->intern->count() > 0)
    @foreach($mentor->intern as $intern)
        <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}">
            <td>{{ $intern->employee->FirstName }}</td>
            <td>{{  $intern->employee->LastName }}</td>
        </tr>
    @endforeach
    @else
        Mentor don't have any intern
    @endif
@endforeach

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

go to:

Tools > Options > Debugging > General > unchecked "Require source files to exactly match the original version"

Python: List vs Dict for look up table

You don't actually need to store 10 million values in the table, so it's not a big deal either way.

Hint: think about how large your result can be after the first sum of squares operation. The largest possible result will be much smaller than 10 million...

Convert String (UTF-16) to UTF-8 in C#

Check the Jon Skeet answer to this other question: UTF-16 to UTF-8 conversion (for scripting in Windows)

It contains the source code that you need.

Hope it helps.

Why maven? What are the benefits?

Maven can provide benefits for your build process by employing standard conventions and practices to accelerate your development cycle while at the same time helping you achieve a higher rate of success. For a more detailed look at how Maven can help you with your development process please refer to The Benefits of Using Maven.

How to handle the new window in Selenium WebDriver using Java?

Set<String> windows = driver.getWindowHandles();
Iterator<String> itr = windows.iterator();

//patName will provide you parent window
String patName = itr.next();

//chldName will provide you child window
String chldName = itr.next();

//Switch to child window
driver.switchto().window(chldName);

//Do normal selenium code for performing action in child window

//To come back to parent window
driver.switchto().window(patName);

How to exit an application properly

in this case I start Outlook and then close it

Dim ol 

Set ol = WScript.CreateObject("Outlook.Application") 'Starts Outlook

ol.quit 'Closes Outlook

How to sum array of numbers in Ruby?

New for Ruby 2.4.0

You can use the aptly named method Enumerable#sum. It has a lot of advantages over inject(:+) but there are some important notes to read at the end as well.

Examples

Ranges

(1..100).sum
#=> 5050

Arrays

[1, 2, 4, 9, 2, 3].sum
#=> 21

[1.9, 6.3, 20.3, 49.2].sum
#=> 77.7

Important note

This method is not equivalent to #inject(:+). For example

%w(a b c).inject(:+)
#=> "abc"
%w(a b c).sum
#=> TypeError: String can't be coerced into Integer

Also,

(1..1000000000).sum
#=> 500000000500000000 (execution time: less than 1s)
(1..1000000000).inject(:+)
#=> 500000000500000000 (execution time: upwards of a minute)

See this answer for more information on why sum is like this.

Best ways to teach a beginner to program?

In my biased opinion, C is the best point to start. The language is small, it's high level features are ubiquitous and the low level features let you learn the machine.

I found the C Primer Plus, 5th Edition very helpful as a beginning programmer with almost no programming experience. It assumes no prior programming experience, fun to read and covers C in depth (including the latest C99 standard).

How to create the most compact mapping n ? isprime(n) up to a limit N?

Let me suggest you the perfect solution for 64 bit integers. Sorry to use C#. You have not already specified it as python in your first post. I hope you can find a simple modPow function and analyze it easily.

public static bool IsPrime(ulong number)
{
    return number == 2 
        ? true 
        : (BigInterger.ModPow(2, number, number) == 2 
            ? (number & 1 != 0 && BinarySearchInA001567(number) == false) 
            : false)
}

public static bool BinarySearchInA001567(ulong number)
{
    // Is number in list?
    // todo: Binary Search in A001567 (https://oeis.org/A001567) below 2 ^ 64
    // Only 2.35 Gigabytes as a text file http://www.cecm.sfu.ca/Pseudoprimes/index-2-to-64.html
}

If statement for strings in python?

Even once you fixed the mis-cased if and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in. Here's how you'd do it (and note that if is all lowercase and that the code within the if block is indented one level).

One approach:

if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
    print("this will do the calculation")

Another:

if answer.lower() in ['y', 'yes']:
    print("this will do the calculation")

SVG: text inside rect

This is not possible. If you want to display text inside a rect element you should put them both in a group with the text element coming after the rect element ( so it appears on top ).

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <g>_x000D_
    <rect x="0" y="0" width="100" height="100" fill="red"></rect>_x000D_
    <text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>_x000D_
  </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How to get your Netbeans project into Eclipse

Sharing my experience, how to import simple Netbeans java project into Eclipse workspace. Please follow the following steps:

  1. Copy the Netbeans project folder into Eclipse workspace.
  2. Create .project file, inside the project folder at root level. Below code is the sample reference. Change your project name appropriately.

    <?xml version="1.0" encoding="UTF-8"?>
    <projectDescription>
        <name>PROJECT_NAME</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
            <buildCommand>
                <name>org.eclipse.jdt.core.javabuilder</name>
                <arguments>
                </arguments>
            </buildCommand>
        </buildSpec>
        <natures>
            <nature>org.eclipse.jdt.core.javanature</nature>
        </natures>
    </projectDescription>
    
  3. Now open Eclipse and follow the steps,

    File > import > Existing Projects into Workspace > Select root directory > Finish

  4. Now we need to correct the build path for proper compilation of src, by following these steps:

    Right Click on project folder > Properties > Java Build Path > Click Source tab > Add Folder

(Add the correct src path from project and remove the incorrect ones). Find the image ref link how it looks.

  1. You are done. Let me know for any queries. Thanks.

setup android on eclipse but don't know SDK directory

Late to the conversion...

For me, I found this at:

C:\Program Files (x86)\Android\android-sdk

This is the default location for Windows 64-bit.

Also, try to recall some of your default locations when not presented with some suggestions.

Turn a simple socket into an SSL socket

OpenSSL is quite difficult. It's easy to accidentally throw away all your security by not doing negotiation exactly right. (Heck, I've been personally bitten by a bug where curl wasn't reading the OpenSSL alerts exactly right, and couldn't talk to some sites.)

If you really want quick and simple, put stud in front of your program an call it a day. Having SSL in a different process won't slow you down: http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html

How can I use external JARs in an Android project?

create a folder (like lib) inside your project, copy your jar to that folder. now go to configure build path from right click on project, there in build path select

'add jar' browse to the folder you created and pick the jar.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

build-impl.xml:1031: The module has not been deployed

Check whether you placed the within the .. or outside the ... If you placed it outside the server tag , and if you try to access the init-parameter then it will give error.

SQL Server CTE and recursion example

    --DROP TABLE #Employee
    CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)

    INSERT INTO #Employee VALUES('M11M','Manager',NULL)
    INSERT INTO #Employee VALUES('P11P','Manager',NULL)

    INSERT INTO #Employee VALUES('AA','Clerk',1)
    INSERT INTO #Employee VALUES('AB','Assistant',1)
    INSERT INTO #Employee VALUES('ZC','Supervisor',2)
    INSERT INTO #Employee VALUES('ZD','Security',2)


    SELECT * FROM #Employee (NOLOCK)

    ;
    WITH Emp_CTE 
    AS
    (
        SELECT EmpId,EmpName,Designation, ManagerID
              ,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
        FROM #Employee  
    )
    select EmpId,EmpName,Designation, ManagerID
    FROM Emp_CTE
    order BY ManagerID_N, EmpId

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

_x000D_
_x000D_
.contents {
  width: 50%;
  border: 1px solid black;
  height: 300px;
  overflow: auto;
}

table {
  position: relative;
}

th {
  position: sticky;
  top: 0;
  background: #ffffff;
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="contents">
  <table class="table">
    <thead>
      <tr>
        <th>colunn 1</th>
        <th>colunn 2</th>
        <th>colunn 3</th>
        <th>colunn 4</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Example 1</td>
        <td>Example 2</td>
        <td>Example 3</td>
        <td>Example 4</td>
        <tr>
          <tr>
            <td>Example 1</td>
            <td>Example 2</td>
            <td>Example 3</td>
            <td>Example 4</td>
            <tr>
              <tr>
                <td>Example 1</td>
                <td>Example 2</td>
                <td>Example 3</td>
                <td>Example 4</td>
                <tr>
                  <tr>
                    <td>Example 1</td>
                    <td>Example 2</td>
                    <td>Example 3</td>
                    <td>Example 4</td>
                    <tr>
                      <tr>
                        <td>Example 1</td>
                        <td>Example 2</td>
                        <td>Example 3</td>
                        <td>Example 4</td>
                        <tr>
                          <tr>
                            <td>Example 1</td>
                            <td>Example 2</td>
                            <td>Example 3</td>
                            <td>Example 4</td>
                            <tr>
                              <tr>
                                <td>Example 1</td>
                                <td>Example 2</td>
                                <td>Example 3</td>
                                <td>Example 4</td>
                                <tr>
                                  <tr>
                                    <td>Example 1</td>
                                    <td>Example 2</td>
                                    <td>Example 3</td>
                                    <td>Example 4</td>
                                    <tr>
                                      <tr>
                                        <td>Example 1</td>
                                        <td>Example 2</td>
                                        <td>Example 3</td>
                                        <td>Example 4</td>
                                        <tr>
                                          <tr>
                                            <td>Example 1</td>
                                            <td>Example 2</td>
                                            <td>Example 3</td>
                                            <td>Example 4</td>
                                            <tr>
    </tbody>
  </table>
</div>
_x000D_
_x000D_
_x000D_

Java SSLException: hostname in certificate didn't match

You can also try to set a HostnameVerifier as described here. This worked for me to avoid this error.

// Do not do this in production!!!
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier     
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

// Example send http request
final String url = "https://encrypted.google.com/";  
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Very quick and easy visual instructions to change this (and the select top 1000) for 2008 R2 through SSMS GUI

http://bradmarsh.net/index.php/2008/04/21/sql-2008-change-edit-top-200-rows/

Summary:

  • Go to Tools menu -> Options -> SQL Server Object Explorer
  • Expand SQL Server Object Explorer
  • Choose 'Commands'
  • For 'Value for Edit Top Rows' command, specify '0' to edit all rows

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

Example on ToggleButton

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    editString = ed.getText().toString();
    if(editString.equals("1")){

        toggle.setTextOff("TOGGLE ON");
        toggle.setChecked(true);

    }
    else if(editString.equals("0")){

        toggle.setTextOn("TOGGLE OFF");
        toggle.setChecked(false);

    }
}

How do I save and restore multiple variables in python?

There is a built-in library called pickle. Using pickle you can dump objects to a file and load them later.

import pickle

f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()

f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()

jQuery set checkbox checked

<body>
      <input id="IsActive" name="IsActive" type="checkbox" value="false">
</body>

<script>
    $('#IsActive').change(function () {
         var chk = $("#IsActive")
         var IsChecked = chk[0].checked
         if (IsChecked) {
          chk.attr('checked', 'checked')
         } 
         else {
          chk.removeAttr('checked')                            
         }
          chk.attr('value', IsChecked)
     });
</script>

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How can I add a key/value pair to a JavaScript object?

Simply adding properties:

And we want to add prop2 : 2 to this object, these are the most convenient options:

  1. Dot operator: object.prop2 = 2;
  2. square brackets: object['prop2'] = 2;

So which one do we use then?

The dot operator is more clean syntax and should be used as a default (imo). However, the dot operator is not capable of adding dynamic keys to an object, which can be very useful in some cases. Here is an example:

_x000D_
_x000D_
const obj = {_x000D_
  prop1: 1_x000D_
}_x000D_
_x000D_
const key = Math.random() > 0.5 ? 'key1' : 'key2';_x000D_
_x000D_
obj[key] = 'this value has a dynamic key';_x000D_
_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_

Merging objects:

When we want to merge the properties of 2 objects these are the most convenient options:

  1. Object.assign(), takes a target object as an argument, and one or more source objects and will merge them together. For example:

_x000D_
_x000D_
const object1 = {_x000D_
  a: 1,_x000D_
  b: 2,_x000D_
};_x000D_
_x000D_
const object2 = Object.assign({_x000D_
  c: 3,_x000D_
  d: 4_x000D_
}, object1);_x000D_
_x000D_
console.log(object2);
_x000D_
_x000D_
_x000D_

  1. Object spread operator ...

_x000D_
_x000D_
const obj = {_x000D_
  prop1: 1,_x000D_
  prop2: 2_x000D_
}_x000D_
_x000D_
const newObj = {_x000D_
  ...obj,_x000D_
  prop3: 3,_x000D_
  prop4: 4_x000D_
}_x000D_
_x000D_
console.log(newObj);
_x000D_
_x000D_
_x000D_

Which one do we use?

  • The spread syntax is less verbose and has should be used as a default imo. Don't forgot to transpile this syntax to syntax which is supported by all browsers because it is relatively new.
  • Object.assign() is more dynamic because we have access to all objects which are passed in as arguments and can manipulate them before they get assigned to the new Object.

Find the paths between two given nodes?

In Prolog (specifically, SWI-Prolog)

:- use_module(library(tabling)).

% path(+Graph,?Source,?Target,?Path)
:- table path/4.

path(_,N,N,[N]).
path(G,S,T,[S|Path]) :-
    dif(S,T),
    member(S-I, G), % directed graph
    path(G,I,T,Path).

test:

paths :- Graph =
    [ 1- 2  % node 1 and 2 are connected
    , 2- 3 
    , 2- 5 
    , 4- 2 
    , 5-11
    ,11-12
    , 6- 7 
    , 5- 6 
    , 3- 6 
    , 6- 8 
    , 8-10
    , 8- 9
    ],
    findall(Path, path(Graph,1,7,Path), Paths),
    maplist(writeln, Paths).

?- paths.
[1,2,3,6,7]
[1,2,5,6,7]
true.

Entity Framework Refresh context?

I've made my own head hurt over nothing! The Answer was very simple- I just went back to the basics...

some_Entities   e2 = new some_Entities(); //your entity.

add this line below after you update/delete - you're re-loading your entity-no fancy system methods.

e2 = new some_Entities(); //reset.

MySQL: determine which database is selected?

SELECT DATABASE();

p.s. I didn't want to take the liberty of modifying @cwallenpoole's answer to reflect the fact that this is a MySQL question and not an Oracle question and doesn't need DUAL.

How to detect the device orientation using CSS media queries?

In Javascript it is better to use screen.width and screen.height. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.

The values of screen.width and screen.height change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width is greater than 1280px you're dealing with a PC or laptop.

You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).

How to remove item from list in C#?

List<T> has two methods you can use.

RemoveAt(int index) can be used if you know the index of the item. For example:

resultlist.RemoveAt(1);

Or you can use Remove(T item):

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefault will return null if there is no item (Single will throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id).

var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
    resultList.Remove(itemToRemove);

Html.fromHtml deprecated in Android N

I had a lot of these warnings and I always use FROM_HTML_MODE_LEGACY so I made a helper class called HtmlCompat containing the following:

   @SuppressWarnings("deprecation")
   public static Spanned fromHtml(String source) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY);
        } else {
            return Html.fromHtml(source);
        }
    }

Version vs build in Xcode

(Just leaving this here for my own reference.) This will show version and build for the "version" and "build" fields you see in an Xcode target:

- (NSString*) version {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

In Swift

func version() -> String {
    let dictionary = NSBundle.mainBundle().infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as? String
    let build = dictionary["CFBundleVersion"] as? String
    return "\(version) build \(build)"
}

What jar should I include to use javax.persistence package in a hibernate based application?

In the latest and greatest Hibernate, I was able to resolve the dependency by including the hibernate-jpa-2.0-api-1.0.0.Final.jar within lib/jpa directory. I didn't find the ejb-persistence jar in the most recent download.

Get the previous month's first and last day dates in c#

If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons... This will prevent you from missing any requests created during the date of Jan 31.

DateTime now = DateTime.Now;
DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastMonth = thisMonth.AddMonths(-1);

var RequestIds = rdc.request
  .Where(r => lastMonth <= r.dteCreated)
  .Where(r => r.dteCreated < thisMonth)
  .Select(r => r.intRequestId);

concat scope variables into string in angular directive expression

You can just concat the values using +

<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>

Simple example on jsfiddle

I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.

JavaScript math, round to two decimal places

try using discount.toFixed(2);

$apply already in progress error

In my case i use $apply with angular calendar UI to link some event:

$scope.eventClick = function(event){           
    $scope.$apply( function() {
        $location.path('/event/' + event.id);
    });
};

After reading the doc of the problem: https://docs.angularjs.org/error/$rootScope/inprog

The part Inconsistent API (Sync/Async) is very interesting:

For example, imagine a 3rd party library that has a method which will retrieve data for us. Since it may be making an asynchronous call to a server, it accepts a callback function, which will be called when the data arrives.

Since, the MyController constructor is always instantiated from within an $apply call, our handler is trying to enter a new $apply block from within one.

I change the code to :

$scope.eventClick = function(event){           
    $timeout(function() {
        $location.path('/event/' + event.id);
    }, 0);
};

Works like a charm !

Here we have used $timeout to schedule the changes to the scope in a future call stack. By providing a timeout period of 0ms, this will occur as soon as possible and $timeout will ensure that the code will be called in a single $apply block.

Duplicate Entire MySQL Database

Here's a windows bat file I wrote which combines Vincent and Pauls suggestions. It prompts the user for source and destination names.

Just modify the variables at the top to set the proper paths to your executables / database ports.

:: Creates a copy of a database with a different name.
:: User is prompted for Src and destination name.
:: Fair Warning: passwords are passed in on the cmd line, modify the script with -p instead if security is an issue.
:: Uncomment the rem'd out lines if you want script to prompt for database username, password, etc.

:: See also: http://stackoverflow.com/questions/1887964/duplicate-entire-mysql-database

@set MYSQL_HOME="C:\sugarcrm\mysql\bin"
@set mysqldump_exec=%MYSQL_HOME%\mysqldump
@set mysql_exec=%MYSQL_HOME%\mysql
@set SRC_PORT=3306
@set DEST_PORT=3306
@set USERNAME=TODO_USERNAME
@set PASSWORD=TODO_PASSWORD

:: COMMENT any of the 4 lines below if you don't want to be prompted for these each time and use defaults above.
@SET /p USERNAME=Enter database username: 
@SET /p PASSWORD=Enter database password: 
@SET /p SRC_PORT=Enter SRC database port (usually 3306): 
@SET /p DEST_PORT=Enter DEST database port: 

%MYSQL_HOME%\mysql --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="show databases;"
@IF NOT "%ERRORLEVEL%" == "0" GOTO ExitScript

@SET /p SRC_DB=What is the name of the SRC Database:  
@SET /p DEST_DB=What is the name for the destination database (that will be created):  

%mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="create database %DEST_DB%;"
%mysqldump_exec% --add-drop-table --user=%USERNAME% --password=%PASSWORD% --port=%SRC_PORT% %SRC_DB% | %mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% %DEST_DB%
@echo SUCCESSFUL!!!
@GOTO ExitSuccess

:ExitScript
@echo "Failed to copy database"
:ExitSuccess

Sample output:

C:\sugarcrm_backups\SCRIPTS>copy_db.bat
Enter database username: root
Enter database password: MyPassword
Enter SRC database port (usually 3306): 3308
Enter DEST database port: 3308

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="show databases;"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sugarcrm_550_pro   |
| sugarcrm_550_ce    |
| sugarcrm_640_pro   |
| sugarcrm_640_ce    |
+--------------------+
What is the name of the SRC Database:  sugarcrm
What is the name for the destination database (that will be created):  sugarcrm_640_ce

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="create database sugarcrm_640_ce;"

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysqldump --add-drop-table --user=root --password=MyPassword --port=3308 sugarcrm   | "C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 sugarcrm_640_ce
SUCCESSFUL!!!

How to loop through a checkboxlist and to find what's checked and not checked?

I think the best way to do this is to use CheckedItems:

 foreach (DataRowView objDataRowView in CheckBoxList.CheckedItems)
 {
     // use objDataRowView as you wish                
 }

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

I like live-server. It is fast and has a nice live reload feature, which is very convenient during developpement.

Usage is very simple:

cd ~/Sites/
live-server

By default it creates a server with IP 127.0.0.1 and port 8080.

http://127.0.0.1:8080/

If port 8080 is not free, it uses another port:

http://127.0.0.1:52749/

http://127.0.0.1:52858/

If you need to see the web server on other machines in your local network, you can check what is your IP and use:

live-server --host=192.168.1.121

And here is a script that automatically grab the IP address of the default interface. It works on macOS only.

If you put it in .bash_profile, the live-server command will automatically launch the server with the correct IP.

# **
# Get IP address of default interface
# *
function getIPofDefaultInterface()
{
    local  __resultvar=$1

    # Get default route interface
    if=$(route -n get 0.0.0.0 2>/dev/null | awk '/interface: / {print $2}')
    if [ -n "$if" ]; then
            # Get IP of the default route interface
            local __IP=$( ipconfig getifaddr $if )
            eval $__resultvar="'$__IP'"
    else
        # Echo "No default route found"
        eval $__resultvar="'0.0.0.0'"
    fi
}

alias getIP='getIPofDefaultInterface IP; echo $IP'

# **
# live-server
# https://www.npmjs.com/package/live-server
# *
alias live-server='getIPofDefaultInterface IP && live-server --host=$IP'

Adding items in a Listbox with multiple columns

By using the List property.

ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"

How to install pip with Python 3?

Please follow below steps to install python 3 with pip:

Step 1 : Install Python from download here

Step 2 : you’ll need to download get-pip.py

Step 3 : After download get-pip.py , open your commant prompt and go to directory where your get-pip.py file saved .

Step 4 : Enter command python get-pip.py in cmd.

Step 5 : Pip installed successfully , Verify pip installation by type command in cmd pip --version

Why is my Button text forced to ALL CAPS on Lollipop?

OK, just ran into this. Buttons in Lollipop come out all uppercase AND the font resets to 'normal'. But in my case (Android 5.02) it was working in one layout correctly, but not another!?

Changing APIs didn't work.
Setting to all caps requires min API 14 and the font still resets to 'normal'.

It's because the Android Material Styles forces a change to the styles if there isn't one defined (that's why it worked in one of my layout and not the other because I defined a style).

So the easy fix is to define a style in the manifest for each activity which in my case was just:
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
(hope this helps someone, would have saved me a couple of hours last night)

Easiest way to mask characters in HTML(5) text input

Yes, according to HTML5 drafts you can use the pattern attribute to specify the allowed input using a regular expression. For some types of data, you can use special input fields like <input type=email>. But these features still widely lack support or have qualitatively poor support.

How to get index using LINQ?

myCars.TakeWhile(car => !myCondition(car)).Count();

It works! Think about it. The index of the first matching item equals the number of (not matching) item before it.

Story time

I too dislike the horrible standard solution you already suggested in your question. Like the accepted answer I went for a plain old loop although with a slight modification:

public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
    int index = 0;
    foreach (var item in items) {
        if (predicate(item)) break;
        index++;
    }
    return index;
}

Note that it will return the number of items instead of -1 when there is no match. But let's ignore this minor annoyance for now. In fact the horrible standard solution crashes in that case and I consider returning an index that is out-of-bounds superior.

What happens now is ReSharper telling me Loop can be converted into LINQ-expression. While most of the time the feature worsens readability, this time the result was awe-inspiring. So Kudos to the JetBrains.

Analysis

Pros

  • Concise
  • Combinable with other LINQ
  • Avoids newing anonymous objects
  • Only evaluates the enumerable until the predicate matches for the first time

Therefore I consider it optimal in time and space while remaining readable.

Cons

  • Not quite obvious at first
  • Does not return -1 when there is no match

Of course you can always hide it behind an extension method. And what to do best when there is no match heavily depends on the context.

AppStore - App status is ready for sale, but not in app store

I thought I will post my answer as I recently got into a similar issue (as of September 2019). The App is free for all users in all countries.

For me, after I received a confirmation email from Apple saying that my app is ready for sale (the email did not mention any 24 hours waiting period), I could not find my App in the App Store.

The link to view the App in the App Store in the iTunes Connect (under the App Information section at the bottom page) was broken.

After reading your comments in this thread, I went to the Pricing and Availability section of the App and edited the pricing plan again to be 0 GBP and start date Today and finish date No Finish Date.

Then, I unchecked the countries the App is available on and checked them all again and hit Save.

The App became immediately available in the App store. The link in the App information section was directing me to the App Store and no longer broken.

I hope this will help anyone who is having similar issues lately (getting a confirmation email that the App is ready for sale but cannot find it in the App Store).

Where are the Android icon drawables within the SDK?

  1. Right click on Drawable folder

  2. click on new

  3. click on image asset

Then you can select an icon type

How do I perform a JAVA callback between classes?

I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.

first define a generic callback:

public interface ITypedCallback<T> {
    void execute(T type);
}

create a new ITypedCallback instance on ServerConnections instantiation:

public Server(int _address) {
    serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
        @Override
        public void execute(Socket socket) {
            // do something with your socket here
        }
    });
}

call the execute methode on the callback object.

public class ServerConnections implements Runnable {

    private ITypedCallback<Socket> callback;

    public ServerConnections(ITypedCallback<Socket> _callback) {
        callback = _callback;
    }

    @Override
    public void run() {   
        try {
            mainSocket = new ServerSocket(serverPort);
            while (true) {
                callback.execute(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

btw: I didn't check if it's 100% correct, directly coded it here.

Find something in column A then show the value of B for that row in Excel 2010

Assuming

source data range is A1:B100.
query cell is D1 (here you will input Police or Fire).
result cell is E1

Formula in E1 = VLOOKUP(D1, A1:B100, 2, FALSE)

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

angularjs ng-style: background-image isn't working

Correct syntax for background-image is:

background-image: url("path_to_image");

Correct syntax for ng-style is:

ng-style="{'background-image':'url(https://www.google.com/images/srpr/logo4w.png)'}">

How to replace negative numbers in Pandas Data Frame by zero

If you are dealing with a large df (40m x 700 in my case) it works much faster and memory savvy through iteration on columns with something like.

for col in df.columns:
    df[col][df[col] < 0] = 0

XPath: difference between dot and text()

enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.

In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg

How can I add a class to a DOM element in JavaScript?

new_row.className = "aClassName";

Here's more information on MDN: className

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

How to send a correct authorization header for basic authentication

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

How to convert Calendar to java.sql.Date in Java?

stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));

C# Sort and OrderBy comparison

Darin Dimitrov's answer shows that OrderBy is slightly faster than List.Sort when faced with already-sorted input. I modified his code so it repeatedly sorts the unsorted data, and OrderBy is in most cases slightly slower.

Furthermore, the OrderBy test uses ToArray to force enumeration of the Linq enumerator, but that obviously returns a type (Person[]) which is different from the input type (List<Person>). I therefore re-ran the test using ToList rather than ToArray and got an even bigger difference:

Sort: 25175ms
OrderBy: 30259ms
OrderByWithToList: 31458ms

The code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

class Program
{
    class NameComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return string.Compare(x, y, true);
        }
    }

    class Person
    {
        public Person(string id, string name)
        {
            Id = id;
            Name = name;
        }
        public string Id { get; set; }
        public string Name { get; set; }
        public override string ToString()
        {
            return Id + ": " + Name;
        }
    }

    private static Random randomSeed = new Random();
    public static string RandomString(int size, bool lowerCase)
    {
        var sb = new StringBuilder(size);
        int start = (lowerCase) ? 97 : 65;
        for (int i = 0; i < size; i++)
        {
            sb.Append((char)(26 * randomSeed.NextDouble() + start));
        }
        return sb.ToString();
    }

    private class PersonList : List<Person>
    {
        public PersonList(IEnumerable<Person> persons)
           : base(persons)
        {
        }

        public PersonList()
        {
        }

        public override string ToString()
        {
            var names = Math.Min(Count, 5);
            var builder = new StringBuilder();
            for (var i = 0; i < names; i++)
                builder.Append(this[i]).Append(", ");
            return builder.ToString();
        }
    }

    static void Main()
    {
        var persons = new PersonList();
        for (int i = 0; i < 100000; i++)
        {
            persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
        } 

        var unsortedPersons = new PersonList(persons);

        const int COUNT = 30;
        Stopwatch watch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            watch.Start();
            Sort(persons);
            watch.Stop();
            persons.Clear();
            persons.AddRange(unsortedPersons);
        }
        Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

        watch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            watch.Start();
            OrderBy(persons);
            watch.Stop();
            persons.Clear();
            persons.AddRange(unsortedPersons);
        }
        Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);

        watch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            watch.Start();
            OrderByWithToList(persons);
            watch.Stop();
            persons.Clear();
            persons.AddRange(unsortedPersons);
        }
        Console.WriteLine("OrderByWithToList: {0}ms", watch.ElapsedMilliseconds);
    }

    static void Sort(List<Person> list)
    {
        list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
    }

    static void OrderBy(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
    }

    static void OrderByWithToList(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToList();
    }
}

How to concatenate string variables in Bash

Yet another approach...

> H="Hello "
> U="$H""universe."
> echo $U
Hello universe.

...and yet yet another one.

> H="Hello "
> U=$H"universe."
> echo $U
Hello universe.

How can I find the first and last date in a month using PHP?

To get the first and last date of Last Month;

$dateBegin = strtotime("first day of last month");  
$dateEnd = strtotime("last day of last month");

echo date("D-F-Y", $dateBegin);  
echo "<br>";        
echo date("D-F-Y", $dateEnd);

Why does my Eclipse keep not responding?

for me, it was because of all the outgoing files, i.e workspace is not in sync with SVN, due to the 'target' folders (maven project, or when building web project), add them to svn:ignore.

Link to a section of a webpage

your jump link looks like this

<a href="#div_id">jump link</a>

Then make

<div id="div_id"></div>

the jump link will take you to that div

How to change link color (Bootstrap)

using bootstrap 4 and SCSS check out this link here for full details

https://getbootstrap.com/docs/4.0/getting-started/theming/

in a nutshell...

open up lib/bootstrap/scss/_navbar.scss and find the statements that create these variables

  .navbar-nav {
    .nav-link {
      color: $navbar-light-color;

      @include hover-focus() {
        color: $navbar-light-hover-color;
      }

      &.disabled {
        color: $navbar-light-disabled-color;
      }
    }

so now you need to override

$navbar-light-color
$navbar-light-hover-color
$navbar-light-disabled-color

create a new scss file _localVariables.scss and add the following (with your colors)

$navbar-light-color : #520b71
$navbar-light-hover-color: #F3EFE6;
$navbar-light-disabled-color: #F3EFE6;

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

and on your other scss pages just add

@import "_localVariables";

instead of

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

Attributes / member variables in interfaces?

In Java you can't. Interface has to do with methods and signature, it does not have to do with the internal state of an object -- that is an implementation question. And this makes sense too -- I mean, simply because certain attributes exist, it does not mean that they have to be used by the implementing class. getHeight could actually point to the width variable (assuming that the implementer is a sadist).

(As a note -- this is not true of all languages, ActionScript allows for declaration of pseudo attributes, and I believe C# does too)

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Is there a way to check which CSS styles are being used or not used on a web page?

I'm using CSS Dig. It is made for chrome, but I think it is a great tool!

Remove title in Toolbar in appcompat-v7

The correct way to hide title/label of ToolBar the following codes:

  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(null);

Sending email from Azure

For people wanting to use the built-in .NET SmtpClient rather than the SendGrid client library (not sure if that was the OP's intent), I couldn't get it to work unless I used apikey as my username and the api key itself as the password as outlined here.

<mailSettings>
    <smtp>
        <network host="smtp.sendgrid.net" port="587" userName="apikey" password="<your key goes here>" />
    </smtp>
</mailSettings>

Execute command on all files in a directory

You can use xarg:

ls | xargs -L 1 -d '\n' your-desired-command 
  • -L 1 causes pass 1 item at a time

  • -d '\n' splits the output of ls based on new line.

Composer: The requested PHP extension ext-intl * is missing from your system

This is bit old question but I had faced same problem on linux base server while installing magento 2.

When I am firing composer update or composer install command from my magento root dir. Its was firing below error.

Problem 1
    - The requested PHP extension ext-intl * is missing from your system. Install or enable PHP's intl extension.
  Problem 2
    - The requested PHP extension ext-mbstring * is missing from your system. Install or enable PHP's mbstring extension.
  Problem 3
    - Installation request for pelago/emogrifier 0.1.1 -> satisfiable by pelago/emogrifier[v0.1.1].
    - pelago/emogrifier v0.1.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
   ...

Then, I searched for the available intl & intl extensions, using below commands.

yum list php*intl
yum install php-intl.x86_64  

yum list php*mbstring
yum install php-mbstring.x86_64

And it fixed the issue.

Center div on the middle of screen

Your code is correct you just used .div instead of div

HTML

<div class="ui grid container">
<div class="ui center aligned three column grid">
  <div class="column">
  </div>
  <div class="column">
    </div>
  </div>

CSS

div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}

Check out this Fiddle

Login to Microsoft SQL Server Error: 18456

Just happened to me, and turned out to be different than all other cases listed here.

I happen to have two virtual servers hosted in the same cluster, each with it own IP address. The host configured one of the servers to be the SQL Server, and the other to be the Web server. However, SQL Server is installed and running on both. The host forgot to mention which of the servers is the SQL and which is the Web, so I just assumed the first is Web, second is SQL.

When I connected to the (what I thought is) SQL Server and tried to connect via SSMS, choosing Windows Authentication, I got the error mentioned in this question. After pulling lots of hairs, I went over all the setting, including SQL Server Network Configuration, Protocols for MSSQLSERVER:

screenshot of TCP/IP configuration

Double clicking the TCP/IP gave me this:

TCP/IP properties, showing wrong IP address

The IP address was of the other virtual server! This finally made me realize I simply confused between the servers, and all worked well on the second server.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I just spent about 1 hour to figure out possible solution for the same error.

So what I did under MS WIndows 7 is following

  1. Uninstall all Java packages of all versions.

  2. Download last packages Java SE or JRE for your 32 or 64 Windows and install it.

  3. First install JRE and second is Java SE.

enter image description here

  1. Open text editor and paste this code.

    public class Hello {

      public static void main(String[] args) {
    
         System.out.println("test");
    
      }
    
    } 
    
  2. Save it like Hello.java

  3. Go to Console and compile it like

javac Hello.java

  1. Execute the code like

java Hello

enter image description here

Should be no error.

How to disable 'X-Frame-Options' response header in Spring Security?

If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers().disable()
      ...;
  }
}

How to get the url parameters using AngularJS

While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location service, as injected in your own service or controller:

var paramValue = $location.search().myParam; 

This simple syntax will work for http://example.com/path?myParam=paramValue. However, only if you configured the $locationProvider in the HTML 5 mode before:

$locationProvider.html5Mode(true);

Otherwise have a look at the http://example.com/#!/path?myParam=someValue "Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.

How to capture multiple repeated groups?

Sorry, not Swift, just a proof of concept in the closest language at hand.

// JavaScript POC. Output:
// Matches:  ["GOODBYE","CRUEL","WORLD","IM","LEAVING","U","TODAY"]

let str = `GOODBYE,CRUEL,WORLD,IM,LEAVING,U,TODAY`
let matches = [];

function recurse(str, matches) {
    let regex = /^((,?([A-Z]+))+)$/gm
    let m
    while ((m = regex.exec(str)) !== null) {
        matches.unshift(m[3])
        return str.replace(m[2], '')
    }
    return "bzzt!"
}

while ((str = recurse(str, matches)) != "bzzt!") ;
console.log("Matches: ", JSON.stringify(matches))

Note: If you were really going to use this, you would use the position of the match as given by the regex match function, not a string replace.

Plot smooth line with PyPlot

See the scipy.interpolate documentation for some examples.

The following example demonstrates its use, for linear and cubic spline interpolation:

>>> from scipy.interpolate import interp1d

>>> x = np.linspace(0, 10, num=11, endpoint=True)
>>> y = np.cos(-x**2/9.0)
>>> f = interp1d(x, y)
>>> f2 = interp1d(x, y, kind='cubic')

>>> xnew = np.linspace(0, 10, num=41, endpoint=True)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
>>> plt.legend(['data', 'linear', 'cubic'], loc='best')
>>> plt.show()

enter image description here

Difference between dict.clear() and assigning {} in Python

If you have another variable also referring to the same dictionary, there is a big difference:

>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}

This is because assigning d = {} creates a new, empty dictionary and assigns it to the d variable. This leaves d2 pointing at the old dictionary with items still in it. However, d.clear() clears the same dictionary that d and d2 both point at.

Get current time as formatted string in Go?

Find more info in this post: Get current date and time in various format in golang

This is a taste of the different formats that you'll find in the previous post:

enter image description here

How does bitshifting work in Java?

These examples cover the three types of shifts applied to both a positive and a negative number:

// Signed left shift on 626348975
00100101010101010101001110101111 is   626348975
01001010101010101010011101011110 is  1252697950 after << 1
10010101010101010100111010111100 is -1789571396 after << 2
00101010101010101001110101111000 is   715824504 after << 3

// Signed left shift on -552270512
11011111000101010000010101010000 is  -552270512
10111110001010100000101010100000 is -1104541024 after << 1
01111100010101000001010101000000 is  2085885248 after << 2
11111000101010000010101010000000 is  -123196800 after << 3


// Signed right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >> 1
00001001010101010101010011101011 is   156587243 after >> 2
00000100101010101010101001110101 is    78293621 after >> 3

// Signed right shift on -552270512
11011111000101010000010101010000 is  -552270512
11101111100010101000001010101000 is  -276135256 after >> 1
11110111110001010100000101010100 is  -138067628 after >> 2
11111011111000101010000010101010 is   -69033814 after >> 3


// Unsigned right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >>> 1
00001001010101010101010011101011 is   156587243 after >>> 2
00000100101010101010101001110101 is    78293621 after >>> 3

// Unsigned right shift on -552270512
11011111000101010000010101010000 is  -552270512
01101111100010101000001010101000 is  1871348392 after >>> 1
00110111110001010100000101010100 is   935674196 after >>> 2
00011011111000101010000010101010 is   467837098 after >>> 3

how to get multiple checkbox value using jquery

You can do it like this,

$('.ads_Checkbox:checked')

You can iterate through them with each() and fill the array with checkedbox values.

Live Demo

To get the values of selected checkboxes in array

var i = 0;
$('#save_value').click(function () {
       var arr = [];
       $('.ads_Checkbox:checked').each(function () {
           arr[i++] = $(this).val();
       });      
});

Edit, using .map()

You can also use jQuery.map with get() to get the array of selected checkboxe values.

As a side note using this.value instead of $(this).val() would give better performance.

Live Demo

$('#save_value').click(function(){
    var arr = $('.ads_Checkbox:checked').map(function(){
        return this.value;
    }).get();
}); 

SQL: Group by minimum value in one field while selecting distinct rows

How about something like:

SELECT mt.*     
FROM MyTable mt INNER JOIN
    (
        SELECT id, MIN(record_date) AS MinDate
        FROM MyTable
        GROUP BY id
    ) t ON mt.id = t.id AND mt.record_date = t.MinDate

This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.

Default nginx client_max_body_size

You can increase body size in nginx configuration file as

sudo nano /etc/nginx/nginx.conf

client_max_body_size 100M;

Restart nginx to apply the changes.

sudo service nginx restart

How to remove unwanted space between rows and columns in table?

Adding to vectran's answer: You also have to set cellspacing attribute on the table element for cross-browser compatibility.

<table cellspacing="0">

EDIT (for the sake of completeness I'm expanding this 5 years later:):

Internet Explorer 6 and Internet Explorer 7 required you to set cellspacing directly as a table attribute, otherwise the spacing wouldn't vanish.

Internet Explorer 8 and later versions and all other versions of popular browsers - Chrome, Firefox, Opera 4+ - support the CSS property border-spacing.

So in order to make a cross-browser table cell spacing reset (supporting IE6 as a dinosaur browser), you can follow the below code sample:

_x000D_
_x000D_
table{_x000D_
  border: 1px solid black;_x000D_
}_x000D_
table td {_x000D_
  border: 1px solid black; /* Style just to show the table cell boundaries */_x000D_
}_x000D_
_x000D_
_x000D_
table.no-spacing {_x000D_
  border-spacing:0; /* Removes the cell spacing via CSS */_x000D_
  border-collapse: collapse;  /* Optional - if you don't want to have double border where cells touch */_x000D_
}
_x000D_
<p>Default table:</p>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<p>Removed spacing:</p>_x000D_
_x000D_
<table class="no-spacing" cellspacing="0"> <!-- cellspacing 0 to support IE6 and IE7 -->_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to set the Android progressbar's height?

This is the progress bar I have used.

<ProgressBar
     android:padding="@dimen/dimen_5"
     android:layout_below="@+id/txt_chklist_progress"
     android:id="@+id/pb_media_progress"
     style="@style/MyProgressBar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:progress="70"
     android:scaleY="5"
     android:max="100"
     android:progressBackgroundTint="@color/white"
     android:progressTint="@color/green_above_avg" />

And this is my style tag

 <style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressBackgroundTint">@color/white</item>
    <item name="android:progressTint">@color/green_above_avg</item>
</style>

How to make type="number" to positive numbers only

I have found another solution to prevent negative number.

<input type="number" name="test_name" min="0" oninput="validity.valid||(value='');">

Jquery sortable 'change' event element position

This works for me:

start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
update: function (event, ui) {
        var start_pos = ui.item.data('start_pos');
        var end_pos = ui.item.index();
        //$('#sortable li').removeClass('highlights');
    }

How to calculate mean, median, mode and range from a set of numbers

As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public static void mode(List<Integer> numArr) {
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
    Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();

    int modeFreq = 1; //record the highest frequence
    for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
        Integer curr = numArr.get(x); //O(1)
        freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
        int currFreq = freq.get(curr); //get frequency for current element, O(1)

        //lazy instantiate a list if no existing list, then
        //record mapping of frequency to element (frequency, element), overall O(1)
        mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);

        if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
    }
    mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result
}

Happy coding!

Waiting until the task finishes

Swift 4

You can use Async Function for these situations. When you use DispatchGroup(),Sometimes deadlock may be occures.

var a: Int?
@objc func myFunction(completion:@escaping (Bool) -> () ) {

    DispatchQueue.main.async {
        let b: Int = 3
        a = b
        completion(true)
    }

}

override func viewDidLoad() {
    super.viewDidLoad()

    myFunction { (status) in
        if status {
            print(self.a!)
        }
    }
}

Is there a free GUI management tool for Oracle Database Express?

Yes, there is Oracle SQL Developer, which is maintained by Oracle.

Oracle SQL Developer is a free graphical tool for database development. With SQL Developer, you can browse database objects, run SQL statements and SQL scripts, and edit and debug PL/SQL statements. You can also run any number of provided reports, as well as create and save your own. SQL Developer enhances productivity and simplifies your database development tasks.

SQL Developer can connect to any Oracle Database version 10g and later and runs on Windows, Linux and Mac OSX.

Docker container will automatically stop after "docker run -d"

Argument order matters

Jersey Beans answer (all 3 examples) worked for me. After quite a bit of trial and error I realized that the order of the arguments matter.

Keeps the container running in the background: docker run -t -d <image-name>

Keeps the container running in the foreground: docker run <image-name> -t -d

It wasn't obvious to me coming from a Powershell background.

Find out how much memory is being used by an object in Python

For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.

This method has many drawbacks but it will give you a very fast estimate for very big objects.

Python Pandas Replacing Header with Top Row

new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header

Converting a String array into an int Array in java

To help debug, and make your code better, do this:

private void processLine(String[] strings) {
    Integer[] intarray=new Integer[strings.length];
    int i=0;
    for(String str:strings){
        try {
            intarray[i]=Integer.parseInt(str);
            i++;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
        }
    }
}

Also, from a code neatness point, you could reduce the lines by doing this:

for (String str : strings)
    intarray[i++] = Integer.parseInt(str);

Writing file to web server - ASP.NET

There are methods like WriteAllText in the File class for common operations on files.

Use the MapPath method to get the physical path for a file in your web application.

File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);

Angular 4 default radio button checked by default

We can use [(ngModel)] in following way and have a value selection variable radioSelected

Example tutorial

Demo Link

app.component.html

  <div class="text-center mt-5">
  <h4>Selected value is {{radioSel.name}}</h4>

  <div>
    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 
            {{item.name}}

          </li>
    </ul>
  </div>


  <h5>{{radioSelectedString}}</h5>

  </div>

app.component.ts

  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    title = 'app';
    radioSel:any;
    radioSelected:string;
    radioSelectedString:string;
    itemsList: Item[] = ITEMS;


      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";
        this.getSelecteditem();
      }

      // Get row item from array  
      getSelecteditem(){
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      }
      // Radio Change Event
      onItemChange(item){
        this.getSelecteditem();
      }

  }

Sample Data for Listing

        export const ITEMS: Item[] = [
            {
                name:'Item 1',
                value:'item_1'
            },
            {
                name:'Item 2',
                value:'item_2'
            },
            {
                name:'Item 3',
                value:'item_3'
            },
            {
                name:'Item 4',
                value:'item_4'
                },
                {
                    name:'Item 5',
                    value:'item_5'
                }
        ];

Sql Server : How to use an aggregate function like MAX in a WHERE clause

But its still giving an error message in Query Builder. I am using SqlServerCe 2008.

SELECT         Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount, 
                     Order_Details.TotalPrice
FROM           Order_Products INNER JOIN
                     Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
                     Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING        (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))

I replaced WHERE with HAVING as said by @powerlord. But still showing an error.

Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]

MySQL create stored procedure syntax with delimiter

I have created a simple MySQL procedure as given below:

DELIMITER //
CREATE PROCEDURE GetAllListings()
 BEGIN
 SELECT nid, type, title  FROM node where type = 'lms_listing' order by nid desc;
END //
DELIMITER;

Kindly follow this. After the procedure created, you can see the same and execute it.

Composer: Command Not Found

Your composer.phar command lacks the flag for executable, or it is not inside the path.

The first problem can be fixed with chmod +x composer.phar, the second by calling it as ./composer.phar -v.

You have to prefix executables that are not in the path with an explicit reference to the current path in Unix, in order to avoid going into a directory that has an executable file with an innocent name that looks like a regular command, but is not. Just think of a cat in the current directory that does not list files, but deletes them.

The alternative, and better, fix for the second problem would be to put the composer.phar file into a location that is mentioned in the path

How to re-enable right click so that I can inspect HTML elements in Chrome?

Just Press F12

Go to Sources

There you will find Enable right click. Click on it.

Under this you will find web_accessible_resource.

Open it in this you will find index.js.

Press Ctrl + F and search for disabelRightClick. There you will find

        var disableRightClick = false;  

this line. Replace this line with

        var disableRightClick = true;

Just press Ctrl + s

!! Done. Now your right click is enabled !!

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

One obvious advantage of artificial neural networks over support vector machines is that artificial neural networks may have any number of outputs, while support vector machines have only one. The most direct way to create an n-ary classifier with support vector machines is to create n support vector machines and train each of them one by one. On the other hand, an n-ary classifier with neural networks can be trained in one go. Additionally, the neural network will make more sense because it is one whole, whereas the support vector machines are isolated systems. This is especially useful if the outputs are inter-related.

For example, if the goal was to classify hand-written digits, ten support vector machines would do. Each support vector machine would recognize exactly one digit, and fail to recognize all others. Since each handwritten digit cannot be meant to hold more information than just its class, it makes no sense to try to solve this with an artificial neural network.

However, suppose the goal was to model a person's hormone balance (for several hormones) as a function of easily measured physiological factors such as time since last meal, heart rate, etc ... Since these factors are all inter-related, artificial neural network regression makes more sense than support vector machine regression.

Is Java RegEx case-insensitive?

If your whole expression is case insensitive, you can just specify the CASE_INSENSITIVE flag:

Pattern.compile(regexp, Pattern.CASE_INSENSITIVE)

Checking for NULL pointer in C/C++

I'll start off with this: consistency is king, the decision is less important than the consistency in your code base.

In C++

NULL is defined as 0 or 0L in C++.

If you've read The C++ Programming Language Bjarne Stroustrup suggests using 0 explicitly to avoid the NULL macro when doing assignment, I'm not sure if he did the same with comparisons, it's been a while since I read the book, I think he just did if(some_ptr) without an explicit comparison but I am fuzzy on that.

The reason for this is that the NULL macro is deceptive (as nearly all macros are) it is actually 0 literal, not a unique type as the name suggests it might be. Avoiding macros is one of the general guidelines in C++. On the other hand, 0 looks like an integer and it is not when compared to or assigned to pointers. Personally I could go either way, but typically I skip the explicit comparison (though some people dislike this which is probably why you have a contributor suggesting a change anyway).

Regardless of personal feelings this is largely a choice of least evil as there isn't one right method.

This is clear and a common idiom and I prefer it, there is no chance of accidentally assigning a value during the comparison and it reads clearly:

if (some_ptr) {}

This is clear if you know that some_ptr is a pointer type, but it may also look like an integer comparison:

if (some_ptr != 0) {}

This is clear-ish, in common cases it makes sense... But it's a leaky abstraction, NULL is actually 0 literal and could end up being misused easily:

if (some_ptr != NULL) {}

C++11 has nullptr which is now the preferred method as it is explicit and accurate, just be careful about accidental assignment:

if (some_ptr != nullptr) {}

Until you are able to migrate to C++0x I would argue it's a waste of time worrying about which of these methods you use, they are all insufficient which is why nullptr was invented (along with generic programming issues which came up with perfect forwarding.) The most important thing is to maintain consistency.

In C

C is a different beast.

In C NULL can be defined as 0 or as ((void *)0), C99 allows for implementation defined null pointer constants. So it actually comes down to the implementation's definition of NULL and you will have to inspect it in your standard library.

Macros are very common and in general they are used a lot to make up for deficiencies in generic programming support in the language and other things as well. The language is much simpler and reliance on the preprocessor more common.

From this perspective I'd probably recommend using the NULL macro definition in C.

How to disable phone number linking in Mobile Safari?

<meta name = "format-detection" content = "telephone=no"> does not work for emails: if the HTML you are preparing is for an email, the metatag will be ignored.

If what you are targeting are emails, here's yet another ugly-but-works solution for ya'll:

Example of some HTML you want to avoid being linked or auto formatted:

will cease operations <span class='ios-avoid-format'>on June 1,
2012</span><span></span>.

And the CSS that will make the magic happen:

@media only screen and (device-width: 768px) and (orientation:portrait){
span.ios-date{display:none;}
span.ios-date + span:after{content:"on June 1, 2012";}
}

The drawback: you may need a media query for each of the ipad/iphone portrait/landscape combos

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

Version of Apache installed on a Debian machine

I am using Red Hat Linux and the following command works:

httpd -V

How to check if iframe is loaded or it has a content?

Try this.

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {
        //iframe.contentWindow.alert("Hello");
        iframe.contentWindow.onload = function(){
            alert("I am loaded");
        };
        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    } 

    // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading(){
    alert("I am here");
}
</script>

<body onload="checkIframeLoaded();"> 

Issue with adding common code as git submodule: "already exists in the index"

This happens if the .git file is missing in the target path. It happend to me after I executed git clean -f -d.

I had to delete all target folders showing in the message and then executing git submodule update --remote

What's a good, free serial port monitor for reverse-engineering?

I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.

How to resolve the error on 'react-native start'

The use of yarn prevents this situation. Yarn should use

jQuery - Check if DOM element already exists

if ($('#some_element').length === 0) {
    //If exists then do manipulations
}

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

Angular 4 checkbox change value

Inside your component class:

checkValue(event: any) {
  this.userForm.patchValue({
    state: event
  })
}

Now in controls you have value A or B

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

1 line will do all

For message queue

ipcs -q | sed "$ d; 1,2d" |  awk '{ print "Removing " $2; system("ipcrm -q " $2) }'

ipcs -q will give the records of message queues

sed "$ d; 1,2d " will remove last blank line ("$ d") and first two header lines ("1,2d")

awk will do the rest i.e. printing and removing using command "ipcrm -q" w.r.t. the value of column 2 (coz $2)

undefined reference to 'std::cout'

Yes, using g++ command worked for me:

g++ my_source_code.cpp

openssl s_client using a proxy

You can use proxytunnel:

proxytunnel -p yourproxy:8080 -d www.google.com:443 -a 7000

and then you can do this:

openssl s_client -connect localhost:7000 -showcerts

Hope this can help you!

What is the purpose of class methods?

I recently wanted a very light-weight logging class that would output varying amounts of output depending on the logging level that could be programmatically set. But I didn't want to instantiate the class every time I wanted to output a debugging message or error or warning. But I also wanted to encapsulate the functioning of this logging facility and make it reusable without the declaration of any globals.

So I used class variables and the @classmethod decorator to achieve this.

With my simple Logging class, I could do the following:

Logger._level = Logger.DEBUG

Then, in my code, if I wanted to spit out a bunch of debugging information, I simply had to code

Logger.debug( "this is some annoying message I only want to see while debugging" )

Errors could be out put with

Logger.error( "Wow, something really awful happened." )

In the "production" environment, I can specify

Logger._level = Logger.ERROR

and now, only the error message will be output. The debug message will not be printed.

Here's my class:

class Logger :
    ''' Handles logging of debugging and error messages. '''

    DEBUG = 5
    INFO  = 4
    WARN  = 3
    ERROR = 2
    FATAL = 1
    _level = DEBUG

    def __init__( self ) :
        Logger._level = Logger.DEBUG

    @classmethod
    def isLevel( cls, level ) :
        return cls._level >= level

    @classmethod
    def debug( cls, message ) :
        if cls.isLevel( Logger.DEBUG ) :
            print "DEBUG:  " + message

    @classmethod
    def info( cls, message ) :
        if cls.isLevel( Logger.INFO ) :
            print "INFO :  " + message

    @classmethod
    def warn( cls, message ) :
        if cls.isLevel( Logger.WARN ) :
            print "WARN :  " + message

    @classmethod
    def error( cls, message ) :
        if cls.isLevel( Logger.ERROR ) :
            print "ERROR:  " + message

    @classmethod
    def fatal( cls, message ) :
        if cls.isLevel( Logger.FATAL ) :
            print "FATAL:  " + message

And some code that tests it just a bit:

def logAll() :
    Logger.debug( "This is a Debug message." )
    Logger.info ( "This is a Info  message." )
    Logger.warn ( "This is a Warn  message." )
    Logger.error( "This is a Error message." )
    Logger.fatal( "This is a Fatal message." )

if __name__ == '__main__' :

    print "Should see all DEBUG and higher"
    Logger._level = Logger.DEBUG
    logAll()

    print "Should see all ERROR and higher"
    Logger._level = Logger.ERROR
    logAll()

How to get a cookie from an AJAX response?

The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!

For this to work you need to:

1) login with the ajax request from which you expect cookies to be returned:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) Connect with xhrFields: { withCredentials: true } in the next ajax request(s) to use the credentials saved by the browser

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

The browser takes care of these cookies for you even though they are not readable from the headers nor the document.cookie

How to allocate aligned memory only using the standard library?

If there are constraints that, you cannot waste a single byte, then this solution works: Note: There is a case where this may be executed infinitely :D

   void *mem;  
   void *ptr;
try:
   mem =  malloc(1024);  
   if (mem % 16 != 0) {  
       free(mem);  
       goto try;
   }  
   ptr = mem;  
   memset_16aligned(ptr, 0, 1024);

How do I convert an integer to binary in JavaScript?

The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer)

1. Number System

(123456).toString(2) will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.

2. Internal Representation

The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.

3. Masks & Bitwise Operators

MDN has a good overview of how bitwise operators work. Importantly:

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)

Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.

Here is the MDN example code for converting numbers into 32-bit strings.

function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}

createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"

Datetime BETWEEN statement not working in SQL Server

Do you have times associated with your dates? BETWEEN is inclusive, but when you convert 2013-10-18 to a date it becomes 2013-10-18 00:00:000.00. Anything that is logged after the first second of the 18th will not shown using BETWEEN, unless you include a time value.

Try:

SELECT * FROM LOGS WHERE CHECK_IN BETWEEN CONVERT(datetime,'2013-10-17') AND CONVERT(datetime,'2013-10-18 23:59:59:999')

if you want to search the entire day of the 18th.

SQL DATETIME fields have milliseconds. So I added 999 to the field.

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

Are you running Android M? If so, this is because it's not enough to declare permissions in the manifest. For some permissions, you have to explicitly ask user in the runtime: http://developer.android.com/training/permissions/requesting.html

How do I delete a local repository in git?

In the repository directory you remove the directory named .git and that's all :). On Un*x it is hidden, so you might not see it from file browser, but

cd repository-path/
rm -r .git

should do the trick.

Remove Blank option from Select Option with AngularJS

For reference : Why does angularjs include an empty option in select?

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

Change your code like this

_x000D_
_x000D_
var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
  $scope.feed = {};

  //Configuration
  $scope.feed.configs = [
    {'name': 'Config 1',
     'value': 'config1'},
    {'name': 'Config 2',
     'value': 'config2'},
    {'name': 'Config 3',
     'value': 'config3'}
  ];
  //Setting first option as selected in configuration select
  $scope.feed.config = $scope.feed.configs[0].value;
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp1">
  <div ng-controller="MyController">
    <input type="text" ng-model="feed.name" placeholder="Name" />
    <!-- <select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select> -->
    <select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
    </select>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Working JSFiddle Demo

UPDATE (Dec 31, 2015)

If You don't want to set a default value and want to remove blank option,

<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
      <option value="" selected="selected">Choose</option>
</select>

And in JS no need to initialize value.

$scope.feed.config = $scope.feed.configs[0].value;

can't load package: package .: no buildable Go source files

Another possible reason for the message:

can't load package: .... : no buildable Go source files

Is when the source files being compiled have:

// +build ignore

In which case the files are ignored and not buildable as requested.This behaviour is documented at https://golang.org/pkg/go/build/

What good technology podcasts are out there?

I am the creator of Connected Show (http://www.ConnectedShow.com) and really want to thank this thread for posting us in the list. We are new and would love to get more listeners and more feedback.

How do I compile a .c file on my Mac?

You'll need to get a compiler. The easiest way is probably to install XCode development environment from the CDs/DVDs you got with your Mac, which will give you gcc. Then you should be able compile it like

gcc -o mybinaryfile mysourcefile.c

Counting Chars in EditText Changed Listener

This is a slightly more general answer with more explanation for future viewers.

Add a text changed listener

If you want to find the text length or do something else after the text has been changed, you can add a text changed listener to your edit text.

EditText editText = (EditText) findViewById(R.id.testEditText);
editText.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count)  {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

The listener needs a TextWatcher, which requires three methods to be overridden: beforeTextChanged, onTextChanged, and afterTextChanged.

Counting the characters

You can get the character count in onTextChanged or beforeTextChanged with

charSequence.length()

or in afterTextChanged with

editable.length()

Meaning of the methods

The parameters are a little confusing so here is a little extra explanation.

beforeTextChanged

beforeTextChanged(CharSequence charSequence, int start, int count, int after)

  • charSequence: This is the text content before the pending change is made. You should not try to change it.
  • start: This is the index of where the new text will be inserted. If a range is selected, then it is the beginning index of the range.
  • count: This is the length of selected text that is going to be replaced. If nothing is selected then count will be 0.
  • after: this is the length of the text to be inserted.

onTextChanged

onTextChanged(CharSequence charSequence, int start, int before, int count)

  • charSequence: This is the text content after the change was made. You should not try to modify this value here. Modify the editable in afterTextChanged if you need to.
  • start: This is the index of the start of where the new text was inserted.
  • before: This is the old value. It is the length of previously selected text that was replaced. This is the same value as count in beforeTextChanged.
  • count: This is the length of text that was inserted. This is the same value as after in beforeTextChanged.

afterTextChanged

afterTextChanged(Editable editable)

Like onTextChanged, this is called after the change has already been made. However, now the text may be modified.

  • editable: This is the editable text of the EditText. If you change it, though, you have to be careful not to get into an infinite loop. See the documentation for more details.

Supplemental image from this answer

enter image description here

Python: Find a substring in a string and returning the index of the substring

Not directly answering the question but I got a similar question recently where I was asked to count the number of times a sub-string is repeated in a given string. Here is the function I wrote:

def count_substring(string, sub_string):
    cnt = 0
    len_ss = len(sub_string)
    for i in range(len(string) - len_ss + 1):
        if string[i:i+len_ss] == sub_string:
            cnt += 1
    return cnt

The find() function probably returns the index of the fist occurrence only. Storing the index in place of just counting, can give us the distinct set of indices the sub-string gets repeated within the string.

Disclaimer: I am 'extremly' new to Python programming.

jQuery Ajax File Upload

to upload a file which is submitted by user as a part of form using jquery please follow the below code :

var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);

Then send the form data object to server.

We can also append a File or Blob directly to the FormData object.

data.append("myfile", myBlob, "filename.txt");

How would you make two <div>s overlap?

With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:

div#logo {
  position: absolute;
  left: 100px; // or whatever
}

Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

Select rows of a matrix that meet a condition

I will choose a simple approach using the dplyr package.

If the dataframe is data.

library(dplyr)
result <- filter(data, three == 11)

How to get a variable type in Typescript?

For :

abc:number|string;

Use the JavaScript operator typeof:

if (typeof abc === "number") {
    // do something
}

TypeScript understands typeof

This is called a typeguard.

More

For classes you would use instanceof e.g.

class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`
}

There are also other type guards e.g. in etc https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

Laravel Checking If a Record Exists

if (User::where('email', '[email protected]')->first()) {
    // It exists
} else {
    // It does not exist
}

Use first(), not count() if you only need to check for existence.

first() is faster because it checks for a single match whereas count() counts all matches.

how to declare global variable in SQL Server..?

There is no way to declare a global variable in Transact-SQL. However, if all you want your variables for is to be accessible across batches of a single script, you can use the SQLCMD tool or the SQLCMD mode of SSMS and define that tool/mode-specific variables like this:

:setvar myvar 10

and then use them like this:

$(myvar)

To use SSMS's SQLCMD mode:

enter image description here

Inner text shadow with CSS

I'm using it from this site, also it looks good. Have a look at it Inner shadow

Bootstrap 3 Flush footer to bottom. not fixed

See the example below. This will position your Footer to stick to bottom if the page has less content and behave like a normal footer if the page has more content.

CSS

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 155px; /* .push must be the same height as .footer */
}

HTML

<div class="wrapper">
  <p>Your website content here.</p>
  <div class="push"></div>
</div>
<div class="footer">
  <p>Copyright (c) 2008</p>
</div>

UPDATE: New version of Bootstrap demonstrates how to add sticky footer without adding a wrapper. Please see Jboy Flaga's Answer for more details.

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

typescript - cloning object

It's easy to get a shallow copy with "Object Spread" introduced in TypeScript 2.1

this TypeScript: let copy = { ...original };

produces this JavaScript:

var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
var copy = __assign({}, original);

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

How to enable native resolution for apps on iPhone 6 and 6 Plus?

Note that iPhone 6 will use the 320pt (640px) resolution if you have enabled the 'Display Zoom' in iPhone > Settings > Display & Brightness > View.

How to store directory files listing into an array?

Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.

files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
  printf "   %s\n" $item
done

How to append a date in batch files

Bernhard's answer needed some tweaking work for me because the %DATE% environment variable is in a different format (as commented elsewhere). Also, there was a tilde (~) missing.

Instead of:

set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%

I had to use:

set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%

for the date format:

c:\Scripts>echo %DATE%

Thu 05/14/2009

Converting double to string

Use StringBuilder class, like so:

StringBuilder meme = new StringBuilder(" ");

// Convert and append your double variable
meme.append(String.valueOf(doubleVariable));

// Convert string builder to string
jTextField9.setText(meme.toString());

You will get you desired output.

Python 3 print without parenthesis

You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.

How can I output the value of an enum class in C++11

Following worked for me in C++11:

template <typename Enum>
constexpr typename std::enable_if<std::is_enum<Enum>::value,
                                  typename std::underlying_type<Enum>::type>::type
to_integral(Enum const& value) {
    return static_cast<typename std::underlying_type<Enum>::type>(value);
}

selecting unique values from a column

use

SELECT DISTINCT Date FROM buy ORDER BY Date

so MySQL removes duplicates

BTW: using explicit column names in SELECT uses less resources in PHP when you're getting a large result from MySQL

How do I disable orientation change on Android?

Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:

Avoid reloading activity with asynctask on orientation change in android

Add android:configChanges="keyboardHidden|orientation" to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.

<activity android:name="MainActivity"
     android:screenOrientation="portrait"
     android:configChanges="keyboardHidden|orientation">

See Developer reference configChanges for more details.

However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.

Update: As of Android 3.2, you also need to add "screenSize":

<activity
    android:name="MainActivity"
    android:screenOrientation="portrait"
    android:configChanges="keyboardHidden|orientation|screenSize">

From Developer guide Handling the Configuration Change Yourself

Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).

Android Studio doesn't see device

I have found that what works for me is:

  • CD to your sdk platform-tools folder

  • Check if adb sees your device

    ./adb devices
    
  • If it displays 'List of devices attached' and a blank line below, then restart adb as follows:

    ./adb kill-server
    ./adb start-server
    

    then re-run ./adb devices and see if it picks up the device, eg as follows:

    List of devices attached
    015d2bc285601c0a device

Running bash script from within python

If chmod not working then you also try

import os
os.system('sh script.sh')
#you can also use bash instead of sh

test by me thanks

How to use BOOLEAN type in SELECT statement

select get_something('NAME', sys.diutil.int_to_bool(1)) from dual;

How to delete projects in Intellij IDEA 14?

In my strange case, Intellij remembers forever about my project even if I delete .iml... Thus I did the following:

  1. Close project. Delete the .iml file.
  2. Rename my project directory (say my_proj) to my_proj_backup.
  3. (Possibly not needed) Open my_proj_backup in Intellij and close.
  4. Create an empty directory called my_proj, and open it in Intellij. Then close it.
  5. Remove the my_proj and move my_proj_backup back to my_proj. Then open my_proj in Intellij.

Then it happily forgot the old my_proj :)

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

I loved Powtac's answer, but I wanted to use it in angular.js, so I created a filter using his code.

.filter('HHMMSS', ['$filter', function ($filter) {
    return function (input, decimals) {
        var sec_num = parseInt(input, 10),
            decimal = parseFloat(input) - sec_num,
            hours   = Math.floor(sec_num / 3600),
            minutes = Math.floor((sec_num - (hours * 3600)) / 60),
            seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        var time    = hours+':'+minutes+':'+seconds;
        if (decimals > 0) {
            time += '.' + $filter('number')(decimal, decimals).substr(2);
        }
        return time;
    };
}])

It's functionally identical, except that I added in an optional decimals field to display fractional seconds. Use it like you would any other filter:

{{ elapsedTime | HHMMSS }} displays: 01:23:45

{{ elapsedTime | HHMMSS : 3 }} displays: 01:23:45.678

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

Simple solution with mouseweel event:

$('.element').bind('mousewheel', function(e, d) {
    console.log(this.scrollTop,this.scrollHeight,this.offsetHeight,d);
    if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
        || (this.scrollTop === 0 && d > 0)) {
        e.preventDefault();
    }
});

How can I change cols of textarea in twitter-bootstrap?

Another option is to split off the textarea in the Site.css as follows:

/* Set width on the form input elements since they're 100% wide by default */

input,
select {

  max-width: 280px;
}

textarea {

  /*max-width: 280px;*/
  max-width: 500px;
  width: 280px;
  height: 200px;
}

also (in my MVC 5) add ref to textarea:

@Html.TextAreaFor(model => ................... @class = "form-control", @id="textarea"............

It worked for me

Get a random item from a JavaScript array

var item = items[Math.floor(Math.random() * items.length)];

How to read attribute value from XmlNode in C#?

To expand Konamiman's solution (including all relevant null checks), this is what I've been doing:

if (node.Attributes != null)
{
   var nameAttribute = node.Attributes["Name"];
   if (nameAttribute != null) 
      return nameAttribute.Value;

   throw new InvalidOperationException("Node 'Name' not found.");
}

How to add and remove classes in Javascript without jQuery

When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().

function removeClass(classString, toRemove) {
    classes = classString.split(' ');
    var out = Array();
    for (var i=0; i<classes.length; i++) {
        if (classes[i].length == 0) // double spaces can create empty elements
            continue;
        if (classes[i] == toRemove) // don't include this one
            continue;
        out.push(classes[i])
    }
    return out.join(' ');
}

This method is a lot bigger than a simple replace() but at least it can be used on older browsers. And in case the browser doesn't even support the split() command it's relatively easy to add it using prototype.

How to move screen without moving cursor in Vim?

To leave the cursor in the same column when you use Ctrl+D, Ctrl+F, Ctrl+B, Ctrl+U, G, H, M, L, gg

you should define the following option:

:set nostartofline

Android - how do I investigate an ANR?

Consider using the ANR-Watchdog library to accurately track and capture ANR stack traces in a high level of detail. You can then send them to your crash reporting library. I recommend using setReportMainThreadOnly() in this scenario. You can either make the app throw a non-fatal exception of the freeze point, or make the app force quit when the ANR happens.

Note that the standard ANR reports sent to your Google Play Developer console are often not accurate enough to pinpoint the exact problem. That's why a third-party library is needed.

What's the equivalent of Java's Thread.sleep() in JavaScript?

This eventually helped me:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);

        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }

How to write a cursor inside a stored procedure in SQL Server 2008

What's wrong with just simply using a single, simple UPDATE statement??

UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)

That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.

PHP Unset Array value effect on other indexes

Test it yourself, but here's the output.

php -r '$a=array("a","b","c"); print_r($a); unset($a[1]); print_r($a);'
Array
(
    [0] => a
    [1] => b
    [2] => c
)
Array
(
    [0] => a
    [2] => c
)

Getting value GET OR POST variable using JavaScript?

When i had the issue i saved the value into a hidden input:

in html body:

    <body>
    <?php 
    if (isset($_POST['Id'])){
      $fid= $_POST['Id']; 
    }
    ?>

... then put the hidden input on the page and write the value $fid with php echo

    <input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">

then in $(document).ready( function () {

    var postId=document.getElementById("fid").value;

so i got my hidden url parameter in php an js.

One line if-condition-assignment

In one line:

if someBoolValue: num1 = 20

But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.

if someBoolValue:
    num1 = 20

(Equally, camel caps should be avoided. So rather use some_bool_value.)

Note that an in-line expression some_value if predicate without an else part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.

What does the C++ standard state the size of int, long type to be?

On a 64-bit machine:

int: 4
long: 8
long long: 8
void*: 8
size_t: 8

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I also ran into this problem. My situation was a little different. I was using 'working sets' to group my projects inside of eclipse. What I had done was attempt to delete a project and received errors while deleting. Ignoring the errors I removed the project from my working set and thus didn't see that I even had the project anymore. When I received my error I didn't think to look through my package explorer with 'projects', opposed to working sets, as my top view. After switching to a top level view of projects I found the project that was half deleted and was able to delete its contents from both my workspace and the hard drive.

I haven't had the error since.

What are the differences between char literals '\n' and '\r' in Java?

It depends on which Platform you work. To get the correct result use -

System.getProperty("line.separator")

How can I determine if a variable is 'undefined' or 'null'?

Best way:

if(typeof variable==='undefined' || variable===null) {

/* do your stuff */
}

How to comment out a block of code in Python

The only cure I know for this is a good editor. Sorry.

Differences in string compare methods in C#

In the forms you listed here, there's not much difference between the two. CompareTo ends up calling a CompareInfo method that does a comparison using the current culture; Equals is called by the == operator.

If you consider overloads, then things get different. Compare and == can only use the current culture to compare a string. Equals and String.Compare can take a StringComparison enumeration argument that let you specify culture-insensitive or case-insensitive comparisons. Only String.Compare allows you to specify a CultureInfo and perform comparisons using a culture other than the default culture.

Because of its versatility, I find I use String.Compare more than any other comparison method; it lets me specify exactly what I want.

Android - How to achieve setOnClickListener in Kotlin?

**i have use kotlin-extension so i can access directly by button id:**


btnSignIN.setOnClickListener {
            if (AppUtils.isNetworkAvailable(activity as BaseActivity)) {
                if (checkValidation()) {

                    hitApiLogin()
                }
            }
        }