Programs & Examples On #Android lazyloading

How can I create a keystore?

Use this command to create debug.keystore

keytool -genkey -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

How to add new elements to an array?

You can simply do this:

System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

I have a similar issue with a share Host. I was having 500 error. I just fixed by checking the Laravel version and PHP version. The error was because Laravel 5.6 doesn't run on PHP 7.0.x Once I know this I just reconfigure the project to Laravel 5.5 that is compatible with PHP 7.0.x now everything is right. Another reason I have issues sometimes is the FTP I get corrupted Files and have to upload the project more than once. Hope this help in the future I don't found so many information in this topic.

What is perm space?

It stands for permanent generation:

The permanent generation is special because it holds meta-data describing user classes (classes that are not part of the Java language). Examples of such meta-data are objects describing classes and methods and they are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of the heap which will cause java.lang.OutOfMemoryError: PermGen no matter how high your -Xmx and how much memory you have on the machine.

Disabling the long-running-script message in Internet Explorer

The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.

Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:

RepeatingOperation = function(op, yieldEveryIteration) {

  //keeps count of how many times we have run heavytask() 
  //before we need to temporally check back with the browser.
  var count = 0;   

  this.step = function() {

    //Each time we run heavytask(), increment the count. When count
    //is bigger than the yieldEveryIteration limit, pass control back 
    //to browser and instruct the browser to immediately call op() so
    //we can pick up where we left off.  Repeat until we are done.
    if (++count >= yieldEveryIteration) {
      count = 0;

      //pass control back to the browser, and in 1 millisecond, 
      //have the browser call the op() function.  
      setTimeout(function() { op(); }, 1, [])

      //The following return statement halts this thread, it gives 
      //the browser a sigh of relief, your long-running javascript
      //loop has ended (even though technically we havn't yet).
      //The browser decides there is no need to alarm the user of
      //an unresponsive javascript process.
      return;
      }
    op();
  };
};

Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:

process10000HeavyTasks = function() {
  var len = 10000;  
  for (var i = len - 1; i >= 0; i--) {
    heavytask();   //heavytask() can be run about 20  times before
                   //an 'unresponsive script' dialog appears.
                   //If heavytask() is run more than 20 times in one
                   //javascript thread, the browser informs the user that
                   //an unresponsive script needs to be dealt with.  

                   //This is where we need to terminate this long running
                   //thread, instruct the browser not to panic on an unresponsive
                   //script, and tell it to call us right back to pick up
                   //where we left off.
  }
}

Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()

process10000HeavyTasks = function() {

  var global_i = 10000; //initialize your 'for loop stepper' (i) here.

  var repeater = new this.RepeatingOperation(function() {

    heavytask();

    if (--global_i >= 0){     //Your for loop conditional goes here.
      repeater.step();        //while we still have items to process,
                              //run the next iteration of the loop.
    }
    else {
       alert("we are done");  //when this line runs, the for loop is complete.
    }
  }, 10);                   //10 means process 10 heavytask(), then
                            //yield back to the browser, and have the
                            //browser call us right back.

  repeater.step();          //this command kicks off the recursive closure.

};

Adapted from this source:

http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers

How to differ sessions in browser-tabs?

I've come up with a new solution, which has a tiny bit of overhead, but seems to be working so far as a prototype. One assumption is that you're in an honour system environment for logging in, although this could be adapted by rerequesting a password whenever you switch tabs.

Use localStorage (or equivalent) and the HTML5 storage event to detect when a new browser tab has switched which user is active. When that happens, create a ghost overlay with a message saying you can't use the current window (or otherwise disable the window temporarily, you might not want it to be this conspicuous.) When the window regains focus, send an AJAX request logging the user back in.

One caveat to this approach: you can't have any normal AJAX calls (i.e., ones that depend on your session) happen in a window that doesn't have the focus (e.g. if you had a call happening after a delay), unless you manually make an AJAX re-login call before that. So really all you need do is have your AJAX function check first to make sure localStorage.currently_logged_in_user_id === window.yourAppNameSpace.user_id, and if not, log in first via AJAX.

Another is race conditions: if you can switch windows fast enough to confuse it, you may end up with a relogin1->relogin2->ajax1->ajax2 sequence, with ajax1 being made under the wrong session. Work around this by pushing login AJAX requests onto an array, and then onstorage and before issuing a new login request, abort all current requests.

The last gotcha to look out for is window refreshes. If someone refreshes the window while you've got an AJAX login request active but not completed, it'll be refreshed in the name of the wrong person. In this case you can use the nonstandard beforeunload event to warn the user about the potential mixup and ask them to click Cancel, meanwhile reissuing an AJAX login request. Then the only way they can botch it is by clicking OK before the request completes (or by accidentally hitting enter/spacebar, because OK is--unfortunately for this case--the default.) There are other ways to handle this case, like detecting F5 and Ctrl+R/Alt+R presses, which will work in most cases but could be thwarted by user keyboard shortcut reconfiguration or alternative OS use. However, this is a bit of an edge case in reality, and the worst case scenarios are never that bad: in an honour system configuration, you'd be logged in as the wrong person (but you can make it obvious that this is the case by personalizing pages with colours, styles, prominently displayed names, etc.); in a password configuration, the onus is on the last person who entered their password to have logged out or shared their session, or if this person is actually the current user, then there's no breach.

But in the end you have a one-user-per-tab application that (hopefully) just acts as it should, without having to necessarily set up profiles, use IE, or rewrite URLs. Make sure you make it obvious in each tab who is logged into that particular tab, though...

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

What version of MongoDB is installed on Ubuntu

In the terminal just write : $ mongod --version

Video 100% width and height

You can use Javascript to dynamically set the height to 100% of the window and then center it using a negative left margin based on the ratio of video width to window width.

http://jsfiddle.net/RfV5C/

var $video  = $('video'),
    $window = $(window); 

$(window).resize(function(){
    var height = $window.height();
    $video.css('height', height);

    var videoWidth = $video.width(),
        windowWidth = $window.width(),
    marginLeftAdjust =   (windowWidth - videoWidth) / 2;

    $video.css({
        'height': height, 
        'marginLeft' : marginLeftAdjust
    });
}).resize();

Searching for Text within Oracle Stored Procedures

 SELECT * FROM ALL_source WHERE UPPER(text) LIKE '%BLAH%'

EDIT Adding additional info:

 SELECT * FROM DBA_source WHERE UPPER(text) LIKE '%BLAH%'

The difference is dba_source will have the text of all stored objects. All_source will have the text of all stored objects accessible by the user performing the query. Oracle Database Reference 11g Release 2 (11.2)

Another difference is that you may not have access to dba_source.

Create a string with n characters

My contribution based on the algorithm for fast exponentiation.

/**
 * Repeats the given {@link String} n times.
 * 
 * @param str
 *            the {@link String} to repeat.
 * @param n
 *            the repetition count.
 * @throws IllegalArgumentException
 *             when the given repetition count is smaller than zero.
 * @return the given {@link String} repeated n times.
 */
public static String repeat(String str, int n) {
    if (n < 0)
        throw new IllegalArgumentException(
                "the given repetition count is smaller than zero!");
    else if (n == 0)
        return "";
    else if (n == 1)
        return str;
    else if (n % 2 == 0) {
        String s = repeat(str, n / 2);
        return s.concat(s);
    } else
        return str.concat(repeat(str, n - 1));
}

I tested the algorithm against two other approaches:

  • Regular for loop using String.concat() to concatenate string
  • Regular for loop using a StringBuilder

Test code (concatenation using a for loop and String.concat() becomes to slow for large n, so I left it out after the 5th iteration).

/**
 * Test the string concatenation operation.
 * 
 * @param args
 */
public static void main(String[] args) {
    long startTime;
    String str = " ";

    int n = 1;
    for (int j = 0; j < 9; ++j) {
        n *= 10;
        System.out.format("Performing test with n=%d\n", n);

        startTime = System.currentTimeMillis();
        StringUtil.repeat(str, n);
        System.out
                .format("\tStringUtil.repeat() concatenation performed in    %d milliseconds\n",
                        System.currentTimeMillis() - startTime);

        if (j <5) {
            startTime = System.currentTimeMillis();
            String string = "";
            for (int i = 0; i < n; ++i)
                string = string.concat(str);
            System.out
                    .format("\tString.concat() concatenation performed in        %d milliseconds\n",
                            System.currentTimeMillis() - startTime);
        } else
            System.out
                    .format("\tString.concat() concatenation performed in        x milliseconds\n");
        startTime = System.currentTimeMillis();
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < n; ++i)
            b.append(str);
        b.toString();
        System.out
                .format("\tStringBuilder.append() concatenation performed in %d milliseconds\n",
                        System.currentTimeMillis() - startTime);
    }
}

Results:

Performing test with n=10
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        0 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=100
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=1000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=10000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        43 milliseconds
    StringBuilder.append() concatenation performed in 5 milliseconds
Performing test with n=100000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1579 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=1000000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 10 milliseconds
Performing test with n=10000000
    StringUtil.repeat() concatenation performed in    7 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 112 milliseconds
Performing test with n=100000000
    StringUtil.repeat() concatenation performed in    80 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 1107 milliseconds
Performing test with n=1000000000
    StringUtil.repeat() concatenation performed in    1372 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 12125 milliseconds

Conclusion:

  • For large n - use the recursive approach
  • For small n - for loop has sufficient speed

WSDL/SOAP Test With soapui

definitions is a root element of WSDL so it looks like you are not loading WSDL.

Edit:

I tested it and it looks like the whole problem is with your web server. Your web server returns WSDL to browser but it doesn't return it to any tool because these tools are using very minimalistic HTTP requests without many HTTP headers. One of missing headers is Accept. Once this header is not included in the request your server throws HTTP 400 Bad request.

The easy approach to continue is opening WSDL in the browser, save the wsdl to a file and import that file to soapUI instead of the WSDL from URL.

Convert all strings in a list to int

You can do it simply in one line when taking input.

[int(i) for i in input().split("")]

Split it where you want.

If you want to convert a list not list simply put your list name in the place of input().split("").

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

You should check the $GOPATH directory. If there is an empty directory of the package name, go get doesn't download the package from the repository.

For example, If I want to get the github.com/googollee/go-socket.io package from it's github repository, and there is already an empty directory github.com/googollee/go-socket.io in the $GOPATH, go get doesn't download the package and then complains that there is no buildable Go source file in the directory. Delete any empty directory first of all.

Is it possible to get all arguments of a function as single object inside that function?

In ES6, use Array.from:

function foo()
  {
  foo.bar = Array.from(arguments);
  foo.baz = foo.bar.join();
  }

foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"

For non-ES6 code, use JSON.stringify and JSON.parse:

function foo()
  {
  foo.bar = JSON.stringify(arguments); 
  foo.baz = JSON.parse(foo.bar); 
  }

/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]

/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]

If preservation is needed instead of stringification, use the internal structured cloning algorithm.

If DOM nodes are passed, use XMLSerializer as in an unrelated question.

with (new XMLSerializer()) {serializeToString(document.documentElement) }

If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringify to work properly.

References

update to python 3.7 using anaconda

conda create -n py37 -c anaconda anaconda=5.3

seems to be working.

iOS: how to perform a HTTP POST request?

EDIT: ASIHTTPRequest has been abandoned by the developer. It's still really good IMO, but you should probably look elsewhere now.

I'd highly recommend using the ASIHTTPRequest library if you are handling HTTPS. Even without https it provides a really nice wrapper for stuff like this and whilst it's not hard to do yourself over plain http, I just think the library is nice and a great way to get started.

The HTTPS complications are far from trivial in various scenarios, and if you want to be robust in handling all the variations, you'll find the ASI library a real help.

android.os.NetworkOnMainThreadException with android 4.2

android.os.NetworkOnMainThreadException occurs when you try to access network on your main thread (You main activity execution). To avoid this, you must create a separate thread or AsyncTask or Runnable implementation to execute your JSON data loading. Since HoneyComb you can not further execute the network task on main thread. Here is the implementation using AsyncTask for a network task execution

Callback functions in C++

There is also the C way of doing callbacks: function pointers

//Define a type for the callback signature,
//it is not necessary, but makes life easier

//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*CallbackType)(float);  


void DoWork(CallbackType callback)
{
  float variable = 0.0f;

  //Do calculations

  //Call the callback with the variable, and retrieve the
  //result
  int result = callback(variable);

  //Do something with the result
}

int SomeCallback(float variable)
{
  int result;

  //Interpret variable

  return result;
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWork(&SomeCallback);
}

Now if you want to pass in class methods as callbacks, the declarations to those function pointers have more complex declarations, example:

//Declaration:
typedef int (ClassName::*CallbackType)(float);

//This method performs work using an object instance
void DoWorkObject(CallbackType callback)
{
  //Class instance to invoke it through
  ClassName objectInstance;

  //Invocation
  int result = (objectInstance.*callback)(1.0f);
}

//This method performs work using an object pointer
void DoWorkPointer(CallbackType callback)
{
  //Class pointer to invoke it through
  ClassName * pointerInstance;

  //Invocation
  int result = (pointerInstance->*callback)(1.0f);
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWorkObject(&ClassName::Method);
  DoWorkPointer(&ClassName::Method);
}

What's the difference between ISO 8601 and RFC 3339 Date Formats?

There are lots of differences between ISO 8601 and RFC 3339. Here is some examples to give you an idea:

2020-12-09T16:09:53+00:00 is a date time value that is compliant both both standards.

2020-12-09 16:09:53+00:00 uses a space to separate the date and time. This is allowed by RFC 3339 but not allowed by ISO 8601.

2020-12-09T16:09:53-00:00 has a negative sign in the time offset. This is allowed by RFC 3339 but not allowed by ISO 8601.

20201209T160953Z omits the hyphens. This is allowed by ISO 8601 but not allowed by RFC 3339.

ISO 8601 allows for things like ordinal dates such as 2020-344 which represents the 344th day of year 2020. RFC 3339 doesn't allow for that.

For your questions:

Is one just an extension?

No. As shown above each standard supports syntax variations not supported by the the other standard. So one syntax is not a superset or an extension of the other.

Should I use one over the other?

Of course this depends on your scenario. A safe general strategy is to generate date time strings that are valid by both standards.

Another good general strategy is to use an existing standard library for parsing/formatting date time strings and not write custom implementations unless you are addressing a genuinely custom scenario.

Do I really need to care that bad?

Well, that's up to you. Most regular developers who deal with date time strings should have a high level understanding but don't need to dive into the details.

How do I move to end of line in Vim?

The main question - end of line

$ goes to the end of line, remains in command mode

A goes to the end of line, switches to insert mode

Conversely - start of line (technically the first non-whitespace character)

^ goes to the start of line, remains in command mode

I (uppercase i) goes to the start of line, switches to insert mode

Further - start of line (technically the first column irrespective of whitespace)

0 (zero) goes to the start of line, remains in command mode

0i (zero followed by lowercase i) goes the start of line, switches to insert mode

For those starting to learn vi, here is a good introduction to vi by listing side by side vi commands to typical Windows GUI Editor cursor movement and shortcut keys.

vi editor for Windows users

How to always show the vertical scrollbar in a browser?

Add the class to the div you want to be scrollable.

overflow-x: hidden; hides the horizantal scrollbar. While overflow-y: scroll; allows you to scroll vertically.

<!DOCTYPE html>
<html>
<head>
<style>
.scroll {
    width: 500px;
    height: 300px;
    overflow-x: hidden; 
    overflow-y: scroll;
}


</style>
</head>
<body>

<div class="scroll"><h1> DATA </h1></div>

Is there a macro to conditionally copy rows to another worksheet?

This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.

You may want to add logic to sort your monthly data after it's all been copied

Public Sub MoveData(MonthNumber As Integer, SheetName As String)

Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range

Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
    If Format(cell.Value, "MM") = MonthNumber Then
        copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
    End If
Next cell

End Sub

Sub copyRowTo(rng As Range, ws As Worksheet)
    Dim newRange As Range
    Set newRange = ws.Range("A1")
    If newRange.Offset(1).Value <> "" Then
        Set newRange = newRange.End(xlDown).Offset(1)
        Else
        Set newRange = newRange.Offset(1)
    End If
    rng.Copy
    newRange.PasteSpecial (xlPasteAll)
End Sub

Android List View Drag and Drop sort

I found DragSortListView worked well, although getting started on it could have been easier. Here's a brief tutorial on using it in Android Studio with an in-memory list:

  1. Add this to the build.gradle dependencies for your app:

    compile 'asia.ivity.android:drag-sort-listview:1.0' // Corresponds to release 0.6.1
    
  2. Create a resource for the drag handle ID by creating or adding to values/ids.xml:

    <resources>
        ... possibly other resources ...
        <item type="id" name="drag_handle" />
    </resources>
    
  3. Create a layout for a list item that includes your favorite drag handle image, and assign its ID to the ID you created in step 2 (e.g. drag_handle).

  4. Create a DragSortListView layout, something like this:

    <com.mobeta.android.dslv.DragSortListView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:dslv="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        dslv:drag_handle_id="@id/drag_handle"
        dslv:float_background_color="@android:color/background_light"/>
    
  5. Set an ArrayAdapter derivative with a getView override that renders your list item view.

        final ArrayAdapter<MyItem> itemAdapter = new ArrayAdapter<MyItem>(this, R.layout.my_item, R.id.my_item_name, items) { // The third parameter works around ugly Android legacy. http://stackoverflow.com/a/18529511/145173
            @Override public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                MyItem item = getItem(position);
                ((TextView) view.findViewById(R.id.my_item_name)).setText(item.getName());
                // ... Fill in other views ...
                return view;
            }
        };
    
        dragSortListView.setAdapter(itemAdapter);
    
  6. Set a drop listener that rearranges the items as they are dropped.

        dragSortListView.setDropListener(new DragSortListView.DropListener() {
            @Override public void drop(int from, int to) {
                MyItem movedItem = items.get(from);
                items.remove(from);
                if (from > to) --from;
                items.add(to, movedItem);
                itemAdapter.notifyDataSetChanged();
            }
        });
    

how to print json data in console.log

I used '%j' option in console.log to print JSON objects

console.log("%j", jsonObj);

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:
=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?

How to check if type is Boolean

if(['true', 'yes', '1'].includes(single_value)) {
    return  true;   
}
else if(['false', 'no', '0'].includes(single_value)) {
    return  false;  
}

if you have a string

How to get current date & time in MySQL?

$rs = $db->Insert('register',"'$fn','$ln','$email','$pass','$city','$mo','$fil'","'f_name','l_name=','email','password','city','contact','image'");

I want to truncate a text or line with ellipsis using JavaScript

HTML with JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

The result will be:

My long lo...

Cheers

G.

How to kill MySQL connections

No, there is no built-in MySQL command for that. There are various tools and scripts that support it, you can kill some connections manually or restart the server (but that will be slower).

Use SHOW PROCESSLIST to view all connections, and KILL the process ID's you want to kill.

You could edit the timeout setting to have the MySQL daemon kill the inactive processes itself, or raise the connection count. You can even limit the amount of connections per username, so that if the process keeps misbehaving, the only affected process is the process itself and no other clients on your database get locked out.

If you can't connect yourself anymore to the server, you should know that MySQL always reserves 1 extra connection for a user with the SUPER privilege. Unless your offending process is for some reason using a username with that privilege...

Then after you can access your database again, you should fix the process (website) that's spawning that many connections.

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Apache VirtualHost 403 Forbidden

It could be you haven't setup PHP~!

Loop backwards using indices in Python?

I wanted to loop through a two lists backwards at the same time so I needed the negative index. This is my solution:

a= [1,3,4,5,2]
for i in range(-1, -len(a), -1):
    print(i, a[i])

Result:

-1 2
-2 5
-3 4
-4 3
-5 1

Iterating through all the cells in Excel VBA or VSTO 2005

My VBA skills are a little rusty, but this is the general idea of what I'd do.
The easiest way to do this would be to iterate through a loop for every column:

public sub CellProcessing()
on error goto errHandler

    dim MAX_ROW as Integer   'how many rows in the spreadsheet
    dim i as Integer
    dim cols as String

    for i = 1 to MAX_ROW
        'perform checks on the cell here
        'access the cell with Range("A" & i) to get cell A1 where i = 1
    next i

exitHandler:
    exit sub
errHandler:
    msgbox "Error " & err.Number & ": " & err.Description
    resume exitHandler
end sub

it seems that the color syntax highlighting doesn't like vba, but hopefully this will help somewhat (at least give you a starting point to work from).

  • Brisketeer

How do I use IValidatableObject?

The thing i don't like about iValidate is it seems to only run AFTER all other validation.
Additionally, at least in our site, it would run again during a save attempt. I would suggest you simply create a function and place all your validation code in that. Alternately for websites, you could have your "special" validation in the controller after the model is created. Example:

 public ActionResult Update([DataSourceRequest] DataSourceRequest request, [Bind(Exclude = "Terminal")] Driver driver)
    {

        if (db.Drivers.Where(m => m.IDNumber == driver.IDNumber && m.ID != driver.ID).Any())
        {
            ModelState.AddModelError("Update", string.Format("ID # '{0}' is already in use", driver.IDNumber));
        }
        if (db.Drivers.Where(d => d.CarrierID == driver.CarrierID
                                && d.FirstName.Equals(driver.FirstName, StringComparison.CurrentCultureIgnoreCase)
                                && d.LastName.Equals(driver.LastName, StringComparison.CurrentCultureIgnoreCase)
                                && (driver.ID == 0 || d.ID != driver.ID)).Any())
        {
            ModelState.AddModelError("Update", "Driver already exists for this carrier");
        }

        if (ModelState.IsValid)
        {
            try
            {

add Shadow on UIView using swift 3

loginView.layer.shadowOpacity = 1.0

Generate your own Error code in swift 3

 let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild UserName or Password"]) as Error
            self.showLoginError(error)

create an NSError object and typecast it to Error ,show it anywhere

private func showLoginError(_ error: Error?) {
    if let errorObj = error {
        UIAlertController.alert("Login Error", message: errorObj.localizedDescription).action("OK").presentOn(self)
    }
}

What is the correct way to write HTML using Javascript?

I'm not particularly great at JavaScript or its best practices, but document.write() along with innerHtml() basically allows you to write out strings that may or may not be valid HTML; it's just characters. By using the DOM, you ensure proper, standards-compliant HTML that will keep your page from breaking via plainly bad HTML.

And, as Tom mentioned, JavaScript is done after the page is loaded; it'd probably be a better practice to have the initial setup for your page to be done via standard HTML (via .html files or whatever your server does [i.e. php]).

Performing user authentication in Java EE / JSF using j_security_check

It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.

Postgres ERROR: could not open file for reading: Permission denied

Assuming the psql command-line tool, you may use \copy instead of copy.

\copy opens the file and feeds the contents to the server, whereas copy tells the server the open the file itself and read it, which may be problematic permission-wise, or even impossible if client and server run on different machines with no file sharing in-between.

Under the hood, \copy is implemented as COPY FROM stdin and accepts the same options than the server-side COPY.

Avoid web.config inheritance in child web application using inheritInChildApplications

We were getting an error related to this after a recent release of code to one of our development environments. We have an application that is a child of another application. This relationship has been working fine for YEARS until yesterday.

The problem:
We were getting a yellow stack trace error due to duplicate keys being entered. This is because both the web.config for the child and parent applications had this key. But this existed for many years like this without change. Why all of sudden its an issue now?

The solution:
The reason this was never a problem is because the keys AND values were always the same. Yesterday we updated our SQL connection strings to include the Application Name in the connection string. This made the string unique and all of sudden started to fail.

Without doing any research on the exact reason for this, I have to assume that when the child application inherits the parents web.config values, it ignores identical key/value pairs.

We were able to solve it by wrapping the connection string like this

    <location path="." inheritInChildApplications="false">
        <connectionStrings>
            <!-- Updated connection strings go here -->
        </connectionStrings>
    </location>

Edit: I forgot to mention that I added this in the PARENTS web.config. I didn't have to modify the child's web.config.

Thanks for everyones help on this, saved our butts.

How to use regex in XPath "contains" function

If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()

Does this work for you?

String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));

how to cancel/abort ajax request in axios

import React, { Component } from "react";
import axios from "axios";

const CancelToken = axios.CancelToken;

let cancel;

class Abc extends Component {
  componentDidMount() {
    this.Api();
  }

  Api() {
      // Cancel previous request
    if (cancel !== undefined) {
      cancel();
    }
    axios.post(URL, reqBody, {
        cancelToken: new CancelToken(function executor(c) {
          cancel = c;
        }),
      })
      .then((response) => {
        //responce Body
      })
      .catch((error) => {
        if (axios.isCancel(error)) {
          console.log("post Request canceled");
        }
      });
  }

  render() {
    return <h2>cancel Axios Request</h2>;
  }
}

export default Abc;

Convert negative data into positive data in SQL Server

UPDATE mytbl
SET a = ABS(a)
where a < 0

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

You can also use Edit Site List and make it be an exception so that you can run it from the specific website.

Sort a single String in Java

In Java 8 it can be done with:

String s = "edcba".chars()
    .sorted()
    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
    .toString();

A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:

String sorted =
    Stream.of("edcba".split(""))
        .sorted()
        .collect(Collectors.joining());

MySQL SELECT last few days?

Use for a date three days ago:

WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

Check the DATE_ADD documentation.

Or you can use:

WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )

How to add scroll bar to the Relative Layout?

The following code should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >

<TextView
    android:id="@+id/textView1"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="64dp"
    android:text="Email" />

<TextView
    android:id="@+id/textView2"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="41dp"
    android:text="Password" />

<TextView
    android:id="@+id/textView3"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="47dp"
    android:text="Confirm Password" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textView4"
    android:inputType="textEmailAddress" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />


<TextView
    android:id="@+id/textView4"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="42dp"
    android:text="Date of Birth" />

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView4" />

<TextView
    android:id="@+id/textView5"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/datePicker1"
    android:layout_marginTop="60dp"
    android:layout_toLeftOf="@+id/datePicker1"
    android:text="Gender" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView5"
    android:layout_alignBottom="@+id/textView5"
    android:layout_alignLeft="@+id/editText3"
    android:layout_marginLeft="24dp"
    android:text="Male" />

<RadioButton
    android:id="@+id/radioButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/radioButton1"
    android:layout_below="@+id/radioButton1"
    android:layout_marginTop="14dp"
    android:text="Female" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="23dp"
    android:layout_toLeftOf="@+id/radioButton2"
    android:background="@drawable/rectbutton"
    android:text="Sign Up" />

Common CSS Media Queries Break Points

I'm using 4 break points but as ralph.m said each site is unique. You should experiment. There are no magic breakpoints due to so many devices, screens, and resolutions.

Here is what I use as a template. I'm checking the website for each breakpoint on different mobile devices and updating CSS for each element (ul, div, etc.) not displaying correctly for that breakpoint.

So far that was working on multiple responsive websites I've made.

/* SMARTPHONES PORTRAIT */
@media only screen and (min-width: 300px) {


}

/* SMARTPHONES LANDSCAPE */
@media only screen and (min-width: 480px) {


}

/* TABLETS PORTRAIT */
@media only screen and (min-width: 768px) {


}


/* TABLET LANDSCAPE / DESKTOP */
@media only screen and (min-width: 1024px) {


}    

UPDATE

As per September 2015, I'm using a better one. I find out that these media queries breakpoints match many more devices and desktop screen resolutions.

Having all CSS for desktop on style.css

All media queries on responsive.css: all CSS for responsive menu + media break points

@media only screen and (min-width: 320px) and (max-width: 479px){ ... }

@media only screen and (min-width: 480px) and (max-width: 767px){ ... }

@media only screen and (min-width: 768px) and (max-width: 991px){ ... }

@media only screen and (min-width: 992px){ ... }

Update 2019: As per Hugo comment below, I removed max-width 1999px because of the new very wide screens.

How do I get the file name from a String containing the Absolute file path?

you can use path = C:\Hello\AnotherFolder\TheFileName.PDF

String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

How to enable CORS in flask

All the responses above work okay, but you'll still probably get a CORS error, if the application throws an error you are not handling, like a key-error, if you aren't doing input validation properly, for example. You could add an error handler to catch all instances of exceptions and add CORS response headers in the server response

So define an error handler - errors.py:

from flask import json, make_response, jsonify
from werkzeug.exceptions import HTTPException

# define an error handling function
def init_handler(app):

    # catch every type of exception
    @app.errorhandler(Exception)
    def handle_exception(e):

        #loggit()!          

        # return json response of error
        if isinstance(e, HTTPException):
            response = e.get_response()
            # replace the body with JSON
            response.data = json.dumps({
                "code": e.code,
                "name": e.name,
                "description": e.description,
            })
        else:
            # build response
            response = make_response(jsonify({"message": 'Something went wrong'}), 500)

        # add the CORS header
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.content_type = "application/json"
        return response

then using Billal's answer:

from flask import Flask
from flask_cors import CORS

# import error handling file from where you have defined it
from . import errors

app = Flask(__name__)
CORS(app) # This will enable CORS for all routes
errors.init_handler(app) # initialise error handling 

C++ int to byte array

You don't need a whole function for this; a simple cast will suffice:

int x;
static_cast<char*>(static_cast<void*>(&x));

Any object in C++ can be reinterpreted as an array of bytes. If you want to actually make a copy of the bytes into a separate array, you can use std::copy:

int x;
char bytes[sizeof x];
std::copy(static_cast<const char*>(static_cast<const void*>(&x)),
          static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x,
          bytes);

Neither of these methods takes byte ordering into account, but since you can reinterpret the int as an array of bytes, it is trivial to perform any necessary modifications yourself.

How to dynamically create CSS class in JavaScript and apply?

There is a light jQuery plugin which allows to generate CSS declarations: jQuery-injectCSS

In fact, it uses JSS (CSS described by JSON), but it's quite easy to handle in order to generate dynamic css stylesheets.

$.injectCSS({
    "#test": {
        height: 123
    }
});

How to check if a string contains a specific text

Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.

If $a contains a string, you can use the following:

if (!empty($a)) {      // Means: if not empty
    ...
}

If you also need to confirm that $a is actually a string, use:

if (is_string($a) && !empty($a)) {      // Means: if $a is a string and not empty
    ...
}

SQL set values of one column equal to values of another column in the same table

Sounds like you're working in just one table so something like this:

update your_table
set B = A
where B is null

How to increase font size in a plot in R?

By trial and error, I've determined the following is required to set font size:

  1. cex doesn't work in hist(). Use cex.axis for the numbers on the axes, cex.lab for the labels.
  2. cex doesn't work in axis() either. Use cex.axis for the numbers on the axes.
  3. In place of setting labels using hist(), you can set them using mtext(). You can set the font size using cex, but using a value of 1 actually sets the font to 1.5 times the default!!! You need to use cex=2/3 to get the default font size. At the very least, this is the case under R 3.0.2 for Mac OS X, using PDF output.
  4. You can change the default font size for PDF output using pointsize in pdf().

I suppose it would be far too logical to expect R to (a) actually do what its documentation says it should do, (b) behave in an expected fashion.

What is the most efficient string concatenation method in python?

it pretty much depends on the relative sizes of the new string after every new concatenation. With the + operator, for every concatenation a new string is made. If the intermediary strings are relatively long, the + becomes increasingly slower because the new intermediary string is being stored.

Consider this case:

from time import time
stri=''
a='aagsdfghfhdyjddtyjdhmfghmfgsdgsdfgsdfsdfsdfsdfsdfsdfddsksarigqeirnvgsdfsdgfsdfgfg'
l=[]
#case 1
t=time()
for i in range(1000):
    stri=stri+a+repr(i)
print time()-t

#case 2
t=time()
for i in xrange(1000):
    l.append(a+repr(i))
z=''.join(l)
print time()-t

#case 3
t=time()
for i in range(1000):
    stri=stri+repr(i)
print time()-t

#case 4
t=time()
for i in xrange(1000):
    l.append(repr(i))
z=''.join(l)
print time()-t

Results

1 0.00493192672729

2 0.000509023666382

3 0.00042200088501

4 0.000482797622681

In the case of 1&2, we add a large string, and join() performs about 10 times faster. In case 3&4, we add a small string, and '+' performs slightly faster

Store images in a MongoDB database

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

How do I restart nginx only after the configuration test was successful on Ubuntu?

Actually, as far as I know, nginx would show an empty message and it wouldn't actually restart if the configuration is bad.

The only way to screw it up is by doing an nginx stop and then start again. It would succeed to stop, but fail to start.

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

Using set_facts and with_items together in Ansible

I was hunting around for an answer to this question. I found this helpful. The pattern wasn't apparent in the documentation for with_items.

https://github.com/ansible/ansible/issues/39389

- hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: set_fact
      set_fact:
        foo: "{{ foo }} + [ '{{ item }}' ]"
      with_items:
        - "one"
        - "two"
        - "three"
      vars:
        foo: []

    - name: Print the var
      debug:
        var: foo

Activity restart on rotation Android

Note: I post this answer if someone in the future face the same problem as me. For me the following line wasn't enought:

android:configChanges="orientation"

When I rotated the screen, the method `onConfigurationChanged(Configuration newConfig) did't get called.

Solution: I also had to add "screenSize" even if the problem had to do with the orientation. So in the AndroidManifest.xml - file, add this:

android:configChanges="keyboardHidden|orientation|screenSize"

Then implement the method onConfigurationChanged(Configuration newConfig)

Efficiently counting the number of lines of a text file. (200mb+)

There is another answer that I thought might be a good addition to this list.

If you have perl installed and are able to run things from the shell in PHP:

$lines = exec('perl -pe \'s/\r\n|\n|\r/\n/g\' ' . escapeshellarg('largetextfile.txt') . ' | wc -l');

This should handle most line breaks whether from Unix or Windows created files.

TWO downsides (at least):

1) It is not a great idea to have your script so dependent upon the system its running on ( it may not be safe to assume Perl and wc are available )

2) Just a small mistake in escaping and you have handed over access to a shell on your machine.

As with most things I know (or think I know) about coding, I got this info from somewhere else:

John Reeve Article

How to convert java.util.Date to java.sql.Date?

Converting java.util.Data to java.sql.Data will loose hour, minute and second. So if it is possible, I suggest you use java.sql.Timestamp like this:

prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));

For more info, you can check this question.

How to install PostgreSQL's pg gem on Ubuntu?

Another option is to use Homebrew which works on Linux and macOS to install just the supporting libraries:

brew install libpq

then

brew link libpq --force

(the --force option is required because it conflicts with the postgres formula.)

how to convert binary string to decimal?

parseInt() with radix is a best solution (as was told by many):

But if you want to implement it without parseInt, here is an implementation:

  function bin2dec(num){
    return num.split('').reverse().reduce(function(x, y, i){
      return (y === '1') ? x + Math.pow(2, i) : x;
    }, 0);
  }

How to get the directory of the currently running file?

Use package osext

It's providing function ExecutableFolder() that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.

Online documentation

package main

import (
    "github.com/kardianos/osext"
    "fmt"
    "log"
)

func main() {
    folderPath, err := osext.ExecutableFolder()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(folderPath)
}

Is there a common Java utility to break a list into batches?

With Java 9 you can use IntStream.iterate() with hasNext condition. So you can simplify the code of your method to this:

public static <T> List<List<T>> getBatches(List<T> collection, int batchSize) {
    return IntStream.iterate(0, i -> i < collection.size(), i -> i + batchSize)
            .mapToObj(i -> collection.subList(i, Math.min(i + batchSize, collection.size())))
            .collect(Collectors.toList());
}

Using {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, the result of getBatches(numbers, 4) will be:

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

Convert Json String to C# Object List

Try to change type of ScoreIfNoMatch, like this:

   public class MatrixModel
        {
            public string S1 { get; set; }
            public string S2 { get; set; }
            public string S3 { get; set; }
            public string S4 { get; set; }
            public string S5 { get; set; }
            public string S6 { get; set; }
            public string S7 { get; set; }
            public string S8 { get; set; }
            public string S9 { get; set; }
            public string S10 { get; set; }
            // the type should be string
            public string ScoreIfNoMatch { get; set; }
        }

Iterator invalidation rules

It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator, std::front_insert_iterator, std::insert_iterator) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.

For example, when you are performing a series of insertion operations into a std::vector by using std::insert_iterator it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.

This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.

For example, this code

std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);

for (unsigned n = 20; n > 0; --n)
  *it_ins++ = rand();

is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it will obviously become invalid, but it_ins will continue to remain valid.

[Ljava.lang.Object; cannot be cast to

In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")

This return entity type rather than object type

How do I get the XML root node with C#?

I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.

  using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
    while (reader.Read()) {
      // first element is the root element
      if (reader.NodeType == XmlNodeType.Element) {
        System.Console.WriteLine(reader.Name);
        break;
      }
    }
  }

Can an abstract class have a constructor?

Not only can it, it always does. If you do not specify one then it has a default no arg constructor, just like any other class. In fact, ALL classes, including nested and anonymous classes, will get a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one, so you will always get the default constructor).

A good example of an abstract class having a constructor is the Calendar class. You get a Calendar object by calling Calendar.getInstance(), but it also has constructors which are protected. The reason its constructors are protected is so that only its subclasses can call them (or classes in the same package, but since it's abstract, that doesn't apply). GregorianCalendar is an example of a class that extends Calendar.

ToList().ForEach in Linq

employees.ToList().ForEach(
     emp=>
     {
          collection.AddRange(emp.Departments);
          emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
     });

sys.argv[1], IndexError: list index out of range

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp

Add left/right horizontal padding to UILabel

If you want to add padding to UILabel but not want to subclass it you can put your label in a UIView and give paddings with autolayout like:

Padding with UIView and autolayout

Result:

Result

Spring Boot without the web server

In Spring boot, Spring Web dependency provides an embedded Apache Tomcat web server. If you remove spring-boot-starter-web dependency in the pom.xml then it doesn't provide an embedded web server.

remove the following dependency

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

You can use stepi or nexti (which can be abbreviated to si or ni) to step through your machine code.

How to remove empty lines with or without whitespace in Python

If you are not willing to try regex (which you should), you can use this:

s.replace('\n\n','\n')

Repeat this several times to make sure there is no blank line left. Or chaining the commands:

s.replace('\n\n','\n').replace('\n\n','\n')


Just to encourage you to use regex, here are two introductory videos that I find intuitive:
Regular Expressions (Regex) Tutorial
Python Tutorial: re Module

How can I make an svg scale with its parent container?

After like 48 hours of research, I ended up doing this to get proportional scaling:

NOTE: This sample is written with React. If you aren't using that, change the camel case stuff back to hyphens (ie: change backgroundColor to background-color and change the style Object back to a String).

<div
  style={{
    backgroundColor: 'lightpink',
    resize: 'horizontal',
    overflow: 'hidden',
    width: '1000px',
    height: 'auto',
  }}
>
  <svg
    width="100%"
    viewBox="113 128 972 600"
    preserveAspectRatio="xMidYMid meet"
  >
    <g> ... </g>
  </svg>
</div>

Here's what is happening in the above sample code:

VIEWBOX

MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox

min-x, min-y, width and height

ie: viewbox="0 0 1000 1000"

Viewbox is an important attribute because it basically tells the SVG what size to draw and where. If you used CSS to make the SVG 1000x1000 px but your viewbox was 2000x2000, you would see the top-left quarter of your SVG.

The first two numbers, min-x and min-y, determine if the SVG should be offset inside the viewbox.

My SVG needs to shift up/down or left/right

Examine this: viewbox="50 50 450 450"

The first two numbers will shift your SVG left 50px and up 50px, and the second two numbers are the viewbox size: 450x450 px. If your SVG is 500x500 but it has some extra padding on it, you can manipulate those numbers to move it around inside the "viewbox".

Your goal at this point is to change one of those numbers and see what happens.

You can also completely omit the viewbox, but then your milage will vary depending on every other setting you have at the time. In my experience, you will encounter issues with preserving aspect ratio because the viewbox helps define the aspect ratio.

PRESERVE ASPECT RATIO

MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio

Based on my research, there are lots of different aspect ratio settings, but the default one is called xMidYMid meet. I put it on mine to explicitly remind myself. xMidYMid meet makes it scale proportionately based on the midpoint X and Y. This means it stays centered in the viewbox.

WIDTH

MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/width

Look at my example code above. Notice how I set only width, no height. I set it to 100% so it fills the container it is in. This is what is probably contributing the most to answering this Stack Overflow question.

You can change it to whatever pixel value you want, but I'd recommend using 100% like I did to blow it up to max size and then control it with CSS via the parent container. I recommend this because you will get "proper" control. You can use media queries and you can control the size without crazy JavaScript.

SCALING WITH CSS

Look at my example code above again. Notice how I have these properties:

resize: 'horizontal', // you can safely omit this
overflow: 'hidden',   // if you use resize, use this to fix weird scrollbar appearance
width: '1000px',
height: 'auto',

This is additional, but it shows you how to allow the user to resize the SVG while maintaining the proper aspect ratio. Because the SVG maintains its own aspect ratio, you only need to make width resizable on the parent container, and it will resize as desired.

We leave height alone and/or set it to auto, and we control the resizing with width. I picked width because it is often more meaningful due to responsive designs.

Here is an image of these settings being used:

enter image description here

If you read every solution in this question and are still confused or don't quite see what you need, check out this link here. I found it very helpful:

https://css-tricks.com/scale-svg/

It's a massive article, but it breaks down pretty much every possible way to manipulate an SVG, with or without CSS. I recommend reading it while casually drinking a coffee or your choice of select liquids.

Keeping session alive with Curl and PHP

You also need to set the option CURLOPT_COOKIEFILE.

The manual describes this as

The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

Since you are using the cookie jar you end up saving the cookies when the requests finish, but since the CURLOPT_COOKIEFILE is not given, cURL isn't sending any of the saved cookies on subsequent requests.

Is there an easy way to return a string repeated X number of times?

I would go for Dan Tao's answer, but if you're not using .NET 4.0 you can do something like that:

public static string Repeat(this string str, int count)
{
    return Enumerable.Repeat(str, count)
                     .Aggregate(
                        new StringBuilder(str.Length * count),
                        (sb, s) => sb.Append(s))
                     .ToString();
}

How to include view/partial specific styling in AngularJS

'use strict'; angular.module('app') .run( [ '$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; } ] ) .config( [ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

            $urlRouterProvider
                .otherwise('/app/dashboard');
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: 'views/layout.html'
                })
                .state('app.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard.html',
                    ncyBreadcrumb: {
                        label: 'Dashboard',
                        description: ''
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                .state('ram', {
                    abstract: true,
                    url: '/ram',
                    templateUrl: 'views/layout-ram.html'
                })
                .state('ram.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard-ram.html',
                    ncyBreadcrumb: {
                        label: 'test'
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                 );

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I have been dealing with this problem for a while. I have changed everything as described in this post and even thought error occured. In that case make sure that you clean the project when changing settings in .xml or .properties file. In eclipse environment. Choose Project -> Clean

How to make a HTTP PUT request?

My Final Approach:

    public void PutObject(string postUrl, object payload)
        {
            var request = (HttpWebRequest)WebRequest.Create(postUrl);
            request.Method = "PUT";
            request.ContentType = "application/xml";
            if (payload !=null)
            {
                request.ContentLength = Size(payload);
                Stream dataStream = request.GetRequestStream();
                Serialize(dataStream,payload);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string returnString = response.StatusCode.ToString();
        }

public void Serialize(Stream output, object input)
            {
                var ser = new DataContractSerializer(input.GetType());
                ser.WriteObject(output, input);
            }

Remove carriage return in Unix

Here is the thing,

%0d is the carriage return character. To make it compatabile with Unix. We need to use the below command.

dos2unix fileName.extension fileName.extension

How to use Class<T> in Java?

In java <T> means Generic class. A Generic Class is a class which can work on any type of data type or in other words we can say it is data type independent.

public class Shape<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Where T means type. Now when you create instance of this Shape class you will need to tell the compiler for what data type this will be working on.

Example:

Shape<Integer> s1 = new Shape();
Shape<String> s2 = new Shape();

Integer is a type and String is also a type.

<T> specifically stands for generic type. According to Java Docs - A generic type is a generic class or interface that is parameterized over types.

EC2 instance has no public DNS

It is related to the VPC's feature called "DNS Hostnames". You can enable or disable it. Go to the VPC, under the Actions menu select the "Edit DNS Hostnames" item and then choose "Yes". After doing so, the public DNS of the EC2 instances should be displayed.

IIS_IUSRS and IUSR permissions in IIS8

I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.

In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.

Applying Modify/Write Permissions to the Correct User Account

  1. Right-click the domain when it appears under the Sites list, and choose Edit Permissions

    enter image description here

    Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.

    enter image description here

  2. Click the Edit button, then Add...

  3. In the text box, type IIS AppPool\MyApplicationPoolName, substituting MyApplicationPoolName with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com

    enter image description here

  4. Press the Check Names button. The text you typed will transform (notice the underline):

    enter image description here

  5. Press OK to add the user

  6. With the new user (your domain) selected, now you can safely provide any Modify or Write permissions

    enter image description here

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

This worked well for me on Ubuntu 18.04.

Open sql.lib.php file

nano +613 /usr/share/phpmyadmin/libraries/sql.lib.php

Replace this wrong code:

|| (count($analyzed_sql_results['select_expr'] == 1)

With this one:

|| ((count($analyzed_sql_results['select_expr']) == 1)

Save the file.

Restart your server with:

sudo service apache2 restart

And refresh PhpMyAdmin

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

How to change background and text colors in Sublime Text 3

  1. Go to the preferences
  2. Click on color scheme
  3. Choose your color scheme
  4. I chose plastic, for my case.

Permission is only granted to system app

Path In Android Studio in mac:

Android Studio -> Preferences -> Editor -> Inspections

Expand Android -> Expand Lint -> Expand Correctness

Uncheck the checkbox for Using system app permission

Click on "APPLY" -> "OK"

Indent starting from the second line of a paragraph with CSS

I needed to indent two rows to allow for a larger first word in a para. A cumbersome one-off solution is to place text in an SVG element and position this the same as an <img>. Using float and the SVG's height tag defines how many rows will be indented e.g.

<p style="color: blue; font-size: large; padding-top: 4px;">
<svg height="44" width="260" style="float:left;margin-top:-8px;"><text x="0" y="36" fill="blue" font-family="Verdana" font-size="36">Lorum Ipsum</text></svg> 
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
  • SVG's height and width determine area blocked out.
  • Y=36 is the depth to the SVG text baseline and same as font-size
  • margin-top's allow for best alignment of the SVG text and para text
  • Used first two words here to remind care needed for descenders

Yes it is cumbersome but it is also independent of the width of the containing div.

The above answer was to my own query to allow the first word(s) of a para to be larger and positioned over two rows. To simply indent the first two lines of a para you could replace all the SVG tags with the following single pixel img:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" style="float:left;width:260px;height:44px;" />

Word-wrap in an HTML table

It appears you need to set word-wrap:break-word; on a block element (div), with specified (non relative) width. Ex:

_x000D_
_x000D_
<table style="width: 100%;"><tr>_x000D_
    <td><div style="display:block; word-wrap: break-word; width: 40em;">loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</div></td>_x000D_
    <td><span style="display: inline;">Foo</span></td>_x000D_
</tr></table>
_x000D_
_x000D_
_x000D_

or using word-break:break-all per Abhishek Simon's suggestion.

PivotTable's Report Filter using "greater than"

One way to do this is to pull your field into the rows section of the pivot table from the Filter section. Then group the values that you want to keep into a group, using the group option on the menu. After that is completed, drag your field back into the Filters section. The grouping will remain and you can check or uncheck one box to remove lots of values.

Height of status bar in Android

The default height used to be 25dp. With Android Marshmallow (API 23) the height was reduced to 24dp.

Update: Please be aware that since the age of notches and punch-whole-cameras began, using a static height for the status bar no longer works. Please use window insets instead!

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

How to sort a List of objects by their date (java collections, List<Object>)

You can use this:

Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());

How to remove leading whitespace from each line in a file

For what it's worth, if you are editing this file, you can probably highlight all the lines and use your un-tab button.

  • In Vim, use Shift + V to highlight the lines, then press <<
  • If you're on a Mac, then you can use Atom, Sublime Text, etc., then highlight with your mouse and then press Shift + Tab

I am not sure if there is some requirement that this must be done from the command line. If so, then :thumbs-up: to the accepted answer! =)

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Worked by lowering the spring boot starter parent to 1.5.13

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.13.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

React.js create loop through Array

You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

How to draw circle in html page?

The followings are my 9 solutions. Feel free to insert text into the divs or svg elements.

  1. border-radius
  2. clip-path
  3. html entity
  4. pseudo element
  5. radial-gradient
  6. svg circle & path
  7. canvas arc()
  8. img tag
  9. pre tag

_x000D_
_x000D_
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#B90136';
ctx.fill();
_x000D_
#circle1 {
  background-color: #B90136;
  width: 100px;
  height: 100px;
  border-radius: 50px;
}

#circle2 {
  background-color: #B90136;
  width: 100px;
  height: 100px;
  clip-path: circle();
}

#circle3 {
  color: #B90136;
  font-size: 100px;
  line-height: 100px;
}

#circle4::before {
  content: "";
  display: block;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  background-color: #B90136;
}

#circle5 {
  background-image: radial-gradient(#B90136 70%, transparent 30%);
  height: 100px;
  width: 100px;
}
_x000D_
<h3>1 border-radius</h3>
<div id="circle1"></div>
<hr/>
<h3>2 clip-path</h3>
<div id="circle2"></div>
<hr/>
<h3>3 html entity</h3>
<div id="circle3">&#11044;</div>
<hr/>
<h3>4 pseudo element</h3>
<div id="circle4"></div>
<hr/>
<h3>5 radial-gradient</h3>
<div id="circle5"></div>
<hr/>
<h3>6 svg circle & path</h3>
<svg width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="#B90136" />
</svg>
<hr/>
<h3>7 canvas arc()</h3>
<canvas id="myCanvas" width="100" height="100"></canvas>
<hr/>
<h3>8 img tag</h3>
&nbsp; &nbsp; &lt;img src="circle.png" width="100" height="100" /&gt;
<hr/>
<h3>9 pre tag</h3>
<pre style="line-height:8px;">
     +++
    +++++
   +++++++
  +++++++++
 +++++++++++
 +++++++++++
 +++++++++++
  +++++++++
   +++++++
    +++++
     +++
</pre>
_x000D_
_x000D_
_x000D_

No WebApplicationContext found: no ContextLoaderListener registered?

And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Loading PictureBox Image from resource file with path (Part 3)

Setting "Copy to Output Directory" to "Copy always" or "Copy if newer" may help for you.

Your PicPath is a relative path that is converted into an absolute path at some time while loading the image. Most probably you will see that there are no images on the specified location if you use Path.GetFullPath(PicPath) in Debug.

How to apply a function to two columns of Pandas dataframe

If you have a huge data-set, then you can use an easy but faster(execution time) way of doing this using swifter:

import pandas as pd
import swifter

def fnc(m,x,c):
    return m*x+c

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
df["y"] = df.swifter.apply(lambda x: fnc(x.m, x.x, x.c), axis=1)

Split string into individual words Java

Yet another method, using StringTokenizer :

String s = "I want to walk my dog";
StringTokenizer tokenizer = new StringTokenizer(s);

while(tokenizer.hasMoreTokens()) {
    System.out.println(tokenizer.nextToken());
}

Measuring function execution time in R

Another simple but very powerful way to do this is by using the package profvis. It doesn't just measure the execution time of your code but gives you a drill down for each function you execute. It can be used for Shiny as well.

library(profvis)

profvis({
  #your code here
})

Click here for some examples.

laravel throwing MethodNotAllowedHttpException

I also had the same error but had a different fix, in my XYZ.blade.php I had:

{!! Form::open(array('ul' => 'services.store')) !!}

which gave me the error, - I still don't know why- but when I changed it to

{!! Form::open(array('route' => 'services.store')) !!}

It worked!

I thought it was worth sharing :)

Not equal string

With Equals() you can also use a Yoda condition:

if ( ! "-1".Equals(myString) )

Using psql how do I list extensions installed in a database?

In psql that would be

\dx

See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html

Doing it in plain SQL it would be a select on pg_extension:

SELECT * 
FROM pg_extension

http://www.postgresql.org/docs/current/static/catalog-pg-extension.html

How to resize images proportionally / keeping the aspect ratio?

If I understand the question correctly, you don't even need jQuery for this. Shrinking the image proportionally on the client can be done with CSS alone: just set its max-width and max-height to 100%.

<div style="height: 100px">
<img src="http://www.getdigital.de/images/produkte/t4/t4_css_sucks2.jpg"
    style="max-height: 100%; max-width: 100%">
</div>?

Here's the fiddle: http://jsfiddle.net/9EQ5c/

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Suppose your project has the following structure and you want to do imports in the notebook.ipynb:

/app
  /mypackage
    mymodule.py
  /notebooks
    notebook.ipynb

If you are running Jupyter inside a docker container without any virtualenv it might be useful to create Jupyter (ipython) config in your project folder:

/app
  /profile_default
    ipython_config.py

Content of ipython_config.py:

c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append("/app")'
]

Open the notebook and check it out:

print(sys.path)

['', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/IPython/extensions', '/root/.ipython', '/app']

Now you can do imports in your notebook without any sys.path appending in the cells:

from mypackage.mymodule import myfunc

Highlight Bash/shell code in Markdown files

Per the documentation from GitHub regarding GFM syntax highlighted code blocks

We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.

Rendered on GitHub, console makes the lines after the console blue. bash, sh, or shell don't seem to "highlight" much ...and you can use posh for PowerShell or CMD.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

How do I see the commit differences between branches in git?

I'd suggest the following to see the difference "in commits". For symmetric difference, repeat the command with inverted args:

git cherry -v master [your branch, or HEAD as default]

Java Runtime.getRuntime(): getting output from executing a command line program

If use are already have Apache commons-io available on the classpath, you may use:

Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());

Find where python is installed (if it isn't default dir)

In unix (mac os X included) terminal you can do

which python

and it will tell you.

NuGet behind a proxy

Above Solution by @arcain Plus below steps solved me the issue

  1. Modifying the "package sources" under Nuget package manger settings to check the checkbox to use the nuget.org settings resolved my issue.

  2. I did also changed to use that(nuget.org) as the first choice of package source
    I did uncheck my company package sources to ensure the nuget was always picked up from global sources.

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I have a project that uses generators a lot and needed this to be automatic, so I copied the index_name function from the rails source to override it. I added this in config/initializers/generated_index_name.rb:

# make indexes shorter for postgres
require "active_record/connection_adapters/abstract/schema_statements"
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module SchemaStatements
      def index_name(table_name, options) #:nodoc:
        if Hash === options
          if options[:column]
            "ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
          elsif options[:name]
            options[:name]
          else
            raise ArgumentError, "You must specify the index name"
          end
        else
          index_name(table_name, index_name_options(options))
        end
      end
    end
  end
end

It creates indexes like ix_assignments_on_case_id__project_id and just truncates it to 63 characters if it's still too long. That's still going to be non-unique if the table name is very long, but you can add complications like shortening the table name separately from the column names or actually checking for uniqueness.

Note, this is from a Rails 5.2 project; if you decide to do this, copy the source from your version.

jQuery if statement to check visibility

 $('#column-left form').hide();
 $('.show-search').click(function() {
    $('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
    $('#column-left form').hide(); 
    if(!($('#column-left form').is(":visible"))) {
        $("#offers").show();
    } else {
        $('#offers').hide();
    }
  });

Disable beep of Linux Bash on Windows 10

  1. To disable the beep in bash you need to uncomment (or add if not already there) the line set bell-style none in your /etc/inputrc file.

    Note: Since it is a protected file you need to be a privileged user to edit it (i.e. launch your text editor with something like sudo <editor> /etc/inputrc).

  2. To disable the beep also in vim you need to add set visualbell in your ~/.vimrc file.

  3. To disable the beep also in less (i.e. also in man pages and when using "git diff") you need to add export LESS="$LESS -R -Q" in your ~/.profile file.

#ifdef replacement in the Swift language

Xcode 8 and above

Use Active Compilation Conditions setting in Build settings / Swift compiler - Custom flags.

  • This is the new build setting for passing conditional compilation flags to the Swift compiler.
  • Simple add flags like this: ALPHA, BETA etc.

Then check it with compilation conditions like this:

#if ALPHA
    //
#elseif BETA
    //
#else
    //
#endif

Tip: You can also use #if !ALPHA etc.

DataAdapter.Fill(Dataset)

You need to do this:

OleDbConnection connection = new OleDbConnection(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();

string query = 
    @"SELECT tbl_Computer.*,  tbl_Besitzer.*
    FROM tbl_Computer 
    INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
    WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection); 
DBAdapter.Fill(DS);

By the way, what is this DataSet1? This should be "DataSet".

Apache shows PHP code instead of executing it

I found this to solve my related problem. I added it to the relevant <Directory> section:

<IfModule mod_php5.c>
    php_admin_flag engine on
</IfModule>

Angular-Material DateTime Picker Component?

For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.

I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:

When no input has been given yet, I would advise:

  • On-click of the component, the datepicker should always be triggered first.
  • After the datepicker closes, have the timepicker automatically popup.
  • Use touchUi = true on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.
  • Make sure the datepicker also shows up when clicking on the form (instead of only on the icon which is the default).
  • Use this solution to use the timepicker also in a material form, when placing them behind each other, it looks like it is one form.

After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.

My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.

Edit: Result

enter image description here

<div fxLayout="row">
  <div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
    <mat-form-field>
      <input matInput [ngxTimepicker]="endTime" [format]="24"  placeholder="{{placeholderTime}}" formControlName="endTime" />
    </mat-form-field>
    <ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
  </div>
  <div>
    <mat-form-field>
      <input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
             [min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
    </mat-form-field>
  </div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';

import * as moment_ from 'moment';

const moment = moment_;

import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

class DateConfig {
  startView: 'month' | 'year' | 'multi-year';
  touchUi: boolean;
  minDate: moment_.Moment;
  maxDate: moment_.Moment;
}

@Component({
  selector: 'cb-datetimepicker',
  templateUrl: './cb-datetimepicker.component.html',
  styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {

  @Input() disabled: boolean;
  @Input() placeholderDate: string;
  @Input() placeholderTime: string;
  @Input() model: Date;
  @Input() purpose: string;
  @Input() dateOnly: boolean;

  @Output() dateUpdate = new EventEmitter<Date>();

  public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);

  public dateForm: FormControl;
  public timeFormGroup: FormGroup;
  public endTime: FormControl;

  public momentDate: moment_.Moment;
  public config: DateConfig;

  //myGroup: FormGroup;


  constructor(private adapter : DateAdapter<any>) { }

  ngOnInit() {

    this.adapter.setLocale("nl-NL");//todo: configurable
    this.config = new DateConfig();
    if (this.purpose === "birthday") {
      this.config.startView = 'multi-year';
      this.config.maxDate = moment().add('year', -15);
      this.config.minDate = moment().add('year', -90);
      this.dateOnly = true;
    } //add more configurations
    else {
      this.config.startView = 'month';
      this.config.maxDate = moment().add('year', 100);
      this.config.minDate = moment().add('year', -100);
    }


    if (window.screen.width < 767) {
      this.config.touchUi = true;
    }



    if (this.model) {
      var mom = moment(this.model);
      if (mom.isBefore(moment('1900-01-01'))) {
        this.momentDate = moment();
      } else {
        this.momentDate = mom;
      }
    } else {
      this.momentDate = moment();
    }

    this.dateForm = new FormControl(this.momentDate);
    if (this.disabled) {
      this.dateForm.disable();
    }
    this.endTime = new FormControl(this.momentDate.format("HH:mm"));

    this.timeFormGroup = new FormGroup({
      endTime: this.endTime
    });


  }


  public dateChange(date: MatDatepickerInputEvent<any>) {

    if (moment.isMoment(date.value)) {
      this.momentDate = moment(date.value);
      if (this.dateOnly) {
        this.momentDate = this.momentDate.utc(true);
      } 
      var newDate = this.momentDate.toDate();
      this.model = newDate;
      this.dateUpdate.emit(newDate);
    }

    console.log("datechange",date);
  }

  public timeChange(time: string) {

    var splitted = time.split(':');
    var hour = splitted[0];
    var minute = splitted[1];

    console.log("time change", time);
   this.momentDate = this.momentDate.set('hour', parseInt(hour));
    this.momentDate = this.momentDate.set('minute', parseInt(minute));

    var newDate = this.momentDate.toDate();
    this.model = newDate;
    this.dateUpdate.emit(newDate);
  }
}

One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126

I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).

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

Here is a simple approach:

my_string = 'abcdefg'
print(text.find('def'))

Output:

3

I the substring is not there, you will get -1. For example:

my_string = 'abcdefg'
print(text.find('xyz'))

Output:

-1

Sometimes, you might want to throw exception if substring is not there:

my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present

Output:

Traceback (most recent call last):

File "test.py", line 6, in print(text.index('xyz'))

ValueError: substring not found

How to automatically generate a stacktrace when my program crashes

Linux

While the use of the backtrace() functions in execinfo.h to print a stacktrace and exit gracefully when you get a segmentation fault has already been suggested, I see no mention of the intricacies necessary to ensure the resulting backtrace points to the actual location of the fault (at least for some architectures - x86 & ARM).

The first two entries in the stack frame chain when you get into the signal handler contain a return address inside the signal handler and one inside sigaction() in libc. The stack frame of the last function called before the signal (which is the location of the fault) is lost.

Code

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif

#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#include <unistd.h>

/* This structure mirrors the one found in /usr/include/asm/ucontext.h */
typedef struct _sig_ucontext {
 unsigned long     uc_flags;
 ucontext_t        *uc_link;
 stack_t           uc_stack;
 sigcontext_t      uc_mcontext;
 sigset_t          uc_sigmask;
} sig_ucontext_t;

void crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)
{
 void *             array[50];
 void *             caller_address;
 char **            messages;
 int                size, i;
 sig_ucontext_t *   uc;

 uc = (sig_ucontext_t *)ucontext;

 /* Get the address at the time the signal was raised */
#if defined(__i386__) // gcc specific
 caller_address = (void *) uc->uc_mcontext.eip; // EIP: x86 specific
#elif defined(__x86_64__) // gcc specific
 caller_address = (void *) uc->uc_mcontext.rip; // RIP: x86_64 specific
#else
#error Unsupported architecture. // TODO: Add support for other arch.
#endif

 fprintf(stderr, "signal %d (%s), address is %p from %p\n", 
  sig_num, strsignal(sig_num), info->si_addr, 
  (void *)caller_address);

 size = backtrace(array, 50);

 /* overwrite sigaction with caller's address */
 array[1] = caller_address;

 messages = backtrace_symbols(array, size);

 /* skip first stack frame (points here) */
 for (i = 1; i < size && messages != NULL; ++i)
 {
  fprintf(stderr, "[bt]: (%d) %s\n", i, messages[i]);
 }

 free(messages);

 exit(EXIT_FAILURE);
}

int crash()
{
 char * p = NULL;
 *p = 0;
 return 0;
}

int foo4()
{
 crash();
 return 0;
}

int foo3()
{
 foo4();
 return 0;
}

int foo2()
{
 foo3();
 return 0;
}

int foo1()
{
 foo2();
 return 0;
}

int main(int argc, char ** argv)
{
 struct sigaction sigact;

 sigact.sa_sigaction = crit_err_hdlr;
 sigact.sa_flags = SA_RESTART | SA_SIGINFO;

 if (sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL) != 0)
 {
  fprintf(stderr, "error setting signal handler for %d (%s)\n",
    SIGSEGV, strsignal(SIGSEGV));

  exit(EXIT_FAILURE);
 }

 foo1();

 exit(EXIT_SUCCESS);
}

Output

signal 11 (Segmentation fault), address is (nil) from 0x8c50
[bt]: (1) ./test(crash+0x24) [0x8c50]
[bt]: (2) ./test(foo4+0x10) [0x8c70]
[bt]: (3) ./test(foo3+0x10) [0x8c8c]
[bt]: (4) ./test(foo2+0x10) [0x8ca8]
[bt]: (5) ./test(foo1+0x10) [0x8cc4]
[bt]: (6) ./test(main+0x74) [0x8d44]
[bt]: (7) /lib/libc.so.6(__libc_start_main+0xa8) [0x40032e44]

All the hazards of calling the backtrace() functions in a signal handler still exist and should not be overlooked, but I find the functionality I described here quite helpful in debugging crashes.

It is important to note that the example I provided is developed/tested on Linux for x86. I have also successfully implemented this on ARM using uc_mcontext.arm_pc instead of uc_mcontext.eip.

Here's a link to the article where I learned the details for this implementation: http://www.linuxjournal.com/article/6391

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

Typescript Date Type?

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;

What and where are the stack and heap?

I have something to share, although the major points are already covered.

Stack

  • Very fast access.
  • Stored in RAM.
  • Function calls are loaded here along with the local variables and function parameters passed.
  • Space is freed automatically when program goes out of a scope.
  • Stored in sequential memory.

Heap

  • Slow access comparatively to Stack.
  • Stored in RAM.
  • Dynamically created variables are stored here, which later requires freeing the allocated memory after use.
  • Stored wherever memory allocation is done, accessed by pointer always.

Interesting note:

  • Should the function calls had been stored in heap, it would had resulted in 2 messy points:
    1. Due to sequential storage in stack, execution is faster. Storage in heap would have resulted in huge time consumption thus making the whole program execute slower.
    2. If functions were stored in heap (messy storage pointed by pointer), there would have been no way to return to the caller address back (which stack gives due to sequential storage in memory).

How To Set A JS object property name from a variable

Along the lines of Sainath S.R's comment above, I was able to set a js object property name from a variable in Google Apps Script (which does not support ES6 yet) by defining the object then defining another key/value outside of the object:

var salesperson = ...

var mailchimpInterests = { 
        "aGroupId": true,
    };

mailchimpInterests[salesperson] = true;

Unclosed Character Literal error

'' encloses single char, while "" encloses a String.

Change

y = 'hello';

-->

y = "hello";

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

How to read large text file on windows?

While Large Text File Viewer works great for just looking at a large file (and is free!), if the file is either a delimited or fixed-width file, then you should check out File Query. Not only can it open a file of any size (I have personally opened a 280GB file, but it can go larger), but it lets you query the file as though it was in a database as well, finding out any sort of information you could want from it.

It is not free though, so it is more for people that work with large files a lot, but if you have a one-off problem, you can just use the 30-day trial for free.

How to count the number of columns in a table using SQL?

Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:

SELECT t.owner, 
       t.table_name, 
       t.num_rows, 
       Count(*) 
FROM   all_tables t 
       LEFT JOIN all_tab_columns c 
              ON t.table_name = c.table_name 
WHERE  num_rows IS NOT NULL 
GROUP  BY t.owner, 
          t.table_name, 
          t.num_rows 
ORDER  BY t.num_rows DESC; 

How do I switch between command and insert mode in Vim?

There is also one more solution for that kind of problem, which is rather rare, I think, and you may experience it, if you are using vim on OS X Sierra. Actually, it's a problem with Esc button — not with vim. For example, I wasnt able to exit fullscreen video on youtube using Esc, but I lived with that for a few months until I had experienced the same problem with vim.

I found this solution. If you are lazy enough to follow external link, switching off Siri and killing the process in Activity Monitor helped.

Set padding for UITextField with UITextBorderStyleNone

  1. Create a textfield Custom

PaddingTextField.swift

import UIKit
class PaddingTextField: UITextField {

@IBInspectable var paddingLeft: CGFloat = 0
@IBInspectable var paddingRight: CGFloat = 0

override func textRectForBounds(bounds: CGRect) -> CGRect {
    return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y,
        bounds.size.width - paddingLeft - paddingRight, bounds.size.height);
}

override func editingRectForBounds(bounds: CGRect) -> CGRect {
    return textRectForBounds(bounds)
}}
  1. Set your textfield class is PaddingTextField and custom your padding as you want enter image description here enter image description here

  2. Enjoy it

final

How to get base url with jquery or javascript?

Put this in your header, so it will be available whenever you need it.

var base_url = "<?php echo base_url();?>";

You will get http://localhost:81/your-path-file or http://localhost/your-path-file.

C# version of java's synchronized keyword?

static object Lock = new object();

lock (Lock) 
{
// do stuff
}

How to run a program automatically as admin on Windows 7 at startup?

I think that using the task scheduler to autostart programs is not very user friendly, and sometimes it has had side effects for me (e.g. tray icon for a program is not added).

To remedy this, I have made a program called Elevated Startup that first relaunches itself with administrator privileges, then it launches all files in a directory. Since Elevated Startup is now elevated, all the programs it then launches is also given administrator privileges. The directory is on the start menu next to the classic Startup directory, and works very much the same.

You may encounter one UAC dialog when the program relaunches itself, depending on your UAC settings.

You can get the program here: https://stefansundin.github.io/elevatedstartup/

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

For the record: I had this error trying to fill a subdocument in a wrong way:

{
[CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"]
message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"',
name: 'CastError',
type: 'ObjectId',
path: '_id'
value:
  [ { timestamp: '2014-07-03T00:23:45-04:00',
  date_start: '2014-07-03T00:23:45-04:00',
  date_end: '2014-07-03T00:23:45-04:00',
  operation: 'Deactivation' } ],
}

look ^ value is an array containing an object: wrong!

Explanation: I was sending data from php to a node.js API in this way:

$history = json_encode(
array(
  array(
  'timestamp'  => date('c', time()),
  'date_start' => date('c', time()),
  'date_end'   => date('c', time()),
  'operation'  => 'Deactivation'
)));

As you can see $history is an array containing an array. That's why mongoose try to fill _id (or any other field) with an array instead than a Scheme.ObjectId (or any other data type). The following works:

$history = json_encode(
array(
  'timestamp'  => date('c', time()),
  'date_start' => date('c', time()),
  'date_end'   => date('c', time()),
  'operation'  => 'Deactivation'
));

ModuleNotFoundError: No module named 'sklearn'

The other name of sklearn in anaconda is scikit-learn. simply open your anaconda navigator, go to the environments, select your environment, for example tensorflow or whatever you want to work with, search for scikit_learn in the list of uninstalled packages, apply it and then you can import sklearn in your jupyter.

What is a pre-revprop-change hook in SVN, and how do I create it?

For PC users: The .bat extension did not work for me when used on Windows Server maching. I used VisualSvn as Django Reinhardt suggested, and it created a hook with a .cmd extension.

How to catch a click event on a button?

All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.

An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.

package com.pointerunits.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
   private Button login;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      login = (Button)findViewById(R.id.loginbutton);
      login.setOnClickListener((OnClickListener) this);
      Log.i(DISPLAY_SERVICE, "Activity is created");

   }    

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {

      getMenuInflater().inflate(R.menu.main, menu);
      return true;
    }

   @Override
   public void onClick(View v) {
     Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
   }
}

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

How to import existing *.sql files in PostgreSQL 8.4?

Be careful with "/" and "\". Even on Windows the command should be in the form:

\i c:/1.sql

How to match hyphens with Regular Expression?

use "\p{Pd}" without quotes to match any type of hyphen. The '-' character is just one type of hyphen which also happens to be a special character in Regex.

How to render a DateTime in a specific format in ASP.NET MVC 3?

works for me

<%=Model.MyDateTime.ToString("dd-MMM-yyyy")%>

working with negative numbers in python

Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if numb is negative. If it is then multiply numa by -1 and do numb = abs(numb). Then do the loop.

How to get streaming url from online streaming radio station

The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.

Radio Browser is a searchable site with streaming urls for radio stations around the world:

http://www.radio-browser.info/

Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.

Bulk Record Update with SQL

Your way is correct, and here is another way you can do it:

update      Table1
set         Description = t2.Description
from        Table1 t1
inner join  Table2 t2
on          t1.DescriptionID = t2.ID

The nested select is the long way of just doing a join.

SELECT INTO USING UNION QUERY

INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2

How do I create a right click context menu in Java Swing?

You are probably manually calling setVisible(true) on the menu. That can cause some nasty buggy behavior in the menu.

The show(Component, int x, int x) method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true) just shows the menu without adding any additional behavior.

To make a right click popup menu simply create a JPopupMenu.

class PopUpDemo extends JPopupMenu {
    JMenuItem anItem;
    public PopUpDemo() {
        anItem = new JMenuItem("Click Me!");
        add(anItem);
    }
}

Then, all you need to do is add a custom MouseListener to the components you would like the menu to popup for.

class PopClickListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    private void doPop(MouseEvent e) {
        PopUpDemo menu = new PopUpDemo();
        menu.show(e.getComponent(), e.getX(), e.getY());
    }
}

// Then on your component(s)
component.addMouseListener(new PopClickListener());

Of course, the tutorials have a slightly more in-depth explanation.

Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen() and e.getYOnScreen() methods for the x and y coordinates.

Margin-Top not working for span element?

span is an inline element that doesn't support vertical margins. Put the margin on the outer div instead.

How to convert dd/mm/yyyy string into JavaScript Date object?

I found the default JS date formatting didn't work.

So I used toLocaleString with options

const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);

to get: DD/MM/YYYY format

See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp

Get current user id in ASP.NET Identity 2.0

I had the same issue. I am currently using Asp.net Core 2.2. I solved this problem with the following piece of code.

using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);

I hope this will be useful to someone.

LINQ Inner-Join vs Left-Join

If you actually have a database, this is the most-simple way:

var lsPetOwners = ( from person in context.People
                    from pets in context.Pets
                        .Where(mypet => mypet.Owner == person.ID) 
                        .DefaultIfEmpty()
                     select new { OwnerName = person.Name, Pet = pets.Name }
                   ).ToList();

Why doesn't list have safe "get" method like dictionary?

This guy worked for me:

list_get = lambda l, x: l[x:x+1] and l[x] or 0

lambdas are great for one liner helper functions like this

How to use paths in tsconfig.json?

It looks like there has been an update to React that doesn't allow you to set the "paths" in the tsconfig.json anylonger.

Nicely React just outputs a warning:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

then updates your tsconfig.json and removes the entire "paths" section for you. There is a way to get around this run

npm run eject

This will eject all of the create-react-scripts settings by adding config and scripts directories and build/config files into your project. This also allows a lot more control over how everything is built, named etc. by updating the {project}/config/* files.

Then update your tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./src",
        {…}
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

.setAttribute("disabled", false); changes editable attribute to false

Try doing this instead:

function enable(id)
{
    var eleman = document.getElementById(id);
    eleman.removeAttribute("disabled");        
}

To enable an element you have to remove the disabled attribute. Setting it to false still means it is disabled.

http://jsfiddle.net/SRK2c/

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

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

MySQL JOIN the most recent row only?

It's a good idea that logging actual data into "customer_data" table. With this data you can select all data from "customer_data" table as you wish.

What's the "average" requests per second for a production web application?

You can search "slashdot effect analysis" for graphs of what you would see if some aspect of the site suddenly became popular in the news, e.g. this graph on wiki.

Web-applications that survive tend to be the ones which can generate static pages instead of putting every request through a processing language.

There was an excellent video (I think it might have been on ted.com? I think it might have been by flickr web team? Does someone know the link?) with ideas on how to scale websites beyond the single server, e.g. how to allocate connections amongst the mix of read-only and read-write servers to get best effect for various types of users.

What are the pros and cons of parquet format compared to other formats?

Tom's answer is quite detailed and exhaustive but you may also be interested in this simple study about Parquet vs Avro done at Allstate Insurance, summarized here:

"Overall, Parquet showed either similar or better results on every test [than Avro]. The query-performance differences on the larger datasets in Parquet’s favor are partly due to the compression results; when querying the wide dataset, Spark had to read 3.5x less data for Parquet than Avro. Avro did not perform well when processing the entire dataset, as suspected."

What does request.getParameter return?

String onevalue;   
if(request.getParameterMap().containsKey("one")!=false) 
{
onevalue=request.getParameter("one").toString();
}

Detect home button press in android

Jack's answer is perfectly working for click event while longClick is considering is as menu button click.

By the way, if anyone is wondering how to do via kotlin,

class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
    private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    private var mReceiver: InnerReceiver = InnerReceiver()

    fun startWatch() {
        context.registerReceiver(mReceiver, mFilter)
    }

    fun stopWatch() {
        context.unregisterReceiver(mReceiver)
    }

    inner class InnerReceiver: BroadcastReceiver() {
        private val systemDialogReasonKey = "reason"
        private val systemDialogReasonHomeKey = "homekey"
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(systemDialogReasonKey)
                if (reason != null && reason == systemDialogReasonHomeKey) {
                    listener.onHomeButtonClick()
                }
            }
        }
    } 
}

"Insert if not exists" statement in SQLite

For a unique column, use this:

INSERT OR REPLACE INTO table () values();

For more information, see: sqlite.org/lang_insert

How to connect to a remote MySQL database with Java?

Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.

Counting the Number of keywords in a dictionary in python

Some modifications were made on posted answer UnderWaterKremlin to make it python3 proof. A surprising result below as answer.

System specs:

  • python =3.7.4,
  • conda = 4.8.0
  • 3.6Ghz, 8 core, 16gb.
import timeit

d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000

print (len(d.keys()))
# 1000

print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000))        # 1

print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2

Result:

1) = 37.0100378

2) = 37.002148899999995

So it seems that len(d.keys()) is currently faster than just using len().

Is it possible to sort a ES6 map object?

One way is to get the entries array, sort it, and then create a new Map with the sorted array:

let ar = [...myMap.entries()];
sortedArray = ar.sort();
sortedMap = new Map(sortedArray);

But if you don't want to create a new object, but to work on the same one, you can do something like this:

// Get an array of the keys and sort them
let keys = [...myMap.keys()];
sortedKeys = keys.sort();

sortedKeys.forEach((key)=>{
  // Delete the element and set it again at the end
  const value = this.get(key);
  this.delete(key);
  this.set(key,value);
})

WHERE vs HAVING

WHERE filters before data is grouped, and HAVING filters after data is grouped. This is an important distinction; rows that are eliminated by a WHERE clause will not be included in the group. This could change the calculated values which, in turn(=as a result) could affect which groups are filtered based on the use of those values in the HAVING clause.

And continues,

HAVING is so similar to WHERE that most DBMSs treat them as the same thing if no GROUP BY is specified. Nevertheless, you should make that distinction yourself. Use HAVING only in conjunction with GROUP BY clauses. Use WHERE for standard row-level filtering.

Excerpt From: Forta, Ben. “Sams Teach Yourself SQL in 10 Minutes (5th Edition) (Sams Teach Yourself...).”.

How can I make directory writable?

  • chmod +w <directory> or chmod a+w <directory> - Write permission for user, group and others

  • chmod u+w <directory> - Write permission for user

  • chmod g+w <directory> - Write permission for group

  • chmod o+w <directory> - Write permission for others

ipython notebook clear cell output in code

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Theoretically, the application in DOS Prompt has its own clipboard and shortcuts. To import text from Windows clipboard is "extra". However you can use Alt-Space to open system menu of Prompt window, then press E, P to select Edit, Paste menu. However, MS could provide shortcut using Win-key. There is no chance to be used in DOS application.

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin http://github.com/group/project.git   # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

What is best tool to compare two SQL Server databases (schema and data)?

I've used Red Gate's tools and they are superb. However, if you can't spend any money you could try Open DBDiff to compare schemas.

How do I add a newline to command output in PowerShell?

The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.

Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append

Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.

How to make an Asynchronous Method return a value?

Probably the simplest way to do it is to create a delegate and then BeginInvoke, followed by a wait at some time in the future, and an EndInvoke.

public bool Foo(){
    Thread.Sleep(100000); // Do work
    return true;
}

public SomeMethod()
{
    var fooCaller = new Func<bool>(Foo);
    // Call the method asynchronously
    var asyncResult = fooCaller.BeginInvoke(null, null);

    // Potentially do other work while the asynchronous method is executing.

    // Finally, wait for result
    asyncResult.AsyncWaitHandle.WaitOne();
    bool fooResult = fooCaller.EndInvoke(asyncResult);

    Console.WriteLine("Foo returned {0}", fooResult);
}

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

To add WebAPI in my MVC 5 project.

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  3. Right click controllers folder > add new item > web > Add Web API controller

  4. Web.config will be modified accordingly by VS

  5. Add Application_Start method if not there already

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  6. Add the following class (I added in global.asax.cs file)

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  7. Modify web api method accordingly

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }
    
            // GET api/<controller>/5   : url to use => api/vs/5
            public string Get(int id)
            {
                return (id + 1).ToString();
            }
        }
    }
    
  8. Rebuild and test

  9. Build a simple html page

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>    
        <script src="../<path_to_jquery>/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
            var uri = '/api/vs';
            $(document).ready(function () {
                $.getJSON(uri)
                .done(function (data) {
                    alert('got: ' + data);
                });
    
                $.ajax({
                    url: '/api/vs/5',
                    async: true,
                    success: function (data) {
                        alert('seccess1');
                        var res = parseInt(data);
                        alert('got res=' + res);
                    }
                });
            });
        </script>
    </head>
    <body>
    ....
    </body>
    </html>
    

How to set Internet options for Android emulator?

for the records since this is an old post and since nobody mentioned it, check if you forgot (as I did) to set the android.permission.INTERNET flag in AndroidManifest.xml as, i.e.:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.webviewdemo">
<uses-permission android:name="android.permission.INTERNET"/>
    <application android:icon="@drawable/icon">
        <activity android:name=".WebViewDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

It is because you use a relative path.

The easy way to fix this is by using the __DIR__ magic constant, like:

require_once(__DIR__."/initcontrols/config.php");

From the PHP doc:

The directory of the file. If used inside an include, the directory of the included file is returned

Should I use int or Int32

I use int in the event that Microsoft changes the default implementation for an integer to some new fangled version (let's call it Int32b).

Microsoft can then change the int alias to Int32b, and I don't have to change any of my code to take advantage of their new (and hopefully improved) integer implementation.

The same goes for any of the type keywords.

How to access full source of old commit in BitBucket?

Step 1

Step 1


Step 2

Step 2


Step 3

Step 3


Step 4

Step 4


Final Step

Final Step