Programs & Examples On #Route me

0

c++ bool question

false == 0 and true = !false

i.e. anything that is not zero and can be converted to a boolean is not false, thus it must be true.

Some examples to clarify:

if(0)          // false
if(1)          // true
if(2)          // true
if(0 == false) // true
if(0 == true)  // false
if(1 == false) // false
if(1 == true)  // true
if(2 == false) // false
if(2 == true)  // false
cout << false  // 0
cout << true   // 1

true evaluates to 1, but any int that is not false (i.e. 0) evaluates to true but is not equal to true since it isn't equal to 1.

Change select box option background color

Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

How can I change the image of an ImageView?

if (android.os.Build.VERSION.SDK_INT >= 21) {
            storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
} else {
            storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
}

Is it possible to use Java 8 for Android development?

All the above solutions doesn't seem to work in 2019 with the latest Android Studio 3.4+.

I figured out a perfect and up to date solution to migrate or upgrade your Android Project to Java 8.

Solution: Click on File -> Project Structure -> Modules -> Properties tab.

Change the Source Compatibility and Target Compatibility to 1.8 (Java 8)

enter image description here

List vs tuple, when to use each?

A minor but notable advantage of a list over a tuple is that lists tend to be slightly more portable. Standard tools are less likely to support tuples. JSON, for example, does not have a tuple type. YAML does, but its syntax is ugly compared to its list syntax, which is quite nice.

In those cases, you may wish to use a tuple internally then convert to list as part of an export process. Alternately, you might want to use lists everywhere for consistency.

Angularjs - ng-cloak/ng-show elements blink

I'm using ng-show in a directive to show and hide popups.

<div class="..." ng-show="showPopup">

None of the above worked for me, and using ng-if instead of ng-show would be an overkill. That would imply removing and adding the whole popup content into the DOM at every single click. Instead I added an ng-if into the same element to make sure it doesn't show at the document load:

<div class="..." ng-show="showPopup" ng-if="popupReady">

Afterwards I added the initialization into the controller responsible of this directive with a timeout:

$timeout(function () {
    $scope.popupReady = true;
});

This way I eliminated the flickering issue and avoided the costly operation of DOM insertion at every single click. This came at an expense of using two scope variables for the same purpose instead of one, but so far this is definitely the best option.

Sleeping in a batch file

Just put this in your batch file where you want the wait.

@ping 127.0.0.1 -n 11 -w 1000 > null

Angular2: child component access parent class variable/function

The main article in the Angular2 documentation on this subject is :

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child

It covers the following:

  • Pass data from parent to child with input binding

  • Intercept input property changes with a setter

  • Intercept input property changes with ngOnChanges

  • Parent listens for child event

  • Parent interacts with child via a local variable

  • Parent calls a ViewChild

  • Parent and children communicate via a service

Force youtube embed to start in 720p

The first example below does not work for me, but the second one does (in Chrome).

<iframe width="720" height="405" src="//www.youtube.com/embed/GX_c566xYcQ?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>
<iframe width="720" height="405" src="//youtube.com/v/IplDUxTQxsE?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>

I believe the first one uses the new HTML5 youtube player whereas the bottom one (which works) uses the older flash player. However, the second one doesn't seem to load correctly in Safari/Firefox etc so probably not usable.

How to get client's IP address using JavaScript?

I'm going to offer a method that I use a lot when I want to store information in the html page, and want my javascript to read information without actually having to pass parameters to the javascript. This is especially useful when your script is referenced externally, rather than inline.

It doesn't meet the criterion of "no server side script", however. But if you can include server side scripting in your html, do this:

Make hidden label elements at the bottom of your html page, just above the end body tag.

Your label will look like this:

<label id="ip" class="hiddenlabel"><?php echo $_SERVER['REMOTE_ADDR']; ?></label>

Be sure to make a class called hiddenlabel and set the visibility:hidden so no one actually sees the label. You can store lots of things this way, in hidden labels.

Now, in your javascript, to retrieve the information stored in the label (in this case the client's ip address), you can do this:

var ip = document.getElementById("ip").innerHTML;

Now your variable "ip" equals the ip address. Now you can pass the ip to your API request.

* EDIT 2 YEARS LATER * Two minor refinements:

I routinely use this method, but call the label class="data", because, in fact, it is a way to store data. Class name "hiddenlabel" is kind of a stupid name.

The second modification is in the style sheet, instead of visibility:hidden:

.data{
    display:none;
}

...is the better way of doing it.

Why use getters and setters/accessors?

Although not common for getter and setter, the use of these methods can also be used in AOP/proxy pattern uses. eg for auditing variable you can use AOP to audit update of any value. Without getter/setter it's not possible except changing the code everywhere. Personaly I have never used AOP for that, but it shows one more advantage of using getter/setter.

Convert string in base64 to image and save on filesystem in Python

If the imagestr was bitmap data (which we now know it isn't) you could use this

imagestr is the base64 encoded string
width is the width of the image
height is the height of the image

from PIL import Image
from base64 import decodestring

image = Image.fromstring('RGB',(width,height),decodestring(imagestr))
image.save("foo.png")

Since the imagestr is just the encoded png data

from base64 import decodestring

with open("foo.png","wb") as f:
    f.write(decodestring(imagestr))

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

Auto-increment primary key in SQL tables

Right-click on the table in SSMS, 'Design' it, and click on the id column. In the properties, set the identity to be seeded @ e.g. 1 and to have increment of 1 - save and you're done.

Set port for php artisan.php serve

you can also add host as well with same command like :

php artisan serve --host=172.10.29.100 --port=8080

How to make responsive table

If you want control over the td's/th's like you can do with block level elements & floats: Its NOT possible. There is no way to make a td float over or under a th.

How can I upload files asynchronously?

I recommend using the Fine Uploader plugin for this purpose. Your JavaScript code would be:

$(document).ready(function() {
  $("#uploadbutton").jsupload({
    action: "addFile.do",
    onComplete: function(response){
      alert( "server response: " + response);
    }
  });
});

How to pass data from Javascript to PHP and vice versa?

I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

If you get this error while compiling in Microsoft Mobile Center

? Code signing is required for product type 'Application' in SDK 'iOS 10.3'

** ARCHIVE FAILED **

be aware that Mobile center doesn't yet support automatic signing with certificates of type app-store, ad-hoc and enterprise. Automatic signing only works with development certificates.

There are two things you can do to work around that limitation:

  1. Use a development certificate. You'll have to create a new one in the developer.apple.com portal, download it to your machine, export it to a .p12 file using keychain, then finally provide it to Mobile Center. You know the drill.

  2. Disable automatic signing. You will find that setting in Xcode in your project targets. Once disabled, a little "i" button will be displayed next to the "Xcode managed profile" label. Click that button, some info about the profile will be displayed. On the top left corner of that window, a "PROV" icon is displayed. That is the provisioning profile that you should provide to Mobile Center. Drag and drop the icon into the corresponding field in Mobile Center.

. Xcode

Load image from url

Best Method I have tried instead of using any libraries

public Bitmap getbmpfromURL(String surl){
    try {
        URL url = new URL(surl);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setDoInput(true);
        urlcon.connect();
        InputStream in = urlcon.getInputStream();
        Bitmap mIcon = BitmapFactory.decodeStream(in);
        return  mIcon;
    } catch (Exception e) {
        Log.e("Error", e.getMessage());
        e.printStackTrace();
        return null;
    }
}

Swift - encode URL

Swift 3

In Swift 3 there is addingPercentEncoding

let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)

Output:

test%2Ftest

Swift 1

In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters

var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")

Output:

test%2Ftest

The following are useful (inverted) character sets:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

If you want a different set of characters to be escaped create a set:
Example with added "=" character:

var originalString = "test/test=42"
var customAllowedSet =  NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")

Output:

test%2Ftest%3D42

Example to verify ascii characters not in the set:

func printCharactersInSet(set: NSCharacterSet) {
    var characters = ""
    let iSet = set.invertedSet
    for i: UInt32 in 32..<127 {
        let c = Character(UnicodeScalar(i))
        if iSet.longCharacterIsMember(i) {
            characters = characters + String(c)
        }
    }
    print("characters not in set: \'\(characters)\'")
}

Using command line arguments in VBscript

Set args = Wscript.Arguments

For Each arg In args
  Wscript.Echo arg
Next

From a command prompt, run the script like this:

CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"

Will give results like this:

1
2
A
B
Arg with spaces

Node.js: printing to console without a trailing newline?

Also, if you want to overwrite messages in the same line, for instance in a countdown, you could add '\r' at the end of the string.

process.stdout.write("Downloading " + data.length + " bytes\r");

iOS - Calling App Delegate method from ViewController

Even if technically feasible, is NOT a good approach. When You say: "The splash screen would have buttons for each room that would allow you to jump to any point on the walk through." So you want to pass through appdelegate to call these controllers via tohc events on buttons?

This approach does not follow Apple guidelines and has a lot of drawbacks.

How do I clear the std::queue efficiently?

I do this (Using C++14):

std::queue<int> myqueue;
myqueue = decltype(myqueue){};

This way is useful if you have a non-trivial queue type that you don't want to build an alias/typedef for. I always make sure to leave a comment around this usage, though, to explain to unsuspecting / maintenance programmers that this isn't crazy, and done in lieu of an actual clear() method.

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

How do I fetch lines before/after the grep result in bash?

This prints 10 lines of trailing context after matching lines

grep -i "my_regex" -A 10

If you need to print 10 lines of leading context before matching lines,

grep -i "my_regex" -B 10

And if you need to print 10 lines of leading and trailing output context.

grep -i "my_regex" -C 10

Example

user@box:~$ cat out 
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
user@box:~$

Normal grep

user@box:~$ grep my_regex out 
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines after

user@box:~$ grep -A 2 my_regex out   
line 5 my_regex
line 6
line 7
user@box:~$ 

Grep exact matching lines and 2 lines before

user@box:~$ grep -B 2 my_regex out  
line 3
line 4
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines before and after

user@box:~$ grep -C 2 my_regex out  
line 3
line 4
line 5 my_regex
line 6
line 7
user@box:~$ 

Reference: manpage grep

-A num
--after-context=num

    Print num lines of trailing context after matching lines.
-B num
--before-context=num

    Print num lines of leading context before matching lines.
-C num
-num
--context=num

    Print num lines of leading and trailing output context.

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

There are two things I learned from this:

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

  2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

I hope this helps someone else!

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

Difference between ${} and $() in Bash

  1. $() means: "first evaluate this, and then evaluate the rest of the line".

    Ex :

    echo $(pwd)/myFile.txt
    

    will be interpreted as

    echo /my/path/myFile.txt
    

    On the other hand ${} expands a variable.

    Ex:

    MY_VAR=toto
    echo ${MY_VAR}/myFile.txt
    

    will be interpreted as

    echo toto/myFile.txt
    
  2. Why can't I use it as bash$ while ((i=0;i<10;i++)); do echo $i; done

    I'm afraid the answer is just that the bash syntax for while just isn't the same as the syntax for for.

Google Chrome Full Black Screen

Disable Nvidia's nView Desktop Manager and the problem should resolve.

Excel VBA: function to turn activecell to bold

I use

            chartRange = xlWorkSheet.Rows[1];
            chartRange.Font.Bold = true;

to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.

You can call in VBA directly

            ActiveCell.Font.Bold = True

With this code I create a timestamp in the active cell, with bold font and yellow background

           Private Sub Worksheet_SelectionChange(ByVal Target As Range)
               ActiveCell.Value = Now()
               ActiveCell.Font.Bold = True
               ActiveCell.Interior.ColorIndex = 6
           End Sub

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

TypeScript, Looping through a dictionary

How about this?

for (let [key, value] of Object.entries(obj)) {
    ...
}

How to kill a child process after a given timeout in Bash?

Here's an attempt which tries to avoid killing a process after it has already exited, which reduces the chance of killing another process with the same process ID (although it's probably impossible to avoid this kind of error completely).

run_with_timeout ()
{
  t=$1
  shift

  echo "running \"$*\" with timeout $t"

  (
  # first, run process in background
  (exec sh -c "$*") &
  pid=$!
  echo $pid

  # the timeout shell
  (sleep $t ; echo timeout) &
  waiter=$!
  echo $waiter

  # finally, allow process to end naturally
  wait $pid
  echo $?
  ) \
  | (read pid
     read waiter

     if test $waiter != timeout ; then
       read status
     else
       status=timeout
     fi

     # if we timed out, kill the process
     if test $status = timeout ; then
       kill $pid
       exit 99
     else
       # if the program exited normally, kill the waiting shell
       kill $waiter
       exit $status
     fi
  )
}

Use like run_with_timeout 3 sleep 10000, which runs sleep 10000 but ends it after 3 seconds.

This is like other answers which use a background timeout process to kill the child process after a delay. I think this is almost the same as Dan's extended answer (https://stackoverflow.com/a/5161274/1351983), except the timeout shell will not be killed if it has already ended.

After this program has ended, there will still be a few lingering "sleep" processes running, but they should be harmless.

This may be a better solution than my other answer because it does not use the non-portable shell feature read -t and does not use pgrep.

How to check if an item is selected from an HTML drop down list?

<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
     alert('select one answer');
}
else {
    var selectedText = card.options[card.selectedIndex].text;
    alert(selectedText);
}
</script>

C++ cout hex values?

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

Git's famous "ERROR: Permission to .git denied to user"

I find the solution is the same as @spyar provide which is the Keychain Access app stored the old username.

There are 2 solutions for this situation:

  1. Delete the info in Keychain Access by
    • Open Keychain Access app
    • Search for github
    • Delete corresponding credentials

Or

  1. If you use want to use ssh key. You just change your Repo url from https

https://github.com/username/repo.git

into

[email protected]:username/repo.git

Hope this helps.

How to define hash tables in Bash?

I create HashMaps in bash 3 using dynamic variables. I explained how that works in my answer to: Associative arrays in Shell scripts

Also you can take a look in shell_map, which is a HashMap implementation made in bash 3.

Compute mean and standard deviation by group for multiple variables in a data.frame

The updated dplyr solution, as for 2020

1: summarise_each_() is deprecated as of dplyr 0.7.0. and 2: funs() is deprecated as of dplyr 0.8.0.

ag.dplyr <- DF %>% group_by(ID) %>% summarise(across(.cols = everything(),list(mean = mean, sd = sd)))

HTML image not showing in Gmail

Late to the party but here goes... I have experienced this problem as well and it was solved with the following:

  • Including the scheme in the src url (using "//" does not work - use full scheme EG: "https://")
  • Including width and height attributes
  • Including style="display:block" attribute
  • Including both alt and title attributes

EG:

<img src="https://static.mydomain.com/images/logo.png" alt="Logo" title="Logo" style="display:block" width="200" height="87" />

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

Have you tried this http://tools.android.com/preview-channel ? Download preview channel. After that, install ADT Preview.

XML Parsing - Read a Simple XML File and Retrieve Values

I usually use XmlDocument for this. The interface is pretty straight forward:

var doc = new XmlDocument();
doc.LoadXml(xmlString);

You can access nodes similar to a dictionary:

var tasks = doc["Tasks"];

and loop over all children of a node.

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

if you have multiple file, you use a loop to verify each of the file format, something like this

add: function(e, data) {
        data.url = 'xx/';
        var uploadErrors = [];
         var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
        console.log(data.originalFiles);
        for (var i = 0; i < data.originalFiles.length; i++) {
            if(data.originalFiles[i]['type'].length && !acceptFileTypes.test(data.originalFiles[i]['type'])) {
                    uploadErrors.push('Not an accepted file type');
                    data.originalFiles
                }
                if(data.originalFiles[i]['size'].length && data.originalFiles[i]['size'] > 5000000) {
                    uploadErrors.push('Filesize is too big');
                }
                if(uploadErrors.length > 0) {

                      alert(uploadErrors.join("\n"));
                }
        }
        data.submit();
      },

How to round a Double to the nearest Int in swift?

Swift 3: If you want to round to a certain digit number e.g. 5.678434 -> 5.68 you can just combine the round() or roundf() function with a multiplication:

let value:Float = 5.678434
let roundedValue = roundf(value * 100) / 100
print(roundedValue) //5.68

How to POST a JSON object to a JAX-RS service

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!

How to fix getImageData() error The canvas has been tainted by cross-origin data?

As others have said you are "tainting" the canvas by loading from a cross origins domain.

https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image

However, you may be able to prevent this by simply setting:

img.crossOrigin = "Anonymous";

This only works if the remote server sets the following header appropriately:

Access-Control-Allow-Origin "*"

The Dropbox file chooser when using the "direct link" option is a great example of this. I use it on oddprints.com to hoover up images from the remote dropbox image url, into my canvas, and then submit the image data back into my server. All in javascript

Position a CSS background image x pixels from the right?

This works in Chrome 27, i don't know if it's valid or not or what other browswers do with it. I was surprised about this.

background: url(../img/icon_file_upload.png) top+3px right+10px no-repeat;

filters on ng-model in an input

Use a directive which adds to both the $formatters and $parsers collections to ensure that the transformation is performed in both directions.

See this other answer for more details including a link to jsfiddle.

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

How to grep for two words existing on the same line?

You cat try with below command

cat log|grep -e word1 -e word2

HashMap get/put complexity

It has already been mentioned that hashmaps are O(n/m) in average, if n is the number of items and m is the size. It has also been mentioned that in principle the whole thing could collapse into a singly linked list with O(n) query time. (This all assumes that calculating the hash is constant time).

However what isn't often mentioned is, that with probability at least 1-1/n (so for 1000 items that's a 99.9% chance) the largest bucket won't be filled more than O(logn)! Hence matching the average complexity of binary search trees. (And the constant is good, a tighter bound is (log n)*(m/n) + O(1)).

All that's required for this theoretical bound is that you use a reasonably good hash function (see Wikipedia: Universal Hashing. It can be as simple as a*x>>m). And of course that the person giving you the values to hash doesn't know how you have chosen your random constants.

TL;DR: With Very High Probability the worst case get/put complexity of a hashmap is O(logn).

Find size of object instance in bytes in c#

You can use reflection to gather all the public member or property information (given the object's type). There is no way to determine the size without walking through each individual piece of data on the object, though.

How to clear all data in a listBox?

In C# Core DataSource does not exist, but this work fine:

listbox.ItemsSource = null;
listbox.Items.Clear();

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

SPA best practices for authentication and session management

I would go for the second, the token system.

Did you know about ember-auth or ember-simple-auth? They both use the token based system, like ember-simple-auth states:

A lightweight and unobtrusive library for implementing token based authentication in Ember.js applications. http://ember-simple-auth.simplabs.com

They have session management, and are easy to plug into existing projects too.

There is also an Ember App Kit example version of ember-simple-auth: Working example of ember-app-kit using ember-simple-auth for OAuth2 authentication.

How do I activate a specific workbook and a specific sheet?

You can try this.

Workbooks("Tire.xls").Activate

ThisWorkbook.Sheets("Sheet1").Select
Cells(2,24).value=24

How to schedule a periodic task in Java?

Use Google Guava AbstractScheduledService as given below:

public class ScheduledExecutor extends AbstractScheduledService {

   @Override
   protected void runOneIteration() throws Exception {
      System.out.println("Executing....");
   }

   @Override
   protected Scheduler scheduler() {
        return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
   }

   @Override
   protected void startUp() {
       System.out.println("StartUp Activity....");
   }


   @Override
   protected void shutDown() {
       System.out.println("Shutdown Activity...");
   }

   public static void main(String[] args) throws InterruptedException {
       ScheduledExecutor se = new ScheduledExecutor();
       se.startAsync();
       Thread.sleep(15000);
       se.stopAsync();
   }
}

If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.

How can I hide/show a div when a button is clicked?

This works:

_x000D_
_x000D_
     function showhide(id) {_x000D_
        var e = document.getElementById(id);_x000D_
        e.style.display = (e.style.display == 'block') ? 'none' : 'block';_x000D_
     }
_x000D_
    <!DOCTYPE html>_x000D_
    <html>   _x000D_
    <body>_x000D_
    _x000D_
     <a href="javascript:showhide('uniquename')">_x000D_
      Click to show/hide._x000D_
     </a>_x000D_
    _x000D_
     <div id="uniquename" style="display:none;">_x000D_
      <p>Content goes here.</p>_x000D_
     </div>_x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

CSS scale height to match width - possibly with a formfactor

#map { 
    width: 100%; 
    height: 100vw * 1.72 
}

Run Stored Procedure in SQL Developer?

Using SQL Developer Version 4.0.2.15 Build 15.21 the following works:

SET SERVEROUTPUT ON
var InParam1 varchar2(100)
var InParam2 varchar2(100)
var InParam3 varchar2(100)
var OutParam1 varchar2(100)

BEGIN
    /* Assign values to IN parameters */
    :InParam1 := 'one';
    :InParam2 := 'two';
    :InParam3 := 'three';

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(:InParam1, :InParam2, :InParam3, :OutParam1);
    dbms_output.enable;
    dbms_output.put_line('OutParam1: ' || :OutParam1);
END;
/

Android failed to load JS bundle

Running on device

I have found another answer.

  • adb reverse: only work on Android 5.0+ (API 21).
  • Another: Open the Developer menu by shaking the device, go to Dev Settings, Go to Debug server host for device, type in your machine's IP address and the port of the local dev server

Instantiate and Present a viewController in Swift

No matter what I tried, it just wouldn't work for me - no errors, but no new view controller on my screen either. Don't know why, but wrapping it in timeout function finally made it work:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.0) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "TabletViewController")
    self.present(controller, animated: true, completion: nil)
}

AngularJS: Basic example to use authentication in Single Page Application

I answered a similar question here: AngularJS Authentication + RESTful API


I've written an AngularJS module for UserApp that supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.

You could either:

  1. Modify the module and attach it to your own API, or
  2. Use the module together with UserApp (a cloud-based user management API)

https://github.com/userapp-io/userapp-angular

If you use UserApp, you won't have to write any server-side code for the user stuff (more than validating a token). Take the course on Codecademy to try it out.

Here's some examples of how it works:

  • How to specify which routes that should be public, and which route that is the login form:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    $routeProvider.when('/home', {templateUrl: 'partials/home.html'});
    

    The .otherwise() route should be set to where you want your users to be redirected after login. Example:

    $routeProvider.otherwise({redirectTo: '/home'});

  • Login form with error handling:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • Signup form with error handling:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    
  • Log out link:

    <a href="#" ua-logout>Log Out</a>

    (Ends the session and redirects to the login route)

  • Access user properties:

    User properties are accessed using the user service, e.g: user.current.email

    Or in the template: <span>{{ user.email }}</span>

  • Hide elements that should only be visible when logged in:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • Show an element based on permissions:

    <div ua-has-permission="admin">You are an admin</div>

And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.

If you need any help, just let me know!

How to get the screen width and height in iOS?

Make use of these Structs to know useful info about the current device in Swift 3.0

struct ScreenSize { // Answer to OP's question

    static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
    static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
    static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
    static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)

}

struct DeviceType { //Use this to check what is the device kind you're working with

    static let IS_IPHONE_4_OR_LESS  = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
    static let IS_IPHONE_SE         = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
    static let IS_IPHONE_7          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
    static let IS_IPHONE_7PLUS      = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
    static let IS_IPHONE_X          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 812.0
    static let IS_IPAD              = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0

}


struct iOSVersion { //Get current device's iOS version

    static let SYS_VERSION_FLOAT  = (UIDevice.current.systemVersion as NSString).floatValue
    static let iOS7               = (iOSVersion.SYS_VERSION_FLOAT >= 7.0 && iOSVersion.SYS_VERSION_FLOAT < 8.0)
    static let iOS8               = (iOSVersion.SYS_VERSION_FLOAT >= 8.0 && iOSVersion.SYS_VERSION_FLOAT < 9.0)
    static let iOS9               = (iOSVersion.SYS_VERSION_FLOAT >= 9.0 && iOSVersion.SYS_VERSION_FLOAT < 10.0)
    static let iOS10              = (iOSVersion.SYS_VERSION_FLOAT >= 10.0 && iOSVersion.SYS_VERSION_FLOAT < 11.0)
    static let iOS11              = (iOSVersion.SYS_VERSION_FLOAT >= 11.0 && iOSVersion.SYS_VERSION_FLOAT < 12.0)
    static let iOS12              = (iOSVersion.SYS_VERSION_FLOAT >= 12.0 && iOSVersion.SYS_VERSION_FLOAT < 13.0)

}

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

pandas: best way to select all columns whose names start with X

Just perform a list comprehension to create your columns:

In [28]:

filter_col = [col for col in df if col.startswith('foo')]
filter_col
Out[28]:
['foo.aa', 'foo.bars', 'foo.fighters', 'foo.fox', 'foo.manchu']
In [29]:

df[filter_col]
Out[29]:
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0

Another method is to create a series from the columns and use the vectorised str method startswith:

In [33]:

df[df.columns[pd.Series(df.columns).str.startswith('foo')]]
Out[33]:
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0

In order to achieve what you want you need to add the following to filter the values that don't meet your ==1 criteria:

In [36]:

df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]]==1]
Out[36]:
   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      NaN       1       NaN           NaN      NaN        NaN     NaN
1      NaN     NaN       NaN             1      NaN        NaN     NaN
2      NaN     NaN       NaN           NaN        1        NaN     NaN
3      NaN     NaN       NaN           NaN      NaN        NaN     NaN
4      NaN     NaN       NaN           NaN      NaN        NaN     NaN
5      NaN     NaN         1           NaN      NaN        NaN     NaN

EDIT

OK after seeing what you want the convoluted answer is this:

In [72]:

df.loc[df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]] == 1].dropna(how='all', axis=0).index]
Out[72]:
   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

Get list from pandas DataFrame column headers

as answered by Simeon Visser...you could do

list(my_dataframe.columns.values) 

or

list(my_dataframe) # for less typing.

But I think most the sweet spot is:

list(my_dataframe.columns)

It is explicit, at the same time not unnecessarily long.

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

PHP session handling errors

I got these two error messages, along with two others, and fiddled around for a while before discovering that all I needed to do was restart XAMPP! I hope this helps save someone else from the same wasted time!

Warning: session_start(): open(/var/folders/zw/hdfw48qd25xcch5sz9dd3w600000gn/T/sess_f8bgs41qn3fk6d95s0pfps60n4, O_RDWR) failed: Permission denied (13) in /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php on line 3

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php:3) in /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php on line 3

Warning: Unknown: open(/var/lib/php/session/sess_isu2r2bqudeosqvpoo8a67oj02, O_RDWR) failed: Permission denied (13) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0

Set element focus in angular way

The problem with your solution is that it does not work well when tied down to other directives that creates a new scope, e.g. ng-repeat. A better solution would be to simply create a service function that enables you to focus elements imperatively within your controllers or to focus elements declaratively in the html.

DEMO

JAVASCRIPT

Service

 .factory('focus', function($timeout, $window) {
    return function(id) {
      // timeout makes sure that it is invoked after any other event has been triggered.
      // e.g. click events that need to run before the focus or
      // inputs elements that are in a disabled state but are enabled when those events
      // are triggered.
      $timeout(function() {
        var element = $window.document.getElementById(id);
        if(element)
          element.focus();
      });
    };
  });

Directive

  .directive('eventFocus', function(focus) {
    return function(scope, elem, attr) {
      elem.on(attr.eventFocus, function() {
        focus(attr.eventFocusId);
      });

      // Removes bound events in the element itself
      // when the scope is destroyed
      scope.$on('$destroy', function() {
        elem.off(attr.eventFocus);
      });
    };
  });

Controller

.controller('Ctrl', function($scope, focus) {
    $scope.doSomething = function() {
      // do something awesome
      focus('email');
    };
  });

HTML

<input type="email" id="email" class="form-control">
<button event-focus="click" event-focus-id="email">Declarative Focus</button>
<button ng-click="doSomething()">Imperative Focus</button>

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
{
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}
}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

Pythonic way to create a long multi-line string

Are you talking about multi-line strings? Easy, use triple quotes to start and end them.

s = """ this is a very
        long string if I had the
        energy to type more and more ..."""

You can use single quotes too (3 of them of course at start and end) and treat the resulting string s just like any other string.

NOTE: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.

I.e.,:

' this is a very\n        long string if I had the\n        energy to type more and more ...'

Finally, one can also construct long lines in Python like this:

 s = ("this is a very"
      "long string too"
      "for sure ..."
     )

which will not include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):

'this is a verylong string toofor sure ...'

No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.

postgresql sequence nextval in schema

The quoting rules are painful. I think you want:

SELECT nextval('foo."SQ_ID"');

to prevent case-folding of SQ_ID.

Recursively find files with a specific extension

find -name "*Robert*" \( -name "*.pdf" -o -name "*.jpg" \)

The -o repreents an OR condition and you can add as many as you wish within the braces. So this says to find all files containing the word "Robert" anywhere in their names and whose names end in either "pdf" or "jpg".

App store link for "rate/review this app"

Here is the code that I am using in my app;

-(void)rateApp {

     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[@"itms-apps://itunes.apple.com/app/" stringByAppendingString: @"id547101139"]]]; 
}

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

good postgresql client for windows?

For anyone looking for a web-enabled client for Postgres, I'll just put the link out here to TeamPostgreSQL, a very polished AJAX web client for pg:

http://www.teampostgresql.com

How do I view executed queries within SQL Server Management Studio?

More clear query, targeting Studio sql queries is :

SELECT text  FROM sys.dm_exec_sessions es
  INNER JOIN sys.dm_exec_connections ec
      ON es.session_id = ec.session_id
  CROSS APPLY sys.dm_exec_sql_text(ec.most_recent_sql_handle) 
  where program_name like '%Query'

How do I check (at runtime) if one class is a subclass of another?

issubclass(class, classinfo)

Excerpt:

Return true if class is a subclass (direct, indirect or virtual) of classinfo.

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

<img title="<a href="javascript:alert('hello world')">The Link</a>" /> 

Differences between strong and weak in Objective-C

To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.

 -(void)displayLocalVariable
  {
     UIView* myView = [[UIView alloc] init];
     NSLog(@"myView tag is = %ld", myView.tag);
  }

In above method scope of myView variable is limited to displayLocalVariable method, once the method gets finished myView variable which is holding the UIView object will get deallocated from the memory.

Now what if we want to hold the myView variable throughout our view controller's life cycle. For this we can create the property named as usernameView which will have Strong reference to the variable myView(see @property(nonatomic,strong) UIView* usernameView; and self.usernameView = myView; in below code), as below,

@interface LoginViewController ()

@property(nonatomic,strong) UIView* usernameView;
@property(nonatomic,weak) UIView* dummyNameView;

- (void)displayLocalVariable;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated
{
     [self displayLocalVariable];
}

- (void)displayLocalVariable
{
   UIView* myView = [[UIView alloc] init];
   NSLog(@"myView tag is = %ld", myView.tag);
   self.usernameView = myView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end

Now in above code you can see myView has been assigned to self.usernameView and self.usernameView is having a strong reference(as we declared in interface using @property) to myView. Hence myView will not get deallocated from memory till self.usernameView is alive.

  • Weak reference

Now consider assigning myName to dummyNameView which is a Weak reference, self.dummyNameView = myView; Unlike Strong reference Weak will hold the myView only till there is Strong reference to myView. See below code to understand Weak reference,

-(void)displayLocalVariable
  {
     UIView* myView = [[UIView alloc] init];
     NSLog(@"myView tag is = %ld", myView.tag);
     self.dummyNameView = myView;
  }

In above code there is Weak reference to myView(i.e. self.dummyNameView is having Weak reference to myView) but there is no Strong reference to myView, hence self.dummyNameView will not be able to hold the myView value.

Now again consider the below code,

-(void)displayLocalVariable
      {
         UIView* myView = [[UIView alloc] init];
         NSLog(@"myView tag is = %ld", myView.tag);
         self.usernameView = myView;
         self.dummyNameView = myView;
      } 

In above code self.usernameView has a Strong reference to myView, hence self.dummyNameView will now have a value of myView even after method ends since myView has a Strong reference associated with it.

Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated till it's retain count reaches to 0.

Hope this helps.

When and where to use GetType() or typeof()?

typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.

GetType() is a method you call on individual objects, to get the execution-time type of the object.

Note that unless you only want exactly instances of TextBox (rather than instances of subclasses) you'd usually use:

if (myControl is TextBox)
{
    // Whatever
}

Or

TextBox tb = myControl as TextBox;
if (tb != null)
{
    // Use tb
}

How do I convert datetime.timedelta to minutes, hours in Python?

I don't think it's a good idea to caculate yourself.

If you just want a pretty output, just covert it into str with str() function or directly print() it.

And if there's further usage of the hours and minutes, you can parse it to datetime object use datetime.strptime()(and extract the time part with datetime.time() mehtod), for example:

import datetime

delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()

Get records of current month

Try this query:

SELECT *
FROM table 
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())

Printing reverse of any String without using any predefined function?

this is the best solution for this

public class String_rev {
public static void main(String[] args) {
    String str="Karan Rajput";
    int ln=str.length();
    for (int i = ln; i > 0; i--) {
        System.out.print(str.charAt(i-1));
    }
}

}

How to redirect output of systemd service to a file

You possibly get this error:

Failed to parse output specifier, ignoring: /var/log1.log

From the systemd.exec(5) man page:

StandardOutput=

Controls where file descriptor 1 (STDOUT) of the executed processes is connected to. Takes one of inherit, null, tty, journal, syslog, kmsg, journal+console, syslog+console, kmsg+console or socket.

The systemd.exec(5) man page explains other options related to logging. See also the systemd.service(5) and systemd.unit(5) man pages.

Or maybe you can try things like this (all on one line):

ExecStart=/bin/sh -c '/usr/local/bin/binary1 agent -config-dir /etc/sample.d/server 2>&1 > /var/log.log' 

An "and" operator for an "if" statement in Bash

Try this:

if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]

or

if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]

How do I test if a string is empty in Objective-C?

Simply Check your string length

 if (!yourString.length)
 {
   //your code  
 }

a message to NIL will return nil or 0, so no need to test for nil :).

Happy coding ...

jQuery make global variable

You can avoid declaration of global variables by adding them directly to the global object:

(function(global) {

  ...

  global.varName = someValue;

  ...

}(this));

A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.

You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.

How to close Android application?

by calling finish(); in OnClick button or on menu

case R.id.menu_settings:

      finish();
     return true;

Getting last day of the month in a given string date

I use this one-liner on my JasperServer Reports:

new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(new java.util.Date().format('yyyy') + "-" + (new Integer (new SimpleDateFormat("MM").format(new Date()))+1) + "-01")-1)

Doesn't look nice but works for me. Basically it's adding 1 to the current month, get the first day of that month and subtract one day.

Checking images for similarity with OpenCV

This is a huge topic, with answers from 3 lines of code to entire research magazines.

I will outline the most common such techniques and their results.

Comparing histograms

One of the simplest & fastest methods. Proposed decades ago as a means to find picture simmilarities. The idea is that a forest will have a lot of green, and a human face a lot of pink, or whatever. So, if you compare two pictures with forests, you'll get some simmilarity between histograms, because you have a lot of green in both.

Downside: it is too simplistic. A banana and a beach will look the same, as both are yellow.

OpenCV method: compareHist()

Template matching

A good example here matchTemplate finding good match. It convolves the search image with the one being search into. It is usually used to find smaller image parts in a bigger one.

Downsides: It only returns good results with identical images, same size & orientation.

OpenCV method: matchTemplate()

Feature matching

Considered one of the most efficient ways to do image search. A number of features are extracted from an image, in a way that guarantees the same features will be recognized again even when rotated, scaled or skewed. The features extracted this way can be matched against other image feature sets. Another image that has a high proportion of the features matching the first one is considered to be depicting the same scene.

Finding the homography between the two sets of points will allow you to also find the relative difference in shooting angle between the original pictures or the amount of overlapping.

There are a number of OpenCV tutorials/samples on this, and a nice video here. A whole OpenCV module (features2d) is dedicated to it.

Downsides: It may be slow. It is not perfect.


Over on the OpenCV Q&A site I am talking about the difference between feature descriptors, which are great when comparing whole images and texture descriptors, which are used to identify objects like human faces or cars in an image.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

Another possible issue might be that the meta values contain non US-ASCII characters. For me it helped to UrlEncode the values when adding them to the putRequest:

request.Metadata.Add(AmzMetaPrefix + "artist", HttpUtility.UrlEncode(song.Artist));
request.Metadata.Add(AmzMetaPrefix + "title", HttpUtility.UrlEncode(song.Title));

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

What is "runtime"?

If my understanding from reading the above answers is correct, Runtime is basically 'background processes' such as garbage collection, memory-allocation, basically any processes that are invoked indirectly, by the libraries / frameworks that your code is written in, and specifically those processes that occur after compilation, while the application is running.

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

Convert JSONArray to String Array

Take a look at this tutorial. Also you can parse above json like :

JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
    list.add(arr.getJSONObject(i).getString("name"));
}

How to create a simple proxy in C#?

Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.

If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.

If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.

Best way to Bulk Insert from a C# DataTable

This is going to be largely dependent on the RDBMS you're using, and whether a .NET option even exists for that RDBMS.

If you're using SQL Server, use the SqlBulkCopy class.

For other database vendors, try googling for them specifically. For example a search for ".NET Bulk insert into Oracle" turned up some interesting results, including this link back to Stack Overflow: Bulk Insert to Oracle using .NET.

'POCO' definition

Whilst I'm sure POCO means Plain Old Class Object or Plain Old C Object to 99.9% of people here, POCO is also Animator Pro's (Autodesk) built in scripting language.

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Isn't the size of character in Java 2 bytes?

Java allocates 2 of 2 bytes for character as it follows UTF-16. It occupies minimum 2 bytes while storing a character, and maximum of 4 bytes. There is no 1 byte or 3 bytes of storage for character.

How can I test a PDF document if it is PDF/A compliant?

Do you have Adobe PDFL or Acrobat Professional? You can use preflight operation if you do.

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

How to set the height of an input (text) field in CSS?

You use this style code

.heighttext{
 float:right;
 height:30px;
 width:70px;
 }

How to convert file to base64 in JavaScript?

JavaScript btoa() function can be used to convert data into base64 encoded string

How can I plot with 2 different y-axes?

Another alternative which is similar to the accepted answer by @BenBolker is redefining the coordinates of the existing plot when adding a second set of points.

Here is a minimal example.

Data:

x  <- 1:10
y1 <- rnorm(10, 100, 20)
y2 <- rnorm(10, 1, 1)

Plot:

par(mar=c(5,5,5,5)+0.1, las=1)

plot.new()
plot.window(xlim=range(x), ylim=range(y1))
points(x, y1, col="red", pch=19)
axis(1)
axis(2, col.axis="red")
box()

plot.window(xlim=range(x), ylim=range(y2))
points(x, y2, col="limegreen", pch=19)
axis(4, col.axis="limegreen")

example

Mongodb: failed to connect to server on first connect

Adding one more answer as the solution is from different contexts:

MongoDb Atlas problem solution

I connected to MongoDB Atlas and whitelisted my machine's IP by following the below steps:

  • Go to the security tab

the security tab

  • Go to the network access tab under the security tab

network access tab under security tab

  • Go to the IP whitelist tab

IP whitelist tab


SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Change a Nullable column to NOT NULL with Default Value

If its SQL Server you can do it on the column properties within design view

Try this?:

ALTER TABLE dbo.TableName 
  ADD CONSTRAINT DF_TableName_ColumnName
    DEFAULT '01/01/2000' FOR ColumnName

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

Your solution might be to add the original IP and/or hostname also:

ALLOWED_HOSTS = [
  'localhost',
  '127.0.0.1',
  '111.222.333.444',
  'mywebsite.com']

The condition to be satisfied is that the host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) should match one of the values in ALLOWED_HOSTS.

Get yesterday's date in bash on Linux, DST-safe

As this question is tagged "DST safe"

And using fork to date command implie delay, there is a simple and more efficient way using pure bash built-in:

printf -v tznow '%(%z %s)T' -1
TZ=${tznow% *} printf -v yesterday '%(%Y-%m-%d)T' $(( ${tznow#* } - 86400 ))
echo $yesterday

This is a lot quicker on more system friendly than having to fork to date.

From V>=5.0, there is a new variable $EPOCHSECONDS

printf -v tz '%(%z)T' -1
TZ=$tz printf -v yesterday '%(%Y-%m-%d)T' $(( EPOCHSECONDS - 86400 ))
echo $yesterday

Capturing Groups From a Grep RegEx

str="1w 2d 1h"
regex="([0-9])w ([0-9])d ([0-9])h"
if [[ $str =~ $regex ]]
then
    week="${BASH_REMATCH[1]}"
    day="${BASH_REMATCH[2]}"
    hour="${BASH_REMATCH[3]}"
    echo $week --- $day ---- $hour
fi

output: 1 --- 2 ---- 1

Best TCP port number range for internal applications

Short answer: use an unassigned user port

Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.

The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.

You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.

The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.

The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.

Elegant way to check for missing packages and install them?

This is the purpose of the rbundler package: to provide a way to control the packages that are installed for a specific project. Right now the package works with the devtools functionality to install packages to your project's directory. The functionality is similar to Ruby's bundler.

If your project is a package (recommended) then all you have to do is load rbundler and bundle the packages. The bundle function will look at your package's DESCRIPTION file to determine which packages to bundle.

library(rbundler)
bundle('.', repos="http://cran.us.r-project.org")

Now the packages will be installed in the .Rbundle directory.

If your project isn't a package, then you can fake it by creating a DESCRIPTION file in your project's root directory with a Depends field that lists the packages that you want installed (with optional version information):

Depends: ggplot2 (>= 0.9.2), arm, glmnet

Here's the github repo for the project if you're interested in contributing: rbundler.

Which passwordchar shows a black dot (•) in a winforms textbox?

One more solution to use this Unicode black circle >>

Start >> All Programs >> Accessories >> System Tools >> Character Map

Then select Arial font and choose the Black circle copy it and paste it into PasswordChar property of the textbox.

That's it....

svn list of files that are modified in local copy

As said you have to use SVN Check for modification in GUI and tortoiseproc.exe /command:repostatus /path:"<path-to-version-control-file-or-directory>" in CLI to see changes related to the root of the <path-to-version-control-file-or-directory>.

Sadly, but this command won't show ALL local changes, it does show only those changes which are related to the requested directory root. The changes taken separately, like standalone checkouts or orphan external directories in the root subdirectory will be shown as Unversioned or Nested and you might miss to commit/lookup them.

To avoid such condition you have to either call to tortoiseproc.exe /command:repostatus /pathfile:"<path-to-file-with-list-of-items-to-lookup-from>" (see detailed documentation on the command line: https://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-automation.html), or use some 3dparty applications/utilities/scripts to wrap the call.

I has been wrote my own set of scripts for Windows to automate the call from the Total Commander: https://sf.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/ToolAdaptors/totalcmd/README_EN.txt (search for TortoiseSVN)

- Opens TortoiseSVN status dialog for a set of WC directories (always opens to show unversioned changes).

Command:   call_nowindow.vbs
Arguments: tortoisesvn\TortoiseProcByNestedWC.bat /command:repostatus "%P" %S

- Opens TortoiseSVN commit dialogs for a set of WC directories (opens only if has not empty versioned changes).

Command:   call_nowindow.vbs
Arguments: tortoisesvn\TortoiseProcByNestedWC.bat /command:commit "%P" %S

See the README_EN.txt for the latest details (you have to execute the configure.bat before the usage and copy rest of scripts on yourself like call_nowindow.vbs).

Importing a GitHub project into Eclipse

I think you need to create a branch before you can import into your local Eclipse, otherwise, there is an error leading to incapable of importing repository from Github or Bitbucket.

How to get cumulative sum

Once the table is created -

select 
    A.id, A.SomeNumt, SUM(B.SomeNumt) as sum
    from @t A, @t B where A.id >= B.id
    group by A.id, A.SomeNumt

order by A.id

Can't operator == be applied to generic types in C#?

The .Equals() works for me while TKey is a generic type.

public virtual TOutputDto GetOne(TKey id)
{
    var entity =
        _unitOfWork.BaseRepository
            .FindByCondition(x => 
                !x.IsDelete && 
                x.Id.Equals(id))
            .SingleOrDefault();


    // ...
}

How to convert ZonedDateTime to Date?

If you are interested in now only, then simply use:

Date d = new Date();

Difference between no-cache and must-revalidate

max-age=0, must-revalidate and no-cache aren't exactly identical. With must-revalidate, if the server doesn't respond to a revalidation request, the browser/proxy is supposed to return a 504 error. With no-cache, it would just show the cached content, which would be probably preferred by the user (better to have something stale than nothing at all). This is why must-revalidate is intended for critical transactions only.

How to include static library in makefile

Make sure that the -L option appears ahead of the -l option; the order of options in linker command lines does matter, especially with static libraries. The -L option specifies a directory to be searched for libraries (static or shared). The -lname option specifies a library which is with libmine.a (static) or libmine.so (shared on most variants of Unix, but Mac OS X uses .dylib and HP-UX used to use .sl). Conventionally, a static library will be in a file libmine.a. This is convention, not mandatory, but if the name is not in the libmine.a format, you cannot use the -lmine notation to find it; you must list it explicitly on the compiler (linker) command line.

The -L./libmine option says "there is a sub-directory called libmine which can be searched to find libraries". I can see three possibilities:

  1. You have such a sub-directory containing libmine.a, in which case you also need to add -lmine to the linker line (after the object files that reference the library).
  2. You have a file libmine that is a static archive, in which case you simply list it as a file ./libmine with no -L in front.
  3. You have a file libmine.a in the current directory that you want to pick up. You can either write ./libmine.a or -L . -lmine and both should find the library.

Maven: how to override the dependency added by a library

What you put inside the </dependencies> tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.

However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement> tag.

You can also use the </dependencyManagement> to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).

How can I check if a user is logged-in in php?

Logins are not too complicated, but there are some specific pieces that almost all login processes need.

First, make sure you enable the session variable on all pages that require knowledge of logged-in status by putting this at the beginning of those pages:

session_start();

Next, when the user submits their username and password via the login form, you will typically check their username and password by querying a database containing username and password information, such as MySQL. If the database returns a match, you can then set a session variable to contain that fact. You might also want to include other information:

if (match_found_in_database()) {
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $username; // $username coming from the form, such as $_POST['username']
                                       // something like this is optional, of course
}

Then, on the page that depends on logged-in status, put the following (don't forget the session_start()):

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
    echo "Please log in first to see this page.";
}

Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.

MySQL order by before group by

Just use the max function and group function

    select max(taskhistory.id) as id from taskhistory
            group by taskhistory.taskid
            order by taskhistory.datum desc

How to install requests module in Python 3.4, instead of 2.7

while installing python packages in a global environment is doable, it is a best practice to isolate the environment between projects (creating virtual environments). Otherwise, confusion between Python versions will arise, just like your problem.

The simplest method is to use venv library in the project directory:

python3 -m venv venv

Where the first venv is to call the venv package, and the second venv defines the virtual environment directory name. Then activate the virtual environment:

source venv/bin/activate

Once the virtual environment has been activated, your pip install ... commands would not be interfered with any other Python version or pip version anymore. For installing requests:

pip install requests

Another benefit of the virtual environment is to have a concise list of libraries needed for that specific project.

*note: commands only work on Linux and Mac OS

Can't escape the backslash with regex?

This solution fixed my problem while replacing br tag to '\n' .

alert(content.replace(/<br\/\>/g,'\n'));

Section vs Article HTML5

A section is basically a wrapper for h1 (or other h tags) and the content that corresponds to this. An article is essentially a document within your document that is repeated or paginated...like each blog post on your document can be an article, or each comment on your document can be an article.

How to get full width in body element

If its in a landscape then you will be needing more width and less height! That's just what all websites have.

Lets go with a basic first then the rest!

The basic CSS:

By CSS you can do this,

#body {
width: 100%;
height: 100%;
}

Here you are using a div with id body, as:

<body>
  <div id="body>
    all the text would go here!
  </div>
</body>

Then you can have a web page with 100% height and width.

What if he tries to resize the window?

The issues pops up, what if he tries to resize the window? Then all the elements inside #body would try to mess up the UI. For that you can write this:

#body {
height: 100%;
width: 100%;
}

And just add min-height max-height min-width and max-width.

This way, the page element would stay at the place they were at the page load.

Using JavaScript:

Using JavaScript, you can control the UI, use jQuery as:

$('#body').css('min-height', '100%');

And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.

How to not add scroll to the web page:

If you are not trying to add a scroll, then you can use this JS

$('#body').css('min-height', screen.height); // or anyother like window.height

This way, the document will get a new height whenever the user would load the page.

Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!

Tip: So try using JS to find current Screen size and edit the page! :)

How do I alter the precision of a decimal column in Sql Server?

Go to enterprise manager, design table, click on your field.

Make a decimal column

In the properties at the bottom there is a precision property

Create an application setup in visual studio 2013

I will tell , how i solved almost similar problem. I developed a application using VS 2013 and tried to create wizard for it failed to do. Later i installed premium VS and tried and failed.

at last i used "ClickOnce" and it worked fine.

So i believe here also , "CLICKONCE" would help you.

How to stop text from taking up more than 1 line?

You can use CSS white-space Property to achieve this.

white-space: nowrap

How to check if an alert exists using WebDriver?

public boolean isAlertPresent() {

try 
{ 
    driver.switchTo().alert(); 
    system.out.println(" Alert Present");
}  
catch (NoAlertPresentException e) 
{ 
    system.out.println("No Alert Present");
}    

}

Make a phone call programmatically

In Swift 3.0,

static func callToNumber(number:String) {

        let phoneFallback = "telprompt://\(number)"
        let fallbackURl = URL(string:phoneFallback)!

        let phone = "tel://\(number)"
        let url = URL(string:phone)!

        let shared = UIApplication.shared

        if(shared.canOpenURL(fallbackURl)){
            shared.openURL(fallbackURl)
        }else if (shared.canOpenURL(url)){
            shared.openURL(url)
        }else{
            print("unable to open url for call")
        }

    }

What is the difference between cache and persist?

Cache() and persist() both the methods are used to improve performance of spark computation. These methods help to save intermediate results so they can be reused in subsequent stages.

The only difference between cache() and persist() is ,using Cache technique we can save intermediate results in memory only when needed while in Persist() we can save the intermediate results in 5 storage levels(MEMORY_ONLY, MEMORY_AND_DISK, MEMORY_ONLY_SER, MEMORY_AND_DISK_SER, DISK_ONLY).

What is "stdafx.h" used for in Visual Studio?

I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put

#include <Windows.h>

instead.

Does MySQL foreign_key_checks affect the entire database?

# will get you the current local (session based) state.
SHOW Variables WHERE Variable_name='foreign_key_checks';

If you didn't SET GLOBAL, only your session was affected.

Jquery UI Datepicker not displaying

Please make sure that you are using the same version of jquery-ui 'js' and 'css' files. Sometimes that could be a problem.

How to select all columns, except one column in pandas?

Another slight modification to @Salvador Dali enables a list of columns to exclude:

df[[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]

or

df.loc[:,[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]

Making heatmap from pandas DataFrame

You want matplotlib.pcolor:

import numpy as np 
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

This gives:

Output sample

Linux: command to open URL in default browser

On distributions that come with the open command,

$ open http://www.google.com

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

sort files by date in PHP

You need to put the files into an array in order to sort and find the last modified file.

$files = array();
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);

    // sort
    ksort($files);
    // find the last modification
    $reallyLastModified = end($files);

    foreach($files as $file) {
        $lastModified = date('F d Y, H:i:s',filemtime($file));
        if(strlen($file)-strpos($file,".swf")== 4){
           if ($file == $reallyLastModified) {
             // do stuff for the real last modified file
           }
           echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
        }
    }
}

Not tested, but that's how to do it.

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

How do I undo 'git add' before commit?

In Sourcetree you can do this easily via the GUI. You can check which command Sourcetree uses to unstage a file.

I created a new file and added it to Git. Then I unstaged it using the Sourcetree GUI. This is the result:

Unstaging files [08/12/15 10:43] git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree reset -q -- path/to/file/filename.java

Sourcetree uses reset to unstage new files.

Creating a byte array from a stream

just my couple cents... the practice that I often use is to organize the methods like this as a custom helper

public static class StreamHelpers
{
    public static byte[] ReadFully(this Stream input)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            input.CopyTo(ms);
            return ms.ToArray();
        }
    }
}

add namespace to the config file and use it anywhere you wish

'Incorrect SET Options' Error When Building Database Project

I had the same issue with the filtered index and my inserts and updates were failing. All I did was to change the stored procedure that had the insert and update statement to:

create procedure abc
()
AS
BEGIN
SET NOCOUNT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON 
SET ANSI_WARNINGS ON 
SET ANSI_PADDING ON 
end

How to include files outside of Docker's build context?

An easy workaround might be to simply mount the volume (using the -v or --mount flag) to the container when you run it and access the files that way.

example:

docker run -v /path/to/file/on/host:/desired/path/to/file/in/container/ image_name

for more see: https://docs.docker.com/storage/volumes/

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

Button Width Match Parent

         OutlineButton(
              onPressed: () {
                logInButtonPressed(context);
              },
              child: Container(
                width: MediaQuery.of(context).size.width / 2,
                child: Text(
                  “Log in”,
                  textAlign: TextAlign.center,
                ),
              ),
            )

Something like this works for me.

How to search a list of tuples in Python

Supposing the list may be long and the numbers may repeat, consider using the SortedList type from the Python sortedcontainers module. The SortedList type will automatically maintain the tuples in order by number and allow for fast searching.

For example:

from sortedcontainers import SortedList
sl = SortedList([(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")])

# Get the index of 53:

index = sl.bisect((53,))

# With the index, get the tuple:

tup = sl[index]

This will work a lot faster than the list comprehension suggestion by doing a binary search. The dictionary suggestion will be faster still but won't work if there could be duplicate numbers with different strings.

If there are duplicate numbers with different strings then you need to take one more step:

end = sl.bisect((53 + 1,))

results = sl[index:end]

By bisecting for 54, we will find the end index for our slice. This will be significantly faster on long lists as compared with the accepted answer.

ADB Driver and Windows 8.1

The most complete answer I have found is here: http://blog.kikicode.com/2013/10/installing-android-adb-driver-in.html

I'm copying the complete answer below.


Installing Android ADB driver in Windows 8.1 64-bit when all else fails

For some reason I just couldn't get my machine to recognize Xperia J in Windows 8.1 64-bit. Even after installing latest Sony PC Companion (2.10.174). Device Manager kept showing yellow exclamation mark to an 'Android'.

Here's the solution, but I don't promise it will work on your device!

1. Find out your device's VID and PID

Open Device Manager, right-click that Android with yellow exclamation mark and click Properties. Go to Details tab. In Property, select Hardware Ids. Right-click the value and click Copy. Paste the value somewhere.

2. Download Android USB Driver

Run Android SDK Manager. Expand Extras, tick Google USB Driver, click Install packages. After installation, look for the driver location by hovering mouse over Google USB Driver. The location will appear in the tooltip.

3. Modify android_winusb.inf

Go to the usb driver location, for example in the above picture it is c:\Android\android-studio\sdk\extras\google\usb_driver Make a backup copy of android_winusb.inf Open android_winusb.inf with a text editor. Notepad is fine but Notepad++ is better, it will syntax highlight the inf file! Look for [Google.NTx86], and insert a line with your device's hardware ID that you copied above, for example

[Google.NTx86]

; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Look for [Google.NTamd86], and insert the same lines, for example:

[Google.NTamd64]

; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Save the file.

4. Disable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions DISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON

Restart Windows.

5. Install driver

Open Device Manager, right-click that Android with yellow exclamation mark and click Update Driver Software. Click Browse my computer for driver software. Enter or browse to the folder containing android_winusb.inf, eg: C:\Android\android-studio\sdk\extras\google\usb_driver Click Next. The driver will install. Run adb devices to confirm your device is working fine.

6. Re-enable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions ENABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING OFF

Restart Windows. Run adb devices to reconfirm!

How can I access and process nested objects, arrays or JSON?

If you are looking for one or more objects that meets certain criteria you have a few options using query-js

//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1 
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});

There's also a single and a singleOrDefault they work much like firstand firstOrDefaultrespectively. The only difference is that they will throw if more than one match is found.

for further explanation of query-js you can start with this post

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

Numpy: Divide each row by a vector element

Pythonic way to do this is ...

np.divide(data.T,vector).T

This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.

#NOTE: No of columns in both data and vector should match

java.math.BigInteger cannot be cast to java.lang.Integer

As we see from the javaDoc, BigInteger is not a subclass of Integer:

java.lang.Object                      java.lang.Object
   java.lang.Number                       java.lang.Number
      java.math.BigInteger                    java.lang.Integer

And that's the reason why casting from BigInteger to Integer is impossible.

Casting of java primitives will do some conversion (like casting from double to int) while casting of types will never transform classes.

Reading from text file until EOF repeats last line

The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.

What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.

I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.

  • 0

So add a prime read and move the loop's read to the end:

int x;

iFile >> x; // prime read here
while (!iFile.eof()) {
    cerr << x << endl;
    iFile >> x;
}

What is AndroidX?

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Changes in gradle:

implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'

When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library

Refer to: https://developer.android.com/jetpack/androidx/migrate

What is this CSS selector? [class*="span"]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
    <strong class="span6">Blah blah</strong>
</div>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

How do I prevent DIV tag starting a new line?

The div tag is a block element, causing that behavior.

You should use a span element instead, which is inline.

If you really want to use div, add style="display: inline". (You can also put that in a CSS rule)

How do we use runOnUiThread in Android?

You can use from this sample :

In the following example, we are going to use this facility to publish the result from a synonym search that was processed by a background thread.

To accomplish the goal during the OnCreate activity callback, we will set up onClickListener to run searchTask on a created thread.

When the user clicks on the Search button, we will create a Runnable anonymous class that searches for the word typed in R.id.wordEt EditText and starts the thread to execute Runnable.

When the search completes, we will create an instance of Runnable SetSynonymResult to publish the result back on the synonym TextView over the UI thread.

This technique is sometime not the most convenient one, especially when we don't have access to an Activity instance; therefore, in the following chapters, we are going to discuss simpler and cleaner techniques to update the UI from a background computing task.

public class MainActivity extends AppCompatActivity {

    class SetSynonymResult implements Runnable {
        String synonym;

        SetSynonymResult(String synonym) {
            this.synonym = synonym;
        }

        public void run() {
            Log.d("AsyncAndroid", String.format("Sending synonym result %s on %d",
                    synonym, Thread.currentThread().getId()) + " !");
            TextView tv = (TextView) findViewById(R.id.synonymTv);
            tv.setText(this.synonym);
        }
    }

    ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button search = (Button) findViewById(R.id.searchBut);
        final EditText word = (EditText) findViewById(R.id.wordEt);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Runnable searchTask = new Runnable() {
                    @Override
                    public void run() {
                        String result = searchSynomim(word.getText().toString());
                        Log.d("AsyncAndroid", String.format("Searching for synonym for %s on %s",
                                word.getText(), Thread.currentThread().getName()));
                        runOnUiThread(new SetSynonymResult(result));
                    }
                };
                Thread thread = new Thread(searchTask);
                thread.start();
            }
        });

    }

    static int i = 0;

    String searchSynomim(String word) {
        return ++i % 2 == 0 ? "fake" : "mock";
    }
}

Source :

asynchronous android programming Helder Vasconcelos

SQL Server: combining multiple rows into one row

You can achieve this is to combine For XML Path and STUFF as follows:

SELECT (STUFF((
        SELECT ', ' + StringValue
        FROM Jira.customfieldvalue
        WHERE CUSTOMFIELD = 12534
        AND ISSUE = 19602
        FOR XML PATH('')
        ), 1, 2, '')
    ) AS StringValue

Lock, mutex, semaphore... what's the difference?

Using C programming on a Linux variant as a base case for examples.

Lock:

• Usually a very simple construct binary in operation either locked or unlocked

• No concept of thread ownership, priority, sequencing etc.

• Usually a spin lock where the thread continuously checks for the locks availability.

• Usually relies on atomic operations e.g. Test-and-set, compare-and-swap, fetch-and-add etc.

• Usually requires hardware support for atomic operation.

File Locks:

• Usually used to coordinate access to a file via multiple processes.

• Multiple processes can hold the read lock however when any single process holds the write lock no other process is allowed to acquire a read or write lock.

• Example : flock, fcntl etc..

Mutex:

• Mutex function calls usually work in kernel space and result in system calls.

• It uses the concept of ownership. Only the thread that currently holds the mutex can unlock it.

• Mutex is not recursive (Exception: PTHREAD_MUTEX_RECURSIVE).

• Usually used in Association with Condition Variables and passed as arguments to e.g. pthread_cond_signal, pthread_cond_wait etc.

• Some UNIX systems allow mutex to be used by multiple processes although this may not be enforced on all systems.

Semaphore:

• This is a kernel maintained integer whose values is not allowed to fall below zero.

• It can be used to synchronize processes.

• The value of the semaphore may be set to a value greater than 1 in which case the value usually indicates the number of resources available.

• A semaphore whose value is restricted to 1 and 0 is referred to as a binary semaphore.

Git push existing repo to a new and different remote repo server?

I found a solution using set-url which is concise and fairly easy to understand:

  1. create a new repo at Github
  2. cd into the existing repository on your local machine (if you haven't cloned it yet, then do this first)
  3. git remote set-url origin https://github.com/user/example.git
  4. git push -u origin master

jQuery Force set src attribute for iframe

<script type="text/javascript">
  document.write(
    "<iframe id='myframe' src='http://www.example.com/" + 
    window.location.search + "' height='100' width='100%' >"
  ) 
</script>  

This code takes the url-parameters (?a=1&b=2) from the page containing the iframe and attaches them to the base url of the iframe. It works for my purposes.

Compare two Timestamp in java

From : http://download.oracle.com/javase/6/docs/api/java/sql/Timestamp.html#compareTo(java.sql.Timestamp)

public int compareTo(Timestamp ts)

Compares this Timestamp object to the given Timestamp object. Parameters: ts - the Timestamp object to be compared to this Timestamp object Returns: the value 0 if the two Timestamp objects are equal; a value less than 0 if this Timestamp object is before the given argument; and a value greater than 0 if this Timestamp object is after the given argument. Since: 1.4

What do numbers using 0x notation mean?

SIMPLE

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example :

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or any base ..

Hope Helped in some way.

Good day,

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

Determine the size of an InputStream

You can't determine the amount of data in a stream without reading it; you can, however, ask for the size of a file:

http://java.sun.com/javase/6/docs/api/java/io/File.html#length()

If that isn't possible, you can write the bytes you read from the input stream to a ByteArrayOutputStream which will grow as required.

How to unlock a file from someone else in Team Foundation Server

Team Foundation Sidekicks has a Status sidekick that allows you to query for checked out work items. Once a work item is selected, click the "Undo lock" buttons on the toolbar.

Rights

Keep in mind that you will need the appropriate rights. The permissions are called "Undo other users' changes" and "Unlock other users' changes". These permissions can be viewed by:

  1. Right-clicking the desired project, folder, or file in Source Control Explorer
  2. Select Properties
  3. Select the Security tab
  4. Select the appropriate user or group in the Users and Groups section at the top
  5. View the "Permissions for [user/group]:" section at the bottom

Screenshot of unlocking a file using Team Foundation Sidekicks

Disclaimer: this answer is an edited repost of Brett Roger's answer to a similar question.

Python: "TypeError: __str__ returned non-string" but still prints to output?

I Had the same problem, in my case, was because i was returned a digit:

def __str__(self):
    return self.code

str is waiting for a str, not another.

now work good with:

def __str__(self):
    return self.name

where name is a STRING.

Property 'value' does not exist on type 'EventTarget'

In my case, I had:

const handleOnChange = (e: ChangeEvent) => {
  doSomething(e.target.value);
}

And the issue was that I did not provide a type argument to ChangeEvent so that it knows e.target was an HTMLInputElement. Even if I manually told it that target was an input element (e.g. const target: HTMLInputElement = e.target), the ChangeEvent still didn't know that made sense.

The solution was to do:

// add type argument
const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
  doSomething(e.target.value);
}

Hashmap does not work with int, char

Generics can't use primitive types in the form of keywords.

Use

public HashMap<Character, Integer> buildMap(String letters)
{
    HashMap<Character, Integer> checkSum = new HashMap<Character, Integer>();

    for ( int i = 0; i < letters.length(); ++i )
    {
        checkSum.put(letters.charAt(i), primes[i]);
    }

    return checkSum;
}

Updated: With Java 7 and later, you can use the diamond operator.

HashMap<Character, Integer> checkSum = new HashMap<>();

Converting an int or String to a char array on Arduino

You can convert it to char* if you don't need a modifiable string by using:

(char*) yourString.c_str();

This would be very useful when you want to publish a String variable via MQTT in arduino.

maximum value of int

Why not write a piece of code like:

int  max_neg = ~(1 << 31);
int  all_ones = -1;
int max_pos = all_ones & max_neg;

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Format output string, right alignment

Simple tabulation of the output:

a = 0.3333333
b = 200/3
print("variable a    variable b")
print("%10.2f    %10.2f" % (a, b))

output:

variable a    variable b
      0.33         66.67

%10.2f: 10 is the minimum length and 2 is the number of decimal places.

What is a Java String's default initial value?

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)

How to dismiss keyboard for UITextView with return key?

Just solved this problem a different way.

  • Create a button that will be placed in the background
  • From the Attribute Inspector, change the button type to custom, and the makes the button transparent.
  • Expand the button to cover the whole view, and make sure the button is behind all the other object. Easy way to do this is to drag the button to the top of list view in the View
  • Control drag the button to the viewController.h file and create an action (Sent Event: Touch Up Inside) like :

    (IBAction)ExitKeyboard:(id)sender;
    
  • In ViewController.m should look like :

    (IBAction)ExitKeyboard:(id)sender {
        [self.view endEditing:TRUE];
    }
    
  • Run app, and when you click away from the TextView, the keyboard disappears

Using lodash to compare jagged arrays (items existence without order)

Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays

It's an old question, but I was having issues with the speed of using .sort() or sortBy(), so I used this instead:

function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
  return (
    array1.length === array2.length &&
    array1.every((str) => array2.includes(str)) &&
    array2.every((str) => array1.includes(str))
  )
}

It was intended to fail fast, and for my purposes works fine.

CSS - display: none; not working

Another trick is to use

.class {
position: absolute;
visibility:hidden;
display:none;
}

This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none works later on it will be working. Keep in mind that visibility:hidden may not remove it from screen readers.

How to ignore certain files in Git

First create a .gitignore file where we have to store the names of files and directories to be ignored. To ignore a directory;

name_of_directory/

To ignore a file;

name_of_file

We don't need to provide the complete path of the file or directory to be ignored, we just have to provide its name.

If you want to ignore all files with same extention;

*.pyc  #will ignore all files with pyc extention

Using Python's list index() method on a list of tuples or objects?

One possibility is to use the itemgetter function from the operator module:

import operator

f = operator.itemgetter(0)
print map(f, tuple_list).index("cherry") # yields 1

The call to itemgetter returns a function that will do the equivalent of foo[0] for anything passed to it. Using map, you then apply that function to each tuple, extracting the info into a new list, on which you then call index as normal.

map(f, tuple_list)

is equivalent to:

[f(tuple_list[0]), f(tuple_list[1]), ...etc]

which in turn is equivalent to:

[tuple_list[0][0], tuple_list[1][0], tuple_list[2][0]]

which gives:

["pineapple", "cherry", ...etc]

Is there a way to make npm install (the command) to work behind proxy?

There is good information on curl's page on SSL and certificate issues. I base most of my answer on the information there.

Using strict-ssl false is bad practice and can create issues. What we can do instead is add the certificate that is being injected, by the "man in the middle" certificate.

How to solve this on Windows:

  1. Download the CA Certificates from curl based on Mozilla's CA bundle. You can also use curl's "firefox-db2pem.sh" shellscript to convert your local Firefox database.
  2. Go to a webpage using https, for example Stackoverflow in Chrome or Internet Explorer
  3. Click the lock icon, click View certificates or "Valid" in Chrome
  4. Navigate to the Certification path. The top certificate, or the root certificate is the one we want to extract. Click that certificate and then "view certificate"
  5. Click the second tab, "Details". Click "Copy to file". Pick the DER format and make note of where you save the file. Pick a suitable filename, like rootcert.cer
  6. If you have Git installed you will have openssl.exe. Otherwise, install git for windows at this stage. Most likely the openssl executable will be at C:\Program Files\git\usr\bin\openssl.exe. We will use openssl to convert the file to the PEM format we need for NPM to understand it.
  7. Convert the file you saved in step 5 by using this command:
    openssl x509 -inform DES -in **rootcert**.cer -out outcert.pem -text
    where rootcert is the filename of the certificate you saved in step 5.
  8. Open the outcert.pem in a text-editor smart enough to understand line-endings, so not notepad. Select all the text and copy it to clipboard.
  9. Now we will paste that content to the end of the CA Cert bundle made in step 1. So open the cacert.pem in your advanced texteditor. Go to the end of the file and paste the content from previous step to the end of file. (Preserve the empty line below what you just pasted)
  10. Copy the saved cabundle.pem to a suitable place. Eg your %userprofile% or ~. Make note of the location of the file.
  11. Now we will tell npm/yarn to use the new bundle. In a commandline, write
    npm config set cafile **C:\Users\username\cacert.pem
    where C:\Users\username\cacert.pem is the path from step 10.
  12. Optionally: turn on strict-ssl again, npm config set strict-ssl true

Phew! We made it! Now npm can understand how to connect. Bonus is that you can tell curl to use the same cabundle.pem and it will also understand HTTPs.

MVC controller : get JSON object from HTTP body?

I've been trying to get my ASP.NET MVC controller to parse some model that i submitted to it using Postman.

I needed the following to get it to work:

  • controller action

    [HttpPost]
    [PermitAllUsers]
    [Route("Models")]
    public JsonResult InsertOrUpdateModels(Model entities)
    {
        // ...
        return Json(response, JsonRequestBehavior.AllowGet);
    }
    
  • a Models class

    public class Model
    {
        public string Test { get; set; }
        // ...
    }
    
  • headers for Postman's request, specifically, Content-Type

    postman headers

  • json in the request body

    enter image description here

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Actually the "Remote" option in Configuration Menu for Plug-In works by me (Win7 64, ie8 with all updates), however:

  1. You need administrator rights
  2. The plug-in should be disabled before pressing the remove button
  3. You need restart internet-explorer to see the changes.

Also the previous comment about browsing-history->view objects was also useful if plug-in was installed right now.

Regards!

Access-control-allow-origin with multiple domains

There can only be one Access-Control-Allow-Origin response header, and that header can only have one origin value. Therefore, in order to get this to work, you need to have some code that:

  1. Grabs the Origin request header.
  2. Checks if the origin value is one of the whitelisted values.
  3. If it is valid, sets the Access-Control-Allow-Origin header with that value.

I don't think there's any way to do this solely through the web.config.

if (ValidateRequest()) {
    Response.Headers.Remove("Access-Control-Allow-Origin");
    Response.AddHeader("Access-Control-Allow-Origin", Request.UrlReferrer.GetLeftPart(UriPartial.Authority));

    Response.Headers.Remove("Access-Control-Allow-Credentials");
    Response.AddHeader("Access-Control-Allow-Credentials", "true");

    Response.Headers.Remove("Access-Control-Allow-Methods");
    Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}

Wait until all promises complete even if some rejected

var err;
Promise.all([
    promiseOne().catch(function(error) { err = error;}),
    promiseTwo().catch(function(error) { err = error;})
]).then(function() {
    if (err) {
        throw err;
    }
});

The Promise.all will swallow any rejected promise and store the error in a variable, so it will return when all of the promises have resolved. Then you can re-throw the error out, or do whatever. In this way, I guess you would get out the last rejection instead of the first one.