Programs & Examples On #Wspbuilder

WSPBuilder is a SharePoint Solution Package (WSP) creation tool for WSS 3.0 & MOSS 2007.

How many parameters are too many?

For me , when the list crosses one line on my IDE, then it's one parameter too many. I want to see all the parameters in one line without breaking eye contact. But that's just my personal preference.

How to delete all files older than 3 days when "Argument list too long"?

To delete all files and directories within the current directory:

find . -mtime +3 | xargs rm -Rf

Or alternatively, more in line with the OP's original command:

find . -mtime +3 -exec rm -Rf -- {} \;

Python Loop: List Index Out of Range

  1. In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
    Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.

We can fix this issue by iterating over a range of indexes instead:

for i in range(len(a))

and access the a's items like that: a[i]. This won't give any errors.

  1. In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.

To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.

  1. There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:

b = [a[i] + a[i+1] for i in range(len(a) - 1)]

This does the job in only one line.

Move_uploaded_file() function is not working

Easiest Way to Uplaod a file

$FileName = $file_name;
$path = 'Users/Desktop/uploads/images'; 
$location = $path . $data['name']; 
move_uploaded_file($data['temp_name'],$location);

jquery datatables default sort

You can use the fnSort function, see the details here:

http://datatables.net/api#fnSort

How do I reverse a C++ vector?

You can also use std::list instead of std::vector. list has a built-in function list::reverse for reversing elements.

From Arraylist to Array

This is the best way (IMHO).

List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);

This code works also:

String[] myArray = myArrayList.toArray(new String[0]);

But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.

In bootstrap how to add borders to rows without adding up?

On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:

First give all of the rows children a border on the right and bottom

.borders div{
    border-right:1px solid #999;
    border-bottom:1px solid #999;
}

Next give the first child of each or a left border

.borders div:first-child{
    border-left:
    1px solid #999;
}

Last make sure to clear the borders for their child elements

.borders div > div{
    border:0;
}

HTML:

<div class="row borders">
    <div class="col-xs-5 col-md-2">Email</div>
    <div class="col-xs-7 col-md-4">[email protected]</div>
    <div class="col-xs-5 col-md-2">Phone</div>
    <div class="col-xs-7 col-md-4">555-123-4567</div>
</div>

Calling an executable program using awk

I use the power of awk to delete some of my stopped docker containers. Observe carefully how i construct the cmd string first before passing it to system.

docker ps -a | awk '$3 ~ "/bin/clish" { cmd="docker rm "$1;system(cmd)}'

Here, I use the 3rd column having the pattern "/bin/clish" and then I extract the container ID in the first column to construct my cmd string and passed that to system.

How should I throw a divide by zero exception in Java without actually dividing by zero?

There are two ways you could do this. Either create your own custom exception class to represent a divide by zero error or throw the same type of exception the java runtime would throw in this situation.

Define custom exception

public class DivideByZeroException() extends ArithmeticException {
}

Then in your code you would check for a divide by zero and throw this exception:

if (divisor == 0) throw new DivideByZeroException();

Throw ArithmeticException

Add to your code the check for a divide by zero and throw an arithmetic exception:

if (divisor == 0) throw new java.lang.ArithmeticException("/ by zero");

Additionally, you could consider throwing an illegal argument exception since a divisor of zero is an incorrect argument to pass to your setKp() method:

if (divisor == 0) throw new java.lang.IllegalArgumentException("divisor == 0");

Setting a backgroundImage With React Inline Styles

try this it worked in my case

backgroundImage: `url("${Background}")`

ActiveXObject creation error " Automation server can't create object"

This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.

Calling async method synchronously

To prevent deadlocks I always try to use Task.Run() when I have to call an async method synchronously that @Heinzi mentions.

However the method has to be modified if the async method uses parameters. For example Task.Run(GenerateCodeAsync("test")).Result gives the error:

Argument 1: cannot convert from 'System.Threading.Tasks.Task<string>' to 'System.Action'

This could be called like this instead:

string code = Task.Run(() => GenerateCodeAsync("test")).Result;

Regular expression for floating point numbers

what you need is:

[\-\+]?[0-9]*(\.[0-9]+)?

I escaped the "+" and "-" sign and also grouped the decimal with its following digits since something like "1." is not a valid number.

The changes will allow you to match integers and floats. for example:

0
+1
-2.0
2.23442

How is the default max Java heap size determined?

This is changed in Java 6 update 18.

Assuming that we have more than 1 GB of physical memory (quite common these days), it's always 1/4th of your physical memory for the server vm.

Datatables on-the-fly resizing

I got this to work as follows:

First ensure that in your dataTable definition your aoColumns array includes sWidth data expressed as a % not fixed pixels or ems. Then ensure you have set the bAutoWidth property to false Then add this little but of JS:

update_table_size = function(a_datatable) {
  if (a_datatable == null) return;
  var dtb;
  if (typeof a_datatable === 'string') dtb = $(a_datatable)
  else dtb = a_datatable;
  if (dtb == null) return;

  dtb.css('width', dtb.parent().width());
  dtb.fnAdjustColumSizing();
}

$(window).resize(function() {
  setTimeout(function(){update_table_size(some_table_selector_or_table_ref)}, 250);
});

Works a treat and my table cells handle the white-space: wrap; CSS (which wasn't working without setting the sWidth, and was what led me to this question.)

How to access /storage/emulated/0/

Try This

private String getFilename() {
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File(filepath + "/AudioRecorder" );
    if (!file.exists()) {
        file.mkdirs();
    }
    return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".mp4");
}

PHP Fatal error: Cannot redeclare class

I have encountered that same problem: newer php version doesn't deal the same with multiple incluse of the same file (as a library), so now I have to change all my include by some include_once.

Or this tricks could help, if you d'ont have too much class in your library...

if( class_exists('TestClass') != true )
{
   //your definition of TestClass
}

Selecting last element in JavaScript array

Underscore and Lodash have the _.last(Array) method, that returns the last element in an Array. They both work about the same

_.last([5, 4, 3, 2, 1]);
=> 1

Ramda also has a _.last function

R.last(['fi', 'fo', 'fum']); //=> 'fum'

How could I create a function with a completion handler in Swift?

Swift 5.0 + , Simple and Short

example:

Style 1

    func methodName(completionBlock: () -> Void)  {

          print("block_Completion")
          completionBlock()
    }

Style 2

    func methodName(completionBlock: () -> ())  {

        print("block_Completion")
        completionBlock()
    }

Use:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        methodName {

            print("Doing something after Block_Completion!!")
        }
    }

Output

block_Completion

Doing something after Block_Completion!!

How can I get dictionary key as variable directly in Python (not by searching from value)?

if you just need to get a key-value from a simple dictionary like e.g:

os_type = {'ubuntu': '20.04'}

use popitem() method:

os, version = os_type.popitem()
print(os) # 'ubuntu'
print(version) # '20.04'

Cannot import XSSF in Apache POI

I Got the Solution Guys

You need to keep some points in your mind .

  1. There are two different dependency one is (poi) & other dependency is (poi- ooxml) but make sure you must use poi-ooxml dependency in your code.

  2. Just Add the following dependency in pom.xml & Save it.

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.9</version>
  </dependency>

3 .After you have saved the pom.xml then you need to try a small thing ,Use (.) operator will try to import/fetch it & finally will not see any sort of error because now it has imported that thing in your package.

Sample Code to Understand Better !!

package ReadFile;// package   
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  // automatically added to your code after importing
public class Test          
{  
public static void Hello() // Method  
{  
XSSFWorkbook workbook = new XSSFWorkbook();   
}  
}

I tried my best to give you the solution , If you face any issue comment here i will try
to solve it .

Keep Learning Guys !!

Yes or No confirm box using jQuery

Try This... It's very simple just use confirm dialog box for alert with YES|NO.

if(confirm("Do you want to upgrade?")){ Your code }

Cannot catch toolbar home button click event

I changed the DrawerLayout a bit to get the events and be able to consume and event, such as if you want to use the actionToggle as back if you are in detail view:

public class ListenableDrawerLayout extends DrawerLayout {

    private OnToggleButtonClickedListener mOnToggleButtonClickedListener;
    private boolean mManualCall;

    public ListenableDrawerLayout(Context context) {
        super(context);
    }

    public ListenableDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListenableDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Sets the listener for the toggle button
     *
     * @param mOnToggleButtonClickedListener
     */
    public void setOnToggleButtonClickedListener(OnToggleButtonClickedListener mOnToggleButtonClickedListener) {
        this.mOnToggleButtonClickedListener = mOnToggleButtonClickedListener;
    }

    /**
     * Opens the navigation drawer manually from code<br>
     * <b>NOTE: </b>Use this function instead of the normal openDrawer method
     *
     * @param drawerView
     */
    public void openDrawerManual(View drawerView) {
        mManualCall = true;
        openDrawer(drawerView);
    }

    /**
     * Closes the navigation drawer manually from code<br>
     * <b>NOTE: </b>Use this function instead of the normal closeDrawer method
     *
     * @param drawerView
     */
    public void closeDrawerManual(View drawerView) {
        mManualCall = true;
        closeDrawer(drawerView);
    }


    @Override
    public void openDrawer(View drawerView) {

        // Check for listener and for not manual open
        if (!mManualCall && mOnToggleButtonClickedListener != null) {

            // Notify the listener and behave on its reaction
            if (mOnToggleButtonClickedListener.toggleOpenDrawer()) {
                return;
            }

        }
        // Manual call done
        mManualCall = false;

        // Let the drawer layout to its stuff
        super.openDrawer(drawerView);
    }

    @Override
    public void closeDrawer(View drawerView) {

        // Check for listener and for not manual close
        if (!mManualCall && mOnToggleButtonClickedListener != null) {

            // Notify the listener and behave on its reaction
            if (mOnToggleButtonClickedListener.toggleCloseDrawer()) {
                return;
            }

        }
        // Manual call done
        mManualCall = false;

        // Let the drawer layout to its stuff
        super.closeDrawer(drawerView);
    }

    /**
     * Interface for toggle button callbacks
     */
    public static interface OnToggleButtonClickedListener {

        /**
         * The ActionBarDrawerToggle has been pressed in order to open the drawer
         *
         * @return true if we want to consume the event, false if we want the normal behaviour
         */
        public boolean toggleOpenDrawer();

        /**
         * The ActionBarDrawerToggle has been pressed in order to close the drawer
         *
         * @return true if we want to consume the event, false if we want the normal behaviour
         */
        public boolean toggleCloseDrawer();
    }

}

jQuery 1.9 .live() is not a function

I tend not to use the .on() syntax, if not necessary. For example you can migrate easier like this:

old:

$('.myButton').live('click', function);

new:

$('.myButton').click(function)

Here is a list of valid event handlers: https://api.jquery.com/category/forms/

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

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

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

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

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

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

How does the "view" method work in PyTorch?

I figured it out that x.view(-1, 16 * 5 * 5) is equivalent to x.flatten(1), where the parameter 1 indicates the flatten process starts from the 1st dimension(not flattening the 'sample' dimension) As you can see, the latter usage is semantically more clear and easier to use, so I prefer flatten().

MySql sum elements of a column

Try this:

select sum(a), sum(b), sum(c)
from your_table

Set cookies for cross origin requests

In order for the client to be able to read cookies from cross-origin requests, you need to have:

  1. All responses from the server need to have the following in their header:

    Access-Control-Allow-Credentials: true

  2. The client needs to send all requests with withCredentials: true option

In my implementation with Angular 7 and Spring Boot, I achieved that with the following:


Server-side:

@CrossOrigin(origins = "http://my-cross-origin-url.com", allowCredentials = "true")
@Controller
@RequestMapping(path = "/something")
public class SomethingController {
  ...
}

The origins = "http://my-cross-origin-url.com" part will add Access-Control-Allow-Origin: http://my-cross-origin-url.com to every server's response header

The allowCredentials = "true" part will add Access-Control-Allow-Credentials: true to every server's response header, which is what we need in order for the client to read the cookies


Client-side:

import { HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

    constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // send request with credential options in order to be able to read cross-origin cookies
        req = req.clone({ withCredentials: true });

        // return XSRF-TOKEN in each request's header (anti-CSRF security)
        const headerName = 'X-XSRF-TOKEN';
        let token = this.tokenExtractor.getToken() as string;
        if (token !== null && !req.headers.has(headerName)) {
            req = req.clone({ headers: req.headers.set(headerName, token) });
        }
        return next.handle(req);
    }
}

With this class you actually inject additional stuff to all your request.

The first part req = req.clone({ withCredentials: true });, is what you need in order to send each request with withCredentials: true option. This practically means that an OPTION request will be send first, so that you get your cookies and the authorization token among them, before sending the actual POST/PUT/DELETE requests, which need this token attached to them (in the header), in order for the server to verify and execute the request.

The second part is the one that specifically handles an anti-CSRF token for all requests. Reads it from the cookie when needed and writes it in the header of every request.

The desired result is something like this:

response request

Postgresql - change the size of a varchar column to lower length

I was facing the same problem trying to truncate a VARCHAR from 32 to 8 and getting the ERROR: value too long for type character varying(8). I want to stay as close to SQL as possible because I'm using a self-made JPA-like structure that we might have to switch to different DBMS according to customer's choices (PostgreSQL being the default one). Hence, I don't want to use the trick of altering System tables.

I ended using the USING statement in the ALTER TABLE:

ALTER TABLE "MY_TABLE" ALTER COLUMN "MyColumn" TYPE varchar(8)
USING substr("MyColumn", 1, 8)

As @raylu noted, ALTER acquires an exclusive lock on the table so all other operations will be delayed until it completes.

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

This will update the local database of remote branches.

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.

Basics

The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.

The common interfaces

The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:

  • CrudRepository - CRUD methods
  • PagingAndSortingRepository - methods for pagination and sorting (extends CrudRepository)

Store-specific interfaces

The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…) of JpaRepository which is different from delete(…) as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).

We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository.

Custom repository base interfaces

The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:

  1. Depending on a Spring Data repository interface couples your repository interface to the library. I don't think this is a particular issue as you'll probably use abstractions like Page or Pageable in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.
  2. By extending e.g. CrudRepository, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository that doesn't include the save(…) and delete(…) methods of CrudRepository.

The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:

interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }

interface ReadOnlyRepository<T> extends Repository<T, Long> {

  // Al finder methods go here
}

The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long for consistency. The second interface usually has all the find…(…) methods copied from CrudRepository and PagingAndSortingRepository but does not expose the manipulating ones. Read more on that approach in the reference documentation.

Summary - tl;dr

The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.

htaccess redirect if URL contains a certain string

If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.

To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :

RewriteEngine on

RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]

Include jQuery in the JavaScript Console

Post 2020 method, using dynamic import, self executing IIFE, asynchronous function!

_x000D_
_x000D_
(async () => {
    await import('https://code.jquery.com/jquery-2.2.4.min.js')
    // Library ready
    console.log(jQuery)
})()
_x000D_
_x000D_
_x000D_

enter image description here

Another example

https://caniuse.com/es6-module-dynamic-import

How do you import a large MS SQL .sql file?

  1. Take command prompt with administrator privilege

  2. Change directory to where the .sql file stored

  3. Execute the following command

    sqlcmd -S 'your server name' -U 'user name of server' -P 'password of server' -d 'db name'-i script.sql

How to create a GUID / UUID

Well, this has a bunch of answers already, but unfortunately there's not a "true" random in the bunch. The version below is an adaptation of broofa's answer, but updated to include a "true" random function that uses crypto libraries where available, and the Alea() function as a fallback.

  Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }
  Math.trueRandom = (function() {
  var crypt = window.crypto || window.msCrypto;

  if (crypt && crypt.getRandomValues) {
      // if we have a crypto library, use it
      var random = function(min, max) {
          var rval = 0;
          var range = max - min;
          if (range < 2) {
              return min;
          }

          var bits_needed = Math.ceil(Math.log2(range));
          if (bits_needed > 53) {
            throw new Exception("We cannot generate numbers larger than 53 bits.");
          }
          var bytes_needed = Math.ceil(bits_needed / 8);
          var mask = Math.pow(2, bits_needed) - 1;
          // 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111

          // Create byte array and fill with N random numbers
          var byteArray = new Uint8Array(bytes_needed);
          crypt.getRandomValues(byteArray);

          var p = (bytes_needed - 1) * 8;
          for(var i = 0; i < bytes_needed; i++ ) {
              rval += byteArray[i] * Math.pow(2, p);
              p -= 8;
          }

          // Use & to apply the mask and reduce the number of recursive lookups
          rval = rval & mask;

          if (rval >= range) {
              // Integer out of acceptable range
              return random(min, max);
          }
          // Return an integer that falls within the range
          return min + rval;
      }
      return function() {
          var r = random(0, 1000000000) / 1000000000;
          return r;
      };
  } else {
      // From https://web.archive.org/web/20120502223108/http://baagoe.com/en/RandomMusings/javascript/
      // Johannes Baagøe <[email protected]>, 2010
      function Mash() {
          var n = 0xefc8249d;

          var mash = function(data) {
              data = data.toString();
              for (var i = 0; i < data.length; i++) {
                  n += data.charCodeAt(i);
                  var h = 0.02519603282416938 * n;
                  n = h >>> 0;
                  h -= n;
                  h *= n;
                  n = h >>> 0;
                  h -= n;
                  n += h * 0x100000000; // 2^32
              }
              return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
          };

          mash.version = 'Mash 0.9';
          return mash;
      }

      // From http://baagoe.com/en/RandomMusings/javascript/
      function Alea() {
          return (function(args) {
              // Johannes Baagøe <[email protected]>, 2010
              var s0 = 0;
              var s1 = 0;
              var s2 = 0;
              var c = 1;

              if (args.length == 0) {
                  args = [+new Date()];
              }
              var mash = Mash();
              s0 = mash(' ');
              s1 = mash(' ');
              s2 = mash(' ');

              for (var i = 0; i < args.length; i++) {
                  s0 -= mash(args[i]);
                  if (s0 < 0) {
                      s0 += 1;
                  }
                  s1 -= mash(args[i]);
                  if (s1 < 0) {
                      s1 += 1;
                  }
                  s2 -= mash(args[i]);
                  if (s2 < 0) {
                      s2 += 1;
                  }
              }
              mash = null;

              var random = function() {
                  var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
                  s0 = s1;
                  s1 = s2;
                  return s2 = t - (c = t | 0);
              };
              random.uint32 = function() {
                  return random() * 0x100000000; // 2^32
              };
              random.fract53 = function() {
                  return random() +
                      (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
              };
              random.version = 'Alea 0.9';
              random.args = args;
              return random;

          }(Array.prototype.slice.call(arguments)));
      };
      return Alea();
  }
}());

Math.guid = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)    {
      var r = Math.trueRandom() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
  });
};

ArrayList vs List<> in C#

As mentioned in .NET Framework documentation

We don't recommend that you use the ArrayList class for new development. Instead, we recommend that you use the generic List<T> class. The ArrayList class is designed to hold heterogeneous collections of objects. However, it does not always offer the best performance. Instead, we recommend the following:

  • For a heterogeneous collection of objects, use the List<Object> (in C#) or List(Of Object) (in Visual Basic) type.
  • For a homogeneous collection of objects, use the List<T> class.

See also Non-generic collections shouldn't be used

table shows how the non-generic collection types can be replaced by their generic counterparts

Import cycle not allowed

This is a circular dependency issue. Golang programs must be acyclic. In Golang cyclic imports are not allowed (That is its import graph must not contain any loops)

Lets say your project go-circular-dependency have 2 packages "package one" & it has "one.go" & "package two" & it has "two.go" So your project structure is as follows

+--go-circular-dependency    
      +--one    
         +-one.go
      +--two        
         +-two.go

This issue occurs when you try to do something like following.

Step 1 - In one.go you import package two (Following is one.go)

package one

import (
    "go-circular-dependency/two"
)

//AddOne is
func AddOne() int {
    a := two.Multiplier()
    return a + 1
}

Step 2 - In two.go you import package one (Following is two.go)

package two

import (
    "fmt"
    "go-circular-dependency/one"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    //import AddOne from "package one"
    x := one.AddOne()
    fmt.Println(x)
}

In Step 2, you will receive an error "can't load package: import cycle not allowed" (This is called "Circular Dependency" error)

Technically speaking this is bad design decision and you should avoid this as much as possible, but you can "Break Circular Dependencies via implicit interfaces" (I personally don't recommend, and highly discourage this practise, because by design Go programs must be acyclic)

Try to keep your import dependency shallow. When the dependency graph becomes deeper (i.e package x imports y, y imports z, z imports x) then circular dependencies become more likely.

Sometimes code repetition is not bad idea, which is exactly opposite of DRY (don't repeat yourself)

So in Step 2 that is in two.go you should not import package one. Instead in two.go you should actually replicate the functionality of AddOne() written in one.go as follows.

package two

import (
    "fmt"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    // x := one.AddOne()
    x := Multiplier() + 1
    fmt.Println(x)
}

Numpy: Divide each row by a vector element

Pythonic way to do this is ...

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

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

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

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

I use SingleOrDefault in situations where my logic dictates that the will be either zero or one results. If there are more, it's an error situation, which is helpful.

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

public static Date convertTimestampToDate(Timestamp timestamp)  {
        Instant ins=timestamp.toLocalDateTime().atZone(ZoneId.systemDefault()).toInstant();
        return  Date.from(ins);
}

MVC3 DropDownListFor - a simple example?

You should do like this:

@Html.DropDownListFor(m => m.ContribType, 
                new SelectList(Model.ContribTypeOptions, 
                               "ContribId", "Value"))

Where:

m => m.ContribType

is a property where the result value will be.

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

extern std::pair<std::string_view, Base*(*)()> const factories[2];

decltype(factories) factories{
  {"blah", []() -> Base*{return new Blah;}},
  {"foo", []() -> Base*{return new Foo;}}
};

SonarQube Exclude a directory

Try something like this:

sonar.exclusions=src/java/test/**

Best practice when adding whitespace in JSX

I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:

<p>
    Hello {
        <span>World</span>
    }!
</p>

or

<p>
    Hello {}
    <span>World</span>
    {} again!
</p>

Each of these produces clean html without additional &nbsp; or other extraneous markup. It creates fewer text nodes than using {' '}, and allows using of html entities where {' hello &amp; goodbye '} does not.

Parsing string as JSON with single quotes?

Using single quotes for keys are not allowed in JSON. You need to use double quotes.

For your use-case perhaps this would be the easiest solution:

str = '{"a":1}';

Source:

If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.

ImportError: DLL load failed: The specified module could not be found

Installing the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019 worked for me with a similar problem, and helped with another (slightly different) driver issue.

How do I print output in new line in PL/SQL?

Pass the string and replace space with line break, it gives you desired result.

select replace('shailendra kumar',' ',chr(10)) from dual;

correct way to use super (argument passing)

Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs or remove them from *args. Instead, you can define a Base class which unlike object, absorbs/ignores arguments:

class Base(object):
    def __init__(self, *args, **kwargs): pass

class A(Base):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(Base):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(arg, *args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(arg, *args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(arg, *args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10)

yields

MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']
E arg= 10
C arg= 10
A
D arg= 10
B

Note that for this to work, Base must be the penultimate class in the MRO.

How to split csv whose columns may contain ,

With Cinchoo ETL - an open source library, it can automatically handles columns values containing separators.

string csv = @"2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,""Corvallis, OR"",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

using (var p = ChoCSVReader.LoadText(csv)
    )
{
    Console.WriteLine(p.Dump());
}

Output:

Key: Column1 [Type: String]
Value: 2
Key: Column2 [Type: String]
Value: 1016
Key: Column3 [Type: String]
Value: 7/31/2008 14:22
Key: Column4 [Type: String]
Value: Geoff Dalgas
Key: Column5 [Type: String]
Value: 6/5/2011 22:21
Key: Column6 [Type: String]
Value: http://stackoverflow.com
Key: Column7 [Type: String]
Value: Corvallis, OR
Key: Column8 [Type: String]
Value: 7679
Key: Column9 [Type: String]
Value: 351
Key: Column10 [Type: String]
Value: 81
Key: Column11 [Type: String]
Value: b437f461b3fd27387c5d8ab47a293d35
Key: Column12 [Type: String]
Value: 34

For more information, please visit codeproject article.

Hope it helps.

How to vertically align elements in a div?

My trick is to put inside the div a table with 1 row and 1 column, set 100% of width and height, and the property vertical-align:middle.

<div>

    <table style="width:100%; height:100%;">
        <tr>
            <td style="vertical-align:middle;">
                BUTTON TEXT
            </td>
        </tr>
    </table>

</div>

Fiddle: http://jsfiddle.net/joan16v/sbqjnn9q/

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

Changing the highlight color when selecting text in an HTML text input

Try this code to use:

/* For Mozile Firefox Browser */

::-moz-selection { background-color: #4CAF50; }

/* For Other Browser*/
::selection { background-color: #4CAF50; }

Make Bootstrap 3 Tabs Responsive

I prefer a css only scheme based on horizontal scroll, like tabs on android. This's my solution, just wrap with a class nav-tabs-responsive:

<div class="nav-tabs-responsive">
  <ul class="nav nav-tabs" role="tablist">
    <li>...</li>
  </ul>
</div>

And two css lines:

.nav-tabs { min-width: 600px; }
.nav-tabs-responsive { overflow: auto; }

600px is the point over you will be responsive (you can set it using bootstrap variables)

test if event handler is bound to an element in jQuery

This solution is no more supported since jQuery 1.8 as we can read on the blog here:

$(element).data(“events”): This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.

So, you should unbind/rebind it or simply, use a boolean to determine if your event as been attached or not (which is in my opinion the best solution).

How do I start my app on startup?

Another approach is to use android.intent.action.USER_PRESENT instead of android.intent.action.BOOT_COMPLETED to avoid slow downs during the boot process. But this is only true if the user has enabled the lock Screen - otherwise this intent is never broadcasted.

Reference blog - The Problem With Android’s ACTION_USER_PRESENT Intent

PHP: If internet explorer 6, 7, 8 , or 9

Checking for MSIE only is not enough to detect IE. You need also "Trident" which is only used in IE11. So here is my solution which worked an versions 8 to 11.

$agent=strtoupper($_SERVER['HTTP_USER_AGENT']);
$isIE=(strpos($agent,'MSIE')!==false || strpos($agent,'TRIDENT')!==false);

How do I pass options to the Selenium Chrome driver using Python?

This is how I did it.

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-extensions')

chrome = webdriver.Chrome(chrome_options=chrome_options)

Get epoch for a specific date using Javascript

You can create a Date object, and call getTime on it:

new Date(2010, 6, 26).getTime() / 1000

Removing the fragment identifier from AngularJS urls (# symbol)

If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:

  1. Set up your base href in your _Layout page: <head> <base href="/"> </head>

  2. Then, add following in your angular app config : $locationProvider.html5Mode(true)

  3. Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refreash will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all

url:

routes.MapRoute(
    name: "App",
    url: "{*url}",
    defaults: new {
        controller = "Home", action = "Index"
    }
);

How do I know the script file name in a Bash script?

Re: Tanktalus's (accepted) answer above, a slightly cleaner way is to use:

me=$(readlink --canonicalize --no-newline $0)

If your script has been sourced from another bash script, you can use:

me=$(readlink --canonicalize --no-newline $BASH_SOURCE)

I agree that it would be confusing to dereference symlinks if your objective is to provide feedback to the user, but there are occasions when you do need to get the canonical name to a script or other file, and this is the best way, imo.

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

Split an integer into digits to compute an ISBN checksum

On Older versions of Python...

map(int,str(123))

On New Version 3k

list(map(int,str(123)))

Execute and get the output of a shell command in node.js

Thanks to Renato answer, I have created a really basic example:

const exec = require('child_process').exec

exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))

It will just print your global git username :)

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

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

There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.

One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.

For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, this);
  }
}

(Above code has not been tested.)

The following code could be used to add the JPanelWithBackground into a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

In this example, the ImageIO.read(File) method was used to read in the external JPEG file.

Storing Form Data as a Session Variable

You can solve this problem using this code:

if(!empty($_GET['variable from which you get'])) 
{
$_SESSION['something']= $_GET['variable from which you get'];
}

So you get the variable from a GET form, you will store in the $_SESSION['whatever'] variable just once when $_GET['variable from which you get']is set and if it is empty $_SESSION['something'] will store the old parameter

How to find nth occurrence of character in a string?

public static int nth(String source, String pattern, int n) {

   int i = 0, pos = 0, tpos = 0;

   while (i < n) {

      pos = source.indexOf(pattern);
      if (pos > -1) {
         source = source.substring(pos+1);
         tpos += pos+1;
         i++;
      } else {
         return -1;
      }
   }

   return tpos - 1;
}

javascript, for loop defines a dynamic variable name

You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do

for (var i = myArray.length - 1; i >= 0; i--) {    console.log(eval(myArray[i])); }; 

More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.

var result = {}; for (var i = myArray.length - 1; i >= 0; i--) {     result[myArray[i]] = eval(myArray[i]);   }; 

I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

In c++ what does a tilde "~" before a function name signify?

That would be the destructor(freeing up any dynamic memory)

Calling another different view from the controller using ASP.NET MVC 4

You have to specify the name of the custom view and its related model in Controller Action method.

public ActionResult About()
{            
   return View("NameOfViewYouWantToReturn",Model); 
}

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

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

Something like 'contains any' for Java set?

A good way to implement containsAny for sets is using the Guava Sets.intersection().

containsAny would return a boolean, so the call looks like:

Sets.intersection(set1, set2).isEmpty()

This returns true iff the sets are disjoint, otherwise false. The time complexity of this is likely slightly better than retainAll because you dont have to do any cloning to avoid modifying your original set.

PowerShell to remove text from a string

This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.

To keep the text which falls between the equal sign and the comma:

-replace "^.*?=(.*?),.*?$",'$1'

This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.

How to clear/delete the contents of a Tkinter Text widget?

I checked on my side by just adding '1.0' and it start working

tex.delete('1.0', END)

you can also try this

How to capture a JFrame's close button click event?

Try this:

setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

It will work.

How to tar certain file types in all subdirectories?

find ./someDir -name "*.php" -o -name "*.html" | tar -cf my_archive -T -

regular expression: match any word until first space

for the entire line

^(\w+)\s+(\w+)\s+(\d+(?:\/\d+){2})\s+(\w+)$

Can you find all classes in a package using reflection?

If you're in Spring-land you can use PathMatchingResourcePatternResolver;

  PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  Resource[] resources = resolver.getResources("classpath*:some/package/name/*.class");

    Arrays.asList(resources).forEach(r->{
        ...
    });

How to test which port MySQL is running on and whether it can be connected to?

If you are on a system where netstat is not available (e.g. RHEL 7 and more recent Debian releases) you can use ss, as below:

sudo ss -tlpn | grep mysql

And you'll get something like the following for output:

LISTEN     0      50        *:3306        *:*        users:(("mysqld",pid=5307,fd=14))

The fourth column is Local Address:Port. So in this case Mysql is listening on port 3306, the default.

Get the name of a pandas DataFrame

In many situations, a custom attribute attached to a pd.DataFrame object is not necessary. In addition, note that pandas-object attributes may not serialize. So pickling will lose this data.

Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label'].

df = pd.DataFrame()

dfs = {'some_label': df}

What is the Difference Between read() and recv() , and Between send() and write()?

Per the first hit on Google

read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.

How to create a Restful web service with input parameters?

Be careful. For this you need @GET (not @PUT).

Postgres: INSERT if does not exist already

Unfortunately, PostgreSQL supports neither MERGE nor ON DUPLICATE KEY UPDATE, so you'll have to do it in two statements:

UPDATE  invoices
SET     billed = 'TRUE'
WHERE   invoices = '12345'

INSERT
INTO    invoices (invoiceid, billed)
SELECT  '12345', 'TRUE'
WHERE   '12345' NOT IN
        (
        SELECT  invoiceid
        FROM    invoices
        )

You can wrap it into a function:

CREATE OR REPLACE FUNCTION fn_upd_invoices(id VARCHAR(32), billed VARCHAR(32))
RETURNS VOID
AS
$$
        UPDATE  invoices
        SET     billed = $2
        WHERE   invoices = $1;

        INSERT
        INTO    invoices (invoiceid, billed)
        SELECT  $1, $2
        WHERE   $1 NOT IN
                (
                SELECT  invoiceid
                FROM    invoices
                );
$$
LANGUAGE 'sql';

and just call it:

SELECT  fn_upd_invoices('12345', 'TRUE')

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Postgres integer arrays as parameters?

I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,

SELECT * FROM some_table WHERE id_column = ANY(@id_list)

where @id_list is bound to an int[] parameter by way of

command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;

where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).

How to split a line into words separated by one or more spaces in bash?

s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...

Difference Between $.getJSON() and $.ajax() in jQuery

.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc

N.B .load, .get and .post are also simple wrappers around the .ajax method.

How to make modal dialog in WPF?

Did you try showing your window using the ShowDialog method?

Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

Remove ':hover' CSS behavior from element

Use the :not pseudo-class to exclude the classes you don't want the hover to apply to:

FIDDLE

<div class="test"> blah </div>
<div class="test"> blah </div>
<div class="test nohover"> blah </div>

.test:not(.nohover):hover {  
    border: 1px solid red; 
}

This does what you want in one css rule!

Python display text with font & color?

You can use your own custom fonts by setting the font path using pygame.font.Font

pygame.font.Font(filename, size): return Font

example:

pygame.font.init()
font_path = "./fonts/newfont.ttf"
font_size = 32
fontObj = pygame.font.Font(font_path, font_size)

Then render the font using fontObj.render and blit to a surface as in veiset's answer above. :)

The import org.junit cannot be resolved

When you add TestNG to your Maven dependencies , Change scope from test to compile.Hope this would solve your issue..

Truncating all tables in a Postgres database

Explicit cursors are rarely needed in plpgsql. Use the simpler and faster implicit cursor of a FOR loop:

Note: Since table names are not unique per database, you have to schema-qualify table names to be sure. Also, I limit the function to the default schema 'public'. Adapt to your needs, but be sure to exclude the system schemas pg_* and information_schema.

Be very careful with these functions. They nuke your database. I added a child safety device. Comment the RAISE NOTICE line and uncomment EXECUTE to prime the bomb ...

CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
  RETURNS void AS
$func$
DECLARE
   _tbl text;
   _sch text;
BEGIN
   FOR _sch, _tbl IN 
      SELECT schemaname, tablename
      FROM   pg_tables
      WHERE  tableowner = _username
      AND  
      -- dangerous, test before you execute!
      RAISE NOTICE '%',  -- once confident, comment this line ...
      -- EXECUTE         -- ... and uncomment this one
         format('TRUNCATE TABLE %I.%I CASCADE', _sch, _tbl);
   END LOOP;
END
$func$ LANGUAGE plpgsql;

format() requires Postgres 9.1 or later. In older versions concatenate the query string like this:

'TRUNCATE TABLE ' || quote_ident(_sch) || '.' || quote_ident(_tbl)  || ' CASCADE';

Single command, no loop

Since we can TRUNCATE multiple tables at once we don't need any cursor or loop at all:

Aggregate all table names and execute a single statement. Simpler, faster:

CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
  RETURNS void AS
$func$
BEGIN
   -- dangerous, test before you execute!
   RAISE NOTICE '%',  -- once confident, comment this line ...
   -- EXECUTE         -- ... and uncomment this one
  (SELECT 'TRUNCATE TABLE '
       || string_agg(format('%I.%I', schemaname, tablename), ', ')
       || ' CASCADE'
   FROM   pg_tables
   WHERE  tableowner = _username
   AND    schemaname = 'public'
   );
END
$func$ LANGUAGE plpgsql;

Call:

SELECT truncate_tables('postgres');

Refined query

You don't even need a function. In Postgres 9.0+ you can execute dynamic commands in a DO statement. And in Postgres 9.5+ the syntax can be even simpler:

DO
$func$
BEGIN
   -- dangerous, test before you execute!
   RAISE NOTICE '%',  -- once confident, comment this line ...
   -- EXECUTE         -- ... and uncomment this one
   (SELECT 'TRUNCATE TABLE ' || string_agg(oid::regclass::text, ', ') || ' CASCADE'
    FROM   pg_class
    WHERE  relkind = 'r'  -- only tables
    AND    relnamespace = 'public'::regnamespace
   );
END
$func$;

About the difference between pg_class, pg_tables and information_schema.tables:

About regclass and quoted table names:

For repeated use

Create a "template" database (let's name it my_template) with your vanilla structure and all empty tables. Then go through a DROP / CREATE DATABASE cycle:

DROP DATABASE mydb;
CREATE DATABASE mydb TEMPLATE my_template;

This is extremely fast, because Postgres copies the whole structure on the file level. No concurrency issues or other overhead slowing you down.

If concurrent connections keep you from dropping the DB, consider:

Opening a new tab to read a PDF file

Will open your pdf in a new tab with pdf viewer and can download too

<a className=""
   href="/project_path_to_your_pdf_asset/failename.pdf"
   target="_blank"
>
   View PDF
</a>

toBe(true) vs toBeTruthy() vs toBeTrue()

Disclamer: This is just a wild guess

I know everybody loves an easy-to-read list:

  • toBe(<value>) - The returned value is the same as <value>
  • toBeTrue() - Checks if the returned value is true
  • toBeTruthy() - Check if the value, when cast to a boolean, will be a truthy value

    Truthy values are all values that aren't 0, '' (empty string), false, null, NaN, undefined or [] (empty array)*.

    * Notice that when you run !![], it returns true, but when you run [] == false it also returns true. It depends on how it is implemented. In other words: (!![]) === ([] == false)


On your example, toBe(true) and toBeTrue() will yield the same results.

How to reverse apply a stash?

git stash show -p | git apply --reverse

Warning, that would not in every case: "git apply -R"(man) did not handle patches that touch the same path twice correctly, which has been corrected with Git 2.30 (Q1 2021).

This is most relevant in a patch that changes a path from a regular file to a symbolic link (and vice versa).

See commit b0f266d (20 Oct 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit c23cd78, 02 Nov 2020)

apply: when -R, also reverse list of sections

Helped-by: Junio C Hamano
Signed-off-by: Jonathan Tan

A patch changing a symlink into a file is written with 2 sections (in the code, represented as "struct patch"): firstly, the deletion of the symlink, and secondly, the creation of the file.

When applying that patch with -R, the sections are reversed, so we get: (1) creation of a symlink, then (2) deletion of a file.

This causes an issue when the "deletion of a file" section is checked, because Git observes that the so-called file is not a file but a symlink, resulting in a "wrong type" error message.

What we want is: (1) deletion of a file, then (2) creation of a symlink.

In the code, this is reflected in the behavior of previous_patch() when invoked from check_preimage() when the deletion is checked.
Creation then deletion means that when the deletion is checked, previous_patch() returns the creation section, triggering a mode conflict resulting in the "wrong type" error message.

But deletion then creation means that when the deletion is checked, previous_patch() returns NULL, so the deletion mode is checked against lstat, which is what we want.

There are also other ways a patch can contain 2 sections referencing the same file, for example, in 7a07841c0b ("git-apply: handle a patch that touches the same path more than once better", 2008-06-27, Git v1.6.0-rc0 -- merge). "git apply -R"(man) fails in the same way, and this commit makes this case succeed.

Therefore, when building the list of sections, build them in reverse order (by adding to the front of the list instead of the back) when -R is passed.

How to convert a datetime to string in T-SQL

You can use the convert statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:

SELECT convert(varchar(20), getdate(), 120)

The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS in 24 hour clock.

You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.

How to call a method after bean initialization is complete?

To expand on the @PostConstruct suggestion in other answers, this really is the best solution, in my opinion.

  • It keeps your code decoupled from the Spring API (@PostConstruct is in javax.*)
  • It explicitly annotates your init method as something that needs to be called to initialize the bean
  • You don't need to remember to add the init-method attribute to your spring bean definition, spring will automatically call the method (assuming you register the annotation-config option somewhere else in the context, anyway).

How do you decompile a swf file

Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text

Angularjs ng-model doesn't work inside ng-if

The ng-if directive, like other directives creates a child scope. See the script below (or this jsfiddle)

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>_x000D_
_x000D_
<script>_x000D_
    function main($scope) {_x000D_
        $scope.testa = false;_x000D_
        $scope.testb = false;_x000D_
        $scope.testc = false;_x000D_
        $scope.obj = {test: false};_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<div ng-app >_x000D_
    <div ng-controller="main">_x000D_
        _x000D_
        Test A: {{testa}}<br />_x000D_
        Test B: {{testb}}<br />_x000D_
        Test C: {{testc}}<br />_x000D_
        {{obj.test}}_x000D_
        _x000D_
        <div>_x000D_
            testa (without ng-if): <input type="checkbox" ng-model="testa" />_x000D_
        </div>_x000D_
        <div ng-if="!testa">_x000D_
            testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            testc (with ng-if): <input type="checkbox" ng-model="testc" />_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            object (with ng-if): <input type="checkbox" ng-model="obj.test" />_x000D_
        </div>_x000D_
        _x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So, your checkbox changes the testb inside of the child scope, but not the outer parent scope.

Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.

Detecting when Iframe content has loaded (Cross browser)

to detect when the iframe has loaded and its document is ready?

It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).

If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:

<img id="x" ... />
<script type="text/javascript">
    document.getElementById('x').onload= function() {
        ...
    };
</script>

there is no guarantee that the item won't already have loaded by the time the script executes.

The ways out of load-races are:

  1. on IE, you can use the ‘readyState’ property to see if something's already loaded;

  2. if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;

  3. the old-school way of including it in the markup:

    <img onload="callback(this)" ... />

Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.

Remove the last line from a file in Bash

awk 'NR>1{print buf}{buf = $0}'

Essentially, this code says the following:

For each line after the first, print the buffered line

for each line, reset the buffer

The buffer is lagged by one line, hence you end up printing lines 1 to n-1

Passing JavaScript array to PHP through jQuery $.ajax

You need to turn this into a string. You can do this using the stringify method in the JSON2 library.

http://www.json.org/

http://www.json.org/js.html

The code would look something like:

var myJSONText = JSON.stringify(myObject);

So

['Location Zero', 'Location One', 'Location Two'];

Will become:

"['Location Zero', 'Location One', 'Location Two']"

You'll have to refer to a PHP guru on how to handle this on the server. I think other answers here intimate a solution.

Data can be returned from the server in a similar way. I.e. you can turn it back into an object.

var myObject = JSON.parse(myJSONString);

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

You can try

WebElement navigationPageButton = (new WebDriverWait(driver, 10))
 .until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();

Remove leading and trailing spaces?

Starting file:

     line 1
   line 2
line 3  
      line 4 

Code:

with open("filename.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        stripped = line.strip()
        print(stripped)

Output:

line 1
line 2
line 3
line 4

Is iterating ConcurrentHashMap values thread safe?

You may use this class to test two accessing threads and one mutating the shared instance of ConcurrentHashMap:

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Map<String, String> map;

    public Accessor(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (Map.Entry<String, String> entry : this.map.entrySet())
      {
        System.out.println(
            Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']'
        );
      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        System.out.println(Thread.currentThread().getName() + ": " + i);
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.map);
    Accessor a2 = new Accessor(this.map);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

No exception will be thrown.

Sharing the same iterator between accessor threads can lead to deadlock:

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while(iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st = Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

As soon as you start sharing the same Iterator<Map.Entry<String, String>> among accessor and mutator threads java.lang.IllegalStateExceptions will start popping up.

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st =
              Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Random random = new Random();

    private final Iterator<Map.Entry<String, String>> iterator;

    private final Map<String, String> map;

    public Mutator(Map<String, String> map, Iterator<Map.Entry<String, String>> iterator)
    {
      this.map = map;
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        try
        {
          iterator.remove();
          this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        } catch (Exception ex)
        {
          ex.printStackTrace();
        }
      }

    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(map, this.iterator);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

How to include a child object's child object in Entity Framework 5

A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.

public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)

{

    foreach (var include in includeProperties)
     {

        query = query.Include(include);
     }

        return query.ToList();
}

Open new popup window without address bars in firefox & IE

check this if it works it works fine for me

<script>
  var windowObjectReference;
  var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=400,height=350";

     function openRequestedPopup() {
      windowObjectReference = window.open("http://www.flyingedge.in/", "CNN_WindowName", strWindowFeatures);
     }
</script>

Iterating through list of list in Python

So wait, this is just a list-within-a-list?

The easiest way is probably just to use nested for loops:

>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
...     for number in list:
...         print number
...
1
3
4
2
4
4
3
4
5

Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.

Also, for performance reasons, you might want to look at using list comprehensions to do this:

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions

Define make variable at rule execution time

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

edit (in response to comments):

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

The modular crypt format for bcrypt consists of

  • $2$, $2a$ or $2y$ identifying the hashing algorithm and format
  • a two digit value denoting the cost parameter, followed by $
  • a 53 characters long base-64-encoded value (they use the alphabet ., /, 09, AZ, az that is different to the standard Base 64 Encoding alphabet) consisting of:
    • 22 characters of salt (effectively only 128 bits of the 132 decoded bits)
    • 31 characters of encrypted output (effectively only 184 bits of the 186 decoded bits)

Thus the total length is 59 or 60 bytes respectively.

As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARYor BINARY(60) (see The _bin and binary Collations for information about the difference).

CHAR is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A is treated as equal to a. See The _bin and binary Collations for more information.

When to use Hadoop, HBase, Hive and Pig?

Consider that you work with RDBMS and have to select what to use - full table scans, or index access - but only one of them.
If you select full table scan - use hive. If index access - HBase.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).

The reason I wanted that version in particular is because that's what ships with MVC currently.

Here's the code:

$(document).ready(function() {
    $("#topBar").css("position", "absolute");
});

$(window).scroll(function() {
    $("#topBar").css("top", $(window).scrollTop() + "px");
});

CodeIgniter removing index.php from url

Step:-1 Open the folder “application/config” and open the file “config.php“. find and replace the below code in config.php file.

//find the below code   
$config['index_page'] = "index.php" 
//replace with the below code
$config['index_page'] = ""

Step:-2 Go to your CodeIgniter folder and create .htaccess

Path:
Your_website_folder/
application/
assets/
system/
.htaccess <——— this file
index.php

Step:-3 Write below code in .htaccess file

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L] 
</IfModule>

Step:-4 In some case the default setting for uri_protocol does not work properly. To solve this problem just open the file “application/config/config.php“, then find and replace the below code

//Not needed for CodeIgniter 3 its already there.
//find the below code
$config['uri_protocol'] = "AUTO"
//replace with the below code
$config['uri_protocol'] = "REQUEST_URI" 

Thats all but in wamp server it does not work because rewrite_module by default disabled so we have need to enable it. for this do the following

  1. Left click WAMP icon
  2. Apache
  3. Apache Modules
  4. Left click rewrite_module

Original Documentation

Example Link

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

How to clear the logs properly for a Docker container?

Docker for Mac users, here is the solution:

    1. Find log file path by:

      $ docker inspect | grep log

    1. SSH into the docker machine( suppose the name is default, if not, run docker-machine ls to find out):

      $ docker-machine ssh default

    1. Change to root user(reference):

      $ sudo -i

    1. Delete the log file content:

      $ echo "" > log_file_path_from_step1

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Best way of invoking getter by reflection

You can invoke reflections and also, set order of sequence for getter for values through annotations

public class Student {

    private String grade;

    private String name;

    private String id;

    private String gender;

    private Method[] methods;

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Order {
        int value();
    }

    /**
     * Sort methods as per Order Annotations
     * 
     * @return
     */
    private void sortMethods() {

        methods = Student.class.getMethods();

        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                Order or1 = o1.getAnnotation(Order.class);
                Order or2 = o2.getAnnotation(Order.class);
                if (or1 != null && or2 != null) {
                    return or1.value() - or2.value();
                }
                else if (or1 != null && or2 == null) {
                    return -1;
                }
                else if (or1 == null && or2 != null) {
                    return 1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    /**
     * Read Elements
     * 
     * @return
     */
    public void readElements() {
        int pos = 0;
        /**
         * Sort Methods
         */
        if (methods == null) {
            sortMethods();
        }
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
                pos++;
                String value = "";
                try {
                    value = (String) method.invoke(this);
                }
                catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " Pos: " + pos + " Value: " + value);
            }
        }
    }

    // /////////////////////// Getter and Setter Methods

    /**
     * @param grade
     * @param name
     * @param id
     * @param gender
     */
    public Student(String grade, String name, String id, String gender) {
        super();
        this.grade = grade;
        this.name = name;
        this.id = id;
        this.gender = gender;
    }

    /**
     * @return the grade
     */
    @Order(value = 4)
    public String getGrade() {
        return grade;
    }

    /**
     * @param grade the grade to set
     */
    public void setGrade(String grade) {
        this.grade = grade;
    }

    /**
     * @return the name
     */
    @Order(value = 2)
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the id
     */
    @Order(value = 1)
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the gender
     */
    @Order(value = 3)
    public String getGender() {
        return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     * Main
     * 
     * @param args
     * @throws IOException
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Student student = new Student("A", "Anand", "001", "Male");
        student.readElements();
    }
  }

Output when sorted

getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A

How can I make XSLT work in chrome?

After 8 years the situation is changed a bit.

I'm unable to open a new session of Google Chrome without other parameters and allow 'file:' schema.

On macOS I do:

open -n -a "Google Chrome" --args \
    --disable-web-security \               # This disable all CORS and other security checks
    --user-data-dir=$HOME/fakeChromeDir    # This let you to force open a new Google Chrome session

Without this arguments I'm unable to test the XSL stylesheet in local.

Scale an equation to fit exact page width

\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

or

\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

Generate preview image from Video file?

I recommend php-ffmpeg library.

Extracting image

You can extract a frame at any timecode using the FFMpeg\Media\Video::frame method.

This code returns a FFMpeg\Media\Frame instance corresponding to the second 42. You can pass any FFMpeg\Coordinate\TimeCode as argument, see dedicated documentation below for more information.

$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');

If you want to extract multiple images from the video, you can use the following filter:

$video
    ->filters()
    ->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
    ->synchronize();

$video
    ->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');

By default, this will save the frames as jpg images.

You are able to override this using setFrameFileType to save the frames in another format:

$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);

$video->addFilter($filter);

Android how to use Environment.getExternalStorageDirectory()

Environment.getExternalStorageDirectory().getAbsolutePath()

Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.

Here's a simple example for writing a file:

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();

Edit:

Oops - you wanted an example for reading ...

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);

byte[] bytes;

// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes); 
fiStream.close();

Copying data from one SQLite database to another

Objective-C code for copy Table from a Database to another Database

-(void) createCopyDatabase{

          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
          NSString *documentsDir = [paths objectAtIndex:0];

          NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;

          NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
          NSFileManager *fileManager = [NSFileManager defaultManager];
          char *error;

         if ([fileManager fileExistsAtPath:newdbPath]) {
             [fileManager removeItemAtPath:newdbPath error:nil];
         }
         sqlite3 *database;
         //open database
        if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
            NSLog(@"Error to open database");
        }

        NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];

       sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
       if (error) {
           NSLog(@"Error to Attach = %s",error);
       }

       //Query for copy Table
       NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
       sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);
        }

        //Query for copy Table with Where Clause

        sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
        sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);
        }
 }

Creating a chart in Excel that ignores #N/A or blank cells

Select the labels above the bar. Format Data Labels. Instead of selecting "VALUE" (unclick). SELECT Value from cells. Select the value. Use the following statement: if(cellvalue="","",cellvalue) where cellvalue is what ever the calculation is in the cell.

omp parallel vs. omp parallel for

These are equivalent.

#pragma omp parallel spawns a group of threads, while #pragma omp for divides loop iterations between the spawned threads. You can do both things at once with the fused #pragma omp parallel for directive.

Shell script to delete directories older than n days

find supports -delete operation, so:

find /base/dir/* -ctime +10 -delete;

I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.

The most voted solution here is missing -maxdepth 0 so it will call rm -rf for every subdirectory, after deleting it. That doesn't make sense, so I suggest:

find /base/dir/* -maxdepth 0  -type d -ctime +10 -exec rm -rf {} \;

The -delete solution above doesn't use -maxdepth 0 because find would complain the dir is not empty. Instead, it implies -depth and deletes from the bottom up.

"Too many values to unpack" Exception

This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.

A quick search turned up an entry in James Bennett's blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.

To quote the blog entry:

The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.

If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.

TemplateSyntaxError at /

Caught an exception while rendering: too many values to unpack

Original Traceback (most recent call last):
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
    result = node.render(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
    output = force_unicode(self.filter_expression.resolve(context))
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
    obj = self.var.resolve(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
    value = self._resolve_lookup(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
    current = current()
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
    app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack

This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.

You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.

I'm 99% sure that this was the original problem encountered here.

how to sync windows time from a ntp time server in command

While the w32tm /resync in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".

In order to truly force the resync (Windows 7):

  1. Control Panel -> Date and Time
  2. "Change date and time..." (requires Admin privileges)
  3. Add or Subtract a few minutes (I used -5 minutes)
  4. Run "cmd.exe" as administrator
  5. w32tm /resync
  6. Visually check that the seconds in the "Date and Time" control panel are ticking at the same time as your authoritative clock(s). (I used watch -n 0.1 date on a Linux machine on the network that I had SSH'd over into)

--- Rapid Method ---

  1. Run "cmd.exe" as administrator
  2. net start w32time (Time Service must be running)
  3. time 8 (where 8 may be replaced by any 'hour' value, presumably 0-23)
  4. w32tm /resync
  5. Jump to 3, as needed.

UITableView, Separator color where to set?

Swift 3, xcode version 8.3.2, storyboard->choose your table View->inspector->Separator.

Swift 3, xcode version 8.3.2

How to hide/show div tags using JavaScript?

Have you tried

document.getElementById('body').style.display = "none";

instead of

document.getElementById('body').style.display = "hidden";?

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

How to convert a byte array to a hex string in Java?

This simple oneliner works for me
String result = new BigInteger(1, inputBytes).toString(16);
EDIT - Using this will remove the leading zeros, but hey worked for my use-case. Thanks @Voicu for pointing it out

VMWare Player vs VMWare Workstation

from http://www.vmware.com/products/player/faqs.html:

How does VMware Player compare to VMware Workstation? VMware Player enables you to quickly and easily create and run virtual machines. However, VMware Player lacks many powerful features, remote connections to vSphere, drag and drop upload to vSphere, multiple Snapshots and Clones, and much more.

Not being able to revert snapshots it's a big no for me.

Attach IntelliJ IDEA debugger to a running Java process

It's possible, but you have to add some JVM flags when you start your application.

You have to add remote debug configuration: Edit configuration -> Remote.

Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y)

Get bottom and right position of an element

You can use the .position() for this

var link = $(element);
var position = link.position(); //cache the position
var right = $(window).width() - position.left - link.width();
var bottom = $(window).height() - position.top - link.height();

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

I got this error: "Source option 5 is no longer supported. Use 6 or later" after I changed the pom.xml

<java.version>7</java.version>

to

<java.version>11</java.version>

Later to realise the property was used with a dash insteal of a dot:

  <source>${java-version}</source>
  <target>${java-version}</target>

(swearings), I replaced the dot with a dash and the error went away:

<java-version>11</javaversion>

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

What is Python Whitespace and how does it work?

Whitespace just means characters which are used for spacing, and have an "empty" representation. In the context of python, it means tabs and spaces (it probably also includes exotic unicode spaces, but don't use them). The definitive reference is here: http://docs.python.org/2/reference/lexical_analysis.html#indentation

I'm not sure exactly how to use it.

Put it at the front of the line you want to indent. If you mix spaces and tabs, you'll likely see funky results, so stick with one or the other. (The python community usually follows PEP8 style, which prescribes indentation of four spaces).

You need to create a new indent level after each colon:

for x in range(0, 50):
    print x
    print 2*x

print x

In this code, the first two print statements are "inside" the body of the for statement because they are indented more than the line containing the for. The third print is outside because it is indented less than the previous (nonblank) line.

If you don't indent/unindent consistently, you will get indentation errors. In addition, all compound statements (i.e. those with a colon) can have the body supplied on the same line, so no indentation is required, but the body must be composed of a single statement.

Finally, certain statements, like lambda feature a colon, but cannot have a multiline block as the body.

How can I convert a .py to .exe for Python?

I've been using Nuitka and PyInstaller with my package, PySimpleGUI.

Nuitka There were issues getting tkinter to compile with Nuikta. One of the project contributors developed a script that fixed the problem.

If you're not using tkinter it may "just work" for you. If you are using tkinter say so and I'll try to get the script and instructions published.

PyInstaller I'm running 3.6 and PyInstaller is working great! The command I use to create my exe file is:

pyinstaller -wF myfile.py

The -wF will create a single EXE file. Because all of my programs have a GUI and I do not want to command window to show, the -w option will hide the command window.

This is as close to getting what looks like a Winforms program to run that was written in Python.

[Update 20-Jul-2019]

There is PySimpleGUI GUI based solution that uses PyInstaller. It uses PySimpleGUI. It's called pysimplegui-exemaker and can be pip installed.

pip install PySimpleGUI-exemaker

To run it after installing:

python -m pysimplegui-exemaker.pysimplegui-exemaker

SQLRecoverableException: I/O Exception: Connection reset

add java security in your run command

java -jar -Djava.security.egd="file:///dev/urandom" yourjarfilename.jar

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

c# regex matches example

So you're trying to grab numeric values that are preceded by the token "%download%#"?

Try this pattern:

(?<=%download%#)\d+

That should work. I don't think # or % are special characters in .NET Regex, but you'll have to either escape the backslash like \\ or use a verbatim string for the whole pattern:

var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);

Tested here: http://rextester.com/BLYCC16700

NOTE: The lookbehind assertion (?<=...) is important because you don't want to include %download%# in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. More on lookaround assertions here.

Trying to get property of non-object - Laravel 5

Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).

How do I "break" out of an if statement?

There's always a goto statement, but I would recommend nesting an if with an inverse of the breaking condition.

How to tell if a connection is dead in python

It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I got this issue when Eclipse was unable to find the JDBC driver. Had to do a gradle refresh from the eclipse to get this work.

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

Error while inserting date - Incorrect date value:

I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.

My error message:

Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.

Convert command line arguments into an array in Bash

Side-by-side view of how the array and $@ are practically the same.

Code:

#!/bin/bash

echo "Dollar-1 : $1"
echo "Dollar-2 : $2"
echo "Dollar-3 : $3"
echo "Dollar-AT: $@"
echo ""

myArray=( "$@" )

echo "A Val 0: ${myArray[0]}"
echo "A Val 1: ${myArray[1]}"
echo "A Val 2: ${myArray[2]}"
echo "A All Values: ${myArray[@]}"

Input:

./bash-array-practice.sh 1 2 3 4

Output:

Dollar-1 : 1
Dollar-2 : 2
Dollar-3 : 3
Dollar-AT: 1 2 3 4

A Val 0: 1
A Val 1: 2
A Val 2: 3
A All Values: 1 2 3 4

How do I search for an object by its ObjectId in the mongo console?

I think you better write something like this:

db.getCollection('Blog').find({"_id":ObjectId("58f6724e97990e9de4f17c23")})

Return row of Data Frame based on value in a column - R

You could use dplyr:

df %>% group_by("Amount") %>% slice(which.min(x))

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

Is there a reason for C#'s reuse of the variable in a foreach?

In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.

The language specification says:

8.8.4 The foreach statement

(...)

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
  E e = ((C)(x)).GetEnumerator();
  try {
      while (e.MoveNext()) {
          V v = (V)(T)e.Current;
          embedded-statement
      }
  }
  finally {
      … // Dispose e
  }
}

(...)

The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:

int[] values = { 7, 9, 13 };
Action f = null;
foreach (var value in values)
{
    if (f == null) f = () => Console.WriteLine("First value: " + value);
}
f();

If v was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13, which is what the invocation of f would print. Instead, because each iteration has its own variable v, the one captured by f in the first iteration will continue to hold the value 7, which is what will be printed. (Note: earlier versions of C# declared v outside of the while loop.)

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Try like this:

$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);

Pay particular attention to the set() call's 3rd parameter. false prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data array.

The query generated by above code:

UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'

How to clear a data grid view

DataGrid.DataSource = null;
DataGrid.DataBind();

How to merge two sorted arrays into a sorted array?

public static int[] merge(int[] a, int[] b) {

    int[] answer = new int[a.length + b.length];
    int i = 0, j = 0, k = 0;

    while (i < a.length && j < b.length)  
       answer[k++] = a[i] < b[j] ? a[i++] :  b[j++];

    while (i < a.length)  
        answer[k++] = a[i++];

    while (j < b.length)    
        answer[k++] = b[j++];

    return answer;
}

Is a little bit more compact but exactly the same!

Dynamically load a function from a DLL

LoadLibrary does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary is called at runtime (remember that C++ is a statically typed language).

You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress.

Example

#include <windows.h>
#include <iostream>

/* Define a function pointer for our imported
 * function.
 * This reads as "introduce the new type f_funci as the type: 
 *                pointer to a function returning an int and 
 *                taking no arguments.
 *
 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)
 * with the exported function. __stdcall is the convention used by the WinAPI
 */
typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // resolve function address here
  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;

  return EXIT_SUCCESS;
}

Also, you should export your function from the DLL correctly. This can be done like this:

int __declspec(dllexport) __stdcall funci() {
   // ...
}

As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

If you look into the source of java.lang.Runtime, you'll see exec finally call protected method: execVM, which means it uses Virtual memory. So for Unix-like system, VM depends on amount of swap space + some ratio of physical memory.

Michael's answer did solve your problem but it might (or to say, would eventually) cause the O.S. deadlock in memory allocation issue since 1 tell O.S. less careful of memory allocation & 0 is just guessing & obviously that you are lucky that O.S. guess you can have memory THIS TIME. Next time? Hmm.....

Better approach is that you experiment your case & give a good swap space & give a better ratio of physical memory used & set value to 2 rather than 1 or 0.

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Git submodule head 'reference is not a tree' error

Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.

The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.

Inside, Out

If you already know which commit you want the submodule to use, cd to the submodule, check out the commit you want, then git add and git commit it back in the super-project.

Example:

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c. Go there and check it out directly.

Checkout in the Submodule

$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..

Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit> to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).

Update the Super-project

A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.

$ git add sub

Check the Results

$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.


Outside, In

If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.

Find the Super-project's Errant Commit

$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

OK, it looks like it went bad in ce5d37c, so we will restore the submodule from its parent (ce5d37c~).

Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c) and use the above “inside, out” process instead.

Checkout in the Super-project

$ git checkout ce5d37c~ -- sub

This reset the submodule entry for sub to what it was at commit ce5d37c~ in the super-project.

Update the Submodule

$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'

The submodule update went OK (it indicates a detached HEAD).

Check the Results

$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The first diff shows that sub is now the same in ce5d37c~. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.

how to pass command line arguments to main method dynamically

go to Run Configuration and in argument tab you can write your argument

How do I create an Android Spinner as a popup?

Adding a small attribute as android:spinnerMode="dialog" would show the spinner contents in a pop-up.

Using Spring 3 autowire in a standalone Java application

Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.

package com.zetcode.bean;

import org.springframework.stereotype.Component;

@Component
public class Message {

   private String message = "Hello there!";

   public void setMessage(String message){

      this.message  = message;
   }

   public String getMessage(){

      return message;
   }
}

This is a simple bean. It is decorated with the @Component annotation for auto-detection by Spring container.

package com.zetcode.main;

import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(Application.class);

        Application p = context.getBean(Application.class);
        p.start();
    }

    @Autowired
    private Message message;
    private void start() {
        System.out.println("Message: " + message.getMessage());
    }
}

This is the main Application class. The @ComponentScan annotation searches for components. The @Autowired annotation injects the bean into the message variable. The AnnotationConfigApplicationContext is used to create the Spring application context.

My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.

SQL Server using wildcard within IN

Try this

select * 
from jobdetails 
where job_no between '0711' and '0713'

the only problem is that job '0713' is going to be returned as well so can use '07299999999999' or just add and job_no <> '0713'

Dan zamir

replace anchor text with jquery

To reference an element by id, you need to use the # qualifier.

Try:

alert($("#link1").text());

To replace it, you could use:

$("#link1").text('New text');

The .html() function would work in this case too.

jQuery change event on dropdown

You should've kept that DOM ready function

$(function() {
    $("#projectKey").change(function() {
        alert( $('option:selected', this).text() );
    });
});

The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body> tag

How to find schema name in Oracle ? when you are connected in sql session using read only user

To create a read-only user, you have to setup a different user than the one owning the tables you want to access.

If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:

  1. Set the current schema in your session:
ALTER SESSION SET CURRENT_SCHEMA=XYZ
  1. Create synonyms for all tables:
CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1

So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:

  1. Query the current schema setting:
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL
  1. List your synonyms:
SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER
  1. Investigate all tables (with the exception of the some well-known standard schemas):
SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS');

How do I filter ForeignKey choices in a Django ModelForm?

This is simple, and works with Django 1.4:

class ClientAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ClientAdminForm, self).__init__(*args, **kwargs)
        # access object through self.instance...
        self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)

class ClientAdmin(admin.ModelAdmin):
    form = ClientAdminForm
    ....

You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):

ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to 
   override the default formfield for a foreign keys field. For example, 
   to return a subset of objects for this foreign key field based on the
   user:'''

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.

I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site.

The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration).

The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset.

In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above.

class FrontEndAdmin(models.ModelAdmin):
    def __init__(self, model, admin_site):
        self.model = model
        self.opts = model._meta
        self.admin_site = admin_site
        super(FrontEndAdmin, self).__init__(model, admin_site)

remove 'delete' buttons:

    def get_actions(self, request):
        actions = super(FrontEndAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

prevents delete permission

    def has_delete_permission(self, request, obj=None):
        return False

filters objects that can be viewed on the admin site:

    def get_queryset(self, request):
        if request.user.is_superuser:
            try:
                qs = self.model.objects.all()
            except AttributeError:
                qs = self.model._default_manager.get_queryset()
            return qs

        else:
            try:
                qs = self.model.objects.all()
            except AttributeError:
                qs = self.model._default_manager.get_queryset()

            if hasattr(self.model, ‘user’):
                return qs.filter(user=request.user)
            if hasattr(self.model, ‘porcupine’):
                return qs.filter(porcupine=request.user.porcupine)
            else:
                return qs

filters choices for all foreignkey fields on the admin site:

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if request.employee.is_superuser:
            return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

        else:
            if hasattr(db_field.rel.to, 'user'):
                kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
            if hasattr(db_field.rel.to, 'porcupine'):
                kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
            return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

What does value & 0xff do in Java?

In 32 bit format system the hexadecimal value 0xff represents 00000000000000000000000011111111 that is 255(15*16^1+15*16^0) in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.

How can I give access to a private GitHub repository?

Struggled to find this as well.

Heres a screenshot of how to do it:

enter image description here

How to get the position of a character in Python?

What happens when the string contains a duplicate character? from my experience with index() I saw that for duplicate you get back the same index.

For example:

s = 'abccde'
for c in s:
    print('%s, %d' % (c, s.index(c)))

would return:

a, 0
b, 1
c, 2
c, 2
d, 4

In that case you can do something like that:

for i, character in enumerate(my_string):
   # i is the position of the character in the string

The type or namespace name could not be found

I encountered this issue it turned out to be.

Project B references Project A.

Project A compiled as A.dll (assembly name = A).

Project B compiled as A.dll (assembly name A).

Visual Studio 2010 wasn't catching this. Resharper was okay, but wouldn't compile. WinForms designer gave misleading error message saying likely resulting from incompatbile platform targets.

The solution, after a painful day, was to make sure assemblies don't have same name.

Is there a float input type in HTML5?

This topic (e.g. step="0.01") relates to stepMismatch and is supported by all browsers as follows: enter image description here

What's your most controversial programming opinion?

Less code is better than more!

If the users say "that's it?", and your work remains invisible, it's done right. Glory can be found elsewhere.

How to strip all non-alphabetic characters from string in SQL Server?

Another possibe option for SQL Server 2017+, without loops and/or recursion, is a string-based approach using TRANSLATE() and REPLACE().

T-SQL statement:

DECLARE @pattern varchar(52) = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

SELECT 
   v.[Text], 
   REPLACE(
      TRANSLATE(
         v.[Text],
         REPLACE(TRANSLATE(v.[Text], @pattern, REPLICATE('a', LEN(@pattern))), 'a', ''),
         REPLICATE('0', LEN(REPLACE(TRANSLATE(v.[Text], @pattern, REPLICATE('a', LEN(@pattern))), 'a', '')))
      ),
      '0',
      ''
   ) AS AlphabeticCharacters
FROM (VALUES
   ('abc1234def5678ghi90jkl#@$&'),
   ('1234567890'),
   ('JAHDBESBN%*#*@*($E*sd55bn')
) v ([Text])

or as a function:

CREATE FUNCTION dbo.RemoveNonAlphabeticCharacters (@Text varchar(1000)) 
RETURNS varchar(1000)
AS BEGIN

   DECLARE @pattern varchar(52) = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
   SET @text = REPLACE(
      TRANSLATE(
         @Text,
         REPLACE(TRANSLATE(@Text, @pattern, REPLICATE('a', LEN(@pattern))), 'a', ''),
         REPLICATE('0', LEN(REPLACE(TRANSLATE(@Text, @pattern, REPLICATE('a', LEN(@pattern))), 'a', '')))
      ),
      '0',
      ''
   )
   
   RETURN @Text
END

Best practice to return errors in ASP.NET Web API

For Web API 2 my methods consistently return IHttpActionResult so I use...

public IHttpActionResult Save(MyEntity entity)
{
  ....

    return ResponseMessage(
        Request.CreateResponse(
            HttpStatusCode.BadRequest, 
            validationErrors));
}

How should I escape commas and speech marks in CSV files so they work in Excel?

Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:

'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'

Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)

How does `scp` differ from `rsync`?

rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.

Use rsync -vP username@host:/path/to/file .

The -P option preserves partially downloaded files and also shows progress.

As usual check man rsync

What is the best regular expression to check if a string is a valid URL?

I found the following Regex for URLs, tested successfully with 500+ URLs:

/\b(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\b/gi

I know it looks ugly, but the good thing is that it works. :)

Explanation and demo with 581 random URLs on regex101.

Source: In search of the perfect URL validation regex

Can an Option in a Select tag carry multiple values?

I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.

HTML

<select class="example">
    <option value="1" data-value="A">One</option>
    <option value="2" data-value="B">Two</option>
    <option value="3" data-value="C">Three</option>
    <option value="4" data-value="D">Four</option>
</select>

JS

$('select.example').change(function() {

    var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');

    console.log(other_val);

});

Set angular scope variable in markup

You can set values from html like this. I don't think there is a direct solution from angular yet.

 <div style="visibility: hidden;">{{activeTitle='home'}}</div>

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

Remove files from Git commit

As the accepted answer indicates, you can do this by resetting the entire commit. But this is a rather heavy handed approach.
A cleaner way to do this would be to keep the commit, and simply remove the changed files from it.

git reset HEAD^ -- path/to/file
git commit --amend --no-edit

The git reset will take the file as it was in the previous commit, and stage it in the index. The file in the working directory is untouched.
The git commit will then commit and squash the index into the current commit.

This essentially takes the version of the file that was in the previous commit and adds it to the current commit. This results in no net change, and so the file is effectively removed from the commit.

How to check if NSString begins with a certain character

Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.

Can I do Model->where('id', ARRAY) multiple where conditions?

If you need by several params:

$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
                  ->whereNotIn('id', $not_ids)
                  ->where('status', 1)
                  ->get();

How can I compare two dates in PHP?

If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:

$date = $row->expireDate;

$date->add(new DateInterval('PT24H')); // adds 24 hours

$now = new \DateTime();

if($now < $date) { /* expired after 24 hours */ }

But in your case you could do the comparison just as the following:

$today = new DateTime('Y-m-d');

$date = $row->expireDate;

if($today < $date) { /* do something */ }

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

Difference between ref and out parameters in .NET

Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.

namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            // u can try giving int i=100 but is useless as that value is not passed into
            // the method. Only variable goes into the method and gets changed its
            // value and comes out. 
            int i; 

            a.abc(out i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(out int i)
        {

            i = 10;

        }

    }
}

Output:

10

===============================================

Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.

namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            int i = 0;

            a.abc(ref i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(ref int i)
        {
            System.Console.WriteLine(i);
            i = 10;

        }

    }
}

Output:

    0
    10

=================================

Hope its clear now.

How do I check if a file exists in Java?

There is specific purpose to design these methods. We can't say use anyone to check file exist or not.

  1. isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
  2. exists(): Tests whether the file or directory denoted by this abstract pathname exists. docs.oracle.com

Remove an onclick listener

    /**
 * Remove an onclick listener
 *
 * @param view
 * @author [email protected]
 * @website https://github.com/androidmalin
 * @data 2016-05-16
 */
public static void unBingListener(View view) {
    if (view != null) {
        try {
            if (view.hasOnClickListeners()) {
                view.setOnClickListener(null);

            }

            if (view.getOnFocusChangeListener() != null) {
                view.setOnFocusChangeListener(null);

            }

            if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
                ViewGroup viewGroup = (ViewGroup) view;
                int viewGroupChildCount = viewGroup.getChildCount();
                for (int i = 0; i < viewGroupChildCount; i++) {
                    unBingListener(viewGroup.getChildAt(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Using DISTINCT inner join in SQL

Is this what you mean?

SELECT DISTINCT C.valueC
FROM 
C
INNER JOIN B ON C.id = B.lookupC
INNER JOIN A ON B.id = A.lookupB

How do I pass an object from one activity to another on Android?

It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.