Programs & Examples On #Teaser

File URL "Not allowed to load local resource" in the Internet Browser

You will have to provide a link to your file that is accessible through the browser, that is for instance:

<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">

versus

<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">

If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:

<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">

But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.

Django: OperationalError No Such Table

This comment on this page worked for me and a few others. It deserves its own answer:

python manage.py migrate --run-syncdb

angularjs ng-style: background-image isn't working

It is possible to parse dynamic values in a couple of way.

Interpolation with double-curly braces:

ng-style="{'background-image':'url({{myBackgroundUrl}})'}"

String concatenation:

ng-style="{'background-image': 'url(' + myBackgroundUrl + ')'}"

ES6 template literals:

ng-style="{'background-image': `url(${myBackgroundUrl})`}"

What's the strangest corner case you've seen in C# or .NET?

C# supports conversions between arrays and lists as long as the arrays are not multidimensional and there is an inheritance relation between the types and the types are reference types

object[] oArray = new string[] { "one", "two", "three" };
string[] sArray = (string[])oArray;

// Also works for IList (and IEnumerable, ICollection)
IList<string> sList = (IList<string>)oArray;
IList<object> oList = new string[] { "one", "two", "three" };

Note that this does not work:

object[] oArray2 = new int[] { 1, 2, 3 }; // Error: Cannot implicitly convert type 'int[]' to 'object[]'
int[] iArray = (int[])oArray2;            // Error: Cannot convert type 'object[]' to 'int[]'

Scrolling to an Anchor using Transition/CSS3

Just apply scroll behaviour to all elements with this one-line code:

_x000D_
_x000D_
*{
scroll-behavior: smooth !important;
}
_x000D_
_x000D_
_x000D_

Is there any option to limit mongodb memory usage?

this worked for me on an AWS instance, to at least clear the cached memory mongo was using. after this you can see how your settings have had effect.

ubuntu@hongse:~$ free -m
             total       used       free     shared    buffers     cached
Mem:          3952       3667        284          0        617        514
-/+ buffers/cache:       2535       1416
Swap:            0          0          0
ubuntu@hongse:~$ sudo su
root@hongse:/home/ubuntu# sync; echo 3 > /proc/sys/vm/drop_caches
root@hongse:/home/ubuntu# free -m
             total       used       free     shared    buffers     cached
Mem:          3952       2269       1682          0          1         42
-/+ buffers/cache:       2225       1726
Swap:            0          0          0

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

Try installing this, it's a known workaround for enabling the C++ compiler for Python 2.7.

In my experience, when pip does not find vcvarsall.bat compiler, all I do is opening a Visual Studio console as it set the path variables to call vcvarsall.bat directly and then I run pip on this command line.

What's the difference between & and && in MATLAB?

A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...

  1. As others have mentioned, the short-circuiting behavior of &&/|| is similar to most C-like languages. That similarity / familiarity is generally considered a point in its favor.
  2. Using the && or || forms forces you to write the full code for deciding your intent for vector arguments. When a = [1 0 0 1] and b = [0 1 0 1], is a&b true or false? I can't remember the rules for MATLAB's &, can you? Most people can't. On the other hand, if you use && or ||, you're FORCED to write the code "in full" to resolve the condition.

Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.

phpexcel to download

Instead of saving it to a file, save it to php://output­Docs:

$objWriter->save('php://output');

This will send it AS-IS to the browser.

You want to add some headers­Docs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):

// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');

// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');

// Write file to the browser
$objWriter->save('php://output');

First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.

What is the difference between Amazon SNS and Amazon SQS?

AWS SNS is a publisher subscriber network, where subscribers can subscribe to topics and will receive messages whenever a publisher publishes to that topic.

AWS SQS is a queue service, which stores messages in a queue. SQS cannot deliver any messages, where an external service (lambda, EC2, etc.) is needed to poll SQS and grab messages from SQS.

SNS and SQS can be used together for multiple reasons.

  1. There may be different kinds of subscribers where some need the immediate delivery of messages, where some would require the message to persist, for later usage via polling. See this link.

  2. The "Fanout Pattern." This is for the asynchronous processing of messages. When a message is published to SNS, it can distribute it to multiple SQS queues in parallel. This can be great when loading thumbnails in an application in parallel, when images are being published. See this link.

  3. Persistent storage. When a service that is going to process a message is not reliable. In a case like this, if SNS pushes a notification to a Service, and that service is unavailable, then the notification will be lost. Therefore we can use SQS as a persistent storage and then process it afterwards.

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I seem to recall having a similar problem a few months ago. I solved it temporarily by copying the referenced DLL to the Release folder, thus satisfying Visual Studio's expectations. Later, I discovered the reference to the Release DLL in my actual code. You should try doing a search through the entire project for \release\project.dll.

Also, I have noticed that Visual Studio unit test projects sometimes put a "DeploymentItem" attribute on each of the test methods pointing to your target DLL, and if you switch between Debug and Release, Visual Studio can get confused if the DLL is no longer in the expected location. In my experience, these attributes can be safely deleted if you didn't put them there yourself as part of a "single deployment" scenario.

Where to change default pdf page width and font size in jspdf.debug.js?

Besides using one of the default formats you can specify any size you want in the unit you specify.

For example:

// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);

The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).

Your 1st parameter (landscape or portrait) determines what becomes the width and the height.

In the sourcecode on GitHub you can see the supported units (relative proportions to pt), and you can also see the default page formats (with their sizes in pt).

How to run a Powershell script from the command line and pass a directory as a parameter

you are calling a script file not a command so you have to use -file eg :

powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"

for PS V2

powershell.exe -noexit &'c:\my scripts\test.ps1'

(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )

"starting Tomcat server 7 at localhost has encountered a prob"

nop... just open the four dateis: content.xml; server.xml; tomcat-users.xml and web.xml in the tap servers. There are some text. Change the number of port 8080 to 8081

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

In my case, there was no process to kill.

Updating docker fixed the problem.

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

What is the difference between bottom-up and top-down?

Lets take fibonacci series as an example

1,1,2,3,5,8,13,21....

first number: 1
Second number: 1
Third Number: 2

Another way to put it,

Bottom(first) number: 1
Top (Eighth) number on the given sequence: 21

In case of first five fibonacci number

Bottom(first) number :1
Top (fifth) number: 5 

Now lets take a look of recursive Fibonacci series algorithm as an example

public int rcursive(int n) {
    if ((n == 1) || (n == 2)) {
        return 1;
    } else {
        return rcursive(n - 1) + rcursive(n - 2);
    }
}

Now if we execute this program with following commands

rcursive(5);

if we closely look into the algorithm, in-order to generate fifth number it requires 3rd and 4th numbers. So my recursion actually start from top(5) and then goes all the way to bottom/lower numbers. This approach is actually top-down approach.

To avoid doing same calculation multiple times we use Dynamic Programming techniques. We store previously computed value and reuse it. This technique is called memoization. There are more to Dynamic programming other then memoization which is not needed to discuss current problem.

Top-Down

Lets rewrite our original algorithm and add memoized techniques.

public int memoized(int n, int[] memo) {
    if (n <= 2) {
        return 1;
    } else if (memo[n] != -1) {
        return memo[n];
    } else {
        memo[n] = memoized(n - 1, memo) + memoized(n - 2, memo);
    }
    return memo[n];
}

And we execute this method like following

   int n = 5;
    int[] memo = new int[n + 1];
    Arrays.fill(memo, -1);
    memoized(n, memo);

This solution is still top-down as algorithm start from top value and go to bottom each step to get our top value.

Bottom-Up

But, question is, can we start from bottom, like from first fibonacci number then walk our way to up. Lets rewrite it using this techniques,

public int dp(int n) {
    int[] output = new int[n + 1];
    output[1] = 1;
    output[2] = 1;
    for (int i = 3; i <= n; i++) {
        output[i] = output[i - 1] + output[i - 2];
    }
    return output[n];
}

Now if we look into this algorithm it actually start from lower values then go to top. If i need 5th fibonacci number i am actually calculating 1st, then second then third all the way to up 5th number. This techniques actually called bottom-up techniques.

Last two, algorithms full-fill dynamic programming requirements. But one is top-down and another one is bottom-up. Both algorithm has similar space and time complexity.

How can I find last row that contains data in a specific column?

Here's a solution for finding the last row, last column, or last cell. It addresses the A1 R1C1 Reference Style dilemma for the column it finds. Wish I could give credit, but can't find/remember where I got it from, so "Thanks!" to whoever it was that posted the original code somewhere out there.

Sub Macro1
    Sheets("Sheet1").Select
    MsgBox "The last row found is: " & Last(1, ActiveSheet.Cells)
    MsgBox "The last column (R1C1) found is: " & Last(2, ActiveSheet.Cells)
    MsgBox "The last cell found is: " & Last(3, ActiveSheet.Cells)
    MsgBox "The last column (A1) found is: " & Last(4, ActiveSheet.Cells)
End Sub

Function Last(choice As Integer, rng As Range)
' 1 = last row
' 2 = last column (R1C1)
' 3 = last cell
' 4 = last column (A1)
    Dim lrw As Long
    Dim lcol As Integer

    Select Case choice
    Case 1:
        On Error Resume Next
        Last = rng.Find(What:="*", _
                        After:=rng.Cells(1), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
        On Error GoTo 0

    Case 2:
        On Error Resume Next
        Last = rng.Find(What:="*", _
                        After:=rng.Cells(1), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
        On Error GoTo 0

    Case 3:
        On Error Resume Next
        lrw = rng.Find(What:="*", _
                       After:=rng.Cells(1), _
                       LookAt:=xlPart, _
                       LookIn:=xlFormulas, _
                       SearchOrder:=xlByRows, _
                       SearchDirection:=xlPrevious, _
                       MatchCase:=False).Row
        lcol = rng.Find(What:="*", _
                        After:=rng.Cells(1), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
        Last = Cells(lrw, lcol).Address(False, False)
        If Err.Number > 0 Then
            Last = rng.Cells(1).Address(False, False)
            Err.Clear
        End If
        On Error GoTo 0
    Case 4:
        On Error Resume Next
        Last = rng.Find(What:="*", _
                        After:=rng.Cells(1), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
        On Error GoTo 0
        Last = R1C1converter("R1C" & Last, 1)
        For i = 1 To Len(Last)
            s = Mid(Last, i, 1)
            If Not s Like "#" Then s1 = s1 & s
        Next i
        Last = s1

    End Select

End Function

Function R1C1converter(Address As String, Optional R1C1_output As Integer, Optional RefCell As Range) As String
    'Converts input address to either A1 or R1C1 style reference relative to RefCell
    'If R1C1_output is xlR1C1, then result is R1C1 style reference.
    'If R1C1_output is xlA1 (or missing), then return A1 style reference.
    'If RefCell is missing, then the address is relative to the active cell
    'If there is an error in conversion, the function returns the input Address string
    Dim x As Variant
    If RefCell Is Nothing Then Set RefCell = ActiveCell
    If R1C1_output = xlR1C1 Then
        x = Application.ConvertFormula(Address, xlA1, xlR1C1, , RefCell) 'Convert A1 to R1C1
    Else
        x = Application.ConvertFormula(Address, xlR1C1, xlA1, , RefCell) 'Convert R1C1 to A1
    End If
    If IsError(x) Then
        R1C1converter = Address
    Else
        'If input address is A1 reference and A1 is requested output, then Application.ConvertFormula
        'surrounds the address in single quotes.
        If Right(x, 1) = "'" Then
            R1C1converter = Mid(x, 2, Len(x) - 2)
        Else
            x = Application.Substitute(x, "$", "")
            R1C1converter = x
        End If
    End If
End Function

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I had a similar issue. pytest did not recognize a module installed in the environment I was working in.

I resolved it by also installing pytest into the same environment.

Need to get current timestamp in Java

java.time

As of Java 8+ you can use the java.time package. Specifically, use DateTimeFormatterBuilder and DateTimeFormatter to format the patterns and literals.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("MM").appendLiteral("/")
        .appendPattern("dd").appendLiteral("/")
        .appendPattern("yyyy").appendLiteral(" ")
        .appendPattern("hh").appendLiteral(":")
        .appendPattern("mm").appendLiteral(":")
        .appendPattern("ss").appendLiteral(" ")
        .appendPattern("a")
        .toFormatter();
System.out.println(LocalDateTime.now().format(formatter));

The output ...

06/22/2015 11:59:14 AM

Or if you want different time zone

// system default
System.out.println(formatter.withZone(ZoneId.systemDefault()).format(Instant.now()));
// Chicago
System.out.println(formatter.withZone(ZoneId.of("America/Chicago")).format(Instant.now()));
// Kathmandu
System.out.println(formatter.withZone(ZoneId.of("Asia/Kathmandu")).format(Instant.now()));

The output ...

06/22/2015 12:38:42 PM
06/22/2015 02:08:42 AM
06/22/2015 12:53:42 PM

MySQL convert date string to Unix timestamp

For current date just use UNIX_TIMESTAMP() in your MySQL query.

Sum one number to every element in a list (or array) in Python

using List Comprehension:

>>> L = [1]*5
>>> [x+1 for x in L]
[2, 2, 2, 2, 2]
>>> 

which roughly translates to using a for loop:

>>> newL = []
>>> for x in L:
...     newL+=[x+1]
... 
>>> newL
[2, 2, 2, 2, 2]

or using map:

>>> map(lambda x:x+1, L)
[2, 2, 2, 2, 2]
>>> 

Node.js connect only works on localhost

On your app, makes it reachable from any device in the network:

app.listen(3000, "0.0.0.0");

For NodeJS in Azure, GCP & AWS

For Azure vm deployed in resource manager, check your virtual network security group and open ports or port ranges to make it reachable, otherwise in your cloud endpoints if vm is deployed in old version of azure.

Just look for equivalent of it for GCP and AWS

How to format numbers by prepending 0 to single-digit numbers?

@Lifehack's answer was very useful to me; where I think we can do it in one line for positive numbers

 String(input).padStart(2, '0');

Could not load file or assembly 'System.Data.SQLite'

I have a 64 bit dev machine and 32 bit build server. I used this code prior to NHibernate initialisation. Works a charm on any architecture (well the 2 I have tested)

Hope this helps someone.

Guido

        private static void LoadSQLLiteAssembly()
        {
            Uri dir = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            FileInfo fi = new FileInfo(dir.AbsolutePath);           
            string binFile = fi.Directory.FullName + "\\System.Data.SQLite.DLL";
            if (!File.Exists(binFile)) File.Copy(GetAppropriateSQLLiteAssembly(), binFile, false);
        }

        private static string GetAppropriateSQLLiteAssembly()
        {
            string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
            string arch = ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? "32" : "64");
            return GetLibsDir() + "\\NUnit\\System.Data.SQLite.x" + arch + ".DLL";
        }

Why does the C++ STL not provide any "tree" containers?

the std::map is based on a red black tree. You can also use other containers to help you implement your own types of trees.

Avoid duplicates in INSERT INTO SELECT query in SQL Server

From SQL Server you can set a Unique key index on the table for (Columns that needs to be unique)

From sql server right click on the table design select Indexes/Keys

Select column(s) that will be not duplicate , then type Unique Key

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Just note that maybe your Entity have primary key but your table in database doesn't have primary key.

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Give full access of .composer to user.

sudo chown -R 'user-name' /home/'user-name'/.composer

or

sudo chmod 777 -R /home/'user-name'/.composer

user-name is your system user-name.

to get user-name type "whoami" in terminal:

enter image description here

Building and running app via Gradle and Android Studio is slower than via Eclipse

Here's what helped this beginning Android programmer (former professional programmer, years ago) in speeding up Android Studio 2.2. I know this is a rehash, but, just summarizing in one place.

Initial builds can still be brutally slow, but restarts of running apps are now usually very tolerable. I'm using a sub-optimal PC: AMD Quad-Core A8-7410 CPU, 8MB RAM, non-SSD HD, Win 10. (And, this is my first Stack Overflow posting.... ;)

IN SETTINGS -> GRADLE:

yes for "Offline work" (this is perhaps the most import setting).

IN SETTINGS -> COMPILER:

yes for "Compile independent modules in parallel" (not sure if this does in fact help utilize multicore CPUs).

IN GRADLE SCRIPTS, "build.gradle (Module: app)":

defaultConfig {
    ...
   // keep min high so that restarted apps can be hotswapped...obviously, this is hugely faster.
   minSdkVersion 14
   ...
    // enabling multidex support...does make big difference for me.
    multiDexEnabled true

ALSO IN GRADLE SCRIPTS, "gradle.properties (Project Properties)":

org.gradle.jvmargs=-Xmx3048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

org.gradle.parallel=true org.gradle.daemon=true

Additionally, testing on a physical device instead of the emulator is working well for me; a small tablet that stands up is convenient.

How do I size a UITextView to its content?

We can do it by constraints .

  1. Set Height constraints for UITextView. enter image description here

2.Create IBOutlet for that height constraint.

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;

3.don't forget to set delegate for your textview.

4.

-(void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    NSLog(@"this is updating height%@",NSStringFromCGSize(newFrame.size));
    [UIView animateWithDuration:0.2 animations:^{
                  _txtheightconstraints.constant=newFrame.size.height;
    }];

}

then update your constraint like this :)

Most efficient way to find smallest of 3 numbers Java?

Let me first repeat what others already said, by quoting from the article "Structured Programming with go to Statements" by Donald Knuth:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.

(emphasis by me)

So if you have identified that a seemingly trivial operation like the computation of the minimum of three numbers is the actual bottleneck (that is, the "critical 3%") in your application, then you may consider optimizing it.

And in this case, this is actually possible: The Math#min(double,double) method in Java has very special semantics:

Returns the smaller of two double values. That is, the result is the value closer to negative infinity. If the arguments have the same value, the result is that same value. If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero.

One can have a look at the implementation, and see that it's actually rather complex:

public static double min(double a, double b) {
    if (a != a)
        return a;   // a is NaN
    if ((a == 0.0d) &&
        (b == 0.0d) &&
        (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) {
        // Raw conversion ok since NaN can't map to -0.0.
        return b;
    }
    return (a <= b) ? a : b;
}

Now, it may be important to point out that this behavior is different from a simple comparison. This can easily be examined with the following example:

public class MinExample
{
    public static void main(String[] args)
    {
        test(0.0, 1.0);
        test(1.0, 0.0);
        test(-0.0, 0.0);
        test(Double.NaN, 1.0);
        test(1.0, Double.NaN);
    }

    private static void test(double a, double b)
    {
        double minA = Math.min(a, b);
        double minB = a < b ? a : b;
        System.out.println("a: "+a);
        System.out.println("b: "+b);
        System.out.println("minA "+minA);
        System.out.println("minB "+minB);
        if (Double.doubleToRawLongBits(minA) !=
            Double.doubleToRawLongBits(minB))
        {
            System.out.println(" -> Different results!");
        }
        System.out.println();
    }
}

However: If the treatment of NaN and positive/negative zero is not relevant for your application, you can replace the solution that is based on Math.min with a solution that is based on a simple comparison, and see whether it makes a difference.

This will, of course, be application dependent. Here is a simple, artificial microbenchmark (to be taken with a grain of salt!)

import java.util.Random;

public class MinPerformance
{
    public static void main(String[] args)
    {
        bench();
    }

    private static void bench()
    {
        int runs = 1000;
        for (int size=10000; size<=100000; size+=10000)
        {
            Random random = new Random(0);
            double data[] = new double[size];
            for (int i=0; i<size; i++)
            {
                data[i] = random.nextDouble();
            }
            benchA(data, runs);
            benchB(data, runs);
        }
    }

    private static void benchA(double data[], int runs)
    {
        long before = System.nanoTime();
        double sum = 0;
        for (int r=0; r<runs; r++)
        {
            for (int i=0; i<data.length-3; i++)
            {
                sum += minA(data[i], data[i+1], data[i+2]);
            }
        }
        long after = System.nanoTime();
        System.out.println("A: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
    }

    private static void benchB(double data[], int runs)
    {
        long before = System.nanoTime();
        double sum = 0;
        for (int r=0; r<runs; r++)
        {
            for (int i=0; i<data.length-3; i++)
            {
                sum += minB(data[i], data[i+1], data[i+2]);
            }
        }
        long after = System.nanoTime();
        System.out.println("B: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
    }

    private static double minA(double a, double b, double c)
    {
        return Math.min(a, Math.min(b, c));
    }

    private static double minB(double a, double b, double c)
    {
        if (a < b)
        {
            if (a < c)
            {
                return a;
            }
            return c;
        }
        if (b < c)
        {
            return b;
        }
        return c;
    }
}

(Disclaimer: Microbenchmarking in Java is an art, and for more reliable results, one should consider using JMH or Caliper).

Running this with JRE 1.8.0_31 may result in something like

....
A: length 90000, time 545.929078, result 2.247805342620906E7
B: length 90000, time 441.999193, result 2.247805342620906E7
A: length 100000, time 608.046928, result 2.5032781001456387E7
B: length 100000, time 493.747898, result 2.5032781001456387E7

This at least suggests that it might be possible to squeeze out a few percent here (again, in a very artifical example).


Analyzing this further, by looking at the hotspot disassembly output created with

java -server -XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation -XX:+PrintAssembly MinPerformance

one can see the optimized versions of both methods, minA and minB.

First, the output for the method that uses Math.min:

Decoding compiled method 0x0000000002992310:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000001c010910} &apos;minA&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;
  # parm0:    xmm0:xmm0   = double
  # parm1:    xmm1:xmm1   = double
  # parm2:    xmm2:xmm2   = double
  #           [sp+0x60]  (sp of caller)
  0x0000000002992480: mov    %eax,-0x6000(%rsp)
  0x0000000002992487: push   %rbp
  0x0000000002992488: sub    $0x50,%rsp
  0x000000000299248c: movabs $0x1c010cd0,%rsi
  0x0000000002992496: mov    0x8(%rsi),%edi
  0x0000000002992499: add    $0x8,%edi
  0x000000000299249c: mov    %edi,0x8(%rsi)
  0x000000000299249f: movabs $0x1c010908,%rsi   ; {metadata({method} {0x000000001c010910} &apos;minA&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;)}
  0x00000000029924a9: and    $0x3ff8,%edi
  0x00000000029924af: cmp    $0x0,%edi
  0x00000000029924b2: je     0x00000000029924e8  ;*dload_0
                        ; - MinPerformance::minA@0 (line 58)

  0x00000000029924b8: vmovsd %xmm0,0x38(%rsp)
  0x00000000029924be: vmovapd %xmm1,%xmm0
  0x00000000029924c2: vmovapd %xmm2,%xmm1       ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)

  0x00000000029924c6: nop
  0x00000000029924c7: callq  0x00000000028c6360  ; OopMap{off=76}
                        ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)
                        ;   {static_call}
  0x00000000029924cc: vmovapd %xmm0,%xmm1       ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)

  0x00000000029924d0: vmovsd 0x38(%rsp),%xmm0   ;*invokestatic min
                        ; - MinPerformance::minA@7 (line 58)

  0x00000000029924d6: nop
  0x00000000029924d7: callq  0x00000000028c6360  ; OopMap{off=92}
                        ;*invokestatic min
                        ; - MinPerformance::minA@7 (line 58)
                        ;   {static_call}
  0x00000000029924dc: add    $0x50,%rsp
  0x00000000029924e0: pop    %rbp
  0x00000000029924e1: test   %eax,-0x27623e7(%rip)        # 0x0000000000230100
                        ;   {poll_return}
  0x00000000029924e7: retq
  0x00000000029924e8: mov    %rsi,0x8(%rsp)
  0x00000000029924ed: movq   $0xffffffffffffffff,(%rsp)
  0x00000000029924f5: callq  0x000000000297e260  ; OopMap{off=122}
                        ;*synchronization entry
                        ; - MinPerformance::minA@-1 (line 58)
                        ;   {runtime_call}
  0x00000000029924fa: jmp    0x00000000029924b8
  0x00000000029924fc: nop
  0x00000000029924fd: nop
  0x00000000029924fe: mov    0x298(%r15),%rax
  0x0000000002992505: movabs $0x0,%r10
  0x000000000299250f: mov    %r10,0x298(%r15)
  0x0000000002992516: movabs $0x0,%r10
  0x0000000002992520: mov    %r10,0x2a0(%r15)
  0x0000000002992527: add    $0x50,%rsp
  0x000000000299252b: pop    %rbp
  0x000000000299252c: jmpq   0x00000000028ec620  ; {runtime_call}
  0x0000000002992531: hlt
  0x0000000002992532: hlt
  0x0000000002992533: hlt
  0x0000000002992534: hlt
  0x0000000002992535: hlt
  0x0000000002992536: hlt
  0x0000000002992537: hlt
  0x0000000002992538: hlt
  0x0000000002992539: hlt
  0x000000000299253a: hlt
  0x000000000299253b: hlt
  0x000000000299253c: hlt
  0x000000000299253d: hlt
  0x000000000299253e: hlt
  0x000000000299253f: hlt
[Stub Code]
  0x0000000002992540: nop                       ;   {no_reloc}
  0x0000000002992541: nop
  0x0000000002992542: nop
  0x0000000002992543: nop
  0x0000000002992544: nop
  0x0000000002992545: movabs $0x0,%rbx          ; {static_stub}
  0x000000000299254f: jmpq   0x000000000299254f  ; {runtime_call}
  0x0000000002992554: nop
  0x0000000002992555: movabs $0x0,%rbx          ; {static_stub}
  0x000000000299255f: jmpq   0x000000000299255f  ; {runtime_call}
[Exception Handler]
  0x0000000002992564: callq  0x000000000297b9e0  ; {runtime_call}
  0x0000000002992569: mov    %rsp,-0x28(%rsp)
  0x000000000299256e: sub    $0x80,%rsp
  0x0000000002992575: mov    %rax,0x78(%rsp)
  0x000000000299257a: mov    %rcx,0x70(%rsp)
  0x000000000299257f: mov    %rdx,0x68(%rsp)
  0x0000000002992584: mov    %rbx,0x60(%rsp)
  0x0000000002992589: mov    %rbp,0x50(%rsp)
  0x000000000299258e: mov    %rsi,0x48(%rsp)
  0x0000000002992593: mov    %rdi,0x40(%rsp)
  0x0000000002992598: mov    %r8,0x38(%rsp)
  0x000000000299259d: mov    %r9,0x30(%rsp)
  0x00000000029925a2: mov    %r10,0x28(%rsp)
  0x00000000029925a7: mov    %r11,0x20(%rsp)
  0x00000000029925ac: mov    %r12,0x18(%rsp)
  0x00000000029925b1: mov    %r13,0x10(%rsp)
  0x00000000029925b6: mov    %r14,0x8(%rsp)
  0x00000000029925bb: mov    %r15,(%rsp)
  0x00000000029925bf: movabs $0x515db148,%rcx   ; {external_word}
  0x00000000029925c9: movabs $0x2992569,%rdx    ; {internal_word}
  0x00000000029925d3: mov    %rsp,%r8
  0x00000000029925d6: and    $0xfffffffffffffff0,%rsp
  0x00000000029925da: callq  0x00000000512a9020  ; {runtime_call}
  0x00000000029925df: hlt
[Deopt Handler Code]
  0x00000000029925e0: movabs $0x29925e0,%r10    ; {section_word}
  0x00000000029925ea: push   %r10
  0x00000000029925ec: jmpq   0x00000000028c7340  ; {runtime_call}
  0x00000000029925f1: hlt
  0x00000000029925f2: hlt
  0x00000000029925f3: hlt
  0x00000000029925f4: hlt
  0x00000000029925f5: hlt
  0x00000000029925f6: hlt
  0x00000000029925f7: hlt

One can see that the treatment of special cases involves some effort - compared to the output that uses simple comparisons, which is rather straightforward:

Decoding compiled method 0x0000000002998790:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000001c0109c0} &apos;minB&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;
  # parm0:    xmm0:xmm0   = double
  # parm1:    xmm1:xmm1   = double
  # parm2:    xmm2:xmm2   = double
  #           [sp+0x20]  (sp of caller)
  0x00000000029988c0: sub    $0x18,%rsp
  0x00000000029988c7: mov    %rbp,0x10(%rsp) ;*synchronization entry
                        ; - MinPerformance::minB@-1 (line 63)

  0x00000000029988cc: vucomisd %xmm0,%xmm1
  0x00000000029988d0: ja     0x00000000029988ee  ;*ifge
                        ; - MinPerformance::minB@3 (line 63)

  0x00000000029988d2: vucomisd %xmm1,%xmm2
  0x00000000029988d6: ja     0x00000000029988de  ;*ifge
                        ; - MinPerformance::minB@22 (line 71)

  0x00000000029988d8: vmovapd %xmm2,%xmm0
  0x00000000029988dc: jmp    0x00000000029988e2
  0x00000000029988de: vmovapd %xmm1,%xmm0 ;*synchronization entry
                        ; - MinPerformance::minB@-1 (line 63)

  0x00000000029988e2: add    $0x10,%rsp
  0x00000000029988e6: pop    %rbp
  0x00000000029988e7: test   %eax,-0x27688ed(%rip)        # 0x0000000000230000
                        ;   {poll_return}
  0x00000000029988ed: retq
  0x00000000029988ee: vucomisd %xmm0,%xmm2
  0x00000000029988f2: ja     0x00000000029988e2  ;*ifge
                        ; - MinPerformance::minB@10 (line 65)

  0x00000000029988f4: vmovapd %xmm2,%xmm0
  0x00000000029988f8: jmp    0x00000000029988e2
  0x00000000029988fa: hlt
  0x00000000029988fb: hlt
  0x00000000029988fc: hlt
  0x00000000029988fd: hlt
  0x00000000029988fe: hlt
  0x00000000029988ff: hlt
[Exception Handler]
[Stub Code]
  0x0000000002998900: jmpq   0x00000000028ec920  ;   {no_reloc}
[Deopt Handler Code]
  0x0000000002998905: callq  0x000000000299890a
  0x000000000299890a: subq   $0x5,(%rsp)
  0x000000000299890f: jmpq   0x00000000028c7340  ; {runtime_call}
  0x0000000002998914: hlt
  0x0000000002998915: hlt
  0x0000000002998916: hlt
  0x0000000002998917: hlt

Whether or not there are cases where such an optimization really makes a difference in an application is hard to tell. But at least, the bottom line is:

  • The Math#min(double,double) method is not the same as a simple comparison, and the treatment of the special cases does not come for free
  • There are cases where the special case treatment that is done by Math#min is not necessary, and then a comparison-based approach may be more efficient
  • As already pointed out in other answers: In most cases, the performance difference will not matter. However, for this particular example, one should probably create a utility method min(double,double,double) anyhow, for better convenience and readability, and then it would be easy to do two runs with the different implementations, and see whether it really affects the performance.

(Side note: The integer type methods, like Math.min(int,int) actually are a simple comparison - so I would expect no difference for these).

Regex for allowing alphanumeric,-,_ and space

For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.

  1. ABC123
  2. ABC 123
  3. ABC123(space)
  4. ABC 123 (space)

So I ended up by writing custom regex as below.

/^([a-z]+[\s]*[0-9]+[\s]*)+$/i

enter image description here

Here, I gave * in [\s]* as it is not mandatory to have a space. A postal code may or may not contains space in my case.

Rubymine: How to make Git ignore .idea files created by Rubymine

Add .idea/* to your exclusion list to prevent tracking of all .idea files, directories, and sub-resources.

How to view UTF-8 Characters in VIM or Gvim

Is this problem solved meanwhile?

I had the problem that gvim didn't display all unicode characters (but only a subset, including the umlauts and accented characters), while :set guifont? was empty; see my question. After reading here, setting the guifont to a sensible value fixed it for me. However, I don't need characters beyond 2 bytes.

How to loop through all elements of a form jQuery

pure JavaScript is not that difficult:

for(var i=0; i < form.elements.length; i++){
    var e = form.elements[i];
    console.log(e.name+"="+e.value);
}

Note: because form.elements is a object for-in loop does not work as expected.

Answer found here (by Chris Pietschmann), documented here (W3S).

Enable remote connections for SQL Server Express 2012

This article helped me...

How to enable remote connections in SQL Server

Everything in SQL Server was configured, my issue was the firewall was blocking port 1433

Does delete on a pointer to a subclass call the base class destructor?

The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.

class A
{
    char *someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { delete[] someHeapMemory; }
};

class B
{
    A* APtr;
public:
    B() : APtr(new A()) {}
    ~B() { delete APtr; }
};

class C
{
    A Amember;
public:
    C() : Amember() {}
    ~C() {} // A is freed / destructed automatically.
};

int main()
{
    B* BPtr = new B();
    delete BPtr; // Calls ~B() which calls ~A() 
    C *CPtr = new C();
    delete CPtr;
    B b;
    C c;
} // b and c are freed/destructed automatically

In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.

auto_ptr, unique_ptr and shared_ptr etc... are great for making this lifetime management much easier:

class A
{
    shared_array<char> someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { } // someHeapMemory is delete[]d automatically
};

class B
{
    shared_ptr<A> APtr;
public:
    B() : APtr(new A()) {}
    ~B() {  } // APtr is deleted automatically
};

int main()
{
    shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically

fatal: does not appear to be a git repository

It is most likely that you got your repo's SSH URL wrong.

To confirm, go to your repository on Github and click the clone or download button. Then click the use SSH link.

ssh link

Now copy your official repo's SSH link. Mine looked like this - [email protected]:borenho/que-ay.git

You can now do git remote add origin [email protected]:borenho/que-ay.git if you didn't have origin yet.

If you had set origin before, change it by using git remote set-url origin [email protected]:borenho/que-ay.git

Now push with git push -u origin master

What is the difference between a cer, pvk, and pfx file?

Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:

  • Both PKCS12 and PEM can store entire cert chains: public keys, private keys, and root (CA) certs.
  • .pfx == .p12 == "PKCS12"
    • fully encrypted
  • .pem == .cer == .cert == "PEM" (or maybe not... could be binary... see comments...)
    • base-64 (string) encoded X509 cert (binary) with a header and footer
      • base-64 is basically just a string of "A-Za-z0-9+/" used to represent 0-63, 6 bits of binary at a time, in sequence, sometimes with 1 or 2 "=" characters at the very end when there are leftovers ("=" being "filler/junk/ignore/throw away" characters)
      • the header and footer is something like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" or "-----BEGIN ENCRYPTED PRIVATE KEY-----" and "-----END ENCRYPTED PRIVATE KEY-----"
    • Windows recognizes .cer and .cert as cert files
  • .jks == "Java Key Store"
    • just a Java-specific file format which the API uses
      • .p12 and .pfx files can also be used with the JKS API
  • "Trust Stores" contain public, trusted, root (CA) certs, whereas "Identity/Key Stores" contain private, identity certs; file-wise, however, they are the same.

What's the best three-way merge tool?

Just checked out P4merge since I heard about it in another blog article:

enter image description here

Very slick interface, and FREE! I've been a faithful Araxis Merge user, but considering this is free and awesome, I'd encourage you to check it out.

Alternative to file_get_contents?

Yes, if you have URL wrappers disabled you should use sockets or, even better, the cURL library.

If it's part of your site then refer to it with the file system path, not the web URL. /var/www/..., rather than http://domain.tld/....

global variable for all controller and views

Most popular answers here with BaseController didn't worked for me on Laravel 5.4, but they have worked on 5.3. No idea why.

I have found a way which works on Laravel 5.4 and gives variables even for views which are skipping controllers. And, of course, you can get variables from the database.

add in your app/Providers/AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Using view composer to set following variables globally
        view()->composer('*',function($view) {
            $view->with('user', Auth::user());
            $view->with('social', Social::all()); 
            // if you need to access in controller and views:
            Config::set('something', $something); 
        });
    }
}

credit: http://laraveldaily.com/global-variables-in-base-controller/

How can I merge two MySQL tables?

Not as complicated as it sounds.... Just leave the duplicate primary key out of your query.... this works for me !

INSERT INTO
  Content(
    `status`,
    content_category,
    content_type,
    content_id,
    user_id,
    title,
    description,
    content_file,
    content_url,
    tags,
    create_date,
    edit_date,
    runs
  )
SELECT `status`,
  content_category,
  content_type,
  content_id,
  user_id,
  title,
  description,
  content_file,
  content_url,
  tags,
  create_date,
  edit_date,
  runs
FROM
  Content_Images

Close Form Button Event

private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK);
        System.Windows.Forms.Application.Exit();
    }
    else
    {
        this.Activate();
    }  
}

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

What does template <unsigned int N> mean?

Yes, it is a non-type parameter. You can have several kinds of template parameters

  • Type Parameters.
    • Types
    • Templates (only classes and alias templates, no functions or variable templates)
  • Non-type Parameters
    • Pointers
    • References
    • Integral constant expressions

What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:

Template type parameter:

template<typename T>
struct Container {
    T t;
};

// pass type "long" as argument.
Container<long> test;

Template integer parameter:

template<unsigned int S>
struct Vector {
    unsigned char bytes[S];
};

// pass 3 as argument.
Vector<3> test;

Template pointer parameter (passing a pointer to a function)

template<void (*F)()>
struct FunctionWrapper {
    static void call_it() { F(); }
};

// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;

Template reference parameter (passing an integer)

template<int &A>
struct SillyExample {
    static void do_it() { A = 10; }
};

// pass flag as argument
int flag;
SillyExample<flag> test;

Template template parameter.

template<template<typename T> class AllocatePolicy>
struct Pool {
    void allocate(size_t n) {
        int *p = AllocatePolicy<int>::allocate(n);
    }
};

// pass the template "allocator" as argument. 
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;

A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:

template<unsigned int SIZE = 3>
struct Vector {
    unsigned char buffer[SIZE];
};

Vector<> test;

Syntactically, template<> is reserved to mark an explicit template specialization, instead of a template without parameters:

template<>
struct Vector<3> {
    // alternative definition for SIZE == 3
};

Printf width specifier to maintain precision of floating-point value

The short answer to print floating point numbers losslessly (such that they can be read back in to exactly the same number, except NaN and Infinity):

  • If your type is float: use printf("%.9g", number).
  • If your type is double: use printf("%.17g", number).

Do NOT use %f, since that only specifies how many significant digits after the decimal and will truncate small numbers. For reference, the magic numbers 9 and 17 can be found in float.h which defines FLT_DECIMAL_DIG and DBL_DECIMAL_DIG.

How to navigate through textfields (Next / Done Buttons)

This is a simple solution in swift, with no tag using, no storyboard tricks...

Just use this extension :

extension UITextField{

    func nextTextFieldField() -> UITextField?{
        //field to return
        var returnField : UITextField?
        if self.superview != nil{
            //for each view in superview
            for (_, view) in self.superview!.subviews.enumerate(){
                //if subview is a text's field
                if view.isKindOfClass(UITextField){
                    //cast curent view as text field
                    let currentTextField = view as! UITextField
                    //if text field is after the current one
                    if currentTextField.frame.origin.y > self.frame.origin.y{
                        //if there is no text field to return already
                        if returnField == nil {
                            //set as default return
                            returnField = currentTextField
                        }
                            //else if this this less far than the other
                        else if currentTextField.frame.origin.y < returnField!.frame.origin.y{
                            //this is the field to return
                            returnField = currentTextField
                        }
                    }
                }
            }
        }
        //end of the mdethod
        return returnField
    }

}

And call it like this (for example) with your textfield delegate:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    textField.nextTextFieldField()?.becomeFirstResponder()
    return true
}

How to escape a JSON string containing newline characters using JavaScript?

Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of \n with \\n.

EDIT:

As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace() method and replace all of the special characters like this:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
                                      .replace(/\\'/g, "\\'")
                                      .replace(/\\"/g, '\\"')
                                      .replace(/\\&/g, "\\&")
                                      .replace(/\\r/g, "\\r")
                                      .replace(/\\t/g, "\\t")
                                      .replace(/\\b/g, "\\b")
                                      .replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server. 

But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace() calls. So let's put that functionality into a function called, escapeSpecialChars(). Let's go ahead and attach it to the prototype chain of the String object, so we can call escapeSpecialChars() directly on String objects.

Like so:

String.prototype.escapeSpecialChars = function() {
    return this.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
};

Once we have defined that function, the main body of our code is as simple as this:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server

How do I export (and then import) a Subversion repository?

Basically, there are plenty of ways to accomplish the task. The topic is covered in depth in SVNBook | Migrating Repository Data Elsewhere, so I suggest reading the book's section.

Here is a brief description of your options:

  • It depends on your environment, but there is a great chance that you can simply copy the repository to the new server and it will work. You have to revise repository hook scripts after copying the repo to ensure that they are working as you expect.

  • You can use svnadmin dump and svnadmin load commands to, ehm, generate full dump and then load it to another repository on another server. You will need to svnadmin create a new clean repository to load the dump into it. Keep in mind that the approach deals with repository history only and does not move hook scripts and repository configuration files! As well, you must have read filesystem access to the original repository to dump it.

  • Since Subversion 1.7, svnrdump tool is available. Generally speaking, it mimics svnadmin dump and svnadmin load functionality, but operates remotely. You are not required to have read / write filesystem access to original and target repositories as tool operates remotely like Subversion client, e.g. over HTTPS protocol. So you need to have read access to original repository and read / write to the target one.

  • Another option is to use svnadmin hotcopy command. The command is mostly used for backup purpose, it creates full copy of the repository including configuration and hook scripts. You can move hotcopied repository to another server then.

Relative paths in Python

I'm not sure if this applies to some of the older versions, but I believe Python 3.3 has native relative path support.

For example the following code should create a text file in the same folder as the python script:

open("text_file_name.txt", "w+t")

(note that there shouldn't be a forward or backslash at the beginning if it's a relative path)

cURL error 60: SSL certificate: unable to get local issuer certificate

I just experienced this same problem with the Laravel 4 php framework which uses the guzzlehttp/guzzle composer package. For some reason, the SSL certificate for mailgun stopped validating suddenly and I got that same "error 60" message.

If, like me, you are on a shared hosting without access to php.ini, the other solutions are not possible. In any case, Guzzle has this client initializing code that would most likely nullify the php.ini effects:

// vendor/guzzlehttp/guzzle/src/Client.php
    $settings = [
        'allow_redirects' => true,
        'exceptions'      => true,
        'decode_content'  => true,
        'verify'          => __DIR__ . '/cacert.pem'
    ];

Here Guzzle forces usage of its own internal cacert.pem file, which is probably now out of date, instead of using the one provided by cURL's environment. Changing this line (on Linux at least) configures Guzzle to use cURL's default SSL verification logic and fixed my problem:

        'verify'          => true

You can also set this to false if you don't care about the security of your SSL connection, but that's not a good solution.

Since the files in vendor are not meant to be tampered with, a better solution would be to configure the Guzzle client on usage, but this was just too difficult to do in Laravel 4.

Hope this saves someone else a couple hours of debugging...

What is better, adjacency lists or adjacency matrices for graph problems in C++?

I am just going to touch on overcoming the trade-off of regular adjacency list representation, since other answers have covered other aspects.

It is possible to represent a graph in adjacency list with EdgeExists query in amortized constant time, by taking advantage of Dictionary and HashSet data structures. The idea is to keep vertices in a dictionary, and for each vertex, we keep a hash set referencing to other vertices it has edges with.

One minor trade-off in this implementation is that it will have space complexity O(V + 2E) instead of O(V + E) as in regular adjacency list, since edges are represented twice here (because each vertex have its own hash set of edges). But operations such as AddVertex, AddEdge, RemoveEdge can be done in amortized time O(1) with this implementation, except for RemoveVertex which takes O(V) like adjacency matrix. This would mean that other than implementation simplicity, adjacency matrix don't have any specific advantage. We can save space on sparse graph with almost the same performance in this adjacency list implementation.

Take a look at implementations below in Github C# repository for details. Note that for weighted graph it uses a nested dictionary instead of dictionary-hash set combination so as to accommodate weight value. Similarly for directed graph there is separate hash sets for in & out edges.

Advanced-Algorithms

Note: I believe using lazy deletion we can further optimize RemoveVertex operation to O(1) amortized, even though I haven't tested that idea. For example, upon deletion just mark the vertex as deleted in dictionary, and then lazily clear orphaned edges during other operations.

Email validation using jQuery

use this

if ($this.hasClass('tb-email')) {
    var email = $this.val();
    var txt = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!txt.test(email)) {
        e.preventDefault();
        $this.addClass('error');
    } else {
        $this.removeClass('error');
    }
}

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

How to post JSON to a server using C#?

var data = Encoding.ASCII.GetBytes(json);

byte[] postBytes = Encoding.UTF8.GetBytes(json);

Use ASCII instead of UFT8

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

i am not sure but, I think you can use @ResponseEntity and @ResponseBody and send 2 different one is Success and second is error message like :

@RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
Book bookInfo2() {
    Book book = new Book();
    book.setBookName("Ramcharitmanas");
    book.setWriter("TulasiDas");
    return book;
}

@RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE )
public ResponseEntity<Book> bookInfo3() {
    Book book = new Book();
    book.setBookName("Ramayan");
    book.setWriter("Valmiki");
    return ResponseEntity.accepted().body(book);
}

For more detail refer to this: http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity

Syntax for a for loop in ruby

What? From 2010 and nobody mentioned Ruby has a fine for /in loop (it's just nobody uses it):

ar = [1,2,3,4,5,6]
for item in ar
  puts item
end

Convert a hexadecimal string to an integer efficiently in C?

In C you can convert a hexadecimal number to decimal in many ways. One way is to cast the hexadecimal number to an integer. I personally found this to be simple and small.

Here is an sample code for converting a Hexadecimal number to a Decimal number with the help of casting.

#include <stdio.h>

int main(){
    unsigned char Hexadecimal = 0x6D;   //example hex number
    int Decimal = 0;    //decimal number initialized to 0


        Decimal = (int) Hexadecimal;  //conversion

    printf("The decimal number is %d\n", Decimal);  //output
    return 0;
}

Postgresql column reference "id" is ambiguous

SELECT vg.id, 
       vg.name
  FROM v_groups vg INNER JOIN  
       people2v_groups p2vg ON vg.id = p2vg.v_group_id
 WHERE p2vg.people_id = 0;

Printing a java map Map<String, Object> - How?

I'm sure there's some nice library that does this sort of thing already for you... But to just stick with the approach you're already going with, Map#entrySet gives you a combined Object with the key and the value. So something like:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}

will do what you're after.


If you're using java 8, there's also the new streaming approach.

map.forEach((key, value) -> System.out.println(key + ":" + value));

C# equivalent to Java's charAt()?

Console.WriteLine allows the user to specify a position in a string.

See sample:

string str = "Tigger"; Console.WriteLine( str[0] ); //returns "T"; Console.WriteLine( str[2] ); //returns "g";

There you go!

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

_x000D_
_x000D_
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();

dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);

document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>

</body>
</html>
_x000D_
_x000D_
_x000D_

Getting title and meta tags from external website

We use Apache Tika via php (command line utility) with -j for json :

http://tika.apache.org/

<?php
    shell_exec( 'java -jar tika-app-1.4.jar -j http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying' );
?>

This is a sample output from a random guardian article :

{
   "Content-Encoding":"UTF-8",
   "Content-Length":205599,
   "Content-Type":"text/html; charset\u003dUTF-8",
   "DC.date.issued":"2013-07-21",
   "X-UA-Compatible":"IE\u003dEdge,chrome\u003d1",
   "application-name":"The Guardian",
   "article:author":"http://www.guardian.co.uk/profile/nicholaswatt",
   "article:modified_time":"2013-07-21T22:42:21+01:00",
   "article:published_time":"2013-07-21T22:00:03+01:00",
   "article:section":"Politics",
   "article:tag":[
      "Lynton Crosby",
      "Health policy",
      "NHS",
      "Health",
      "Healthcare industry",
      "Society",
      "Public services policy",
      "Lobbying",
      "Conservatives",
      "David Cameron",
      "Politics",
      "UK news",
      "Business"
   ],
   "content-id":"/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "dc:title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
   "description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
   "fb:app_id":180444840287,
   "keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
   "msapplication-TileColor":"#004983",
   "msapplication-TileImage":"http://static.guim.co.uk/static/a314d63c616d4a06f5ec28ab4fa878a11a692a2a/common/images/favicons/windows_tile_144_b.png",
   "news_keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
   "og:description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
   "og:image":"https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pixies/2013/7/21/1374433351329/Lynton-Crosby-008.jpg",
   "og:site_name":"the Guardian",
   "og:title":"Tory strategist Lynton Crosby in new lobbying row",
   "og:type":"article",
   "og:url":"http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "resourceName":"tory-strategist-lynton-crosby-lobbying",
   "title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
   "twitter:app:id:googleplay":"com.guardian",
   "twitter:app:id:iphone":409128287,
   "twitter:app:name:googleplay":"The Guardian",
   "twitter:app:name:iphone":"The Guardian",
   "twitter:app:url:googleplay":"guardian://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "twitter:card":"summary_large_image",
   "twitter:site":"@guardian"
}

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

I worked on both Travis and Jenkins: I will list down some of the features of both:

Setup CI for a project

Travis comes in first place. It's very easy to setup. Takes less than a minute to setup with GitHub.

  1. Login to GitHub
  2. Create Web Hook for Travis.
  3. Return to Travis, and login with your GitHub credentials
  4. Sync your GitHub repo and enable Push and Pull requests.

Jenkins:

  1. Create an Environment (Master Jenkins)
  2. Create web hooks
  3. Configure each job (takes time compare to Travis)

Re-running builds

Travis: Anyone with write access on GitHub can re-run the build by clicking on `restart build

Jenkins: Re-run builds based on a phrase. You provide phrase text in PR/commit description, like reverify jenkins.

Controlling environment

Travis: Travis provides hosted environment. It installs required software for every build. It’s a time-consuming process.

Jenkins: One-time setup. Installs all required software on a node/slave machine, and then builds/tests on a pre-installed environment.

Build Logs:

Travis: Supports build logs to place in Amazon S3.

Jenkins: Easy to setup with build artifacts plugin.

Find and replace strings in vim on multiple lines

VI search and replace command examples

Let us say you would like to find a word called “foo” and replace with “bar”.

First hit [Esc] key

Type : (colon) followed by %s/foo/bar/ and hit [Enter] key

:%s/foo/bar/

DataTable, How to conditionally delete rows

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}

How to Make A Chevron Arrow Using CSS?

This can be solved much easier than the other suggestions.

Simply draw a square and apply a border property to just 2 joining sides.

Then rotate the square according to the direction you want the arrow to point, for exaple: transform: rotate(<your degree here>)

_x000D_
_x000D_
.triangle {_x000D_
    border-right: 10px solid; _x000D_
    border-bottom: 10px solid;_x000D_
    height: 30px;_x000D_
    width: 30px;_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

What are the use cases for selecting CHAR over VARCHAR in SQL?

Using CHAR (NCHAR) and VARCHAR (NVARCHAR) brings differences in the ways the database server stores the data. The first one introduces trailing blanks; I have encountered problem when using it with LIKE operator in SQL SERVER functions. So I have to make it safe by using VARCHAR (NVARCHAR) all the times.

For example, if we have a table TEST(ID INT, Status CHAR(1)), and you write a function to list all the records with some specific value like the following:

CREATE FUNCTION List(@Status AS CHAR(1) = '')
RETURNS TABLE
AS
RETURN
SELECT * FROM TEST
WHERE Status LIKE '%' + @Status '%'

In this function we expect that when we put the default parameter the function will return all the rows, but in fact it does not. Change the @Status data type to VARCHAR will fix the issue.

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

Git - Undo pushed commits

2020 Simple way :

git reset <commit_hash>

(The hash of the last commit you want to keep).

You will keep the now uncommitted changes locally.

If you want to push again, you have to do :

git push -f

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

Rename multiple files based on pattern in Unix

Using find, xargs and sed:

find . -name "fgh*" -type f -print0 | xargs -0 -I {} sh -c 'mv "{}" "$(dirname "{}")/`echo $(basename "{}") | sed 's/^fgh/jkl/g'`"'

It's more complex than @nik's solution but it allows to rename files recursively. For instance, the structure,

.
+-- fghdir
¦   +-- fdhfilea
¦   +-- fghfilea
+-- fghfile\ e
+-- fghfilea
+-- fghfileb
+-- fghfilec
+-- other
    +-- fghfile\ e
    +-- fghfilea
    +-- fghfileb
    +-- fghfilec

would be transformed to this,

.
+-- fghdir
¦   +-- fdhfilea
¦   +-- jklfilea
+-- jklfile\ e
+-- jklfilea
+-- jklfileb
+-- jklfilec
+-- other
    +-- jklfile\ e
    +-- jklfilea
    +-- jklfileb
    +-- jklfilec

The key to make it work with xargs is to invoke the shell from xargs.

What is content-type and datatype in an AJAX request?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

If you're posting something like:

{"name":"John Doe"}

and expecting back:

{"success":true}

Then you should have:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

If you're expecting the following:

<div>SUCCESS!!!</div>

Then you should do:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

One more - if you want to post:

name=John&age=34

Then don't stringify the data, and do:

var data = {"name":"John", "age": 34}
$.ajax({
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.

Simulating ENTER keypress in bash script

echo -ne '\n' | <yourfinecommandhere>

or taking advantage of the implicit newline that echo generates (thanks Marcin)

echo | <yourfinecommandhere>

Now we can simply use the --sk option:

--sk, --skip-keypress Don't wait for a keypress after each test

i.e. sudo rkhunter --sk --checkall

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

How to print third column to last column?

...or a simpler solution: cut -f 3- INPUTFILE just add the correct delimiter (-d) and you got the same effect.

how to find my angular version in my project?

For Angular 2+ you can run this in the console:

document.querySelector('[ng-version]').getAttribute('ng-version')

For AngularJS 1.x:

angular.version.full

How do I add a foreign key to an existing SQLite table?

You can try this:

ALTER TABLE [Child] ADD COLUMN column_name INTEGER REFERENCES parent_table_name(column_id);

MySQL timezone change?

issue the command:

SET time_zone = 'America/New_York';

(Or whatever time zone GMT+1 is.: http://www.php.net/manual/en/timezones.php)

This is the command to set the MySQL timezone for an individual client, assuming that your clients are spread accross multiple time zones.

This command should be executed before every SQL command involving dates. If your queries go thru a class, then this is easy to implement.

@Resource vs @Autowired

When you analyze critically from the base classes of these two annotations.You will realize the following differences.

@Autowired uses AutowiredAnnotationBeanPostProcessor to inject dependencies.
@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies.

Even though they use different post processor classes they all behave nearly identically. The differences critically lie in their execution paths, which I have highlighted below.

@Autowired / @Inject

1.Matches by Type
2.Restricts by Qualifiers
3.Matches by Name

@Resource

1.Matches by Name
2.Matches by Type
3.Restricts by Qualifiers (ignored if match is found by name)

Creating a static class with no instances

The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.

That is, the Pythonic way would be:

# My module
elements = []

def add_element(x):
  elements.append(x)

But if you want to mirror the structure of Java, you can do:

# My module
class World(object):
  elements = []

  @staticmethod
  def add_element(x):
    World.elements.append(x)

You can also do this with @classmethod if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):

# My module
class World(object):
  elements = []

  @classmethod
  def add_element(cls, x):
    cls.elements.append(x)

How do I crop an image in Java?

There are two potentially major problem with the leading answer to this question. First, as per the docs:

public BufferedImage getSubimage(int x, int y, int w, int h)

Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.

Essentially, what this means is that result from getSubimage acts as a pointer which points at a subsection of the original image.

Why is this important? Well, if you are planning to edit the subimage for any reason, the edits will also happen to the original image. For example, I ran into this problem when I was using the smaller image in a separate window to zoom in on the original image. (kind of like a magnifying glass). I made it possible to invert the colors to see certain details more easily, but the area that was "zoomed" also got inverted in the original image! So there was a small section of the original image that had inverted colors while the rest of it remained normal. In many cases, this won't matter, but if you want to edit the image, or if you just want a copy of the cropped section, you might want to consider a method.

Which brings us to the second problem. Fortunately, it is not as big a problem as the first. getSubImage shares the same data array as the original image. That means that the entire original image is still stored in memory. Assuming that by "crop" the image you actually want a smaller image, you will need to redraw it as a new image rather than just get the subimage.

Try this:

BufferedImage img = image.getSubimage(startX, startY, endX, endY); //fill in the corners of the desired crop location here
BufferedImage copyOfImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = copyOfImage.createGraphics();
g.drawImage(img, 0, 0, null);
return copyOfImage; //or use it however you want

This technique will give you the cropped image you are looking for by itself, without the link back to the original image. This will preserve the integrity of the original image as well as save you the memory overhead of storing the larger image. (If you do dump the original image later)

How to tell which row number is clicked in a table?

This would get you the index of the clicked row, starting with one:

_x000D_
_x000D_
$('#thetable').find('tr').click( function(){_x000D_
alert('You clicked row '+ ($(this).index()+1) );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id="thetable">_x000D_
   <tr>_x000D_
      <td>1</td><td>1</td><td>1</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
      <td>2</td><td>2</td><td>2</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
      <td>3</td><td>3</td><td>3</td>_x000D_
   </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

If you want to return the number stored in that first cell of each row:

$('#thetable').find('tr').click( function(){
  var row = $(this).find('td:first').text();
  alert('You clicked ' + row);
});

How to display count of notifications in app launcher icon

I have figured out how this is done for Sony devices.

I've blogged about it here. I've also posted a seperate SO question about this here.


Sony devices use a class named BadgeReciever.

  1. Declare the com.sonyericsson.home.permission.BROADCAST_BADGE permission in your manifest file:

  2. Broadcast an Intent to the BadgeReceiver:

    Intent intent = new Intent();
    
    intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.yourdomain.yourapp.MainActivity");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", "99");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.yourdomain.yourapp");
    
    sendBroadcast(intent);
    
  3. Done. Once this Intent is broadcast the launcher should show a badge on your application icon.

  4. To remove the badge again, simply send a new broadcast, this time with SHOW_MESSAGE set to false:

    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
    

I've excluded details on how I found this to keep the answer short, but it's all available in the blog. Might be an interesting read for someone.

Setting Short Value Java

In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L, D, F to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.

The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:

byte foo = (byte)0;
short bar = (short)0;

In your setLongValue(100L) method call, you don't have to necessarily include the L suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.

VBA test if cell is in a range

Here is another option to see if a cell exists inside a range. In case you have issues with the Intersect solution as I did.

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then
    'The individual cell exists in the named range
Else
    'The individual cell does not exist in the named range
End If

InStr is a VBA function that checks if a string exists within another string.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

How can I run a windows batch file but hide the command window?

To self-hide already running script you'll need getCmdPid.bat and windowoMode.bat

@echo off

echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode hidden

echo --other commands--
pause

Here I've compiled all ways that I know to start a hidden process with batch without external tools.With a ready to use scripts (some of them rich on options) , and all of them form command line.Where is possible also the PID is returned .Used tools are IEXPRESS,SCHTASKS,WScript.Shell,Win32_Process and JScript.Net - but all of them wrapped in a .bat files.

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

Pretty much the same as other snippets on this page but just organizing things up over an function, here we go...

String str=shell_exec("ls -l");

The Class function:

public String shell_exec(String cmd)
       {
       String o=null;
       try
         {
         Process p=Runtime.getRuntime().exec(cmd);
         BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));
         String r;
         while((r=b.readLine())!=null)o+=r;
         }catch(Exception e){o="error";}
       return o;
       }

How to make a website secured with https

@balalakshmi mentioned about the correct authentication settings. Authentication is only half of the problem, the other half is authorization.

If you're using Forms Authentication and standard controls like <asp:Login> there are a couple of things you'll need to do to ensure that only your authenticated users can access secured pages.

In web.config, under the <system.web> section you'll need to disable anonymous access by default:

<authorization>
 <deny users="?" />
</authorization>

Any pages that will be accessed anonymously (such as the Login.aspx page itself) will need to have an override that re-allows anonymous access. This requires a <location> element and must be located at the <configuration> level (outside the <system.web> section), like this:

<!-- Anonymous files -->
<location path="Login.aspx">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Note that you'll also need to allow anonymous access to any style sheets or scripts that are used by the anonymous pages:

<!-- Anonymous folders -->
<location path="styles">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Be aware that the location's path attribute is relative to the web.config folder and cannot have a ~/ prefix, unlike most other path-type configuration attributes.

How to Navigate from one View Controller to another using Swift

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

CSS smooth bounce animation

The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration to suit your needs.

_x000D_
_x000D_
.animated {_x000D_
  -webkit-animation-duration: .5s;_x000D_
  animation-duration: .5s;_x000D_
  -webkit-animation-fill-mode: both;_x000D_
  animation-fill-mode: both;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  0%, 100% {_x000D_
    -webkit-transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    -webkit-transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
@keyframes bounce {_x000D_
  0%, 100% {_x000D_
    transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
.bounce {_x000D_
  -webkit-animation-name: bounce;_x000D_
  animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  background-color: red;_x000D_
  position: relative;_x000D_
  top: 100px;_x000D_
  left: 100px;_x000D_
  border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
  position: relative;_x000D_
  top: 92px;_x000D_
  left: -300px;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
_x000D_
_x000D_


Here is how your original keyframe settings would be interpreted by the browser:

  • At 0% (that is, at 0s or start of animation) - translate by 0px in Y axis.
  • At 20% (that is, at 0.5s of animation) - translate by 0px in Y axis.
  • At 40% (that is, at 1s of animation) - translate by 0px in Y axis.
  • At 50% (that is, at 1.25s of animation) - translate by 5px in Y axis. This results in a gradual upward movement.
  • At 60% (that is, at 1.5s of animation) - translate by 0px in Y axis. This results in a gradual downward movement.
  • At 80% (that is, at 2s of animation) - translate by 0px in Y axis.
  • At 100% (that is, at 2.5s or end of animation) - translate by 0px in Y axis.

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

I've chmoded my keypair to 600 in order to get into my personal instance last night,

And this is the way it is supposed to be.

From the EC2 documentation we have "If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you." The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.

The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.

Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.

Any problems you are having are client side, so be sure to include local OS information with any follow up questions!

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

How to convert all elements in an array to integer in JavaScript?

If you want to convert an Array of digits to a single number just use:

Number(arrayOfDigits.join(''));

Example

const arrayOfDigits = [1,2,3,4,5];

const singleNumber = Number(arrayOfDigits.join(''));

console.log(singleNumber); //12345

How big can a MySQL database get before performance starts to degrade

The database size does matter. If you have more than one table with more than a million records, then performance starts indeed to degrade. The number of records does of course affect the performance: MySQL can be slow with large tables. If you hit one million records you will get performance problems if the indices are not set right (for example no indices for fields in "WHERE statements" or "ON conditions" in joins). If you hit 10 million records, you will start to get performance problems even if you have all your indices right. Hardware upgrades - adding more memory and more processor power, especially memory - often help to reduce the most severe problems by increasing the performance again, at least to a certain degree. For example 37 signals went from 32 GB RAM to 128GB of RAM for the Basecamp database server.

How to enable Ad Hoc Distributed Queries

If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

Clicking submit button of an HTML form by a Javascript code

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click();

Rails 4 - passing variable to partial

Either

render partial: 'user', locals: {size: 30}

Or

render 'user', size: 30

To use locals, you need partial. Without the partial argument, you can just list variables directly (not within locals)

How to insert programmatically a new line in an Excel cell in C#?

Have you tried "\n" I guess, it should work.

Changing navigation bar color in Swift

Swift 4:

Perfectly working code to change the navigation bar appearance at application level.

enter image description here

// MARK: Navigation Bar Customisation

// To change background colour.
UINavigationBar.appearance().barTintColor = .init(red: 23.0/255, green: 197.0/255, blue: 157.0/255, alpha: 1.0)

// To change colour of tappable items.
UINavigationBar.appearance().tintColor = .white

// To apply textAttributes to title i.e. colour, font etc.
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : UIColor.white,
                                                    .font : UIFont.init(name: "AvenirNext-DemiBold", size: 22.0)!]
// To control navigation bar's translucency.
UINavigationBar.appearance().isTranslucent = false

Happy Coding!

How to style icon color, size, and shadow of Font Awesome Icons

http://fortawesome.github.io/Font-Awesome/examples/

<i class="icon-thumbs-up icon-3x main-color"></i>

Here I have defined a global style in my CSS where main-color is a class, in my case it is a light blue hue. I find that using inline styles on Icons with Font Awesome works well, esp in the case when you name your colors semantically, i.e. nav-color if you want a separate color for that, etc.

In this example on their website, and how I have written in my example as well, the newest version of Font Awesome has changed the syntax slightly of adjusting the size.Before it used to be:

icon-xxlarge

where now I have to use:

icon-3x

Of course, this all depends on what version of Font Awesome you have installed on your environment. Hope this helps.

Comparing two input values in a form validation with AngularJS

This module works well for comparing two fields. Works great with Angular 1.3+. Simple to use https://www.npmjs.com/package/angular-password

It also allows saving the module as a generic. Just include them in packages list of your module.

Javascript Src Path

src="/clock.js"

be careful it's root of the domain.

P.S. and please use lowercase for attribute names.

Bootstrap 3: Text overlay on image

Set the position to absolute; to move the caption area in the correct position

CSS

.post-content {
    background: none repeat scroll 0 0 #FFFFFF;
    opacity: 0.5;
    margin: -54px 20px 12px; 
    position: absolute;
}

Bootply

How to display an alert box from C# in ASP.NET?

Hey Try This Code.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Data has been saved", true);

Cheers

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

Why should you use strncpy instead of strcpy?

What you're looking for is the function strlcpy() which does terminate always the string with 0 and initializes the buffer. It also is able to detect overflows. Only problem, it's not (really) portable and is present only on some systems (BSD, Solaris). The problem with this function is that it opens another can of worms as can be seen by the discussions on http://en.wikipedia.org/wiki/Strlcpy

My personal opinion is that it is vastly more useful than strncpy() and strcpy(). It has better performance and is a good companion to snprintf(). For platforms which do not have it, it is relatively easy to implement. (for the developement phase of a application I substitute these two function (snprintf() and strlcpy()) with a trapping version which aborts brutally the program on buffer overflows or truncations. This allows to catch quickly the worst offenders. Especially if you work on a codebase from someone else.

EDIT: strlcpy() can be implemented easily:

size_t strlcpy(char *dst, const char *src, size_t dstsize)
{
  size_t len = strlen(src);
  if(dstsize) {
    size_t bl = (len < dstsize-1 ? len : dstsize-1);
    ((char*)memcpy(dst, src, bl))[bl] = 0;
  }
  return len;
}

Pandas index column title or name

If you do not want to create a new row but simply put it in the empty cell then use:

df.columns.name = 'foo'

Otherwise use:

df.index.name = 'foo'

How can I commit files with git?

It looks like all of the edits are already a part of the index. So to commit just use the commit command

git commit -m "My Commit Message"

Looking at your messages though my instinct says that you probably don't want the cache files to be included in your depot. Especially if it something that is built on the fly when running your program. If so then you should add the following line to your .gitignore file

httpdocs/newsite/manifest/cache/*

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

How to combine paths in Java?

Late to the party perhaps, but I wanted to share my take on this. I'm using a Builder pattern and allow conveniently chained append(more) calls, and allows mixing File and String. It can easily be extended to support working with Path objects as well, and furthermore handles the different path separators correctly on both Linux, Macintosh, etc.

public class Files  {
    public static class PathBuilder {
        private File file;

        private PathBuilder ( File root ) {
            file = root;
        }

        private PathBuilder ( String root ) {
            file = new File(root);
        }

        public PathBuilder append ( File more ) {
            file = new File(file, more.getPath()) );
            return this;
        }

        public PathBuilder append ( String more ) {
            file = new File(file, more);
            return this;
        }

        public File buildFile () {
            return file;
        }
    }

    public static PathBuilder buildPath ( File root ) {
        return new PathBuilder(root);
    }

    public static PathBuilder buildPath ( String root ) {
        return new PathBuilder(root);
    }
}

Example of usage:

File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha"; 

File file = Files.buildPath(root).append(hello).append(world)
              .append(filename).buildFile();
String absolute = file.getAbsolutePath();

The resulting absolute will contain something like:

/hello/world/warez.lha

or maybe even:

A:\hello\world\warez.lha

ld.exe: cannot open output file ... : Permission denied

If you think the executable is locked by a process, try Process Explorer from SysInternals. In the File/handle, enter Fibonacci.exe and you should see who holds the file.

If it is not enough, you can use Process Monitor (from SysInternals, again) to follow the activity of all processes on your system on Fibonacci.exe. With a little bit of analysis (call stacks), you'll may find out why the access to the file is denied and what make it disappear.

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

Let's un-complicate Bootstrap!

responsive bootstrap columns

Notice how the col-sm occupies the 100% width (in other terms breaks into new line) below 576px but col doesn't. You can notice the current width at the top center in gif.

Here comes the code:

<div class="container">
    <div class="row">
        <div class="col">col</div>
        <div class="col">col</div>
        <div class="col">col</div>
    </div>
    <div class="row">
        <div class="col-sm">col-sm</div>
        <div class="col-sm">col-sm</div>
        <div class="col-sm">col-sm</div>
    </div>
</div>

Bootstrap by default aligns all the columns(col) in a single row with equal width. In this case three col will occupy 100%/3 width each, whatever the screen size. You can notice that in gif.

Now what if we want to render only one column per line i.e give 100% width to each column but for smaller screens only? Now comes the col-xx classes!

I used col-sm because I wanted to break the columns into separate lines below 576px. These 4 col-xx classes are provided by Bootstrap for different display devices like mobiles, tablets, laptops, large monitors etc.

So,col-sm would break below 576px, col-md would break below 768px, col-lg would break below 992px and col-xl would break below 1200px

Note that there's no col-xs class in bootstrap 4.

Bootstrap Grid System

This pretty much sums-up. You can go back to work.


But there's bit more to it. Now comes the col-* and col-xx-* for customizing width.

Remember in the above example I mentioned that col or col-xx takes the equal width in a row. So if we want to give more width to a specific col we can do this.

Bootstrap row is divided into 12 parts, so in above example there were 3 col so each one takes 12/3 = 4 part. You can consider these parts as a way to measure width.

We could also write that in format col-* i.e. col-4 like this :

<div class="row">
  <div class="col-4">col</div>
  <div class="col-4">col</div>
  <div class="col-4">col</div>
</div>

And it would've made no difference because by default bootstrap gives equal width to col (4 + 4 + 4 = 12).

But, what if we want to give 7 parts to 1st col, 3 parts to 2nd col and rest 2 parts (12-7-3 = 2) to 3rd col (7+3+2 so total is 12), we can simply do this:

<div class="row">
  <div class="col-7">col-7</div>
  <div class="col-3">col-3</div>
  <div class="col-2">col-2</div>
</div>

enter image description here

and you can customize the width of col-xx-* classes also.

<div class="row">
    <div class="col-sm-7">col-sm-7</div>
    <div class="col-sm-3">col-sm-3</div>
    <div class="col-sm-2">col-sm-2</div>
</div>

enter image description here

How does it look in the action?

responsive grid

What if sum of col is more than 12? Then the col will shift/adjust to below line. Yes, there can be any number of columns for a row!

<div class="row">
        <div class="col-12">col-12</div>
        <div class="col-9">col-9</div>
        <div class="col-6">col-6</div>
        <div class="col-6">col-6</div>
    </div>

enter image description here

What if we want 3 columns in a row for large screens but split these columns into 2 rows for small screens?

<div class="row">
    <div class="col-12 col-sm">col-12 col-sm TOP</div>
    <div class="col col-sm">col col-sm</div>
    <div class="col col-sm">col col-sm</div>
</div>

enter image description here

You can play around here: https://jsfiddle.net/JerryGoyal/6vqno0Lm/

Laravel form html with PUT method for PUT routes

in your view blade change to

{{ Form::open(['action' => 'postcontroller@edit', 'method' => 'PUT', 'class' = 'your class here']) }}

<div>
{{ Form::textarea('textareanamehere', 'default value here', ['placeholder' => 'your place holder here', 'class' => 'your class here']) }}
</div>

<div>
{{ Form::submit('Update', ['class' => 'btn class here'])}}
</div>

{{ Form::close() }}

actually you can use raw form like your question. but i dont recomended it. dan itulah salah satu alasan agan belajar framework, simple, dan cepat. so kenapa pake raw form kalo ada yang lebih mudah. hehe. proud to be indonesian.

reference: Laravel Blade Form

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.

Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.

How can I set the color of a selected row in DataGrid

I spent the better part of a day fiddling with this problem. Turned out the RowBackground Property on the DataGrid - which I had set - was overriding all attempts to change it in . As soon as I deleted it, everything worked. (Same goes for Foreground set in DataGridTextColumn, by the way).

Callback function for JSONP with jQuery AJAX

$.ajax({
        url: 'http://url.of.my.server/submit',
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'jsonp_callback'
    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});

Send and receive messages through NSNotificationCenter in Objective-C?

if you're using NSNotificationCenter for updating your view, don't forget to send it from the main thread by calling dispatch_async:

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});

lexical or preprocessor issue file not found occurs while archiving?

For what it's worth, my problem was completely unrelated to the error Xcode was giving. I stumbled onto a solution by deleting the .h reference, compiling, adding the reference back and compiling again. The actual error then became evident.

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is a POSIX standard but not standard C.

How to use __doPostBack()

Here's a brief tutorial on how __doPostBack() works.

To be honest, I don't use it much; at least directly. Many server controls, (e.g., Button, LinkButton, ImageButton, parts of the GridView, etc.) use __doPostBack as their post back mechanism.

POST data to a URL in PHP

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

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/

How to pattern match using regular expression in Scala?

Since version 2.10, one can use Scala's string interpolation feature:

implicit class RegexOps(sc: StringContext) {
  def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}

scala> "123" match { case r"\d+" => true case _ => false }
res34: Boolean = true

Even better one can bind regular expression groups:

scala> "123" match { case r"(\d+)$d" => d.toInt case _ => 0 }
res36: Int = 123

scala> "10+15" match { case r"(\d\d)${first}\+(\d\d)${second}" => first.toInt+second.toInt case _ => 0 }
res38: Int = 25

It is also possible to set more detailed binding mechanisms:

scala> object Doubler { def unapply(s: String) = Some(s.toInt*2) }
defined module Doubler

scala> "10" match { case r"(\d\d)${Doubler(d)}" => d case _ => 0 }
res40: Int = 20

scala> object isPositive { def unapply(s: String) = s.toInt >= 0 }
defined module isPositive

scala> "10" match { case r"(\d\d)${d @ isPositive()}" => d.toInt case _ => 0 }
res56: Int = 10

An impressive example on what's possible with Dynamic is shown in the blog post Introduction to Type Dynamic:

object T {

  class RegexpExtractor(params: List[String]) {
    def unapplySeq(str: String) =
      params.headOption flatMap (_.r unapplySeq str)
  }

  class StartsWithExtractor(params: List[String]) {
    def unapply(str: String) =
      params.headOption filter (str startsWith _) map (_ => str)
  }

  class MapExtractor(keys: List[String]) {
    def unapplySeq[T](map: Map[String, T]) =
      Some(keys.map(map get _))
  }

  import scala.language.dynamics

  class ExtractorParams(params: List[String]) extends Dynamic {
    val Map = new MapExtractor(params)
    val StartsWith = new StartsWithExtractor(params)
    val Regexp = new RegexpExtractor(params)

    def selectDynamic(name: String) =
      new ExtractorParams(params :+ name)
  }

  object p extends ExtractorParams(Nil)

  Map("firstName" -> "John", "lastName" -> "Doe") match {
    case p.firstName.lastName.Map(
          Some(p.Jo.StartsWith(fn)),
          Some(p.`.*(\\w)$`.Regexp(lastChar))) =>
      println(s"Match! $fn ...$lastChar")
    case _ => println("nope")
  }
}

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

What about error messages in use site?

And what about when comes the use case one needs to integrate existing types with a custom one that fits a DSL. One have to be well educated on matters of association, precedence, implicit conversions, implicit parameters, higher kinds, and maybe existential types.

It's very good to know that mostly it's simple but it's not necessarily enough. At least there must be one guy who knows this stuff if widespread library is to be designed.

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

How to close current tab in a browser window?

a bit late but this is what i found out...

window.close() will only work (IE is an exception) if the window that you are trying to close() was opened by a script using window.open() method.

!(please see the comment of @killstreet below about anchor tag with target _blank)

TLDR: chrome & firefox allow to close them.

you will get console error: Scripts may not close windows that were not opened by script. as an error and nothing else.

you could add a unique parameter in the URL to know if the page was opened from a script (like time) - but its just a hack and not a native functionality and will fail in some cases.

i couldn't find any way to know if the page was opened from a open() or not, and close will not throw and errors. this will NOT print "test":

try{
  window.close();
}
catch (e){
  console.log("text");
}

you can read in MDN more about the close() function

Creating a Jenkins environment variable using Groovy

You can also define a variable without the EnvInject Plugin within your Groovy System Script:

import hudson.model.*
def build = Thread.currentThread().executable
def pa = new ParametersAction([
  new StringParameterValue("FOO", "BAR")
])
build.addAction(pa)

Then you can access this variable in the next build step which (for example) is an windows batch command:

@echo off
Setlocal EnableDelayedExpansion
echo FOO=!FOO!

This echo will show you "FOO=BAR".

Regards

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

The original conio.h was implemented by Borland, so its not a part of the C Standard Library nor is defined by POSIX.

But here is an implementation for Linux that uses ncurses to do the job.

Execute a shell script in current shell with sudo permission

I'm not sure if this breaks any rules but

sudo bash script.sh

seems to work for me.

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

How to interpolate variables in strings in JavaScript, without concatenation?

If you like to write CoffeeScript you could do:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript actually IS javascript, but with a much better syntax.

For an overview of CoffeeScript check this beginner's guide.

Spring Boot access static resources missing scr/main/resources

I use spring boot, so i can simple use:

File file = ResourceUtils.getFile("classpath:myfile.xml");

Efficiently test if a port is open on Linux?

nc -l 8000

Where 8000 is the port number. If the port is free, it will start a server that you can close easily. If it isn't it will throw an error:

nc: Address already in use

Using openssl to get the certificate from a server

HOST=gmail-pop.l.google.com
PORT=995

openssl s_client -servername $HOST -connect $HOST:$PORT < /dev/null 2>/dev/null | openssl x509 -outform pem

Changing the git user inside Visual Studio Code

This could be because of the reason that the credentials are saved and you need to update those credentials and you can do that by following the below steps

control panel-> credential manager ->under generic credential you will be able to see the credentials related to git

Try to update them if that does not work delete them and add new ones

for other platforms or different versions of the operating system you need to find out where the credentails are saved related to git and update them.

How to use Python's pip to download and keep the zipped files for a package?

In version 7.1.2 pip downloads the wheel of a package (if available) with the following:

pip install package -d /path/to/downloaded/file

The following downloads a source distribution:

pip install package -d /path/to/downloaded/file --no-binary :all:

These download the dependencies as well, if pip is aware of them (e.g., if pip show package lists them).


Update

As noted by Anton Khodak, pip download command is preferred since version 8. In the above examples this means that /path/to/downloaded/file needs to be given with option -d, so replacing install with download works.

Is it not possible to define multiple constructors in Python?

For the example you gave, use default values:

class City:
    def __init__(self, name="Default City Name"):
        ...
    ...

In general, you have two options:

1) Do if-elif blocks based on the type:

def __init__(self, name):
    if isinstance(name, str):
        ...
    elif isinstance(name, City):
        ...
    ...

2) Use duck typing --- that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.

Getting around the Max String size in a vba function?

Couldn't you just have another sub that acts as a caller using module level variable(s) for the arguments you want to pass. For example...

Option Explicit
Public strMsg As String

Sub Scheduler()

    strMsg = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    Application.OnTime Now + TimeValue("00:00:01"), "'Caller'"

End Sub

Sub Caller()

    Call aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa("It Works! " & strMsg)

End Sub

Sub aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(strMessage As String)

    MsgBox strMessage

End Sub

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Apparently this error has multiple causes. Here's what fixed it for me.

I was running the build command like this:

./gradlew :testapp: build

Running it without the space fixed the issue:

./gradlew :testapp:build

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

If you don't have permissions to change your default DB you could manually select a different DB at the top of your queries...

USE [SomeOtherDb]
SELECT 'I am now using a different DB'

Will work as long as you have permission to the other DB

Rails select helper - Default selected value, how?

If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)

logger.warn("f #{f.object.inspect}")

so, use the following script to get the proper selected option:

:selected => f.object.your_field 

What is reflection and why is it useful?

As per my understanding:

Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection.

It is frequently used in scenarios where a class name changes frequently. If such a situation arises, then it is complicated for the programmer to rewrite the application and change the name of the class again and again.

Instead, by using reflection, there is need to worry about a possibly changing class name.

Pass a reference to DOM object with ng-click

While you do the following, technically speaking:

<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
  //reference to the button that triggered the function:
  $event.target
};

This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.

You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796

How can I get a resource "Folder" from inside my jar File?

This link tells you how.

The magic is the getResourceAsStream() method :

InputStream is = 
this.getClass().getClassLoader().getResourceAsStream("yourpackage/mypackage/myfile.xml")

How do I group Windows Form radio buttons?

Look at placing your radio buttons in a GroupBox.

Alternative to Intersect in MySQL

AFAIR, MySQL implements INTERSECT through INNER JOIN.

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

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

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

How to redirect and append both stdout and stderr to a file with Bash?

Try this

You_command 1>output.log  2>&1

Your usage of &>x.file does work in bash4. sorry for that : (

Here comes some additional tips.

0, 1, 2...9 are file descriptors in bash.

0 stands for stdin, 1 stands for stdout, 2 stands for stderror. 3~9 is spare for any other temporary usage.

Any file descriptor can be redirected to other file descriptor or file by using operator > or >>(append).

Usage: <file_descriptor> > <filename | &file_descriptor>

Please reference to http://www.tldp.org/LDP/abs/html/io-redirection.html

typeof operator in C

It is a C extension from the GCC compiler , see http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

How to convert hashmap to JSON object in Java

For those using org.json.simple.JSONObject, you could convert the map to Json String and parse it to get the JSONObject.

JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));

How can I "reset" an Arduino board?

Try the following:

  1. Prepare the basic empty program (empty setup, loop, etc.)
  2. Compile it.
  3. Reset the Arduino using the hardware button on the chip
  4. Press Ctrl + U to upload your code.
  5. If unsuccessful - got to 3.

There is a delay before the boot loader starts the programs, just work on your timing. It worked for me when a bug in my Arduino's code was executing a soft reset every 500 ms.

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

in my case my arraylist trhows me that error with the JSONObject , but i fin this solution for my array of String objects

List<String> listStrings= new ArrayList<String>();
String json = new Gson().toJson(listStrings);
return json;

Works like charm with angular Gson version 2.8.5

How to loop through all enum values in C#?

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    ...
}

MySQL's now() +1 day

INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);

how to print an exception using logger?

You should probably clarify which logger are you using.

org.apache.commons.logging.Log interface has method void error(Object message, Throwable t) (and method void info(Object message, Throwable t)), which logs the stack trace together with your custom message. Log4J implementation has this method too.

So, probably you need to write:

logger.error("BOOM!", e);

If you need to log it with INFO level (though, it might be a strange use case), then:

logger.info("Just a stack trace, nothing to worry about", e);

Hope it helps.

What's the difference between Sender, From and Return-Path?

A minor update to this: a sender should never set the Return-Path: header. There's no such thing as a Return-Path: header for a message in transit. That header is set by the MTA that makes final delivery, and is generally set to the value of the 5321.From unless the local system needs some kind of quirky routing.

It's a common misunderstanding because users rarely see an email without a Return-Path: header in their mailboxes. This is because they always see delivered messages, but an MTA should never see a Return-Path: header on a message in transit. See http://tools.ietf.org/html/rfc5321#section-4.4

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

How to compress a String in Java?

Your friend is correct. Both gzip and ZIP are based on DEFLATE. This is a general purpose algorithm, and is not intended for encoding small strings.

If you need this, a possible solution is a custom encoding and decoding HashMap<String, String>. This can allow you to do a simple one-to-one mapping:

HashMap<String, String> toCompressed, toUncompressed;

String compressed = toCompressed.get(uncompressed);
// ...
String uncompressed = toUncompressed.get(compressed);

Clearly, this requires setup, and is only practical for a small number of strings.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

It is more efficient to use if-return-return or if-else-return?

From a performance point of view, it doesn't matter in Python, and I'd assume the same for every modern language out there.

It really comes down to style and readability. Your second option (if-else block) is more readable than the first, and a lot more readable than the one-liner ternary operation.

A keyboard shortcut to comment/uncomment the select text in Android Studio

if you are findind keyboard shortcuts for Fix doc comment like this:

/**
 * ...
 */

you can do it by useing Live Template(setting - editor - Live Templates - add)

/**
 * $comment$
 */

What is the correct way to write HTML using Javascript?

Perhaps a good idea is to use jQuery in this case. It provides handy functionality and you can do things like this:

$('div').html('<b>Test</b>');

Take a look at http://docs.jquery.com/Attributes/html#val for more information.

Set Icon Image in Java

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

e.g.,

// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);

// use icon here
game.frame.setIconImage(myImg);

How to configure Spring Security to allow Swagger URL to be accessed without authentication

I had the same problem using Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0. And I solved the problem using the following security configuration that allows public access to Swagger UI resources.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- Swagger UI v2
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",
            // -- Swagger UI v3 (OpenAPI)
            "/v3/api-docs/**",
            "/swagger-ui/**"
            // other public endpoints of your API may be appended to this array
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                // ... here goes your custom security configuration
                authorizeRequests().
                antMatchers(AUTH_WHITELIST).permitAll().  // whitelist Swagger UI resources
                // ... here goes your custom security configuration
                antMatchers("/**").authenticated();  // require authentication for any endpoint that's not whitelisted
    }

}

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

Where to find htdocs in XAMPP Mac

There are two ways to find it:

One way is to open Finder>Applications>XAMPP(FolderNotTheInstaller)>htdocs

Another way is cmd+space and searches for manager-osx,

go to Welcome and click the Open Application Folder.

enter image description here

What are unit tests, integration tests, smoke tests, and regression tests?

Everyone will have slightly different definitions, and there are often grey areas. However:

  • Unit test: does this one little bit (as isolated as possible) work?
  • Integration test: do these two (or more) components work together?
  • Smoke test: does this whole system (as close to being a production system as possible) hang together reasonably well? (i.e. are we reasonably confident it won't create a black hole?)
  • Regression test: have we inadvertently re-introduced any bugs we'd previously fixed?

Calculate date from week number

One of the biggest problems I found was to convert from weeks to dates, and then from dates to weeks.

The main problem is when trying to get the correct week year from a date that belongs to a week of the previous year. Luckily System.Globalization.ISOWeek.GetYear handles this.

Here is my solution:

public class WeekOfYear
{
    public static (int Year, int Week) DateToWeekOfYear(DateTime date) =>
        (ISOWeek.GetYear(date), ISOWeek.GetWeekOfYear(date));

    public static bool ValidYearAndWeek(int year, int week) =>
           year >= 1 && year <= 9999 && week >= 1 && week <= 53 // bounds of year/week
        && !(year <= 1 && week <= 1) && !(year >= 9999 && week >= 53); // bounds of DateTime

    public int Year { get; }
    public int Week { get; }
    public virtual DateTime StartOfWeek { get; protected set; }
    public virtual DateTime EndOfWeek { get; protected set; }

    public virtual IEnumerable<DateTime> DaysInWeek =>
        Enumerable.Range(1, 10).Select(i => StartOfWeek.AddDays(i));

    public WeekOfYear(int year, int week)
    {
        if (!ValidYearAndWeek(year, week))
            throw new ArgumentException($"DateTime can't represent {week} of year {year}.");

        Year = year;
        Week = week;
        StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday);
        EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddDays(1).AddTicks(-1);
    }

    public WeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
    public WeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}

The second biggest problem was the preference for weeks starting on Sundays in the US.

The solution I cam up with subclasses WeekOfYear from above, and manages the offset of the in the constructor (which converts week to dates) and DateToWeekOfYear (which converts from date to week).

public class UsWeekOfYear : WeekOfYear
{
    public static new (int Year, int Week) DateToWeekOfYear(DateTime date)
    {
        // if date is a sunday, return the next week
        if (date.DayOfWeek == DayOfWeek.Sunday) date = date.AddDays(1);
        return WeekOfYear.DateToWeekOfYear(date);
    }

    public UsWeekOfYear(int year, int week) : base(year, week)
    {
        StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday).AddDays(-1);
        EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddTicks(-1);
    }

    public UsWeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
    public UsWeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}

Here is some test code:

public static void Main(string[] args)
{
    Console.WriteLine("== Last Week / First Week");
    Log(new WeekOfYear(2020, 53));
    Log(new UsWeekOfYear(2020, 53));

    Log(new WeekOfYear(2021, 1));
    Log(new UsWeekOfYear(2021, 1));

    Console.WriteLine("\n== Year Crossover (iso)");
    var start = new DateTime(2020, 12, 26);
    var i = 0;
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed

    Console.WriteLine("\n== Year Crossover (us)");
    i = 0;
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed

    var x = new UsWeekOfYear(2020, 53) as WeekOfYear;
}

public static void Log(WeekOfYear week)
{
    Console.WriteLine($"{week} - {week.StartOfWeek:yyyy-MM-dd} ({week.StartOfWeek:ddd}) - {week.EndOfWeek:yyyy-MM-dd} ({week.EndOfWeek:ddd})");
}

public static void Log(DateTime date, WeekOfYear week)
{
    Console.WriteLine($"{date:yyyy-MM-dd (ddd)} - {week} - {week.StartOfWeek:yyyy-MM-dd (ddd)} - {week.EndOfWeek:yyyy-MM-dd (ddd)}");
}

CSS customized scroll bar in div

I tried a lot of plugins, most of them don't support all browsers, I prefer iScroll and nanoScroller works for all these browsers :

  • IE11 -> IE6
  • IE10 - WP8
  • IE9 - WP7
  • IE Xbox One
  • IE Xbox 360
  • Google Chrome
  • FireFox
  • Opera
  • Safari

But iScroll do not work with touch!

demo iScroll : http://lab.cubiq.org/iscroll/examples/simple/
demo nanoScroller : http://jamesflorentino.github.io/nanoScrollerJS/

scrollIntoView Scrolls just too far

So, perhaps this is a bit clunky but so far so good. Im working in angular 9.

file .ts

scroll(el: HTMLElement) {
  el.scrollIntoView({ block: 'start',  behavior: 'smooth' });   
}

file .html

<button (click)="scroll(target)"></button>
<div  #target style="margin-top:-50px;padding-top: 50px;" ></div>

I adjust the offset with margin and padding top.

Saludos!

Android and setting width and height programmatically in dp units

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

Ant is using wrong java version

Use the following 2 properties for javac tag:

fork="yes"  
executable="full-path-to-the-javac-you-want-to-use".

Explaination of the properties can be found here

how to mysqldump remote db from local machine

As I haven't seen it at serverfault yet, and the answer is quite simple:

Change:

ssh -f -L3310:remote.server:3306 [email protected] -N

To:

ssh -f -L3310:localhost:3306 [email protected] -N

And change:

mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name

To:

mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name

(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)

edit: well, to elaborate: if host is set to localhost, a configured (or default) --socket option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Joining Spark dataframes on the key

From https://spark.apache.org/docs/1.5.1/api/java/org/apache/spark/sql/DataFrame.html, use join:

Inner equi-join with another DataFrame using the given column.

PersonDf.join(ProfileDf,$"personId")

OR

PersonDf.join(ProfileDf,PersonDf("personId") === ProfileDf("personId"))

Update:

You can also save the DFs as temp table using df.registerTempTable("tableName") and you can write sql queries using sqlContext.

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

What is the purpose of Order By 1 in SQL select statement?

An example here from a sample test WAMP server database:-

mysql> select * from user_privileges;

| GRANTEE            | TABLE_CATALOG | PRIVILEGE_TYPE          | IS_GRANTABLE |
   +--------------------+---------------+-------------------------+--------------+
| 'root'@'localhost' | def           | SELECT                  | YES          |
| 'root'@'localhost' | def           | INSERT                  | YES          |
| 'root'@'localhost' | def           | UPDATE                  | YES          |
| 'root'@'localhost' | def           | DELETE                  | YES          |
| 'root'@'localhost' | def           | CREATE                  | YES          |
| 'root'@'localhost' | def           | DROP                    | YES          |
| 'root'@'localhost' | def           | RELOAD                  | YES          |
| 'root'@'localhost' | def           | SHUTDOWN                | YES          |
| 'root'@'localhost' | def           | PROCESS                 | YES          |
| 'root'@'localhost' | def           | FILE                    | YES          |
| 'root'@'localhost' | def           | REFERENCES              | YES          |
| 'root'@'localhost' | def           | INDEX                   | YES          |
| 'root'@'localhost' | def           | ALTER                   | YES          |
| 'root'@'localhost' | def           | SHOW DATABASES          | YES          |
| 'root'@'localhost' | def           | SUPER                   | YES          |
| 'root'@'localhost' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'localhost' | def           | LOCK TABLES             | YES          |
| 'root'@'localhost' | def           | EXECUTE                 | YES          |
| 'root'@'localhost' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'localhost' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'localhost' | def           | CREATE VIEW             | YES          |
| 'root'@'localhost' | def           | SHOW VIEW               | YES          |
| 'root'@'localhost' | def           | CREATE ROUTINE          | YES          |
| 'root'@'localhost' | def           | ALTER ROUTINE           | YES          |
| 'root'@'localhost' | def           | CREATE USER             | YES          |
| 'root'@'localhost' | def           | EVENT                   | YES          |
| 'root'@'localhost' | def           | TRIGGER                 | YES          |
| 'root'@'localhost' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'127.0.0.1' | def           | SELECT                  | YES          |
| 'root'@'127.0.0.1' | def           | INSERT                  | YES          |
| 'root'@'127.0.0.1' | def           | UPDATE                  | YES          |
| 'root'@'127.0.0.1' | def           | DELETE                  | YES          |
| 'root'@'127.0.0.1' | def           | CREATE                  | YES          |
| 'root'@'127.0.0.1' | def           | DROP                    | YES          |
| 'root'@'127.0.0.1' | def           | RELOAD                  | YES          |
| 'root'@'127.0.0.1' | def           | SHUTDOWN                | YES          |
| 'root'@'127.0.0.1' | def           | PROCESS                 | YES          |
| 'root'@'127.0.0.1' | def           | FILE                    | YES          |
| 'root'@'127.0.0.1' | def           | REFERENCES              | YES          |
| 'root'@'127.0.0.1' | def           | INDEX                   | YES          |
| 'root'@'127.0.0.1' | def           | ALTER                   | YES          |
| 'root'@'127.0.0.1' | def           | SHOW DATABASES          | YES          |
| 'root'@'127.0.0.1' | def           | SUPER                   | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'127.0.0.1' | def           | LOCK TABLES             | YES          |
| 'root'@'127.0.0.1' | def           | EXECUTE                 | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'127.0.0.1' | def           | CREATE VIEW             | YES          |
| 'root'@'127.0.0.1' | def           | SHOW VIEW               | YES          |
| 'root'@'127.0.0.1' | def           | CREATE ROUTINE          | YES          |
| 'root'@'127.0.0.1' | def           | ALTER ROUTINE           | YES          |
| 'root'@'127.0.0.1' | def           | CREATE USER             | YES          |
| 'root'@'127.0.0.1' | def           | EVENT                   | YES          |
| 'root'@'127.0.0.1' | def           | TRIGGER                 | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'::1'       | def           | SELECT                  | YES          |
| 'root'@'::1'       | def           | INSERT                  | YES          |
| 'root'@'::1'       | def           | UPDATE                  | YES          |
| 'root'@'::1'       | def           | DELETE                  | YES          |
| 'root'@'::1'       | def           | CREATE                  | YES          |
| 'root'@'::1'       | def           | DROP                    | YES          |
| 'root'@'::1'       | def           | RELOAD                  | YES          |
| 'root'@'::1'       | def           | SHUTDOWN                | YES          |
| 'root'@'::1'       | def           | PROCESS                 | YES          |
| 'root'@'::1'       | def           | FILE                    | YES          |
| 'root'@'::1'       | def           | REFERENCES              | YES          |
| 'root'@'::1'       | def           | INDEX                   | YES          |
| 'root'@'::1'       | def           | ALTER                   | YES          |
| 'root'@'::1'       | def           | SHOW DATABASES          | YES          |
| 'root'@'::1'       | def           | SUPER                   | YES          |
| 'root'@'::1'       | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'::1'       | def           | LOCK TABLES             | YES          |
| 'root'@'::1'       | def           | EXECUTE                 | YES          |
| 'root'@'::1'       | def           | REPLICATION SLAVE       | YES          |
| 'root'@'::1'       | def           | REPLICATION CLIENT      | YES          |
| 'root'@'::1'       | def           | CREATE VIEW             | YES          |
| 'root'@'::1'       | def           | SHOW VIEW               | YES          |
| 'root'@'::1'       | def           | CREATE ROUTINE          | YES          |
| 'root'@'::1'       | def           | ALTER ROUTINE           | YES          |
| 'root'@'::1'       | def           | CREATE USER             | YES          |
| 'root'@'::1'       | def           | EVENT                   | YES          |
| 'root'@'::1'       | def           | TRIGGER                 | YES          |
| 'root'@'::1'       | def           | CREATE TABLESPACE       | YES          |
| ''@'localhost'     | def           | USAGE                   | NO           |
+--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)

And when it is given additional order by PRIVILEGE_TYPE or can be given order by 3 . Notice the 3rd column (PRIVILEGE_TYPE) getting sorted alphabetically.

mysql> select * from user_privileges order by PRIVILEGE_TYPE;
+--------------------+---------------+-------------------------+--------------+
| GRANTEE            | TABLE_CATALOG | PRIVILEGE_TYPE          | IS_GRANTABLE |
+--------------------+---------------+-------------------------+--------------+
| 'root'@'127.0.0.1' | def           | ALTER                   | YES          |
| 'root'@'::1'       | def           | ALTER                   | YES          |
| 'root'@'localhost' | def           | ALTER                   | YES          |
| 'root'@'::1'       | def           | ALTER ROUTINE           | YES          |
| 'root'@'localhost' | def           | ALTER ROUTINE           | YES          |
| 'root'@'127.0.0.1' | def           | ALTER ROUTINE           | YES          |
| 'root'@'127.0.0.1' | def           | CREATE                  | YES          |
| 'root'@'::1'       | def           | CREATE                  | YES          |
| 'root'@'localhost' | def           | CREATE                  | YES          |
| 'root'@'::1'       | def           | CREATE ROUTINE          | YES          |
| 'root'@'localhost' | def           | CREATE ROUTINE          | YES          |
| 'root'@'127.0.0.1' | def           | CREATE ROUTINE          | YES          |
| 'root'@'::1'       | def           | CREATE TABLESPACE       | YES          |
| 'root'@'localhost' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'::1'       | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'localhost' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'localhost' | def           | CREATE USER             | YES          |
| 'root'@'127.0.0.1' | def           | CREATE USER             | YES          |
| 'root'@'::1'       | def           | CREATE USER             | YES          |
| 'root'@'localhost' | def           | CREATE VIEW             | YES          |
| 'root'@'127.0.0.1' | def           | CREATE VIEW             | YES          |
| 'root'@'::1'       | def           | CREATE VIEW             | YES          |
| 'root'@'127.0.0.1' | def           | DELETE                  | YES          |
| 'root'@'::1'       | def           | DELETE                  | YES          |
| 'root'@'localhost' | def           | DELETE                  | YES          |
| 'root'@'::1'       | def           | DROP                    | YES          |
| 'root'@'localhost' | def           | DROP                    | YES          |
| 'root'@'127.0.0.1' | def           | DROP                    | YES          |
| 'root'@'127.0.0.1' | def           | EVENT                   | YES          |
| 'root'@'::1'       | def           | EVENT                   | YES          |
| 'root'@'localhost' | def           | EVENT                   | YES          |
| 'root'@'127.0.0.1' | def           | EXECUTE                 | YES          |
| 'root'@'::1'       | def           | EXECUTE                 | YES          |
| 'root'@'localhost' | def           | EXECUTE                 | YES          |
| 'root'@'127.0.0.1' | def           | FILE                    | YES          |
| 'root'@'::1'       | def           | FILE                    | YES          |
| 'root'@'localhost' | def           | FILE                    | YES          |
| 'root'@'localhost' | def           | INDEX                   | YES          |
| 'root'@'127.0.0.1' | def           | INDEX                   | YES          |
| 'root'@'::1'       | def           | INDEX                   | YES          |
| 'root'@'::1'       | def           | INSERT                  | YES          |
| 'root'@'localhost' | def           | INSERT                  | YES          |
| 'root'@'127.0.0.1' | def           | INSERT                  | YES          |
| 'root'@'127.0.0.1' | def           | LOCK TABLES             | YES          |
| 'root'@'::1'       | def           | LOCK TABLES             | YES          |
| 'root'@'localhost' | def           | LOCK TABLES             | YES          |
| 'root'@'127.0.0.1' | def           | PROCESS                 | YES          |
| 'root'@'::1'       | def           | PROCESS                 | YES          |
| 'root'@'localhost' | def           | PROCESS                 | YES          |
| 'root'@'::1'       | def           | REFERENCES              | YES          |
| 'root'@'localhost' | def           | REFERENCES              | YES          |
| 'root'@'127.0.0.1' | def           | REFERENCES              | YES          |
| 'root'@'::1'       | def           | RELOAD                  | YES          |
| 'root'@'localhost' | def           | RELOAD                  | YES          |
| 'root'@'127.0.0.1' | def           | RELOAD                  | YES          |
| 'root'@'::1'       | def           | REPLICATION CLIENT      | YES          |
| 'root'@'localhost' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'::1'       | def           | REPLICATION SLAVE       | YES          |
| 'root'@'localhost' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'127.0.0.1' | def           | SELECT                  | YES          |
| 'root'@'::1'       | def           | SELECT                  | YES          |
| 'root'@'localhost' | def           | SELECT                  | YES          |
| 'root'@'127.0.0.1' | def           | SHOW DATABASES          |  YES          |
| 'root'@'::1'       | def           | SHOW DATABASES          | YES          |
| 'root'@'localhost' | def           | SHOW DATABASES          | YES          |
| 'root'@'127.0.0.1' | def           | SHOW VIEW               | YES          |
| 'root'@'::1'       | def           | SHOW VIEW               | YES          |
| 'root'@'localhost' | def           | SHOW VIEW               | YES          |
| 'root'@'localhost' | def           | SHUTDOWN                | YES          |
| 'root'@'127.0.0.1' | def           | SHUTDOWN                | YES          |
| 'root'@'::1'       | def           | SHUTDOWN                | YES          |
| 'root'@'::1'       | def           | SUPER                   | YES          |
| 'root'@'localhost' | def           | SUPER                   | YES          |
| 'root'@'127.0.0.1' | def           | SUPER                   | YES          |
| 'root'@'127.0.0.1' | def           | TRIGGER                 | YES          |
| 'root'@'::1'       | def           | TRIGGER                 | YES          |
| 'root'@'localhost' | def           | TRIGGER                 | YES          |
| 'root'@'::1'       | def           | UPDATE                  | YES          |
| 'root'@'localhost' | def           | UPDATE                  | YES          |
| 'root'@'127.0.0.1' | def           | UPDATE                  | YES          |
| ''@'localhost'     | def           | USAGE                   | NO           |     +--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)

DEFINITIVELY, a long answer and alot of scrolling. Also I struggled hard to pass the output of the queries to a text file. Here is how to do that without using the annoying into outfile thing-

tee E:/sqllogfile.txt;

And when you are done, stop the logging-

tee off;

Hope it adds more clarity.

How to overcome "datetime.datetime not JSON serializable"?

I faced this issue today, I found something called pickle. It's a built-in library for serializing python objects and also load it from a pickle file.

The only difference I found between pickle and json is pickle file is a binary file, where as json is a usual text file.

And It doesn't cause any issues with datetime objects.

RestTemplate: How to send URL and query parameters together

One simple way to do that is:

String url = "http://test.com/Services/rest/{id}/Identifier"

UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));

and then adds the query params.

What's the difference between %s and %d in Python string formatting?

%s is used to hold space for string %d is used to hold space for number

name = "Moses";
age = 23
print("My name is %s am CEO at MoTech Computers " %name)
print("Current am %d years old" %age)
print("So Am %s and am %d years old" %(name,age))

Program output

this video goes deep about that tip https://www.youtube.com/watch?v=4zN5YsuiqMA

How do I get the max and min values from a set of numbers entered?

You just need to keep track of a max value like this:

int maxValue = 0;

Then as you iterate through the numbers, keep setting the maxValue to the next value if it is greater than the maxValue:

if (value > maxValue) {
    maxValue = value;
}

Repeat in the opposite direction for minValue.

c++ Read from .csv file

a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume

getline(file, genero, ' ') ; 

it is newline \n

so change that line to

getline(file, genero); // \n is default delimiter

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

How to remove a web site from google analytics

Here's an updated answer, as of Sept. 2013. This took me awhile to figure out.

  1. Go to the Admin tab.

    enter image description here

  2. In the middle column, select the web property that you want to delete from the dropdown.

    enter image description here

  3. In the right-hand column, click on "View Settings." ("Property Settings" in dec. 2015)

    enter image description here

  4. At the bottom of the next page, select "Delete this view."

    enter image description here

It will warn you that you're about to delete all of the data associated with this property. If you're sure, confirm.

Done!

Remove all non-"word characters" from a String in Java, leaving accented characters?

Use [^\p{L}\p{Nd}]+ - this matches all (Unicode) characters that are neither letters nor (decimal) digits.

In Java:

String resultString = subjectString.replaceAll("[^\\p{L}\\p{Nd}]+", "");

Edit:

I changed \p{N} to \p{Nd} because the former also matches some number symbols like ¼; the latter doesn't. See it on regex101.com.

Select values from XML field in SQL Server 2008

If you are able to wrap your XML in a root element - say then the following is your solution:

DECLARE @PersonsXml XML = '<persons><person><firstName>Jon</firstName><lastName>Johnson</lastName></person>
<person><firstName>Kathy</firstName><lastName>Carter</lastName></person>
<person><firstName>Bob</firstName><lastName>Burns</lastName></person></persons>'

SELECT  b.value('(./firstName/text())[1]','nvarchar(max)') as FirstName, b.value('(./lastName/text())[1]','nvarchar(max)') as LastName
FROM @PersonsXml.nodes('/persons/person') AS a(b)

enter image description here

How can I show a message box with two buttons?

msgbox ("Message goes here",0+16,"Title goes here")

if the user is supposed to make a decision the variable can be added like this.

variable=msgbox ("Message goes here",0+16,"Title goes here")

The numbers in the middle vary what the message box looks like. Here is the list

0 - ok button only

1 - ok and cancel

2 - abort, retry and ignore

3 - yes no and cancel

4 - yes and no

5 - retry and cancel

TO CHANGE THE SYMBOL (RIGHT NUMBER)

16 - critical message icon

32 - warning icon

48 - warning message

64 - info message

DEFAULT BUTTON

0 = vbDefaultButton1 - First button is default

256 = vbDefaultButton2 - Second button is default

512 = vbDefaultButton3 - Third button is default

768 = vbDefaultButton4 - Fourth button is default

SYSTEM MODAL

4096 = System modal, alert will be on top of all applications

Note: There are some extra numbers. You just have to add them to the numbers already there like

msgbox("Hello World", 0+16+0+4096)

from https://www.instructables.com/id/The-Ultimate-VBS-Tutorial/

How can I combine two commits into one commit?

  1. Checkout your branch and count quantity of all your commits.
  2. Open git bash and write: git rebase -i HEAD~<quantity of your commits> (i.e. git rebase -i HEAD~5)
  3. In opened txt file change pick keyword to squash for all commits, except first commit (which is on the top). For top one change it to reword (which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc then save by entering wq! and press enter.
  4. Provide Comment.
  5. Open Git and make "Fetch all" to see new changes.

Done

What’s the best way to reload / refresh an iframe?

Use reload for IE and set src for other browsers. (reload does not work on FF) tested on IE 7,8,9 and Firefox

if(navigator.appName == "Microsoft Internet Explorer"){
    window.document.getElementById('iframeId').contentWindow.location.reload(true);
}else {
    window.document.getElementById('iframeId').src = window.document.getElementById('iframeId').src;
}

RabbitMQ / AMQP: single queue, multiple consumers for same message?

To get the behavior you want, simply have each consumer consume from its own queue. You'll have to use a non-direct exchange type (topic, header, fanout) in order to get the message to all of the queues at once.

Is std::vector copying the objects with a push_back?

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever>.

However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).

How to get the function name from within that function?

I know this is a old question but lately I've been facing some similar issue while trying to decorate some React Component's methods, for debugging purposes. As people already said, arguments.caller and arguments.callee are forbidden in strict mode which is probably enabled by default in your React transpiling. You can either disable it, or I've been able to come up with another hack, because in React all class functions are named, you can actually do this:

Component.prototype.componentWillMount = function componentWillMount() {
    console.log('Callee name: ', this.__proto__.constructor.toString().substr(0,30));
...
}