Programs & Examples On #Zend tool

Draw a connecting line between two elements

js-graph.it supports this use case, as seen by its getting started guide, supporting dragging elements without connection overlaps. Doesn't seem like it supports editing/creating connections. Doesn't seem it is maintained anymore.

SQL Query - Using Order By in UNION

Browsing this comment section I came accross two different patterns answering the question. Sadly for SQL 2012, the second pattern doesn't work, so here's my "work around"


Order By on a Common Column

This is the easiest case you can encounter. Like many user pointed out, all you really need to do is add an Order By at the end of the query

SELECT a FROM table1
UNION
SELECT a FROM table2
ORDER BY field1

or

SELECT a FROM table1 ORDER BY field1
UNION
SELECT a FROM table2 ORDER BY field1

Order By on Different Columns

Here's where it actually gets tricky. Using SQL 2012, I tried the top post and it doesn't work.

SELECT * FROM 
(
  SELECT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1

UNION ALL

SELECT * FROM
( 
  SELECT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2

Following the recommandation in the comment I tried this

SELECT * FROM 
(
  SELECT TOP 100 PERCENT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1

UNION ALL

SELECT * FROM
( 
  SELECT TOP 100 PERCENT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2

This code did compile but the DUMMY_ALIAS1 and DUMMY_ALIAS2 override the Order By established in the Select statement which makes this unusable.

The only solution that I could think of, that worked for me was not using a union and instead making the queries run individually and then dealing with them. So basically, not using a Union when you want to Order By

Django, creating a custom 500/404 error page

No additional view is required. https://docs.djangoproject.com/en/3.0/ref/views/

Just put the error files in the root of templates directory

  • 404.html
  • 400.html
  • 403.html
  • 500.html

And it should use your error page when debug is False

What is event bubbling and capturing?

Bubbling

  Event propagate to the upto root element is **BUBBLING**.

Capturing

  Event propagate from body(root) element to eventTriggered Element is **CAPTURING**.

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

Why does this "Slow network detected..." log appear in Chrome?

As soon as I disabled the DuckDuckGo Privacy Essentials plugin it disappeared. Bit annoying as the fonts I was serving was from localhost so shouldn't be anything to do with a slow network connection.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Delete all rows in table

As other have said, TRUNCATE TABLE is far quicker, but it does have some restrictions (taken from here):

You cannot use TRUNCATE TABLE on tables that:

- Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
- Participate in an indexed view.
- Are published by using transactional replication or merge replication.

For tables with one or more of these characteristics, use the DELETE statement instead.

The biggest drawback is that if the table you are trying to empty has foreign keys pointing to it, then the truncate call will fail.

Stopping Docker containers by image name - Ubuntu

Adding on top of @VonC superb answer, here is a ZSH function that you can add into your .zshrc file:

dockstop() {
  docker rm $(docker stop $(docker ps -a -q --filter ancestor="$1" --format="{{.ID}}"))
}

Then in your command line, simply do dockstop myImageName and it will stop and remove all containers that were started from an image called myImageName.

Is there any standard for JSON API response format?

The RFC 7807: Problem Details for HTTP APIs is at the moment the closest thing we have to an official standard.

Chrome DevTools Devices does not detect device when plugged in

None of the mentioned answers worked for me. However, what worked for me is port forwarding. Steps detailed here:

  1. Ensure you have adb installed (steps here for windowd, mac, ubuntu)
  2. Ensure you have chrome running on your mobile device
  3. On your PC, run the following from command line:

    adb forward tcp:9222 localabstract:chrome_devtools_remote

  4. On running the above command, accept the authorization on your mobile phone. Below is the kind of output I see on my laptop:

    $:/> adb forward tcp:9222 localabstract:chrome_devtools_remote

    * daemon not running. starting it now on port 5037 *

    * daemon started successfully *

  5. Now open your chrome and enter 'localhost:9222' and you shall see the active tab to inspect.

Here is the source for this approach

Simple working Example of json.net in VB.net

In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))

Ruby value of a hash key?

How about this?

puts "ok" if hash_variable["key"] == "X"

You can access hash values with the [] operator

while EOF in JAVA?

nextLine() will throw an exception when there's no line and it will never return null,you can try the Scanner Class instead : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.

Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.

As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.


UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.

For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.


UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :

Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :

  1. Open the jquery.fancybox-1.3.4.js file (full version, not pack version) with a text/html editor.
  2. Find around the line 29 where it says :

    isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
    

    and replace it by (EDITED March 19, 2013: more accurate filter):

    isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
    

    UPDATE (March 19, 2013): Also replace $.browser.msie by navigator.userAgent.match(/msie [6]/i) around line 615 (and/or replace all $.browser.msie instances, if any), thanks joofow ... that's it!

Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)

NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)

Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

Why should I use a container div in HTML?

I know this is an old question, but i faced this issue myself redesigning a website. Troy Dalmasso got me thinking. He makes a good point. So, i started to see if i could get it working without a container div.

I could when i set the width of the body. In my case to 960px.

This is the css i use:

html {
  text-align:center;
}

body {
  margin: 0 auto;
  width: 960px;
}

This nicely centers the inline-blocks which also have a fixed width.

Hope this is of use to anyone.

How to jump to top of browser page

you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Other

How to set css style to asp.net button?

<asp:LinkButton ID="mybutton" Text="Link Button" runat="server"></asp:LinkButton>

With Hover effects :

 #mybutton
        {
            background-color: #000;
            color: #fff;
            font-size: 20px;
            width: 150px;
            font-weight: bold;
        }
        #mybutton:hover
        {
            background-color: #fff;
            color: #000;
        }

http://www.parallelcodes.com/asp-net-button-css/

In Python, how do you convert a `datetime` object to seconds?

To get the Unix time (seconds since January 1, 1970):

>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0

How to close an iframe within iframe itself

function closeWin()   // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframe_callback'));
}


<input class="question" name="Close" type="button" value="Close" onClick="closeWin()" tabindex="10" /> 

What's wrong with overridable method calls in constructors?

Here's an example which helps to understand this:

public class Main {
    static abstract class A {
        abstract void foo();
        A() {
            System.out.println("Constructing A");
            foo();
        }
    }

    static class C extends A {
        C() { 
            System.out.println("Constructing C");
        }
        void foo() { 
            System.out.println("Using C"); 
        }
    }

    public static void main(String[] args) {
        C c = new C(); 
    }
}

If you run this code, you get the following output:

Constructing A
Using C
Constructing C

You see? foo() makes use of C before C's constructor has been run. If foo() requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo() expects, you get a warning.

Check if argparse optional argument is set or not

You can check an optionally passed flag with store_true and store_false argument action options:

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument('-flag', dest='flag_exists', action='store_true')

print argparser.parse_args([])
# Namespace(flag_exists=False)
print argparser.parse_args(['-flag'])
# Namespace(flag_exists=True)

This way, you don't have to worry about checking by conditional is not None. You simply check for True or False. Read more about these options in the docs here

How can I remove 3 characters at the end of a string in php?

<?php echo substr("abcabcabc", 0, -3); ?>

X close button only using css

Main point you are looking for is:

.tag-remove::before {
  content: 'x'; // here is your X(cross) sign.
  color: #fff;
  font-weight: 300;
  font-family: Arial, sans-serif;
}

FYI, you can make a close button by yourself very easily:

_x000D_
_x000D_
#mdiv {_x000D_
  width: 25px;_x000D_
  height: 25px;_x000D_
  background-color: red;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.mdiv {_x000D_
  height: 25px;_x000D_
  width: 2px;_x000D_
  margin-left: 12px;_x000D_
  background-color: black;_x000D_
  transform: rotate(45deg);_x000D_
  Z-index: 1;_x000D_
}_x000D_
_x000D_
.md {_x000D_
  height: 25px;_x000D_
  width: 2px;_x000D_
  background-color: black;_x000D_
  transform: rotate(90deg);_x000D_
  Z-index: 2;_x000D_
}
_x000D_
<div id="mdiv">_x000D_
  <div class="mdiv">_x000D_
    <div class="md"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

"Char cannot be dereferenced" error

If Character.isLetter(ch) looks a bit wordy/ugly you can use a static import.

import static java.lang.Character.*;


if(isLetter(ch)) {

} else if(isDigit(ch)) {

} 

How to get the CPU Usage in C#?

public int GetCpuUsage()
{
    var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);
    cpuCounter.NextValue();
    System.Threading.Thread.Sleep(1000); //This avoid that answer always 0
    return (int)cpuCounter.NextValue();
}

Original information in this link https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/

Make install, but not to default directories?

It could be dependent upon what is supported by the module you are trying to compile. If your makefile is generated by using autotools, use:

--prefix=<myinstalldir>

when running the ./configure

some packages allow you to also override when running:

make prefix=<myinstalldir>

however, if your not using ./configure, only way to know for sure is to open up the makefile and check. It should be one of the first few variables at the top.

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

In my case the "Fix Issue" button triggers a spinner for about 20 seconds and fixes nothing.

This works for me (iOS 7 iPhone 5, Xcode 5):

Xcode > Window > Organizer > Devices

Find the connected device(with a green dot) on the left pane. Select "Provisioning Profiles" On the right pane, there is a line with warning. Delete this line.

Now go back to click the "Fix Issue" button and everything is fine - the app runs in the device as expected.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

You can also upgrade Mehrdad Afshari's solution by rewriting the extention method to faster (and better looking) one:

static class EnumerableExtensions
{
    public static T MaxElement<T, R>(this IEnumerable<T> container, Func<T, R> valuingFoo) where R : IComparable
    {
        var enumerator = container.GetEnumerator();
        if (!enumerator.MoveNext())
            throw new ArgumentException("Container is empty!");

        var maxElem = enumerator.Current;
        var maxVal = valuingFoo(maxElem);

        while (enumerator.MoveNext())
        {
            var currVal = valuingFoo(enumerator.Current);

            if (currVal.CompareTo(maxVal) > 0)
            {
                maxVal = currVal;
                maxElem = enumerator.Current;
            }
        }

        return maxElem;
    }
}

And then just use it:

var maxObject = list.MaxElement(item => item.Height);

That name will be clear to people using C++ (because there is std::max_element in there).

How do I catch an Ajax query post error?

$.post('someUri', { }, 
  function(data){ doSomeStuff })
 .fail(function(error) { alert(error.responseJSON) });

Get full query string in C# ASP.NET

Try Request.Url.Query if you want the raw querystring as a string.

Difference between text and varchar (character varying)

In my opinion, varchar(n) has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.

TL;DR: If you use text type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n), you can prevent it.

Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text type or varchar(n) where n is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n) where n is not too much greater than 2712, you're safe from these errors.

Matrix multiplication using arrays

The method mults is a procedure(Pascal) or subroutine(Fortran)

The method multMatrix is a function(Pascal,Fortran)

import java.util.*;

public class MatmultE
{
private static Scanner sc = new Scanner(System.in);
  public static void main(String [] args)
  {
    double[][] A={{4.00,3.00},{2.00,1.00}}; 
    double[][] B={{-0.500,1.500},{1.000,-2.0000}};
    double[][] C=multMatrix(A,B);
    printMatrix(A);
    printMatrix(B);    
    printMatrix(C);

    double a[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
    double b[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
    double[][] c=multMatrix(a,b);
    printMatrix(a);
    printMatrix(b);    
    printMatrix(c);

    double[][] a1 = readMatrix();
    double[][] b1 = readMatrix();
    double[][] c1 = new double[a1.length][b1[0].length];
    mults(a1,b1,c1,a1.length,a1[0].length,b1.length,b1[0].length);
    printMatrix(c1);
    printMatrixE(c1);
  }

   public static double[][] readMatrix() {
       int rows = sc.nextInt();
       int cols = sc.nextInt();
       double[][] result = new double[rows][cols];
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
              result[i][j] = sc.nextDouble();
           }
       }
       return result;
   }


  public static void printMatrix(double[][] mat) {
  System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
       int rows = mat.length;
       int columns = mat[0].length;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.printf("%8.3f " , mat[i][j]);
           }
           System.out.println();
       }
   System.out.println();
  }

  public static void printMatrixE(double[][] mat) {
  System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
       int rows = mat.length;
       int columns = mat[0].length;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.printf("%9.2e " , mat[i][j]);
           }
           System.out.println();
       }
   System.out.println();
  }


   public static double[][] multMatrix(double a[][], double b[][]){//a[m][n], b[n][p]
   if(a.length == 0) return new double[0][0];
   if(a[0].length != b.length) return null; //invalid dims

   int n = a[0].length;
   int m = a.length;
   int p = b[0].length;

   double ans[][] = new double[m][p];

   for(int i = 0;i < m;i++){
      for(int j = 0;j < p;j++){
         ans[i][j]=0;
         for(int k = 0;k < n;k++){
            ans[i][j] += a[i][k] * b[k][j];
         }
      }
   }
   return ans;
   }

   public static void mults(double a[][], double b[][], double c[][], int r1, 
                        int c1, int r2, int c2){
      for(int i = 0;i < r1;i++){
         for(int j = 0;j < c2;j++){
            c[i][j]=0;
            for(int k = 0;k < c1;k++){
               c[i][j] += a[i][k] * b[k][j];
            }
         }
      }
   }
}

where as input matrix you can enter

inE.txt

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.0 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0

in unix like cmmd line execute the command:

$ java MatmultE < inE.txt > outE.txt

and you get the output

outC.txt

Matrix[2][2]
   4.000    3.000 
   2.000    1.000 

Matrix[2][2]
  -0.500    1.500 
   1.000   -2.000 

Matrix[2][2]
   1.000    0.000 
   0.000    1.000 

Matrix[3][4]
   1.000    2.000   -2.000    0.000 
  -3.000    4.000    7.000    2.000 
   6.000    0.000    3.000    1.000 

Matrix[4][2]
  -1.000    3.000 
   0.000    9.000 
   1.000  -11.000 
   4.000   -5.000 

Matrix[3][2]
  -3.000   43.000 
  18.000  -60.000 
   1.000  -20.000 

Matrix[4][3]
  -7.000   15.000    3.000 
 -36.000   70.000   20.000 
-105.000  189.000   57.000 
-256.000  420.000   96.000 

Matrix[4][3]
-7.00e+00  1.50e+01  3.00e+00 
-3.60e+01  7.00e+01  2.00e+01 
-1.05e+02  1.89e+02  5.70e+01 
-2.56e+02  4.20e+02  9.60e+01 

How to change facebook login button with my custom image

I got it working with a call to something as simple as

function fb_login() {
  FB.login( function() {}, { scope: 'email,public_profile' } );
}

I don't know if facebook will ever be able to block this circumvention, but for now I can use whatever HTML or image I want to call fb_login and it works fine.

Reference: Facebook API Docs

How to change the remote a branch is tracking?

If you're sane about it, editing the config file's safe enough. If you want to be a little more paranoid, you can use the porcelain command to modify it:

git config branch.master.remote newserver

Of course, if you look at the config before and after, you'll see that it did exactly what you were going to do.

But in your individual case, what I'd do is:

git remote rename origin old-origin
git remote rename new-origin origin

That is, if the new server is going to be the canonical remote, why not call it origin as if you'd originally cloned from it?

Formatting DataBinder.Eval data

Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.

Mark Up:-

<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>

Code behind:-

Public Function fLabel(ByVal tval) As String
   fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function

Removing the password from a VBA project

My 2 cents on Excel 2016:

  1. open the xls file with Notepad++
  2. Search for DPB= and replace it with DPx=
  3. Save the file
  4. Open the file, open the VB Editor, open modules will not work (error 40230)
  5. Save the file as xlsm
  6. It works

Setting the selected value on a Django forms.ChoiceField

This doesn't touch on the immediate question at hand, but this Q/A comes up for searches related to trying to assign the selected value to a ChoiceField.

If you have already called super().__init__ in your Form class, you should update the form.initial dictionary, not the field.initial property. If you study form.initial (e.g. print self.initial after the call to super().__init__), it will contain values for all the fields. Having a value of None in that dict will override the field.initial value.

e.g.

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        # assign a (computed, I assume) default value to the choice field
        self.initial['choices_field_name'] = 'default value'
        # you should NOT do this:
        self.fields['choices_field_name'].initial = 'default value'

Click events on Pie Charts in Chart.js

If using a Donught Chart, and you want to prevent user to trigger your event on click inside the empty space around your chart circles, you can use the following alternative :

var myDoughnutChart = new Chart(ctx).Doughnut(data);

document.getElementById("myChart").onclick = function(evt){
    var activePoints = myDoughnutChart.getSegmentsAtEvent(evt);

    /* this is where we check if event has keys which means is not empty space */       
    if(Object.keys(activePoints).length > 0)
    {
        var label = activePoints[0]["label"];
        var value = activePoints[0]["value"];
        var url = "http://example.com/?label=" + label + "&value=" + value
        /* process your url ... */
    }
};

If statement in aspx page

<div>
    <% 
        if (true)
        {
    %>
    <div>
        Show true content
    </div>
    <%
        }
        else
        {
    %>
    <div>
        Show false content
    </div>
    <%
        }
    %>
</div>

Footnotes for tables in LaTeX

The best way to do it without any headache is to use the \tablefootnote command from the tablefootnote package. Add the following to your preamble:

\usepackage{tablefootnote}

It just works without the need of additional tricks.

Detect end of ScrollView

I went through the solutions on the internet. Mostly solutions didn't work in the project I'm working on. Following solutions work fine for me.

Using onScrollChangeListener (works on API 23):

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollY;

                if(scrollY==0){
                    //top detected
                }
                if(bottom==0){
                    //bottom detected
                }
            }
        });
    }

using scrollChangeListener on TreeObserver

 scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollView.getScrollY();

            if(scrollView.getScrollY()==0){
                //top detected
            }
            if(bottom==0) {
                //bottom detected
            }
        }
    });

Hope this solution helps :)

Not equal <> != operator on NULL

I would like to suggest this code I made to find if there is a change in a value, i being the new value and d being the old (although the order does not matter). For that matter, a change from value to null or vice versa is a change but from null to null is not (of course, from value to another value is a change but from value to the same it is not).

CREATE FUNCTION [dbo].[ufn_equal_with_nulls]
(
    @i sql_variant,
    @d sql_variant
)
RETURNS bit
AS
BEGIN
    DECLARE @in bit = 0, @dn bit = 0
    if @i is null set @in = 1
    if @d is null set @dn = 1

    if @in <> @dn
        return 0

    if @in = 1 and @dn = 1
        return 1

    if @in = 0 and @dn = 0 and @i = @d
        return 1

    return 0

END

To use this function, you can

declare @tmp table (a int, b int)
insert into @tmp values
(1,1),
(1,2),
(1,null),
(null,1),
(null,null)

---- in select ----
select *, [dbo].[ufn_equal_with_nulls](a,b) as [=] from @tmp

---- where equal ----
select *,'equal' as [Predicate] from @tmp where  [dbo].[ufn_equal_with_nulls](a,b) = 1

---- where not equal ----
select *,'not equal' as [Predicate] from @tmp where  [dbo].[ufn_equal_with_nulls](a,b) = 0

The results are:

---- in select ----
a   b   =
1   1   1
1   2   0
1   NULL    0
NULL    1   0
NULL    NULL    1

---- where equal ----
1   1   equal
NULL    NULL    equal

---- where not equal ----
1   2   not equal
1   NULL    not equal
NULL    1   not equal

The usage of sql_variant makes it compatible for variety of types

How to execute an external program from within Node.js?

The simplest way is:

const { exec } = require("child_process")
exec('yourApp').unref()

unref is necessary to end your process without waiting for "yourApp"

Here are the exec docs

What do >> and << mean in Python?

<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
          6<<2'4=6*2*2*2*2*2=64

xampp MySQL does not start

You already have a version of mySQL installed on this machine that is using port 3306. Go into the most recent my.ini file and change the port to 3307. Restart the mySQL service and see if it comes up.

You also need to change port 3306 to 3307 in xampp\php\php.ini

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

How to enable scrolling of content inside a modal?

I had the same issue, and found a fix as below:

$('.yourModalClassOr#ID').on('shown.bs.modal', function (e) {
    $(' yourModalClassOr#ID ').css("max-height", $(window).height());
    $(' yourModalClassOr#ID ').css("overflow-y", "scroll");          /*Important*/
    $(' yourModalClassOr#ID ').modal('handleUpdate');

});

100% working.

How to change the value of ${user} variable used in Eclipse templates

It seems that your best bet is to redefine the java user.name variable either at your command line, or using the eclipse.ini file in your eclipse install root directory.

This seems to work fine for me:

-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Duser.name=Davide Inglima
-Xms40m
-Xmx512m    

Update:

http://morlhon.net/blog/2005/09/07/eclipse-username/ is a dead link...

Here's a new one: https://web.archive.org/web/20111225025454/http://morlhon.net:80/blog/2005/09/07/eclipse-username/

Displaying Windows command prompt output and redirecting it to a file

Unfortunately there is no such thing.

Windows console applications only have a single output handle. (Well, there are two STDOUT, STDERR but it doesn't matter here) The > redirects the output normally written to the console handle to a file handle.

If you want to have some kind of multiplexing you have to use an external application which you can divert the output to. This application then can write to a file and to the console again.

How to actually search all files in Visual Studio

Press Ctrl+,

Then you will see a docked window under name of "Go to all"

This a picture of the "Go to all" in my IDE

Picture

oracle plsql: how to parse XML and insert into table

CREATE OR REPLACE PROCEDURE ADDEMP
    (xml IN CLOB)
AS
BEGIN
    INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
    SELECT 
        ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
       ,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
       ,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
       ,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
       ,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
    FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

    COMMIT;
END;

Using true and false in C

I prefer the third solution, i.e. using 1 and 0, because it is particularly useful when you have to test if a condition is true or false: you can simply use a variable for the if argument.
If you use other methods, I think that, to be consistent with the rest of the code, I should use a test like this:

if (variable == TRUE)
{
   ...
}

instead of:

if (variable)
{
   ...
}

How to Find the Default Charset/Encoding in Java?

I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.

Updating a date in Oracle SQL table

Here is how you set the date and time:

update user set expiry_date=TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss') where id=123;

Unix command to check the filesize

Here's yet another option to add to the mix:

$ du -b file.txt

That is: estimate file space usage of file.txt in bytes.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

In Python, when to use a Dictionary, List or Set?

  • Do you just need an ordered sequence of items? Go for a list.
  • Do you just need to know whether or not you've already got a particular value, but without ordering (and you don't need to store duplicates)? Use a set.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.

Regex: matching up to the first occurrence of a character

I found that

/^[^,]*,/

works well.

',' being the "delimiter" here.

Create comma separated strings C#?

Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.

Pros - More flexible than an array.

Cons - You can't pass a string containing a comma.

CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();

list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");

string s = list.ToString(); //Huey,Dewey,Louie

Getting title and meta tags from external website

get_meta_tags did not work with title.

Only meta tags with name attributes like

<meta name="description" content="the description">

will be parsed.

How to remove non-alphanumeric characters?

I was looking for the answer too and my intention was to clean every non-alpha and there shouldn't have more than one space.
So, I modified Alex's answer to this, and this is working for me preg_replace('/[^a-z|\s+]+/i', ' ', $name)
The regex above turned sy8ed sirajul7_islam to sy ed sirajul islam
Explanation: regex will check NOT ANY from a to z in case insensitive way or more than one white spaces, and it will be converted to a single space.

Print JSON parsed object?

Use string formats;

console.log("%s %O", "My Object", obj);

Chrome has Format Specifiers with the following;

  • %s Formats the value as a string.
  • %d or %i Formats the value as an integer.
  • %f Formats the value as a floating point value.
  • %o Formats the value as an expandable DOM element (as in the Elements panel).
  • %O Formats the value as an expandable JavaScript object.
  • %c Formats the output string according to CSS styles you provide.

Firefox also has String Substitions which have similar options.

  • %o Outputs a hyperlink to a JavaScript object. Clicking the link opens an inspector.
  • %d or %i Outputs an integer. Formatting is not yet supported.
  • %s Outputs a string.
  • %f Outputs a floating-point value. Formatting is not yet supported.

Safari has printf style formatters

  • %d or %i Integer
  • %[0.N]f Floating-point value with N digits of precision
  • %o Object
  • %s String

Must issue a STARTTLS command first

Adding

props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)

How to get just the date part of getdate()?

Try this:

SELECT CONVERT(date, GETDATE())

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

Integration Services project templates are now available in the latest release of SSDT for Visual Studio 2017.

Note: if you have recently installed SSDT for Visual Studio 2017. You need to remove the Reporting Services and Analysis Services installations before you proceed with installing SSDT.

How do I remove/delete a virtualenv?

The following command works for me.

rm -rf /path/to/virtualenv

How do I write a Windows batch script to copy the newest file from a directory?

I know you asked for Windows but thought I'd add this anyway,in Unix/Linux you could do:

cp `ls -t1 | head -1` /somedir/

Which will list all files in the current directory sorted by modification time and then cp the most recent to /somedir/

How do I create a message box with "Yes", "No" choices and a DialogResult?

You can also use this variant with text strings, here's the complete changed code (Code from Mikael), tested in C# 2012:

// Variable
string MessageBoxTitle = "Some Title";
string MessageBoxContent = "Sure";

DialogResult dialogResult = MessageBox.Show(MessageBoxContent, MessageBoxTitle, MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
    //do something
}
else if (dialogResult == DialogResult.No)
{
    //do something else
}

You can after

.YesNo

insert a message icon

, MessageBoxIcon.Question

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

Python 3 ImportError: No module named 'ConfigParser'

You can instead use the mysqlclient package as a drop-in replacement for MySQL-python. It is a fork of MySQL-python with added support for Python 3.

I had luck with simply

pip install mysqlclient

in my python3.4 virtualenv after

sudo apt-get install python3-dev libmysqlclient-dev

which is obviously specific to ubuntu/debian, but I just wanted to share my success :)

REST vs JSON-RPC?

If your service works fine with only models and the GET/POST/PUT/DELETE pattern, use pure REST.

I agree that HTTP is originally designed for stateless applications.

But for modern, more complex (!) real-time (web) applications where you will want to use Websockets (which often imply statefulness), why not use both? JSON-RPC over Websockets is very light so you have the following benefits:

  • Instant updates on every client (define your own server-to-client RPC call for updating the models)
  • Easy to add complexity (try to make an Etherpad clone with only REST)
  • If you do it right (add RPC only as an extra for real-time), most is still usable with only REST (except if the main feature is a chat or something)

As you are only designing the server side API, start with defining REST models and later add JSON-RPC support as needed, keeping the number of RPC calls to a minimum.

(and sorry for parentheses overuse)

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

  1. Add Internet permission in Androidmanifest.xml file

uses-permission android:name="android.permission.INTERNET

  1. Open cmd in windows
  2. type "ipconfig" then press enter
  3. find IPv4 Address. . . . . . . . . . . : 192.168.X.X
  4. use this URL "http://192.168.X.X:your_virtual_server_port/your_service.php"

Why can't radio buttons be "readonly"?

Radio buttons would only need to be read-only if there are other options. If you don't have any other options, a checked radio button cannot be unchecked. If you have other options, you can prevent the user from changing the value merely by disabling the other options:

<input type="radio" name="foo" value="Y" checked>
<input type="radio" name="foo" value="N" disabled>

Fiddle: http://jsfiddle.net/qqVGu/

Set order of columns in pandas dataframe

Construct it with a list instead of a dictionary

frame = pd.DataFrame([
        [1, .1, 'a'],
        [2, .2, 'e'],
        [3,  1, 'i'],
        [4,  4, 'o']
    ], columns=['one thing', 'second thing', 'other thing'])

frame

   one thing  second thing other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           4.0           o

How to import a Python class that is in a directory above?

Import module from a directory which is exactly one level above the current directory:

from .. import module

Set cURL to use local virtual hosts

Does the server actually get the requests, and are you handling the host name (alias) properly?

after adding to my .hosts file

Check your webserver log, to see how the request came in...

curl has options to dump the request sent, and response received, it is called trace, which will will be saved to a file.

--trace

If you are missing host or header information - you can force those headers with the config option.

I would get the curl request working on the command line, and then try to implement in PHP.

the config option is

-K/--config

the options that are relevant in curl are here

--trace Enables a full trace dump of all incoming and outgoing data, including descriptive information, to the given output file. Use "-" as filename to have the output sent to stdout.

      This option overrides previous uses of -v/--verbose or --trace-ascii.

      If this option is used several times, the last one will be used.

-K/--config Specify which config file to read curl arguments from. The config file is a text file in which command line arguments can be written which then will be used as if they were written on the actual command line. Options and their parameters must be specified on the same config file line, separated by whitespace, colon, the equals sign or any combination thereof (however, the preferred separa- tor is the equals sign). If the parameter is to contain whitespace, the parameter must be enclosed within quotes. Within double quotes, the following escape sequences are available: \, \", \t, \n, \r and \v. A backslash preceding any other letter is ignored. If the first column of a config line is a '#' character, the rest of the line will be treated as a comment. Only write one option per physical line in the config file.

      Specify the filename to -K/--config as '-' to make curl read the file from stdin.

      Note that to be able to specify a URL in the config file, you need to specify it using the --url option, and not by simply writing the URL on its own line. So, it could look similar to this:

      url = "http://curl.haxx.se/docs/"

      Long option names can optionally be given in the config file without the initial double dashes.

      When curl is invoked, it always (unless -q is used) checks for a default config file and uses it if found. The default config file is checked for in the following places in this order:

      1) curl tries to find the "home dir": It first checks for the CURL_HOME and then the HOME environment variables. Failing that, it uses getpwuid() on UNIX-like systems (which  returns  the  home  dir
      given the current user in your system). On Windows, it then checks for the APPDATA variable, or as a last resort the '%USERPROFILE%\Application Data'.

      2)  On windows, if there is no _curlrc file in the home dir, it checks for one in the same dir the curl executable is placed. On UNIX-like systems, it will simply try to load .curlrc from the deter-
      mined home dir.

      # --- Example file ---
      # this is a comment
      url = "curl.haxx.se"
      output = "curlhere.html"
      user-agent = "superagent/1.0"

      # and fetch another URL too
      url = "curl.haxx.se/docs/manpage.html"
      -O
      referer = "http://nowhereatall.com/"
      # --- End of example file ---

      This option can be used multiple times to load multiple config files.

Facebook API: Get fans of / people who like a page

According to the Facebook documentation it's not possible to get all the fans of a page:

Although you can't get a list of all the fans of a Facebook Page, you can find out whether a specific person has liked a Page.

Optimistic vs. Pessimistic locking

There are basically two most popular answers. The first one basically says

Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.

Another answer is

optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.

or

Optimistic locking works best when you have rare collisions

As it is put on this page.

I created my answer to explain how "keep connection" is related to "low collisions".

To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?

You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.

You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.

In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.

I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.

How do I access the $scope variable in browser's console using AngularJS?

Somewhere in your controller (often the last line is a good place), put

console.log($scope);

If you want to see an inner/implicit scope, say inside an ng-repeat, something like this will work.

<li ng-repeat="item in items">
   ...
   <a ng-click="showScope($event)">show scope</a>
</li>

Then in your controller

function MyCtrl($scope) {
    ...
    $scope.showScope = function(e) {
        console.log(angular.element(e.srcElement).scope());
    }
}

Note that above we define the showScope() function in the parent scope, but that's okay... the child/inner/implicit scope can access that function, which then prints out the scope based on the event, and hence the scope associated with the element that fired the event.

@jm-'s suggestion also works, but I don't think it works inside a jsFiddle. I get this error on jsFiddle inside Chrome:

> angular.element($0).scope()
ReferenceError: angular is not defined

How to present UIActionSheet iOS Swift?

Swift 3 For displaying UIAlertController from UIBarButtonItem on iPad

        let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)

    alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
        print("User click Approve button")
    }))

    alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
        print("User click Edit button")
    }))

    alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
        print("User click Delete button")
    }))

    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.cancel, handler:{ (UIAlertAction)in
        print("User click Dismiss button")
    }))

    if let presenter = alert.popoverPresentationController {
        presenter.barButtonItem = sender
    }

    self.present(alert, animated: true, completion: {
        print("completion block")
    })

Call js-function using JQuery timer

You can use setInterval() method also you can call your setTimeout() from your custom function for example

function everyTenSec(){
  console.log("done");
  setTimeout(everyTenSec,10000);
}
everyTenSec();

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Rather than having nested cursor loops a more efficient approach would be to use one cursor loop with an outer join between the tables.

BEGIN
    FOR rec IN (SELECT a.needed_field,b.other_field
                  FROM table1 a
                  LEFT OUTER JOIN table2 b
                    ON a.needed_field = b.condition_field
                 WHERE a.column = ???)
    LOOP
       IF rec.other_field IS NOT NULL THEN
         -- whatever processing needs to be done to other_field
       END IF;
    END LOOP;
END;

What does [STAThread] do?

The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.

Read more info here (Archived, June 2009)

and

Why is STAThread required?

Show pop-ups the most elegant way

It's funny because I'm learning Angular myself and was watching some video's from their channel on Youtube. The speaker mentions your exact problem in this video https://www.youtube.com/watch?v=ZhfUv0spHCY#t=1681 around the 28:30 minute mark.

It comes down to placing that particular piece of code in a service rather then a controller.

My guess would be to inject new popup elements into the DOM and handle them separate instead of showing and hiding the same element. This way you can have multiple popups.

The whole video is very interesting to watch as well :-)

How can I toggle word wrap in Visual Studio?

Following https://docs.microsoft.com/en-gb/visualstudio/ide/reference/how-to-manage-word-wrap-in-the-editor

When viewing a document: Edit / Advanced / Word Wrap (Ctrl+E, Ctrl+W)

General settings: Tools / Options / Text Editor / All Languages / Word wrap

Or search for 'word wrap' in the Quick Launch box.


Known issues:

If you're familiar with word wrap in Notepad++, Sublime Text, or Visual Studio Code, be aware of the following issues where Visual Studio behaves differently to other editors:

  1. Triple click doesn't select whole line
  2. Cut command doesn't delete whole line
  3. Pressing End key twice does not move cursor to end of line

Unfortunately these bugs have been closed "lower priority". If you'd like these bugs fixed, please vote for the feature request Fix known issues with word wrap.

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

Delete default value of an input text on click

For future reference, I have to include the HTML5 way to do this.

<input name="Email" type="text" id="Email" value="[email protected]" placeholder="What's your programming question ? be specific." />

If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see http://www.kamikazemusic.com/quick-tips/jquery-html5-placeholder-fix/ (archive.org version) for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.

Also, the provided link is a well-tested and well-developed solution, which should work out of the box.

Insertion sort vs Bubble Sort Algorithms

Bubble Sort is not online (it cannot sort a stream of inputs without knowing how many items there will be) because it does not really keep track of a global maximum of the sorted elements. When an item is inserted you will need to start the bubbling from the very beginning

How can I match on an attribute that contains a certain string?

A 2.0 XPath that works:

//*[tokenize(@class,'\s+')='atag']

or with a variable:

//*[tokenize(@class,'\s+')=$classname]

How can I get (query string) parameters from the URL in Next.js?

import { useRouter } from 'next/router';

function componentName() {
    const router = useRouter();
    console.log('router obj', router);
}

We can find the query object inside a router using which we can get all query string parameters.

Copy file from source directory to binary directory using CMake

if you want to copy folder from currant directory to binary (build folder) folder

file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/yourFolder/ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yourFolder/)

then the syntexe is :

file(COPY pathSource DESTINATION pathDistination)

Reading a .txt file using Scanner class in Java

  1. You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
  2. The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
  3. While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to disable auto-play for local video in iframe

What do you think about video tag ? If you don't have to use iframe tag you can use video tag instead.

<video width="500" height="345" src="hey.mp4"  />

You should not use autoplay attribute in your video tag to disable autoplay.

Disable scrolling when touch moving certain element

The ultimate solution would be setting overflow: hidden; on document.documentElement like so:

/* element is an HTML element You want catch the touch */
element.addEventListener('touchstart', function(e) {
    document.documentElement.style.overflow = 'hidden';
});

document.addEventListener('touchend', function(e) {
    document.documentElement.style.overflow = 'auto';
});

By setting overflow: hidden on start of touch it makes everything exceeding window hidden thus removing availability to scroll anything (no content to scroll).

After touchend the lock can be freed by setting overflow to auto (the default value).

It is better to append this to <html> because <body> may be used to do some styling, plus it can make children behave unexpectedly.

EDIT: About touch-action: none; - Safari doesn't support it according to MDN.

CSS container div not getting height

I ran into this same issue, and I have come up with four total viable solutions:

  1. Make the container display: flex; (this is my favorite solution)
  2. Add overflow: auto; or overflow: hidden; to the container
  3. Add the following CSS for the container:
.c:after {
    clear: both;
    content: "";
    display: block;
}
  1. Make the following the last item inside the container:
<div style="clear: both;"></div>

Python: What OS am I running on?

You can also use only platform module without importing os module to get all the information.

>>> import platform
>>> platform.os.name
'posix'
>>> platform.uname()
('Darwin', 'mainframe.local', '15.3.0', 'Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64', 'x86_64', 'i386')

A nice and tidy layout for reporting purpose can be achieved using this line:

for i in zip(['system','node','release','version','machine','processor'],platform.uname()):print i[0],':',i[1]

That gives this output:

system : Darwin
node : mainframe.local
release : 15.3.0
version : Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64
machine : x86_64
processor : i386

What is missing usually is the operating system version but you should know if you are running windows, linux or mac a platform indipendent way is to use this test:

In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]:
   ....:     if i[0]:
   ....:         print 'Version: ',i[0]

Installing PG gem on OS X - failure to build native extension

I believe the “correct” answer would be to first configure PATH correctly for Postgres.app by adding the following to ~/.profile (.zshrc or ~/.zprofile if using ZSH):

export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin

Then open a new tab or window in terminal and install the pg gem with:

ARCHFLAGS="-arch x86_64" gem install pg

Documented here:

Array as session variable

session_start();          //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id'];   //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);   
//print_r($_SESSION['student']);


<table class="table">     //html part
    <tr>
      <th>Name</th>
      <th>City</th>
    </tr>

    <tr>
     <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
     echo '<td>'.$_SESSION['student'][$i].'</td>';
     }  ?>
    </tr>
</table>

box-shadow on bootstrap 3 container

Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.

Example: http://jsfiddle.net/SHLu4/2/

It'll be something like:

<div class="container drop-shadow">
    <div class="container">
        <div class="row">
            <div class="col-md-8">Main Area</div>
            <div class="col-md-4">Side Area</div>
        </div>
    </div>
</div>

And your CSS:

<style>
    .drop-shadow {
        -webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
        box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
    }
    .container.drop-shadow {
        padding-left:0;
        padding-right:0;
    }
</style>

Conversion of Char to Binary in C

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

Explanation:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

How to count TRUE values in a logical vector

Another option is to use summary function. It gives a summary of the Ts, Fs and NAs.

> summary(hival)
   Mode   FALSE    TRUE    NA's 
logical    4367      53    2076 
> 

YouTube: How to present embed video with sound muted

<iframe width="560" height="315" src="https://www.youtube.com/embed/ULzr7JsFp0k?list=PLF8tTShmRC6vp9YTjkVdm1qKuTimC6K3e&rel=0&amp;autoplay=1&controls=1&loop=1" rel=0&amp frameborder="0" allowfullscreen></iframe>

How to enable PHP's openssl extension to install Composer?

you need to enable the openssl extension in

C:\wamp\bin\php\php5.4.12\php.ini 

that is the php configuration file that has it type has "configuration settings" with a driver-notepad like icon.

  1. open it either with notepad or any editor,
  2. search for openssl "your ctrl + F " would do.
  3. there is a semi-colon before the openssl extension

    ;extension=php_openssl.dll
    

    remove the semi-colon and you'll have

    extension=php_openssl.dll
    
  4. save the file and restart your WAMP server after that you're good to go. re-install the application again that should work.

How to exit from ForEach-Object in PowerShell

You have two options to abruptly exit out of ForEach-Object pipeline in PowerShell:

  1. Apply exit logic in Where-Object first, then pass objects to Foreach-Object, or
  2. (where possible) convert Foreach-Object into a standard Foreach looping construct.

Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":

Solution-1: use Where-Object filter BEFORE Foreach-Object:

[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
     if($_ -eq 2) {$exit = $true}    #OR $exit = ($_ -eq 2);
     $_;
}

OR

1..10 | Where-Object {$_ -le 2} | Foreach-Object {
     $_;
}

Solution-2: Converted Foreach-Object into standard Foreach looping construct:

Foreach ($i in 1..10) { 
     if ($i -eq 3) {break;}
     $i;
}

PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object pipeline. Note: return doesn't exit, it only skips specific iteration (similar to continue in most programming languages), here is an example of return:

Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
     if ($_ -eq 3) {return;}  #skips only 3rd iteration.
     $_;
}

HTH

What is the best way to merge mp3 files?

As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.

You're going to need to use a tool which can combine the audio data for you.

mp3wrap would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.

The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.

response.sendRedirect() from Servlet to JSP does not seem to work

You can use this:

response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));

The last part is your path in your web-app

nginx error "conflicting server name" ignored

There should be only one localhost defined, check sites-enabled or nginx.conf.

Launch Bootstrap Modal on page load

Like others have mentioned, create your modal with display:block

<div class="modal in" tabindex="-1" role="dialog" style="display:block">
...

Place the backdrop anywhere on your page, it does not necesarily need to be at the bottom of the page

<div class="modal-backdrop fade show"></div> 

Then, to be able to close the dialog again, add this

<script>
    $("button[data-dismiss=modal]").click(function () {
        $(".modal.in").removeClass("in").addClass("fade").hide();
        $(".modal-backdrop").remove();
    });
</script>

Hope this helps

ipad safari: disable scrolling, and bounce effect?

To prevent scrolling on modern mobile browsers you need to add the passive: false. I had been pulling my hair out getting this to work until I found this solution. I have only found this mentioned in one other place on the internet.

_x000D_
_x000D_
function preventDefault(e){_x000D_
    e.preventDefault();_x000D_
}_x000D_
_x000D_
function disableScroll(){_x000D_
    document.body.addEventListener('touchmove', preventDefault, { passive: false });_x000D_
}_x000D_
function enableScroll(){_x000D_
    document.body.removeEventListener('touchmove', preventDefault);_x000D_
}
_x000D_
_x000D_
_x000D_

How to spyOn a value property (rather than a method) with Jasmine

In February 2017, they merged a PR adding this feature, they released in April 2017.

so to spy on getters/setters you use: const spy = spyOnProperty(myObj, 'myGetterName', 'get'); where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {} and the third param is the type get or set.

You can use the same assertions that you already use with the spies created with spyOn.

So you can for example:

const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.

Here's the line in the github source code where this method is available if you are interested.

https://github.com/jasmine/jasmine/blob/7f8f2b5e7a7af70d7f6b629331eb6fe0a7cb9279/src/core/requireInterface.js#L199

Answering the original question, with jasmine 2.6.1, you would:

const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home') in your URL patterns.

The solution is to update your urls.py to include the view callable. This means that you have to import the view in your urls.py. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.

from django.conf.urls import include, url

from django.contrib.auth.views import login
from myapp.views import home, contact

urlpatterns = [
    url(r'^$', home, name='home'),
    url(r'^contact/$', contact, name='contact'),
    url(r'^login/$', login, name='login'),
]

If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.

from django.conf.urls import include, url

from django.contrib.auth import views as auth_views
from myapp import views as myapp_views

urlpatterns = [
    url(r'^$', myapp_views.home, name='home'),
    url(r'^contact/$', myapp_views.contact, name='contact'),
    url(r'^login/$', auth_views.login, name='login'),
]

Note that we have used as myapp_views and as auth_views, which allows us to import the views.py from multiple apps without them clashing.

See the Django URL dispatcher docs for more information about urlpatterns.

How to get Text BOLD in Alert or Confirm box?

Maybe you coul'd use UTF8 bold chars.

For examples: https://yaytext.com/bold-italic/

It works on Chromium 80.0, I don't know on other browsers...

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

Quickest way to compare two generic lists for differences

Use Except:

var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();

I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach.

If you want to combine these, you could create a method with the above and then a return statement:

return !firstNotSecond.Any() && !secondNotFirst.Any();

One point to note is that there is a difference in results between the original code in the question and the solution here: any duplicate elements which are only in one list will only be reported once with my code, whereas they'd be reported as many times as they occur in the original code.

For example, with lists of [1, 2, 2, 2, 3] and [1], the "elements in list1 but not list2" result in the original code would be [2, 2, 2, 3]. With my code it would just be [2, 3]. In many cases that won't be an issue, but it's worth being aware of.

gradle build fails on lint task

if abortOnError false will not resolve your problem, you can try this.

lintOptions {
    checkReleaseBuilds false
}

How to convert buffered image to image and vice-versa?

BufferedImage is a subclass of Image. You don't need to do any conversion.

Set TextView text from html-formatted string resource in XML

Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in

<![CDATA[ ...raw html... ]]>

Example:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

Then, in your code:

TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));

IMHO, this is several orders of magnitude nicer to work with :-)

How to obtain the last index of a list?

You can use the list length. The last index will be the length of the list minus one.

len(list1)-1 == 3

Python: Find index of minimum item in list of floats

You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:

from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0] 

Sending emails through SMTP with PHPMailer

try port 25 instead of 456.

I got the same error when using port 456, and changing it to 25 worked for me.

How can I convert a Timestamp into either Date or DateTime object?

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

C# ListView Column Width Auto

Use this:

yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

from here

psql: server closed the connection unexepectedly

In my case I was making an connection through pgAdmin with ssh tunneling and set to host field ip address but it was necessary to set localhost

Regular expression to extract numbers from a string

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

How to select data where a field has a min value in MySQL?

Use HAVING MIN(...)

Something like:

SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

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

I got this error because I found out that I referenced jQuery twice.

The first time: on the master page (_Layout.cshtml) in ASP.NET MVC, and then again on one current page so I commented out the one on the master page.

If you are using ASP.NET MVC this snippet could help you

@*@Scripts.Render("~/bundles/jquery")*@//comment this line 
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

and in the current page I added these lines

<script src="~/scripts/jquery-1.10.2.js"></script>

<!-- #region datatables files -->
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<!-- #endregion -->

Hope this help you even if don't use ASP.NET MVC

Where does Android emulator store SQLite database?

Since the question is not restricted to Android Studio, So I am giving the path for Visual Studio 2015 (worked for Xamarin).

Tools-Android-Android Device Monitor

enter image description here

  • Locate the database file mentioned in above image, and click on Pull button as it shown in image 2.
  • Save the file in your desired location.
  • You can open that file using SQLite Studio or DB Browser for SQLite.

Special Thanks to other answerers of this question.

How to remove the arrows from input[type="number"] in Opera

I've been using some simple CSS and it seems to remove them and work fine.

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    appearance: none;_x000D_
    margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

This tutorial from CSS Tricks explains in detail & also shows how to style them

How to subtract 30 days from the current date using SQL Server

SELECT DATEADD(day,-30,date) AS before30d 
FROM...

But it is strongly recommended to keep date in datetime column, not varchar.

Override console.log(); for production

Here is what I did

    var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.

var logger = {
    force:false,
    original:null,
    log:function(obj)
    {
        var hostName = window.location.hostname;
        if(domainNames.indexOf(hostName) > -1)
        {
            if(window.myLogger.force === true)
            {
                window.myLogger.original.apply(this,arguments);
            }
        }else {
            window.myLogger.original.apply(this,arguments);
        }
    },
    forceLogging:function(force){
        window.myLogger.force = force;
    },
    original:function(){
        return window.myLogger.original;
    },
    init:function(){
        window.myLogger.original = console.log;
        console.log = window.myLogger.log;
    }
}

window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");

Also posted about it here. http://bhavinsurela.com/naive-way-of-overriding-console-log/

How do I split a string with multiple separators in JavaScript?

Lets keep it simple: (add a "[ ]+" to your RegEx means "1 or more")

This means "+" and "{1,}" are the same.

var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept

UILabel - Wordwrap text

UILabel has a property lineBreakMode that you can set as per your requirement.

How to test code dependent on environment variables using JUnit?

Even though I think this answer is the best for Maven projects, It can be achieved via reflect as well (tested in Java 8):

public class TestClass {
    private static final Map<String, String> DEFAULTS = new HashMap<>(System.getenv());
    private static Map<String, String> envMap;

    @Test
    public void aTest() {
        assertEquals("6", System.getenv("NUMBER_OF_PROCESSORS"));
        System.getenv().put("NUMBER_OF_PROCESSORS", "155");
        assertEquals("155", System.getenv("NUMBER_OF_PROCESSORS"));
    }

    @Test
    public void anotherTest() {
        assertEquals("6", System.getenv("NUMBER_OF_PROCESSORS"));
        System.getenv().put("NUMBER_OF_PROCESSORS", "77");
        assertEquals("77", System.getenv("NUMBER_OF_PROCESSORS"));
    }

    /*
     * Restore default variables for each test
     */
    @BeforeEach
    public void initEnvMap() {
        envMap.clear();
        envMap.putAll(DEFAULTS);
    }

    @BeforeAll
    public static void accessFields() throws Exception {
        envMap = new HashMap<>();
        Class<?> clazz = Class.forName("java.lang.ProcessEnvironment");
        Field theCaseInsensitiveEnvironmentField = clazz.getDeclaredField("theCaseInsensitiveEnvironment");
        Field theUnmodifiableEnvironmentField = clazz.getDeclaredField("theUnmodifiableEnvironment");
        removeStaticFinalAndSetValue(theCaseInsensitiveEnvironmentField, envMap);
        removeStaticFinalAndSetValue(theUnmodifiableEnvironmentField, envMap);
    }

    private static void removeStaticFinalAndSetValue(Field field, Object value) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, value);
    }
}

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.

Clear text input on click with AngularJS

$scope.clearSearch = function () {
    $scope.searchAll = "";
};

http://jsfiddle.net/nzPJD/

JsFiddle of how you could do it without using inline JS.

Soft hyphen in HTML (<wbr> vs. &shy;)

Sometimes web browsers seems to be more forgiving if you use the Unicode string &#173; rather than the &shy; entity.

Find current directory and file's directory

1.To get the current directory full path

    >>import os
    >>print os.getcwd()

o/p:"C :\Users\admin\myfolder"

1.To get the current directory folder name alone

    >>import os
    >>str1=os.getcwd()
    >>str2=str1.split('\\')
    >>n=len(str2)
    >>print str2[n-1]

o/p:"myfolder"

Cannot read property 'addEventListener' of null

I faced a similar situation. This is probably because the script is executed before the page loads. By placing the script at the bottom of the page, I circumvented the problem.

TCP vs UDP on video stream

I recommend you to look at new p2p live protocol Bittorent Live.

As for streaming it's better to use UDP, first because it lowers the load on servers, but mostly because you can send packets with multicast, it's simpler than sending it to each connected client.

Is module __file__ attribute absolute or relative?

With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of sys.path, and file as the result of this lookup (more details in PyMOTW Modules and Imports.). So if the module is located in an absolute path in sys.path the result is absolute, but if it is located in a relative path in sys.path the result is relative.

Now the site.py startup file takes care of delivering only absolute path in sys.path, except the initial '', so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing sys.path), you will get always an absolute path, but when the module is accessed through the current directory.

Now if you trick sys.path in a funny way you can get anything.

As example if you have a sample module foo.py in /tmp/ with the code:

import sys
print(sys.path)
print (__file__)

If you go in /tmp you get:

>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
./foo.py

When in in /home/user, if you add /tmp your PYTHONPATH you get:

>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
/tmp/foo.py

Even if you add ../../tmp, it will be normalized and the result is the same.

But if instead of using PYTHONPATH you use directly some funny path you get a result as funny as the cause.

>>> import sys
>>> sys.path.append('../../tmp')
>>> import foo
['', '/usr/lib/python3.3', .... , '../../tmp']
../../tmp/foo.py

Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:

we don't want to have to call getpwd() on every import .... getpwd() is relatively slow and can sometimes fail outright,

So your path is used as it is.

How do you monitor network traffic on the iPhone?

For Mac OS X

  1. Install Charles Proxy
  2. In Charles go to Proxy > Proxy Settings. It should display the HTTP proxy port (it's 8888 by default).

For Windows

  1. Install Fiddler2
  2. Tools -> Fiddler Options -> Connections and check "Allow remote computers to connect"

General Setup

  1. Go to Settings > Wifi > The i symbol > At the bottom Proxy > Set to manual and then for the server put the computer you are working on IP address, for port put 8888 as that is the default for each of these applications

ARP Spoofing

General notes for the final section, if you want to sniff all the network traffic would be to use ARP spoofing to forward all the traffic from your iOS to a laptop/desktop. There are multiple tools to ARP spoof and research would need to be done on all the specifics. This allows you to see every ounce of traffic as your router will route all data meant for the iOS device to the laptop/desktop and then you will be forwarding this data to the iOS device (automatically).

Please note I only recommend this as a last resort.

Reading a file character by character in C

There are a number of things wrong with your code:

char *readFile(char *fileName)
{
    FILE *file;
    char *code = malloc(1000 * sizeof(char));
    file = fopen(fileName, "r");
    do 
    {
      *code++ = (char)fgetc(file);

    } while(*code != EOF);
    return code;
}
  1. What if the file is greater than 1,000 bytes?
  2. You are increasing code each time you read a character, and you return code back to the caller (even though it is no longer pointing at the first byte of the memory block as it was returned by malloc).
  3. You are casting the result of fgetc(file) to char. You need to check for EOF before casting the result to char.

It is important to maintain the original pointer returned by malloc so that you can free it later. If we disregard the file size, we can achieve this still with the following:

char *readFile(char *fileName)
{
    FILE *file = fopen(fileName, "r");
    char *code;
    size_t n = 0;
    int c;

    if (file == NULL)
        return NULL; //could not open file

    code = malloc(1000);

    while ((c = fgetc(file)) != EOF)
    {
        code[n++] = (char) c;
    }

    // don't forget to terminate with the null character
    code[n] = '\0';        

    return code;
}

There are various system calls that will give you the size of a file; a common one is stat.

StringIO in Python3

On Python 3 numpy.genfromtxt expects a bytes stream. Use the following:

numpy.genfromtxt(io.BytesIO(x.encode()))

Copy or rsync command

Keep in mind that while transferring files internally on a machine i.e not network transfer, using the -z flag can have a massive difference in the time taken for the transfer.

Transfer within same machine

Case 1: With -z flag:
    TAR took: 9.48345208168
    Encryption took: 2.79352903366
    CP took = 5.07273387909
    Rsync took = 30.5113282204

Case 2: Without the -z flag:
    TAR took: 10.7535531521
    Encryption took: 3.0386879921
    CP took = 4.85565590858
    Rsync took = 4.94515299797

SoapUI "failed to load url" error when loading WSDL

Close and reopen soapui. Probably is a bug of the application

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

How do I show running processes in Oracle DB?

Keep in mind that there are processes on the database which may not currently support a session.

If you're interested in all processes you'll want to look to v$process (or gv$process on RAC)

Calculating Distance between two Latitude and Longitude GeoCoordinates

For those who are using Xamarin and don't have access to the GeoCoordinate class, you can use the Android Location class instead:

public static double GetDistanceBetweenCoordinates (double lat1, double lng1, double lat2, double lng2) {
            var coords1 = new Location ("");
            coords1.Latitude = lat1;
            coords1.Longitude = lng1;
            var coords2 = new Location ("");
            coords2.Latitude = lat2;
            coords2.Longitude = lng2;
            return coords1.DistanceTo (coords2);
        }

How to pass multiple parameters in thread in VB

First of all: AddressOf just gets the delegate to a function - you cannot specify anything else (i.e. capture any variables).

Now, you can start up a thread in two possible ways.

  • Pass an Action in the constructor and just Start() the thread.
  • Pass a ParameterizedThreadStart and forward one extra object argument to the method pointed to when calling .Start(parameter)

I consider the latter option an anachronism from pre-generic, pre-lambda times - which have ended at the latest with VB10.

You could use that crude method and create a list or structure which you pass to your threading code as this single object parameter, but since we now have closures, you can just create the thread on an anonymous Sub that knows all necessary variables by itself (which is work performed for you by the compiler).

Soo ...

Dim Evaluator = New Thread(Sub() Me.TestThread(goodList, 1))

It's really just that ;)

Labels for radio buttons in rails form

This an example from my project for rating using radio buttons and its labels

<div class="rating">
  <%= form.radio_button :star, '1' %>
  <%= form.label :star, '?', value: '1' %>

  <%= form.radio_button :star, '2' %>
  <%= form.label :star, '?', value: '2' %>

  <%= form.radio_button :star, '3' %>
  <%= form.label :star, '?', value: '3' %>

  <%= form.radio_button :star, '4' %>
  <%= form.label :star, '?', value: '4' %>

  <%= form.radio_button :star, '5' %>
  <%= form.label :star, '?', value: '5' %>
</div>

How can I get color-int from color resource?

If your current min. API level is 23, you can simply use getColor() like we are using for getString():

//example
textView.setTextColor(getColor(R.color.green));
// if context is not available(ex: not in activity) use with context.getColor()

If you want below API level 23, just use this:

textView.setTextColor(getResources().getColor(R.color.green));

But note that getResources().getColor() is deprecated in API Level 23. In that case replace above with:

textView.setTextColor(ContextCompat.getColor(this /*context*/, R.color.green)) //Im in an activity, so I can use `this`

ContextCompat: Helper for accessing features in Context

If You want, you can constraint with SDK_INT like below:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    textView.setTextColor(getColor(R.color.green));
} else {
    textView.setTextColor(getResources().getColor(R.color.green));
}

window.location.href and window.open () methods in JavaScript

There are already answers which describes about window.location.href property and window.open() method.

I will go by Objective use:

1. To redirect the page to another

Use window.location.href. Set href property to the href of another page.

2. Open link in the new or specific window.

Use window.open(). Pass parameters as per your goal.

3. Know current address of the page

Use window.location.href. Get value of window.location.href property. You can also get specific protocol, hostname, hashstring from window.location object.

See Location Object for more information.

How to access route, post, get etc. parameters in Zend Framework 2

All the above methods will work fine if your content-type is "application/-www-form-urlencoded". But if your content-type is "application/json" then you will have to do the following:

$params = json_decode(file_get_contents('php://input'), true); print_r($params);

Reason : See #7 in https://www.toptal.com/php/10-most-common-mistakes-php-programmers-make

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

When should iteritems() be used instead of items()?

future.utils allows for python 2 and 3 compatibility.

# Python 2 and 3: option 3
from future.utils import iteritems
heights = {'man': 185,'lady': 165}
for (key, value) in iteritems(heights):
    print(key,value)

>>> ('lady', 165)
>>> ('man', 185)

See this link: https://python-future.org/compatible_idioms.html

Using openssl to get the certificate from a server

A one-liner to extract the certificate from a remote server in PEM format, this time using sed:

openssl s_client -connect www.google.com:443 2>/dev/null </dev/null |  sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

Xcode build failure "Undefined symbols for architecture x86_64"

When updating to Xcode 7.1, you might see this type of error, and it can't be resolved by any of the above answers. One of the symptoms in my case was that the app runs on the device not in the simulator. You'll probably see a huge number of errors related to pretty much all of the frameworks you're using.

The fix is actually quite simple. You just need to delete an entry from the "Framework Search Paths" setting, found in your TARGETS > Build Settings > Search Paths section (make sure the "All" tab is selected)

enter image description here

If you see another entry here (besides $(inherited)) for your main target(s) or your test target, just delete the faulty path from all targets and rebuild.

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

Change Spinner dropdown icon

We can manage it by hiding the icon as i did:

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Spinner android:id="@+id/fragment_filter_sp_users"
             android:layout_width="match_parent"
             android:background="@color/colorTransparent"
             android:layout_height="wrap_content"/>

    <ImageView
            android:layout_gravity="end|bottom"
            android:contentDescription="@null"
            android:layout_marginBottom="@dimen/_5sdp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_arrow_bottom"
    />
</FrameLayout>

How do I control how Emacs makes backup files?

If you've ever been saved by an Emacs backup file, you probably want more of them, not less of them. It is annoying that they go in the same directory as the file you're editing, but that is easy to change. You can make all backup files go into a directory by putting something like the following in your .emacs.

(setq backup-directory-alist `(("." . "~/.saves")))

There are a number of arcane details associated with how Emacs might create your backup files. Should it rename the original and write out the edited buffer? What if the original is linked? In general, the safest but slowest bet is to always make backups by copying.

(setq backup-by-copying t)

If that's too slow for some reason you might also have a look at backup-by-copying-when-linked.

Since your backups are all in their own place now, you might want more of them, rather than less of them. Have a look at the Emacs documentation for these variables (with C-h v).

(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)

Finally, if you absolutely must have no backup files:

(setq make-backup-files nil)

It makes me sick to think of it though.

Download Excel file via AJAX MVC

CSL's answer was implemented in a project I'm working on but the problem I incurred was scaling out on Azure broke our file downloads. Instead, I was able to do this with one AJAX call:

SERVER

[HttpPost]
public FileResult DownloadInvoice(int id1, int id2)
{
    //necessary to get the filename in the success of the ajax callback
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    byte[] fileBytes = _service.GetInvoice(id1, id2);
    string fileName = "Invoice.xlsx";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

CLIENT (modified version of Handle file download from ajax post)

$("#downloadInvoice").on("click", function() {
    $("#loaderInvoice").removeClass("d-none");

    var xhr = new XMLHttpRequest();
    var params = [];
    xhr.open('POST', "@Html.Raw(Url.Action("DownloadInvoice", "Controller", new { id1 = Model.Id1, id2 = Model.Id2 }))", true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
            var type = xhr.getResponseHeader('Content-Type');

            var blob = typeof File === 'function'
                ? new File([this.response], filename, { type: type })
                : new Blob([this.response], { type: type });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);

                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof a.download === 'undefined') {
                        window.location = downloadUrl;
                    } else {
                        a.href = downloadUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    window.location = downloadUrl;

                }

                setTimeout(function() {
                        URL.revokeObjectURL(downloadUrl);
                    $("#loaderInvoice").addClass("d-none");
                }, 100); // cleanup
            }
        }
    };
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send($.param(params));
});

How to properly override clone method?

public class MyObject implements Cloneable, Serializable{   

    @Override
    @SuppressWarnings(value = "unchecked")
    protected MyObject clone(){
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream bOs = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bOs);
            oos.writeObject(this);
            ois = new ObjectInputStream(new ByteArrayInputStream(bOs.toByteArray()));
            return  (MyObject)ois.readObject();

        } catch (Exception e) {
            //Some seriouse error :< //
            return null;
        }finally {
            if (oos != null)
                try {
                    oos.close();
                } catch (IOException e) {

                }
            if (ois != null)
                try {
                    ois.close();
                } catch (IOException e) {

                }
        }
    }
}

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

I was facing the same problem when import projects into IntelliJ.

for in my case first, check SDK details and check you have configured JDK correctly or not.

Go to File-> Project Structure-> platform Settings-> SDKs

Check your JDK is correct or not.

enter image description here

Next, I Removed project from IntelliJ and delete all IntelliJ and IDE related files and folder from the project folder (.idea, .settings, .classpath, dependency-reduced-pom). Also, delete the target folder and re-import the project.

The above solution worked in my case.

How to wait until an element exists?

if you have async dom changes, this function checks (with time limit in seconds) for the DOM elements, it will not be heavy for the DOM and its Promise based :)

function getElement(selector, i = 5) {
  return new Promise(async (resolve, reject) => {
    if(i <= 0) return reject(`${selector} not found`);
    const elements = document.querySelectorAll(selector);
    if(elements.length) return resolve(elements);
    return setTimeout(async () => await getElement(selector, i-1), 1000);
  })
}

// Now call it with your selector

try {
  element = await getElement('.woohoo');
} catch(e) { // catch the e }

//OR

getElement('.woohoo', 5)
.then(element => { // do somthing with the elements })
.catch(e => { // catch the error });

TortoiseGit-git did not exit cleanly (exit code 1)

I was heard that, one of the reasons is , the project is too large, so increasing the post buffer could solve the problem. so open the editSystemWideGitConfig, and add the following statements under [http] , postBuffer = 524288000. maybe work.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Senguttuvan: your solution was the only thing that worked for me.

function btnClose() {
  $(".ui-dialog-titlebar-close").trigger('click');
}

Flutter.io Android License Status Unknown

Refer--https://robbinespu.gitlab.io/blog/2020/03/03/flutter-issue-fixed-android-license-status-unknown-on-windows/

So here the solution, open your SDK manager then uncheck Hide Obsolete Packages

enter image description here

Now you’ll see Android SDK Tools (Obsolete) 26.1.1 appears. Tick that package and hit apply button then ok button. it will download sdk. then restart Android studio

Nice, now if you run flutter doctor, you should get positive result as below

PS D:\Workplace\flutter_projects> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[v] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale en-MY)

[v] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[v] Android Studio (version 3.6)
[v] VS Code (version 1.42.1)
[v] Connected device (1 available)

• No issues found!

PS D:\Workplace\flutter_projects> flutter doctor --android-licenses -v
All SDK package licenses accepted.======] 100% Computing updates...

Run flutter doctor --android-licenses and enter Y when is asked

if needed we can download package manually here https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip (for Windows user). Hope this tutorial help people who looking for solution

How to autosize and right-align GridViewColumn data in WPF?

This is your code

<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="40"/>
            <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="100" />
            <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}"/>
        </GridView>
    </ListView.View>
</ListView>

Try this

<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Id}" Width="Auto">
               <GridViewColumnHeader Content="ID" Width="Auto" />
            </GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding FirstName}" Width="Auto">
              <GridViewColumnHeader Content="First Name" Width="Auto" />
            </GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding LastName}" Width="Auto">
              <GridViewColumnHeader Content="Last Name" Width="Auto" />
            </GridViewColumn
        </GridView>
    </ListView.View>
</ListView>

Testing Private method using mockito

You're not suppose to test private methods. Only non-private methods needs to be tested as these should call the private methods anyway. If you "want" to test private methods, it may indicate that you need to rethink your design:

Am I using proper dependency injection? Do I possibly needs to move the private methods into a separate class and rather test that? Must these methods be private? ...can't they be default or protected rather?

In the above instance, the two methods that are called "randomly" may actually need to be placed in a class of their own, tested and then injected into the class above.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

How to merge many PDF files into a single one?

You can use http://www.mergepdf.net/ for example

Or:

PDFTK http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/

If you are NOT on Ubuntu and you have the same problem (and you wanted to start a new topic on SO and SO suggested to have a look at this question) you can also do it like this:

Things You'll Need:

* Full Version of Adobe Acrobat
  1. Open all the .pdf files you wish to merge. These can be minimized on your desktop as individual tabs.

  2. Pull up what you wish to be the first page of your merged document.

  3. Click the 'Combine Files' icon on the top left portion of the screen.

  4. The 'Combine Files' window that pops up is divided into three sections. The first section is titled, 'Choose the files you wish to combine'. Select the 'Add Open Files' option.

  5. Select the other open .pdf documents on your desktop when prompted.

  6. Rearrange the documents as you wish in the second window, titled, 'Arrange the files in the order you want them to appear in the new PDF'

  7. The final window, titled, 'Choose a file size and conversion setting' allows you to control the size of your merged PDF document. Consider the purpose of your new document. If its to be sent as an e-mail attachment, use a low size setting. If the PDF contains images or is to be used for presentation, choose a high setting. When finished, select 'Next'.

  8. A final choice: choose between either a single PDF document, or a PDF package, which comes with the option of creating a specialized cover sheet. When finished, hit 'Create', and save to your preferred location.

    • Tips & Warnings

Double check the PDF documents prior to merging to make sure all pertinent information is included. Its much easier to re-create a single PDF page than a multi-page document.

Updating the list view when the adapter data changes

substitute:

mMyListView.invalidate();

for:

((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

passing 2 $index values within nested ng-repeat

Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!

Right way

  <table>
    <tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
        <td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">

          <b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
          <small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>

        </td>
    </tr>
  </table>

Check: plnkr.co/52oIhLfeXXI9ZAynTuAJ

angular 2 sort and filter

It is not supported by design. The sortBy pipe can cause real performance issues for a production scale app. This was an issue with angular version 1.

You should not create a custom sort function. Instead, you should sort your array first in the typescript file and then display it. If the order needs to be updated when for example a dropdown is selected then have this dropdown selection trigger a function and call your sort function called from that. This sort function can be extracted to a service so that it can be re-used. This way, the sorting will only be applied when it is required and your app performance will be much better.

Changing iframe src with Javascript

Here's the jQuery way to do it:

$('#calendar').attr('src', loc);

How can I generate a list or array of sequential integers in Java?

This one might works for you....

void List<Integer> makeSequence(int begin, int end) {

  AtomicInteger ai=new AtomicInteger(begin);
  List<Integer> ret = new ArrayList(end-begin+1);

  while ( end-->begin) {

    ret.add(ai.getAndIncrement());

  }
  return ret;  
}

Get drop down value

Use the value property of the <select> element. For example:

var value = document.getElementById('your_select_id').value;
alert(value);

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

While I realize this is a bit of an older post, I thought this might help people in a similar situation. I made a quick one line VBScript to pull info for whatever special folder you would like (no error checking though) and it works like this:

Create a file "GetShellFolder.vbs" with the following line:

WScript.Echo WScript.CreateObject("WScript.Shell").SpecialFolders(WScript.Arguments(0))

I always make sure to copy cscript.exe (32-bit version) to the same folder as the batch file I am running this from, I will assume you are doing the same (I have had situations where users have somehow removed C:\Windows\system32 from their path, or managed to get rid of cscript.exe, or it's infected or otherwise doesn't work).

Now copy the file to be copied to the same folder and create a batch file in there with the following lines:

for /f "delims=" %%i in ('^""%~dp0cscript.exe" "%~dp0GetShellFolder.vbs" "Desktop" //nologo^"') DO SET SHELLDIR=%%i
copy /y "%~dp0<file_to_copy>" "%SHELLDIR%\<file_to_copy>"

In the above code you can replace "Desktop" with any valid special folder (Favorites, StartMenu, etc. - the full official list is at https://msdn.microsoft.com/en-us/library/0ea7b5xe%28v=vs.84%29.aspx) and of course <file_to_copy> with the actual file you want placed there. This saves you from trying to access the registry (which you can't do as a limited user anyway) and should be simple enough to adapt to multiple applications.

Oh and for those that don't know the "%~dp0" is just the directory from which the script is being called. It works for UNC paths as well which makes the batch file using it extremely portable. That specifically ends in a trailing "\" though so it can look a little odd at first glance.

What is the difference between mocking and spying when using Mockito?

If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:

  1. Using a mock you would have to set it up by invoking 7 callRealMethod and stub one method
  2. Using a spy you have to set it up by stubbing one method

The official documentation on doCallRealMethod recommends using a spy for partial mocks.

See also javadoc spy(Object) to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.

Echo off but messages are displayed

"echo off" is not ignored. "echo off" means that you do not want the commands echoed, it does not say anything about the errors produced by the commands.

The lines you showed us look okay, so the problem is probably not there. So, please show us more lines. Also, please show us the exact value of INSTALL_PATH.

MISCONF Redis is configured to save RDB snapshots

After banging my head through so many SO questions finally - for me @Axel Advento' s answer worked but with few extra steps - I was still facing the permission issues.
I had to switch user to redis, create a new dir in it's home dir and then set it as redis's dir.

sudo su - redis -s /bin/bash
mkdir redis_dir
redis-cli CONFIG SET dir $(realpath redis_dir)
exit # to logout from redis user (optional)

How to force div to appear below not next to another?

use clear:left; or clear:both in your css.

#map { float:left; width:700px; height:500px; }
 #list { float:left; width:200px; background:#eee; list-style:none; padding:0; }
 #similar { float:left; width:200px; background:#000; clear:both; } 


<div id="map"></div>        
<ul id="list"></ul>
<div id ="similar">
 this text should be below, not next to ul.
</div>

Set cellpadding and cellspacing in CSS?

TBH. For all the fannying around with CSS you might as well just use cellpadding="0" cellspacing="0" since they are not deprecated...

Anyone else suggesting margins on <td>'s obviously has not tried this.

How to post JSON to PHP with curl

You should escape the quotes like this:

curl -i -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}'  \
  http://localhost:3570/index.php/trainingServer/screencast.json

How to remove focus without setting focus to another control?

Try the following (calling clearAllEditTextFocuses();)

private final boolean clearAllEditTextFocuses() {
    View v = getCurrentFocus();
    if(v instanceof EditText) {
        final FocusedEditTextItems list = new FocusedEditTextItems();
        list.addAndClearFocus((EditText) v);

        //Focus von allen EditTexten entfernen
        boolean repeat = true;
        do {
            v = getCurrentFocus();
            if(v instanceof EditText) {
                if(list.containsView(v))
                    repeat = false;
                else list.addAndClearFocus((EditText) v);
            } else repeat = false;
        } while(repeat);

        final boolean result = !(v instanceof EditText);
        //Focus wieder setzen
        list.reset();
        return result;
    } else return false;
}

private final static class FocusedEditTextItem {

    private final boolean focusable;

    private final boolean focusableInTouchMode;

    @NonNull
    private final EditText editText;

    private FocusedEditTextItem(final @NonNull EditText v) {
        editText = v;
        focusable = v.isFocusable();
        focusableInTouchMode = v.isFocusableInTouchMode();
    }

    private final void clearFocus() {
        if(focusable)
            editText.setFocusable(false);
        if(focusableInTouchMode)
            editText.setFocusableInTouchMode(false);
        editText.clearFocus();
    }

    private final void reset() {
        if(focusable)
            editText.setFocusable(true);
        if(focusableInTouchMode)
            editText.setFocusableInTouchMode(true);
    }

}

private final static class FocusedEditTextItems extends ArrayList<FocusedEditTextItem> {

    private final void addAndClearFocus(final @NonNull EditText v) {
        final FocusedEditTextItem item = new FocusedEditTextItem(v);
        add(item);
        item.clearFocus();
    }

    private final boolean containsView(final @NonNull View v) {
        boolean result = false;
        for(FocusedEditTextItem item: this) {
            if(item.editText == v) {
                result = true;
                break;
            }
        }
        return result;
    }

    private final void reset() {
        for(FocusedEditTextItem item: this)
            item.reset();
    }

}

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

xlarge screens are at least 960dp x 720dp layout-xlarge 10" tablet (720x1280 mdpi, 800x1280 mdpi, etc.)

large screens are at least 640dp x 480dp tweener tablet like the Streak (480x800 mdpi), 7" tablet (600x1024 mdpi)

normal screens are at least 470dp x 320dp layout typical phone screen (480x800 hdpi)

small screens are at least 426dp x 320dp typical phone screen (240x320 ldpi, 320x480 mdpi, etc.)

jQuery Ajax requests are getting cancelled without being sent

I have had the same problem, for me I was creating the iframe for temporary manner and I was removing the iframe before the ajax become completes, so the browser would cancel my ajax request.

Simple JavaScript Checkbox Validation

Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.

HTML:

<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />

JavaScript:

var alterDisabledState = function () {

var isMyCheckboxChecked = $('#myCheckbox').is(':checked');

     if (isMyCheckboxChecked) {
     $('myButton').removeAttr("disabled");
     } 
     else {
             $('myButton').attr("disabled", "disabled");
     }
}

Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.

Copying PostgreSQL database to another server

Here is an example using pg_basebackup

I chose to go this route because it backs up the entire database cluster (users, databases, etc.).

I'm posting this as a solution on here because it details every step I had to take, feel free to add recommendations or improvements after reading other answers on here and doing some more research.

For Postgres 12 and Ubuntu 18.04 I had to do these actions:


On the server that is currently running the database:

Update pg_hba.conf, for me located at /etc/postgresql/12/main/pg_hba.conf

Add the following line (substitute 192.168.0.100 with the IP address of the server you want to copy the database to).

host  replication  postgres  192.168.0.100/32  trust

Update postgresql.conf, for me located at /etc/postgresql/12/main/postgresql.conf. Add the following line:

listen_addresses = '*'

Restart postgres:

sudo service postgresql restart


On the host you want to copy the database cluster to:

sudo service postgresql stop

sudo su root

rm -rf /var/lib/postgresql/12/main/*

exit

sudo -u postgres pg_basebackup -h 192.168.0.101 -U postgres -D /var/lib/postgresql/12/main/

sudo service postgresql start

Big picture - stop the service, delete everything in the data directory (mine is in /var/lib/postgreql/12). The permissions on this directory are drwx------ with user and group postgres. I could only do this as root, not even with sudo -u postgres. I'm unsure why. Ensure you are doing this on the new server you want to copy the database to! You are deleting the entire database cluster.

Make sure to change the IP address from 192.168.0.101 to the IP address you are copying the database from. Copy the data from the original server with pg_basebackup. Start the service.

Update pg_hba.conf and postgresql.conf to match the original server configuration - before you made any changes adding the replication line and the listen_addresses line (in my care I had to add the ability to log-in locally via md5 to pg_hba.conf).

Note there are considerations for max_wal_senders and wal_level that can be found in the documentation. I did not have to do anything with this.

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.

As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.

Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).

Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.

The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.

Adding a caption to an equation in LaTeX

As in this forum post by Gonzalo Medina, a third way may be:

\documentclass{article}
\usepackage{caption}

\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}

\begin{document}

Some text

\begin{equ}[!ht]
  \begin{equation}
    a=b+c
  \end{equation}
\caption{Caption of the equation}
\end{equ}

Some other text
 
\end{document}

More details of the commands used from package caption: here.

A screenshot of the output of the above code:

screenshot of output

How can I view the contents of an ElasticSearch index?

If you didn't index too much data into the index yet, you can use term facet query on the field that you would like to debug to see the tokens and their frequencies:

curl -XDELETE 'http://localhost:9200/test-idx'
echo
curl -XPUT 'http://localhost:9200/test-idx' -d '
{
    "settings": {
        "index.number_of_shards" : 1,
        "index.number_of_replicas": 0
    },
    "mappings": {            
        "doc": {
            "properties": {
                "message": {"type": "string", "analyzer": "snowball"}
            }
        }
    }

}'
echo
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '
{
  "message": "How is this going to be indexed?"
}
'
echo
curl -XPOST 'http://localhost:9200/test-idx/_refresh'
echo
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true&search_type=count' -d '{
    "query": {
        "match": {
            "_id": "1"
        }
    },
    "facets": {
        "tokens": {
            "terms": {
                "field": "message"
            }
        }
    }
}
'
echo

C++11 rvalues and move semantics confusion (return statement)

None of them will copy, but the second will refer to a destroyed vector. Named rvalue references almost never exist in regular code. You write it just how you would have written a copy in C++03.

std::vector<int> return_vector()
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> rval_ref = return_vector();

Except now, the vector is moved. The user of a class doesn't deal with it's rvalue references in the vast majority of cases.

Checking if an object is a number in C#

Rather than rolling your own, the most reliable way to tell if an in-built type is numeric is probably to reference Microsoft.VisualBasic and call Information.IsNumeric(object value). The implementation handles a number of subtle cases such as char[] and HEX and OCT strings.

Python: list of lists

I came here because I'm new with python and lazy so I was searching an example to create a list of 2 lists, after a while a realized the topic here could be wrong... this is a code to create a list of lists:

listoflists = []
for i in range(0,2):
    sublist = []
    for j in range(0,10)
        sublist.append((i,j))
    listoflists.append(sublist)
print listoflists

this the output [ [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9)], [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9)] ]

The problem with your code seems to be you are creating a tuple with your list and you get the reference to the list instead of a copy. That I guess should fall under a tuple topic...

jQuery: find element by text

Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:

var text = "text";

var search = $( "ul li label" ).filter( function ()
{
    return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()

Hope someone in the near future finds it helpful.