Programs & Examples On #Javascript framework

A JavaScript framework is a library of pre-written JavaScript which allows for easier development of JavaScript-based applications, especially for AJAX and other web-centric technologies.

AngularJs ReferenceError: $http is not defined

Probably you haven't injected $http service to your controller. There are several ways of doing that.

Please read this reference about DI. Then it gets very simple:

function MyController($scope, $http) {
   // ... your code
}

Angular JS break ForEach

Use the Array Some Method

 var exists = [0,1,2].some(function(count){
      return count == 1
 });

exists will return true, and you can use this as a variable in your function

if(exists){
    console.log('this is true!')
}

Array Some Method - Javascript

Get epoch for a specific date using Javascript

Number(new Date(2010, 6, 26))

Works the same way as things above. If you need seconds don't forget to / 1000

AngularJS passing data to $http.get request

Starting from AngularJS v1.4.8, you can use get(url, config) as follows:

var data = {
 user_id:user.id
};

var config = {
 params: data,
 headers : {'Accept' : 'application/json'}
};

$http.get(user.details_path, config).then(function(response) {
   // process response here..
 }, function(response) {
});

How to get an element by its href in jquery?

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="http://google.com"]');

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

jQuery: Check if div with certain class name exists

You can use size(), but jQuery recommends you use length to avoid the overhead of another function call:

$('div.mydivclass').length

So:

// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {

http://api.jquery.com/size/

http://api.jquery.com/length/

UPDATE

The selected answer uses a perf test, but it's slightly flawed since it is also including element selection as part of the perf, which is not what's being tested here. Here is an updated perf test:

http://jsperf.com/check-if-div-exists/3

My first run of the test shows that property retrieval is faster than index retrieval, although IMO it's pretty negligible. I still prefer using length as to me it makes more sense as to the intent of the code instead of a more terse condition.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

As complement to Mark's answer, the compile function does not have access to scope, but the link function does.

I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).

How to create a jQuery plugin with methods?

What about using triggers? Does anyone know any drawback using them? The benefit is that all internal variables are accessible via the triggers, and the code is very simple.

See on jsfiddle.

Example usage

<div id="mydiv">This is the message container...</div>

<script>
    var mp = $("#mydiv").messagePlugin();

    // the plugin returns the element it is called on
    mp.trigger("messagePlugin.saySomething", "hello");

    // so defining the mp variable is not needed...
    $("#mydiv").trigger("messagePlugin.repeatLastMessage");
</script>

Plugin

jQuery.fn.messagePlugin = function() {

    return this.each(function() {

        var lastmessage,
            $this = $(this);

        $this.on('messagePlugin.saySomething', function(e, message) {
            lastmessage = message;
            saySomething(message);
        });

        $this.on('messagePlugin.repeatLastMessage', function(e) {
            repeatLastMessage();
        });

        function saySomething(message) {
            $this.html("<p>" + message + "</p>");
        }

        function repeatLastMessage() {
            $this.append('<p>Last message was: ' + lastmessage + '</p>');
        }

    });

}

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

Please check this jsFiddle. (The code is basically the same you posted but I use an element instead of the window to bind the scroll events).

As far as I can see, there is no problem with the code you posted. The error you mentioned normally occurs when you create a loop of changes over a property. For example, like when you watch for changes on a certain property and then change the value of that property on the listener:

$scope.$watch('users', function(value) {
  $scope.users = [];
});

This will result on an error message:

Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: ...

Make sure that your code doesn't have this kind of situations.

update:

This is your problem:

<div ng-init="user.score=user.id+1"> 

You shouldn't change objects/models during the render or otherwise, it will force a new render (and consequently a loop, which causes the 'Error: 10 $digest() iterations reached. Aborting!').

If you want to update the model, do it on the Controller or on a Directive, never on the view. angularjs documentation recommends not to use the ng-init exactly to avoid these kinds of situations:

Use ngInit directive in templates (for toy/example apps only, not recommended for real applications)

Here's a jsFiddle with a working example.

How to generate UL Li list from string array using jquery?

Other variation of Abhishek Bhalani: You can use Array.map() instead of $.each()

var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
      var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
      $('<a class="ui-all">'+ i + ': ' + item.name + '<a/>')
        .appendTo(li);
    });

What is the difference between React Native and React?

In Reactjs, virtual DOM is used to render browser code in Reactjs while in React Native, native APIs are used to render components in mobile.

The apps developed with Reactjs renders HTML in UI while React Native uses JSX for rendering UI, which is nothing but javascript.

Convert dd-mm-yyyy string to date

regular expression example:

new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

On Windows I had solved this problem in the following way :

1) uninstalled Python

2) navigated to C:\Users\MyName\AppData\Local\Programs(your should turn on hidden files visibility Show hidden files instruction)

3) deleted 'Python' folder

4) installed Python

While loop in batch

A while loop can be simulated in cmd.exe with:

:still_more_files
    if %countfiles% leq 21 (
        rem change countfile here
        goto :still_more_files
    )

For example, the following script:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    set /a "x = 0"

:more_to_process
    if %x% leq 5 (
        echo %x%
        set /a "x = x + 1"
        goto :more_to_process
    )

    endlocal

outputs:

0
1
2
3
4
5

For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:

    @echo off
    set backupdir=c:\test

:more_files_to_process
    for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
    if %num% gtr 20 (
        cscript /nologo c:\deletefile.vbs %backupdir%
        goto :more_files_to_process
    )

Javascript search inside a JSON object

You can try this:

function search(data,search) {
    var obj = [], index=0;
    for(var i=0; i<data.length; i++) {
      for(key in data[i]){
         if(data[i][key].toString().toLowerCase().indexOf(search.toLowerCase())!=-1) {
                obj[index] = data[i];
                index++;
                break;
         }
     }
     return obj;
}
console.log(search(obj.list,'my Name'));

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

For the difference between A1 and Today's date you could enter: =ABS(TODAY()-A1)

which returns the (fractional) number of days between the dates.

You're likely getting a #VALUE! error in your formula because Excel treats dates as numbers.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Non-invocable member cannot be used like a method?

As the error clearly states, OffenceBox.Text() is not a function and therefore doesn't make sense.

JavaScript: Get image dimensions

Similar question asked and answered using JQuery here:

Get width height of remote image from url

function getMeta(url){
  $("<img/>").attr("src", url).load(function(){
     s = {w:this.width, h:this.height};
     alert(s.w+' '+s.h);      
  }); 
}

getMeta("http://page.com/img.jpg");

changing source on html5 video tag

Another way you can do in Jquery.

HTML

<video id="videoclip" controls="controls" poster="" title="Video title">
    <source id="mp4video" src="video/bigbunny.mp4" type="video/mp4"  />
</video>

<div class="list-item">
     <ul>
         <li class="item" data-video = "video/bigbunny.mp4"><a href="javascript:void(0)">Big Bunny.</a></li>
     </ul>
</div>

Jquery

$(".list-item").find(".item").on("click", function() {
        let videoData = $(this).data("video");
        let videoSource = $("#videoclip").find("#mp4video");
        videoSource.attr("src", videoData);
        let autoplayVideo = $("#videoclip").get(0);
        autoplayVideo.load();
        autoplayVideo.play();
    });

How to shift a block of code left/right by one space in VSCode?

UPDATE

While these methods work, newer versions of VS Code uses the Ctrl+] shortcut to indent a block of code once, and Ctrl+[ to remove indentation.

This method detects the indentation in a file and indents accordingly.You can change the size of indentation by clicking on the Select Indentation setting in the bottom right of VS Code (looks something like "Spaces: 2"), selecting "Indent using Spaces" from the drop-down menu and then selecting by how many spaces you would like to indent.

How to delete large data of table in SQL without log?

Shorter syntax

select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
  DELETE TOP (10000) LargeTable 
  WHERE readTime < dateadd(MONTH,-7,GETDATE())
END

See full command of running/stopped container in Docker

docker ps --no-trunc will display the full command along with the other details of the running containers.

Shortcut to Apply a Formula to an Entire Column in Excel

Select a range of cells (the entire column in this case), type in your formula, and hold down Ctrl while you press Enter. This places the formula in all selected cells.

pandas groupby sort descending order

Do your groupby, and use reset_index() to make it back into a DataFrame. Then sort.

grouped = df.groupby('mygroups').sum().reset_index()
grouped.sort_values('mygroups', ascending=False)

Android - how to replace part of a string by another string?

String str = "to";
str.replace("to", "xyz");

Just try it :)

Unzip files programmatically in .net

Until now, I was using cmd processes in order to extract an .iso file, copy it into a temporary path from server and extracted on a usb stick. Recently I've found that this is working perfectly with .iso's that are less than 10Gb. For a iso like 29Gb this method gets stuck somehow.

    public void ExtractArchive()
    {
        try
        {

            try
            {
                Directory.Delete(copyISOLocation.OutputPath, true); 
            }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
            }

            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            //stackoverflow
            cmd.StartInfo.Arguments = "-R";

            cmd.Disposed += (sender, args) => {
                Console.WriteLine("CMD Process disposed");
            };
            cmd.Exited += (sender, args) => {
                Console.WriteLine("CMD Process exited");
            };
            cmd.ErrorDataReceived += (sender, args) => {
                Console.WriteLine("CMD Process error data received");
                Console.WriteLine(args.Data);
            };
            cmd.OutputDataReceived += (sender, args) => {
                Console.WriteLine("CMD Process Output data received");
                Console.WriteLine(args.Data);
            };

            //stackoverflow


            cmd.Start();

            cmd.StandardInput.WriteLine("C:");
            //Console.WriteLine(cmd.StandardOutput.Read());
            cmd.StandardInput.Flush();

            cmd.StandardInput.WriteLine("cd C:\\\"Program Files (x86)\"\\7-Zip\\");
            //Console.WriteLine(cmd.StandardOutput.ReadToEnd());
            cmd.StandardInput.Flush();

            cmd.StandardInput.WriteLine(string.Format("7z.exe x -o{0} {1}", copyISOLocation.OutputPath, copyISOLocation.TempIsoPath));
            //Console.WriteLine(cmd.StandardOutput.ReadToEnd());
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();
            Console.WriteLine(cmd.StandardOutput.ReadToEnd());
            Console.WriteLine(cmd.StandardError.ReadToEnd());

Find a line in a file and remove it

I refactored the solution that Narek had to create (according to me) a slightly more efficient and easy to understand code. I used embedded Automatic Resource Management, a recent feature in Java and used a Scanner class which according to me is more easier to understand and use.

Here is the code with edited Comments:

public class RemoveLineInFile {

    private static File file;

    public static void main(String[] args) {
        //create a new File
        file = new File("hello.txt");
        //takes in String that you want to get rid off
        removeLineFromFile("Hello");
    }


    public static void removeLineFromFile(String lineToRemove) {


        //if file does not exist, a file is created

            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    System.out.println("File "+file.getName()+" not created successfully");
                }
            }

            // Construct the new temporary file that will later be renamed to the original
            // filename.
            File tempFile = new File(file.getAbsolutePath() + ".tmp");

           //Two Embedded Automatic Resource Managers used
            // to effectivey handle IO Responses
          try(Scanner scanner = new Scanner(file)) {
              try (PrintWriter pw = new PrintWriter(new FileWriter(tempFile))) {

                  //a declaration of a String Line Which Will Be assigned Later
                  String line;

                  // Read from the original file and write to the new
                  // unless content matches data to be removed.
                  while (scanner.hasNextLine()) {
                      line = scanner.nextLine();
                      if (!line.trim().equals(lineToRemove)) {

                          pw.println(line);
                          pw.flush();
                      }
                  }
                  // Delete the original file
                  if (!file.delete()) {
                      System.out.println("Could not delete file");
                      return;
                  }

                  // Rename the new file to the filename the original file had.
                  if (!tempFile.renameTo(file))
                      System.out.println("Could not rename file");
              }
          }
        catch (IOException e)
        {
            System.out.println("IO Exception Occurred");
        }

    }



}

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

In your pom.xml you should add distributionManagement configuration to where to deploy.

In the following example I have used file system as the locations.

<distributionManagement>
       <repository>
         <id>internal.repo</id>
         <name>Internal repo</name>
         <url>file:///home/thara/testesb/in</url>
       </repository>
   </distributionManagement>

you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :

mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

How to Replace dot (.) in a string in Java

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

Twitter Bootstrap vs jQuery UI?

Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,

  • Widgets: jQuery UI wins here. The date widget it provides is immensely useful, and Twitter Bootstrap provides nothing of the sort.
  • Scaffolding: Bootstrap wins here. Twitter's grid both fluid and fixed are top notch. jQuery UI doesn't even provide this direction leaving page layout up to the end user.
  • Out of the box professionalism: Bootstrap using CSS3 is leagues ahead, jQuery UI looks dated by comparison.
  • Icons: I'll go tie on this one. Bootstrap has nicer icons imho than jQuery UI, but I don't like the terms one bit, Glyphicons Halflings are normally not available for free, but an arrangement between Bootstrap and the Glyphicons creators have made this possible at no cost to you as developers. As a thank you, we ask you to include an optional link back to Glyphicons whenever practical.
  • Images & Thumbnails: goes to Bootstrap, jQuery UI doesn't even help here.

Other notes,

  • It's important to understand how these two technologies compete in the spheres too. There is a lot of overlap, but if you want simple scaffolding and fixed/fluid creation Bootstrap isn't another technology, it's the best technology. If you want any single widget, jQuery UI probably isn't even in the top three. Today, jQuery UI is mainly just a toy for consistency and proof of concept for a client-side widget creation using a unified framework.

INSERT with SELECT

I think your INSERT statement is wrong, see correct syntax: http://dev.mysql.com/doc/refman/5.1/en/insert.html

edit: as Andrew already pointed out...

How can I lookup a Java enum from its String value?

since java 8 you can initialize the map in a single line and without static block

private static Map<String, Verbosity> stringMap = Arrays.stream(values())
                 .collect(Collectors.toMap(Enum::toString, Function.identity()));

How disable / remove android activity label and label bar?

If your application theme is AppTheme(or anything else), then in styles.xml add the following code:

<style name="HiddenTitleTheme" parent="AppTheme">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
 </style>

Then in manifest file add the following in the activity tag for which you want to disable activity label:

android:theme="@style/HiddenTitleTheme"

Deleting multiple columns based on column names in Pandas

Not sure if this solution has been mentioned anywhere yet but one way to do is is pandas.Index.difference.

>>> df = pd.DataFrame(columns=['A','B','C','D'])
>>> df
Empty DataFrame
Columns: [A, B, C, D]
Index: []
>>> to_remove = ['A','C']
>>> df = df[df.columns.difference(to_remove)]
>>> df
Empty DataFrame
Columns: [B, D]
Index: []

Please explain the exec() function and its family

When a process uses fork(), it creates a duplicate copy of itself and this duplicates becomes the child of the process. The fork() is implemented using clone() system call in linux which returns twice from kernel.

  • A non-zero value(Process ID of child) is returned to the parent.
  • A value of zero is returned to the child.
  • In case the child is not created successfully due to any issues like low memory, -1 is returned to the fork().

Let’s understand this with an example:

pid = fork(); 
// Both child and parent will now start execution from here.
if(pid < 0) {
    //child was not created successfully
    return 1;
}
else if(pid == 0) {
    // This is the child process
    // Child process code goes here
}
else {
    // Parent process code goes here
}
printf("This is code common to parent and child");

In the example, we have assumed that exec() is not used inside the child process.

But a parent and child differs in some of the PCB(process control block) attributes. These are:

  1. PID - Both child and parent have a different Process ID.
  2. Pending Signals - The child doesn’t inherit Parent’s pending signals. It will be empty for the child process when created.
  3. Memory Locks - The child doesn’t inherit its parent’s memory locks. Memory locks are locks which can be used to lock a memory area and then this memory area cannot be swapped to disk.
  4. Record Locks - The child doesn’t inherit its parent’s record locks. Record locks are associated with a file block or an entire file.
  5. Process resource utilisation and CPU time consumed is set to zero for the child.
  6. The child also doesn’t inherit timers from the parent.

But what about the child memory? Is a new address space created for a child?

The answers in no. After the fork(), both parent and child share the memory address space of parent. In linux, these address space are divided into multiple pages. Only when the child writes to one of the parent memory pages, a duplicate of that page is created for the child. This is also known as copy on write(Copy parent pages only when the child writes to it).

Let’s understand copy on write with an example.

int x = 2;
pid = fork();
if(pid == 0) {
    x = 10;
    // child is changing the value of x or writing to a page
    // One of the parent stack page will contain this local               variable. That page will be duplicated for child and it will store the value 10 in x in duplicated page.  
}
else {
    x = 4;
}

But why is copy on write necessary?

A typical process creation takes place through fork()-exec() combination. Let’s first understand what exec() does.

Exec() group of functions replaces the child’s address space with a new program. Once exec() is called within a child, a separate address space will be created for the child which is totally different from the parent’s one.

If there was no copy on write mechanism associated with fork(), duplicate pages would have created for the child and all the data would have been copied to child’s pages. Allocating new memory and copying data is a very expensive process(takes processor’s time and other system resources). We also know that in most cases, the child is going to call exec() and that would replace the child’s memory with a new program. So the first copy which we did would have been a waste if copy on write was not there.

pid = fork();
if(pid == 0) {
    execlp("/bin/ls","ls",NULL);
    printf("will this line be printed"); // Think about it
    // A new memory space will be created for the child and that   memory will contain the "/bin/ls" program(text section), it's stack, data section and heap section
else {
    wait(NULL);
    // parent is waiting for the child. Once child terminates, parent will get its exit status and can then continue
}
return 1; // Both child and parent will exit with status code 1.

Why does parent waits for a child process?

  1. The parent can assign a task to it’s child and wait till it completes it’s task. Then it can carry some other work.
  2. Once the child terminates, all the resources associated with child are freed except for the process control block. Now, the child is in zombie state. Using wait(), parent can inquire about the status of child and then ask the kernel to free the PCB. In case parent doesn’t uses wait, the child will remain in the zombie state.

Why is exec() system call necessary?

It’s not necessary to use exec() with fork(). If the code that the child will execute is within the program associated with parent, exec() is not needed.

But think of cases when the child has to run multiple programs. Let’s take the example of shell program. It supports multiple commands like find, mv, cp, date etc. Will be it right to include program code associated with these commands in one program or have child load these programs into the memory when required?

It all depends on your use case. You have a web server which given an input x that returns the 2^x to the clients. For each request, the web server creates a new child and asks it to compute. Will you write a separate program to calculate this and use exec()? Or you will just write computation code inside the parent program?

Usually, a process creation involves a combination of fork(), exec(), wait() and exit() calls.

SyntaxError: expected expression, got '<'

I had this same error when I migrated a Wordpress site to another server. The URL in the header for my js scripts was still pointing to the old server and domain name.

Once I updated the domain name, the error went away.

Scroll part of content in fixed position container

What worked for me :

div#scrollable {
    overflow-y: scroll;
    max-height: 100vh;
}

How do I use Notepad++ (or other) with msysgit?

As of Git for Windows v2.15.0 (October 30th 2017) it is now possible to configure nano or Notepad++ as Git's default editor instead of vim.

During the installation you'll see the following screen:

enter image description here

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

Embed image in a <button> element

Why don't you use an image with an onclick attribute?

For example:

<script>
function myfunction() {
}
</script>
<img src='Myimg.jpg' onclick='myfunction()'>

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This happened to me because I created a new project which was trying to use System.Web.Providers DefaultMembershipProvider for membership. My DB and application was set up to use System.Web.Security.SqlMembershipProvider instead. I had to update the provider and connection string (since this provider seems to have some weird connection string requirements) to get it working.

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

Any way to write a Windows .bat file to kill processes?

Download PSKill. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.

ReferenceError: $ is not defined

Though my response is late, but it can still help.

lf you are using Spring Tool Suite and you still think that the JQuery file reference path is correct, then refresh your project whenever you modify the JQuery file.

You refresh by right-clicking on the project name -> refresh.

That's what solved mine.

SQL-Server: The backup set holds a backup of a database other than the existing

In the Options, change the "Restore As" file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.

How can I check whether a option already exist in select by JQuery

if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
  alert("option doesn't exist!");
}

Check if image exists on server using JavaScript?

You may call this JS function to check if file exists on the Server:

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();

    if (xhr.status == "404") {
        console.log("File doesn't exist");
        return false;
    } else {
        console.log("File exists");
        return true;
    }
}

How to auto-remove trailing whitespace in Eclipse?

I am not aware of any solution for the second part of your question. The reason is that it is not clear how to define I changed. Changed when? Just between 2 saves or between commits... Basically - forget it.

I assume you would like to stick to some guideline, but do not touch the rest of the code. But the guideline should be used overall, and not for bites and pieces. So my suggestion is - change all the code to the guideline: it is once-off operation, but make sure that all your developers have the same plugin (AnyEdit) with the same settings for the project.

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

How to fix/convert space indentation in Sublime Text?

I found, in my mind, a simpler solution than Magne:

On mac:

"cmd+f" => "  "(two spaces) => "alt+enter" => "arrow right" => "  "(two more spaces) => set tab width to 4(this can be done before or after.

On windows or other platforms change cmd+f and alt+enter with whatever your find and select all hotkeys are.

Note: this method is prone to "errors" if you have more than one space within your code. It is thus less safe than Magne's method, but it is faster (for me at least).

Add quotation at the start and end of each line in Notepad++

You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:

  1. Find (in regular expression mode):

    (.+)
    

    Replace with:

    "\1"
    

    This adds the quotes:

    "AliceBlue"
    "AntiqueWhite"
    "Aqua"
    "Aquamarine"
    "Azure"
    "Beige"
    "Bisque"
    "Black"
    "BlanchedAlmond"
    
  2. Find (in extended mode):

    \r\n
    

    Replace with (with a space after the comma, not shown):

    , 
    

    This converts the lines into a comma-separated list:

    "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
    

  3. Add the var myArray = assignment and braces manually:

    var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
    

What are the differences in die() and exit() in PHP?

PHP manual on die:

die — Equivalent to exit

You can even do die; the same way as exit; - with or without parens.

The only advantage of choosing die() over exit(), might be the time you spare on typing an extra letter ;-)

PHP: convert spaces in string into %20?

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

MySQL - ERROR 1045 - Access denied

I could not connect to MySql Administrator. I fixed it by creating another user and assigning all the permissions.

I logged in with that new user and it worked.

How do I manage conflicts with git submodules?

Well, its not technically managing conflicts with submodules (ie: keep this but not that), but I found a way to continue working...and all I had to do was pay attention to my git status output and reset the submodules:

git reset HEAD subby
git commit

That would reset the submodule to the pre-pull commit. Which in this case is exactly what I wanted. And in other cases where I need the changes applied to the submodule, I'll handle those with the standard submodule workflows (checkout master, pull down the desired tag, etc).

Doctrine findBy 'does not equal'

I solved this rather easily (without adding a method) so i'll share:

use Doctrine\Common\Collections\Criteria;

$repository->matching( Criteria::create()->where( Criteria::expr()->neq('id', 1) ) );

By the way, i'm using the Doctrine ORM module from within Zend Framework 2 and i'm not sure whether this would be compatible in any other case.

In my case, i was using a form element configuration like this: to show all roles except "guest" in a radio button array.

$this->add(array(
    'type' => 'DoctrineModule\Form\Element\ObjectRadio',
        'name' => 'roles',
        'options' => array(
            'label' => _('Roles'),
            'object_manager' => $this->getEntityManager(),
            'target_class'   => 'Application\Entity\Role',
            'property' => 'roleId',
            'find_method'    => array(
                'name'   => 'matching',
                'params' => array(
                    'criteria' => Criteria::create()->where(
                        Criteria::expr()->neq('roleId', 'guest')
                ),
            ),
        ),
    ),
));

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I used all above changes but still I was getting same issue on my web application.

Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.

They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.

Hope this answer will help someone.This is what worked for me

How to get the location of the DLL currently executing?

If you're working with an asp.net application and you want to locate assemblies when using the debugger, they are usually put into some temp directory. I wrote the this method to help with that scenario.

private string[] GetAssembly(string[] assemblyNames)
{
    string [] locations = new string[assemblyNames.Length];


    for (int loop = 0; loop <= assemblyNames.Length - 1; loop++)       
    {
         locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault();
    }
    return locations;
}

For more details see this blog post http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/

If you can't change the source code, or redeploy, but you can examine the running processes on the computer use Process Explorer. I written a detailed description here.

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

I've written a full description of how do this for a dll inside IIS - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

How can I provide multiple conditions for data trigger in WPF?

To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c).

For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.

The logic for dimming is thus:

NOT IsFocused AND (IsDefocused OR NOT Enabled)

To implement this logic, I made a generic IMultiValueConverter named (awkwardly) to match my logic

// 'P' represents a parenthesis
//     !  a &&  ( b ||  !  c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
    // redacted [...] for brevity
    public object Convert(object[] values, ...)
    {
        bool a = System.Convert.ToBoolean(values[0]);
        bool b = System.Convert.ToBoolean(values[1]);
        bool c = System.Convert.ToBoolean(values[2]);

        return !a && (b || !c);
    }
    ...
}

In the XAML I use this in a MultiDataTrigger in a <Style><Style.Triggers> resource

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <!-- when the equation is TRUE ... -->
        <Condition Value="True">
            <Condition.Binding>
                <MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
                    <!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
                    <Binding Path="IsFocus"/>
                    <Binding Path="IsDefocused" />
                    <Binding Path="Enabled" />
                </MultiBinding>
            </Condition.Binding>
        </Condition>
    </MultiDataTrigger.Conditions>
    <MultiDataTrigger.Setters>
        <!-- ... show the 'dim-out' overlay -->
        <Setter Property="Visibility" Value="Visible" />
    </MultiDataTrigger.Setters>
</MultiDataTrigger>

And for completeness sake, my converter is defined in a ResourceDictionary

<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
    <conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>

Load external css file like scripts in jquery which is compatible in ie also

Quick function based on responses.

loadCSS = function(href) {

  var cssLink = $("<link>");
  $("head").append(cssLink); //IE hack: append before setting href

  cssLink.attr({
    rel:  "stylesheet",
    type: "text/css",
    href: href
  });

};

Usage:

loadCSS("/css/file.css");

What is the difference between json.load() and json.loads() functions

Yes, s stands for string. The json.loads function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!

How to make an anchor tag refer to nothing?

Here are the three ways for <a> tag's href tag property refer to nothing:

<a href="JavaScript:void(0)"> link </a>

<a href="javascript:;">link</a >

<a href="#" onclick="return false;"> Link </a>

anaconda/conda - install a specific package version

If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used

conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"

conda install -y torchvision">=0.3.0"
conda install  openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"

where option -y, --yes Do not ask for confirmation.

Here is a summary:

Format         Sample Specification     Results
Exact          qtconsole==4.5.1         4.5.1
Fuzzy          qtconsole=4.5            4.5.0, 4.5.1, ..., etc.
>=, >, <, <=  "qtconsole>=4.5"          4.5.0 or higher
               qtconsole"<4.6"          less than 4.6.0

OR            "qtconsole=4.5.1|4.5.2"   4.5.1, 4.5.2
AND           "qtconsole>=4.3.1,<4.6"   4.3.1 or higher but less than 4.6.0

Potion of the above information credit to Conda Cheat Sheet

Tested on conda 4.7.12

Best way to format if statement with multiple conditions

In Perl you could do this:

{
  ( VeryLongCondition_1 ) or last;
  ( VeryLongCondition_2 ) or last;
  ( VeryLongCondition_3 ) or last;
  ( VeryLongCondition_4 ) or last;
  ( VeryLongCondition_5 ) or last;
  ( VeryLongCondition_6 ) or last;

  # Guarded code goes here
}

If any of the conditions fail it will just continue on, after the block. If you are defining any variables that you want to keep around after the block, you will need to define them before the block.

Getting String value from enum in Java

if status is of type Status enum, status.name() will give you its defined name.

What's the environment variable for the path to the desktop?

Quite old topic. But I want to give my 2 cents...

I've slightly modified tomasz86 solution, to look in the old style "Shell Folders" instead of "User Shell Folders", so i don't need to expand the envvar %userprofile%

Also there is no dependency from powershell/vbscript/etc....

for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"`) do if %%A==REG_SZ  set desktopdir=%%B
echo %desktopdir%

Hope it helps.

adding directory to sys.path /PYTHONPATH

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

How do I create a ListView with rounded corners in Android?

The other answers are very useful, thanks to the authors!

But I could not see how to customise the rectangle when highlighting an item upon selection rather than disabling the highlighting @alvins @bharat dojeha.

The following works for me to create a rounded list view item container with no outline and a lighter grey when selected of the same shape:

Your xml needs to contain a selector such as e.g. ( in res/drawable/customshape.xml):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <stroke android:width="8dp" android:color="@android:color/transparent" />
        <padding android:left="14dp" android:top="14dp"
                android:right="14dp" android:bottom="14dp" />
        <corners android:radius="10dp" />
        <gradient 
             android:startColor="@android:color/background_light"
             android:endColor="@android:color/transparent" 
             android:angle="225"/> 
    </shape>
</item>
<item android:state_pressed="false">
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <stroke android:width="8dp" android:color="@android:color/transparent" />
        <padding android:left="14dp" android:top="14dp"
                android:right="14dp" android:bottom="14dp" />
        <corners android:radius="10dp" />
        <gradient 
             android:startColor="@android:color/darker_gray"
             android:endColor="@android:color/transparent" 
             android:angle="225"/> 
    </shape>        
</item>

Then you need to implement a list adapter and override the getView method to set the custom selector as background

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //snip
        convertView.setBackgroundResource(R.drawable.customshape);
        //snip
    }

and need to also 'hide' the default selector rectangle e.g in onCreate (I also hide my thin grey divider line between the items):

listView.setSelector(android.R.color.transparent);
listview.setDivider(null);

This approach solves a general solution for drawables, not just ListViewItem with various selection states.

PostgreSQL Crosstab Query

Sorry this isn't complete because I can't test it here, but it may get you off in the right direction. I'm translating from something I use that makes a similar query:

select mt.section, mt1.count as Active, mt2.count as Inactive
from mytable mt
left join (select section, count from mytable where status='Active')mt1
on mt.section = mt1.section
left join (select section, count from mytable where status='Inactive')mt2
on mt.section = mt2.section
group by mt.section,
         mt1.count,
         mt2.count
order by mt.section asc;

The code I'm working from is:

select m.typeID, m1.highBid, m2.lowAsk, m1.highBid - m2.lowAsk as diff, 100*(m1.highBid - m2.lowAsk)/m2.lowAsk as diffPercent
from mktTrades m
   left join (select typeID,MAX(price) as highBid from mktTrades where bid=1 group by typeID)m1
   on m.typeID = m1.typeID
   left join (select typeID,MIN(price) as lowAsk  from mktTrades where bid=0 group by typeID)m2
   on m1.typeID = m2.typeID
group by m.typeID, 
         m1.highBid, 
         m2.lowAsk
order by diffPercent desc;

which will return a typeID, the highest price bid and the lowest price asked and the difference between the two (a positive difference would mean something could be bought for less than it can be sold).

How to use OpenCV SimpleBlobDetector

Note: all the examples here are using the OpenCV 2.X API.

In OpenCV 3.X, you need to use:

Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params);

See also: the transition guide: http://docs.opencv.org/master/db/dfa/tutorial_transition_guide.html#tutorial_transition_hints_headers

Bootstrap - Removing padding or margin when screen size is smaller

To solve problems like this I'm using CSS - fastest & simplest way I think... Just modify it by your needs...

@media only screen and (max-width: 480px) {
    #your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 480px) and (max-width: 768px) {
    #your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
    #your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 959px) {
    #your_id {width:000px;height:000px;}
}

How do I convert two lists into a dictionary?

Like this:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}

Voila :-) The pairwise dict constructor and zip function are awesomely useful.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

How do I extract data from JSON with PHP?

You can use json_decode() to convert a json string to a PHP object/array.

Eg.

Input:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

Output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Few Points to remember:

  • json_decode requires the string to be a valid json else it will return NULL.
  • In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
  • Make sure you pass in utf8 content, or json_decode may error out and just return a NULL value.

How to subtract date/time in JavaScript?

Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:

subtractDates: function(date1, date2) {
    return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
    return moment().subtract(dateSince).milliseconds();
},

'innerText' works in IE, but not in Firefox

As in 2016 from Firefox v45, innerText works on firefox, take a look at its support: http://caniuse.com/#search=innerText

If you want it to work on previous versions of Firefox, you can use textContent, which has better support on Firefox but worse on older IE versions: http://caniuse.com/#search=textContent

Android: Background Image Size (in Pixel) which Support All Devices

The following are the best dimensions for the app to run in all devices. For understanding multiple supporting screens you have to read http://developer.android.com/guide/practices/screens_support.html

xxxhdpi: 1280x1920 px
xxhdpi: 960x1600 px
xhdpi: 640x960 px
hdpi: 480x800 px
mdpi: 320x480 px
ldpi: 240x320 px

JavaScript closures vs. anonymous functions

According to the closure definition:

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

You are using closure if you define a function which use a variable which is defined outside of the function. (we call the variable a free variable).
They all use closure(even in the 1st example).

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Twig ternary operator, Shorthand if-then-else

You can use shorthand syntax as of Twig 1.12.0

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

Delete files or folder recursively on Windows CMD

You could also do:

del /s /p *.{your extension here}

The /p will prompt you for each found file, if you're nervous about deleting something you shouldn't.

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

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

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

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

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

div[class^="something"] { }

which would work on something like this:-

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

and 'ends with...'

div[class$="something"] { }

which would work on

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

Good references

Find the IP address of the client in an SSH session

One thumb up for @Nikhil Katre's answer :

Simplest command to get the last 10 users logged in to the machine is last|head.

To get all the users simply use last command

The one using who or pinky did what is basically asked. But But But they don't give historical sessions info.

Which might also be interesting if you want to know someone who has just logged in and logged out already when you start this checking.

if it is a multiuser system. I recommand add the user account you are looking for:

last | grep $USER | head

EDIT:

In my case, both $SSH_CLIENT and $SSH_CONNECTION do not exist.

How to have a drop down <select> field in a rails form?

<%= f.select :email_provider, ["gmail","yahoo","msn"]%>

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

Displaying the Indian currency symbol on a website

You can do it with Intl.NumberFormat native API.

_x000D_
_x000D_
var number = 123456.78;_x000D_
_x000D_
// India uses thousands/lakh/crore separators_x000D_
console.log(new Intl.NumberFormat('en-IN', {_x000D_
  style: 'currency',_x000D_
  currency: 'INR'_x000D_
}).format(number));
_x000D_
_x000D_
_x000D_

SQL Server Pivot Table with multiple column aggregates

I would do this slightly different by applying both the UNPIVOT and the PIVOT functions to get the final result. The unpivot takes the values from both the totalcount and totalamount columns and places them into one column with multiple rows. You can then pivot on those results.:

select chardate,
  Australia_totalcount as [Australia # of Transactions], 
  Australia_totalamount as [Australia Total $ Amount],
  Austria_totalcount as [Austria # of Transactions], 
  Austria_totalamount as [Austria Total $ Amount]
from
(
  select 
    numericmonth, 
    chardate,
    country +'_'+col col, 
    value
  from
  (
    select numericmonth, 
      country, 
      chardate,
      cast(totalcount as numeric(10, 2)) totalcount,
      cast(totalamount as numeric(10, 2)) totalamount
    from mytransactions
  ) src
  unpivot
  (
    value
    for col in (totalcount, totalamount)
  ) unpiv
) s
pivot
(
  sum(value)
  for col in (Australia_totalcount, Australia_totalamount,
              Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth

See SQL Fiddle with Demo.

If you have an unknown number of country names, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @colsName AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col) 
                      from mytransactions
                      cross apply 
                      (
                        select 'TotalCount' col
                        union all
                        select 'TotalAmount'
                      ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsName 
    = STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col) 
               +' as ['
               + country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
             from mytransactions
             cross apply 
             (
                select 'TotalCount' col
                union all
                select 'TotalAmount'
             ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'SELECT chardate, ' + @colsName + ' 
     from 
     (
      select 
        numericmonth, 
        chardate,
        country +''_''+col col, 
        value
      from
      (
        select numericmonth, 
          country, 
          chardate,
          cast(totalcount as numeric(10, 2)) totalcount,
          cast(totalamount as numeric(10, 2)) totalamount
        from mytransactions
      ) src
      unpivot
      (
        value
        for col in (totalcount, totalamount)
      ) unpiv
     ) s
     pivot 
     (
       sum(value)
       for col in (' + @cols + ')
     ) p 
     order by numericmonth'

execute(@query)

See SQL Fiddle with Demo

Both give the result:

|             CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12               |                          36 |                   699.96 |                        11 |                 257.82 |
| Aug-12               |                          44 |                  1368.71 |                         5 |                 126.55 |
| Sep-12               |                          52 |                  1161.33 |                         7 |                  92.11 |
| Oct-12               |                          50 |                  1099.84 |                        12 |                 103.56 |
| Nov-12               |                          38 |                  1078.94 |                        21 |                 377.68 |
| Dec-12               |                          63 |                  1668.23 |                         3 |                  14.35 |

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

Equivalent of "continue" in Ruby

Writing Ian Purton's answer in a slightly more idiomatic way:

(1..5).each do |x|
  next if x < 2
  puts x
end

Prints:

  2
  3
  4
  5

How to check if a file contains a specific string using Bash

##To check for a particular  string in a file

cd PATH_TO_YOUR_DIRECTORY #Changing directory to your working directory
File=YOUR_FILENAME  
if grep -q STRING_YOU_ARE_CHECKING_FOR "$File"; ##note the space after the string you are searching for
then
echo "Hooray!!It's available"
else
echo "Oops!!Not available"
fi

Bash script prints "Command Not Found" on empty lines

Add the current directory ( . ) to PATH to be able to execute a script, just by typing in its name, that resides in the current directory:

PATH=.:$PATH

OSError: [WinError 193] %1 is not a valid Win32 application

For anyone experiencing this on windows after an update

What happened was that Windows Defender made some changes. Possibly cause running data extraction scripts, but python.exe got reduced to 0kb for that project. Copying the python.exe from another project and replacing it solved for now.

Find object by its property in array of objects with AngularJS way

How about plain JavaScript? More about Array.prototype.filter().

_x000D_
_x000D_
var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]_x000D_
_x000D_
var item73 = myArray.filter(function(item) {_x000D_
  return item.id === '73';_x000D_
})[0];_x000D_
_x000D_
// even nicer with ES6 arrow functions:_x000D_
// var item73 = myArray.filter(i => i.id === '73')[0];_x000D_
_x000D_
console.log(item73); // {"id": "73", "name": "john"}
_x000D_
_x000D_
_x000D_

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

Python: read all text file lines in loop

There's no need to check for EOF in python, simply do:

with open('t.ini') as f:
   for line in f:
       # For Python3, use print(line)
       print line
       if 'str' in line:
          break

Why the with statement:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

Why would one mark local variables and method parameters as "final" in Java?

You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.

Creating a class object in c++

In the first case you are creating the object on the heap using new. In the second case you are creating the object on the stack, so it will be disposed of when going out of scope. In C++ you'll need to delete objects on the heapexplicitly using delete when you don't Need them anymore.

To call a static method from a class, do

Singleton* singleton = Singleton::get_sample();

in your main-function or wherever.

Grid of responsive squares

The accepted answer is great, however this can be done with flexbox.

Here's a grid system written with BEM syntax that allows for 1-10 columns to be displayed per row.

If there the last row is incomplete (for example you choose to show 5 cells per row and there are 7 items), the trailing items will be centered horizontally. To control the horizontal alignment of the trailing items, simply change the justify-content property under the .square-grid class.

.square-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.square-grid__cell {
  background-color: rgba(0, 0, 0, 0.03);
  box-shadow: 0 0 0 1px black;
  overflow: hidden;
  position: relative;
}

.square-grid__content {
  left: 0;
  position: absolute;
  top: 0;
}

.square-grid__cell:after {
  content: '';
  display: block;
  padding-bottom: 100%;
}

// Sizes – Number of cells per row

.square-grid__cell--10 {
  flex-basis: 10%;
}

.square-grid__cell--9 {
  flex-basis: 11.1111111%;
}

.square-grid__cell--8 {
  flex-basis: 12.5%;
}

.square-grid__cell--7 {
  flex-basis: 14.2857143%;
}

.square-grid__cell--6 {
  flex-basis: 16.6666667%;
}

.square-grid__cell--5 {
  flex-basis: 20%;
}

.square-grid__cell--4 {
  flex-basis: 25%;
}

.square-grid__cell--3 {
  flex-basis: 33.333%;
}

.square-grid__cell--2 {
  flex-basis: 50%;
}

.square-grid__cell--1 {
  flex-basis: 100%;
}

_x000D_
_x000D_
.square-grid {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.square-grid__cell {_x000D_
  background-color: rgba(0, 0, 0, 0.03);_x000D_
  box-shadow: 0 0 0 1px black;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.square-grid__content {_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
.square-grid__cell:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  padding-bottom: 100%;_x000D_
}_x000D_
_x000D_
// Sizes – Number of cells per row_x000D_
_x000D_
.square-grid__cell--10 {_x000D_
  flex-basis: 10%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--9 {_x000D_
  flex-basis: 11.1111111%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--8 {_x000D_
  flex-basis: 12.5%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--7 {_x000D_
  flex-basis: 14.2857143%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--6 {_x000D_
  flex-basis: 16.6666667%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--5 {_x000D_
  flex-basis: 20%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--4 {_x000D_
  flex-basis: 25%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--3 {_x000D_
  flex-basis: 33.333%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--2 {_x000D_
  flex-basis: 50%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--1 {_x000D_
  flex-basis: 100%;_x000D_
}
_x000D_
<div class='square-grid'>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: https://jsfiddle.net/patrickberkeley/noLm1r45/3/

This is tested in FF and Chrome.

How can I create a Java method that accepts a variable number of arguments?

This is just an extension to above provided answers.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

Clearly explained here and rules to follow to use Variable Argument.

How to check whether java is installed on the computer

Type in the command window

java -version

If it gives an output everything should be fine. If you want to develop software you might want to set the PATH.

@Autowired - No qualifying bean of type found for dependency

This may help you:

I have the same exception in my project. After searching while I found that I am missing the @Service annotation to the class where I am implementing the interface which I want to @Autowired.

In your code you can add the @Service annotation to MailManager class.

@Transactional
@Service
public class MailManager extends AbstractManager implements IMailManager {

When to use an interface instead of an abstract class and vice versa?

Use an abstract class if you want to provide some basic implementations.

Best way to copy a database (SQL Server 2008)

The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.

If you cannot detach the production db you should use backup and restore.

You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.

You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.

This will lists the orphaned users:

EXEC sp_change_users_login 'Report'

If you already have a login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user'

If you want to create a new login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Which Ruby version am I really running?

The ruby version 1.8.7 seems to be your system ruby.

Normally you can choose the ruby version you'd like, if you are using rvm with following. Simple change into your directory in a new terminal and type in:

rvm use 2.0.0

You can find more details about rvm here: http://rvm.io Open the website and scroll down, you will see a few helpful links. "Setting up default rubies" for example could help you.

Update: To set the ruby as default:

rvm use 2.0.0 --default

What is the difference between MVC and MVVM?

Simple Difference: (Inspired by Yaakov's Coursera AngularJS course)

enter image description here

MVC (Model View Controller)

  1. Models: Models contain data information. Does not call or use Controller and View. Contains the business logic and ways to represent data. Some of this data, in some form, may be displayed in the view. It can also contain logic to retrieve the data from some source.
  2. Controller: Acts as the connection between view and model. View calls Controller and Controller calls the model. It basically informs the model and/or the view to change as appropriate.
  3. View: Deals with UI part. Interacts with the user.

MVVM (Model View View Model)

ViewModel:

  1. It is the representation of the state of the view.
  2. It holds the data that’s displayed in the view.
  3. Responds to view events, aka presentation logic.
  4. Calls other functionalities for business logic processing.
  5. Never directly asks the view to display anything.

BeanFactory vs ApplicationContext

ApplicationContext: It loads spring beans configured in spring configuration file,and manages the life cycle of the spring bean as and WHEN CONTAINER STARTS.It won't wait until getBean("springbeanref") is called.

BeanFactory It loads spring beans configured in spring configuration file,manages the life cycle of the spring bean when we call the getBean("springbeanref").So when we call the getBean("springbeanref") at the time of spring bean life cycle starts.

How to get last inserted id?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DBDemo2
{
    public partial class Form1 : Form
    {
        string connectionString = "Database=company;Uid=sa;Pwd=mypassword";
        System.Data.SqlClient.SqlConnection connection;
        System.Data.SqlClient.SqlCommand command;

        SqlParameter idparam = new SqlParameter("@eid", SqlDbType.Int, 0);
        SqlParameter nameparam = new SqlParameter("@name", SqlDbType.NChar, 20);
        SqlParameter addrparam = new SqlParameter("@addr", SqlDbType.NChar, 10);

        public Form1()
        {
            InitializeComponent();

            connection = new System.Data.SqlClient.SqlConnection(connectionString);
            connection.Open();
            command = new System.Data.SqlClient.SqlCommand(null, connection);
            command.CommandText = "insert into employee(ename, city) values(@name, @addr);select SCOPE_IDENTITY();";

            command.Parameters.Add(nameparam);
            command.Parameters.Add(addrparam);
            command.Prepare();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {


            try
            {
                int id = Int32.Parse(textBoxID.Text);
                String name = textBoxName.Text;
                String address = textBoxAddress.Text;

                command.Parameters[0].Value = name;
                command.Parameters[1].Value = address;

                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    int nid = Convert.ToInt32(reader[0]);
                    MessageBox.Show("ID : " + nid);
                }
                /*int af = command.ExecuteNonQuery();
                MessageBox.Show(command.Parameters["ID"].Value.ToString());
                */
            }
            catch (NullReferenceException ne)
            {
                MessageBox.Show("Error is : " + ne.StackTrace);
            }
            catch (Exception ee)
            {
                MessageBox.Show("Error is : " + ee.StackTrace);
            }
        }

        private void buttonSave_Leave(object sender, EventArgs e)
        {

        }

        private void Form1_Leave(object sender, EventArgs e)
        {
            connection.Close();
        }
    }
}

Folder is locked and I can't unlock it

To unlock a blocked document: 1. Right click -> Lock 2. Check the "Steal the locks" check box 2. Release the lock

How to use the PRINT statement to track execution as stored procedure is running?

SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO to indicate the end of a batch and to retrieve the results:

PRINT '1'
GO

WAITFOR DELAY '00:00:05'

PRINT '2'
GO

WAITFOR DELAY '00:00:05'

PRINT '3'
GO

In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT, which gbn has provided as an answer as I type this.

Entity Framework 6 Code first Default value

In EF core released 27th June 2016 you can use fluent API for setting default value. Go to ApplicationDbContext class, find/create the method name OnModelCreating and add the following fluent API.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<YourTableName>()
        .Property(b => b.Active)
        .HasDefaultValue(true);
}

What's the best way to determine which version of Oracle client I'm running?

You can get the version of the oracle client by running this command sqlplus /nolog on cmd. Another alternative will be to browse to the path C:\Program Files\Oracle\Inventory and open the "Inventory.xml" file which will give you the version as per below:

<?xml version="1.0" standalone="yes" ?>
<!-- Copyright (c) 1999, 2019, Oracle and/or its affiliates.
All rights reserved. -->
<!-- Do not modify the contents of this file by hand. -->
<INVENTORY>
<VERSION_INFO>
   <SAVED_WITH>12.2.0.1.4</SAVED_WITH>
   <MINIMUM_VER>2.1.0.6.0</MINIMUM_VER>
</VERSION_INFO>

How to read a text file into a list or an array with Python

So you want to create a list of lists... We need to start with an empty list

list_of_lists = []

next, we read the file content, line by line

with open('data') as f:
    for line in f:
        inner_list = [elt.strip() for elt in line.split(',')]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int(elt.strip()) for elt in line.split(',')]
        list_of_lists.append(inner_list)

A common use case is that of columnar data, but our units of storage are the rows of the file, that we have read one by one, so you may want to transpose your list of lists. This can be done with the following idiom

by_cols = zip(*list_of_lists)

Another common use is to give a name to each column

col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
by_names = {}
for i, col_name in enumerate(col_names):
    by_names[col_name] = by_cols[i]

so that you can operate on homogeneous data items

 mean_apple_prices = [money/fruits for money, fruits in
                     zip(by_names['apples revenue'], by_names['apples_sold'])]

Most of what I've written can be speeded up using the csv module, from the standard library. Another third party module is pandas, that lets you automate most aspects of a typical data analysis (but has a number of dependencies).


Update While in Python 2 zip(*list_of_lists) returns a different (transposed) list of lists, in Python 3 the situation has changed and zip(*list_of_lists) returns a zip object that is not subscriptable.

If you need indexed access you can use

by_cols = list(zip(*list_of_lists))

that gives you a list of lists in both versions of Python.

On the other hand, if you don't need indexed access and what you want is just to build a dictionary indexed by column names, a zip object is just fine...

file = open('some_data.csv')
names = get_names(next(file))
columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
d = {}
for name, column in zip(names, columns): d[name] = column

EXCEL VBA Check if entry is empty or not 'space'

Most terse version I can think of

Len(Trim(TextBox1.Value)) = 0

If you need to do this multiple times, wrap it in a function

Public Function HasContent(text_box as Object) as Boolean
    HasContent = (Len(Trim(text_box.Value)) > 0)
End Function

Usage

If HasContent(TextBox1) Then
    ' ...

Vue 'export default' vs 'new Vue'

export default is used to create local registration for Vue component.

Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Search in all files in a project in Sublime Text 3

You can search a directory using Find ? Find in files. This also includes all opened tabs.

The keyboard shortcut is Ctrl?+F on non-Mac (regular) keyboards, and ??+F on a Mac.

You'll be presented with three boxes: Find, Where and Replace. It's a regular Find/Find-replace search where Where specifies a file or directory to search. I for example often use a file name or . for searching the current directory. There are also a few special constructs that can be used within the Where field:

<project>,<current file>,<open files>,<open folders>,-*.doc,*.txt

Note that these are not placeholders, you type these verbatim. Most of them are self-explanatory (e.g. -*.doc excludes files with a .doc extension).

Pressing the ... to the right will present you with all available options.

After searching you'll be presented with a Find results page with all of your matching results. To jump to specific lines and files from it you simply double-click on a line.

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

What do I do when my program crashes with exception 0xc0000005 at address 0?

Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).

So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

Removing duplicate rows in Notepad++

Whether the file is sorted or not, you can use below regex to remove duplicates in anywhere occurred in your file.

Find what: ^([^\r]*[^\n])(.*?)\r?\n\1$
Replace with: \1\2
Search Mode:

  • "Regular expression"
  • Check the ". matches newline" option

do "Replace All" as many time as possible until you see "0 occurrences were replaced"

SQL Server: Difference between PARTITION BY and GROUP BY

-- BELOW IS A SAMPLE WHICH OUTLINES THE SIMPLE DIFFERENCES
-- READ IT AND THEN EXECUTE IT
-- THERE ARE THREE ROWS OF EACH COLOR INSERTED INTO THE TABLE
-- CREATE A database called testDB


-- use testDB
USE [TestDB]
GO


-- create Paints table
CREATE TABLE [dbo].[Paints](
    [Color] [varchar](50) NULL,
    [glossLevel] [varchar](50) NULL
) ON [PRIMARY]

GO


-- Populate Table
insert into paints (color, glossLevel)
select 'red', 'eggshell'
union
select 'red', 'glossy'
union
select 'red', 'flat'
union
select 'blue', 'eggshell'
union
select 'blue', 'glossy'
union
select 'blue', 'flat'
union
select 'orange', 'glossy'
union
select 'orange', 'flat'
union
select 'orange', 'eggshell'
union
select 'green', 'eggshell'
union
select 'green', 'glossy'
union
select 'green', 'flat'
union
select 'black', 'eggshell'
union
select 'black', 'glossy'
union
select 'black', 'flat'
union
select 'purple', 'eggshell'
union
select 'purple', 'glossy'
union
select 'purple', 'flat'
union
select 'salmon', 'eggshell'
union
select 'salmon', 'glossy'
union
select 'salmon', 'flat'


/*   COMPARE 'GROUP BY' color to 'OVER (PARTITION BY Color)'  */

-- GROUP BY Color 
-- row quantity defined by group by
-- aggregate (count(*)) defined by group by
select count(*) from paints
group by color

-- OVER (PARTITION BY... Color 
-- row quantity defined by main query
-- aggregate defined by OVER-PARTITION BY
select color
, glossLevel
, count(*) OVER (Partition by color)
from paints

/* COMPARE 'GROUP BY' color, glossLevel to 'OVER (PARTITION BY Color, GlossLevel)'  */

-- GROUP BY Color, GlossLevel
-- row quantity defined by GROUP BY
-- aggregate (count(*)) defined by GROUP BY
select count(*) from paints
group by color, glossLevel



-- Partition by Color, GlossLevel
-- row quantity defined by main query
-- aggregate (count(*)) defined by OVER-PARTITION BY
select color
, glossLevel
, count(*) OVER (Partition by color, glossLevel)
from paints

How to get full REST request body using Jersey?

Try this using this single code:

import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/serviceX")
public class MyClassRESTService {

    @POST
    @Path("/doSomething")   
    public void someMethod(String x) {

        System.out.println(x);
                // String x contains the body, you can process
                // it, parse it using JAXB and so on ...

    }
}

The url for try rest services ends .... /serviceX/doSomething

How to find sum of several integers input by user using do/while, While statement or For statement

A simple program shows how to use for loop to find sum of serveral integers.

#include <iostream>    
using namespace std;

int main ()
{
    int sum = 0;

    int endnum = 2;

    for(int i = 0; i<=endnum; i++){
        sum += i;
    }
    cout<<sum;
}

How to use UIVisualEffectView to Blur Image?

If anyone would like the answer in Swift :

var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.

var blurView = UIVisualEffectView(effect: blurEffect)

blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!

Update :

As of now, it's available under the IB so you don't have to code anything for it :)

Jupyter Notebook not saving: '_xsrf' argument missing from post

The easiest way I found is this:

https://github.com/nteract/hydrogen/issues/922#issuecomment-405456346

Just open another (non-running, existing) notebook on the same kernel, and the issue is magically gone; you can again save the notebooks that were previously showing the _xsrf error.

If you have already closed the Jupyter home page, you can find a link to it on the terminal from which Jupyter was started.

Android studio takes too much memory

Try switching your JVM to eclipse openj9. Its gonna use way less memory. I swapped it and its using 600Mb constantly.

Why is there no SortedList in Java?

JavaFX SortedList

Though it took a while, Java 8 does have a sorted List. http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html

As you can see in the javadocs, it is part of the JavaFX collections, intended to provide a sorted view on an ObservableList.

Update: Note that with Java 11, the JavaFX toolkit has moved outside the JDK and is now a separate library. JavaFX 11 is available as a downloadable SDK or from MavenCentral. See https://openjfx.io

java: How can I do dynamic casting of a variable from one type to another?

For what it is worth, most scripting languages (like Perl) and non-static compile-time languages (like Pick) support automatic run-time dynamic String to (relatively arbitrary) object conversions. This CAN be accomplished in Java as well without losing type-safety and the good stuff statically-typed languages provide WITHOUT the nasty side-effects of some of the other languages that do evil things with dynamic casting. A Perl example that does some questionable math:

print ++($foo = '99');  # prints '100'
print ++($foo = 'a0');  # prints 'a1'

In Java, this is better accomplished (IMHO) by using a method I call "cross-casting". With cross-casting, reflection is used in a lazy-loaded cache of constructors and methods that are dynamically discovered via the following static method:

Object fromString (String value, Class targetClass)

Unfortunately, no built-in Java methods such as Class.cast() will do this for String to BigDecimal or String to Integer or any other conversion where there is no supporting class hierarchy. For my part, the point is to provide a fully dynamic way to achieve this - for which I don't think the prior reference is the right approach - having to code every conversion. Simply put, the implementation is just to cast-from-string if it is legal/possible.

So the solution is simple reflection looking for public Members of either:

STRING_CLASS_ARRAY = (new Class[] {String.class});

a) Member member = targetClass.getMethod(method.getName(),STRING_CLASS_ARRAY); b) Member member = targetClass.getConstructor(STRING_CLASS_ARRAY);

You will find that all of the primitives (Integer, Long, etc) and all of the basics (BigInteger, BigDecimal, etc) and even java.regex.Pattern are all covered via this approach. I have used this with significant success on production projects where there are a huge amount of arbitrary String value inputs where some more strict checking was needed. In this approach, if there is no method or when the method is invoked an exception is thrown (because it is an illegal value such as a non-numeric input to a BigDecimal or illegal RegEx for a Pattern), that provides the checking specific to the target class inherent logic.

There are some downsides to this:

1) You need to understand reflection well (this is a little complicated and not for novices). 2) Some of the Java classes and indeed 3rd-party libraries are (surprise) not coded properly. That is, there are methods that take a single string argument as input and return an instance of the target class but it isn't what you think... Consider the Integer class:

static Integer getInteger(String nm)
      Determines the integer value of the system property with the specified name.

The above method really has nothing to do with Integers as objects wrapping primitives ints. Reflection will find this as a possible candidate for creating an Integer from a String incorrectly versus the decode, valueof and constructor Members - which are all suitable for most arbitrary String conversions where you really don't have control over your input data but just want to know if it is possible an Integer.

To remedy the above, looking for methods that throw Exceptions is a good start because invalid input values that create instances of such objects should throw an Exception. Unfortunately, implementations vary as to whether the Exceptions are declared as checked or not. Integer.valueOf(String) throws a checked NumberFormatException for example, but Pattern.compile() exceptions are not found during reflection lookups. Again, not a failing of this dynamic "cross-casting" approach I think so much as a very non-standard implementation for exception declarations in object creation methods.

If anyone would like more details on how the above was implemented, let me know but I think this solution is much more flexible/extensible and with less code without losing the good parts of type-safety. Of course it is always best to "know thy data" but as many of us find, we are sometimes only recipients of unmanaged content and have to do the best we can to use it properly.

Cheers.

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

Get element type with jQuery

also you can use:

$("#elementId").get(0).tagName

Identifier not found error on function call

You have to define void swapCase before the main definition.

Write HTML to string

I wrote these classes which served me well. It's simple yet pragmatic.

public class HtmlAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }

    public HtmlAttribute(string name) : this(name, null) { }

    public HtmlAttribute(
        string name,
        string @value)
    {
        this.Name = name;
        this.Value = @value;
    }

    public override string ToString()
    {
        if (string.IsNullOrEmpty(this.Value))
            return this.Name;

        if (this.Value.Contains('"'))
            return string.Format("{0}='{1}'", this.Name, this.Value);

        return string.Format("{0}=\"{1}\"", this.Name, this.Value);
    }
}

public class HtmlElement
{
    protected List<HtmlAttribute> Attributes { get; set; }
    protected List<object> Childs { get; set; }
    public string Name { get; set; }
    protected HtmlElement Parent { get; set; }

    public HtmlElement() : this(null) { }

    public HtmlElement(string name, params object[] childs)
    {
        this.Name = name;
        this.Attributes = new List<HtmlAttribute>();
        this.Childs = new List<object>();

        if (childs != null && childs.Length > 0)
        {
            foreach (var c in childs)
            {
                Add(c);
            }
        }
    }

    public void Add(object o)
    {
        var a = o as HtmlAttribute;
        if (a != null)
            this.Attributes.Add(a);
        else
        {
            var h = o as HtmlElement;
            if (h != null && !string.IsNullOrEmpty(this.Name))
            {
                h.Parent = this;
                this.Childs.Add(h);
            }
            else
                this.Childs.Add(o);
        }
    }

    public override string ToString()
    {
        var result = new StringBuilder();

        if (!string.IsNullOrEmpty(this.Name))
        {
            result.Append(string.Format("<{0}", this.Name));
            if (this.Attributes.Count > 0)
            {
                result.Append(" ");
                foreach (var attr in this.Attributes)
                {
                    result.Append(attr.ToString());
                    result.Append(" ");
                }

                result = new StringBuilder(result.ToString().TrimEnd(' '));
            }

            if (this.Childs.Count == 0)
            {
                result.Append(" />");
            }
            else
            {
                result.AppendLine(">");

                foreach (var c in this.Childs)
                {
                    var cParts = c.ToString().Split('\n');

                    foreach (var p in cParts)
                    {
                        result.AppendLine(string.Format("{0}", p));
                    }
                }

                result.Append(string.Format("</{0}>", this.Name));
            }
        }
        else
        {
            foreach (var c in this.Childs)
            {
                var cParts = c.ToString().Split('\n');

                foreach (var p in cParts)
                {
                    result.AppendLine(string.Format("{0}", p));
                }
            }
        }

        var head = GetHeading(this);

        var ps = result.ToString().Split('\n');
        return string.Join("\r\n", (from p in ps select head + p.TrimEnd('\r')).ToArray());
    }

    string GetHeading(HtmlElement h)
    {
        if (h.Parent != null)
            return "    ";
        else
            return string.Empty;
    }
}

How to programmatically tell if a Bluetooth device is connected?

I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:

BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothGatt.GATT);
int status = -1;

for (BluetoothDevice device : devices) {
  status = bm.getConnectionState(device, BLuetoothGatt.GATT);
  // compare status to:
  //   BluetoothProfile.STATE_CONNECTED
  //   BluetoothProfile.STATE_CONNECTING
  //   BluetoothProfile.STATE_DISCONNECTED
  //   BluetoothProfile.STATE_DISCONNECTING
}

Real-world examples of recursion

Parsing a tree of controls in Windows Forms or WebForms (.NET Windows Forms / ASP.NET).

What does the shrink-to-fit viewport meta attribute do?

As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.

After 9.2.x. IOS remove this tag check on its' browser.

You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html

Regex for Comma delimited list

i used this for a list of items that had to be alphanumeric without underscores at the front of each item.

^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$

How to generate .json file with PHP?

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

Then change the data :

$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
    if ($entry['activity_code'] == '1') {
        $data[$key]['activity_name'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);

copy

Turn off deprecated errors in PHP 5.3

You can do it in code by calling the following functions.

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

or

error_reporting(E_ALL ^ E_DEPRECATED);

getResourceAsStream() is always returning null

To my knowledge the file has to be right in the folder where the 'this' class resides, i.e. not in WEB-INF/classes but nested even deeper (unless you write in a default package):

net/domain/pkg1/MyClass.java  
net/domain/pkg1/abc.txt

Putting the file in to your java sources should work, compiler copies that file together with class files.

Find elements inside forms and iframe using Java and Selenium WebDriver

On Selenium >= 3.41 (C#) the rigth syntax is:

webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));

How to get an Array with jQuery, multiple <input> with the same name

Q:How to access name array text field

<input type="text" id="task" name="task[]" />

Answer - Using Input name array :

$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

This worked for me with phpmyadmin under Ubuntu 16.04:

I edited /etc/phpmyadmin/config.inc.php and changed the following 2 lines:

$cfg['Servers'][$i]['controluser'] = 'root'; 
$cfg['Servers'][$i]['controlpass'] = 'thepasswordgiventoroot'; 

Java 8 Distinct by property

I made a generic version:

private <T, R> Collector<T, ?, Stream<T>> distinctByKey(Function<T, R> keyExtractor) {
    return Collectors.collectingAndThen(
            toMap(
                    keyExtractor,
                    t -> t,
                    (t1, t2) -> t1
            ),
            (Map<R, T> map) -> map.values().stream()
    );
}

An exemple:

Stream.of(new Person("Jean"), 
          new Person("Jean"),
          new Person("Paul")
)
    .filter(...)
    .collect(distinctByKey(Person::getName)) // return a stream of Person with 2 elements, jean and Paul
    .map(...)
    .collect(toList())

Regular expression to return text between parenthesis

import re

fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

In my case, it was literally a bad USB cable. Apparently it was right on the edge - adb logcat would work, but about half the time I would get this error when trying to push an app to the device.

Changed to a different cable, and everything was fine. The old cable was also very slow at charging, so I should have suspected it sooner...

How to show code but hide output in RMarkdown?

As @ J_F answered in the comments, using {r echo = T, results = 'hide'}.

I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!

You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.

Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
                      results = "hide")
```

Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.

```{r analysis, results="markup"}
# code here
```

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.

java.lang.IllegalArgumentException: No enum constant

Also the problem was when we at Parcelize read moment write some short if.

My solution for this was

1.Create companion object with parsing method.

enum class CarsType {
    @Json(name = "SMALL")
    SMALL,
    @Json(name = "BIG")
    BIG;

    companion object {
        fun nullableValueOf(name: String?) = when (name) {
            null -> null
            else -> valueOf(name)
        }
    }
}

2. In Parcerable read place use it like this

data class CarData(
    val carId: String? = null,
    val carType: CarsType?,
    val data: String?
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        CarsType.nullableValueOf(parcel.readString()),
        parcel.readString())

sending mail from Batch file

PowerShell comes with a built in command for it. So running directly from a .bat file:

powershell -ExecutionPolicy ByPass -Command Send-MailMessage ^
    -SmtpServer server.address.name ^
    -To [email protected] ^
    -From [email protected] ^
    -Subject Testing ^
    -Body 123

NB -ExecutionPolicy ByPass is only needed if you haven't set up permissions for running PS from CMD

Also for those looking to call it from within powershell, drop everything before -Command [inclusive], and ` will be your escape character (not ^)

How to get UTC timestamp in Ruby?

time = Time.zone.now()

It will work as

irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC

Subversion ignoring "--password" and "--username" options

I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:

Host server.hostname
  User username

I found this blog post helpful: http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html

What does the "@" symbol do in SQL?

Its a parameter the you need to define. to prevent SQL Injection you should pass all your variables in as parameters.

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.

You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />
    </head>
    <body>
            <!-- your html content -->
            <script src="/script.js"></script>
    </body>
</html>



When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.

jQuery Keypress Arrow Keys

$(document).on( "keydown",  keyPressed);

function keyPressed (e){
    e = e || window.e;
    var newchar = e.which || e.keyCode;
    alert(newchar)
}

How to enable file upload on React's Material UI simple input?

The API provides component for this purpose.

<Button
  variant="contained"
  component="label"
>
  Upload File
  <input
    type="file"
    hidden
  />
</Button>

How do I check if a string contains another string in Swift?

Swift 4 way to check for substrings, including the necessary Foundation (or UIKit) framework import:

import Foundation // or UIKit

let str = "Oh Canada!"

str.contains("Can") // returns true

str.contains("can") // returns false

str.lowercased().contains("can") // case-insensitive, returns true

Unless Foundation (or UIKit) framework is imported, str.contains("Can") will give a compiler error.


This answer is regurgitating manojlds's answer, which is completely correct. I have no idea why so many answers go through so much trouble to recreate Foundation's String.contains(subString: String) method.

form confirm before submit

$('#myForm').submit(function() {
    var c = confirm("Click OK to continue?");
    return c; //you can just return c because it will be true or false
});

Use of Java's Collections.singletonList()?

Here's one view on the singleton methods:

I have found these various "singleton" methods to be useful for passing a single value to an API that requires a collection of that value. Of course, this works best when the code processing the passed-in value does not need to add to the collection.

Adding 'serial' to existing column in Postgres

Look at the following commands (especially the commented block).

DROP TABLE foo;
DROP TABLE bar;

CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);

INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;

-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later

SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result

INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');

SELECT * FROM foo;
SELECT * FROM bar;

Trying to add adb to PATH variable OSX

If anyone can't seem to get there .bash_profile file to take any new Paths AND you have other commands in that file (like alias commands) then try moving the PATH statements to the top of the file.

That is the only thing that worked for me. The reason it worked was because I had some typos in my alias commands and apparently this file throws an error and exits if it runs into a problem. So that is why my PATH statements weren't being run. Moving it to the top just let it run first.

What is the OAuth 2.0 Bearer Token exactly?

Please read the example in rfc6749 sec 7.1 first.

The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.

PoP means kind of multi-factor authentication to make access token more secure. ref

Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).

Maybe it's not the case, but I would say,

  • access token = payment methods
  • bearer token = cash
  • access token with PoP mechanism = credit card (signature or password will be verified, sometimes need to show your ID to match the name on the card)

BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

I came across this error on linux environment. If not using headless then you will need

from sys import platform
    if platform != 'win32':
        from pyvirtualdisplay import Display
        display = Display(visible=0, size=(800, 600))
        display.start()

Freeze screen in chrome debugger / DevTools panel for popover inspection?

I tried the other solutions here, they work but I'm lazy so this is my solution

  1. hover over the element to trigger expanded state
  2. ctrl+shift+c
  3. hover over element again
  4. right click
  5. navigate to the debugger

by right clicking it no longer registers mouse event since a context menu pops up, so you can move the mouse away safely

How do I POST JSON data with cURL?

I am using the below format to test with a web server.

use -F 'json data'

Let's assume this JSON dict format:

{
    'comment': {
        'who':'some_one',
        'desc' : 'get it'
    }
}

Full example

curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to crop an image in OpenCV using Python

i had this question and found another answer here: copy region of interest

If we consider (0,0) as top left corner of image called im with left-to-right as x direction and top-to-bottom as y direction. and we have (x1,y1) as the top-left vertex and (x2,y2) as the bottom-right vertex of a rectangle region within that image, then:

roi = im[y1:y2, x1:x2]

here is a comprehensive resource on numpy array indexing and slicing which can tell you more about things like cropping a part of an image. images would be stored as a numpy array in opencv2.

:)

How to make an empty div take space

Simply add a zero width space character inside a pseudo element

.class:after {
    content: '\200b';
}

What does the variable $this mean in PHP?

Generally, this keyword is used inside a class, generally with in the member functions to access non-static members of a class(variables or functions) for the current object.

  1. this keyword should be preceded with a $ symbol.
  2. In case of this operator, we use the -> symbol.
  3. Whereas, $this will refer the member variables and function for a particular instance.

Let's take an example to understand the usage of $this.

<?php
class Hero {
    // first name of hero
    private $name;
    
    // public function to set value for name (setter method)
    public function setName($name) {
        $this->name = $name;
    }
    
    // public function to get value of name (getter method)
    public function getName() {
        return $this->name;
    }
}

// creating class object
$stark = new Hero();

// calling the public function to set fname
$stark->setName("IRON MAN");

// getting the value of the name variable
echo "I Am " . $stark->getName();
?>

OUTPUT: I am IRON MAN

NOTE: A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.

How to get just numeric part of CSS property with jQuery?

parseInt($(this).css('marginBottom'), 10);

parseInt will automatically ignore the units.

For example:

var marginBottom = "10px";
marginBottom = parseInt(marginBottom, 10);
alert(marginBottom); // alerts: 10

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

If you still get too many authentication failures errors:

nano ~/.ssh/config

And paste:

Host bitbucket_james
    HostName bitbucket.org
    User james
    Port 22
    IdentitiesOnly=yes
    IdentityFile=~/.ssh/id_rsa_bitbucket_james

And most important - you should bitbucket_james alias instead of bitbucket.org when you set up your remote URL:

git remote set-url origin git@bitbucket_james:repo_owner_user/repo_name.git

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

How to stop a function

This will end the function, and you can even customize the "Error" message:

import sys

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        sys.exit("The player doesn't want to play again") #Right here 

How to uncheck checkbox using jQuery Uniform library

_x000D_
_x000D_
 $("#checkall").change(function () {_x000D_
            var checked = $(this).is(':checked');_x000D_
            if (checked) {_x000D_
                $(".custom-checkbox").each(function () {_x000D_
                    $(this).prop("checked", true).uniform();_x000D_
                });_x000D_
            } else {_x000D_
                $(".custom-checkbox").each(function () {_x000D_
                    $(this).prop("checked", false).uniform();_x000D_
                });_x000D_
            }_x000D_
        });_x000D_
_x000D_
        // Changing state of CheckAll custom-checkbox_x000D_
        $(".custom-checkbox").click(function () {_x000D_
            if ($(".custom-checkbox").length == $(".custom-checkbox:checked").length) {_x000D_
                $("#chk-all").prop("checked", true).uniform();_x000D_
            } else {_x000D_
                $("#chk-all").removeAttr("checked").uniform();_x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id='checkall' /> Select All<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="PHP"> PHP<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="AngularJS"> AngularJS<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="Python"> Python<br/>_x000D_
 <input type="checkbox" class='custom-checkbox' name="languages" value="Java"> Java<br/>
_x000D_
_x000D_
_x000D_

Import Excel Spreadsheet Data to an EXISTING sql table?

Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.

I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.

DisplayName attribute from Resources?

Update:

I know it's too late but I'd like to add this update:

I'm using the Conventional Model Metadata Provider which presented by Phil Haacked it's more powerful and easy to apply take look at it : ConventionalModelMetadataProvider


Old Answer

Here if you wanna support many types of resources:

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
    private readonly PropertyInfo nameProperty;

    public LocalizedDisplayNameAttribute(string displayNameKey, Type resourceType = null)
        : base(displayNameKey)
    {
        if (resourceType != null)
        {
            nameProperty = resourceType.GetProperty(base.DisplayName,
                                           BindingFlags.Static | BindingFlags.Public);
        }
    }

    public override string DisplayName
    {
        get
        {
            if (nameProperty == null)
            {
                return base.DisplayName;
            }
            return (string)nameProperty.GetValue(nameProperty.DeclaringType, null);
        }
    }
}

Then use it like this:

    [LocalizedDisplayName("Password", typeof(Res.Model.Shared.ModelProperties))]
    public string Password { get; set; }

For the full localization tutorial see this page.

How to set a Default Route (To an Area) in MVC

Adding the following to my Application_Start works for me, although I'm not sure if you have this setting in RC:

var engine = (WebFormViewEngine)ViewEngines.Engines.First();

// These additions allow me to route default requests for "/" to the home area
engine.ViewLocationFormats = new string[] { 
    "~/Views/{1}/{0}.aspx",
    "~/Views/{1}/{0}.ascx",
    "~/Areas/{1}/Views/{1}/{0}.aspx", // new
    "~/Areas/{1}/Views/{1}/{0}.ascx", // new
    "~/Areas/{1}/Views/{0}.aspx", // new
    "~/Areas/{1}/Views/{0}.ascx", // new
    "~/Views/{1}/{0}.ascx",
    "~/Views/Shared/{0}.aspx",
    "~/Views/Shared/{0}.ascx"
};

Merge two dataframes by index

This answer has been resolved for a while and all the available options are already out there. However in this answer I'll attempt to shed a bit more light on these options to help you understand when to use what.

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax


Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using named indexes)
  2. DataFrame.join (joins on index)
  3. pd.concat (joins on index)
PROS CONS
merge

• supports inner/left/right/full
• supports column-column, index-column, index-index joins

• can only join two frames at a time

join

• supports inner/left (default)/right/full
• can join multiple DataFrames at a time

• only supports index-index joins

concat

• specializes in joining multiple DataFrames at a time
• very fast (concatenation is linear time)

• only supports inner/full (default) joins
• only supports index-index joins


Index to index joins

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

Other types of joins (left, right, outer) follow similar syntax (and can be controlled using how=...).

Notable Alternatives

  1. DataFrame.join defaults to a left outer join on the index.

     left.join(right, how='inner',)
    

    If you happen to get ValueError: columns overlap but no suffix specified, you will need to specify lsuffix and rsuffix= arguments to resolve this. Since the column names are same, a differentiating suffix is required.

  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default.

     pd.concat([left, right], axis=1, sort=False)
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

left.merge(right, left_index=True, right_on='key')

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple levels/columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


This post is an abridged version of my work in Pandas Merging 101. Please follow this link for more examples and other topics on merging.

How to check for a Null value in VB.NET

The equivalent of null in VB is Nothing so your check wants to be:

If editTransactionRow.pay_id IsNot Nothing Then
    stTransactionPaymentID = editTransactionRow.pay_id
End If

Or possibly, if you are actually wanting to check for a SQL null value:

If editTransactionRow.pay_id <> DbNull.Value Then
    ...
End If

Java - Best way to print 2D array?

With Java 8 using Streams and ForEach:

    Arrays.stream(array).forEach((i) -> {
        Arrays.stream(i).forEach((j) -> System.out.print(j + " "));
        System.out.println();
    });

The first forEach acts as outer loop while the next as inner loop

Setting "checked" for a checkbox with jQuery

If you happen to be using Bootstrap (perhaps unawarely) ...

$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')

http://www.bootstraptoggle.com/

SQL Call Stored Procedure for each Row without using a cursor

If you don't what to use a cursor I think you'll have to do it externally (get the table, and then run for each statement and each time call the sp) it Is the same as using a cursor, but only outside SQL. Why won't you use a cursor ?

How do I automatically set the $DISPLAY variable for my current session?

Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.

PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
    export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"}  $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
    echo "DISPLAY set to $DISPLAY"
else
    echo "Could not set DISPLAY"
fi
unset PID

You should just be able to drop that in your .bashrc file.

TypeError: $(...).on is not a function

I tried the solution of Oskar (and many others) but for me it finaly only worked with:

jQuery(function($){
   // Your jQuery code here, using the $
});

See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

Portable way to get file size (in bytes) in shell?

I ended up writing my own program (really small) to display just the size. More information here: http://fwhacking.blogspot.com/2011/03/bfsize-print-file-size-in-bytes-and.html

The two most clean ways in my opinion with common Linux tools are:

$ stat -c %s /usr/bin/stat
50000

$ wc -c < /usr/bin/wc
36912

But I just don't want to be typing parameters or pipe the output just to get a file size, so I'm using my own bfsize.

HashMap get/put complexity

In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.

When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.

The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).

If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.

Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.

IE11 prevents ActiveX from running

We started finding some machines with IE 11 not playing video (via flash) after we set the emulation mode of our app (web browser control) to 110001. Adding the meta tag to our htm files worked for us.

How to handle invalid SSL certificates with Apache HttpClient?

The Apache HttpClient 4.5 way:

org.apache.http.ssl.SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
sslContextBuilder.loadTrustMaterial(new org.apache.http.conn.ssl.TrustSelfSignedStrategy());
SSLContext sslContext = sslContextBuilder.build();
org.apache.http.conn.ssl.SSLConnectionSocketFactory sslSocketFactory =
        new SSLConnectionSocketFactory(sslContext, new org.apache.http.conn.ssl.DefaultHostnameVerifier());

HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(sslSocketFactory);
httpClient = httpClientBuilder.build();

NOTE: org.apache.http.conn.ssl.SSLContextBuilder is deprecated and org.apache.http.ssl.SSLContextBuilder is the new one (notice conn missing from the latter's package name).

Failed to find 'ANDROID_HOME' environment variable

Came here from google looking for same issue and wasted 4 hours to figure out what could be wrong. And now I feel really stupid while posting this answer. In my case SDK, JDK, JRE, Ant and everything else was installed and working a day before.

But just one particular project was giving me this issue. This one was under "C:\Users\Name\Documents" location

Soon I realized that I was running cmd as normal user, as soon as I choose "Run as Administrator" everything started working.

Tip: Always consider project location carefully!

maxlength ignored for input type="number" in Chrome

I will make this quick and easy to understand!

Instead of maxlength for type='number' (maxlength is meant to define the maximum amount of letters for a string in a text type), use min='' and max='' .

Cheers

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Stop and Start a service via batch or cmd file?

Use the SC (service control) command, it gives you a lot more options than just start & stop.

  DESCRIPTION:
          SC is a command line program used for communicating with the
          NT Service Controller and services.
  USAGE:
      sc <server> [command] [service name]  ...

      The option <server> has the form "\\ServerName"
      Further help on commands can be obtained by typing: "sc [command]"
      Commands:
        query-----------Queries the status for a service, or
                        enumerates the status for types of services.
        queryex---------Queries the extended status for a service, or
                        enumerates the status for types of services.
        start-----------Starts a service.
        pause-----------Sends a PAUSE control request to a service.
        interrogate-----Sends an INTERROGATE control request to a service.
        continue--------Sends a CONTINUE control request to a service.
        stop------------Sends a STOP request to a service.
        config----------Changes the configuration of a service (persistant).
        description-----Changes the description of a service.
        failure---------Changes the actions taken by a service upon failure.
        qc--------------Queries the configuration information for a service.
        qdescription----Queries the description for a service.
        qfailure--------Queries the actions taken by a service upon failure.
        delete----------Deletes a service (from the registry).
        create----------Creates a service. (adds it to the registry).
        control---------Sends a control to a service.
        sdshow----------Displays a service's security descriptor.
        sdset-----------Sets a service's security descriptor.
        GetDisplayName--Gets the DisplayName for a service.
        GetKeyName------Gets the ServiceKeyName for a service.
        EnumDepend------Enumerates Service Dependencies.

      The following commands don't require a service name:
      sc <server> <command> <option>
        boot------------(ok | bad) Indicates whether the last boot should
                        be saved as the last-known-good boot configuration
        Lock------------Locks the Service Database
        QueryLock-------Queries the LockStatus for the SCManager Database
  EXAMPLE:
          sc start MyService

Dynamically create checkbox with JQuery from text input

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

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

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

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

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

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

How to do relative imports in Python?

"Guido views running scripts within a package as an anti-pattern" (rejected PEP-3122)

I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.

Count textarea characters

$("#textarea").keyup(function(){
  $("#count").text($(this).val().length);
});

The above will do what you want. If you want to do a count down then change it to this:

$("#textarea").keyup(function(){
  $("#count").text("Characters left: " + (500 - $(this).val().length));
});

Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks @Niet)

document.getElementById('textarea').onkeyup = function () {
  document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};

How to access a dictionary element in a Django template?

Similar to the answer by @russian_spy :

<ul>
{% for choice in choices.items %} 
  <li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>

This might be suitable for breaking down more complex dictionaries.

Find index of a value in an array

Try this...

var key = words.Where(x => x.IsKey == true);

Referencing Row Number in R

Perhaps with dataframes one of the most easy and practical solution is:

data = dplyr::mutate(data, rownum=row_number())

How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called ref to each child. There are now two ways to implement references: Using React.createRef() and callback refs.

Using React.createRef()

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref attribute.

class FormEditor extends React.Component {
  constructor(props) {
    super(props);
    this.FieldEditor1 = React.createRef();
  }
  render() {
    return <FieldEditor ref={this.FieldEditor1} />;
  }
}

In order to access this kind of ref, you'll need to use:

const currentFieldEditor1 = this.FieldEditor1.current;

This will return an instance of the mounted component so you can then use currentFieldEditor1.state to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />) then this.divRef.current will return the underlying DOM element instead of a component instance.

Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

<FieldEditor
    ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
    {...props}
/>

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

this.fieldEditor1

and then use this.fieldEditor1.state to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />) then this.divRef will return the underlying DOM element instead of a component instance.

Further Information

If you want to read more about React's ref property, check out this page from Facebook.

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state to "make things happen".

Hope this helps ^_^

Edit: Added React.createRef() method for creating refs. Removed ES5 code.

2D arrays in Python

I would suggest that you use a dictionary like so:

arr = {}

arr[1] = (1, 2, 4)
arr[18] = (3, 4, 5)

print(arr[1])
>>> (1, 2, 4)

If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", e.g. try-except.

How to logout and redirect to login page using Laravel 5.4?

if you are looking to do it via code on specific conditions, here is the solution worked for me. I have used in middleware to block certain users: these lines from below is the actual code to logout:

$auth = new LoginController();
$auth->logout($request);

Complete File:

namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Http\Controllers\Auth\LoginController;
class ExcludeCustomers{
    public function handle($request, Closure $next){
        $user = Auth::guard()->user();
        if( $user->role == 3 ) {
            $auth = new LoginController();
            $auth->logout($request);
            header("Location: https://google.com");
            die();
        } 
        return $next($request);
    }
}

Getting list of files in documents folder

This code prints out all the directories and files in my documents directory:

Some modification of your function:

func listFilesFromDocumentsFolder() -> [String]
{
    let dirs = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
    if dirs != [] {
        let dir = dirs[0]
        let fileList = try! FileManager.default.contentsOfDirectory(atPath: dir)
        return fileList
    }else{
        let fileList = [""]
        return fileList
    }
}

Which gets called by:

    let fileManager:FileManager = FileManager.default
    let fileList = listFilesFromDocumentsFolder()

    let count = fileList.count

    for i in 0..<count
    {
        if fileManager.fileExists(atPath: fileList[i]) != true
        {
            print("File is \(fileList[i])")
        }
    }

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

If JDK installed but still not working.

In Eclipse follow below steps:- Window --> Preference --> Installed JREs -->Change path of JRE to JDK(add).