Programs & Examples On #Pia

Response to preflight request doesn't pass access control check

A very common cause of this error could be that the host API had mapped the request to a http method (e.g. PUT) and the API client is calling the API using a different http method (e.g. POST or GET)

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

Adding headers when using httpClient.GetAsync

You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

This doesn't just reference to POST-requests, you can also use it for GET-requests.

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

I accomplished something similar using jQuery Waypoints.

There's a lot of moving parts, and quite a bit of logic (that I hope to get on GitHub some day soon), but essentially what you could do is...

  1. Duplicate the table DOM structure in JavaScript and add a class called fixed.
  2. Add styles for table.fixed that make it invisible.
  3. Set a way point at the bottom of the header navigation that adds a class called sticky to table.fixed
  4. Add styles for table.sticky.fixed that position it just below the navbar and also make just the thead content visible. This also has a z-index so it is laid above the rest of the content.
  5. Add another waypoint, but in the downward scroll event, that removes .sticky from the table.fixed

You have to duplicate the entire table DOM in order to ensure column widths line up appropriately.

If that sounds really complicated, you might want to try playing around with the DataTables plugin and the FixedHeader extension: https://datatables.net/extensions/fixedheader/

How do I send a JSON string in a POST request in Go

In addition to standard net/http package, you can consider using my GoRequest which wraps around net/http and make your life easier without thinking too much about json or struct. But you can also mix and match both of them in one request! (you can see more details about it in gorequest github page)

So, in the end your code will become like follow:

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)
    request := gorequest.New()
    titleList := []string{"title1", "title2", "title3"}
    for _, title := range titleList {
        resp, body, errs := request.Post(url).
            Set("X-Custom-Header", "myvalue").
            Send(`{"title":"` + title + `"}`).
            End()
        if errs != nil {
            fmt.Println(errs)
            os.Exit(1)
        }
        fmt.Println("response Status:", resp.Status)
        fmt.Println("response Headers:", resp.Header)
        fmt.Println("response Body:", body)
    }
}

This depends on how you want to achieve. I made this library because I have the same problem with you and I want code that is shorter, easy to use with json, and more maintainable in my codebase and production system.

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');


JSFiddle: http://jsfiddle.net/VB59f/2

Cannot find Microsoft.Office.Interop Visual Studio

If you're using Visual Studio 2015 and you're encountering this problem, you can install MS Office Developer Tools for VS2015 here.

Disable password authentication for SSH

Here's a script to do this automatically

# Only allow key based logins
sed -n 'H;${x;s/\#PasswordAuthentication yes/PasswordAuthentication no/;p;}' /etc/ssh/sshd_config > tmp_sshd_config
cat tmp_sshd_config > /etc/ssh/sshd_config
rm tmp_sshd_config

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

To resolve the Could not load file or assembly 'System.Web.Http' error use NuGet to install the Web API 2.1 WebHost.

In solution explorer in the references right click and select manage nuget packages. (if not there install nuget)

enter image description here

In the manage NuGet Packages window on the left side click online then in top right search for Web Host and install Microsoft ASP.NET Web API 2.1 Web Host. (Once installed the install button will change to a green check)

After that the project will reload and when it's build again the error will be resolved and the project will debug and run. The error will be gone and you may be 'The resource cannot be found. Just append the url ( ex from localhost:52088/ to localhost:52088api/products )

Your question was good and helped me.

Hope this answer helps!

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are using PHPMyAdmin You can be solved this issue by doing this:

CAUTION: Don't use this solution if you want to maintain existing records in your table.

Step 1: Select database export method to custom:

enter image description here

Step 2: Please make sure to check truncate table before insert in data creation options:

enter image description here

Now you are able to import this database successfully.

ValueError: invalid literal for int () with base 10

I found a work around. Python will convert the number to a float. Simply calling float first then converting that to an int will work: output = int(float(input))

CSS - center two images in css side by side

Flexbox can do this with just two css rules on a surrounding div.

_x000D_
_x000D_
.social-media{_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

That's not exactly what I had in mind. What do you do if you have a generic type to only be known at runtime?

public MyDTO toObject() {
  try {
    var methodInfo = MethodBase.GetCurrentMethod();
    if (methodInfo.DeclaringType != null) {
      var fullName = methodInfo.DeclaringType.FullName + "." + this.dtoName;
      Type type = Type.GetType(fullName);
      if (type != null) {
        var obj = JsonConvert.DeserializeObject(payload);
      //var obj = JsonConvert.DeserializeObject<type.MemberType.GetType()>(payload);  // <--- type ?????
          ...
      }
    }

    // Example for java..   Convert this to C#
    return JSONUtil.fromJSON(payload, Class.forName(dtoName, false, getClass().getClassLoader()));
  } catch (Exception ex) {
    throw new ReflectInsightException(MethodBase.GetCurrentMethod().Name, ex);
  }
}

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

CSS white space at bottom of page despite having both min-height and height tag

I faced this issue because my web page was zoomed out to 90% and as I was viewing my page in responsive mode through the browser developer tools, I did not notice it right away.

What is the difference between buffer and cache memory in Linux?

Cache: This is a place acquired by kernel on physical RAM to store pages in caches. Now we need some sort of index to get the address of pages from caches. Here we need the buffer for page caches which keeps metadata of page cache.

Graph implementation C++

There can be an even simpler representation assuming that one has to only test graph algorithms not use them(graph) else where. This can be as a map from vertices to their adjacency lists as shown below :-

#include<bits/stdc++.h>
using namespace std;

/* implement the graph as a map from the integer index as a key to the   adjacency list
 * of the graph implemented as a vector being the value of each individual key. The
 * program will be given a matrix of numbers, the first element of each row will
 * represent the head of the adjacency list and the rest of the elements will be the
 * list of that element in the graph.
*/

typedef map<int, vector<int> > graphType;

int main(){

graphType graph;
int vertices = 0;

cout << "Please enter the number of vertices in the graph :- " << endl;
cin >> vertices;
if(vertices <= 0){
    cout << "The number of vertices in the graph can't be less than or equal to 0." << endl;
    exit(0);
}

cout << "Please enter the elements of the graph, as an adjacency list, one row after another. " << endl;
for(int i = 0; i <= vertices; i++){

    vector<int> adjList;                    //the vector corresponding to the adjacency list of each vertex

    int key = -1, listValue = -1;
    string listString;
    getline(cin, listString);
    if(i != 0){
        istringstream iss(listString);
        iss >> key;
        iss >> listValue;
        if(listValue != -1){
            adjList.push_back(listValue);
            for(; iss >> listValue; ){
                adjList.push_back(listValue);
            }
            graph.insert(graphType::value_type(key, adjList));
        }
        else
            graph.insert(graphType::value_type(key, adjList));
    }
}

//print the elements of the graph
cout << "The graph that you entered :- " << endl;
for(graphType::const_iterator iterator = graph.begin(); iterator != graph.end(); ++iterator){
    cout << "Key : " << iterator->first << ", values : ";

    vector<int>::const_iterator vectBegIter = iterator->second.begin();
    vector<int>::const_iterator vectEndIter = iterator->second.end();
    for(; vectBegIter != vectEndIter; ++vectBegIter){
        cout << *(vectBegIter) << ", ";
    }
    cout << endl;
}
}

How to implement the factory method pattern in C++ correctly

I don't try to answer all of my questions, as I believe it is too broad. Just a couple of notes:

there are cases when object construction is a task complex enough to justify its extraction to another class.

That class is in fact a Builder, rather than a Factory.

In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.

Then you could have your factory encapsulate it in a smart pointer. I believe this way you can have your cake and eat it too.

This also eliminates the issues related to return-by-value.

Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.

Indeed. All design patterns have their (language specific) constraints and drawbacks. It is recommended to use them only when they help you solve your problem, not for their own sake.

If you are after the "perfect" factory implementation, well, good luck.

AttributeError: 'module' object has no attribute 'urlopen'

your code used in python2.x, you can use like this:

from urllib.request import urlopen
urlopen(url)

by the way, suggest another module called requests is more friendly to use, you can use pip install it, and use like this:

import requests
requests.get(url)
requests.post(url)

I thought it is easily to use, i am beginner too....hahah

Peak detection in a 2D array

Just a couple of ideas off the top of my head:

  • take the gradient (derivative) of the scan, see if that eliminates the false calls
  • take the maximum of the local maxima

You might also want to take a look at OpenCV, it's got a fairly decent Python API and might have some functions you'd find useful.

Is there a limit on an Excel worksheet's name length?

I use the following vba code where filename is a string containing the filename I want, and Function RemoveSpecialCharactersAndTruncate is defined below:

worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename)

'Function to remove special characters from file before saving

Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$)
    Dim IllegalCharacterSet$
    Dim i As Integer
'Set of illegal characters
    IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=,"
    'Iterate through illegal characters and replace any instances
    For i = 1 To Len(IllegalCharacterSet) - 1
        FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "")
    Next
    'Return the value capped at 31 characters (Excel limit)
    RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _
                           Application.WorksheetFunction.Min(Len(FormattedString), 31))
End Function

How to disable anchor "jump" when loading a page?

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

Faster way to zero memory than with memset?

x86 is rather broad range of devices.

For totally generic x86 target, an assembly block with "rep movsd" could blast out zeros to memory 32-bits at time. Try to make sure the bulk of this work is DWORD aligned.

For chips with mmx, an assembly loop with movq could hit 64bits at a time.

You might be able to get a C/C++ compiler to use a 64-bit write with a pointer to a long long or _m64. Target must be 8 byte aligned for the best performance.

for chips with sse, movaps is fast, but only if the address is 16 byte aligned, so use a movsb until aligned, and then complete your clear with a loop of movaps

Win32 has "ZeroMemory()", but I forget if thats a macro to memset, or an actual 'good' implementation.

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

The only elasticsearch vs solr performance comparison I've been able to find so far is here:

Solr vs elasticsearch Deathmatch!

Web Reference vs. Service Reference

Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.

If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.

Why can't decimal numbers be represented exactly in binary?

If you make a big enough number with floating point (as it can do exponents), then you'll end up with inexactness in front of the decimal point, too. So I don't think your question is entirely valid because the premise is wrong; it's not the case that shifting by 10 will always create more precision, because at some point the floating point number will have to use exponents to represent the largeness of the number and will lose some precision that way as well.

Is System.nanoTime() completely useless?

I am linking to what essentially is the same discussion where Peter Lawrey is providing a good answer. Why I get a negative elapsed time using System.nanoTime()?

Many people mentioned that in Java System.nanoTime() could return negative time. I for apologize for repeating what other people already said.

  1. nanoTime() is not a clock but CPU cycle counter.
  2. Return value is divided by frequency to look like time.
  3. CPU frequency may fluctuate.
  4. When your thread is scheduled on another CPU, there is a chance of getting nanoTime() which results in a negative difference. That's logical. Counters across CPUs are not synchronized.
  5. In many cases, you could get quite misleading results but you wouldn't be able to tell because delta is not negative. Think about it.
  6. (unconfirmed) I think you may get a negative result even on the same CPU if instructions are reordered. To prevent that, you'd have to invoke a memory barrier serializing your instructions.

It'd be cool if System.nanoTime() returned coreID where it executed.

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

Change label text using JavaScript

Because your script runs BEFORE the label exists on the page (in the DOM). Either put the script after the label, or wait until the document has fully loaded (use an OnLoad function, such as the jQuery ready() or http://www.webreference.com/programming/javascript/onloads/)

This won't work:

<script>
  document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
<label id="lbltipAddedComment">test</label>

This will work:

<label id="lbltipAddedComment">test</label>
<script>
  document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>

This example (jsfiddle link) maintains the order (script first, then label) and uses an onLoad:

<label id="lbltipAddedComment">test</label>
<script>
function addLoadEvent(func) {  
      var oldonload = window.onload;  
      if (typeof window.onload != 'function') {  
        window.onload = func;  
      } else {  
        window.onload = function() {  
          if (oldonload) {  
            oldonload();  
          }  
          func();  
        }  
      }  
    }  

   addLoadEvent(function() {  
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';

    });  
</script>

Convert .class to .java

This is for Mac users:

first of all you have to clarify where the class file is... so for example, in 'Terminal' (A Mac Application) you would type:

cd

then wherever you file is e.g:

cd /Users/CollarBlast/Desktop/JavaFiles/

then you would hit enter. After that you would do the command. e.g:

cd /Users/CollarBlast/Desktop/JavaFiles/ (then i would press enter...)

Then i would type the command:

javap -c JavaTestClassFile.class (then i would press enter again...)

and hopefully it should work!

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

How to find index position of an element in a list when contains returns true

Here is an example:

List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2

How to reset the bootstrap modal when it gets closed and open it fresh again?

Reset form inside the modal. Sample Code:

$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
    $('#myModal form')[0].reset();
});

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

As another option, you can do look ups like:

class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')

    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'

Dynamic height for DIV

You should be okay to just take the height property out of the CSS.

Select subset of columns in data.table R

If it's not mandatory to specify column names:

> cor(dt[, !c(1:3, 5)])
             V4          V6          V7         V8          V9         V10
V4   1.00000000 -0.50472635 -0.07123705  0.9089868 -0.17232607 -0.77988709
V6  -0.50472635  1.00000000  0.05757776 -0.2374420  0.67334474  0.29476983
V7  -0.07123705  0.05757776  1.00000000 -0.1812176 -0.36093750  0.01102428
V8   0.90898683 -0.23744196 -0.18121755  1.0000000  0.21372140 -0.75798418
V9  -0.17232607  0.67334474 -0.36093750  0.2137214  1.00000000 -0.01179544
V10 -0.77988709  0.29476983  0.01102428 -0.7579842 -0.01179544  1.00000000

How to avoid Sql Query Timeout

My team were experiencing these issues intermittently with long running SSIS packages. This has been happening since Windows server patching.

Our SSIS and SQL servers are on separate VM servers.

Working with our Wintel Servers team we rebooted both servers and for the moment, the problem appears to have gone away.

The engineer has said that they're unsure if the issue is the patches or new VMTools that they updated at the same time. We'll monitor for now and if the timeout problems recur, they'll try rolling back the VMXNET3 driver, first, then if that doesn't work, take off the June Rollup patches.

So for us the issue is nothing to do with our SQL Queries (we're loading billions of new rows so it has to be long running).

Git - How to use .netrc file on Windows to save user and password

Is it possible to use a .netrc file on Windows?

Yes: You must:

  • define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)
  • put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.
Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":
git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

??? believes in the comments that "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page): . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".


A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://[email protected]/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.


With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).
On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.
Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"


With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

How can I be notified when an element is added to the page?

You can use livequery plugin for jQuery. You can provide a selector expression such as:

$("input[type=button].removeItemButton").livequery(function () {
    $("#statusBar").text('You may now remove items.');
});

Every time a button of a removeItemButton class is added a message appears in a status bar.

In terms of efficiency you might want avoid this, but in any case you could leverage the plugin instead of creating your own event handlers.

Revisited answer

The answer above was only meant to detect that an item has been added to the DOM through the plugin.

However, most likely, a jQuery.on() approach would be more appropriate, for example:

$("#myParentContainer").on('click', '.removeItemButton', function(){
          alert($(this).text() + ' has been removed');
});

If you have dynamic content that should respond to clicks for example, it's best to bind events to a parent container using jQuery.on.

'\r': command not found - .bashrc / .bash_profile

For those who don't have dos2unix installed (and don't want to install it):

Remove trailing \r character that causes this error:

sed -i 's/\r$//' filename


Explanation:

Option -i is for in-place editing, we delete the trailing \r directly in the input file. Thus be careful to type the pattern correctly.

JavaScript variable assignments from tuples

Here is a simple Javascript Tuple implementation:

var Tuple = (function () {
   function Tuple(Item1, Item2) {
      var item1 = Item1;
      var item2 = Item2;
      Object.defineProperty(this, "Item1", {
          get: function() { return item1  }
      });
      Object.defineProperty(this, "Item2", {
          get: function() { return item2  }
      });
   }
   return Tuple;
})();

var tuple = new Tuple("Bob", 25); // Instantiation of a new Tuple
var name = tuple.Item1; // Assignment. name will be "Bob"
tuple.Item1 = "Kirk"; // Will not set it. It's immutable.

This is a 2-tuple, however, you could modify my example to support 3,4,5,6 etc. tuples.

Node.js connect only works on localhost

Most probably your server socket is bound to the loopback IP address 127.0.0.1 instead of the "all IP addresses" symbolic IP 0.0.0.0 (note this is NOT a netmask). To confirm this, run sudo netstat -ntlp (If you are on linux) or netstat -an -f inet -p tcp | grep LISTEN (OSX) and check which IP your process is bound to (look for the line with ":3000"). If you see "127.0.0.1", that's the problem. Fix it by passing "0.0.0.0" to the listen call:

var app = connect().use(connect.static('public')).listen(3000, "0.0.0.0");

Escaping special characters in Java Regular Expressions

I wrote this pattern:

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

And use it in this method:

String escapeSpecialRegexChars(String str) {

    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

Then you can use it like this, for example:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}

We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*\\Q" + text + "\\E.*")
}

How can I tell how many objects I've stored in an S3 bucket?

From the command line in AWS CLI, use ls plus --summarize. It will give you the list of all of your items and the total number of documents in a particular bucket. I have not tried this with buckets containing sub-buckets:

aws s3 ls "s3://MyBucket" --summarize

It make take a bit long (it took listing my 16+K documents about 4 minutes), but it's faster than counting 1K at a time.

Defining a percentage width for a LinearLayout?

I solved a similar issue applying some padding to the LinearLayout like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/app_background"
    android:padding="35dip">

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/black">

</RelativeLayout>
</LinearLayout>

This probably won't give you an exact percentage but can be easily graduated and avoid extra unnecessary layout elements.

How to access Spring MVC model object in javascript file?

JavaScript is run on the client side. Your model does not exist on the client side, it only exists on the server side while you are rendering your .jsp.

If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.

Update:

A simple example

<%-- SomeJsp.jsp --%>
<script>var paramOne =<c:out value="${paramOne}"/></script>

What does "to stub" mean in programming?

This phrase is almost certainly an analogy with a phase in house construction — "stubbing out" plumbing. During construction, while the walls are still open, the rough plumbing is put in. This is necessary for the construction to continue. Then, when everything around it is ready enough, one comes back and adds faucets and toilets and the actual end-product stuff. (See for example How to Install a Plumbing Stub-Out.)

When you "stub out" a function in programming, you build enough of it to work around (for testing or for writing other code). Then, you come back later and replace it with the full implementation.

How can you dynamically create variables via a while loop?

Use the exec() method. For example, say you have a dictionary and you want to turn each key into a variable with its original dictionary value can do the following.

Python 2

>>> c = {"one": 1, "two": 2}
>>> for k,v in c.iteritems():
...    exec("%s=%s" % (k,v))

>>> one
1
>>> two
2

Python 3

>>> c = {"one": 1, "two": 2}
>>> for k,v in c.items():
...    exec("%s=%s" % (k,v))

>>> one
1
>>> two
2

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

Laravel - check if Ajax request

Maybe this helps. You have to refer the @param

         /**       
         * Display a listing of the resource.
         *
         * @param  Illuminate\Http\Request $request
         * @return Response
         */
        public function index(Request $request)
        {
            if($request->ajax()){
                return "AJAX";
            }
            return "HTTP";
        }

Create a temporary table in MySQL with an index from a select

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement

Example :

CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

In Bash, how can I check if a string begins with some value?

If you're using a recent version of Bash (v3+), I suggest the Bash regex comparison operator =~, for example,

if [[ "$HOST" =~ ^user.* ]]; then
    echo "yes"
fi

To match this or that in a regex, use |, for example,

if [[ "$HOST" =~ ^user.*|^host1 ]]; then
    echo "yes"
fi

Note - this is 'proper' regular expression syntax.

  • user* means use and zero-or-more occurrences of r, so use and userrrr will match.
  • user.* means user and zero-or-more occurrences of any character, so user1, userX will match.
  • ^user.* means match the pattern user.* at the begin of $HOST.

If you're not familiar with regular expression syntax, try referring to this resource.

Dynamic Height Issue for UITableView Cells (Swift)

For objective c this is one of my nice solution. it's worked for me.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.text = [_nameArray objectAtIndex:indexPath.row];
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

We need to apply these 2 changes.

1)cell.textLabel.numberOfLines = 0;
  cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;

2)return UITableViewAutomaticDimension;

Alert handling in Selenium WebDriver (selenium 2) with Java

Write the following method:

public boolean isAlertPresent() {
    try {
        driver.switchTo().alert();
        return true;
    } // try
    catch (Exception e) {
        return false;
    } // catch
}

Now, you can check whether alert is present or not by using the method written above as below:

if (isAlertPresent()) {
    driver.switchTo().alert();
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();
}

Select a date from date picker using Selenium webdriver

There is an argument for keeping it simple and stupid if the date picker comes from a simple html5 input and the goal is to test whatever events were added to the test. Consider for example:

<input type=date name=mydate /> 

and one wants to set a test where 'mydate' is hardcoded to 02/22/2017, a solution with python is to use the following code, which is simple enough to debug to observe what it does:

def setdate(elem_name, date_str):
    elem = driver.find_element_by_name('mydate')
    elem.click()
    elem.send_keys(Keys.ARROW_LEFT)
    elem.send_keys(Keys.ARROW_LEFT)
    elem.send_keys(date_str)

setdate('mydate'', '02222017')

How to import other Python files?

There are couple of ways of including your python script with name abc.py

  1. e.g. if your file is called abc.py (import abc) Limitation is that your file should be present in the same location where your calling python script is.

import abc

  1. e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.

from folder import abc

  1. Incase abc.py script is available insider internal_folder which is present inside folder

from folder.internal_folder import abc

  1. As answered by James above, in case your file is at some fixed location

import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule

In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)

%load_ext autoreload 
%autoreload 2

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

Javascript Regexp dynamic generation from variables?

You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.

var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Accessing dictionary value by index in python

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

Uncaught TypeError: (intermediate value)(...) is not a function

I have faced this issue when I created a new ES2015 class where the property name was equal to the method name.

e.g.:

class Test{
  constructor () {
    this.test = 'test'
  }

  test (test) {
    this.test = test
  }
}

let t = new Test()
t.test('new Test')

Please note this implementation was in NodeJS 6.10.

As a workaround (if you do not want to use the boring 'setTest' method name), you could use a prefix for your 'private' properties (like _test).

Open your Developer Tools in jsfiddle.

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

What’s the best way to load a JSONObject from a json text file?

Another way of doing the same could be using the Gson Class

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.

How do I find out what License has been applied to my SQL Server installation?

I know this post is older, but haven't seen a solution that provides the actual information, so I want to share what I use for SQL Server 2012 and above. the link below leads to the screenshot showing the information.

First (so no time is wasted):

SQL Server 2000:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')

SQL Server 2005+

The "SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')" is not in use anymore. You can see more details on MSFT documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql?view=sql-server-2017

SQL Server 2005 - 2008R2 you would have to:

Using PowerShell: https://www.ryadel.com/en/sql-server-retrieve-product-key-from-an-existing-installation/

Using TSQL (you would need to know the registry key path off hand): https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-server-registry-transact-sql?view=sql-server-2017

SQL Server 2012+

Now, you can extract SQL Server Licensing information from the SQL Server Error Log, granted it may not be formatted the way you want, but the information is there and can be parsed, along with more descriptive information that you probably didn't expect.

EXEC sp_readerrorlog @p1 = 0
                    ,@p2 = 1
                    ,@p3 = N'licensing'

NOTE: I tried pasting the image directly, but since I am new at stakoverflow we have to follow the link below.

SQL Server License information via sp_readerrorlog

How do I create a new user in a SQL Azure database?

I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/

It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager database role

I used this and Stuart's answer to do the following:
On the master database (see link as to who has permissions on this):

CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'

And then on the database in question:

CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]

You can also create users like this, according to the link:

CREATE USER [[email protected]] FROM EXTERNAL PROVIDER;

Clearing a string buffer/builder after loop

One option is to use the delete method as follows:

StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
   sb.append("a");

   // This will clear the buffer
   sb.delete(0, sb.length());
}

Another option (bit cleaner) uses setLength(int len):

sb.setLength(0);

See Javadoc for more info:

Get class name using jQuery

Try it

HTML

<div class="class_area-1">
    area 1
</div>

<div class="class_area-2">
    area 2
</div>

<div class="class_area-3">
    area 3
</div>

jQuery

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="application/javascript">
    $('div').click(function(){
        alert($(this).attr('class'));
    });
</script>

Xcode/Simulator: How to run older iOS version?

To add previous iOS simulator to Xcode 4.2, you need old xcode_3.2.6_and_ios_sdk_4.3.dmg (or similar version) installer file and do as following:

  • Mount the xcode_3.2.6_and_ios_sdk_4.3.dmg file
  • Open mounting disk image and choose menu: Go->Go to Folder...
  • Type /Volumes/Xcode and iOS SDK/Packages/ then click Go. There are many packages and find to iPhoneSimulatorSDK(version).pkg
  • Double click to install package you want to add and wait for installer displays.
  • In Installer click Continue and choose destination, Choose folder...
  • Explorer shows and select Developer folder and click Choose
  • Install and repeat with other simulator as you need.
  • Restart Xcode.

Now there are a list of your installed simulator.

How do I disable form fields using CSS?

It's very curious that you have visible and display properties in CSS but not enable/disable.

It's very curious that you think that's very curious. You're misunderstanding the purpose of CSS. CSS is not meant to change the behavior of form elements. It's meant to change their style only. Hiding a text field doesn't mean the text field is no longer there or that the browser won't send its data when you submit the form. All it does is hide it from the user's eyes.

To actually disable your fields, you must use the disabled attribute in HTML or the disabled DOM property in JavaScript.

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

display data from SQL database into php/ html table

You say you have a database on PhpMyAdmin, so you are using MySQL. PHP provides functions for connecting to a MySQL database.

$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');

$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";  //$row['index'] the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection

In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.

This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.

How to add 20 minutes to a current date?

Add it in milliseconds:

var currentDate = new Date();
var twentyMinutesLater = new Date(currentDate.getTime() + (20 * 60 * 1000));

How to undo a git merge with conflicts

Sourcetree

If you not commit your merge, then just double click on another branch (=checkout) and when sourcetree ask you about discarding all changes then agree

How to find the most recent file in a directory using .NET, and without looping?

Another approach if you are using Directory.EnumerateFiles and want to read files in latest modified by first.

foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))

}

Troubleshooting "Illegal mix of collations" error in mysql

You can try this script, that converts all of your databases and tables to utf8.

How to set up tmux so that it starts up with specified windows opened?

You should specify it in your tmux config file (~/.tmux.conf), for example:

new mocp
neww mutt

new -d
neww
neww

(opens one session with 2 windows with mocp launched in first and mutt in second, and another detached session with 3 empty windows).

How to view .img files?

OSFMount , MagicDisc , Gizmo Director/Gizmo Drive , The Takeaway .

All these work well on .img files

How to iterate through SparseArray?

Seems I found the solution. I hadn't properly noticed the keyAt(index) function.

So I'll go with something like this:

for(int i = 0; i < sparseArray.size(); i++) {
   int key = sparseArray.keyAt(i);
   // get the object by the key.
   Object obj = sparseArray.get(key);
}

Calculating arithmetic mean (one type of average) in Python

def avg(l):
    """uses floating-point division."""
    return sum(l) / float(len(l))

Examples:

l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]

print(avg(l1)) # 9.0
print(avg(l2)) # 0.0

How to put comments in Django templates

This way can be helpful if you want to comment some Django Template format Code.

{#% include 'file.html' %#} (Right Way)

Following code still executes if commented with HTML Comment.

<!-- {% include 'file.html' %} --> (Wrong Way)

How to implement OnFragmentInteractionListener

I'd like to add the destruction of the listener when the fragment is detached from the activity or destroyed.

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

and when using the new onStart() method with Context

@Override
public void onDestroy() {
    super.onDestroy();
    mListener = null;
}

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

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

How to edit a JavaScript alert box title?

You can do this in IE:

<script language="VBScript">
Sub myAlert(title, content)
      MsgBox content, 0, title
End Sub
</script>

<script type="text/javascript">
myAlert("My custom title", "Some content");
</script>

(Although, I really wish you couldn't.)

Is there a way to represent a directory tree in a Github README.md?

I got resolver the problem in this way:

  1. Insert command tree in bash.

Example

enter image description here

  1. Create a README.md in github repository and copy bash result
  2. Insert in .md file within markdown code

Example

enter image description here 4. See the output and be happy =) enter image description here

Mongodb service won't start

Delete the .lock file from the C:\mongodb\data\ path and then restart the mongodb service.

Set position / size of UI element as percentage of screen size

I think what you want is to set the android:layout_weight,

http://developer.android.com/resources/tutorials/views/hello-linearlayout.html

something like this (I'm just putting text views above and below as placeholders):

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="68"/>
    <Gallery 
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="0dp"

        android:layout_weight="16"
    />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="16"/>

  </LinearLayout>

http://localhost/ not working on Windows 7. What's the problem?

Well you are getting a 404, so the web server is running, it just can't find the file.

Check the http.conf file. If it pointing to the right root directory?

If you are using different ports, then check http.conf to see if Apache is listening on the right port, or if apache is redirecting traffic on the port to anther root directory.

Maybe posting your http.conf file might help?

How to display HTML in TextView?

You can use simple Kotlin extension function like this:

fun TextView.setHtmlText(source: String) {
    this.text = HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

And usage:

textViewMessage.setHtmlText("Message: <b>Hello World</b>")

LINQ: "contains" and a Lambda query

If I understand correctly, you need to convert the type (char value) that you store in Building list to the type (enum) that you store in buildingStatus list.

(For each status in the Building list//character value//, does the status exists in the buildingStatus list//enum value//)

public static IQueryable<Building> WithStatus(this IQueryable<Building> qry,  
IList<BuildingStatuses> buildingStatus) 
{ 
    return from v in qry
           where ContainsStatus(v.Status)
           select v;
} 


private bool ContainsStatus(v.Status)
{
    foreach(Enum value in Enum.GetValues(typeof(buildingStatus)))
    {
        If v.Status == value.GetCharValue();
            return true;
    }

    return false;
}

Java Comparator class to sort arrays

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

Android: how do I check if activity is running?

Found an easy workaround with the following code

@Override 
protected void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
                // Activity is being brought to front and not being  created again, 
                // Thus finishing this activity will bring the last viewed activity to foreground
                finish(); 
            } 
    }

Read/Write String from/to a File in Android

the first thing we need is the permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

so in an asyncTask Kotlin class, we treat the creation of the file

    import android.os.AsyncTask
    import android.os.Environment
    import android.util.Log
    import java.io.*
    class WriteFile: AsyncTask<String, Int, String>() {
        private val mFolder = "/MainFolder"
        lateinit var folder: File
        internal var writeThis = "string to cacheApp.txt"
        internal var cacheApptxt = "cacheApp.txt"
        override fun doInBackground(vararg writethis: String): String? {
            val received = writethis[0]
            if(received.isNotEmpty()){
                writeThis = received
            }
            folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
            if(!folder.exists()){
                folder.mkdir()
                val readME = File(folder, cacheApptxt)
                val file = File(readME.path)
                val out: BufferedWriter
                try {
                    out = BufferedWriter(FileWriter(file, true), 1024)
                    out.write(writeThis)
                    out.newLine()
                    out.close()
                    Log.d("Output_Success", folder.path)
                } catch (e: Exception) {
                    Log.d("Output_Exception", "$e")
                }
            }
            return folder.path

    }

        override fun onPostExecute(result: String) {
            super.onPostExecute(result)

            if(result.isNotEmpty()){
                //implement an interface or do something
                Log.d("onPostExecuteSuccess", result)
            }else{
                Log.d("onPostExecuteFailure", result)
            }
        }

    }

Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this

    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Build
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat

    class ReadandWrite {
        private val mREAD = 9
        private val mWRITE = 10
        private var readAndWrite: Boolean = false
        fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
            if (Build.VERSION.SDK_INT < 23) {
                readAndWrite = true
            } else {
                val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
                val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                if (mRead != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
                } else {
                    readAndWrite = true
                }

                if (mWrite != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
                } else {
                    readAndWrite = true
                }
            }
            return readAndWrite
        }
    }

then in an activity, execute the call.

  var pathToFileCreated = ""
    val anRW = ReadandWrite().readAndwriteStorage(this,this)
    if(anRW){
        pathToFileCreated =  WriteFile().execute("onTaskComplete").get()
        Log.d("pathToFileCreated",pathToFileCreated)
    }

Best solution to protect PHP code without encryption

in my opinion is, but just in case if your php code program is written for standalone model... best solutions is c) You could wrap the php in a container like Phalanger (.NET). as everyone knows it's bind tightly to the system especially if your program is intended for windows users. you just can make your own protection algorithm in windows programming language like .NET/VB/C# or whatever you know in .NET prog.lang.family sets.

Set width of a "Position: fixed" div relative to parent div

I´m not sure as to what the second problem is (based on your edit), but if you apply width:inherit to all inner divs, it works: http://jsfiddle.net/4bGqF/9/

You might want to look into a javascript solution for browsers that you need to support and that don´t support width:inherit

Pyinstaller setting icons don't change

I know this is old and whatnot (and not exactly sure if it's a question), but after searching, I had success with this command for --onefile:

pyinstaller.exe --onefile --windowed --icon=app.ico app.py

Google led me to this page while I was searching for an answer on how to set an icon for my .exe, so maybe it will help someone else.

The information here was found at this site: https://mborgerson.com/creating-an-executable-from-a-python-script

Create Excel file in Java

Flat files do not allow providing meta information.

I would suggest writing out a HTML table containing the information you need, and let Excel read it instead. You can then use <b> tags to do what you ask for.

What is the facade design pattern?

Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html

What are metaclasses in Python?

Note that in python 3.6 a new dunder method __init_subclass__(cls, **kwargs) was introduced to replace a lot of common use cases for metaclasses. Is is called when a subclass of the defining class is created. See python docs.

ORA-00918: column ambiguously defined in SELECT *

You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:

SELECT DISTINCT
    coaches.id,
    people.*,
    users.*,
    coaches.*
FROM "COACHES"
    INNER JOIN people ON people.id = coaches.person_id
    INNER JOIN users ON coaches.person_id = users.person_id
    LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
    rownum <= 25

It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.

How to find which version of Oracle is installed on a Linux server (In terminal)

As the user running the Oracle Database one can also try $ORACLE_HOME/OPatch/opatch lsinventory which shows the exact version and patches installed.

For example this is a quick oneliner which should only return the version number:

$ORACLE_HOME/OPatch/opatch lsinventory | awk '/^Oracle Database/ {print $NF}'

How to get root directory in yii2

To get the base URL you can use this (would return "http:// localhost/yiistore2/upload")

Yii::app()->baseUrl

The following Code would return just "localhost/yiistore2/upload" without http[s]://

Yii::app()->getBaseUrl(true)

Or you could get the webroot path (would return "d:\wamp\www\yii2store")

Yii::getPathOfAlias('webroot')

How to get time in milliseconds since the unix epoch in Javascript?

Date.now() returns a unix timestamp in milliseconds.

_x000D_
_x000D_
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
_x000D_
_x000D_

Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:

_x000D_
_x000D_
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
_x000D_
_x000D_

Finding the index of elements based on a condition using python list comprehension

Another way:

>>> [i for i in range(len(a)) if a[i] > 2]
[2, 5]

In general, remember that while find is a ready-cooked function, list comprehensions are a general, and thus very powerful solution. Nothing prevents you from writing a find function in Python and use it later as you wish. I.e.:

>>> def find_indices(lst, condition):
...   return [i for i, elem in enumerate(lst) if condition(elem)]
... 
>>> find_indices(a, lambda e: e > 2)
[2, 5]

Note that I'm using lists here to mimic Matlab. It would be more Pythonic to use generators and iterators.

Maven Modules + Building a Single Specific Module

Any best practices here?

Use the Maven advanced reactor options, more specifically:

-pl, --projects
        Build specified reactor projects instead of all projects
-am, --also-make
        If project list is specified, also build projects required by the list

So just cd into the parent P directory and run:

mvn install -pl B -am

And this will build B and the modules required by B.

Note that you need to use a colon if you are referencing an artifactId which differs from the directory name:

mvn install -pl :B -am

As described here: https://stackoverflow.com/a/26439938/480894

Copy multiple files with Ansible

You can loop through variable with list of directories:

- name: Copy files from several directories
  copy:
    src: "{{ item }}"
    dest: "/etc/fooapp/"
    owner: root
    mode: "0600"
  loop: "{{ files }}"
  vars:
    files:
      - "dir1/"
      - "dir2/"

Cannot make Project Lombok work on Eclipse

Did you add

-vmargs
...
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar

to your eclipse.ini?

Because if you have (and if you have added the lombok.jar to the libraries used by your project), it works just fine with Eclipse Helios:

alt text


Ian Tegebo mentions in the comments that:

a simple "restart" was not sufficient to pick up the changed vmargs:
I needed to explicitly exit and then start again.


chrisjleu mentions in the comments:

If you happen to be running a customized Eclipse Helios (3.6+) distribution then you may have to use the full path to lombok.jar in both the vm arguments.
See commit b47e87f for more details.

boolean fullPathRequired = IdeFinder.getOS() == EclipseFinder.OS.UNIX || System.getProperty("lombok.installer.fullpath") != null;

Excel formula to reference 'CELL TO THE LEFT'

If you change your cell reference to use R1C1 notation (Tools|Options, General tab), then you can use a simple notation and paste it into any cell.

Now your formula is simply:

=RC[-1]

How do I install cURL on cygwin?

In order to install any package,we must first find the setup.exe file.I could not locate this file.so i downloaded this file (or you can do a wget).I am on windows64 bit.So ,if you go to https://cygwin.com/install.html ,you can download setup-x86_64.exe file from the install and updates section,move this setup-x86_64.exe to your c:/cygwin64,and then run it from there ( setup-x86_64.exe -q -P curl)

customize Android Facebook Login button

In newer Facebook SDK, the login and logout text name is :

 <com.facebook.login.widget.LoginButton
 xmlns:facebook="http://schemas.android.com/apk/res-auto"
 facebook:com_facebook_login_text=""
 facebook:com_facebook_logout_text=""/>

Retrieve list of tasks in a queue in Celery

This worked for me in my application:

def get_celery_queue_active_jobs(queue_name):
    connection = <CELERY_APP_INSTANCE>.connection()

    try:
        channel = connection.channel()
        name, jobs, consumers = channel.queue_declare(queue=queue_name, passive=True)
        active_jobs = []

        def dump_message(message):
            active_jobs.append(message.properties['application_headers']['task'])

        channel.basic_consume(queue=queue_name, callback=dump_message)

        for job in range(jobs):
            connection.drain_events()

        return active_jobs
    finally:
        connection.close()

active_jobs will be a list of strings that correspond to tasks in the queue.

Don't forget to swap out CELERY_APP_INSTANCE with your own.

Thanks to @ashish for pointing me in the right direction with his answer here: https://stackoverflow.com/a/19465670/9843399

How to disable phone number linking in Mobile Safari?

I use a zero-width joiner &zwj;

Just put that somewhere in the phone number and it works for me. Tested in BrowserStack (and Litmus for emails).

Is there an easy way to reload css without reloading the page?

i now have this:

    function swapStyleSheet() {
        var old = $('#pagestyle').attr('href');
        var newCss = $('#changeCss').attr('href');
        var sheet = newCss +Math.random(0,10);
        $('#pagestyle').attr('href',sheet);
        $('#profile').attr('href',old);
        }
    $("#changeCss").on("click", function(event) { 
        swapStyleSheet();
    } );

make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:

<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />

<img src="click.jpg" id="changeCss" href="css2.css?t=">

conversion from infix to prefix

simple google search came up with this. Doubt anyone can explain this any simpler. But I guess after an edit, I can try to bring forward the concepts so that you can answer your own question.

Hint :

Study for exam, hard, you must. Predict you, grade get high, I do :D

Explanation :

It's all about the way operations are associated with operands. each notation type has its own rules. You just need to break down and remember these rules. If I told you I wrote (2*2)/3 as [* /] (2,2,3) all you need to do is learn how to turn the latter notation in the former notation.

My custom notation says that take the first two operands and multiple them, then the resulting operand should be divided by the third. Get it ? They are trying to teach you three things.

  1. To become comfortable with different notations. The example I gave is what you will find in assembly languages. operands (which you act on) and operations (what you want to do to the operands).
  2. Precedence rules in computing do not necessarily need to follow those found in mathematics.
  3. Evaluation: How a machine perceives programs, and how it might order them at run-time.

How to get the list of properties of a class?

Based on @MarcGravell's answer, here's a version that works in Unity C#.

ObjectsClass foo = this;
foreach(var prop in foo.GetType().GetProperties()) {
    Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
}

Form submit with AJAX passing form data to PHP without page refresh

$(document).ready(function(){
$('#userForm').on('submit', function(e){
        e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit. 
// This solved the problem.
        e.stopImmediatePropagation();
    // show that something is loading
    $('#response').html("<b>Loading data...</b>");

    // Call ajax for pass data to other place
    $.ajax({
    type: 'POST',
    url: 'somephpfile.php',
    data: $(this).serialize() // getting filed value in serialize form
    })
    .done(function(data){ // if getting done then call.

    // show the response
    $('#response').html(data);

    })
    .fail(function() { // if fail then getting message

    // just in case posting your form failed
    alert( "Posting failed." );

    });

    // to prevent refreshing the whole page page
    return false;

    });

How to get milliseconds from LocalDateTime in Java 8

Why didn't anyone mentioned the method LocalDateTime.toEpochSecond():

LocalDateTime localDateTime = ... // whatever e.g. LocalDateTime.now()
long time2epoch = localDateTime.toEpochSecond(ZoneOffset.UTC);

This seems way shorter that many suggested answers above...

How to change the height of a div dynamically based on another div using css?

The simplest way to get equal height columns, without the ugly side effects that come along with absolute positioning, is to use the display: table properties:

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: table;
}

.div2, .div3 {
  display: table-cell;
}
.div2 {
  width:150px;
  height:auto;
  background-color: #F4A460;  

}
.div3 {
  width:150px;
  height:auto;
  background-color: #FFFFE0;  
}

http://jsfiddle.net/E4Zgj/21/


Now, if your goal is to have .div2 so that it is only as tall as it needs to be to contain its content while .div3 is at least as tall as .div2 but still able to expand if its content makes it taller than .div2, then you need to use flexbox. Flexbox support isn't quite there yet (IE10, Opera, Chrome. Firefox follows an old spec, but is following the current spec soon).

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: flex;
  align-items: flex-start;
}

.div2 {
  width:150px;
  background-color: #F4A460;
}

.div3 {
  width:150px;
  background-color: #FFFFE0;
  align-self: stretch;
}

http://jsfiddle.net/E4Zgj/22/

Turn off deprecated errors in PHP 5.3

I needed to adapt this to

error_reporting = E_ALL & ~E_DEPRECATED

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Don't convert line endings. It's not the VCS's job to interpret data -- just store and version it. Every modern text editor can read both kinds of line endings anyway.

How to remove the URL from the printing page?

On Chrome 57 the following worked for me, if you have control of the HTML page that needs to be printed (in my case I needed to print a small 3x1 inch label):

  • remove the HTML title element from header (either temporarily using jquery or permanently if that page does not really need a title)
  • set the @page margin to 0 as mentioned by @Chamika Sandamal

This resulted in printing a page that only contained the body text, no URLs, no page #s etc.

Saving changes after table edit in SQL Server Management Studio

Many changes you can make very easily and visually in the table editor in SQL Server Management Studio actually require SSMS to drop the table in the background and re-create it from scratch. Even simple things like reordering the columns cannot be expressed in standard SQL DDL statement - all SSMS can do is drop and recreate the table.

This operation can be a) very time consuming on a large table, or b) might even fail for various reasons (like FK constraints and stuff). Therefore, SSMS in SQL Server 2008 introduced that new option the other answers have already identified.

It might seem counter-intuitive at first to prevent such changes - and it's certainly a nuisance on a dev server. But on a production server, this option and its default value of preventing such changes becomes a potential life-saver!

Convert a Python int into a big-endian string of bytes

Probably the best way is via the built-in struct module:

>>> import struct
>>> x = 1245427
>>> struct.pack('>BH', x >> 16, x & 0xFFFF)
'\x13\x00\xf3'
>>> struct.pack('>L', x)[1:]  # could do it this way too
'\x13\x00\xf3'

Alternatively -- and I wouldn't usually recommend this, because it's mistake-prone -- you can do it "manually" by shifting and the chr() function:

>>> x = 1245427
>>> chr((x >> 16) & 0xFF) + chr((x >> 8) & 0xFF) + chr(x & 0xFF)
'\x13\x00\xf3'

Out of curiosity, why do you only want three bytes? Usually you'd pack such an integer into a full 32 bits (a C unsigned long), and use struct.pack('>L', 1245427) but skip the [1:] step?

HtmlEncode from Class Library

In case you're using SharePoint 2010, using the following line of code will avoid having to reference the whole System.Web library:

Microsoft.SharePoint.Utilities.SPHttpUtility.HtmlEncode(stringToEncode);

Show a number to two decimal places

$twoDecNum = sprintf('%0.2f', round($number, 2));

The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.

How to set an iframe src attribute from a variable in AngularJS

It is the $sce service that blocks URLs with external domains, it is a service that provides Strict Contextual Escaping services to AngularJS, to prevent security vulnerabilities such as XSS, clickjacking, etc. it's enabled by default in Angular 1.2.

You can disable it completely, but it's not recommended

angular.module('myAppWithSceDisabledmyApp', [])
   .config(function($sceProvider) {
       $sceProvider.enabled(false);
   });

for more info https://docs.angularjs.org/api/ng/service/$sce

What is difference between XML Schema and DTD?

Similarities:

DTDs and Schemas both perform the same basic functions:

  • First, they both declare a laundry list of elements and attributes.
  • Second, both describe how those elements are grouped, nested or used within the XML. In other words, they declare the rules by which you are allowing someone to create an XML file within your workflow, and
  • Third, both DTDs and schemas provide methods for restricting, or forcing, the type or format of an element. For example, within the DTD or Schema you can force a date field to be written as 01/05/06 or 1/5/2006.

Differences:

  • DTDs are better for text-intensive applications, while schemas have several advantages for data-intensive workflows.

  • Schemas are written in XML and thusly follow the same rules, while DTDs are written in a completely different language.

Examples:

DTD:

<?xml version="1.0" encoding="UTF-8"?>
    <!ELEMENT employees (Efirstname, Elastname, Etitle, Ephone, Eemail)>
         <!ELEMENT Efirstname (#PCDATA)>
         <!ELEMENT Elastname (#PCDATA)>
         <!ELEMENT Etitle (#PCDATA)>
         <!ELEMENT Ephone (#PCDATA)>
         <!ELEMENT Eemail (#PCDATA)>

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:od="urn:schemas-microsoft-com:officedata">
<xsd:element name="dataroot">
     <xsd:complexType>
          <xsd:sequence>
               <xsd:element ref="employees" minOccurs="0" maxOccurs="unbounded"/>
          </xsd:sequence>
          <xsd:attribute name="generated" type="xsd:dateTime"/>
      </xsd:complexType>
</xsd:element>
<xsd:element name="employees">
      <xsd:annotation>
           <xsd:appinfo>
               <od:index index-name="PrimaryKey" index-key="Employeeid " primary="yes"
                unique="yes" clustered="no"/>
          <od:index index-name="Employeeid" index-key="Employeeid " primary="no" unique="no"
           clustered="no"/>
     </xsd:appinfo>
</xsd:annotation>
     <xsd:complexType>
          <xsd:sequence>
               <xsd:element name="Elastname" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Etitle" minOccurs="0" od:jetType="text" od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Ephone" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Eemail" minOccurs="0" od:jetType="text"
               od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Ephoto" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
          </xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Get User's Current Location / Coordinates

Update for iOS 12.2 with Swift 5

you must add following privacy permissions in plist file

<key>NSLocationWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Description</string>

Here is how I am

getting current location and showing on Map in Swift 2.0

Make sure you have added CoreLocation and MapKit framework to your project (This doesn't required with XCode 7.2.1)

import Foundation
import CoreLocation
import MapKit

class DiscoverViewController : UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!
    var locationManager: CLLocationManager!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        if (CLLocationManager.locationServicesEnabled())
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {

        let location = locations.last! as CLLocation

        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

        self.map.setRegion(region, animated: true)
    }
}

Here is the result screen

a screenshot of the map, centered in Mumbai

Set max-height on inner div so scroll bars appear, but not on parent div

If you make

overflow: hidden in the outer div and overflow-y: scroll in the inner div it will work.

http://jsfiddle.net/C8MuZ/11/

How can I change the value of the elements in a vector?

You might want to consider using some algorithms instead:

// read in the data:
std::copy(std::istream_iterator<double>(input), 
          std::istream_iterator<double>(),
          std::back_inserter(v));

sum = std::accumulate(v.begin(), v.end(), 0);
average = sum / v.size();

You can modify the values with std::transform, though until we get lambda expressions (C++0x) it may be more trouble than it's worth:

class difference { 
    double base;
public:
    difference(double b) : base(b) {}
    double operator()(double v) { return v-base; }
};

std::transform(v.begin(), v.end(), v.begin(), difference(average));

Install apk without downloading

you can use this code .may be solve the problem

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);

How do I resolve a TesseractNotFoundError?

I'm currently using Windows and needed to develop a PDF parser but adding a new environment variable via sysdm.cpl alone did not work. For other Windows user, I strongly suggest adding C:\Program Files (x86)\Tesseract-OCR to your profile.ps1 as well (if using Powershell that is).

Git refusing to merge unrelated histories on rebase

I had the same problem. The problem is remote had something preventing this.

I first created a local repository. I added a LICENSE and README.md file to my local and committed.

Then I wanted a remote repository so I created one on GitHub. Here I made a mistake of checking "Initialize this repository with a README", which created a README.md in remote too.

So now when I ran

git push --set-upstream origin master

I got:

error: failed to push some refs to 'https://github.com/lokeshub/myTODs.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes
(e.g. hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Now to overcome this I did

git pull origin master

Which resulted in the below error:

From https://github.com/lokeshub/myTODs
branch            master     -> FETCH_HEAD
fatal: refusing to merge unrelated histories**

I tried:

git pull origin master --allow-unrelated-histories

Result:

From https://github.com/lokeshub/myTODs
 * branch            master     -> FETCH_HEAD
Auto-merging README.md
CONFLICT (add/add): Merge conflict in README.md
Automatic merge failed;
fix conflicts and then commit the result.

Solution:

I removed the remote repository and created a new (I think only removing file README could have worked) and after that the below worked:

git remote rm origin
git remote add origin https://github.com/lokeshub/myTODOs.git
git push --set-upstream origin master

DataGridView.Clear()

If I remember correctly, I set the DataSource property to null to clear the DataGridView:

datagridview.DataSource = null;

How do I convert a String to an InputStream in Java?

You can try cactoos for that.

final InputStream input = new InputStreamOf("example");

The object is created with new and not a static method for a reason.

Android: Flush DNS

copied from: https://android.stackexchange.com/questions/12962/flush-clear-dns-cache

Addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are cached for 10 seconds. From everything I've seen, there's nothing built in to flush the cache. This is apparently a reported bug http://code.google.com/p/android/issues/detail?id=7904 in Android because of the way it stores DNS cache. Clearing the browser cache doesn't touch the DNS, the "hard reset" clears it.

Android Min SDK Version vs. Target SDK Version

For those who want a summary,

android:minSdkVersion

is minimum version till your application supports. If your device has lower version of android , app will not install.

while,

android:targetSdkVersion

is the API level till which your app is designed to run. Means, your phone's system don't need to use any compatibility behaviours to maintain forward compatibility because you have tested against till this API.

Your app will still run on Android versions higher than given targetSdkVersion but android compatibility behaviour will kick in.

Freebie -

android:maxSdkVersion

if your device's API version is higher, app will not install. Ie. this is the max API till which you allow your app to install.

ie. for MinSDK -4, maxSDK - 8, targetSDK - 8 My app will work on minimum 1.6 but I also have used features that are supported only in 2.2 which will be visible if it is installed on a 2.2 device. Also, for maxSDK - 8, this app will not install on phones using API > 8.

At the time of writing this answer, Android documentation was not doing a great job at explaining it. Now it is very well explained. Check it here

AngularJS accessing DOM elements inside directive template

I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:

{
     template: '<div>' +
    '<div class="title">{{title}}</div>' +
    '<div class="body" ng-transclude></div>' +
    '</div>',

    link: function(scope, element, attrs) {
        // Title element
        var title = angular.element(element.children()[0]),
        // ...
    }
}

Understanding events and event handlers in C#

I recently made an example of how to use events in c#, and posted it on my blog. I tried to make it as clear as possible, with a very simple example. In case it might help anyone, here it is: http://www.konsfik.com/using-events-in-csharp/

It includes description and source code (with lots of comments), and it mainly focuses on a proper (template - like) usage of events and event handlers.

Some key points are:

  • Events are like "sub - types of delegates", only more constrained (in a good way). In fact an event's declaration always includes a delegate (EventHandlers are a type of delegate).

  • Event Handlers are specific types of delegates (you may think of them as a template), which force the user to create events which have a specific "signature". The signature is of the format: (object sender, EventArgs eventarguments).

  • You may create your own sub-class of EventArgs, in order to include any type of information the event needs to convey. It is not necessary to use EventHandlers when using events. You may completely skip them and use your own kind of delegate in their place.

  • One key difference between using events and delegates, is that events can only be invoked from within the class that they were declared in, even though they may be declared as public. This is a very important distinction, because it allows your events to be exposed so that they are "connected" to external methods, while at the same time they are protected from "external misuse".

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

How to clean up R memory (without the need to restart my PC)?

Use ls() function to see what R objects are occupying space. use rm("objectName") to clear the objects from R memory that is no longer required. See this too.

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

File upload progress bar with jQuery

This solved my problem

var url = "http://localhost/tech1/index.php?route=app/upload/ajax"; 

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
          var $img = $link.find('i'); 
          $link.html('Uploading..('+percentComplete+'%)');
          $link.append($img);
      }
    }, false);

    return xhr;
  },
  url: url,
  type: "POST",
  data: JSON.stringify(uploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    console.log(result);
  }
});

How can I copy a conditional formatting from one document to another?

If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.

Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

similar to answers above but this has worked faithfully for me... in a service add:

    //sometimes you need to refresh scope, use this to prevent conflict
    this.applyAsNeeded = function (scope) {
        if (!scope.$$phase) {
            scope.$apply();
        }
    };

'this' implicitly has type 'any' because it does not have a type annotation

The error is indeed fixed by inserting this with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS

It should've been this:

foo.on('error', function(this: Foo, err: any) {

or this:

foo.on('error', function(this: typeof foo, err: any) {

A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

JQuery - Storing ajax response into global variable

your problem might not be related to any local or global scope for that matter just the server delay between the "success" function executing and the time you are trying to take out data from your variable.

chances are you are trying to print the contents of the variable before the ajax "success" function fires.

How can I check if a View exists in a Database?

This is the most portable, least intrusive way:

select
    count(*)
from
    INFORMATION_SCHEMA.VIEWS
where
    table_name = 'MyView'
    and table_schema = 'MySchema'

Edit: This does work on SQL Server, and it doesn't require you joining to sys.schemas to get the schema of the view. This is less important if everything is dbo, but if you're making good use of schemas, then you should keep that in mind.

Each RDBMS has their own little way of checking metadata like this, but information_schema is actually ANSI, and I think Oracle and apparently SQLite are the only ones that don't support it in some fashion.

npm - how to show the latest version of a package

You can use:

npm show {pkg} version

(so npm show express version will return now 3.0.0rc3).

Simple linked list in C++

This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.

#include <iostream>
using namespace std;

class LinkedList{
    // Struct inside the class LinkedList
    // This is one node which is not needed by the caller. It is just
    // for internal work.
    struct Node {
        int x;
        Node *next;
    };

// public member
public:
    // constructor
    LinkedList(){
        head = NULL; // set head to NULL
    }

    // destructor
    ~LinkedList(){
        Node *next = head;
        
        while(next) {              // iterate over all elements
            Node *deleteMe = next;
            next = next->next;     // save pointer to the next element
            delete deleteMe;       // delete the current entry
        }
    }
    
    // This prepends a new value at the beginning of the list
    void addValue(int val){
        Node *n = new Node();   // create new Node
        n->x = val;             // set value
        n->next = head;         // make the node point to the next node.
                                //  If the list is empty, this is NULL, so the end of the list --> OK
        head = n;               // last but not least, make the head point at the new node.
    }

    // returns the first element in the list and deletes the Node.
    // caution, no error-checking here!
    int popValue(){
        Node *n = head;
        int ret = n->x;

        head = head->next;
        delete n;
        return ret;
    }

// private member
private:
    Node *head; // this is the private member variable. It is just a pointer to the first Node
};

int main() {
    LinkedList list;

    list.addValue(5);
    list.addValue(10);
    list.addValue(20);

    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    // because there is no error checking in popValue(), the following
    // is undefined behavior. Probably the program will crash, because
    // there are no more values in the list.
    // cout << list.popValue() << endl;
    return 0;
}

I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo

EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18

How to create an ArrayList from an Array in PowerShell?

I can't get that constructor to work either. This however seems to work:

# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)

You can also pass an integer in the constructor to set an initial capacity.

What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?

Edit:

It seems that you can use the array constructor like this:

$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)

Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

How to output oracle sql result into a file in windows?

just to make the Answer 2 much easier, you can also define the folder where you can put your saved file

    spool /home/admin/myoutputfile.txt
    select * from table_name;
    spool off;

after that only with nano or vi myoutputfile.txt, you will see all the sql track.

hope is that help :)

How do I declare an array with a custom class?

To default-initialize an array of Ts, T must be default constructible. Normally the compiler gives you a default constructor for free. However, since you declared a constructor yourself, the compiler does not generate a default constructor.

Your options:

  • add a default constructor to name, if that makes sense (I don't think so, but I don't know the problem domain);
  • initialize all the elements of the array upon declaration (you can do this because name is an aggregate);

      name someName[4] = { { "Arthur", "Dent" },
                           { "Ford", "Prefect" },
                           { "Tricia", "McMillan" },
                           { "Zaphod", "Beeblebrox" }
                         };
    
  • use a std::vector instead, and only add element when you have them constructed.

Difference between spring @Controller and @RestController annotation

The @Controller annotation indicates that the class is a "Controller" like a web controller while @RestController annotation indicates that the class is a controller where @RequestMapping methods assume @ResponseBody semantics by default i.e. servicing REST API

JavaScript: undefined !== undefined?

var a;

typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true

React native ERROR Packager can't listen on port 8081

Try to run in another port like 3131. Run the command:

react-native run-android --port=3131

How to maintain page scroll position after a jquery event is carried out?

You can save the current scroll amount and then set it later:

var tempScrollTop = $(window).scrollTop();

..//Your code

$(window).scrollTop(tempScrollTop);

How to auto generate migrations with Sequelize CLI from Sequelize models?

Another solution is to put data definition into a separate file.

The idea is to write data common for both model and migration into a separate file, then require it in both the migration and the model. Then in the model we can add validations, while the migration is already good to go.

In order to not clutter this post with tons of code i wrote a GitHub gist.

See it here: https://gist.github.com/igorvolnyi/f7989fc64006941a7d7a1a9d5e61be47

jQuery counter to count up to a target number

A different approach. Use Tween.js for the counter. It allows the counter to slow down, speed up, bounce, and a slew of other goodies, as the counter gets to where its going.

http://jsbin.com/ekohep/2/edit#javascript,html,live

Enjoy :)

PS, doesn't use jQuery - but obviously could.

Reset auto increment counter in postgres

Note that if you have table name with '_', it is removed in sequence name.

For example, table name: user_tokens column: id Sequence name: usertokens_id_seq

A project with an Output Type of Class Library cannot be started directly

You can right click the Class Library project and from the drop-down choose Initialize Interactive C# which will load your project context and you can work it in the interactive session.

permission denied - php unlink

You'll first require to close the file using fclose($handle); it's not deleting because the file is in use. So first close the file and then try.

In MySQL, can I copy one row to insert into the same table?

This procedure assumes that:

  • you don't have _duplicate_temp_table
  • your primary key is int
  • you have access to create table

Of course this is not perfect, but in certain (probably most) cases it will work.

DELIMITER $$
CREATE PROCEDURE DUPLICATE_ROW(copytable VARCHAR(255), primarykey VARCHAR(255), copyid INT, out newid INT)
BEGIN
        DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @error=1;
        SET @temptable = '_duplicate_temp_table';
        SET @sql_text = CONCAT('CREATE TABLE ', @temptable, ' LIKE ', copytable);
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('INSERT INTO ', @temptable, ' SELECT * FROM ', copytable, ' where ', primarykey,'=', copyid);
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('SELECT max(', primarykey, ')+1 FROM ', copytable, ' INTO @newid');
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('UPDATE ', @temptable, ' SET ', primarykey, '=@newid');
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('INSERT INTO ', copytable, ' SELECT * FROM ', @temptable, '');
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('DROP TABLE ', @temptable);
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SELECT @newid INTO newid;
END $$
DELIMITER ;

CALL DUPLICATE_ROW('table', 'primarykey', 1, @duplicate_id);
SELECT @duplicate_id;

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

Placeholder in UITextView

I extended KmKndy's answer, so that the placeholder remains visible until the user starts editing the UITextView rather than just taps on it. This mirrors the functionality in the Twitter and Facebook apps. My solution doesn't require you to subclass and works if the user types directly or pastes text!

Example of Placeholder Twitter App

- (void)textViewDidChangeSelection:(UITextView *)textView{
    if ([textView.text isEqualToString:@"What's happening?"] && [textView.textColor isEqual:[UIColor lightGrayColor]])[textView setSelectedRange:NSMakeRange(0, 0)];

}

- (void)textViewDidBeginEditing:(UITextView *)textView{

    [textView setSelectedRange:NSMakeRange(0, 0)];
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length != 0 && [[textView.text substringFromIndex:1] isEqualToString:@"What's happening?"] && [textView.textColor isEqual:[UIColor lightGrayColor]]){
        textView.text = [textView.text substringToIndex:1];
        textView.textColor = [UIColor blackColor]; //optional

    }
    else if(textView.text.length == 0){
        textView.text = @"What's happening?";
        textView.textColor = [UIColor lightGrayColor];
        [textView setSelectedRange:NSMakeRange(0, 0)];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"What's happening?";
        textView.textColor = [UIColor lightGrayColor]; //optional
    }
    [textView resignFirstResponder];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (textView.text.length > 1 && [textView.text isEqualToString:@"What's happening?"]) {
         textView.text = @"";
         textView.textColor = [UIColor blackColor];
    }

    return YES;
}

just remember to set myUITextView with the exact text on creation e.g.

UITextView *myUITextView = [[UITextView alloc] init];
myUITextView.delegate = self;
myUITextView.text = @"What's happening?";
myUITextView.textColor = [UIColor lightGrayColor]; //optional

and make the parent class a UITextView delegate before including these methods e.g.

@interface MyClass () <UITextViewDelegate>
@end

Send JSON data from Javascript to PHP?

PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.

In order to pass it as a string from Javascript, you can convert it to JSON using

JSON.stringify(object);

or a library such as Prototype

Using Python's os.path, how do I go up one directory?

os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates'))

As far as where the templates folder should go, I don't know since Django 1.4 just came out and I haven't looked at it yet. You should probably ask another question on SE to solve that issue.

You can also use normpath to clean up the path, rather than abspath. However, in this situation, Django expects an absolute path rather than a relative path.

For cross platform compatability, use os.pardir instead of '..'.

Where could I buy a valid SSL certificate?

Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.

All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.

There are many clients you can use to install a Let's Encrypt certificate:

Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

In your comment on @Kenneth's answer you're saying that ReadAsStringAsync() is returning empty string.

That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.

What you can do is this:

public static string GetRequestBody()
{
    var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
    bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
    var bodyText = bodyStream.ReadToEnd();
    return bodyText;
}

How do I use CMake?

Regarding CMake 3.13.3, platform Windows, and IDE Visual Studio 2017, I suggest this guide. In brief I suggest:
1. Download cmake > unzip it > execute it.
2. As example download GLFW > unzip it > create inside folder Build.
3. In cmake Browse "Source" > Browse "Build" > Configure and Generate.
4. In Visual Studio 2017 Build your Solution.
5. Get the binaries.
Regards.

C++: constructor initializer for arrays

Just to update this question for C++11, this is now both possible to do and very natural:

struct Foo { Foo(int x) { /* ... */  } };

struct Baz { 
     Foo foo[3];

     Baz() : foo{{4}, {5}, {6}} { }
};

Those braces can also be elided for an even more concise:

struct Baz { 
     Foo foo[3];

     Baz() : foo{4, 5, 6} { }
};

Which can easily be extended to multi-dimensional arrays too:

struct Baz {
    Foo foo[3][2];

    Baz() : foo{1, 2, 3, 4, 5, 6} { }
};

Reset local repository branch to be just like remote repository HEAD

This is something I face regularly, & I've generalised the script Wolfgang provided above to work with any branch

I also added an "are you sure" prompt, & some feedback output

#!/bin/bash
# reset the current repository
# WF 2012-10-15
# AT 2012-11-09
# see http://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
branchname=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`
read -p "Reset branch $branchname to origin (y/n)? "
[ "$REPLY" != "y" ] || 
echo "about to auto-commit any changes"
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
  echo "Creating backup auto-save branch: auto-save-$branchname-at-$timestamp"
  git branch "auto-save-$branchname-at-$timestamp" 
fi
echo "now resetting to origin/$branchname"
git fetch origin
git reset --hard origin/$branchname

Binding a list in @RequestParam

It wasn't obvious to me that although you can accept a Collection as a request param, but on the consumer side you still have to pass in the collection items as comma separated values.

For example if the server side api looks like this:

@PostMapping("/post-topics")
public void handleSubscriptions(@RequestParam("topics") Collection<String> topicStrings) {

    topicStrings.forEach(topic -> System.out.println(topic));
}

Directly passing in a collection to the RestTemplate as a RequestParam like below will result in data corruption

public void subscribeToTopics() {

    List<String> topics = Arrays.asList("first-topic", "second-topic", "third-topic");

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.postForEntity(
            "http://localhost:8088/post-topics?topics={topics}",
            null,
            ResponseEntity.class,
            topics);
}

Instead you can use

public void subscribeToTopics() {

    List<String> topicStrings = Arrays.asList("first-topic", "second-topic", "third-topic");
    String topics = String.join(",",topicStrings);

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.postForEntity(
            "http://localhost:8088/post-topics?topics={topics}",
            null,
            ResponseEntity.class,
            topics);
}

The complete example can be found here, hope it saves someone the headache :)

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

How can I clear event subscriptions in C#?

Instead of adding and removing callbacks manually and having a bunch of delegate types declared everywhere:

// The hard way
public delegate void ObjectCallback(ObjectType broadcaster);

public class Object
{
    public event ObjectCallback m_ObjectCallback;
    
    void SetupListener()
    {
        ObjectCallback callback = null;
        callback = (ObjectType broadcaster) =>
        {
            // one time logic here
            broadcaster.m_ObjectCallback -= callback;
        };
        m_ObjectCallback += callback;

    }
    
    void BroadcastEvent()
    {
        m_ObjectCallback?.Invoke(this);
    }
}

You could try this generic approach:

public class Object
{
    public Broadcast<Object> m_EventToBroadcast = new Broadcast<Object>();

    void SetupListener()
    {
        m_EventToBroadcast.SubscribeOnce((ObjectType broadcaster) => {
            // one time logic here
        });
    }

    ~Object()
    {
        m_EventToBroadcast.Dispose();
        m_EventToBroadcast = null;
    }

    void BroadcastEvent()
    {
        m_EventToBroadcast.Broadcast(this);
    }
}


public delegate void ObjectDelegate<T>(T broadcaster);
public class Broadcast<T> : IDisposable
{
    private event ObjectDelegate<T> m_Event;
    private List<ObjectDelegate<T>> m_SingleSubscribers = new List<ObjectDelegate<T>>();

    ~Broadcast()
    {
        Dispose();
    }

    public void Dispose()
    {
        Clear();
        System.GC.SuppressFinalize(this);
    }

    public void Clear()
    {
        m_SingleSubscribers.Clear();
        m_Event = delegate { };
    }

    // add a one shot to this delegate that is removed after first broadcast
    public void SubscribeOnce(ObjectDelegate<T> del)
    {
        m_Event += del;
        m_SingleSubscribers.Add(del);
    }

    // add a recurring delegate that gets called each time
    public void Subscribe(ObjectDelegate<T> del)
    {
        m_Event += del;
    }

    public void Unsubscribe(ObjectDelegate<T> del)
    {
        m_Event -= del;
    }

    public void Broadcast(T broadcaster)
    {
        m_Event?.Invoke(broadcaster);
        for (int i = 0; i < m_SingleSubscribers.Count; ++i)
        {
            Unsubscribe(m_SingleSubscribers[i]);
        }
        m_SingleSubscribers.Clear();
    }
}

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

This works for me: http://gitblit.com/setup_client.html

Eclipse/EGit/JGit

Window->Preferences->Team->Git->Configuration
Click the New Entry button

Key = http.sslVerify
Value = false

link with target="_blank" does not open in new tab in Chrome

most simple answer

<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>

it will work

How to pass variable number of arguments to a PHP function

For those looking for a way to do this with $object->method:

call_user_func_array(array($object, 'method_name'), $array);

I was successful with this in a construct function that calls a variable method_name with variable parameters.

How do I get DOUBLE_MAX?

You are looking for the float.h header.

Best way to create a temp table with same columns and type as a permanent table

Sortest one...

select top 0 * into #temptable from mytable

Note : This creates an empty copy of temp, But it doesn't create a primary key

SQL search multiple values in same field

This has been partially answered here: MySQL Like multiple values

I advise against

$search = explode( ' ', $search );

and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;

$search = str_replace('"', "''", search );

But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.

function makeSQL_search_pattern($search) {
    search_pattern = false;
    //escape the special regex chars
    $search = str_replace('"', "''", $search);
    $search = str_replace('^', "\\^", $search);
    $search = str_replace('$', "\\$", $search);
    $search = str_replace('.', "\\.", $search);
    $search = str_replace('[', "\\[", $search);
    $search = str_replace(']', "\\]", $search);
    $search = str_replace('|', "\\|", $search);
    $search = str_replace('*', "\\*", $search);
    $search = str_replace('+', "\\+", $search);
    $search = str_replace('{', "\\{", $search);
    $search = str_replace('}', "\\}", $search);
    $search = explode(" ", $search);
    for ($i = 0; $i < count($search); $i++) {
        if ($i > 0 && $i < count($search) ) {
           $search_pattern .= "|";
        }
        $search_pattern .= $search[$i];
    }
    return search_pattern;
}

$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();

I have not tested this code, but this is what I would do in your case. I hope this helps.

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

How to import multiple csv files in a single load?

Note that you can use other tricks like :

-- One or more wildcard:
       .../Downloads20*/*.csv
--  braces and brackets   
       .../Downloads201[1-5]/book.csv
       .../Downloads201{11,15,19,99}/book.csv

Flutter position stack widget in center

You can change the Positioned with Align inside a Stack:

Align(
  alignment: Alignment.bottomCenter,
  child: ... ,
),

For more info about Stack: Exploring Stack

How do I sort arrays using vbscript?

Here's another vbscript implementation of quicksort. This is the in-place, unstable approach as defined in wikipedia (see here: http://en.wikipedia.org/wiki/Quicksort). Uses much less memory (original implementation requires upper and lower temporary storage arrays to be created upon every iteration, which can increase memory size by n terms in the worst case).

For ascending order, switch the signs.

If you want to sort characters, use Asc(ch) function.

'-------------------------------------
 '  quicksort
 '    Carlos Nunez, created: 25 April, 2010.
 '
 '  NOTE:   partition function also
 '          required
 '-------------------------------------
function qsort(list, first, last)
    Dim i, j
    if (typeName(list) <> "Variant()" or ubound(list) = 0) then exit function       'list passed must be a collection or array.

    'if the set size is less than 3, we can do a simple comparison sort.
    if (last-first) < 3 then
        for i = first to last
            for j = first to last
                if list(i) < list(j) then
                    swap list,i,j
                end if
            next
        next
    else
        dim p_idx

        'we need to set the pivot relative to the position of the subset currently being sorted.
        'if the starting position of the subset is the first element of the whole set, then the pivot is the median of the subset.
        'otherwise, the median is offset by the first position of the subset.
        '-------------------------------------------------------------------------------------------------------------------------
        if first-1 < 0 then
            p_idx   = round((last-first)/2,0)
        else
            p_idx   = round(((first-1)+((last-first)/2)),0)
        end if

        dim p_nidx:     p_nidx  = partition(list, first, last, p_idx)
        if p_nidx = -1 then exit function

        qsort list, first, p_nidx-1
        qsort list, p_nidx+1, last
    end if
end function


function partition(list, first, last, idx)
    Dim i
    partition = -1

    dim p_val:      p_val = list(idx)
    swap list,idx,last
    dim swap_pos:   swap_pos = first
    for i = first to last-1 
        if list(i) <= p_val then
            swap list,i,swap_pos
            swap_pos = swap_pos + 1
        end if
    next
    swap list,swap_pos,last

    partition = swap_pos
end function

function swap(list,a_pos,b_pos)
    dim tmp
    tmp = list(a_pos)
    list(a_pos) = list(b_pos)
    list(b_pos) = tmp   
end function

How do I determine the dependencies of a .NET application?

Dependency walker works on normal win32 binaries. All .NET dll's and exe's have a small stub header part which makes them look like normal binaries, but all it basically says is "load the CLR" - so that's all that dependency walker will tell you.

To see which things your .NET app actually relies on, you can use the tremendously excellent .NET reflector from Red Gate. (EDIT: Note that .NET Reflector is now a paid product. ILSpy is free and open source and very similar.)

Load your DLL into it, right click, and chose 'Analyze' - you'll then see a "Depends On" item which will show you all the other dll's (and methods inside those dll's) that it needs.

It can sometimes get trickier though, in that your app depends on X dll, and X dll is present, but for whatever reason can't be loaded or located at runtime.

To troubleshoot those kinds of issues, Microsoft have an Assembly Binding Log Viewer which can show you what's going on at runtime

How to create a thread?

The following ways work.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

Default FirebaseApp is not initialized

changing

classpath 'com.google.gms:google-services:4.1.0'

to

classpath 'com.google.gms:google-services:4.0.1'

Works for me

Upload file to FTP using C#

public void UploadFtpFile(string folderName, string fileName)
{

    FtpWebRequest request;

    string folderName; 
    string fileName;
    string absoluteFileName = Path.GetFileName(fileName);

    request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/{2}", "127.0.0.1", folderName, absoluteFileName))) as FtpWebRequest;
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UseBinary = 1;
    request.UsePassive = 1;
    request.KeepAlive = 1;
    request.Credentials =  new NetworkCredential(user, pass);
    request.ConnectionGroupName = "group"; 

    using (FileStream fs = File.OpenRead(fileName))
    {
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        fs.Close();
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(buffer, 0, buffer.Length);
        requestStream.Flush();
        requestStream.Close();
    }
}

How to use

UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img");

use this in your foreach

and you only need to create folder one time

to create a folder

request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/", "127.0.0.1", "testFolder"))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse();

When is TCP option SO_LINGER (0) required?

The listen socket on a server can use linger with time 0 to have access to binding back to the socket immediately and to reset any clients whose connections are not yet finished connecting. TIME_WAIT is something that is only interesting when you have a multi-path network and can end up with miss-ordered packets or otherwise are dealing with odd network packet ordering/arrival-timing.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Just had this problem on Indigo SR2. It popped up after I removed a superfluous jar from the classpath (build path). Restarting Eclipse didn't help. Added back the jar to the build path...error went away. Removed the jar once again, and this time I was spared from another complaint.

Can two or more people edit an Excel document at the same time?

Unfortunately, the file must be locked for updates unless you're using Office 2010 and SharePoint 2010 together. This means that only one user per time can edit a file. The locking and version tracking capabilities of SharePoint are excellent, and this makes it a great tool for the type of collaboration you're talking about, but you would have to split documents into multiple files in order to extend the amount that could be edited at a time. For instance, we sometimes unmerge documents into technical, requirements, and financials sections so that the 3 experts required for the review can work concurrently. We then merge when everyone is finished.

Filter Linq EXCEPT on properties

ColinE's answer is simple and elegant. If your lists are larger and provided that the excluded apps list is sorted, BinarySearch<T> may prove faster than Contains.

EXAMPLE:

unfilteredApps.Where(i => excludedAppIds.BinarySearch(i.Id) < 0);

pandas read_csv and filter columns with usecols

The solution lies in understanding these two keyword arguments:

  • names is only necessary when there is no header row in your file and you want to specify other arguments (such as usecols) using column names rather than integer indices.
  • usecols is supposed to provide a filter before reading the whole DataFrame into memory; if used properly, there should never be a need to delete columns after reading.

So because you have a header row, passing header=0 is sufficient and additionally passing names appears to be confusing pd.read_csv.

Removing names from the second call gives the desired output:

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        header=0,
        index_col=["date", "loc"], 
        usecols=["date", "loc", "x"],
        parse_dates=["date"])

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Check if input is integer type in C

I was having the same problem, finally figured out what to do:

#include <stdio.h>
#include <conio.h>

int main ()
{
    int x;
    float check;
    reprocess:
    printf ("enter a integer number:");
    scanf ("%f", &check);
    x=check;
    if (x==check)
    printf("\nYour number is %d", x);
    else 
    {
         printf("\nThis is not an integer number, please insert an integer!\n\n");
         goto reprocess;
    }
    _getch();
    return 0;
}

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

Is Visual Studio Community a 30 day trial?

For my case the problem was in fact that i broke machine.config and looks like VS couldn't have a connection I've added the following lines to my machine.config

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
<!--
-->

After replacing the previous section to:

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
-->

VS started to work.

Set background colour of cell to RGB value of data in cell

You can use VBA - something like

Range("A1:A6").Interior.Color = RGB(127,187,199)

Just pass in the cell value.

How do I read image data from a URL in Python?

USE urllib.request.urlretrieve() AND PIL.Image.open() TO DOWNLOAD AND READ IMAGE DATA :

import requests

import urllib.request

import PIL
urllib.request.urlretrieve("https://i.imgur.com/ExdKOOz.png", "sample.png")
img = PIL.Image.open("sample.png")
img.show()

or Call requests.get(url) with url as the address of the object file to download via a GET request. Call io.BytesIO(obj) with obj as the content of the response to load the raw data as a bytes object. To load the image data, call PIL.Image.open(bytes_obj) with bytes_obj as the bytes object:

import io
response = requests.get("https://i.imgur.com/ExdKOOz.png")
image_bytes = io.BytesIO(response.content)
img = PIL.Image.open(image_bytes)
img.show()

Query to display all tablespaces in a database and datafiles

In oracle, generally speaking, there are number of facts that I will mention in following section:

  • Each database can have many Schema/User (Logical division).
  • Each database can have many tablespaces (Logical division).
  • A schema is the set of objects (tables, indexes, views, etc) that belong to a user.
  • In Oracle, a user can be considered the same as a schema.
  • A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional one for application indexes.

Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.

However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.

So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:

SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'

Create hive table using "as select" or "like" and also specify delimiter

Both the answers provided above work fine.

  1. CREATE TABLE person AS select * from employee;
  2. CREATE TABLE person LIKE employee;

LINQ equivalent of foreach for IEnumerable<T>

To stay fluent one can use such a trick:

GetItems()
    .Select(i => new Action(i.DoStuf)))
    .Aggregate((a, b) => a + b)
    .Invoke();

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You could just use: {in and out function callback}

$(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });

For your example, better will be to use CSS pseudo class :hover: {no js/jquery needed}

.result {
    height: 72px;
    width: 100%;
    border: 1px solid #000;
  }
  .result:hover {
    background-color: #000;
  }

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

HTML email with Javascript

Here's what you CAN do:

You can attach (to the email) an html document that contains javascript.

Then, when the recipient opens the attachment, their web browser will facilitate the dynamic features you've implemented.

Convert xlsx to csv in Linux with command line

Use csvkit

in2csv data.xlsx > data.csv

For details check their excellent docs

How to save as a new file and keep working on the original one in Vim?

After save new file press

Ctrl-6

This is shortcut to alternate file

Swift Beta performance: sorting arrays

Swift Array performance revisited:

I wrote my own benchmark comparing Swift with C/Objective-C. My benchmark calculates prime numbers. It uses the array of previous prime numbers to look for prime factors in each new candidate, so it is quite fast. However, it does TONS of array reading, and less writing to arrays.

I originally did this benchmark against Swift 1.2. I decided to update the project and run it against Swift 2.0.

The project lets you select between using normal swift arrays and using Swift unsafe memory buffers using array semantics.

For C/Objective-C, you can either opt to use NSArrays, or C malloc'ed arrays.

The test results seem to be pretty similar with fastest, smallest code optimization ([-0s]) or fastest, aggressive ([-0fast]) optimization.

Swift 2.0 performance is still horrible with code optimization turned off, whereas C/Objective-C performance is only moderately slower.

The bottom line is that C malloc'd array-based calculations are the fastest, by a modest margin

Swift with unsafe buffers takes around 1.19X - 1.20X longer than C malloc'd arrays when using fastest, smallest code optimization. the difference seems slightly less with fast, aggressive optimization (Swift takes more like 1.18x to 1.16x longer than C.

If you use regular Swift arrays, the difference with C is slightly greater. (Swift takes ~1.22 to 1.23 longer.)

Regular Swift arrays are DRAMATICALLY faster than they were in Swift 1.2/Xcode 6. Their performance is so close to Swift unsafe buffer based arrays that using unsafe memory buffers does not really seem worth the trouble any more, which is big.

BTW, Objective-C NSArray performance stinks. If you're going to use the native container objects in both languages, Swift is DRAMATICALLY faster.

You can check out my project on github at SwiftPerformanceBenchmark

It has a simple UI that makes collecting stats pretty easy.

It's interesting that sorting seems to be slightly faster in Swift than in C now, but that this prime number algorithm is still faster in Swift.

__init__() got an unexpected keyword argument 'user'

I got the same error.

On my view I was overriding get_form_kwargs() like this:

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

How to kill a process in MacOS?

I recently faced similar issue where the atom editor will not close. Neither was responding. Kill / kill -9 / force exit from Activity Monitor - didn't work. Finally had to restart my mac to close the app.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

I came here looking for an answer to my distorted images. Not totally sure about what the op is looking for above, but I found that adding in align-items: center would solve it for me. Reading the docs, it makes sense to override this if you are flexing images directly, since align-items: stretch is the default. Another solution is to wrap your images with a div first.

.myFlexedImage {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
}

Display / print all rows of a tibble (tbl_df)

The tibble vignette has an updated way to change its default printing behavior:

You can control the default appearance with options:

options(tibble.print_max = n, tibble.print_min = m): if there are more than n rows, print only the first m rows. Use options(tibble.print_max = Inf) to always show all rows.

options(tibble.width = Inf) will always print all columns, regardless of the width of the screen.

examples

This will always print all rows:

options(tibble.print_max = Inf)

This will not actually limit the printing to 50 lines:

options(tibble.print_max = 50)

But this will restrict printing to 50 lines:

options(tibble.print_max = 50, tibble.print_min = 50)

How to do a LIKE query with linq?

var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();

User can use this of like query in Linq and fill the student model.

How do I capture all of my compiler's output to a file?

Assume you want to hilight warning and error from build ouput:

make |& grep -E "warning|error"

Differences between fork and exec

Fork creates a copy of a calling process. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{

  //child code

  exit(0);

}

//parent code

wait(cpid);

// end

(for child process text(code),data,stack is same as calling process) child process executes code in if block.

EXEC replaces the current process with new process's code,data,stack. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{   
  //child code

  exec(foo);

  exit(0);    
}

//parent code

wait(cpid);

// end

(after exec call unix kernel clears the child process text,data,stack and fills with foo process related text/data) thus child process is with different code (foo's code {not same as parent})

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

What is the difference between user and kernel modes in operating systems?

CPU rings are the most clear distinction

In x86 protected mode, the CPU is always in one of 4 rings. The Linux kernel only uses 0 and 3:

  • 0 for kernel
  • 3 for users

This is the most hard and fast definition of kernel vs userland.

Why Linux does not use rings 1 and 2: CPU Privilege Rings: Why rings 1 and 2 aren't used?

How is the current ring determined?

The current ring is selected by a combination of:

  • global descriptor table: a in-memory table of GDT entries, and each entry has a field Privl which encodes the ring.

    The LGDT instruction sets the address to the current descriptor table.

    See also: http://wiki.osdev.org/Global_Descriptor_Table

  • the segment registers CS, DS, etc., which point to the index of an entry in the GDT.

    For example, CS = 0 means the first entry of the GDT is currently active for the executing code.

What can each ring do?

The CPU chip is physically built so that:

  • ring 0 can do anything

  • ring 3 cannot run several instructions and write to several registers, most notably:

    • cannot change its own ring! Otherwise, it could set itself to ring 0 and rings would be useless.

      In other words, cannot modify the current segment descriptor, which determines the current ring.

    • cannot modify the page tables: How does x86 paging work?

      In other words, cannot modify the CR3 register, and paging itself prevents modification of the page tables.

      This prevents one process from seeing the memory of other processes for security / ease of programming reasons.

    • cannot register interrupt handlers. Those are configured by writing to memory locations, which is also prevented by paging.

      Handlers run in ring 0, and would break the security model.

      In other words, cannot use the LGDT and LIDT instructions.

    • cannot do IO instructions like in and out, and thus have arbitrary hardware accesses.

      Otherwise, for example, file permissions would be useless if any program could directly read from disk.

      More precisely thanks to Michael Petch: it is actually possible for the OS to allow IO instructions on ring 3, this is actually controlled by the Task state segment.

      What is not possible is for ring 3 to give itself permission to do so if it didn't have it in the first place.

      Linux always disallows it. See also: Why doesn't Linux use the hardware context switch via the TSS?

How do programs and operating systems transition between rings?

  • when the CPU is turned on, it starts running the initial program in ring 0 (well kind of, but it is a good approximation). You can think this initial program as being the kernel (but it is normally a bootloader that then calls the kernel still in ring 0).

  • when a userland process wants the kernel to do something for it like write to a file, it uses an instruction that generates an interrupt such as int 0x80 or syscall to signal the kernel. x86-64 Linux syscall hello world example:

    .data
    hello_world:
        .ascii "hello world\n"
        hello_world_len = . - hello_world
    .text
    .global _start
    _start:
        /* write */
        mov $1, %rax
        mov $1, %rdi
        mov $hello_world, %rsi
        mov $hello_world_len, %rdx
        syscall
    
        /* exit */
        mov $60, %rax
        mov $0, %rdi
        syscall
    

    compile and run:

    as -o hello_world.o hello_world.S
    ld -o hello_world.out hello_world.o
    ./hello_world.out
    

    GitHub upstream.

    When this happens, the CPU calls an interrupt callback handler which the kernel registered at boot time. Here is a concrete baremetal example that registers a handler and uses it.

    This handler runs in ring 0, which decides if the kernel will allow this action, do the action, and restart the userland program in ring 3. x86_64

  • when the exec system call is used (or when the kernel will start /init), the kernel prepares the registers and memory of the new userland process, then it jumps to the entry point and switches the CPU to ring 3

  • If the program tries to do something naughty like write to a forbidden register or memory address (because of paging), the CPU also calls some kernel callback handler in ring 0.

    But since the userland was naughty, the kernel might kill the process this time, or give it a warning with a signal.

  • When the kernel boots, it setups a hardware clock with some fixed frequency, which generates interrupts periodically.

    This hardware clock generates interrupts that run ring 0, and allow it to schedule which userland processes to wake up.

    This way, scheduling can happen even if the processes are not making any system calls.

What is the point of having multiple rings?

There are two major advantages of separating kernel and userland:

  • it is easier to make programs as you are more certain one won't interfere with the other. E.g., one userland process does not have to worry about overwriting the memory of another program because of paging, nor about putting hardware in an invalid state for another process.
  • it is more secure. E.g. file permissions and memory separation could prevent a hacking app from reading your bank data. This supposes, of course, that you trust the kernel.

How to play around with it?

I've created a bare metal setup that should be a good way to manipulate rings directly: https://github.com/cirosantilli/x86-bare-metal-examples

I didn't have the patience to make a userland example unfortunately, but I did go as far as paging setup, so userland should be feasible. I'd love to see a pull request.

Alternatively, Linux kernel modules run in ring 0, so you can use them to try out privileged operations, e.g. read the control registers: How to access the control registers cr0,cr2,cr3 from a program? Getting segmentation fault

Here is a convenient QEMU + Buildroot setup to try it out without killing your host.

The downside of kernel modules is that other kthreads are running and could interfere with your experiments. But in theory you can take over all interrupt handlers with your kernel module and own the system, that would be an interesting project actually.

Negative rings

While negative rings are not actually referenced in the Intel manual, there are actually CPU modes which have further capabilities than ring 0 itself, and so are a good fit for the "negative ring" name.

One example is the hypervisor mode used in virtualization.

For further details see:

ARM

In ARM, the rings are called Exception Levels instead, but the main ideas remain the same.

There exist 4 exception levels in ARMv8, commonly used as:

  • EL0: userland

  • EL1: kernel ("supervisor" in ARM terminology).

    Entered with the svc instruction (SuperVisor Call), previously known as swi before unified assembly, which is the instruction used to make Linux system calls. Hello world ARMv8 example:

    hello.S

    .text
    .global _start
    _start:
        /* write */
        mov x0, 1
        ldr x1, =msg
        ldr x2, =len
        mov x8, 64
        svc 0
    
        /* exit */
        mov x0, 0
        mov x8, 93
        svc 0
    msg:
        .ascii "hello syscall v8\n"
    len = . - msg
    

    GitHub upstream.

    Test it out with QEMU on Ubuntu 16.04:

    sudo apt-get install qemu-user gcc-arm-linux-gnueabihf
    arm-linux-gnueabihf-as -o hello.o hello.S
    arm-linux-gnueabihf-ld -o hello hello.o
    qemu-arm hello
    

    Here is a concrete baremetal example that registers an SVC handler and does an SVC call.

  • EL2: hypervisors, for example Xen.

    Entered with the hvc instruction (HyperVisor Call).

    A hypervisor is to an OS, what an OS is to userland.

    For example, Xen allows you to run multiple OSes such as Linux or Windows on the same system at the same time, and it isolates the OSes from one another for security and ease of debug, just like Linux does for userland programs.

    Hypervisors are a key part of today's cloud infrastructure: they allow multiple servers to run on a single hardware, keeping hardware usage always close to 100% and saving a lot of money.

    AWS for example used Xen until 2017 when its move to KVM made the news.

  • EL3: yet another level. TODO example.

    Entered with the smc instruction (Secure Mode Call)

The ARMv8 Architecture Reference Model DDI 0487C.a - Chapter D1 - The AArch64 System Level Programmer's Model - Figure D1-1 illustrates this beautifully:

enter image description here

The ARM situation changed a bit with the advent of ARMv8.1 Virtualization Host Extensions (VHE). This extension allows the kernel to run in EL2 efficiently:

enter image description here

VHE was created because in-Linux-kernel virtualization solutions such as KVM have gained ground over Xen (see e.g. AWS' move to KVM mentioned above), because most clients only need Linux VMs, and as you can imagine, being all in a single project, KVM is simpler and potentially more efficient than Xen. So now the host Linux kernel acts as the hypervisor in those cases.

Note how ARM, maybe due to the benefit of hindsight, has a better naming convention for the privilege levels than x86, without the need for negative levels: 0 being the lower and 3 highest. Higher levels tend to be created more often than lower ones.

The current EL can be queried with the MRS instruction: what is the current execution mode/exception level, etc?

ARM does not require all exception levels to be present to allow for implementations that don't need the feature to save chip area. ARMv8 "Exception levels" says:

An implementation might not include all of the Exception levels. All implementations must include EL0 and EL1. EL2 and EL3 are optional.

QEMU for example defaults to EL1, but EL2 and EL3 can be enabled with command line options: qemu-system-aarch64 entering el1 when emulating a53 power up

Code snippets tested on Ubuntu 18.10.

Get JSON Data from URL Using Android?

Easy way to get JSON especially for Android SDK 23:

public class MainActivity extends AppCompatActivity {

Button btnHit;
TextView txtJson;
ProgressDialog pd;

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

    btnHit = (Button) findViewById(R.id.btnHit);
    txtJson = (TextView) findViewById(R.id.tvJsonItem);

    btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute("Url address here");
        }
    });


}


private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}
}

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

I do the following:

...WHERE 
    fieldname COLLATE DATABASE_DEFAULT = otherfieldname COLLATE DATABASE_DEFAULT

Works every time. :)

How can I implement custom Action Bar with custom buttons in Android?

1 You can use a drawable

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_item1"
        android:icon="@drawable/my_item_drawable"
        android:title="@string/menu_item1"
        android:showAsAction="ifRoom" />
</menu>

2 Create a style for the action bar and use a custom background:

<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <!-- other activity and action bar styles here -->
    </style>
    <!-- style for the action bar backgrounds -->
    <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:background">@drawable/background</item>
        <item name="android:backgroundStacked">@drawable/background</item>
        <item name="android:backgroundSplit">@drawable/split_background</item>
    </style>
</resources>

3 Style again android:actionBarDivider

The android documentation is very usefull for that.

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.