Programs & Examples On #Conference

Remove all items from a FormArray in Angular

While loop will take long time to delete all items if array has 100's of items. You can empty both controls and value properties of FormArray like below.

clearFormArray = (formArray: FormArray) => { formArray.controls = []; formArray.setValue([]); }

Disable Proximity Sensor during call

I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.

What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.

What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

UL has margin on the left

I don't see any margin or margin-left declarations for #footer-wrap li.

This ought to do the trick:

#footer-wrap ul,
#footer-wrap li {
    margin-left: 0;
    list-style-type: none;
}

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

Hibernate error - QuerySyntaxException: users is not mapped [from users]

Some Linux based MySQL installations require case sensitive. Work around is to apply nativeQuery.

@Query(value = 'select ID, CLUMN2, CLUMN3 FROM VENDOR c where c.ID = :ID', nativeQuery = true)

TCP vs UDP on video stream

While reading the TCP UDP debate I noticed a logical flaw. A TCP packet loss causing a one minute delay that's converted into a one minute buffer cant be correlated to UDP dropping a full minute while experiencing the same loss. A more fair comparison is as follows.

TCP experiences a packet loss. The video is stopped while TCP resend's packets in an attempt to stream mathematically perfect packets. Video is delayed for one minute and picks up where it left off after missing packet makes its destination. We all wait but we know we wont miss a single pixel.

UDP experiences a packet loss. For a second during the video stream a corner of the screen gets a little blurry. No one notices and the show goes on without looking for the lost packets.

Anything that streams gains the most benefits from UDP. The packet loss causing a one minute delay to TCP would not cause a one minute delay to UDP. Considering that most systems use multiple resolution streams making things go blocky when starving for packets, makes even more sense to use UDP.

UDP FTW when streaming.

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

Live Video Streaming with PHP

Same problem/answer here, quoted below

I'm assuming you mean that you want to run your own private video calls, not simply link to Skype calls or similar. You really have 2 options here: host it yourself, or use a hosted solution and integrate it into your product.


Self-Hosted ----------------- This is messy. This can all be accomplished with PHP, but that is probably not the most advisable solution, as it is not the best tool for the job on all sides. Flash is much more efficient at a/v capture and transport on the user end. You can try to do this without flash, but you will have headaches. HTML5 may make your life easier, but if you're shooting for maximum compatibility, flash is the simplest way to go for creating the client. Then, as far as the actual server side that will relay the audio/video, you could write a chat server in php, but you're better off using an open source project, like janenz00's mention of red5, that's already built and interfacing with it through your client (if it doesn't already have one). Or you could homebrew a flash client as mentioned before and hook it up to a flash streaming server on both sides...either way it gets complicated fast, and is beyond my expertise to help you with at all.


Hosted Service ----------------- All in, my recommendation, unless you want to administer a ridiculous setup of many complex servers and failure points is to use a hosted service like UserPlane or similar and offload all the processing and technical work to people who are good at that, and then worry about interfacing with their api and getting their client well integrated into your site. You will be a happier developer if you do.

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

How can I use Google's Roboto font on a website?

You don't really need to do any of this.

  • Go to Google's Web Fonts page
  • search for Roboto in the search box at the top right
  • Select the variants of the font you want to use
  • click 'Select This Font' at the top and choose the weights and character sets you need.

The page will give you a <link> element to include in your pages, and a list of sample font-family rules to use in your CSS.

Using Google's fonts this way guarantees availability, and reduces bandwidth to your own server.

Nested classes' scope?

I think you can simply do:

class OuterClass:
    outer_var = 1

    class InnerClass:
        pass
    InnerClass.inner_var = outer_var

The problem you encountered is due to this:

A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
(...)
A scope defines the visibility of a name within a block.
(...)
The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope. This means that the following will fail:

   class A:  

       a = 42  

       b = list(a + i for i in range(10))

http://docs.python.org/reference/executionmodel.html#naming-and-binding

The above means:
a function body is a code block and a method is a function, then names defined out of the function body present in a class definition do not extend to the function body.

Paraphrasing this for your case:
a class definition is a code block, then names defined out of the inner class definition present in an outer class definition do not extend to the inner class definition.

How do I speed up the gwt compiler?

  • Split your application into multiple modules or entry points and re-compile then only when needed.
  • Analyse your application using the trunk version - which provides the Story of your compile. This may or may not be relevant to the 1.6 compiler but it can indicate what's going on.

Executing an EXE file using a PowerShell script

  1. clone $args
  2. push your args in new array
  3. & $path $args

Demo:

$exePath = $env:NGINX_HOME + '/nginx.exe'
$myArgs = $args.Clone()

$myArgs += '-p'
$myArgs += $env:NGINX_HOME

& $exepath $myArgs

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

How exactly does binary code get converted into letters?

Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.

1 - Convert every 4 binary digits into one hex digit.

Here's a binary to hex conversion chart:

0001 = 1 
0010 = 2 
0011 = 3 
0100 = 4 
0101 = 5
0110 = 6
0111 = 7
1000 = 8

1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f

(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)

Once you know that chart, converting any string of binary digits into a string of hex digits is simple.

For example,

01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex

Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.

(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)

2 - Split the string of hex digits into pairs.

When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.

You would split a hex number like 7340298b392 this into 6 pairs, like this:

7340298b392 = 07 34 02 98 b3 92

(Notice I prepended a 0, since I had an odd number of hex digits.)

That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)

3 - Convert each pair of hex digits into a decimal number.

Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.

For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)

4 - Convert the decimal numbers into ASCII characters.

Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.

So what letter is 68?

68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.

So 68 is 'D'.

You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.


Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that

hex 41 = 'A' 
hex 61 = 'a'

So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.

For example

01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'

(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)

I saw this on a shirt once, and was able to read it in my head:

01000100
01000001
01000100

I did it like this:

01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D

The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.


How did I know right away that 92, b3, and 98 were not letters?

Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.


So that's how you can do it as a human.

How do computer programs do it?

For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.

(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)

How can I get browser to prompt to save password?

The truth is, you can't force the browser to ask. I'm sure the browser has it's own algorithm for guessing if you've entered a username/password, such as looking for an input of type="password" but you cannot set anything to force the browser.

You could, as others suggest, add user information in a cookie. If you do this, you better encrypt it at the least and do not store their password. Perhaps store their username at most.

SQL Error: ORA-01861: literal does not match format string 01861

ORA-01861: literal does not match format string

This happens because you have tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.

You can overcome this issue by carrying out following alteration.

TO_DATE('1989-12-09','YYYY-MM-DD')

As a general rule, if you are using the TO_DATE function, TO_TIMESTAMP function, TO_CHAR function, and similar functions, make sure that the literal that you provide matches the format string that you've specified

Is there a css cross-browser value for "width: -moz-fit-content;"?

At last I fixed it simply using:

display: table;

ValueError: invalid literal for int () with base 10

I found a work around. Python will convert the number to a float. Simply calling float first then converting that to an int will work: output = int(float(input))

Best way to check for nullable bool in a condition expression (if ...)

If you're in a situation where you don't have control over whether part of the condition is checking a nullable value, you can always try the following:

if( someInt == 6 && someNullableBool == null ? false : (bool)someNullableBool){
    //perform your actions if true
}

I know it's not exactly a purist approach putting a ternary in an if statement but it does resolve the issue cleanly.

This is, of course, a manual way of saying GetValueOrDefault(false)

Check if application is installed - Android

    private boolean isAppExist() {

    PackageManager pm = getPackageManager();
    try {
        PackageInfo info = pm.getPackageInfo("com.facebook.katana", PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
    return true;
}




if (isFacebookExist()) {showToast(" Facebook is  install.");}
     else {showToast(" Facebook is not install.");}

fork() child and parent processes

It is printing twice because you are calling printf twice, once in the execution of your program and once in the fork. Try taking your fork() out of the printf call.

What are the differences between a multidimensional array and an array of arrays in C#?

I would like to update on this, because in .NET Core multi-dimensional arrays are faster than jagged arrays. I ran the tests from John Leidegren and these are the results on .NET Core 2.0 preview 2. I increased the dimension value to make any possible influences from background apps less visible.

Debug (code optimalization disabled)
Running jagged 
187.232 200.585 219.927 227.765 225.334 222.745 224.036 222.396 219.912 222.737 

Running multi-dimensional  
130.732 151.398 131.763 129.740 129.572 159.948 145.464 131.930 133.117 129.342 

Running single-dimensional  
 91.153 145.657 111.974  96.436 100.015  97.640  94.581 139.658 108.326  92.931 


Release (code optimalization enabled)
Running jagged 
108.503 95.409 128.187 121.877 119.295 118.201 102.321 116.393 125.499 116.459 

Running multi-dimensional 
 62.292  60.627  60.611  60.883  61.167  60.923  62.083  60.932  61.444  62.974 

Running single-dimensional 
 34.974  33.901  34.088  34.659  34.064  34.735  34.919  34.694  35.006  34.796 

I looked into disassemblies and this is what I found

jagged[i][j][k] = i * j * k; needed 34 instructions to execute

multi[i, j, k] = i * j * k; needed 11 instructions to execute

single[i * dim * dim + j * dim + k] = i * j * k; needed 23 instructions to execute

I wasn't able to identify why single-dimensional arrays were still faster than multi-dimensional but my guess is that it has to do with some optimalization made on the CPU

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

System.Drawing.Image to stream C#

Try the following:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

How to catch a click event on a button?

Change your onCreate to

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

for me this update worked

Python function as a function argument?

def x(a):
    print(a)
    return a

def y(func_to_run, a):
    return func_to_run(a)

y(x, 1)

That I think would be a more proper sample. Now what I wonder is if there is a way to code the function to use within the argument submission to another function. I believe there is in C++, but in Python I am not sure.

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

What should I do when 'svn cleanup' fails?

I hit an issue where following an Update, SVN showed a folder as being conflicted. Strangely, this was only visible through the command line - TortoiseSVN thought it was all fine.

#>svn st
!       my_dir
!       my_dir\sub_dir

svn cleanup, svn revert, svn update and svn resolve were all unsuccessful at fixing this.

I eventually solved the problem as follows:

  • Look in the .svn directory for "sub_dir"
  • Use RC -> Properties to uncheck the 'read only' flag on the entries file
  • Open the entries file and delete the line "unfinished ..." and the corresponding checksum
  • Save, and re-enable the read-only flag
  • Repeat for the my_dir directory

Following that, everything was fine.

Note I didn't have any local changes, so I don't know if you'd be at risk if you did. I didn't use the delete / update method suggested by others - I got into this state by trying that on the my_dir/sub_dir/sub_sub_dir directory (which started with the same symptoms) - so I didn't want to risk making things worse again!

Not quite on-topic, but maybe helpful if someone comes across this post as I did.

How to implement a Map with multiple keys?

Depending on how it will be used, you can either do this with two maps Map<K1, V> and Map<K2, V> or with two maps Map<K1, V> and Map<K2, K1>. If one of the keys is more permanent than the other, the second option may make more sense.

Convert string to integer type in Go?

Here are three ways to parse strings into integers, from fastest runtime to slowest:

  1. strconv.ParseInt(...) fastest
  2. strconv.Atoi(...) still very fast
  3. fmt.Sscanf(...) not terribly fast but most flexible

Here's a benchmark that shows usage and example timing for each function:

package main

import "fmt"
import "strconv"
import "testing"

var num = 123456
var numstr = "123456"

func BenchmarkStrconvParseInt(b *testing.B) {
  num64 := int64(num)
  for i := 0; i < b.N; i++ {
    x, err := strconv.ParseInt(numstr, 10, 64)
    if x != num64 || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkAtoi(b *testing.B) {
  for i := 0; i < b.N; i++ {
    x, err := strconv.Atoi(numstr)
    if x != num || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkFmtSscan(b *testing.B) {
  for i := 0; i < b.N; i++ {
    var x int
    n, err := fmt.Sscanf(numstr, "%d", &x)
    if n != 1 || x != num || err != nil {
      b.Error(err)
    }
  }
}

You can run it by saving as atoi_test.go and running go test -bench=. atoi_test.go.

goos: darwin
goarch: amd64
BenchmarkStrconvParseInt-8      100000000           17.1 ns/op
BenchmarkAtoi-8                 100000000           19.4 ns/op
BenchmarkFmtSscan-8               2000000          693   ns/op
PASS
ok      command-line-arguments  5.797s

Format SQL in SQL Server Management Studio

Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.

While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!

Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)

Use Azure Data Studio if you: [..] Are mostly editing or executing queries.

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

Spring Boot default H2 jdbc connection (and H2 console)

Check spring application.properties

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

here testdb is database defined Make sure h2 console have same value while connecting other wise it will connect to default db

enter image description here

Send email with PHP from html form on submit with the same script

You need to add an action into your form like:

<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
    <!-- All your input for the form here -->
</form>

Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']); does is that it sends your information to the top of your script so you could use it.

How can I disable ARC for a single file in a project?

  1. select project -> targets -> build phases -> compiler sources
  2. select file -> compiler flags
  3. add -fno-objc-arc

CSS: Auto resize div to fit container width

I have updated your jsfiddle and here is CSS changes you need to do:

#content
{
    min-width:700px;
    margin-right: -210px;
    width:100%;
    float:left;
    background-color:AppWorkspace;
}

Check if a user has scrolled to the bottom

To stop repeated alert of Nick's answer

ScrollActivate();

function ScrollActivate() {
    $(window).on("scroll", function () {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
            $(window).off("scroll");
            alert("near bottom!");
        }
    });
}

Counter in foreach loop in C#

Or even more simple if you don't want to use a lot of linq and for some reason don't want to use a for loop.

int i = 0;
foreach(var x in arr)
{
   //Do some stuff
   i++;
}

How to position a table at the center of div horizontally & vertically

To position horizontally center you can say width: 50%; margin: auto;. As far as I know, that's cross browser. For vertical alignment you can try vertical-align:middle;, but it may only work in relation to text. It's worth a try though.

Editing the git commit message in GitHub

No, because the commit message is related with the commit SHA / hash, and if we change it the commit SHA is also changed. The way I used is to create a comment on that commit. I can't think the other way.

List all files from a directory recursively with Java

The fast way to get the content of a directory using Java 7 NIO :

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.nio.file.Path;

...

Path dir = FileSystems.getDefault().getPath( filePath );
DirectoryStream<Path> stream = Files.newDirectoryStream( dir );
for (Path path : stream) {
   System.out.println( path.getFileName() );
}
stream.close();

How to rename a component in Angular CLI?

If you are using VS Code, you can rename the .ts, .html, .css/.scss, .spec.ts files and the IDE will take care of the imports for you. Therefore there will be no complaints from the files that import files from your component (such as app.module.ts). However, you will still have to rename the component name everywhere it is being used.

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Run local python script on remote server

It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,

cat hello.py | ssh [email protected] python -

Run python --help for more info.

Reading settings from app.config or web.config in .NET

Right click on your class library, and choose the "Add References" option from the Menu.

And from the .NET tab, select System.Configuration. This would include the System.Configuration DLL file into your project.

jQuery load more data on scroll

I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.

Function:

function ifViewLoadContent(elem, LoadContent)
    {
            var top_of_element = $(elem).offset().top;
            var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            if(!$(elem).hasClass("ImLoaded"))   {
                $(elem).load(LoadContent).addClass("ImLoaded");
            }
            }
            else {
               return false;
            }
        }

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

To use:

$(window).scroll(function (event) {
        ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
    });

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).

How to create a database from shell command?

Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

Rails params explained?

Params contains the following three groups of parameters:

  1. User supplied parameters
    • GET (http://domain.com/url?param1=value1&param2=value2 will set params[:param1] and params[:param2])
    • POST (e.g. JSON, XML will automatically be parsed and stored in params)
    • Note: By default, Rails duplicates the user supplied parameters and stores them in params[:user] if in UsersController, can be changed with wrap_parameters setting
  2. Routing parameters
    • match '/user/:id' in routes.rb will set params[:id]
  3. Default parameters
    • params[:controller] and params[:action] is always available and contains the current controller and action

How do I get a TextBox to only accept numeric input in WPF?

If you do not want to write a lot of code to do a basic function (I don't know why people make long methods) you can just do this:

  1. Add namespace:

    using System.Text.RegularExpressions;
    
  2. In XAML, set a TextChanged property:

    <TextBox x:Name="txt1" TextChanged="txt1_TextChanged"/>
    
  3. In WPF under txt1_TextChanged method, add Regex.Replace:

    private void txt1_TextChanged(object sender, TextChangedEventArgs e)
    {
        txt1.Text = Regex.Replace(txt1.Text, "[^0-9]+", "");
    }
    

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

JavaScript - cannot set property of undefined

The object stored at d[a] has not been set to anything. Thus, d[a] evaluates to undefined. You can't assign a property to undefined :). You need to assign an object or array to d[a]:

d[a] = [];
d[a]["greeting"] = b;

console.debug(d);

SQL Server 2008 - Case / If statements in SELECT Clause

Just a note here that you may actually be better off having 3 separate SELECTS for reasons of optimization. If you have one single SELECT then the generated plan will have to project all columns col1, col2, col3, col7, col8 etc, although, depending on the value of the runtime @var, only some are needed. This may result in plans that do unnecessary clustered index lookups because the non-clustered index Doesn't cover all columns projected by the SELECT.

On the other hand 3 separate SELECTS, each projecting the needed columns only may benefit from non-clustered indexes that cover just your projected column in each case.

Of course this depends on the actual schema of your data model and the exact queries, but this is just a heads up so you don't bring the imperative thinking mind frame of procedural programming to the declarative world of SQL.

JavaScript equivalent of PHP’s die

This should kind of work like die();

function die(msg = ''){
    if(msg){
        document.getElementsByTagName('html')[0].innerHTML = msg;
    }else{
        document.open();
        document.write(msg);
        document.close();
    }
    throw msg;
}

Make an image follow mouse pointer

by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.

example as below http://jsfiddle.net/BfLAh/1/

_x000D_
_x000D_
$(document).mousemove(function(e) {
  $("#follow").css({
    left: e.pageX,
    top: e.pageY
  });
});
_x000D_
#follow {
  position: absolute;
  text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
_x000D_
_x000D_

updated to follow slowly

http://jsfiddle.net/BfLAh/3/

for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with

-webkit-transform: rotate(-90deg); 
-moz-transform: rotate(-90deg); 

for the speed , you can set the jquery .animation duration to certain amount.

jquery: $(window).scrollTop() but no $(window).scrollBottom()

For the future, I've made scrollBottom into a jquery plugin, usable in the same way that scrollTop is (i.e. you can set a number and it will scroll that amount from the bottom of the page and return the number of pixels from the bottom of the page, or, return the number of pixels from the bottom of the page if no number is provided)

$.fn.scrollBottom = function(scroll){
  if(typeof scroll === 'number'){
    window.scrollTo(0,$(document).height() - $(window).height() - scroll);
    return $(document).height() - $(window).height() - scroll;
  } else {
    return $(document).height() - $(window).height() - $(window).scrollTop();
  }
}
//Basic Usage
$(window).scrollBottom(500);

Search for "does-not-contain" on a DataFrame in pandas

You can use Apply and Lambda to select rows where a column contains any thing in a list. For your scenario :

df[df["col"].apply(lambda x:x not in [word1,word2,word3])]

Bootstrap: Position of dropdown menu relative to navbar item

Not sure about how other people solve this problem or whether Bootstrap has any configuration for this.

I found this thread that provides a solution:

https://github.com/twbs/bootstrap/issues/1411

One of the post suggests the use of

<ul class="dropdown-menu" style="right: 0; left: auto;">

I tested and it works.

Hope to know whether Bootstrap provides config for doing this, not via the above css.

Cheers.

Invalid default value for 'dateAdded'

CURRENT_TIMESTAMP is only acceptable on TIMESTAMP fields. DATETIME fields must be left either with a null default value, or no default value at all - default values must be a constant value, not the result of an expression.

relevant docs: http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html

You can work around this by setting a post-insert trigger on the table to fill in a "now" value on any new records.

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Posed question

Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.

Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.

Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:

Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.

Application-specific question

However, returning to your task, I'd research 2 topics:

  1. metrics commonly used for your specific task - it lets (a) to compare your method with others and understand if you do something wrong, and (b) to not explore this by yourself and reuse someone else's findings;
  2. cost of different errors of your methods - for example, use-case of your application may rely on 4- and 5-star reviewes only - in this case, good metric should count only these 2 labels.

Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:

  1. Accuracy, which is used, e.g. in

Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."

(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.

Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.

(link)

  1. MSE (or, less often, Mean Absolute Error - MAE) - see, for example,

Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).

(link) - they explore both accuracy and MSE, considering the latter to be better

Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.

(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.

Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.

About approaches, not metrics

Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.

How can I escape square brackets in a LIKE clause?

If you would need to escape special characters like '_' (underscore), as it was in my case, and you are not willing/not able to define an ESCAPE clause, you may wish to enclose the special character with square brackets '[' and ']'.

This explains the meaning of the "weird" string '[[]' - it just embraces the '[' character with square brackets, effectively escaping it.

My use case was to specify the name of a stored procedure with underscores in it as a filter criteria for the Profiler. So I've put string '%name[_]of[_]a[_]stored[_]procedure%' in a TextData LIKE field and it gave me trace results I wanted to achieve.

Here is a good example from the documentation: LIKE (Transact-SQL) - Using Wildcard Characters As Literals

Pass variable to function in jquery AJAX success callback

You can't pass parameters like this - the success object maps to an anonymous function with one parameter and that's the received data. Create a function outside of the for loop which takes (data, i) as parameters and perform the code there:

function image_link(data, i) {
   $(data).find("a:contains(.jpg)").each(function(){                                
       new Image().src = url[i] + $(this).attr("href");
   }
}
...
success: function(data){
    image_link(data, i)
}

How to copy a dictionary and only edit the copy

As others have explained, the built-in dict does not do what you want. But in Python2 (and probably 3 too) you can easily create a ValueDict class that copies with = so you can be sure that the original will not change.

class ValueDict(dict):

    def __ilshift__(self, args):
        result = ValueDict(self)
        if isinstance(args, dict):
            dict.update(result, args)
        else:
            dict.__setitem__(result, *args)
        return result # Pythonic LVALUE modification

    def __irshift__(self, args):
        result = ValueDict(self)
        dict.__delitem__(result, args)
        return result # Pythonic LVALUE modification

    def __setitem__(self, k, v):
        raise AttributeError, \
            "Use \"value_dict<<='%s', ...\" instead of \"d[%s] = ...\"" % (k,k)

    def __delitem__(self, k):
        raise AttributeError, \
            "Use \"value_dict>>='%s'\" instead of \"del d[%s]" % (k,k)

    def update(self, d2):
        raise AttributeError, \
            "Use \"value_dict<<=dict2\" instead of \"value_dict.update(dict2)\""


# test
d = ValueDict()

d <<='apples', 5
d <<='pears', 8
print "d =", d

e = d
e <<='bananas', 1
print "e =", e
print "d =", d

d >>='pears'
print "d =", d
d <<={'blueberries': 2, 'watermelons': 315}
print "d =", d
print "e =", e
print "e['bananas'] =", e['bananas']


# result
d = {'apples': 5, 'pears': 8}
e = {'apples': 5, 'pears': 8, 'bananas': 1}
d = {'apples': 5, 'pears': 8}
d = {'apples': 5}
d = {'watermelons': 315, 'blueberries': 2, 'apples': 5}
e = {'apples': 5, 'pears': 8, 'bananas': 1}
e['bananas'] = 1

# e[0]=3
# would give:
# AttributeError: Use "value_dict<<='0', ..." instead of "d[0] = ..."

Please refer to the lvalue modification pattern discussed here: Python 2.7 - clean syntax for lvalue modification. The key observation is that str and int behave as values in Python (even though they're actually immutable objects under the hood). While you're observing that, please also observe that nothing is magically special about str or int. dict can be used in much the same ways, and I can think of many cases where ValueDict makes sense.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

A formula to copy the values from a formula to another column

What about trying with VLOOKUP? The syntax is:

=VLOOKUP(cell you want to copy, range you want to copy, 1, FALSE).

It should do the trick.

Apache error: _default_ virtualhost overlap on port 443

It is highly unlikely that adding NameVirtualHost *:443 is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).

If you're running a relatively stock Apache configuration, you probably have this somewhere:

<VirtualHost _default_:443>

Your best bet is to either:

  • Place your additional SSL configuration into this existing VirtualHost container, or
  • Comment out this entire VirtualHost block and create a new one. Don't forget to include all the relevant SSL options.

ImportError: No module named PyQt4.QtCore

I was having the same error - ImportError: No module named PyQt4.QtGui. Instead of running your python file (which uses PyQt) on the terminal as -

python file_name.py

Run it with sudo privileges -

sudo python file_name.py

This worked for me!

Insert into ... values ( SELECT ... FROM ... )

Both the answers I see work fine in Informix specifically, and are basically standard SQL. That is, the notation:

INSERT INTO target_table[(<column-list>)] SELECT ... FROM ...;

works fine with Informix and, I would expect, all the DBMS. (Once upon 5 or more years ago, this is the sort of thing that MySQL did not always support; it now has decent support for this sort of standard SQL syntax and, AFAIK, it would work OK on this notation.) The column list is optional but indicates the target columns in sequence, so the first column of the result of the SELECT will go into the first listed column, etc. In the absence of the column list, the first column of the result of the SELECT goes into the first column of the target table.

What can be different between systems is the notation used to identify tables in different databases - the standard has nothing to say about inter-database (let alone inter-DBMS) operations. With Informix, you can use the following notation to identify a table:

[dbase[@server]:][owner.]table

That is, you may specify a database, optionally identifying the server that hosts that database if it is not in the current server, followed by an optional owner, dot, and finally the actual table name. The SQL standard uses the term schema for what Informix calls the owner. Thus, in Informix, any of the following notations could identify a table:

table
"owner".table
dbase:table
dbase:owner.table
dbase@server:table
dbase@server:owner.table

The owner in general does not need to be quoted; however, if you do use quotes, you need to get the owner name spelled correctly - it becomes case-sensitive. That is:

someone.table
"someone".table
SOMEONE.table

all identify the same table. With Informix, there's a mild complication with MODE ANSI databases, where owner names are generally converted to upper-case (informix is the exception). That is, in a MODE ANSI database (not commonly used), you could write:

CREATE TABLE someone.table ( ... )

and the owner name in the system catalog would be "SOMEONE", rather than 'someone'. If you enclose the owner name in double quotes, it acts like a delimited identifier. With standard SQL, delimited identifiers can be used many places. With Informix, you can use them only around owner names -- in other contexts, Informix treats both single-quoted and double-quoted strings as strings, rather than separating single-quoted strings as strings and double-quoted strings as delimited identifiers. (Of course, just for completeness, there is an environment variable, DELIMIDENT, that can be set - to any value, but Y is safest - to indicate that double quotes always surround delimited identifiers and single quotes always surround strings.)

Note that MS SQL Server manages to use [delimited identifiers] enclosed in square brackets. It looks weird to me, and is certainly not part of the SQL standard.

How to increase scrollback buffer size in tmux?

This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.

tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000

This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.

I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:

#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000

Using Python's os.path, how do I go up one directory?

From the current file path you could use:

os.path.join(os.path.dirname(__file__),'..','img','banner.png')

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Just use

filter_input(INPUT_METHOD_NAME, 'var_name') instead of $_INPUT_METHOD_NAME['var_name'] filter_input_array(INPUT_METHOD_NAME) instead of $_INPUT_METHOD_NAME

e.g

    $host= filter_input(INPUT_SERVER, 'HTTP_HOST');
    echo $host;

instead of

    $host= $_SERVER['HTTP_HOST'];
    echo $host;

And use

    var_dump(filter_input_array(INPUT_SERVER));

instead of

    var_dump($_SERVER);

N.B: Apply to all other Super Global variable

How to pass multiple checkboxes using jQuery ajax post

The following from Paul Tarjan worked for me,

var data = { 'user_ids[]' : []};
$(":checked").each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,

var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

Just change name_of_your_form to the name of your form.

I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,

<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>

This way if no boxes are checked, it will still set the array with a value of "none".

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

i solve by way nuget. the first you install nuget. the second you use.
illustration follow:

third : Check to see if this is the latest version by looking at the "Version" property.

The finaly : you check project have latest version again.

How do I initialize the base (super) class?

Both

SuperClass.__init__(self, x)

or

super(SubClass,self).__init__( x )

will work (I prefer the 2nd one, as it adheres more to the DRY principle).

See here: http://docs.python.org/reference/datamodel.html#basic-customization

How do I create a crontab through a script

Cron jobs usually are stored in a per-user file under /var/spool/cron

The simplest thing for you to do is probably just create a text file with the job configured, then copy it to the cron spool folder and make sure it has the right permissions (600).

How can I change the Java Runtime Version on Windows (7)?

If you are using windows 10 or windows server 2012, the steps to change the java runtime version is this:

  1. Open regedit using 'Run'
  2. Navigate to HKEY_LOCAL_MACHINE -> SOFTWARE -> JavaSoft -> Java Runtime Environment
  3. Here you will see all the versions of java you installed on your PC. For me I have several versions of java 1.8 installed, so the folder displayed here are 1.8, 1.8.0_162 and 1.8.0_171
  4. Click the '1.8' folder, then double click the JavaHome and RuntimeLib keys, Change the version number inside to whichever Java version you want your PC to run on. For example, if the Value data of the key is 'C:\Program Files\Java\jre1.8.0_171', you can change this to 'C:\Program Files\Java\jre1.8.0_162'.
  5. You can then verify the version change by typing 'java -version' on the command line.

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

In order to keep leading zeroes, here is a small variation on what has Paul suggested (eg md5 hash):

public static String MD5hash(String text) throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance("MD5").digest(text.getBytes());
    return String.format("%032x",new BigInteger(1, hash));
}

Oops, this looks poorer than what's Ayman proposed, sorry for that

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

To bypass google's check, which is what you really want, simply remove the extensions from the file when you send it, and add them back after you download it. For example:

  • tar czvf file.tar.gz directory
  • mv file.tar.gz filetargz
  • [send filetargz via gmail]
  • [download filetargz]
  • [rename filetargz to file.tar.gz and open]

How to trigger button click in MVC 4

as per @anaximander s answer but your signup action should look more like

    [HttpPost]
    public ActionResult SignUp(Account account)
    {
        if(ModelState.IsValid){
            //do something with account
            return RedirectToAction("Index"); 
        }
        return View("SignUp");
    }

Stop Excel from automatically converting certain text values to dates

I know this is an old question, but the problem is not going away soon. CSV files are easy to generate from most programming languages, rather small, human-readable in a crunch with a plain text editor, and ubiquitous.

The problem is not only with dates in text fields, but anything numeric also gets converted from text to numbers. A couple of examples where this is problematic:

  • ZIP/postal codes
  • telephone numbers
  • government ID numbers

which sometimes can start with one or more zeroes (0), which get thrown away when converted to numeric. Or the value contains characters that can be confused with mathematical operators (as in dates: /, -).

Two cases that I can think of that the "prepending =" solution, as mentioned previously, might not be ideal is

  • where the file might be imported into a program other than MS Excel (MS Word's Mail Merge function comes to mind),
  • where human-readability might be important.

My hack to work around this

If one pre/appends a non-numeric and/or non-date character in the value, the value will be recognized as text and not converted. A non-printing character would be good as it will not alter the displayed value. However, the plain old space character (\s, ASCII 32) doesn't work for this as it gets chopped off by Excel and then the value still gets converted. But there are various other printing and non-printing space characters that will work well. The easiest however is to append (add after) the simple tab character (\t, ASCII 9).

Benefits of this approach:

  • Available from keyboard or with an easy-to-remember ASCII code (9),
  • It doesn't bother the importation,
  • Normally does not bother Mail Merge results (depending on the template layout - but normally it just adds a wide space at the end of a line). (If this is however a problem, look at other characters e.g. the zero-width space (ZWSP, Unicode U+200B)
  • is not a big hindrance when viewing the CSV in Notepad (etc),
  • and could be removed by find/replace in Excel (or Notepad etc).
  • You don't need to import the CSV, but can simply double-click to open the CSV in Excel.

If there's a reason you don't want to use the tab, look in an Unicode table for something else suitable.

Another option

might be to generate XML files, for which a certain format also is accepted for import by newer MS Excel versions, and which allows a lot more options similar to .XLS format, but I don't have experience with this.

So there are various options. Depending on your requirements/application, one might be better than another.


Addition

It needs to be said that newer versions (2013+) of MS Excel don't open the CSV in spreadsheet format any more - one more speedbump in one's workflow making Excel less useful... At least, instructions exist for getting around it. See e.g. this Stackoverflow: How to correctly display .csv files within Excel 2013? .

Run php script as daemon process

I run a large number of PHP daemons.

I agree with you that PHP is not the best (or even a good) language for doing this, but the daemons share code with the web-facing components so overall it is a good solution for us.

We use daemontools for this. It is smart, clean and reliable. In fact we use it for running all of our daemons.

You can check this out at http://cr.yp.to/daemontools.html.

EDIT: A quick list of features.

  • Automatically starts the daemon on reboot
  • Automatically restart dameon on failure
  • Logging is handled for you, including rollover and pruning
  • Management interface: 'svc' and 'svstat'
  • UNIX friendly (not a plus for everyone perhaps)

AngularJS - How to use $routeParams in generating the templateUrl?

I've added support for this in my fork of angular. It allows you to specify

$routeProvider
    .when('/:some/:param/:filled/:url', {
          templateUrl:'/:some/:param/:filled/template.ng.html'
     });

https://github.com/jamie-pate/angular.js/commit/dc9be174af2f6e8d55b798209dfb9235f390b934

not sure this will get picked up as it is kind of against the grain for angular, but it is useful to me

How to manipulate arrays. Find the average. Beginner Java

-while(int i=0; i < data.length; i++) 
+for(int i=0; i < data.length; i++) 

Pass multiple values with onClick in HTML link

If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:

<a href=# onclick="return ReAssign(valuationId,user)">Re-Assign</a>

If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:

<?php
    echo '<a href=# onclick="return ReAssign(\'' + $valuationId + '\',\'' + $user + '\')">Re-Assign</a>';
?>

The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:

var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId + '\',\'' + user + '\')">Re-Assign</a> </td>  </tr>');

The moral of the story is

'someString(\''+'otherString'+','+'yetAnotherString'+'\')'

Will get evaluated as:

someString('otherString,yetAnotherString');

Whereas you would need:

someString('otherString','yetAnotherString');

C# Change A Button's Background Color

In WPF, the background is not a Color, it is a Brush. So, try this for starters:

using System.Windows.Media;

// ....

ButtonToday.Background = new SolidColorBrush(Colors.Red);

More sensibly, though, you should probably look at doing this in your Xaml instead of in code.

Remove file from SVN repository without deleting local copy

Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.

Rename your file back.

MySQL and GROUP_CONCAT() maximum length

The correct parameter to set the maximum length is:

SET @@group_concat_max_len = value_numeric;

value_numeric must be > 1024; by default the group_concat_max_len value is 1024.

How to auto resize and adjust Form controls with change in resolution

in the form load event add this line

this.WindowState = FormWindowState.Maximized;

Rounding to 2 decimal places in SQL

Try this...

SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;

Erase whole array Python

Now to answer the question that perhaps you should have asked, like "I'm getting 100 floats form somewhere; do I need to put them in an array or list before I find the minimum?"

Answer: No, if somewhere is a iterable, instead of doing this:

temp = []
for x in somewhere:
   temp.append(x)
answer = min(temp)

you can do this:

answer = min(somewhere)

Example:

answer = min(float(line) for line in open('floats.txt'))

In Perl, how can I read an entire file into a string?

You could simply create a sub-routine:

#Get File Contents
sub gfc
{
    open FC, @_[0];
    join '', <FC>;
}

AngularJS UI Router - change url without reloading state

i did this but long ago in version: v0.2.10 of UI-router like something like this::

$stateProvider
  .state(
    'home', {
      url: '/home',
      views: {
        '': {
          templateUrl: Url.resolveTemplateUrl('shared/partial/main.html'),
          controller: 'mainCtrl'
        },
      }
    })
  .state('home.login', {
    url: '/login',
    templateUrl: Url.resolveTemplateUrl('authentication/partial/login.html'),
    controller: 'authenticationCtrl'
  })
  .state('home.logout', {
    url: '/logout/:state',
    controller: 'authenticationCtrl'
  })
  .state('home.reservationChart', {
    url: '/reservations/?vw',
    views: {
      '': {
        templateUrl: Url.resolveTemplateUrl('reservationChart/partial/reservationChartContainer.html'),
        controller: 'reservationChartCtrl',
        reloadOnSearch: false
      },
      '[email protected]': {
        templateUrl: Url.resolveTemplateUrl('voucher/partial/viewVoucherContainer.html'),
        controller: 'viewVoucherCtrl',
        reloadOnSearch: false
      },
      '[email protected]': {
        templateUrl: Url.resolveTemplateUrl('voucher/partial/voucherContainer.html'),
        controller: 'voucherCtrl',
        reloadOnSearch: false
      }
    },
    reloadOnSearch: false
  })

SQL: How To Select Earliest Row

In this case a relatively simple GROUP BY can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER():

Runnable example (Wofkflow20 error in original data corrected)

;WITH partitioned AS (
    SELECT company
        ,workflow
        ,date
        ,other_columns
        ,ROW_NUMBER() OVER(PARTITION BY company, workflow
                            ORDER BY date) AS seq
    FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1

Changing file extension in Python

os.path.splitext(), os.rename()

for example:

# renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension
pre, ext = os.path.splitext(renamee)
os.rename(renamee, pre + new_extension)

How to find and turn on USB debugging mode on Nexus 4

Navigate to Settings > About Phone > scroll to the bottom > tap Build number seven (7) times. You'll get a short pop-up in the lower area of your display saying that you're now a developer. 2. Go back and now access the Developer options menu, check 'USB debugging' and click OK on the prompt. This Guide Might Help You : How to Enable USB Debugging in Android Phones

How do I check if an element is really visible with JavaScript?

Here is a part of the response that tells you if an element is in the viewport. You may need to check if there is nothing on top of it using elementFromPoint, but it's a bit longer.

function isInViewport(element) {
  var rect = element.getBoundingClientRect();
  var windowHeight = window.innerHeight || document.documentElement.clientHeight;
  var windowWidth = window.innerWidth || document.documentElement.clientWidth;

  return rect.bottom > 0 && rect.top < windowHeight && rect.right > 0 && rect.left < windowWidth;
}

Ignore files that have already been committed to a Git repository

One thing to also keep in mind if .gitignore does not seem to be ignoring untracked files is that you should not have comments on the same line as the ignores. So this is okay

# ignore all foo.txt, foo.markdown, foo.dat, etc.
foo*

But this will not work:

foo*   # ignore all foo.txt, foo.markdown, foo.dat, etc.

.gitignore interprets the latter case as "ignore files named "foo* # ignore all foo.txt, foo.markdown, foo.dat, etc.", which, of course, you don't have.

Rotate and translate

I can't comment so here goes. About @David Storey answer.

Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.

transformation: translate(0,10%) rotate(25deg);

The rotate operation is done first, then the translate.

See: CSS3 transform order matters: rightmost operation first

How to force link from iframe to be opened in the parent window

If you are using iframe in your webpage you might encounter a problem while changing the whole page through a HTML hyperlink (anchor tag) from the iframe. There are two solutions to mitigate this problem.

Solution 1. You can use target attribute of anchor tag as given in the following example.

<a target="_parent" href="http://www.kriblog.com">link</a>

Solution 2. You can also open a new page in parent window from iframe with JavaScript.

<a href="#" onclick="window.parent.location.href='http://www.kriblog.com';">

Remember ? target="_parent" has been deprecated in XHTML, but it is still supported in HTML 5.x.

More can be read from following link http://www.kriblog.com/html/link-of-iframe-open-in-the-parent-window.html

Concatenate two JSON objects

if using TypeScript, you can use the spread operator (...)

var json = {...json1,...json2} 

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

In php, is 0 treated as empty?

Not sure if there are still people looking for an explanation and a solution. The comments above say it all on the differences between TRUE / FALSE / 1 / 0.
I would just like to bring my 2 cents for the way to display the actual value.

BOOLEAN

If you're working with a Boolean datatype, you're looking for a TRUE vs. FALSE result; if you store it in MySQL, it will be stored as 1 resp. 0 (if I'm not mistaking, this is the same in your server's memory).

So to display the the value in PHP, you need to check if it is true (1) or false (0) and display whatever you want: "TRUE" or "FALSE" or possibly "1" or "0".
Attention, everything bigger (or different) than 0 will also be considered as TRUE in PHP. E.g.: 2, "abc", etc. will all return TRUE.

BIT, TINYINT

If you're working with a number datatype, the way it is stored is the same.
To display the value, you need to tell PHP to handle it as a number. The easiest way I found is to multiply it by 1.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

In visual studio, go to help | about and look at the version of Visual Studio that you're using to compile your app.

MessageBox Buttons?

If you actually want Yes and No buttons (and assuming WinForms):

void button_Click(object sender, EventArgs e)
{
    var message = "Yes or No?";
    var title = "Hey!";
    var result = MessageBox.Show(
        message,                  // the message to show
        title,                    // the title for the dialog box
        MessageBoxButtons.YesNo,  // show two buttons: Yes and No
        MessageBoxIcon.Question); // show a question mark icon

    // the following can be handled as if/else statements as well
    switch (result)
    {
    case DialogResult.Yes:   // Yes button pressed
        MessageBox.Show("You pressed Yes!");
        break;
    case DialogResult.No:    // No button pressed
        MessageBox.Show("You pressed No!");
        break;
    default:                 // Neither Yes nor No pressed (just in case)
        MessageBox.Show("What did you press?");
        break;
    }
}

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

AndroidStudio gradle proxy

in gradle.properties file (project root directory)

You must set proxy for http and https

systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=user
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=localhost
systemProp.http.auth.ntlm.domain=domain

systemProp.https.proxyHost=www.somehost.org
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=user
systemProp.https.proxyPassword=password
systemProp.https.nonProxyHosts=localhost
systemProp.https.auth.ntlm.domain=domain

if you set proxy from File -> Settings ->HTTP Proxy(Under IDE Settings) it only define http proxy and does not set https proxy

jQuery append() vs appendChild()

appendChild is a pure javascript method where as append is a jQuery method.

Java: JSON -> Protobuf & back conversion

I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.

Converting protobuf to JSON for storage and then back to protobuf on load is much more likely to create compatibility problems, because:

  • If the process which performs the conversion is not built with the latest version of the protobuf schema, then converting will silently drop any fields that the process doesn't know about. This is true both of the storing and loading ends.
  • Even with the most recent schema available, JSON <-> Protobuf conversion may be lossy in the presence of imprecise floating-point values and similar corner cases.
  • Protobufs actually have (slightly) stronger backwards-compatibility guarantees than JSON. Like with JSON, if you add a new field, old clients will ignore it. Unlike with JSON, Protobufs allow declaring a default value, which can make it somewhat easier for new clients to deal with old data that is otherwise missing the field. This is only a slight advantage, but otherwise Protobuf and JSON have equivalent backwards-compatibility properties, therefore you are not gaining any backwards-compatibility advantages from storing in JSON.

With all that said, there are many libraries out there for converting protobufs to JSON, usually built on the Protobuf reflection interface (not to be confused with the Java reflection interface; Protobuf reflection is offered by the com.google.protobuf.Message interface).

How to capture a list of specific type with mockito

If you're not afraid of old java-style (non type safe generic) semantics, this also works and is simple'ish:

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(subject.method(argument.capture()); // run your code
List<SomeType> list = argument.getValue(); // first captured List, etc.

How to enable multidexing with the new Android Multidex support library

All answers above are awesome

Also add this otherwise your app will crash like mine without any reason

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

Python: Number of rows affected by cursor.execute("SELECT ...)

To get the number of selected rows I usually use the following:

cursor.execute(sql)
count = (len(cursor.fetchall))

ISO C90 forbids mixed declarations and code in C

Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.

location.host vs location.hostname and cross-browser compatibility?

Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com

What you really want is this:

/(^|\.)domain\.com$/

How do I install soap extension?

In ubuntu to install php_soap on PHP7 use below commands. Reference

sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service

For older version of php use below command and restart apache.

apt-get install php-soap

Constant pointer vs Pointer to constant

int i;
int j;

int * const ptr1 = &i;

The compiler will stop you changing ptr1.

const int * ptr2 = &i;

The compiler will stop you changing *ptr2.

ptr1 = &j; // error
*ptr1 = 7; // ok

ptr2 = &j; // ok
*ptr2 = 7; // error

Note that you can still change *ptr2, just not by literally typing *ptr2:

i = 4;
printf("before: %d\n", *ptr2); // prints 4
i = 5;
printf("after: %d\n", *ptr2); // prints 5
*ptr2 = 6; // still an error

You can also have a pointer with both features:

const int * const ptr3 = &i;

ptr3 = &j; // error
*ptr3 = 7; // error

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

git returns http error 407 from proxy after CONNECT

I had the same problem too, and tried to solve it by setting explicitly the http.proxyAuthMethod to basic.

After running a pcap trace between my server and the proxy, i noticed that the " HTTP CONNECT" request sent to the proxy during a git clone still not have a "Proxy-Authorization" header set to basic. This was due to my git version "1.8.3.1" that do not support http.proxyAuthMethod.

After installing a newest git version (2.16.6), using rpm packages foud here "https://repo.ius.io/7/x86_64/packages/g/", setting http.proxyAuthMethod to basic had finally an effect on git behavior and then my git clone was successful.

I hope this helps

How to get the insert ID in JDBC?

You can use following java code to get new inserted id.

ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, quizid);
ps.setInt(2, userid);
ps.executeUpdate();

ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
    lastInsertId = rs.getInt(1);
}

How to log out user from web site using BASIC authentication?

You can do it entirely in JavaScript:

IE has (for a long time) standard API for clearing Basic Authentication cache:

document.execCommand("ClearAuthenticationCache")

Should return true when it works. Returns either false, undefined or blows up on other browsers.

New browsers (as of Dec 2012: Chrome, FireFox, Safari) have "magic" behavior. If they see a successful basic auth request with any bogus other username (let's say logout) they clear the credentials cache and possibly set it for that new bogus user name, which you need to make sure is not a valid user name for viewing content.

Basic example of that is:

var p = window.location.protocol + '//'
// current location must return 200 OK for this GET
window.location = window.location.href.replace(p, p + 'logout:password@')

An "asynchronous" way of doing the above is to do an AJAX call utilizing the logout username. Example:

(function(safeLocation){
    var outcome, u, m = "You should be logged out now.";
    // IE has a simple solution for it - API:
    try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
    // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
    if (!outcome) {
        // Let's create an xmlhttp object
        outcome = (function(x){
            if (x) {
                // the reason we use "random" value for password is 
                // that browsers cache requests. changing
                // password effectively behaves like cache-busing.
                x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                x.send("")
                // x.abort()
                return 1 // this is **speculative** "We are done." 
            } else {
                return
            }
        })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
    }
    if (!outcome) {
        m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
    }
    alert(m)
    // return !!outcome
})(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)

You can make it a bookmarklet too:

javascript:(function(c){var a,b="You should be logged out now.";try{a=document.execCommand("ClearAuthenticationCache")}catch(d){}a||((a=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):void 0)?(a.open("HEAD",c||location.href,!0,"logout",(new Date).getTime().toString()),a.send(""),a=1):a=void 0);a||(b="Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.");alert(b)})(/*pass safeLocation here if you need*/);

How to see docker image contents

EXPLORING DOCKER IMAGE!

  1. Figure out what kind of shell is in there bash or sh...

Inspect the image first: docker inspect name-of-container-or-image

Look for entrypoint or cmd in the JSON return.

  1. Then do: docker run --rm -it --entrypoint=/bin/bash name-of-image

once inside do: ls -lsa or any other shell command like: cd ..

The -it stands for interactive... and TTY. The --rm stands for remove container after run.

If there are no common tools like ls or bash present and you have access to the Dockerfile simple add the common tool as a layer.
example (alpine Linux):

RUN apk add --no-cache bash

And when you don't have access to the Dockerfile then just copy/extract the files from a newly created container and look through them:

docker create <image>  # returns container ID the container is never started.
docker cp <container ID>:<source_path> <destination_path>
docker rm <container ID>
cd <destination_path> && ls -lsah

How to add an existing folder with files to SVN?

I don't use commands. You should be able to do this using the GUI:

  • Right-click an empty space in your My Documents folder, select TortoiseSVN > Repo-browser.
  • Enter http://subversion... (your URL path to your Subversion server/directory you will save to) as your path and select OK
  • Right-click the root directory in Repo and select Add folder. Give it the name of your project and create it.
  • Right-click the project folder in the Repo-browser and select Checkout. The Checkout directory will be your Visual Studio\Projects\{your project} folder. Select OK.
  • You will receive a warning that the folder is not empty. Say Yes to checkout/export to that folder - it will not overwrite your project files.
  • Open your project folder. You will see question marks on folders that are associated with your VS project that have not yet been added to Subversion. Select those folders using Ctrl + Click, then right-click one of the selected items and select TortoiseSVN > Add
  • Select OK on the prompt
  • Your files should add. Select OK on the Add Finished! dialog
  • Right-click in an empty area of the folder and select Refresh. You’ll see “+” icons on the folders/files, now
  • Right-click an empty area in the folder once again and select SVN Commit
  • Add a message regarding what you are committing and click OK

What is the difference between float and double?

Unlike an int (whole number), a float have a decimal point, and so can a double. But the difference between the two is that a double is twice as detailed as a float, meaning that it can have double the amount of numbers after the decimal point.

SQLite - getting number of rows in a database

In SQL, NULL = NULL is false, you usually have to use IS NULL:

SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words

But, if you want the number of rows, you should just use count(id) since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.

If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.

But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.

Android: How to bind spinner to custom object list?

For simple solutions you can just Overwrite the "toString" in your object

public class User{
    public int ID;
    public String name;

    @Override
    public String toString() {
        return name;
    }
}

and then you can use:

ArrayAdapter<User> dataAdapter = new ArrayAdapter<User>(mContext, android.R.layout.simple_spinner_item, listOfUsers);

This way your spinner will show only the user names.

How to add a "confirm delete" option in ASP.Net Gridview?

Try this:

I used for Update and Delete buttons. It doesn't touch Edit button. You can use auto generated buttons.

  protected void gvOperators_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType != DataControlRowType.DataRow) return;
        var updateButton = (LinkButton)e.Row.Cells[0].Controls[0];
        if (updateButton.Text == "Update")
        {
            updateButton.OnClientClick = "return confirm('Do you really want to update?');";
        }
        var deleteButton = (LinkButton)e.Row.Cells[0].Controls[2];
        if (deleteButton.Text == "Delete")
        {
            deleteButton.OnClientClick = "return confirm('Do you really want to delete?');";
        }

    }

What is the difference between up-casting and down-casting with respect to class variable

I know this question asked quite long time ago but for the new users of this question. Please read this article where contains complete description on upcasting, downcasting and use of instanceof operator

  • There's no need to upcast manually, it happens on its own:

    Mammal m = (Mammal)new Cat(); equals to Mammal m = new Cat();

  • But downcasting must always be done manually:

    Cat c1 = new Cat();      
    Animal a = c1;      //automatic upcasting to Animal
    Cat c2 = (Cat) a;    //manual downcasting back to a Cat
    

Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException. This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.

 Cat c1 = new Cat();         
    Animal a = c1;       //upcasting to Animal
    if(a instanceof Cat){ // testing if the Animal is a Cat
        System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");        
        Cat c2 = (Cat)a;
    }

For more information please read this article

What does if __name__ == "__main__": do?

You can checkup for the special variable __name__ with this simple example:

create file1.py

if __name__ == "__main__":
    print("file1 is being run directly")
else:
    print("file1 is being imported")

create file2.py

import file1 as f1

print("__name__ from file1: {}".format(f1.__name__))
print("__name__ from file2: {}".format(__name__))

if __name__ == "__main__":
    print("file2 is being run directly")
else:
    print("file2 is being imported")

Execute file2.py

output:

file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly

EntityType has no key defined error

Using the [key] didn't work for me but using an id property does it. I just add this property in my class.

public int id {get; set;}

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Add at the top:

SET DATEFORMAT ymd; 

or whichever format you are using in your queries

Generating an MD5 checksum of a file

There is a way that's pretty memory inefficient.

single file:

import hashlib
def file_as_bytes(file):
    with file:
        return file.read()

print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()

list of files:

[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:

[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

If you only want 128 bits worth of digest you can do .digest()[:16].

This will give you a list of tuples, each tuple containing the name of its file and its hash.

Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.

Here is a way that is more complex, but memory efficient:

import hashlib

def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
    for block in bytesiter:
        hasher.update(block)
    return hasher.hexdigest() if ashexstr else hasher.digest()

def file_as_blockiter(afile, blocksize=65536):
    with afile:
        block = afile.read(blocksize)
        while len(block) > 0:
            yield block
            block = afile.read(blocksize)


[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
    for fname in fnamelst]

And, again, since MD5 is broken and should not really ever be used anymore:

[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
    for fname in fnamelst]

Again, you can put [:16] after the call to hash_bytestr_iter(...) if you only want 128 bits worth of digest.

How can I listen for a click-and-hold in jQuery?

Try this:

var thumbnailHold;

    $(".image_thumb").mousedown(function() {
        thumbnailHold = setTimeout(function(){
             checkboxOn(); // Your action Here

         } , 1000);
     return false;
});

$(".image_thumb").mouseup(function() {
    clearTimeout(thumbnailHold);
});

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

Retrieve a Fragment from a ViewPager

I implemented this easy with a bit different approach.

My custom FragmentAdapter.getItem method returned not new MyFragment(), but the instance of MyFragment that was created in FragmentAdapter constructor.

In my activity I then got the fragment from the adapter, check if it is instanceOf needed Fragment, then cast and use needed methods.

Can I set text box to readonly when using Html.TextBoxFor?

The following snippet worked for me.

@Html.TextBoxFor(m => m.Crown, new { id = "", @style = "padding-left:5px", @readonly = "true" }) 

Jenkins - Configure Jenkins to poll changes in SCM

I think your cron is not correct. According to what you described, you may need to change cron schedule to

*/5 * * * *

What you put in your schedule now mean it will poll the SCM at 5 past of every hour.

Is it possible to select the last n items with nth-child?

nth-last-child sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.

Change the name of a key in dictionary

Easily done in 2 steps:

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

Or in 1 step:

dictionary[new_key] = dictionary.pop(old_key)

which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].

>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 1

How to get screen dimensions as pixels in Android

Here is a simple adaptation from some answers above in a Kotlin implementation. It requires as mentioned above windowsSoftInput="adjustResize" in the manifest:

class KeyboardWatcher(private val layoutRooView: View) {

    companion object {
        private const val MIN_KEYBOARD_HEIGHT = 200f
    }

    private val displayMetrics: DisplayMetrics = layoutRooView.resources.displayMetrics
    private var stateVisible = false

    var observer: ((Boolean) -> Unit)? = null

    init {
        layoutRooView.viewTreeObserver.addOnGlobalLayoutListener {
            val heightDiff = layoutRooView.rootView.height - layoutRooView.height
            if (!stateVisible && heightDiff > dpToPx(MIN_KEYBOARD_HEIGHT)) {
                stateVisible = true
                observer?.invoke(stateVisible)
            } else if(stateVisible) {
                stateVisible = false
                observer?.invoke(stateVisible)
            }
        }
    }

    private fun dpToPx(valueInDp: Float): Float {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, displayMetrics)
    }
}

And to use:

val activityRootView = findViewById<ViewGroup>(R.id.activityRoot)
KeyboardWatcher(activityRootView).observer = { visible ->
    if (visible) do something here ...
}

Entityframework Join using join method and lambdas

You can find a few examples here:

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts = ds.Tables["Contact"];
DataTable orders = ds.Tables["SalesOrderHeader"];

var query =
    contacts.AsEnumerable().Join(orders.AsEnumerable(),
    order => order.Field<Int32>("ContactID"),
    contact => contact.Field<Int32>("ContactID"),
    (contact, order) => new
    {
        ContactID = contact.Field<Int32>("ContactID"),
        SalesOrderID = order.Field<Int32>("SalesOrderID"),
        FirstName = contact.Field<string>("FirstName"),
        Lastname = contact.Field<string>("Lastname"),
        TotalDue = order.Field<decimal>("TotalDue")
    });


foreach (var contact_order in query)
{
    Console.WriteLine("ContactID: {0} "
                    + "SalesOrderID: {1} "
                    + "FirstName: {2} "
                    + "Lastname: {3} "
                    + "TotalDue: {4}",
        contact_order.ContactID,
        contact_order.SalesOrderID,
        contact_order.FirstName,
        contact_order.Lastname,
        contact_order.TotalDue);
}

Or just google for 'linq join method syntax'.

Service will not start: error 1067: the process terminated unexpectedly

This is a problem related permission. Make sure that the current user has access to the folder which contains installation files.

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

How to set underline text on textview?

In my sign_in.xml file I used this:

<Button
    android:id="@+id/signuptextlinkbtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@android:color/transparent"
    android:onClick="performSingUpMethod"
    android:text="Sign up now!"
    android:textColor="#5B55FF"
    android:textSize="15dp"
    android:textStyle="bold" />

In my SignIn.java file, I used this:

import android.graphics.Paint;
Button signuptextlinkbutton = (Button) findViewById(R.id.signuptextlinkbtn);
signuptextlinkbutton.setPaintFlags(signuptextlinkbutton.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);

Now I can see my link underlined. It was simply text even thought I declared it as a Button.

Convert 4 bytes to int

Converting a 4-byte array into integer:

//Explictly declaring anInt=-4, byte-by-byte
byte[] anInt = {(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xfc}; // Equals -4
//And now you have a 4-byte array with an integer equaling -4...
//Converting back to integer from 4-bytes...
result = (int) ( anInt[0]<<24 | ( (anInt[1]<<24)>>>8 ) | ( (anInt[2]<<24)>>>16) | ( (anInt[3]<<24)>>>24) );

extra qualification error in C++

I saw this error when my header file was missing closing brackets.

Causing this error:

// Obj.h
class Obj {
public:
    Obj();

Fixing this error:

// Obj.h
class Obj {
public:
    Obj();
};

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

what u can also do i place an extra "dummy" div before your last div.

Make it 1 px heigh and the width as much needed to cover the container div/body

This will make the last div appear under it, starting from the left.

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

vbscript output to console

There are five ways to output text to the console:

Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)

WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"

WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.

WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.

StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.

Multipart forms from C# client

A little optimization of the class before. In this version the files are not totally loaded into memory.

Security advice: a check for the boundary is missing, if the file contains the bounday it will crash.

namespace WindowsFormsApplication1
{
    public static class FormUpload
    {
        private static string NewDataBoundary()
        {
            Random rnd = new Random();
            string formDataBoundary = "";
            while (formDataBoundary.Length < 15)
            {
                formDataBoundary = formDataBoundary + rnd.Next();
            }
            formDataBoundary = formDataBoundary.Substring(0, 15);
            formDataBoundary = "-----------------------------" + formDataBoundary;
            return formDataBoundary;
        }

        public static HttpWebResponse MultipartFormDataPost(string postUrl, IEnumerable<Cookie> cookies, Dictionary<string, string> postParameters)
        {
            string boundary = NewDataBoundary();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);

            // Set up the request properties
            request.Method = "POST";
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.UserAgent = "PhasDocAgent 1.0";
            request.CookieContainer = new CookieContainer();

            foreach (var cookie in cookies)
            {
                request.CookieContainer.Add(cookie);
            }

            #region WRITING STREAM
            using (Stream formDataStream = request.GetRequestStream())
            {
                foreach (var param in postParameters)
                {
                    if (param.Value.StartsWith("file://"))
                    {
                        string filepath = param.Value.Substring(7);

                        // Add just the first part of this param, since we will write the file data directly to the Stream
                        string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
                            boundary,
                            param.Key,
                            Path.GetFileName(filepath) ?? param.Key,
                            MimeTypes.GetMime(filepath));

                        formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);

                        // Write the file data directly to the Stream, rather than serializing it to a string.

                        byte[] buffer = new byte[2048];

                        FileStream fs = new FileStream(filepath, FileMode.Open);

                        for (int i = 0; i < fs.Length; )
                        {
                            int k = fs.Read(buffer, 0, buffer.Length);
                            if (k > 0)
                            {
                                formDataStream.Write(buffer, 0, k);
                            }
                            i = i + k;
                        }
                        fs.Close();
                    }
                    else
                    {
                        string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
                            boundary,
                            param.Key,
                            param.Value);
                        formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);
                    }
                }
                // Add the end of the request
                byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                formDataStream.Write(footer, 0, footer.Length);
                request.ContentLength = formDataStream.Length;
                formDataStream.Close();
            }
            #endregion

            return request.GetResponse() as HttpWebResponse;
        }
    }
}

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

plt.show()

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

How to convert a string to lower or upper case in Ruby

Won't work for every, but this just saved me a bunch of time. I just had the problem with a CSV returning "TRUE or "FALSE" so I just added VALUE.to_s.downcase == "true" which will return the boolean true if the value is "TRUE" and false if the value is "FALSE", but will still work for the boolean true and false.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Saving Excel workbook to constant path with filename from two fields

Ok, at that time got it done with the help of a friend and the code looks like this.

Sub Saving()

Dim part1 As String

Dim part2 As String


part1 = Range("C5").Value

part2 = Range("C8").Value


ActiveWorkbook.SaveAs Filename:= _

"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

End Sub

How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou

Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Many questions get answers if we use .Net Reflector to see the actual code of SqlConnection :) true and sspi are the same:

internal class DbConnectionOptions

...

internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
    if ((CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true")) || CompareInsensitiveInvariant(stringValue, "yes"))
    {
        return true;
    }
}

...

EDIT 20.02.2018 Now in .Net Core we can see its open source on github! Search for ConvertValueToIntegratedSecurityInternal method:

https://github.com/dotnet/corefx/blob/fdbb160aeb0fad168b3603dbdd971d568151a0c8/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs

How does one remove a Docker image?

Update, as commented by VonC in How to remove old Docker containers.

With Docker 1.13 (Q4 2016), you now have:

docker system prune will delete ALL unused data (i.e., in order: containers stopped, volumes without containers and images with no containers).

See PR 26108 and commit 86de7c0, which are introducing a few new commands to help facilitate visualizing how much space the Docker daemon data is taking on disk and allowing for easily cleaning up "unneeded" excess.

docker system prune

WARNING! This will remove:
    - all stopped containers
    - all volumes not used by at least one container
    - all images without at least one container associated to them
Are you sure you want to continue? [y/N] y

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

Can I fade in a background image (CSS: background-image) with jQuery?

You can fade your background-image in various ways since Firefox 4 ...

Your CSS:

.box {
    background: #CCCCCC;
    -webkit-transition: background 0.5s linear;
    -moz-transition: background 0.5s linear;
    -o-transition: background 0.5s linear;
    transition: background 0.5s linear;
    }
.box:hover {
    background: url(path/to/file.png) no-repeat #CCCCCC;
    }

Your XHTML:

<div class="box">
    Some Text …
</div>

And thats it.

How can I get a value from a map?

The answer by Steve Jessop explains well, why you can't use std::map::operator[] on a const std::map. Gabe Rainbow's answer suggests a nice alternative. I'd just like to provide some example code on how to use map::at(). So, here is an enhanced example of your function():

void function(const MAP &map, const std::string &findMe) {
    try {
        const std::string& value = map.at(findMe);
        std::cout << "Value of key \"" << findMe.c_str() << "\": " << value.c_str() << std::endl;
        // TODO: Handle the element found.
    }
    catch (const std::out_of_range&) {
        std::cout << "Key \"" << findMe.c_str() << "\" not found" << std::endl;
        // TODO: Deal with the missing element.
    }
}

And here is an example main() function:

int main() {
    MAP valueMap;
    valueMap["string"] = "abc";
    function(valueMap, "string");
    function(valueMap, "strong");
    return 0;
}

Output:

Value of key "string": abc
Key "strong" not found

Code on Ideone

What is the difference between atomic / volatile / synchronized?

You are specifically asking about how they internally work, so here you are:

No synchronization

private int counter;

public int getNextUniqueIndex() {
  return counter++; 
}

It basically reads value from memory, increments it and puts back to memory. This works in single thread but nowadays, in the era of multi-core, multi-CPU, multi-level caches it won't work correctly. First of all it introduces race condition (several threads can read the value at the same time), but also visibility problems. The value might only be stored in "local" CPU memory (some cache) and not be visible for other CPUs/cores (and thus - threads). This is why many refer to local copy of a variable in a thread. It is very unsafe. Consider this popular but broken thread-stopping code:

private boolean stopped;

public void run() {
    while(!stopped) {
        //do some work
    }
}

public void pleaseStop() {
    stopped = true;
}

Add volatile to stopped variable and it works fine - if any other thread modifies stopped variable via pleaseStop() method, you are guaranteed to see that change immediately in working thread's while(!stopped) loop. BTW this is not a good way to interrupt a thread either, see: How to stop a thread that is running forever without any use and Stopping a specific java thread.

AtomicInteger

private AtomicInteger counter = new AtomicInteger();

public int getNextUniqueIndex() {
  return counter.getAndIncrement();
}

The AtomicInteger class uses CAS (compare-and-swap) low-level CPU operations (no synchronization needed!) They allow you to modify a particular variable only if the present value is equal to something else (and is returned successfully). So when you execute getAndIncrement() it actually runs in a loop (simplified real implementation):

int current;
do {
  current = get();
} while(!compareAndSet(current, current + 1));

So basically: read; try to store incremented value; if not successful (the value is no longer equal to current), read and try again. The compareAndSet() is implemented in native code (assembly).

volatile without synchronization

private volatile int counter;

public int getNextUniqueIndex() {
  return counter++; 
}

This code is not correct. It fixes the visibility issue (volatile makes sure other threads can see change made to counter) but still has a race condition. This has been explained multiple times: pre/post-incrementation is not atomic.

The only side effect of volatile is "flushing" caches so that all other parties see the freshest version of the data. This is too strict in most situations; that is why volatile is not default.

volatile without synchronization (2)

volatile int i = 0;
void incIBy5() {
  i += 5;
}

The same problem as above, but even worse because i is not private. The race condition is still present. Why is it a problem? If, say, two threads run this code simultaneously, the output might be + 5 or + 10. However, you are guaranteed to see the change.

Multiple independent synchronized

void incIBy5() {
  int temp;
  synchronized(i) { temp = i }
  synchronized(i) { i = temp + 5 }
}

Surprise, this code is incorrect as well. In fact, it is completely wrong. First of all you are synchronizing on i, which is about to be changed (moreover, i is a primitive, so I guess you are synchronizing on a temporary Integer created via autoboxing...) Completely flawed. You could also write:

synchronized(new Object()) {
  //thread-safe, SRSLy?
}

No two threads can enter the same synchronized block with the same lock. In this case (and similarly in your code) the lock object changes upon every execution, so synchronized effectively has no effect.

Even if you have used a final variable (or this) for synchronization, the code is still incorrect. Two threads can first read i to temp synchronously (having the same value locally in temp), then the first assigns a new value to i (say, from 1 to 6) and the other one does the same thing (from 1 to 6).

The synchronization must span from reading to assigning a value. Your first synchronization has no effect (reading an int is atomic) and the second as well. In my opinion, these are the correct forms:

void synchronized incIBy5() {
  i += 5 
}

void incIBy5() {
  synchronized(this) {
    i += 5 
  }
}

void incIBy5() {
  synchronized(this) {
    int temp = i;
    i = temp + 5;
  }
}

How can I align YouTube embedded video in the center in bootstrap

For a fully responsive IFramed YouTube video, try this:

<div class="blogwidevideo">
<iframe width="854" height="480" style="margin: auto;" src="https://www.youtube-nocookie.com/embed/h5ag-3nnenc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

.blogwidevideo {    
    overflow:hidden;
    padding-bottom:56.25%;
    position:relative;
    height:0;    
}

.blogwidevideo iframe {   
    left:10%; //centers for the 80% width - not needed if width is 100%
    top:0;
    height:80%; //change to 100% if going full width
    width:80%;
    position:absolute;
}

How to convert NSData to byte array in iPhone?

That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).

The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:

[data getBytes:&byteData length:len];

Which fills the array you have allocated with data from the NSData object.

PHP MySQL Google Chart JSON - Complete Example

You can do this more easy way. And 100% works that you want

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";  //your database password
    $dbname = "demo";  //your database name

    $con = new mysqli($servername, $username, $password, $dbname);

    if ($con->connect_error) {
        die("Connection failed: " . $con->connect_error);
    }
    else
    {
        //echo ("Connect Successfully");
    }
    $query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
    $aresult = $con->query($query);

?>

<!DOCTYPE html>
<html>
<head>
    <title>Massive Electronics</title>
    <script type="text/javascript" src="loder.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});

        google.charts.setOnLoadCallback(drawChart);
        function drawChart(){
            var data = new google.visualization.DataTable();
            var data = google.visualization.arrayToDataTable([
                ['Date_time','Tempout'],
                <?php
                    while($row = mysqli_fetch_assoc($aresult)){
                        echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
                    }
                ?>
               ]);

            var options = {
                title: 'Date_time Vs Room Out Temp',
                curveType: 'function',
                legend: { position: 'bottom' }
            };

            var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
            chart.draw(data, options);
        }

    </script>
</head>
<body>
     <div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>

loder.js link here loder.js

No resource identifier found for attribute '...' in package 'com.app....'

this helps for me:

on your build.gradle:

implementation 'com.android.support:design:28.0.0'

How to submit a form using PhantomJS

I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:

var page = new WebPage(), testindex = 0, loadInProgress = false;

page.onConsoleMessage = function(msg) {
  console.log(msg);
};

page.onLoadStarted = function() {
  loadInProgress = true;
  console.log("load started");
};

page.onLoadFinished = function() {
  loadInProgress = false;
  console.log("load finished");
};

var steps = [
  function() {
    //Load Login Page
    page.open("https://website.com/theformpage/");
  },
  function() {
    //Enter Credentials
    page.evaluate(function() {

      var arr = document.getElementsByClassName("login-form");
      var i;

      for (i=0; i < arr.length; i++) { 
        if (arr[i].getAttribute('method') == "POST") {

          arr[i].elements["email"].value="mylogin";
          arr[i].elements["password"].value="mypassword";
          return;
        }
      }
    });
  }, 
  function() {
    //Login
    page.evaluate(function() {
      var arr = document.getElementsByClassName("login-form");
      var i;

      for (i=0; i < arr.length; i++) {
        if (arr[i].getAttribute('method') == "POST") {
          arr[i].submit();
          return;
        }
      }

    });
  }, 
  function() {
    // Output content of page to stdout after form has been submitted
    page.evaluate(function() {
      console.log(document.querySelectorAll('html')[0].outerHTML);
    });
  }
];


interval = setInterval(function() {
  if (!loadInProgress && typeof steps[testindex] == "function") {
    console.log("step " + (testindex + 1));
    steps[testindex]();
    testindex++;
  }
  if (typeof steps[testindex] != "function") {
    console.log("test complete!");
    phantom.exit();
  }
}, 50);

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

How to set up java logging using a properties file? (java.util.logging)

Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");

//Properties preferences = new Properties();
try {
    //FileInputStream configFile = new //FileInputStream("/path/to/app.properties");
    //preferences.load(configFile);
    InputStream configFile = myApp.class.getResourceAsStream("app.properties");
    LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
    System.out.println("WARNING: Could not open configuration file");
    System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");

this is working..:) you have to pass InputStream in readConfiguration().

How to make HTTP Post request with JSON body in Swift

let url = URL(string: "url")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

request.httpMethod = "POST"



let postString = "ChangeAccordingtoyourdata=\(paramOne)&ChangeAccordingtoyourdata2=\(paramTwo)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {                                                 // check for fundamental networking error
        print("error=\(error)")
        return
    }

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(response)")

        SVProgressHUD.showError(withStatus: "Request has not submitted successfully.\nPlease try after some time")
    }

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")

    SVProgressHUD.showSuccess(withStatus: "Request has submitted successfully.\nPlease wait for a while")
    DispatchQueue.main.async {



    // enter code

    }

}
task.resume()

CSS - Expand float child DIV height to parent's height

<div class="parent" style="height:500px;">
<div class="child-left floatLeft" style="height:100%">
</div>

<div class="child-right floatLeft" style="height:100%">
</div>
</div>

I used inline style just to give idea.

Submit a form in a popup, and then close the popup

Try like this as well

covertPostSub("/xyz/test.jsp","?param1=param1&param2=param2","_self","true");
covertPostSub("/xyz/test.jsp","?param1=param1&param2=param2","_blank","true");

var convPop = null;
function covertPostSub(action,paramsTosend,targetIframe,isWindow){
    var Popup = null;
    var form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("id","TheForm");
    form.setAttribute("action", action);
    form.setAttribute("target", targetIframe);
    var params = paramsTosend;
    params = params.substring(1, params.length);
    params = params.split("&");
    for(var key=0; key<params.length; key++) {
        var sa = params[key];
        sa = sa.split("=");
        var xs = (sa[1]);

        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", sa[0]);
            hiddenField.setAttribute("value",xs);

            form.appendChild(hiddenField);
         }
    }
    document.body.appendChild(form);
    form.style.display = "none";
    if(isWindow){
        window.open('', "formpopup","width=900,height=590,toolbar=no,scrollbars=yes,resizable=no,location=0,directories=0,status=1,menubar=0,left=60,top=60");
        form.target = 'formpopup';
        form.submit();
    }else{
        form.submit();
    }

}

Google Maps V3 - How to calculate the zoom level for a given bounds

For swift version

func getBoundsZoomLevel(bounds: GMSCoordinateBounds, mapDim: CGSize) -> Double {
        var bounds = bounds
        let WORLD_DIM = CGSize(width: 256, height: 256)
        let ZOOM_MAX: Double = 21.0
        func latRad(_ lat: Double) -> Double {
            let sin2 = sin(lat * .pi / 180)
            let radX2 = log10((1 + sin2) / (1 - sin2)) / 2
            return max(min(radX2, .pi), -.pi) / 2
        }
        func zoom(_ mapPx: CGFloat,_ worldPx: CGFloat,_ fraction: Double) -> Double {
            return floor(log10(Double(mapPx) / Double(worldPx) / fraction / log10(2.0)))
        }
        let ne = bounds.northEast
        let sw = bounds.southWest
        let latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / .pi
        let lngDiff = ne.longitude - sw.longitude
        let lngFraction = lngDiff < 0 ? (lngDiff + 360) : (lngDiff / 360)
        let latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
        let lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
        return min(latZoom, lngZoom, ZOOM_MAX)
    }

Where is Xcode's build folder?

enter image description here

enter image description here

Configure XCode project settings, it can solve your problem.

Calculating bits required to store decimal number

let its required n bit then 2^n=(base)^digit and then take log and count no. for n

How do I mock a static method that returns void with PowerMock?

To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),

Sample code:

File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);

How can I use Guzzle to send a POST request in JSON?

The simple and basic way (guzzle6):

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';

How do I set the path to a DLL file in Visual Studio?

Another possibility would be to set the Working Directory under the debugging options to be the directory that has that DLL.

Edit: I was going to mention using a batch file to start Visual Studio (and set the PATH variable in the batch file). So then did a bit of searching and see that this exact same question was asked not long ago in this post. The answer suggests the batch file option as well as project settings that apparently may do the job (I did not test it).

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

Difference between numpy.array shape (R, 1) and (R,)

There are a lot of good answers here already. But for me it was hard to find some example, where the shape or array can break all the program.

So here is the one:

import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])


from sklearn.linear_model import LinearRegression
regr = LinearRegression()
regr.fit(a,b)

This will fail with error:

ValueError: Expected 2D array, got 1D array instead

but if we add reshape to a:

a = np.array([1,2,3,4]).reshape(-1,1)

this works correctly!

Django development IDE

As far as I know there is not "an IDE" for Django, but there are some IDEs that support Django right out of the box, specifically the Django syntax for templates.

The name is Komodo, and it has a lot of features, but it's not cheap. If you are not worried about source control or debugging then there is a free version called Komodo Edit.

error: command 'gcc' failed with exit status 1 while installing eventlet

This is an old post but I just run to the same problem on AWS EC2 installing regex. This working perfectly for me

sudo yum -y install gcc

and next

sudo yum -y install gcc-c++

How do I convert an integer to binary in JavaScript?

This is how I manage to handle it:

const decbin = nbr => {
  if(nbr < 0){
     nbr = 0xFFFFFFFF + nbr + 1
  }
  return parseInt(nbr, 10).toString(2)
};

got it from this link: https://locutus.io/php/math/decbin/

Circle drawing with SVG's arc path

Adobe Illustrator uses bezier curves like SVG, and for circles it creates four points. You can create a circle with two elliptical arc commands...but then for a circle in SVG I would use a <circle /> :)

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Make sure your project is 32 bit.

I had this problem, as soon as I ticked "Prefer 32 bit and rebuilt" all the Office Interop assemblies where available in Reference->Assemblies->Search "Office".

How to get the IP address of the server on which my C# application is running on?

To find IP address list I have used this solution

public static IEnumerable<string> GetAddresses()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}

But I personally like below solution to get local valid IP address

public static IPAddress GetIPAddress(string hostName)
{
    Ping ping = new Ping();
    var replay = ping.Send(hostName);

    if (replay.Status == IPStatus.Success)
    {
        return replay.Address;
    }
    return null;
 }

public static void Main()
{
    Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
    Console.WriteLine("Google IP:" + GetIPAddress("google.com");
    Console.ReadLine();
}

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

Calling constructors in c++ without new

In append to JaredPar answer

1-usual ctor, 2nd-function-like-ctor with temporary object.

Compile this source somewhere here http://melpon.org/wandbox/ with different compilers

// turn off rvo for clang, gcc with '-fno-elide-constructors'

#include <stdio.h>
class Thing {
public:
    Thing(const char*){puts(__FUNCTION__ );}
    Thing(const Thing&){puts(__FUNCTION__ );}   
    ~Thing(){puts(__FUNCTION__);}
};
int main(int /*argc*/, const char** /*argv*/) {
    Thing myThing = Thing("asdf");
}

And you will see the result.

From ISO/IEC 14882 2003-10-15

8.5, part 12

Your 1st,2nd construction are called direct-initialization

12.1, part 13

A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]


Where to read about RVO:

12 Special member functions / 12.8 Copying class objects/ Part 15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.

Turn off it with compiler flag from comment to view such copy-behavior)

jQuery Refresh/Reload Page if Ajax Success after time

Lots of good answers here, just out of curiosity after looking into this today, is it not best to use setInterval rather than the setTimeout?

setInterval(function() {
location.reload();
}, 30000);

let me know you thoughts.

What's the Android ADB shell "dumpsys" tool and what are its benefits?

Looking at the source code for dumpsys and service, you can get the list of services available by executing the following:

adb shell service -l

You can then supply the service name you are interested in to dumpsys to get the specific information. For example (note that not all services provide dump info):

adb shell dumpsys activity
adb shell dumpsys cpuinfo
adb shell dumpsys battery

As you can see in the code (and in K_Anas's answer), if you call dumpsys without any service name, it will dump the info on all services in one big dump:

adb shell dumpsys

Some services can receive additional arguments on what to show which normally is explained if you supplied a -h argument, for example:

adb shell dumpsys activity -h
adb shell dumpsys window -h
adb shell dumpsys meminfo -h
adb shell dumpsys package -h
adb shell dumpsys batteryinfo -h

Cookies on localhost with explicit domain

I had much better luck testing locally using 127.0.0.1 as the domain. I'm not sure why, but I had mixed results with localhost and .localhost, etc.

Python append() vs. + operator on lists, why do these give different results?

The concatenation operator + is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append() method is a mutator on list which appends its single object argument (in your specific example the list c) to the subject list. In your example this results in c appending a reference to itself (hence the infinite recursion).

An alternative to '+' concatenation

The list.extend() method is also a mutator method which concatenates its sequence argument with the subject list. Specifically, it appends each of the elements of sequence in iteration order.

An aside

Being an operator, + returns the result of the expression as a new value. Being a non-chaining mutator method, list.extend() modifies the subject list in-place and returns nothing.

Arrays

I've added this due to the potential confusion which the Abel's answer above may cause by mixing the discussion of lists, sequences and arrays. Arrays were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types. Do not confuse arrays with lists. They are not the same.

From the array docs:

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character.

How to update all MySQL table rows at the same time?

just use UPDATE query without condition like this

 UPDATE tablename SET online_status=0;

Git SSH error: "Connect to host: Bad file number"

In my case the IP address of our git host had changed.

Simply flushing the DNS cache fixed the problem.

Suppress/ print without b' prefix for bytes in Python 3

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

How does facebook, gmail send the real time notification?

One important issue with long polling is error handling. There are two types of errors:

  1. The request might timeout in which case the client should reestablish the connection immediately. This is a normal event in long polling when no messages have arrived.

  2. A network error or an execution error. This is an actual error which the client should gracefully accept and wait for the server to come back on-line.

The main issue is that if your error handler reestablishes the connection immediately also for a type 2 error, the clients would DOS the server.

Both answers with code sample miss this.

function longPoll() { 
        var shouldDelay = false;

        $.ajax({
            url: 'poll.php',
            async: true,            // by default, it's async, but...
            dataType: 'json',       // or the dataType you are working with
            timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
            cache: false

        }).done(function (data, textStatus, jqXHR) {
             // do something with data...

        }).fail(function (jqXHR, textStatus, errorThrown ) {
            shouldDelay = textStatus !== "timeout";

        }).always(function() {
            // in case of network error. throttle otherwise we DOS ourselves. If it was a timeout, its normal operation. go again.
            var delay = shouldDelay ? 10000: 0;
            window.setTimeout(longPoll, delay);
        });
}
longPoll(); //fire first handler

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Local variable referenced before assignment?

Best solution: Don't use globals

>>> test1 = 0
>>> def test_func(x):
        return x + 1

>>> test1 = test_func(test1)
>>> test1
1

Read a file line by line assigning the value to a variable

Many people have posted a solution that's over-optimized. I don't think it is incorrect, but I humbly think that a less optimized solution will be desirable to permit everyone to easily understand how is this working. Here is my proposal:

#!/bin/bash
#
# This program reads lines from a file.
#

end_of_file=0
while [[ $end_of_file == 0 ]]; do
  read -r line
  # the last exit status is the 
  # flag of the end of file
  end_of_file=$?
  echo $line
done < "$1"

Remove all non-"word characters" from a String in Java, leaving accented characters?

You might want to remove the accents and diacritic signs first, then on each character position check if the "simplified" string is an ascii letter - if it is, the original position shall contain word characters, if not, it can be removed.

Display label text with line breaks in c#

You can also use <br/> where you want to break the text.

Laravel 5 – Clear Cache in Shared Hosting Server

As I can see: http://itsolutionstuff.com/post/laravel-5-clear-cache-from-route-view-config-and-all-cache-data-from-applicationexample.html

is it possible to use the code below with the new clear cache commands:

//Clear Cache facade value:
Route::get('/clear-cache', function() {
    $exitCode = Artisan::call('cache:clear');
    return '<h1>Cache facade value cleared</h1>';
});

//Reoptimized class loader:
Route::get('/optimize', function() {
    $exitCode = Artisan::call('optimize');
    return '<h1>Reoptimized class loader</h1>';
});

//Route cache:
Route::get('/route-cache', function() {
    $exitCode = Artisan::call('route:cache');
    return '<h1>Routes cached</h1>';
});

//Clear Route cache:
Route::get('/route-clear', function() {
    $exitCode = Artisan::call('route:clear');
    return '<h1>Route cache cleared</h1>';
});

//Clear View cache:
Route::get('/view-clear', function() {
    $exitCode = Artisan::call('view:clear');
    return '<h1>View cache cleared</h1>';
});

//Clear Config cache:
Route::get('/config-cache', function() {
    $exitCode = Artisan::call('config:cache');
    return '<h1>Clear Config cleared</h1>';
});

It's not necessary to give the possibility to clear the caches to everyone, especially in a production enviroment, so I suggest to comment that routes and, when it's needed, to de-comment the code and run the routes.

Extending from two classes

You will want to use interfaces. Generally, multiple inheritance is bad because of the Diamond Problem:

abstract class A {
 abstract string foo();
}

class B extends A {
 string foo () { return "bar"; }
}

class C extends A  {
 string foo() {return "baz"; }
}

class D extends B, C {
 string foo() { return super.foo(); } //What do I do? Which method should I call?
}

C++ and others have a couple ways to solve this, eg

string foo() { return B::foo(); }

but Java only uses interfaces.

The Java Trails have a great introduction on interfaces: http://download.oracle.com/javase/tutorial/java/concepts/interface.html You'll probably want to follow that before diving into the nuances in the Android API.