Programs & Examples On #Counting

Counting is the action of finding the number of elements of a finite set of objects.

Counting the number of True Booleans in a Python List

If you are only concerned with the constant True, a simple sum is fine. However, keep in mind that in Python other values evaluate as True as well. A more robust solution would be to use the bool builtin:

>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3

UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:

>>> sum(1 for x in l if x)
3

P.S. Python trivia: True could be true without being 1. Warning: do not try this at work!

>>> True = 2
>>> if True: print('true')
... 
true
>>> l = [True, True, False, True]
>>> sum(l)
6
>>> sum(bool(x) for x in l)
3
>>> sum(1 for x in l if x)
3

Much more evil:

True = False

How to count digits, letters, spaces for a string in Python?

def match_string(words):
    nums = 0
    letter = 0
    other = 0
    for i in words :
        if i.isalpha():
            letter+=1
        elif i.isdigit():
            nums+=1
        else:
            other+=1
    return nums,letter,other

x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>

How do I count unique visitors to my site?

Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.

In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.

Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!


Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).

How to count the frequency of the elements in an unordered list?

This approach can be tried if you don't want to use any library and keep it simple and short!

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)

o/p

[4, 4, 2, 1, 2]

Find the item with maximum occurrences in a list

Here is a defaultdict solution that will work with Python versions 2.5 and above:

from collections import defaultdict

L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
    d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times

Note if L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67] then there are six 4s and six 7s. However, the result will be (4, 6) i.e. six 4s.

Item frequency count in Python

defaultdict to the rescue!

from collections import defaultdict

words = "apple banana apple strawberry banana lemon"

d = defaultdict(int)
for word in words.split():
    d[word] += 1

This runs in O(n).

Android – Listen For Incoming SMS Messages

This is what i used!

public class SMSListener extends BroadcastReceiver {

    // Get the object of SmsManager
    final SmsManager sms = SmsManager.getDefault();
String mobile,body;

    public void onReceive(Context context, Intent intent) {

        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                     mobile=senderNum.replaceAll("\\s","");
                     body=message.replaceAll("\\s","+");


                    Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + body);


                    // Show Alert
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context,
                            "senderNum: "+ mobile+ ", message: " + message, duration);
                    toast.show();

                } // end for loop
            } // bundle is null

        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);

        }
    }
}

How do I create a file AND any folders, if the folders don't exist?

Following code will create directories (if not exists) & then copy files.

// using System.IO;

// for ex. if you want to copy files from D:\A\ to D:\B\
foreach (var f in Directory.GetFiles(@"D:\A\", "*.*", SearchOption.AllDirectories))
{
    var fi =  new FileInfo(f);
    var di = new DirectoryInfo(fi.DirectoryName);

    // you can filter files here
    if (fi.Name.Contains("FILTER")
    {
        if (!Directory.Exists(di.FullName.Replace("A", "B"))
        {                       
            Directory.CreateDirectory(di.FullName.Replace("A", "B"));           
            File.Copy(fi.FullName, fi.FullName.Replace("A", "B"));
        }
    }
}

How to execute mongo commands through shell scripts?

--shell flag can also be used for javascript files

 mongo --shell /path/to/jsfile/test.js 

The import javax.persistence cannot be resolved

Yes, you will likely need to add another jar or dependency

javax.persistence.* is part of the Java Persistence API (JPA). It is only an API, you can think of it as similar to an interface. There are many implementations of JPA and this answer gives a very good elaboration of each, as well as which to use.

If your javax.persistence.* import cannot be resolved, you will need to provide the jar that implements JPA. You can do that either by manually downloading it (and adding it to your project) or by adding a declaration to a dependency management tool (for eg, Ivy/Maven/Gradle). See here for the EclipseLink implementation (the reference implementation) on Maven repo.

After doing that, your imports should be resolved.

Also see here for what is JPA about. The xml you are referring to could be persistence.xml, which is explained on page 3 of the link.

That being said, you might just be pointing to the wrong target runtime

If i recall correctly, you don't need to provide a JPA implementation if you are deploying it into a JavaEE app server like JBoss. See here "Note that you typically don't need it when you deploy your application in a Java EE 6 application server (like JBoss AS 6 for example).". Try changing your project's target runtime.

If your local project was setup to point to Tomcat while your remote repo assumes a JavaEE server, this could be the case. See here for the difference between Tomcat and JBoss.

Edit: I changed my project to point to GlassFish instead of Tomcat and javax.persistence.* resolved fine without any explicit JPA dependency.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

  1. Note the URL: localhost:55828/token (not localhost:55828/API/token)
  2. Note the request data. Its not in json format, its just plain data without double quotes. [email protected]&password=Test123$&grant_type=password
  3. Note the content type. Content-Type: 'application/x-www-form-urlencoded' (not Content-Type: 'application/json')
  4. When you use JavaScript to make post request, you may use following:

    $http.post("localhost:55828/token", 
      "userName=" + encodeURIComponent(email) +
        "&password=" + encodeURIComponent(password) +
        "&grant_type=password",
      {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
    ).success(function (data) {//...
    

See screenshots below from Postman:

Postman Request

Postman Request Header

Easiest way to split a string on newlines in .NET?

What about using a StringReader?

using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
    string line = reader.ReadLine();
}

Programmatically change the src of an img tag

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)

Python: How to create a unique file name?

In case you need short unique IDs as your filename, try shortuuid, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.

>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22

compared to

>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'

MySQL Query - Records between Today and Last 30 Days

You can also write this in mysql -

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date < DATE_ADD(NOW(), INTERVAL -1 MONTH);

FIXED

How do I clear this setInterval inside a function?

Simplest way I could think of: add a class.

Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.

_x000D_
_x000D_
var i = 0;_x000D_
this.setInterval(function() {_x000D_
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
    console.log('Counting...');_x000D_
    $('#counter').html(i++); //just for explaining and showing_x000D_
  } else {_x000D_
    console.log('Stopped counting');_x000D_
  }_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
    $(this).addClass('pauseInterval');_x000D_
  },function() { //mouse leave_x000D_
    $(this).removeClass('pauseInterval');_x000D_
  }_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
  $('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
  width: 50%;_x000D_
  background: #ddd;_x000D_
  border: 2px solid #009afd;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
  transition: .3s;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
  border-color: red;  _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter">&nbsp;</p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
_x000D_
_x000D_

difference between variables inside and outside of __init__()

Without Self

Create some objects:

class foo(object):
    x = 'original class'

c1, c2 = foo(), foo()

I can change the c1 instance, and it will not affect the c2 instance:

c1.x = 'changed instance'
c2.x
>>> 'original class'

But if I change the foo class, all instances of that class will be changed as well:

foo.x = 'changed class'
c2.x
>>> 'changed class'

Please note how Python scoping works here:

c1.x
>>> 'changed instance'

With Self

Changing the class does not affect the instances:

class foo(object):
    def __init__(self):
        self.x = 'original self'

c1 = foo()
foo.x = 'changed class'
c1.x
>>> 'original self'

read.csv warning 'EOF within quoted string' prevents complete reading of file

I had the similar problem: EOF -warning and only part of data was loading with read.csv(). I tried the quotes="", but it only removed the EOF -warning.

But looking at the first row that was not loading, I found that there was a special character, an arrow ? (hexadecimal value 0x1A) in one of the cells. After deleting the arrow I got the data to load normally.

Why do I get access denied to data folder when using adb?

Starting from API level 8 (Android 2.2), for the debuggable application (the one built by Android Studio all the times unless the release build was requested), you can use the shell run-as command to run a command or executable as a specific user/application or just switch to the UID of your application so you can access its data directory.

List directory content of yourapp:

run-as com.yourapp ls -l /data/data/com.yourapp

Switch to UID of com.yourapp and run all further commands using that uid (until you call exit):

run-as com.yourapp
cd /data/data/com.yourapp
ls -l
exit

 
Note 1: there is a known issue with some HTC Desire phones. Because of a non-standard owner/permissions of the /data/data directory, run-as command fails to run on those phones.

Note 2: As pointed in the comments by @Avio: run-as has issues also with Samsung Galaxy S phones running Cyanogenmod at any version (from 7 to 10.1) because on this platform /data/data is a symlink to /datadata. One way to solve the issue is to replace the symlink with the actual directory (unfortunately this usually requires root access).

How to use activity indicator view on iPhone?

The documentation on this is pretty clear. It's a UIView subclass so you use it like any other view. To start/stop the animation you use

[activityIndicator startAnimating];
[activityIndicator stopAnimating];

How to automatically select all text on focus in WPF TextBox?

Here's a very good very simple solution on MSDN:

<TextBox
    MouseDoubleClick="SelectAddress"
    GotKeyboardFocus="SelectAddress"
    PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" />

Here's the code behind:

private void SelectAddress(object sender, RoutedEventArgs e)
{
    TextBox tb = (sender as TextBox);
    if (tb != null)
    {
        tb.SelectAll();
    }
}

private void SelectivelyIgnoreMouseButton(object sender,
    MouseButtonEventArgs e)
{
    TextBox tb = (sender as TextBox);
    if (tb != null)
    {
        if (!tb.IsKeyboardFocusWithin)
        {
            e.Handled = true;
            tb.Focus();
        }
    }
}

Why should text files end with a newline?

This answer is an attempt at a technical answer rather than opinion.

If we want to be POSIX purists, we define a line as:

A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206

An incomplete line as:

A sequence of one or more non- <newline> characters at the end of the file.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_195

A text file as:

A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the <newline> character. Although POSIX.1-2008 does not distinguish between text files and binary files (see the ISO C standard), many utilities only produce predictable or meaningful output when operating on text files. The standard utilities that have such restrictions always specify "text files" in their STDIN or INPUT FILES sections.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_397

A string as:

A contiguous sequence of bytes terminated by and including the first null byte.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_396

From this then, we can derive that the only time we will potentially encounter any type of issues are if we deal with the concept of a line of a file or a file as a text file (being that a text file is an organization of zero or more lines, and a line we know must terminate with a <newline>).

Case in point: wc -l filename.

From the wc's manual we read:

A line is defined as a string of characters delimited by a <newline> character.

What are the implications to JavaScript, HTML, and CSS files then being that they are text files?

In browsers, modern IDEs, and other front-end applications there are no issues with skipping EOL at EOF. The applications will parse the files properly. It has to since not all Operating Systems conform to the POSIX standard, so it would be impractical for non-OS tools (e.g. browsers) to handle files according to the POSIX standard (or any OS-level standard).

As a result, we can be relatively confident that EOL at EOF will have virtually no negative impact at the application level - regardless if it is running on a UNIX OS.

At this point we can confidently say that skipping EOL at EOF is safe when dealing with JS, HTML, CSS on the client-side. Actually, we can state that minifying any one of these files, containing no <newline> is safe.

We can take this one step further and say that as far as NodeJS is concerned it too cannot adhere to the POSIX standard being that it can run in non-POSIX compliant environments.

What are we left with then? System level tooling.

This means the only issues that may arise are with tools that make an effort to adhere their functionality to the semantics of POSIX (e.g. definition of a line as shown in wc).

Even so, not all shells will automatically adhere to POSIX. Bash for example does not default to POSIX behavior. There is a switch to enable it: POSIXLY_CORRECT.

Food for thought on the value of EOL being <newline>: https://www.rfc-editor.org/old/EOLstory.txt

Staying on the tooling track, for all practical intents and purposes, let's consider this:

Let's work with a file that has no EOL. As of this writing the file in this example is a minified JavaScript with no EOL.

curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o x.js
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o y.js

$ cat x.js y.js > z.js

-rw-r--r--  1 milanadamovsky   7905 Aug 14 23:17 x.js
-rw-r--r--  1 milanadamovsky   7905 Aug 14 23:17 y.js
-rw-r--r--  1 milanadamovsky  15810 Aug 14 23:18 z.js

Notice the cat file size is exactly the sum of its individual parts. If the concatenation of JavaScript files is a concern for JS files, the more appropriate concern would be to start each JavaScript file with a semi-colon.

As someone else mentioned in this thread: what if you want to cat two files whose output becomes just one line instead of two? In other words, cat does what it's supposed to do.

The man of cat only mentions reading input up to EOF, not <newline>. Note that the -n switch of cat will also print out a non- <newline> terminated line (or incomplete line) as a line - being that the count starts at 1 (according to the man.)

-n Number the output lines, starting at 1.

Now that we understand how POSIX defines a line , this behavior becomes ambiguous, or really, non-compliant.

Understanding a given tool's purpose and compliance will help in determining how critical it is to end files with an EOL. In C, C++, Java (JARs), etc... some standards will dictate a newline for validity - no such standard exists for JS, HTML, CSS.

For example, instead of using wc -l filename one could do awk '{x++}END{ print x}' filename , and rest assured that the task's success is not jeopardized by a file we may want to process that we did not write (e.g. a third party library such as the minified JS we curld) - unless our intent was truly to count lines in the POSIX compliant sense.

Conclusion

There will be very few real life use cases where skipping EOL at EOF for certain text files such as JS, HTML, and CSS will have a negative impact - if at all. If we rely on <newline> being present, we are restricting the reliability of our tooling only to the files that we author and open ourselves up to potential errors introduced by third party files.

Moral of the story: Engineer tooling that does not have the weakness of relying on EOL at EOF.

Feel free to post use cases as they apply to JS, HTML and CSS where we can examine how skipping EOL has an adverse effect.

How to impose maxlength on textArea in HTML using JavaScript

Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:

$("#comments").bind("keyup keydown", function() {
    var max = 500;
    var value = $(this).val();
    var left = max - value.length;
    if(left < 0) {
        $(this).val( value.slice(0, left) );
        left = 0;
    }
    $("#charcount").text(left);
}); 

<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>

npm start error with create-react-app

I have created react project locally. This reason of occurring this problem (for me) was that I didn't use sudo before npm and it needs root access (

> sudo npm start

PS1: For windows users, the powershell or command line should be run as administrator)

PS2: If use want to solve the root access issue, you can see this post.

How to test if parameters exist in rails

You can write it more succinctly like the following:

required = [:one, :two, :three]
if required.all? {|k| params.has_key? k}
  # here you know params has all the keys defined in required array
else
  ...
end

Fast ceiling of an integer division in C / C++

For positive numbers:

    q = x/y + (x % y != 0);

How to delete duplicate rows in SQL Server?

Another way of removing dublicated rows without loosing information in one step is like following:

delete from dublicated_table t1 (nolock)
join (
    select t2.dublicated_field
    , min(len(t2.field_kept)) as min_field_kept
    from dublicated_table t2 (nolock)
    group by t2.dublicated_field having COUNT(*)>1
) t3 
on t1.dublicated_field=t3.dublicated_field 
    and len(t1.field_kept)=t3.min_field_kept

What does ECU units, CPU core and memory mean when I launch a instance

ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it

Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

OK, my answer is super nice:

<style>
    #wrapper {
        display:flex;    
        width:100%;
        align-content: streach;
        justify-content: space-between;
    }    

    #wrapper div {
        height:100px;
    }

    .static240 {
        flex: 0 0 240px;
    }
    .static160 {
        flex: 0 0 160px;
    }

    .growMax {
        flex-grow: 1;
    }

</style>

<div id="wrapper">
  <div class="static240" style="background:red;" > </div>
  <div class="static160"  style="background: green;" > </div> 
  <div class="growMax"  style="background:yellow;"  ></div>
</div>

jsfiddle playground

if you wanna support for all browser, use https://github.com/10up/flexibility

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I'm super late to this but I didn't like the other answers

Installing Homebrew

For brew run

"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Installing node & npm

You SHOULD NOT use brew to install node and npm.

I've seen a few places suggested that you should use Homebrew to install Node (like alexpods answer and in this Team Treehouse blog Post) but installing this way you're more prone to run into issues as npm and brew are both package managers and you should have a package manager manage another package manager this leads to problems, like this bug offical npm issues Error: Refusing to delete: /usr/local/bin/npm or this Can't uninstall npm module on OSX

You can read more on the topic in DanHerbert's post Fixing npm On Mac OS X for Homebrew Users, where he goes on to say

Also, using the Homebrew installation of npm will require you to use sudo when installing global packages. Since one of the core ideas behind Homebrew is that apps can be installed without giving them root access, this is a bad idea.

For Everything else

I'd use npm; but you really should just follow the install instruction for each modules following the directions on there website as they will be more aware of any issue or bug they have than anyone else

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

Set margins in a LinearLayout programmatically

Here is a little code to accomplish it:

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(30, 20, 30, 0);

Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);

include external .js file in node.js app

If you just want to test a library from the command line, you could do:

cat somelibrary.js mytestfile.js | node

Navigation bar show/hide

In Swift try this,

navigationController?.isNavigationBarHidden = true  //Hide
navigationController?.isNavigationBarHidden = false //Show

or

navigationController?.setNavigationBarHidden(true, animated: true) //Hide
navigationController?.setNavigationBarHidden(false, animated: true) //Show

how to get all markers on google-maps-v3

If you are using JQuery Google map plug-in then below code will work for you -

var markers = $('#map_canvas').gmap('get','markers');

.NET Events - What are object sender & EventArgs e?

sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.

EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.

When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).

How can I retrieve Id of inserted entity using Entity framework?

Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;

This will work.

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

How to center an iframe horizontally?

The simplest code to align the iframe element:

<div align="center"><iframe width="560" height="315" src="www.youtube.com" frameborder="1px"></iframe></div>

how to add a day to a date using jquery datepicker

The datepicker('setDate') sets the date in the datepicket not in the input.

You should add the date and set it in the input.

var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);

How can I get the current user's username in Bash?

Use the standard Unix/Linux/BSD/MacOS command logname to retrieve the logged in user. This ignores the environment as well as sudo, as these are unreliable reporters. It will always print the logged in user's name and then exit. This command has been around since about 1981.

My-Mac:~ devin$ logname
devin
My-Mac:~ devin$ sudo logname
Password:
devin
My-Mac:~ devin$ sudo su -
My-Mac:~ root# logname
devin
My-Mac:~ root# echo $USER
root

How to change file encoding in NetBeans?

Yes, you can change the encoding of a specific file (or see what it has) with this Encoding Support plugin. With this plugin you will be able to handle the different encodings of your files without problems.

Now it is in version 1.4.0 for NetBeans 8.2 and I use it in Windows 10 several time ago.

The operation is very simple, in the status line you can see the encoding of the open file, and from there you can define its new encoding.

Encoding Support running on Windows 10

JAVA_HOME and PATH are set but java -version still shows the old one

$JAVA_HOME/bin/java -version says 'Permission Denied'

If you cannot access or run code, it which be ignored if added to your path. You need to make it accessible and runnable or get a copy of your own.

Do an

ls -ld $JAVA_HOME $JAVA_HOME/bin $JAVA_HOME/bin/java

to see why you cannot access or run this program,.

How to implement Rate It feature in Android App

Use this library, It is simple and easy.. https://github.com/hotchemi/Android-Rate

by adding the dependency..

dependencies {
  compile 'com.github.hotchemi:android-rate:0.5.6'
}

How do you create an asynchronous method in C#?

If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:

public static Task<T> RunAsync<T>(Func<T> function)
{ 
    if (function == null) throw new ArgumentNullException(“function”); 
    var tcs = new TaskCompletionSource<T>(); 
    ThreadPool.QueueUserWorkItem(_ =>          
    { 
        try 
        {  
           T result = function(); 
           tcs.SetResult(result);  
        } 
        catch(Exception exc) { tcs.SetException(exc); } 
   }); 
   return tcs.Task; 
}

From here and here

To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.

I saw it's also used in the .NET source, e.g. WebClient.cs:

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource<string>(address);

        // Setup the callback event handler
        UploadStringCompletedEventHandler handler = null;
        handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
        this.UploadStringCompleted += handler;

        // Start the async operation.
        try { this.UploadStringAsync(address, method, data, tcs); }
        catch
        {
            this.UploadStringCompleted -= handler;
            throw;
        }

        // Return the task that represents the async operation
        return tcs.Task;
    }

Finally, I also found the following useful:

I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.

To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).

This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.

Introduction to Async/Await on ASP.NET

If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.

How do you echo a 4-digit Unicode character in Bash?

Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:

(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")

Output is the following.

Octal representation is following \0342\0230\0240
?

Java: JSON -> Protobuf & back conversion

Try JsonFormat.printer().print(MessageOrBuilder), it looks good for proto3. Yet, it is unclear how to convert the actual protobuf message (which is provided as the java package of my choice defined in the .proto file) to a com.google.protbuf.Message object.

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

Stretch background image css?

You can't stretch a background image (until CSS 3).

You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.

_x000D_
_x000D_
table {_x000D_
  width: 230px;_x000D_
}_x000D_
_x000D_
.style1 {_x000D_
  text-align: center;_x000D_
  height: 35px;_x000D_
}_x000D_
_x000D_
.bg {_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.bg img {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.bg .linkcontainer {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
  <tr>_x000D_
    <td class="style1">_x000D_
      <div class="bg">_x000D_
        <img src="http://placekitten.com/20/20" alt="" />_x000D_
        <div class="linkcontainer">_x000D_
          <a class="link" href="#">_x000D_
            <span>Answer</span>_x000D_
          </a>_x000D_
        </div>_x000D_
      </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

ERROR 1064 (42000): You have an error in your SQL syntax;

It is varchar and not var_char

CREATE DATABASE IF NOT EXISTS courses;

USE courses;

CREATE TABLE IF NOT EXISTS teachers(
    id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    addr VARCHAR(255) NOT NULL,
    phone INT NOT NULL
);

You should use a SQL tool to visualize possbile errors like MySQL Workbench.

.attr('checked','checked') does not work

Why not try IS?

$('selector').is(':checked') /* result true or false */

Look a FAQ: jQuery .is() enjoin us ;-)

Random Number Between 2 Double Numbers

If you need a random number in the range [double.MinValue; double.MaxValue]

// Because of:
double.MaxValue - double.MinValue == double.PositiveInfinity

// This will be equals to NaN or PositiveInfinity
random.NextDouble() * (double.MaxValue - double.MinValue)

Use instead:

public static class RandomExtensions
{
    public static double NextDoubleInMinMaxRange(this Random random)
    {
        var bytes = new byte[sizeof(double)];
        var value = default(double);
        while (true)
        {
            random.NextBytes(bytes);
            value = BitConverter.ToDouble(bytes, 0);
            if (!double.IsNaN(value) && !double.IsInfinity(value))
                return value;
        }
    }
}

Fastest way to check if a file exist using standard C++/C++11/C?

Although there are several ways to do this the most efficient solution to your problem would probably be to use one of the fstream's predefined method such as good(). With this method you can check whether the file you've specified exist or not.

fstream file("file_name.txt");

if (file.good()) 
{
    std::cout << "file is good." << endl;
}
else 
{
    std::cout << "file isnt good" << endl;
}

I hope you find this useful.

Which selector do I need to select an option by its text?

This will work in jQuery 1.6 (note colon before the opening bracket), but fails on the newer releases (1.10 at the time).

$('#mySelect option:[text=abc]")

How to change color of Toolbar back button in Android?

If you want system back color in white then you can use this code

<com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar_notification"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            app:contentInsetStartWithNavigation="0dp">

            <include layout="@layout/action_bar_notification" />
        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>

Note:- android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" is key

The paste is in your activity where you want to show back button on action bar

final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_notification);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);

How to remove leading zeros from alphanumeric text?

To go with thelost's Apache Commons answer: using guava-libraries (Google's general-purpose Java utility library which I would argue should now be on the classpath of any non-trivial Java project), this would use CharMatcher:

CharMatcher.is('0').trimLeadingFrom(inputString);

DOM element to corresponding vue.js component

Since in Vue 2.0, no solution seems available, a clean solution that I found is to create a vue-id attribute, and also set it on the template. Then on created and beforeDestroy lifecycle these instances are updated on the global object.

Basically:

created: function() {
    this._id = generateUid();
    globalRepo[this._id] = this;
},

beforeDestroy: function() {
    delete globalRepo[this._id]
},

data: function() {
    return {
        vueId: this._id
    }
}

How to send data to COM PORT using JAVA?

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

how to make password textbox value visible when hover an icon

Complete example below. I just love the copy/paste :)

HTML

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
              <div class="panel-body">
                  <form class="form-horizontal" method="" action="">

                     <div class="form-group">
                        <label class="col-md-4 control-label">Email</label>
                           <div class="col-md-6">
                               <input type="email" class="form-control" name="email" value="">
                           </div>
                     </div>
                     <div class="form-group">
                       <label class="col-md-4 control-label">Password</label>
                          <div class="col-md-6">
                              <input id="password-field" type="password" class="form-control" name="password" value="secret">
                              <span toggle="#password-field" class="fa fa-lg fa-eye field-icon toggle-password"></span>
                          </div>
                     </div>
                 </form>
              </div>
           </div>
      </div>
  </div>

CSS

.field-icon {
  float: right;
  margin-right: 8px;
  margin-top: -23px;
  position: relative;
  z-index: 2;
  cursor:pointer;
}

.container{
  padding-top:50px;
  margin: auto;
}

JS

$(".toggle-password").click(function() {
   $(this).toggleClass("fa-eye fa-eye-slash");
   var input = $($(this).attr("toggle"));
   if (input.attr("type") == "password") {
     input.attr("type", "text");
   } else {
     input.attr("type", "password");
   }
});

Try it here: https://codepen.io/anon/pen/ZoMQZP

PowerShell script to return members of multiple security groups

Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv

I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:

Get-Module -ListAvailable | Import-Module

How can I exclude a directory from Visual Studio Code "Explore" tab?

In newer versions of VS Code, you navigate to settings (Ctrl+,), and make sure to select Workspace Settings at the top right.

enter image description here

Then add a files.exclude option to specify patterns to exclude.

You can also add search.exclude if you only want to exclude a file from search results, and not from the folder explorer.

How to convert list of key-value tuples into dictionary?

l=[['A', 1], ['B', 2], ['C', 3]]
d={}
for i,j in l:
d.setdefault(i,j)
print(d)

How can I include all JavaScript files in a directory via JavaScript file?

What about using a server-side script to generate the script tag lines? Crudely, something like this (PHP) -

$handle = opendir("scripts/");

while (($file = readdir($handle))!== false) {
    echo '<script type="text/javascript" src="' . $file . '"></script>';
}

closedir($handle);

Round up value to nearest whole number in SQL UPDATE

Combine round and ceiling to get a proper round up.

select ceiling(round(984.375000), 0)) => 984

while

select round(984.375000, 0) => 984.000000

and

select ceil (984.375000) => 985

How to debug Spring Boot application with Eclipse?

Run below command where pom.xml is placed:

mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"

And start your remote java application with debugging option on port 5005

How to create windows service from java jar?

I've been experimenting with Apache Commons Daemon. It's supports windows (Procrun) and unix (Jsvc). Advanced Installer has a Java Service tutorial with an example project to download. If you get their javaservice.jar running as a windows service you can test it by using "telnet 4444". I used their example because my focus was on getting a java windows service running, not writing java.

Submit two forms with one button

You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.

Check if boolean is true?

The first example nearly always wins in my book:

if(foo)
{
}

It's shorter and more concise. Why add an extra check to something when it's absolutely not needed? Just wasting cycles...

I do agree, though, that sometimes the more verbose syntax makes things more readable (which is ultimately more important as long as performance is acceptable) in situations where variables are poorly named.

How to reduce the image file size using PIL

See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS filter when you do.

Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.

pandas DataFrame: replace nan values with average of columns

Although, the below code does the job, BUT its performance takes a big hit, as you deal with a DataFrame with # records 100k or more:

df.fillna(df.mean())

In my experience, one should replace NaN values (be it with Mean or Median), only where it is required, rather than applying fillna() all over the DataFrame.

I had a DataFrame with 20 variables, and only 4 of them required NaN values treatment (replacement). I tried the above code (Code 1), along with a slightly modified version of it (code 2), where i ran it selectively .i.e. only on variables which had a NaN value

#------------------------------------------------
#----(Code 1) Treatment on overall DataFrame-----

df.fillna(df.mean())

#------------------------------------------------
#----(Code 2) Selective Treatment----------------

for i in df.columns[df.isnull().any(axis=0)]:     #---Applying Only on variables with NaN values
    df[i].fillna(df[i].mean(),inplace=True)

#---df.isnull().any(axis=0) gives True/False flag (Boolean value series), 
#---which when applied on df.columns[], helps identify variables with NaN values

Below is the performance i observed, as i kept on increasing the # records in DataFrame

DataFrame with ~100k records

  • Code 1: 22.06 Seconds
  • Code 2: 0.03 Seconds

DataFrame with ~200k records

  • Code 1: 180.06 Seconds
  • Code 2: 0.06 Seconds

DataFrame with ~1.6 Million records

  • Code 1: code kept running endlessly
  • Code 2: 0.40 Seconds

DataFrame with ~13 Million records

  • Code 1: --did not even try, after seeing performance on 1.6 Mn records--
  • Code 2: 3.20 Seconds

Apologies for a long answer ! Hope this helps !

How to download a Nuget package without nuget.exe or Visual Studio extension?

Although building the URL or using tools is still possible, it is not needed anymore.

https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.

(at the bottom of the right column).


Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)

Example of EntityFramework's detail page

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

What is the best way to get all the divisors of a number?

If you only care about using list comprehensions and nothing else matters to you!

from itertools import combinations
from functools import reduce

def get_devisors(n):
    f = [f for f,e in list(factorGenerator(n)) for i in range(e)]
    fc = [x for l in range(len(f)+1) for x in combinations(f, l)]
    devisors = [1 if c==() else reduce((lambda x, y: x * y), c) for c in set(fc)]
    return sorted(devisors)

How to get the latest file in a folder?

A much faster method on windows (0.05s), call a bat script that does this:

get_latest.bat

@echo off
for /f %%i in ('dir \\directory\in\question /b/a-d/od/t:c') do set LAST=%%i
%LAST%

where \\directory\in\question is the directory you want to investigate.

get_latest.py

from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)

if it finds a file stdout is the path and stderr is None.

Use stdout.decode("utf-8").rstrip() to get the usable string representation of the file name.

How to set True as default value for BooleanField on Django?

I found the cleanest way of doing it is this.

Tested on Django 3.1.5

class MyForm(forms.Form):
    my_boolean = forms.BooleanField(required=False, initial=True)

I found the answer here

Using Java 8 to convert a list of objects into a string obtained from the toString() method

StringListName = ObjectListName.stream().map( m -> m.toString() ).collect( Collectors.toList() );

How does createOrReplaceTempView work in Spark?

CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.

first we read data in csv format and then convert to data frame and create a temp view

Reading data in csv format

val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")

printing the schema

data.printSchema

SchemaOfTable

data.createOrReplaceTempView("Data")

Now we can run sql queries on top the table view we just created

  %sql select Week as Date,Campaign Type,Engagements,Country from Data order     by Date asc

enter image description here

Select all from table with Laravel and Eloquent

using DB facade you can perform SQL queries

 public function index()
{
    return DB::table('table_name')->get();
}

What is a void pointer in C++?

A void* pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.

Ineligible Devices section appeared in Xcode 6.x.x

If you have a chance to run any project on the 'ineligible' device from other Mac with Xcode, try it and then reconnect the device to your Mac (without restarting Xcode/Mac).
For me, after doing that, the 'ineligible device' section disappears and my device returns to the normal status.
Hope it helps for someone.

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..

Both should be same ..Java version mismatched ..Check it

How to compare 2 dataTables

Try to make use of linq to Dataset

(from b in table1.AsEnumerable()  
    select new { id = b.Field<int>("id")}).Except(
         from a in table2.AsEnumerable() 
             select new {id = a.Field<int>("id")})

Check this article : Comparing DataSets using LINQ

Read properties file outside JAR file

I have an example of doing both by classpath or from external config with log4j2.properties

package org.mmartin.app1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.LogManager;


public class App1 {
    private static Logger logger=null; 
    private static final String LOG_PROPERTIES_FILE = "config/log4j2.properties";
    private static final String  CONFIG_PROPERTIES_FILE = "config/config.properties";

    private Properties properties= new Properties();

    public App1() {
        System.out.println("--Logger intialized with classpath properties file--");
        intializeLogger1();
        testLogging();
        System.out.println("--Logger intialized with external file--");
        intializeLogger2();
        testLogging();
    }




    public void readProperties()  {
        InputStream input = null;
        try {
            input = new FileInputStream(CONFIG_PROPERTIES_FILE);
            this.properties.load(input);
        } catch (IOException e) {
            logger.error("Unable to read the config.properties file.",e);
            System.exit(1);
        }
    }

    public void printProperties() {
        this.properties.list(System.out);
    }

    public void testLogging() {
        logger.debug("This is a debug message");
        logger.info("This is an info message");
        logger.warn("This is a warn message");
        logger.error("This is an error message");
        logger.fatal("This is a fatal message");
        logger.info("Logger's name: "+logger.getName());
    }


    private void intializeLogger1() {
        logger = LogManager.getLogger(App1.class);
    }
    private void intializeLogger2() {
        LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        File file = new File(LOG_PROPERTIES_FILE);
        // this will force a reconfiguration
        context.setConfigLocation(file.toURI());
        logger = context.getLogger(App1.class.getName());
    }

    public static void main(String[] args) {
        App1 app1 = new App1();
        app1.readProperties();
        app1.printProperties();
    }
}


--Logger intialized with classpath properties file--
[DEBUG] 2018-08-27 10:35:14.510 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.513 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.513 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.513 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.513 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.514 [main] App1 - Logger's name: org.mmartin.app1.App1
--Logger intialized with external file--
[DEBUG] 2018-08-27 10:35:14.524 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.525 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.525 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.525 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - Logger's name: org.mmartin.app1.App1
-- listing properties --
dbpassword=password
database=localhost
dbuser=user

How to center buttons in Twitter Bootstrap 3?

For Bootstrap 3

we divide the space with the columns, we use 8 small columns (col-xs-8), we leave 4 empty columns (col-xs-offset-4) and we apply the property (center-block)

<!--Footer-->
<div class="modal-footer">
  <div class="col-xs-8 col-xs-offset-4 center-block">
    <button type="submit" class="btn btn-primary">Enviar</button>
    <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
    </div>
</div>

For Bootstrap 4

We use Spacing, Bootstrap includes a wide range of abbreviated and padded response margin utility classes to modify the appearance of an element. The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

more info here: https://getbootstrap.com/docs/4.1/utilities/spacing/

<!--Footer-->
<div class="modal-footer">
  <button type="submit" class="btn btn-primary ml-auto">Enviar</button>
  <button type="button" class="btn btn-danger mr-auto" data-dismiss="modal">Cerrar</button>
</div>

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

This error is coming from the staticfile handler -- which by default doesn't filter any verbs, but probably can only deal with HEAD and GET.

And this is because no other handler stepped up to the plate and said they could handle DELETE.

Since you are using the WEBAPI, which because of routing doesn't have files and therefore extensions, the following additions need to be added to your web.config file:

<system.webserver>
    <httpProtocol>
        <handlers>
          ...
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

            <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

Obviously what is needed depends on classicmode vs integratedmode, and classicmode depends on bitness. In addition, the OPTIONS header has been added for CORS processing, but if you don't do CORS you don't need that.

FYI, your web.config is the local to the application (or application directory) version whose top level is applicationHost.config.

jQuery - hashchange event

I just ran into the same problem (lack of hashchange event in IE7). A workaround that suited for my purposes was to bind the click event of the hash-changing links.

<a class='hash-changer' href='#foo'>Foo</a>

<script type='text/javascript'>

if (("onhashchange" in window) && !($.browser.msie)) { 

    //modern browsers 
    $(window).bind('hashchange', function() {
        var hash = window.location.hash.replace(/^#/,'');
        //do whatever you need with the hash
    });

} else {

    //IE and browsers that don't support hashchange
    $('a.hash-changer').bind('click', function() {
        var hash = $(this).attr('href').replace(/^#/,'');
        //do whatever you need with the hash
    });

}

</script>

MS SQL Date Only Without Time

FWIW, I've been doing the same thing as you for years

CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam 

Seems to me like this is one of the better ways to strip off time in terms of flexibility, speed and readabily. (sorry). Some UDF functions as suggested can be useful, but UDFs can be slow with larger result sets.

How to Truncate a string in PHP to the word closest to a certain number of characters?

Here is my function based on @Cd-MaN's approach.

function shorten($string, $width) {
  if(strlen($string) > $width) {
    $string = wordwrap($string, $width);
    $string = substr($string, 0, strpos($string, "\n"));
  }

  return $string;
}

Spring boot: Unable to start embedded Tomcat servlet container

In my condition when I got an exception " Unable to start embedded Tomcat servlet container",

I opened the debug mode of spring boot by adding debug=true in the application.properties,

and then rerun the code ,and it told me that java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String

Thus, we know that probably I'm using a servlet API of lower version, and it conflicts with spring boot version.

I went to my pom.xml, and found one of my dependencies is using servlet2.5, and I excluded it.

Now it works. Hope it helps.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

Need to get a string after a "word" in a string in c#

Simpler way (if your only keyword is "code" ) may be:

string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();

How can I use Google's Roboto font on a website?

Use /fonts/ or /font/ before font type name in your CSS stylesheet. I face this error but after that its working fine.

@font-face {
    font-family: 'robotoregular';
    src: url('../fonts/Roboto-Regular-webfont.eot');
    src: url('../fonts/Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'),
         url('../fonts/Roboto-Regular-webfont.woff') format('woff'),
         url('../fonts/Roboto-Regular-webfont.ttf') format('truetype'),
         url('../fonts/Roboto-Regular-webfont.svg#robotoregular') format('svg');
    font-weight: normal;
    font-style: normal;

}

Android lollipop change navigation bar color

For people using Kotlin you can put this in your MainActivity.kt:

window.navigationBarColor = ContextCompat.getColor(this@MainActivity, R.color.yourColor)

With window being:

val window: Window = [email protected]

Or you can put this in your themes.xml or styles.xml (requires API level 21):

<item name='android:navigationBarColor'>@color/yourColor</item>

Can PHP cURL retrieve response headers AND body in a single request?

If you don't really need to use curl;

$body = file_get_contents('http://example.com');
var_export($http_response_header);
var_export($body);

Which outputs

array (
  0 => 'HTTP/1.0 200 OK',
  1 => 'Accept-Ranges: bytes',
  2 => 'Cache-Control: max-age=604800',
  3 => 'Content-Type: text/html',
  4 => 'Date: Tue, 24 Feb 2015 20:37:13 GMT',
  5 => 'Etag: "359670651"',
  6 => 'Expires: Tue, 03 Mar 2015 20:37:13 GMT',
  7 => 'Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT',
  8 => 'Server: ECS (cpm/F9D5)',
  9 => 'X-Cache: HIT',
  10 => 'x-ec-custom-error: 1',
  11 => 'Content-Length: 1270',
  12 => 'Connection: close',
)'<!doctype html>
<html>
<head>
    <title>Example Domain</title>...

See http://php.net/manual/en/reserved.variables.httpresponseheader.php

How to delete mysql database through shell command

In general, you can pass any query to mysql from shell with -e option.

mysql -u username -p -D dbname -e "DROP DATABASE dbname"

Error inflating class android.support.design.widget.NavigationView

Generic way of solving issues like Error inflating class X:

  1. check cause stack trace and there should be Resources$NotFoundException like this:
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f0b0066
    at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:190)
    at android.content.res.Resources.loadXmlResourceParser(Resources.java:2094)
    at android.content.res.Resources.getLayout(Resources.java:1111)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:424)
  1. Resource ID is actually exact integer from generated R.java file.
  2. Find 0x7f0b0066 which will point to the xml file which could not be inflated(found).
  3. In most cases that's because directory layout doesn't have this resource, but some layout-XXX has.
  4. And solution is to put resource into all required directories. Or just at least into layout.

Write a file in UTF-8 using FileWriter (Java)?

OK it's 2019 now, and from Java 11 you have a constructor with Charset:

FileWriter?(String fileName, Charset charset)

Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)

Fit image to table cell [Pure HTML]

if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:

<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

see the fiddle : http://jsfiddle.net/Lk2Rh/27/

but still it better to handling this with CSS, i suggest you that.

  • I hope this help.

Tips for using Vim as a Java IDE?

I know this is quite a few years later but here are some interesting plugins. I have not tried either of these yet so YMMV.

https://github.com/mikelue/vim-maven-plugin

https://github.com/vim-scripts/maven-ide

EDIT: Oh an BTW, i've tried eclim off and on, but the reason I like vim is its lightness. Executing eclipse even on headless mode is just too much mental lifting for me.

EDIT2: I've been using playframework lately and this will probably work with maven builds too:

  • For compiling, you can configure VIM's make to run maven or in my case, run a build script, tee that to a file.

    autocmd Filetype java setl makeprg=play_compile
    autocmd Filetype java setl efm=%A\ %#[error]\ %f:%l:\ %m,%-Z\ %#[error]\ %p^,%-C%.%#
    

"play_compile" is just a compile script. It uses SBT so Maven should work just fine here. Even direct javac will work. This way, you can use VIM"s quickfix buffer (:cnext, :clist: cprev, etc).

  • For jumping around the classes, I use ctrl-p. Its beautiful. Use it. Faster than eclipse in jumping around files.

  • For jumping around methods, I use tagsearch with exuberant c-tags. Jump into method declarations by using ctrl-]. Go back using Ctrl-o. Doesnt work as good as eclipse, but it works good enough.

  • I use supertab for code completion. Javacomplete is pretty slow, so I stick with omni-complete. Again, not as accurate as eclipse, but its fast and works good enough for me.

Running python script inside ipython

The %run magic has a parameter file_finder that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending ".py" if necessary.

There doesn't seem to be a way to specify which file finder to use from the %run magic, but there's nothing to stop you from defining your own magic command that calls into %run with an appropriate file finder.

As a very nasty hack, you could override the default file_finder with your own:

IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder

To be honest, at the rate the IPython API is changing that's as likely to continue to work as defining your own magic is.

Python: how can I check whether an object is of type datetime.date?

If your existing code is already relying on from datetime import datetime, you can also simply also import date

from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)

How to force Selenium WebDriver to click on element which is not currently visible?

You can't force accessing/changing element to which the user normally doesn't have access, as Selenium is designed to imitate user interaction.

If this error happens, check if:

  • element is visible in your viewport, try to maximize the current window that webdriver is using (e.g. maximize() in node.js, maximize_window() in Python),
  • your element is not appearing twice (under the same selector), and you're selecting the wrong one,
  • if your element is hidden, then consider making it visible,
  • if you'd like to access/change value of hidden element despite of the limitation, then use Javascript for that (e.g. executeScript() in node.js, execute_script() in Python).

Resizing a button

You should not use "width" and "height" attributes directly, use the style attribute like style="some css here" if you want to use inline styling:

<div class="button" style="width:60px;height:30px;">This is a button</div>

Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:

_x000D_
_x000D_
   .button {_x000D_
        background-color: #000000;_x000D_
        color: #FFFFFF;_x000D_
        padding: 10px;_x000D_
        border-radius: 10px;_x000D_
        -moz-border-radius: 10px;_x000D_
        -webkit-border-radius: 10px;_x000D_
        margin:10px_x000D_
    }_x000D_
    _x000D_
    .small-btn {_x000D_
        width: 50px;_x000D_
        height: 25px;_x000D_
    }_x000D_
    _x000D_
    .medium-btn {_x000D_
        width: 70px;_x000D_
        height: 30px;_x000D_
    }_x000D_
    _x000D_
    .big-btn {_x000D_
        width: 90px;_x000D_
        height: 40px;_x000D_
    }
_x000D_
    <div class="button big-btn">This is a big button</div>_x000D_
    <div class="button medium-btn">This is a medium button</div>_x000D_
    <div class="button small-btn">This is a small button</div>_x000D_
 
_x000D_
_x000D_
_x000D_

jsFiddle example

Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

SELECT *
FROM table
WHERE myDtate BETWEEN now()
    , DATE_SUB(NOW()
    , INTERVAL 1 MONTH)

How do I delete multiple rows with different IDs?

Delete from BA_CITY_MASTER where CITY_NAME in (select CITY_NAME from BA_CITY_MASTER group by CITY_NAME having count(CITY_NAME)>1);

How do you clear Apache Maven's cache?

As some answers have pointed out, sometimes you really want to delete the local repository entirely, for example, there might be some artifacts that can't be purged as they are not anymore referenced by the pom.

If you want to have this deletion embedded in a maven phase, as for example clean you can use the maven-clean-plugin and access the repository through the settings, for example:

 <plugin>
    <inherited>false</inherited>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <phase>clean</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <tasks>
                    <echo>Base clean is attached to deleting local maven cache</echo>
                    <echo>${settings.localRepository}</echo>
                </tasks>
            </configuration>
        </execution>
    </executions>
</plugin>

<plugin>
    <inherited>false</inherited>
    <artifactId>maven-clean-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <filesets>
            <fileset>
                <directory>${settings.localRepository}</directory>
            </fileset>
        </filesets>
    </configuration>
</plugin>

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
    {
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
        {
            strValue = _tags["101"];
            Console.WriteLine(strValue);
        }

        if (_tags.TryGetValue("101", out strValue))
        {
            Console.WriteLine(strValue);
        }
    }
}

Why doesn't the height of a container element increase if it contains floated elements?

You confuse how browsers renders the elements when there are floating elements. If one block element is floating (your inner div in your case), other block elements will ignore it because browser removes floating elements from the normal flow of the web page. Then, because the floated div has been removed from the normal flow, the outside div is filled in, like the inner div isn't there. However, inline elements (images, links, text, blackquotes) will respect the boundaries of the floating element. If you introduce text in the outside div, the text will place arround de inner div.

In other words, block elements (headers, paragraphs, divs, etc) ignore floating elements and fill in, and inline elements (images, links, text, etc) respect boundaries of floating elements.

An fiddle example here

<body>
    <div style="float:right; background-color:blue;width:200px;min-height:400px;margin-right:20px">
           floating element
    </div>
    <h1 style="background-color:red;"> this is a big header</h1>
    <p style="background-color:green"> this is a parragraph with text and a big image. The text places arrounds the floating element. Because of the image is wider than space between paragrah and floating element places down the floating element. Try to make wider the viewport and see what happens :D
        <img src="http://2.bp.blogspot.com/_nKxzQGcCLtQ/TBYPAJ6xM4I/AAAAAAAAAC8/lG6XemOXosU/s1600/css.png">
     </p>

How to set a value to a file input in HTML?

You cannot, due to security reasons.

Imagine:

<form name="foo" method="post" enctype="multipart/form-data">
    <input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>

You don't want the websites you visit to be able to do this, do you? =)

Setting default values to null fields when mapping with Jackson

Only one proposed solution keeps the default-value when some-value:null was set explicitly (POJO readability is lost there and it's clumsy)

Here's how one can keep the default-value and never set it to null

@JsonProperty("some-value")
public String someValue = "default-value";

@JsonSetter("some-value")
public void setSomeValue(String s) {
    if (s != null) { 
        someValue = s; 
    }
}

How to check user is "logged in"?

I managed to find the correct one. It is below.

bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated

EDIT

The credit of this edit goes to @Gianpiero Caretti who suggested this in comment.

bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated

How can I add a new column and data to a datatable that already contains data?

Only you want to set default value parameter. This calling third overloading method.

dt.Columns.Add("MyRow", type(System.Int32),0);

is inaccessible due to its protection level

You need to use the public properties from Main, and not try to directly change the internal variables.

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to access remote server with local phpMyAdmin client?

It is certainly possible to access a remote MySQL server from a local instance of phpMyAdmin, as the other answers have pointed out. And for that to work, you have to configure the remote server's MySQL server to accept remote connections, and allow traffic through the firewall for the port number that MySQL is listening to. I prefer a slightly different solution involving SSH Tunnelling.

The following command will set up an SSH tunnel which will forward all requests made to port 3307 from your local machine to port 3306 on the remote machine:

ssh -NL 3307:localhost:3306 root@REMOTE_HOST

When prompted, you should enter the password for the root user on the remote machine. This will open the tunnel. If you want to run this in the background, you'll need to add the -f argument, and set up Passwordless SSH between your local machine and the remote machine.

After you've got the SSH tunnel working, you can add the remote server to the servers list in your local phpMyAdmin by modifying the /etc/phpmyadmin/config.inc.php file. Add the following to the end of the file:

$cfg['Servers'][$i]['verbose']       = 'Remote Server 1'; // Change this to whatever you like.
$cfg['Servers'][$i]['host']          = '127.0.0.1';
$cfg['Servers'][$i]['port']          = '3307';
$cfg['Servers'][$i]['connect_type']  = 'tcp';
$cfg['Servers'][$i]['extension']     = 'mysqli';
$cfg['Servers'][$i]['compress']      = FALSE;
$cfg['Servers'][$i]['auth_type']     = 'cookie';
$i++;

I wrote a more in-depth blog post about exactly this, in case you need additional help.

Compare objects in Angular

I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

Example:

var obj1 = {
  $key0: "A",
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  $key0: "B"
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)

Adding data attribute to DOM

Using .data() will only add data to the jQuery object for that element. In order to add the information to the element itself you need to access that element using jQuery's .attr or native .setAttribute

$('div').attr('data-info', 1);
$('div')[0].setAttribute('data-info',1);

In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ($('div[data-info="1"]')), but when you use .data() you cannot. In order to select based on the .data() setting, you would need to use jQuery's filter function.

jsFiddle Demo

_x000D_
_x000D_
$('div').data('info', 1);_x000D_
//alert($('div').data('info'));//1_x000D_
_x000D_
$('div').filter(function(){_x000D_
   return $(this).data('info') == 1; _x000D_
}).text('222');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>1</div>
_x000D_
_x000D_
_x000D_

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Replace comma with newline in sed on MacOS?

This works on MacOS Mountain Lion (10.8), Solaris 10 (SunOS 5.10) and RHE Linux (Red Hat Enterprise Linux Server release 5.3, Tikanga)...

$ sed 's/{pattern}/\^J/g' foo.txt > foo2.txt

... where the ^J is done by doing ctrl+v+j. Do mind the \ before the ^J.

PS, I know the sed in RHEL is GNU, the MacOS sed is FreeBSD based, and although I'm not sure about the Solaris sed, I believe this will work pretty much with any sed. YMMV tho'...

Clear text input on click with AngularJS

Try this,

 this.searchAll = element(by.xpath('path here'));
 this.searchAll.sendKeys('');

How do I find the difference between two values without knowing which is larger?

If you don't need a signed integer, this is an alternative that uses a slightly different approach, is easy to read and doesn't require an import:

def distance(a, b):
  if a > 0 and b > 0:
    return max(a, b) - min(a, b)
  elif a < 0 and b < 0:
    return abs(a - b)
  elif a == b:
    return 0
  return abs(a - 0) + abs(b - 0)

Attach Authorization header for all axios requests

The point is to set the token on the interceptors for each request

import axios from "axios";
    
const httpClient = axios.create({
    baseURL: "http://youradress",
    // baseURL: process.env.APP_API_BASE_URL,
});

httpClient.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
});

How do you post to an iframe?

Depends what you mean by "post data". You can use the HTML target="" attribute on a <form /> tag, so it could be as simple as:

<form action="do_stuff.aspx" method="post" target="my_iframe">
  <input type="submit" value="Do Stuff!">
</form>

<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>

If that's not it, or you're after something more complex, please edit your question to include more detail.

There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.

I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.

default.asp

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <form action="do_stuff.asp" method="post" target="my_frame">
    <input type="text" name="someText" value="Some Text">
    <input type="submit">
  </form>
  <iframe name="my_frame" src="do_stuff.asp">
  </iframe>
  </body>
</html>

do_stuff.asp

<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <% if (Request.Form.Count) { %>
  You typed: <%=Request.Form("someText").Item%>
  <% } else { %>
  (not submitted)
  <% } %>
  </body>
</html>

I would be very interested to hear of any browser that doesn't run these examples correctly.

How do I check if a list is empty?

I prefer it explicitly:

if len(li) == 0:
    print('the list is empty')

This way it's 100% clear that li is a sequence (list) and we want to test its size. My problem with if not li: ... is that it gives the false impression that li is a boolean variable.

Android: How to detect double-tap?

Double-tap and Single-tap

Double-tap only

It is quite easy to detect a double tap on a view by using SimpleOnGestureListener (as demonstrated in Hannes Niederhausen's answer).

private class GestureListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        return true;
    }
}

I can't see a big advantage to re-inventing the logic for this (like bughi's answer).

Double-tap and Single-tap with delay

You can also use the SimpleOnGestureListener to differentiate a single-tap and a double-tap as mutually exclusive events. To do that you just override onSingleTapConfirmed. This will delay running the single-tap code until the system is certain that the user hasn't double-tapped (ie, the delay > ViewConfiguration.getDoubleTapTimeout()). There is definately no reason to re-invent all the logic for that (as is done in this, this and other answers).

private class GestureListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        return true;
    }
}

Double-tap and Single-tap with no delay

The potential problem with onSingleTapConfirmed is the delay. Sometimes a noticeable delay is not acceptable. In that case you can replace onSingleTapConfirmed with onSingleTapUp.

private class GestureListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        return true;
    }
}

You need to realize, though, that both onSingleTapUp and onDoubleTap will be called if there is a double-tap. (This is essentially what bughi's answer does and what some of the commenters were complaining about.) You either need to use the delay or call both methods. It's not possible have a single-tap with no delay and at the same time know whether the user is going to tap again.

If the single-tap delay is not acceptable for you then you have a couple options:

  • Accept that both onSingleTapUp and onDoubleTap will be called for a double-tap. Just divide up your logic appropriately so that it doesn't matter. This is essentially what I did when I implemented a double-tap for caps-lock on a custom keyboard.
  • Don't use a double-tap. It's not an intuitive UI action for most things. As Dave Webb suggests, a long press is probably better. You can also implement that with the SimpleOnGestureListener:

    private class GestureListener extends GestureDetector.SimpleOnGestureListener {
    
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }
    
        @Override
        public void onLongPress(MotionEvent e) {
    
        }
    }
    

How to write lists inside a markdown table?

Yes, you can merge them using HTML. When I create tables in .md files from Github, I always like to use HTML code instead of markdown.

Github Flavored Markdown supports basic HTML in .md file. So this would be the answer:

Markdown mixed with HTML:

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|

Or pure HTML:

<table>
  <tbody>
    <tr>
      <th>Tables</th>
      <th align="center">Are</th>
      <th align="right">Cool</th>
    </tr>
    <tr>
      <td>col 3 is</td>
      <td align="center">right-aligned</td>
      <td align="right">$1600</td>
    </tr>
    <tr>
      <td>col 2 is</td>
      <td align="center">centered</td>
      <td align="right">$12</td>
    </tr>
    <tr>
      <td>zebra stripes</td>
      <td align="center">are neat</td>
      <td align="right">$1</td>
    </tr>
    <tr>
      <td>
        <ul>
          <li>item1</li>
          <li>item2</li>
        </ul>
      </td>
      <td align="center">See the list</td>
      <td align="right">from the first column</td>
    </tr>
  </tbody>
</table>

This is how it looks on Github:

BackgroundWorker vs background Thread

You know, sometimes it's just easier to work with a BackgroundWorker regardless of if you're using Windows Forms, WPF or whatever technology. The neat part about these guys is you get threading without having to worry too much about where you're thread is executing, which is great for simple tasks.

Before using a BackgroundWorker consider first if you wish to cancel a thread (closing app, user cancellation) then you need to decide if your thread should check for cancellations or if it should be thrust upon the execution itself.

BackgroundWorker.CancelAsync() will set CancellationPending to true but won't do anything more, it's then the threads responsibility to continually check this, keep in mind also that you could end up with a race condition in this approach where your user cancelled, but the thread completed prior to testing for CancellationPending.

Thread.Abort() on the other hand will throw an exception within the thread execution which enforces cancellation of that thread, you must be careful about what might be dangerous if this exception was suddenly raised within the execution though.

Threading needs very careful consideration no matter what the task, for some further reading:

Parallel Programming in the .NET Framework Managed Threading Best Practices

How to use a App.config file in WPF applications?

You can change configuration file schema back to DotNetConfig.xsd via properties of the app.config file. To find destination of needed schema, you can search it by name or create a WinForms application, add to project the configuration file and in it's properties, you'll find full path to file.

PHP preg_match - only allow alphanumeric strings and - _ characters

Why to use regex? PHP has some built in functionality to do that

<?php
    $valid_symbols = array('-', '_');
    $string1 = "This is a string*";
    $string2 = "this_is-a-string";

    if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
        echo "String 1 not acceptable acceptable";
    }
?>

preg_match('/\s/',$username) will check for blank space

!ctype_alnum(str_replace($valid_symbols, '', $string1)) will check for valid_symbols

Returning string from C function

Easier still: return a pointer to a string that's been malloc'd with strdup.

#include <ncurses.h>

char * getStr(int length)
{   
    char word[length];

    for (int i = 0; i < length; i++)
    {
        word[i] = getch();
    }

    word[i] = '\0';
    return strdup(&word[0]);
}

int main()
{
    char wordd[10];
    initscr();
    *wordd = getStr(10);
    printw("The string is:\n");
    printw("%s\n",*wordd);
    getch();
    endwin();
    return 0;
}

Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

Create Directory When Writing To File In Node.js

first taking the full path including directory and extracting the directory

//Just for the sake of example
cwd=process.cwd()
filendir=path.resolve(cwd,'_site/assets/text','node.txt')

// Extracting directory name
mkdir=path.dirname(filendir)

Now make the directory, add option recursive:true as stated by @David Weldon

fs.mkdirSync(mkdir,{recursive:true})

Then make the file

data='Some random text'
fs.writeFileSync(filendir,data)

How to declare Return Types for Functions in TypeScript

You are correct - here is a fully working example - you'll see that var result is implicitly a string because the return type is specified on the greet() function. Change the type to number and you'll get warnings.

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() : string {
        return "Hello, " + this.greeting;
    }
} 

var greeter = new Greeter("Hi");
var result = greeter.greet();

Here is the number example - you'll see red squiggles in the playground editor if you try this:

greet() : number {
    return "Hello, " + this.greeting;
}

A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

How do I calculate someone's age based on a DateTime type birthday?

Here is a very simple and easy to follow example.

private int CalculateAge()
{
//get birthdate
   DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
   int byear = dtBirth.Year;
   int bmonth = dtBirth.Month;
   int bday = dtBirth.Day;
   DateTime dtToday = DateTime.Now;
   int tYear = dtToday.Year;
   int tmonth = dtToday.Month;
   int tday = dtToday.Day;
   int age = tYear - byear;
   if (bmonth < tmonth)
       age--;
   else if (bmonth == tmonth && bday>tday)
   {
       age--;
   }
return age;
}

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

CSS container div not getting height

Try inserting this clearing div before the last </div>

<div style="clear: both; line-height: 0;">&nbsp;</div>

How do we count rows using older versions of Hibernate (~2009)?

Long count = (Long) session.createQuery("select count(*) from  Book").uniqueResult();

How can I pass a file argument to my bash script using a Terminal command in Linux?

It'll be easier (and more "proper", see below) if you just run your script as

myprogram /path/to/file

Then you can access the path within the script as $1 (for argument #1, similarly $2 is argument #2, etc.)

file="$1"
externalprogram "$file" [other parameters]

Or just

externalprogram "$1" [otherparameters]

If you want to extract the path from something like --file=/path/to/file, that's usually done with the getopts shell function. But that's more complicated than just referencing $1, and besides, switches like --file= are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.

Is there anything like .NET's NotImplementedException in Java?

No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.

Please refer to this discussion about why it's even in .NET.

I guess UnsupportedOperationException comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there? Interface segregation or Liskov substitution issues maybe?

If it's work in progress I'd go for ToBeImplementedException, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.

Using FileSystemWatcher to monitor a directory

You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.

You can wait for a file to be ready by using this function in a loop.

What is the function __construct used for?

Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();

Using pg_dump to only get insert statements from one table within database

just in case you are using a remote access and want to dump all database data, you can use:

pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump

it will create a dump with all database data and use

pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump

to insert the same data in your data base considering you have the same structure

Compress images on client side before uploading

I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html

The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...

However, I’m not sure about using canvas to compress images, but you can certainly resize them.

How to execute an .SQL script file using c#

This works for me:

public void updatedatabase()
{

    SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
    try
    {

        conn.Open();

        string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));

        // split script on GO command
        IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        foreach (string commandString in commandStrings)
        {
            if (commandString.Trim() != "")
            {
                new SqlCommand(commandString, conn).ExecuteNonQuery();
            }
        }
        lblmsg.Text = "Database updated successfully.";

    }
    catch (SqlException er)
    {
        lblmsg.Text = er.Message;
        lblmsg.ForeColor = Color.Red;
    }
    finally
    {
        conn.Close();
    }
}

How do I rename both a Git local and remote branch name?

This can be done even without renaming the local branch in three simple steps:

  1. Go to your repository in GitHub
  2. Create a new branch from the old branch which you want to rename
  3. Delete the old branch

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How can I interrupt a running code in R with a keyboard command?

Control-C works, although depending on what the process is doing it might not take right away.

If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.

Where is the Java SDK folder in my computer? Ubuntu 12.04

WAY-1 : Updated for the shortest and easy way

Below command will give you the path, But it will only work if java command is working in other words if java path is configured.

readlink -f $(which java) 

Read more at Where can I find the Java SDK in Linux?


WAY-2 (Better than WAY-1) : Below answer is still working and try it if above command is not working for you.

You need to dig into symbolic links. Below is steps to get Java directory

Step 1:

$ whereis java
java: /usr/bin/java /etc/java /usr/share/java

That tells the command java resides in /usr/bin/java.

Dig again:

Step 2:

$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java

So, now we know that /usr/bin/java is actually a symbolic link to /etc/alternatives/java.

Dig deeper using the same method above:

Step 3:

$ ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java

So, thats the actual location of java: /usr/local/jre.....

You could still dig deeper to find other symbolic links.


Reference : where is java's home dir?

How do I reference a cell within excel named range?

Add a column to the left so that B10 to B20 is your named range Age.

Set A10 to A20 so that A10 = 1, A11= 2,... A20 = 11 and give the range A10 to A20 a name e.g. AgeIndex.

The 5th element can be then found by using an array formula:

=sum( Age * (1 * (AgeIndex = 5) )

As it's an array formula you'll need to press Ctrl + Shift + Return to make it work and not just return. Doing that, the formula will be turned into an array formula:

{=sum( Age * (1 * (AgeIndex = 5) )}

Global npm install location on windows?

Just press windows button and type %APPDATA% and type enter.

Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.

mysql SELECT IF statement with OR

Presumably this would work:

IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.

For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:

sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now   # to exit the container

Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();

This is probably a more "correct" way of getting it.

How can I generate a tsconfig.json file?

$ npm run tsc -- --init
This worked for the below package.json

  "devDependencies": {
    "@types/jasmine": "^3.6.2",
    "@types/node": "^14.14.19",
    "jasmine": "^3.6.3",
    "protractor": "^7.0.0",
    "typescript": "^4.1.3"
  },

C++ passing an array pointer as a function argument

You're over-complicating it - it just needs to be:

void generateArray(int *a, int si)
{
    for (int j = 0; j < si; j++)
        a[j] = rand() % 9;
}

int main()
{
    const int size=5;
    int a[size];

    generateArray(a, size);

    return 0;
}

When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.

How to override application.properties during production in Spring-Boot?

The spring configuration precedence is as follows.

  1. ServletConfig init Parameter
  2. ServletContext init parameter
  3. JNDI attributes
  4. System.getProperties()

So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.

What is the Linux equivalent to DOS pause?

read without any parameters will only continue if you press enter. The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.

Difference between HashMap and Map in Java..?

HashMap is an implementation of Map. Map is just an interface for any type of map.

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

Get cursor position (in characters) within a text Input field

_x000D_
_x000D_
const inpT = document.getElementById("text-box");_x000D_
const inpC = document.getElementById("text-box-content");_x000D_
// swch gets  inputs ._x000D_
var swch;_x000D_
// swch  if corsur is active in inputs defaulte is false ._x000D_
var isSelect = false;_x000D_
_x000D_
var crnselect;_x000D_
// on focus_x000D_
function setSwitch(e) {_x000D_
  swch = e;_x000D_
  isSelect = true;_x000D_
  console.log("set Switch: " + isSelect);_x000D_
}_x000D_
// on click ev_x000D_
function setEmoji() {_x000D_
  if (isSelect) {_x000D_
    console.log("emoji added :)");_x000D_
    swch.value += ":)";_x000D_
    swch.setSelectionRange(2,2 );_x000D_
    isSelect = true;_x000D_
  }_x000D_
_x000D_
}_x000D_
// on not selected on input . _x000D_
function onout() {_x000D_
  // ??????  ??? ?? ?? _x000D_
  crnselect = inpC.selectionStart;_x000D_
  _x000D_
  // return input select not active after 200 ms ._x000D_
  var len = swch.value.length;_x000D_
  setTimeout(() => {_x000D_
   (len == swch.value.length)? isSelect = false:isSelect = true;_x000D_
  }, 200);_x000D_
}
_x000D_
<h1> Try it !</h1>_x000D_
    _x000D_
  <input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">_x000D_
  <input type="text" onfocus = "setSwitch(this)"  onfocusout = "onout()"  id="text-box-content" size="20" value="content">_x000D_
<button onclick="setEmoji()">emogi :) </button>
_x000D_
_x000D_
_x000D_

Exporting PDF with jspdf not rendering CSS

To remove black background only add background-color: white; to the style of

How can I create a simple message box in Python?

ctype module with threading

i was using the tkinter messagebox but it would crash my code. i didn't want to find out why so i used the ctypes module instead.

for example:

import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

i got that code from Arkelis


i liked that it didn't crash the code so i worked on it and added a threading so the code after would run.

example for my code

import ctypes
import threading


def MessageboxThread(buttonstyle, title, text, icon):
    threading.Thread(
        target=lambda: ctypes.windll.user32.MessageBoxW(buttonstyle, text, title, icon)
    ).start()

messagebox(0, "Your title", "Your text", 1)

for button styles and icon numbers:

## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue

## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle

What is the difference between association, aggregation and composition?

I know this question is tagged as C# but the concepts are pretty generic questions like this redirect here. So I am going to provide my point of view here (a bit biased from java point of view where I am more comfortable).

When we think of Object-oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words the object of one class may use services/methods provided by the object of another class. This kind of relationship is termed as association..

Aggregation and Composition are subsets of association meaning they are specific cases of association.

enter image description here

  • In both aggregation and composition object of one class "owns" object of another class.
  • But there is a subtle difference. In Composition the object of class that is owned by the object of it's owning class cannot live on it's own(Also called "death relationship"). It will always live as a part of it's owning object where as in Aggregation the dependent object is standalone and can exist even if the object of owning class is dead.
  • So in composition if owning object is garbage collected the owned object will also be which is not the case in aggregation.

Confused?

Composition Example : Consider the example of a Car and an engine that is very specific to that car (meaning it cannot be used in any other car). This type of relationship between Car and SpecificEngine class is called Composition. An object of the Car class cannot exist without an object of SpecificEngine class and object of SpecificEngine has no significance without Car class. To put in simple words Car class solely "owns" the SpecificEngine class.

Aggregation Example : Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning the Car object owns the Wheel object but we cannot say the Wheel object has no significance without the Car Object. It can very well be used in a Bike, Truck or different Cars Object.

Summing it up -

To sum it up association is a very generic term used to represent when a class uses the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.

More details here. I am the author of http://opensourceforgeeks.blogspot.in and have added a link above to the relevant post for more context.

Change background color of edittext in android

You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem

Using holoeverywhere

just change some of the 9patch resources to customize the edittext look and feel.

What are the dark corners of Vim your mom never told you about?

:sp %:h - directory listing / file-chooser using the current file's directory

(belongs as a comment under rampion's cd tip, but I don't have commenting-rights yet)

ctypes - Beginner

The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.

Passing and returning an integer

The C++ code for a function which takes an integer and adds one to the returned value,

extern "C" int add_one(int i)
{
    return i+1;
}

Saved as file test.cpp, note the required extern "C" (this can be removed for C code). This is compiled using g++, with arguments similar to Chinmay Kanchi answer,

g++ -shared -o testlib.so -fPIC test.cpp

The Python code uses load_library from the numpy.ctypeslib assuming the path to the shared library in the same directory as the Python script,

import numpy.ctypeslib as ctl
import ctypes

libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)

py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)

This prints 6 as expected.

Passing and printing an array

You can also pass arrays as follows, for a C code to print the element of an array,

extern "C" void print_array(double* array, int N)
{
    for (int i=0; i<N; i++) 
        cout << i << " " << array[i] << endl;
}

which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,

import numpy as np

py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64, 
                                         flags='aligned, c_contiguous'), 
                           ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)

where we specify the array, the first argument to print_array, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,

1.4
2.6
3.0

CodeIgniter - return only one row?

Change only in two line and you are getting actually what you want.

$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;

try it.

Visual Studio Code compile on save

tried the above methods but mine stopped auto-compile when it felt like it, due to maximum files to watch have passed the limit.

run cat /proc/sys/fs/inotify/max_user_watches command .

if it's showing fewer files count including node_modules then open the file /etc/sysctl.conf in root privilege and append

fs.inotify.max_user_watches=524288 into the file and save

run again the cat command to see the result. It will work! hopefully!

using favicon with css

You don't need to - if the favicon is place in the root at favicon.ico, browsers will automatically pick it up.

If you don't see it working, clear your cache etc, it does work without the markup. You only need to use the code if you want to call it something else, or put it on a CDN for instance.

operator << must take exactly one argument

I ran into this problem with templated classes. Here's a more general solution I had to use:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // Friend means operator<< can use private variables
    // It needs to be declared as a template, but T is taken
    template <class U>
    friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}

// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
  obj.toString(os);
  return os;
}

Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.

The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(

Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.

This works too:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // For some reason this requires using T, and not U as above
    friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
    {
        obj.toString(os);
        return os;
    }
}

I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.

C++ Best way to get integer division and remainder

You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.

Create patch or diff file from git repository and apply it to another different git repository

You can just use git diff to produce a unified diff suitable for git apply:

git diff tag1..tag2 > mypatch.patch

You can then apply the resulting patch with:

git apply mypatch.patch

PHP multiline string with PHP

To do that, you must remove all ' charachters in your string or use an escape character. Like:

<?php
    echo '<?php
              echo \'hello world\';
          ?>';
?>

how to pass parameter from @Url.Action to controller function

This way to pass value from Controller to View:

ViewData["ID"] = _obj.ID;

Here is the way to pass value from View to Controller back:

<input type="button" title="Next" value="Next Step" onclick="location.href='@Url.Action("CreatePerson", "Person", new { ID = ViewData["ID"] })'" />

Play audio from a stream using C#

I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.

I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.

Can you target an elements parent element using event.target?

var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ;  i<_RemoveBtn.length ; i++){
    _RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
    console.log(event.currentTarget.parentNode);    
}

Fixed digits after decimal with f-strings

a = 10.1234

print(f"{a:0.2f}")

in 0.2f:

  • 0 is telling python to put no limit on the total number of digits to display
  • .2 is saying that we want to take only 2 digits after decimal (the result will be same as a round() function)
  • f is telling that it's a float number. If you forget f then it will just print 1 less digit after the decimal. In this case, it will be only 1 digit after the decimal.

A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606

How to declare a variable in a PostgreSQL query

In DBeaver you can use parameters in queries just like you can from code, so this will work:

SELECT *
FROM somewhere
WHERE something = :myvar

When you run the query DBeaver will ask you for the value for :myvar and run the query.

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

Where does flask look for image files?

It took me a while to figure this out too. url_for in Flask looks for endpoints that you specified in the routes.py script.

So if you have a decorator in your routes.py file like @blah.route('/folder.subfolder') then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }} . The 'folder.subfolder' argument sends it to a Flask endpoint it recognizes.

However let us say that you stored your image file, some_image.jpg, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py, your route decorator looks like @blah.routes('/folder'). You then have to ask for your image file this way: {{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}

I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

Replace CRLF using powershell

This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:

  • Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).

  • Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.

  • A future version of PowerShell Core will have a
    Convert-TextFile cmdlet with a -LineEnding parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.

In PSv5+, PowerShell-native solutions are now possible, because Set-Content now supports the -NoNewline switch, which prevents undesired appending of a platform-native newline[1] :

# Convert CRLFs to LFs only.
# Note:
#  * (...) around Get-Content ensures that $file is read *in full*
#    up front, so that it is possible to write back the transformed content
#    to the same file.
#  * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
#     expect.
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file

The above relies on Get-Content's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.

Caveats:

  • You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding; without -Encoding:

    • In Windows PowerShell, you'll get "ANSI" encoding, your system's single-byte, 8-bit legacy encoding, such as Windows-1252 on US-English systems.
    • In PowerShell Core, you'll get UTF-8 encoding without a BOM.
  • The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.

  • There's a risk of file corruption, if the process of writing back to the input file gets interrupted.


[1] In fact, if there are multiple strings to write, -NoNewline also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.

Android Studio: Add jar as library?

Put the .jar files in libs folder of the Android project.

Then add this line of code in the app's gradle file:

    compile fileTree(dir: 'libs', include: ['*.jar'])

For Android gradle plugin 3.0 and later, it is better to use this instead:

    implementation fileTree(dir: 'libs', include: ['*.jar'])

npm - EPERM: operation not permitted on Windows

I solved the problem by changing windows user access for the project folder:

Here is a screenshot: http://prntscr.com/djdn0g

enter image description here

How do I apply a diff patch on Windows?

It appears that TortoiseSVN (TortoiseMerge) requires the line Index: foobar.py in the diff/patch file. This is what I needed to do to make a non-TortoiseSVN patch file work with TortoiseSVN's right-click Apply Patch command.

Before:

--- foobar.py.org   Sat May 08 16:00:56 2010
+++ foobar.py   Sat May 08 15:47:48 2010

After:

Index: foobar.py
===================================================================
--- foobar.py
+++ foobar.py   (working copy)

Or if you know the specific revision your contributor was working from:

Index: foobar.py
===================================================================
--- foobar.py   (revision 1157)
+++ foobar.py   (working copy)

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I had the same error code when I used @Transaction on a wrong method/actionlevel.

methodWithANumberOfDatabaseActions() { 
   methodA( ...)
   methodA( ...)
}

@Transactional
void methodA( ...) {
  ... ERROR message
}

I had to place the @Transactional just above the method methodWithANumberOfDatabaseActions(), of course.

That solved the error message in my case.

HTML5 phone number validation with pattern

This code will accept all country code with + sign

<input type="text" pattern="[0-9]{5}[-][0-9]{7}[-][0-9]{1}"/>

Some countries allow a single "0" character instead of "+" and others a double "0" character instead of the "+". Neither are standard.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

If you want to extract the files to the respective folder you can try this

find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;

A multi-processed version for systems that can handle high I/O:

find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"'

Redeploy alternatives to JRebel

You might want to take a look this:

HotSwap support: the object-oriented architecture of the Java HotSpot VM enables advanced features such as on-the-fly class redefinition, or "HotSwap". This feature provides the ability to substitute modified code in a running application through the debugger APIs. HotSwap adds functionality to the Java Platform Debugger Architecture, enabling a class to be updated during execution while under the control of a debugger. It also allows profiling operations to be performed by hotswapping in versions of methods in which profiling code has been inserted.

For the moment, this only allows for newly compiled method body to be redeployed without restarting the application. All you have to do is to run it with a debugger. I tried it in Eclipse and it works splendidly.

Also, as Emmanuel Bourg mentioned in his answer (JEP 159), there is hope to have support for the addition of supertypes and the addition and removal of methods and fields.

Reference: Java Whitepaper 135217: Reliability, Availability and Serviceability

powershell - extract file name and extension

PS C:\Windows\System32\WindowsPowerShell\v1.0>split-path "H:\Documents\devops\tp-mkt-SPD-38.4.10.msi" -leaf
tp-mkt-SPD-38.4.10.msi

PS C:\Windows\System32\WindowsPowerShell\v1.0> $psversiontable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5477
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

Boolean vs boolean in Java

One observation: (though this can be thought of side effect)

boolean being a primitive can either say yes or no.

Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)

JPanel setBackground(Color.BLACK) does nothing

setOpaque(false); 

CHANGED to

setOpaque(true);

PDO closing connection

According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.

Export to csv in jQuery

You can't avoid a server call here, JavaScript simply cannot (for security reasons) save a file to the user's file system. You'll have to submit your data to the server and have it send the .csv as a link or an attachment directly.

HTML5 has some ability to do this (though saving really isn't specified - just a use case, you can read the file if you want), but there's no cross-browser solution in place now.

Mongoose's find method with $or condition does not work properly

I solved it through googling:

var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception, 
// the 'param' must consist of more than 12 characters.

User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, 
  function(err,docs){
    if(!err) res.send(docs);
});

How to set an image as a background for Frame in Swing GUI of java?

if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator

Failed to find target with hash string 'android-25'

Make sure your computer is connected to the internet, then click on the link that comes with the error message i.e "install missing platform(s) and sync project". Give it a few seconds especially if your computer has low specs, it will bring up a window called SDK Quickfix Installation and everything is straightforward from there.

Check if object is a jQuery object

Check out the instanceof operator.

var isJqueryObject = obj instanceof jQuery