Programs & Examples On #Archlinux

Arch Linux is a Linux distribution intended to be lightweight and simple. Its development is focused on simplicity, elegance, code correctness and minimalism from a developer's standpoint.

Cannot get OpenCV to compile because of undefined references?

If you do the following, you will be able to use opencv build from OpenCV_INSTALL_PATH.

cmake_minimum_required(VERSION 2.8)

SET(OpenCV_INSTALL_PATH /home/user/opencv/opencv-2.4.13/release/)

SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")

LINK_DIRECTORIES(${OpenCV_LIB_DIR})

set(OpenCV_LIBS opencv_core opencv_imgproc opencv_calib3d opencv_video opencv_features2d opencv_ml opencv_highgui opencv_objdetect opencv_contrib opencv_legacy opencv_gpu)

# find_package( OpenCV )

project(edge.cpp)

add_executable(edge edge.cpp)

Running a Python script from PHP

To clarify which command to use based on the situation

exec() - Execute an external program

system() - Execute an external program and display the output

passthru() - Execute an external program and display raw output

Source: http://php.net/manual/en/function.exec.php

Inheritance and Overriding __init__ in python

You don't really have to call the __init__ methods of the base class(es), but you usually want to do it because the base classes will do some important initializations there that are needed for rest of the classes methods to work.

For other methods it depends on your intentions. If you just want to add something to the base classes behavior you will want to call the base classes method additionally to your own code. If you want to fundamentally change the behavior, you might not call the base class' method and implement all the functionality directly in the derived class.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

it can also be achieved with below code

import re

text = 'how are u? umberella u! u. U. U@ U# u '
print (re.sub (r'[uU] ( [^a-z] )', r' you\1 ', text))

or

print (re.sub (r'[uU] ( [\s!,.?@#] )', r' you\1 ', text))

Remove files from Git commit

ATTENTION! If you only want to remove a file from your previous commit, and keep it on disk, read juzzlin's answer just above.

If this is your last commit and you want to completely delete the file from your local and the remote repository, you can:

  1. remove the file git rm <file>
  2. commit with amend flag: git commit --amend

The amend flag tells git to commit again, but "merge" (not in the sense of merging two branches) this commit with the last commit.

As stated in the comments, using git rm here is like using the rm command itself!

How do I verify that an Android apk is signed with a release certificate?

    1. unzip apk
    1. keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk to obtain the hash md5
  • keytool -list -v -keystore clave-release.jks
  • compare the md5

https://www.eovao.com/en/a/signature%20apk%20android/3/how-to-verify-signature-of-.apk-android-archive

How do I compare two DateTime objects in PHP 5.2.8?

From the official documentation:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // false
var_dump($date1 < $date2); // true
var_dump($date1 > $date2); // false

For PHP versions before 5.2.2 (actually for any version), you can use diff.

$datetime1 = new DateTime('2009-10-11'); // 11 October 2013
$datetime2 = new DateTime('2009-10-13'); // 13 October 2013

$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // +2 days

java.lang.OutOfMemoryError: Java heap space

To avoid that exception, if you are using JUnit and Spring try adding this in every test class:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)

Java Spring Boot: How to map my app root (“/”) to index.html?

If you use the latest spring-boot 2.1.6.RELEASE with a simple @RestController annotation then you do not need to do anything, just add your index.html file under the resources/static folder:

project
  +-- src
      +-- main
          +-- resources
              +-- static
                  +-- index.html

Then hit the URL http://localhost:8080. Hope that it will help everyone.

What is this Javascript "require"?

I noticed that whilst the other answers explained what require is and that it is used to load modules in Node they did not give a full reply on how to load node modules when working in the Browser.

It is quite simple to do. Install your module using npm as you describe, and the module itself will be located in a folder usually called node_modules.

Now the simplest way to load it into your app is to reference it from your html with a script tag which points at this directory. i.e if your node_modules directory is in the root of the project at the same level as your index.html you would write this in your index.html:

<script src="node_modules/ng"></script>

That whole script will now be loaded into the page - so you can access its variables and methods directly.

There are other approaches which are more widely used in larger projects, such as a module loader like require.js. Of the two, I have not used Require myself, but I think it is considered by many people the way to go.

How to run shell script file using nodejs?

You can execute any shell command using the shelljs module

 const shell = require('shelljs')

 shell.exec('./path_to_your_file')

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

How to implement a Boolean search with multiple columns in pandas

You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (&) and or (|) operators:

foo = df[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]

If you use and or or, then pandas is likely to moan that the comparison is ambiguous. In that case, it is unclear whether we are comparing every value in a series in the condition, and what does it mean if only 1 or all but 1 match the condition. That is why you should use the bitwise operators or the numpy np.all or np.any to specify the matching criteria.

There is also the query method: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html

but there are some limitations mainly to do with issues where there could be ambiguity between column names and index values.

SQLite with encryption/password protection

Keep in mind, the following is not intended to be a substitute for a proper security solution.

After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.

using System.Data.SQLite;

namespace EncryptDB
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = @"C:\Programming\sqlite3\db.db";
            string passwordString = "password";
            byte[] passwordBytes = GetBytes(passwordString);
            SQLiteConnection.CreateFile(connectionString);
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
            conn.SetPassword(passwordBytes);
            conn.Open();
            SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
            sqlCmd.ExecuteNonQuery();
            sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
            sqlCmd.ExecuteNonQuery();
            conn.Close();
        }
        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            bytes = System.Text.Encoding.Default.GetBytes(str);
            return bytes;
        }
    }
}

Optionally, you can remove conn.SetPassword(passwordBytes);, and replace it with conn.ChangePassword("password"); which needs to be placed after conn.Open(); instead of before. Then you won't need the GetBytes method.

To decrypt, it's just a matter of putting the password in your connection string before the call to open.

        string filename = @"C:\Programming\sqlite3\db.db";
        string passwordString = "password";
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
        conn.Open();

Relative URLs in WordPress

should use get_home_url(), then your links are absolute, but it does not affect if you change the site url

How can I use MS Visual Studio for Android Development?

I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.

Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.

How do I remove objects from an array in Java?

If it doesn't matter the order of the elements. you can swap between the elements foo[x] and foo[0], then call foo.drop(1).

foo.drop(n) removes (n) first elements from the array.

I guess this is the simplest and resource efficient way to do.

PS: indexOf can be implemented in many ways, this is my version.

Integer indexOf(String[] arr, String value){
    for(Integer i = 0 ; i < arr.length; i++ )
        if(arr[i] == value)
            return i;         // return the index of the element
    return -1                 // otherwise -1
}

while (true) {
   Integer i;
   i = indexOf(foo,"a")
   if (i == -1) break;
   foo[i] = foo[0];           // preserve foo[0]
   foo.drop(1);
}

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

How do I detect if software keyboard is visible on Android Device or not?

I created a simple class that can be used for this: https://github.com/ravindu1024/android-keyboardlistener. Just copy it in to your project and use as follows:

KeyboardUtils.addKeyboardToggleListener(this, new KeyboardUtils.SoftKeyboardToggleListener()
{
    @Override
    public void onToggleSoftKeyboard(boolean isVisible)
    {
        Log.d("keyboard", "keyboard visible: "+isVisible);
    }
});

How to retrieve SQL result column value using column name in Python?

selecting values from particular column:

import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
    #query execution
    cursor.execute(sql)
    #fetch all rows 
    rs = cursor.fetchall()
    #iterate through rows
    for i in rs:
        #converting set to list
        k=list(i)
        #taking the first element from the list and append it to the list
        l.append(k[0])
    db.commit()
except:
    db.rollback()
db.close()
print(l)

FirebaseInstanceIdService is deprecated

For kotlin I use the following

val fcmtoken = FirebaseMessaging.getInstance().token.await()

and for the extension functions

public suspend fun <T> Task<T>.await(): T {
    // fast path
    if (isComplete) {
        val e = exception
        return if (e == null) {
            if (isCanceled) {
                throw CancellationException("Task $this was cancelled normally.")
            } else {
                @Suppress("UNCHECKED_CAST")
                result as T
            }
        } else {
            throw e
        }
    }

    return suspendCancellableCoroutine { cont ->
        addOnCompleteListener {
            val e = exception
            if (e == null) {
                @Suppress("UNCHECKED_CAST")
                if (isCanceled) cont.cancel() else cont.resume(result as T)
            } else {
                cont.resumeWithException(e)
            }
        }
    }
}

Using grep to search for a string that has a dot in it

grep -F -r '0.49' * treats 0.49 as a "fixed" string instead of a regular expression. This makes . lose its special meaning.

How do you find out the type of an object (in Swift)?

For Swift 3.0

String(describing: <Class-Name>.self)

For Swift 2.0 - 2.3

String(<Class-Name>)

Facebook Oauth Logout

Update: This solution works and just a call to 'FB.logout()' doesn't work because browser wants a user interaction to actually call this function, so that it knows - it is a user not a script.

<a href="#" onclick="FB.logout();">Logout</a> 

MySQL: Large VARCHAR vs. TEXT?

  • TEXT and BLOB may by stored off the table with the table just having a pointer to the location of the actual storage. Where it is stored depends on lots of things like data size, columns size, row_format, and MySQL version.

  • VARCHAR is stored inline with the table. VARCHAR is faster when the size is reasonable, the tradeoff of which would be faster depends upon your data and your hardware, you'd want to benchmark a real-world scenario with your data.

SLF4J: Class path contains multiple SLF4J bindings

For me, it turned out to be an Eclipse/Maven issue after switch from log4j to logback. Take a look into your .classpath file and search for the string "log4j".

In my case I had the following there: <classpathentry kind="var" path="M2_REPO/org/slf4j/slf4j-log4j12/1.7.1/slf4j-log4j12-1.7.1.jar"/> <classpathentry kind="var" path="M2_REPO/log4j/log4j/1.2.17/log4j-1.2.17.jar" />

Removing those entries from the file (or you could regenerate it) fixed the issue.

How to split one text file into multiple *.txt files?

Try something like this:

awk -vc=1 'NR%1000000==0{++c}{print $0 > c".txt"}' Datafile.txt

for filename in *.txt; do mv "$filename" "Prefix_$filename"; done;

Confirm password validation in Angular 6

*This solution is for reactive-form

You may have heard the confirm password is known as cross-field validation. While the field level validator that we usually write can only be applied to a single field. For cross-filed validation, you probably have to write some parent level validator. For specifically the case of confirming password, I would rather do:

this.form.valueChanges.subscribe(field => {
  if (field.password !== field.confirm) {
    this.confirm.setErrors({ mismatch: true });
  } else {
    this.confirm.setErrors(null);
  }
});

And here is the template:

<mat-form-field>
      <input matInput type="password" placeholder="Password" formControlName="password">
      <mat-error *ngIf="password.hasError('required')">Required</mat-error>
</mat-form-field>
<mat-form-field>
    <input matInput type="password" placeholder="Confirm New Password" formControlName="confirm">`enter code here`
    <mat-error *ngIf="confirm.hasError('mismatch')">Password does not match the confirm password</mat-error>
</mat-form-field>

Convert boolean result into number/integer

TL;DR: Avoid Number constructor, unary +; use a simple if all the time; resort to bool | 0 or 1 * bool if benchmarks in your project do better this way.

This is quite an old question, and there exist many valid answers. Something I've noticed is that all benchmarks here are irrelevant - none take into account branch prediction. Also, nowadays, JS engines don't simply interpret the code, they JIT compile it to native machine code and optimize it prior to execution. This means that, besides branch prediction, the compiler can even substitute expressions with their final value.

Now, how do these 2 factors affect the performance of, well, boolean to integer conversion? Let's find out! Before we get into the benchmarks, it is important to know what we benchmark. For the conversion, we're using the following seven conversion methods:

  • Number constructor: Number(bool)
  • If statement (ternary used): bool ? 1 : 0
  • Unary operator +: +bool
  • Bitwise OR: bool | 0
  • Bitwise AND: bool & 1
  • Bitwise double NOT: ~~bool
  • Number multiplication: bool * 1

"Conversion" means converting false to 0 and true to 11. Each conversion method is ran 100000 times, measuring operations/millisecond. In the following tables, conversion methods will be grouped to their results accordingly. The results are from my machine, which features an AMD Ryzen 7 4800HS as its CPU.

The first benchmark converts the constant true:

Method Edge/Chromium (V8) Firefox (Spidermonkey)
Number(bool) 83103 1088
bool ? 1 : 0 83073 7732
+bool 83372 1043
bool | 0 83479 9344
bool & 1 83242 9354
~~bool 83293 9316
bool * 1 83504 9316

Interesting! V8 shows some huge numbers, all of them approximately the same! Spidermonkey doesn't really shine, but we can see that the bitwise and multiplication tricks come first, and the ternary if second. What are the takeaways? Chrome browsers manage to replace our conversions with simply the value 1. This optimization will take place where we can mentally replace the boolean to a constant value.

That above isn't a situation we'll ever encounter in real projects. So let's change our variables: the bool is now Math.random() < 0.5. This yields a 50% chance of true, 50% of false. Do our results change? Let's run this benchmark to see.

Method Edge/Chromium (V8) Firefox (Spidermonkey)
Number(bool) 2405 662
bool ? 1 : 0 1482 1580
+bool 2386 673
bool | 0 2391 2499
bool & 1 2409 2513
~~bool 2341 2493
bool * 1 2398 2518

The results are more consistent now. We see similar numbers for ternary if, bitwise, and multiplication methods, but the Number constructor and unary + perform better on V8. We can presume from the numbers that V8 replaces them with whatever instructions it's using for the bitwise tricks, but in Spidermonkey those functions do all the work.

We haven't still tackled one factor we mentioned above: branch prediction. Let's change, in this benchmark, our boolean variable to Math.random() < 0.01, which means 1% true, 99% false.

Method Edge/Chromium (V8) Firefox (Spidermonkey)
Number(bool) 2364 865
bool ? 1 : 0 2352 2390
+bool 2447 777
bool | 0 2421 2513
bool & 1 2400 2509
~~bool 2446 2501
bool * 1 2421 2497

Unexpected? Expected? I'd say the latter, because in this case branch prediction was successful in almost all cases, given the tiny difference between the ternary if and bitwise hacks. All other results are the same, not much else to say here.

This endeavour brings us back to the original question: how to convert bool to int in Javascript? Here are my suggestions:

  • Avoid Number(bool) and +bool. These 2 methods do a lot of work under the hood, and even though Chrome managed to optimize them in our benchmarks, Firefox did not, and there might be some situations where these optimizations won't be done by the compiler. Besides that, not everyone's on Chrome! I still have to put up with that, don't you?...
  • Use if statements, in general. Don't get smart - the browser will do better, usually, and usually means most of the situations. They are the most readable and clear out of all the methods here. While we're at readability, maybe use if (bool) instead of that ugly ternary! I wish Javascript had what Rust or Python have...
  • Use the rest when it's truly necessary. Maybe benchmarks in your project perform sub-standard, and you found that a nasty if causes bad performance - if that's the case, feel free to get into branchless programming! But don't go too deep in that rabbit hole, nobody will benefit from things like -1 * (a < b) + 1 * (a > b), believe me.

I will be forever grateful to you for reading until the end - this is my first longer, significant StackOverflow answer and it means the world to me if it's been helpful and insightful. If you find any errors, feel free to correct me!


  1. Defined the conversion because it's not truly clear what boolean to integer means. For example, Go does not support this conversion at all.

Best way to get value from Collection by index

It would be just as convenient to simply convert your collection into a list whenever it updates. But if you are initializing, this will suffice:

for(String i : collectionlist){
    arraylist.add(i);
    whateverIntID = arraylist.indexOf(i);
}

Be open-minded.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem.

As it turned out, I ran mvn clean package install.

Correct way is mvn clean install

View HTTP headers in Google Chrome?

For me, as of Google Chrome Version 46.0.2490.71 m, the Headers info area is a little hidden. To access:

  1. While the browser is open, press F12 to access Web Developer tools

  2. When opened, click the "Network" option

  3. Initially, it is possible the page data is not present/up to date. Refresh the page if necessary

  4. Observe the page information appears in the listing. (Also, make sure "All" is selected next to the "Hide data URLs" checkbox)

see screenshot

jQuery not working with IE 11

Place this meta tag after head tag

<meta http-equiv="x-ua-compatible" content="IE=edge">

Using union and order by clause in mysql

Try:

SELECT result.* 
FROM (
 [QUERY 1]
 UNION
 [QUERY 2]
) result
ORDER BY result.id

Where [QUERY 1] and [QUERY 2] are your two queries that you want to merge.

Edit line thickness of CSS 'underline' attribute

Here is one way of achieving this :

HTML :

<h4>This is a heading</h4>

<h4><u>This is another heading</u></h4>

?CSS :

 u {
    text-decoration: none;
    border-bottom: 10px solid black;
  }?

Here is an example: http://jsfiddle.net/AQ9rL/

How do I find the stack trace in Visual Studio?

While debugging, when you hit a break-point.

CTRL+ALT+C

enter image description here

How to delete a row from GridView?

My solution:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    myobj.myconnection();// connection created
    string mystr = "Delete table_name where water_id= '" + GridView1.DataKeys[e.RowIndex].Value + "'";// query
    sqlcmd = new SqlCommand(mystr, myobj.mycon);
    sqlcmd.ExecuteNonQuery();
    fillgrid();
}

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

How Do I Upload Eclipse Projects to GitHub?

Many of these answers mention how to share the project on Git, which is easy, you just share the code on git, but one thing to take note of is that there is no apparent "project file" that the end user can double click on. Instead you have to use Import->General->Existing project and select the whole folder

How to invoke bash, run commands inside the new shell, and then give control back to user?

Append to ~/.bashrc a section like this:

if [ "$subshell" = 'true' ]
then
    # commands to execute only on a subshell
    date
fi
alias sub='subshell=true bash'

Then you can start the subshell with sub.

A regex for version number parsing

It seems pretty hard to have a regex that does exactly what you want (i.e. accept only the cases that you need and reject all others and return some groups for the three components). I've give it a try and come up with this:

^(\*|(\d+(\.(\d+(\.(\d+|\*))?|\*))?))$

IMO (I've not tested extensively) this should work fine as a validator for the input, but the problem is that this regex doesn't offer a way of retrieving the components. For that you still have to do a split on period.

This solution is not all-in-one, but most times in programming it doesn't need to. Of course this depends on other restrictions that you might have in your code.

Cannot find firefox binary in PATH. Make sure firefox is installed

Make sure that firefox must install on default place like ->(c:/Program Files (x86)/mozilla firefox OR c:/Program Files/mozilla firefox, note: at the time of firefox installation do not change the path so let it installing in default path) If firefox is installed on some other place then selenium show those error.

If you have set your firefox in Systems(Windows) environment variable then either remove it or update it with new firefox version path.

If you want to use Firefox in any other place then use below code:-

As FirefoxProfile is depricated we need to use FirefoxOptions as below:

New Code:

File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);   
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));

The full working code of above code is as below:

System.setProperty("webdriver.gecko.driver","D:\\Workspace\\demoproject\\src\\lib\\geckodriver.exe");
File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);   
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.google.co.in/");

Download geckodriver for firefox from below URL:

https://github.com/mozilla/geckodriver/releases

Old Code which will work for old selenium jars versions

File pathBinary = new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();       
WebDriver driver = new FirefoxDriver(firefoxBinary, firefoxProfile);

MySQL Event Scheduler on a specific time everyday

This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:

CREATE EVENT event_name
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    # Your awesome query

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

One point I noticed with Primefaces 3.4 and Netbeans 7.2:

Remove the Netbeans auto-filled parameters for function handleFileUpload i.e. (event) otherwise event could be null.

<h:form>
    <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload(event)}"
        mode="advanced" 
        update="messages"
        sizeLimit="100000" 
        allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>

    <p:growl id="messages" showDetail="true"/>
</h:form>

Change language of Visual Studio 2017 RC

I didn't find a complete answer here

Firstly

You should install your preferred language

  1. Open the Visual Studio Installer.
  2. In installed products click on plus Dropdown menu
  3. click edit
  4. then click on language packs
  5. choose you preferred language and finally click on install

Secondly

  1. Go to Tools -> Options

    2.Select International Settings in Environment

    3.click on Menu and select you preferred language

    4.Click on Ok

    5.restart visual studio

How to install OpenJDK 11 on Windows?

From the comment by @ZhekaKozlov: ojdkbuild has OpenJDK builds (currently 8 and 11) for Windows (zip and msi).

How do I enable TODO/FIXME/XXX task tags in Eclipse?

For me, such tags are enabled by default. You can configure which task tags should be used in the workspace options: Java > Compiler > Task tags

alt text

Check if they are enabled in this location, and that should be enough to have them appear in the Task list (or the Markers view).

Extra note: reinstalling Eclipse won't change anything most of the time if you work on the same workspace. Most settings used by Eclipse are stored in the .metadata folder, in your workspace folder.

NHibernate.MappingException: No persister for: XYZ

I my case I fetched an entity without await:

var company = _unitOfWork.Session.GetAsync<Company>(id);

and then I tried to delete it:

await _unitOfWork.Session.DeleteAsync(company);

I could not decipher the error message that I'm deleting a Task<Company> instead of Company:

MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]

ADB - Android - Getting the name of the current activity

Here is a solution that is easier than the command line adb solution (which does work). It is easier because it is more graphical and can be done from within Eclipse.

In Eclipse with Android device attached go to Window menu > Show View > Other ... use filter text "Windows" to pull up Android > Windows ... show this. The top item in the list is the current activity.

Another way to pull this up is by showing the "Hierarchy View" perspective, which by default will show the Windows window.

Select from table by knowing only date without time (ORACLE)

DATE is a reserved keyword in Oracle, so I'm using column-name your_date instead.

If you have an index on your_date, I would use

WHERE your_date >= TO_DATE('2010-08-03', 'YYYY-MM-DD')
  AND your_date <  TO_DATE('2010-08-04', 'YYYY-MM-DD')

or BETWEEN:

WHERE your_date BETWEEN TO_DATE('2010-08-03', 'YYYY-MM-DD')
                    AND TO_DATE('2010-08-03 23:59:59', 'YYYY-MM-DD HH24:MI:SS')

If there is no index or if there are not too many records

WHERE TRUNC(your_date) = TO_DATE('2010-08-03', 'YYYY-MM-DD')

should be sufficient. TRUNC without parameter removes hours, minutes and seconds from a DATE.


If performance really matters, consider putting a Function Based Index on that column:

CREATE INDEX trunc_date_idx ON t1(TRUNC(your_date));

How can you profile a Python script?

Ever want to know what the hell that python script is doing? Enter the Inspect Shell. Inspect Shell lets you print/alter globals and run functions without interrupting the running script. Now with auto-complete and command history (only on linux).

Inspect Shell is not a pdb-style debugger.

https://github.com/amoffat/Inspect-Shell

You could use that (and your wristwatch).

Converting JSON to XML in Java

Underscore-java library has static method U.jsonToXml(jsonstring). I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";  
        System.out.println(json); 
        String xml = U.jsonToXml(json);  
        System.out.println(xml); 
    }
}

Output:

{"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <name>JSON</name>
  <integer number="true">1</integer>
  <double number="true">2.0</double>
  <boolean boolean="true">true</boolean>
  <nested>
    <id number="true">42</id>
  </nested>
  <array number="true">1</array>
  <array number="true">2</array>
  <array number="true">3</array>
</root>

Pointers in Python?

I wrote the following simple class as, effectively, a way to emulate a pointer in python:

class Parameter:
    """Syntactic sugar for getter/setter pair
    Usage:

    p = Parameter(getter, setter)

    Set parameter value:
    p(value)
    p.val = value
    p.set(value)

    Retrieve parameter value:
    p()
    p.val
    p.get()
    """
    def __init__(self, getter, setter):
        """Create parameter

        Required positional parameters:
        getter: called with no arguments, retrieves the parameter value.
        setter: called with value, sets the parameter.
        """
        self._get = getter
        self._set = setter

    def __call__(self, val=None):
        if val is not None:
            self._set(val)
        return self._get()

    def get(self):
        return self._get()

    def set(self, val):
        self._set(val)

    @property
    def val(self):
        return self._get()

    @val.setter
    def val(self, val):
        self._set(val)

Here's an example of use (from a jupyter notebook page):

l1 = list(range(10))
def l1_5_getter(lst=l1, number=5):
    return lst[number]

def l1_5_setter(val, lst=l1, number=5):
    lst[number] = val

[
    l1_5_getter(),
    l1_5_setter(12),
    l1,
    l1_5_getter()
]

Out = [5, None, [0, 1, 2, 3, 4, 12, 6, 7, 8, 9], 12]

p = Parameter(l1_5_getter, l1_5_setter)

print([
    p(),
    p.get(),
    p.val,
    p(13),
    p(),
    p.set(14),
    p.get()
])
p.val = 15
print(p.val, l1)

[12, 12, 12, 13, 13, None, 14]
15 [0, 1, 2, 3, 4, 15, 6, 7, 8, 9]

Of course, it is also easy to make this work for dict items or attributes of an object. There is even a way to do what the OP asked for, using globals():

def setter(val, dict=globals(), key='a'):
    dict[key] = val

def getter(dict=globals(), key='a'):
    return dict[key]

pa = Parameter(getter, setter)
pa(2)
print(a)
pa(3)
print(a)

This will print out 2, followed by 3.

Messing with the global namespace in this way is kind of transparently a terrible idea, but it shows that it is possible (if inadvisable) to do what the OP asked for.

The example is, of course, fairly pointless. But I have found this class to be useful in the application for which I developed it: a mathematical model whose behavior is governed by numerous user-settable mathematical parameters, of diverse types (which, because they depend on command line arguments, are not known at compile time). And once access to something has been encapsulated in a Parameter object, all such objects can be manipulated in a uniform way.

Although it doesn't look much like a C or C++ pointer, this is solving a problem that I would have solved with pointers if I were writing in C++.

How to resize datagridview control when form resizes

If you want to show the complete headers text

this will auto resize the columns so that the headers will show complete header text.

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

For Dock Mode

If you want to show the Dock Mode in your panel or form.

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

AngularJS- Login and Authentication in each route and controller

Here is another possible solution, using the resolve attribute of the $stateProvider or the $routeProvider. Example with $stateProvider:

.config(["$stateProvider", function ($stateProvider) {

  $stateProvider

  .state("forbidden", {
    /* ... */
  })

  .state("signIn", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAnonymous(); }],
    }
  })

  .state("home", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAuthenticated(); }],
    }
  })

  .state("admin", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.hasRole("ROLE_ADMIN"); }],
    }
  });

}])

Access resolves or rejects a promise depending on the current user rights:

.factory("Access", ["$q", "UserProfile", function ($q, UserProfile) {

  var Access = {

    OK: 200,

    // "we don't know who you are, so we can't say if you're authorized to access
    // this resource or not yet, please sign in first"
    UNAUTHORIZED: 401,

    // "we know who you are, and your profile does not allow you to access this resource"
    FORBIDDEN: 403,

    hasRole: function (role) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasRole(role)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    hasAnyRole: function (roles) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasAnyRole(roles)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAnonymous: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAnonymous()) {
          return Access.OK;
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAuthenticated: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAuthenticated()) {
          return Access.OK;
        } else {
          return $q.reject(Access.UNAUTHORIZED);
        }
      });
    }

  };

  return Access;

}])

UserProfile copies the current user properties, and implement the $hasRole, $hasAnyRole, $isAnonymous and $isAuthenticated methods logic (plus a $refresh method, explained later):

.factory("UserProfile", ["Auth", function (Auth) {

  var userProfile = {};

  var clearUserProfile = function () {
    for (var prop in userProfile) {
      if (userProfile.hasOwnProperty(prop)) {
        delete userProfile[prop];
      }
    }
  };

  var fetchUserProfile = function () {
    return Auth.getProfile().then(function (response) {
      clearUserProfile();
      return angular.extend(userProfile, response.data, {

        $refresh: fetchUserProfile,

        $hasRole: function (role) {
          return userProfile.roles.indexOf(role) >= 0;
        },

        $hasAnyRole: function (roles) {
          return !!userProfile.roles.filter(function (role) {
            return roles.indexOf(role) >= 0;
          }).length;
        },

        $isAnonymous: function () {
          return userProfile.anonymous;
        },

        $isAuthenticated: function () {
          return !userProfile.anonymous;
        }

      });
    });
  };

  return fetchUserProfile();

}])

Auth is in charge of requesting the server, to know the user profile (linked to an access token attached to the request for example):

.service("Auth", ["$http", function ($http) {

  this.getProfile = function () {
    return $http.get("api/auth");
  };

}])

The server is expected to return such a JSON object when requesting GET api/auth:

{
  "name": "John Doe", // plus any other user information
  "roles": ["ROLE_ADMIN", "ROLE_USER"], // or any other role (or no role at all, i.e. an empty array)
  "anonymous": false // or true
}

Finally, when Access rejects a promise, if using ui.router, the $stateChangeError event will be fired:

.run(["$rootScope", "Access", "$state", "$log", function ($rootScope, Access, $state, $log) {

  $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    switch (error) {

    case Access.UNAUTHORIZED:
      $state.go("signIn");
      break;

    case Access.FORBIDDEN:
      $state.go("forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });

}])

If using ngRoute, the $routeChangeError event will be fired:

.run(["$rootScope", "Access", "$location", "$log", function ($rootScope, Access, $location, $log) {

  $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
    switch (rejection) {

    case Access.UNAUTHORIZED:
      $location.path("/signin");
      break;

    case Access.FORBIDDEN:
      $location.path("/forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });

}])

The user profile can also be accessed in the controllers:

.state("home", {
  /* ... */
  controller: "HomeController",
  resolve: {
    userProfile: "UserProfile"
  }
})

UserProfile then contains the properties returned by the server when requesting GET api/auth:

.controller("HomeController", ["$scope", "userProfile", function ($scope, userProfile) {

  $scope.title = "Hello " + userProfile.name; // "Hello John Doe" in the example

}])

UserProfile needs to be refreshed when a user signs in or out, so that Access can handle the routes with the new user profile. You can either reload the whole page, or call UserProfile.$refresh(). Example when signing in:

.service("Auth", ["$http", function ($http) {

  /* ... */

  this.signIn = function (credentials) {
    return $http.post("api/auth", credentials).then(function (response) {
      // authentication succeeded, store the response access token somewhere (if any)
    });
  };

}])
.state("signIn", {
  /* ... */
  controller: "SignInController",
  resolve: {
    /* ... */
    userProfile: "UserProfile"
  }
})
.controller("SignInController", ["$scope", "$state", "Auth", "userProfile", function ($scope, $state, Auth, userProfile) {

  $scope.signIn = function () {
    Auth.signIn($scope.credentials).then(function () {
      // user successfully authenticated, refresh UserProfile
      return userProfile.$refresh();
    }).then(function () {
      // UserProfile is refreshed, redirect user somewhere
      $state.go("home");
    });
  };

}])

How do I get the last character of a string using an Excel function?

No need to apologize for asking a question! Try using the RIGHT function. It returns the last n characters of a string.

=RIGHT(A1, 1)

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

I suspect GCC (mingw) has custom code to disable the checks for the wide printf functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s and %ls backwards for the wide printf functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.

Align image in center and middle within div

This can also be done using the Flexbox layout:

STATIC SIZE

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    height: 300px; /* Or whatever */_x000D_
    background-color: #000;_x000D_
}_x000D_
_x000D_
.child {_x000D_
    width: 100px;  /* Or whatever */_x000D_
    height: 100px; /* Or whatever */_x000D_
    margin: auto;  /* Magic! */_x000D_
}
_x000D_
<div class="parent">_x000D_
    <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DYNAMIC SIZE

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  background-color: #999;_x000D_
}_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  margin: auto;_x000D_
  background-color: #000;_x000D_
  display: flex;_x000D_
  height: 80%;_x000D_
  width: 80%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  margin: auto;  /* Magic! */_x000D_
  max-width: 100%;_x000D_
  max-height: 100%;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I found the example in this article, which does a great job explaining the how to use layout.

How to get current class name including package name in Java?

use this.getClass().getName() to get packageName.className and use this.getClass().getSimpleName() to get only class name

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Take multiple lists into dataframe

Just adding that using the first approach it can be done as -

pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))

Differences between socket.io and websockets

Misconceptions

There are few common misconceptions regarding WebSocket and Socket.IO:

  1. The first misconception is that using Socket.IO is significantly easier than using WebSocket which doesn't seem to be the case. See examples below.

  2. The second misconception is that WebSocket is not widely supported in the browsers. See below for more info.

  3. The third misconception is that Socket.IO downgrades the connection as a fallback on older browsers. It actually assumes that the browser is old and starts an AJAX connection to the server, that gets later upgraded on browsers supporting WebSocket, after some traffic is exchanged. See below for details.

My experiment

I wrote an npm module to demonstrate the difference between WebSocket and Socket.IO:

It is a simple example of server-side and client-side code - the client connects to the server using either WebSocket or Socket.IO and the server sends three messages in 1s intervals, which are added to the DOM by the client.

Server-side

Compare the server-side example of using WebSocket and Socket.IO to do the same in an Express.js app:

WebSocket Server

WebSocket server example using Express.js:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js

Socket.IO Server

Socket.IO server example using Express.js:

var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
  console.error('socket.io connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js

Client-side

Compare the client-side example of using WebSocket and Socket.IO to do the same in the browser:

WebSocket Client

WebSocket client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html

Socket.IO Client

Socket.IO client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html

Network traffic

To see the difference in network traffic you can run my test. Here are the results that I got:

WebSocket Results

2 requests, 1.50 KB, 0.05 s

From those 2 requests:

  1. HTML page itself
  2. connection upgrade to WebSocket

(The connection upgrade request is visible on the developer tools with a 101 Switching Protocols response.)

Socket.IO Results

6 requests, 181.56 KB, 0.25 s

From those 6 requests:

  1. the HTML page itself
  2. Socket.IO's JavaScript (180 kilobytes)
  3. first long polling AJAX request
  4. second long polling AJAX request
  5. third long polling AJAX request
  6. connection upgrade to WebSocket

Screenshots

WebSocket results that I got on localhost:

WebSocket results - websocket-vs-socket.io module

Socket.IO results that I got on localhost:

Socket.IO results - websocket-vs-socket.io module

Test yourself

Quick start:

# Install:
npm i -g websocket-vs-socket.io
# Run the server:
websocket-vs-socket.io

Open http://localhost:3001/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the WebSocket version.

Open http://localhost:3002/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the Socket.IO version.

To uninstall:

# Uninstall:
npm rm -g websocket-vs-socket.io

Browser compatibility

As of June 2016 WebSocket works on everything except Opera Mini, including IE higher than 9.

This is the browser compatibility of WebSocket on Can I Use as of June 2016:

enter image description here

See http://caniuse.com/websockets for up-to-date info.

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

Bootstrap modal: is not a function

Run

npm i @types/jquery
npm install -D @types/bootstrap

in the project to add the jquery types in your Angular Project. After that include

import * as $ from "jquery";
import * as bootstrap from "bootstrap";

in your app.module.ts

Add

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

in your index.html just before the body closing tag.

And if you are running Angular 2-7 include "jquery" in the types field of tsconfig.app.json file.

This will remove all error of 'modal' and '$' in your Angular project.

ImportError: No module named site on Windows

In my case, the issue was another site.py file, that was resolved earlier than the one from Python\Lib, due to PATH setting.

Environment: Windows 10 Pro, Python27.

My desktop has pgAdmin installed, which has file C:\Program Files (x86)\pgAdmin\venv\Lib\site.py. Because PATH environment variable had pdAdmin's home earlier than Python (apparently a bad idea in the first place), pgAdmin's site.py was found first.

All I had to do to fix the issue was to move pgAdmin's home later than Python, in PATH

Stored procedure - return identity as output parameter or scalar

Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).

I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):

CREATE PROCEDURE My_Insert
    @col1            VARCHAR(20),
    @new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO My_Table (col1)
    VALUES (@col1)

    SELECT @new_identity = SCOPE_IDENTITY()

    SELECT @new_identity AS id

    RETURN
END

The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.

A transport-level error has occurred when receiving results from the server

In my case the "SQL Server" Server service stopped. When I restarted the service that enabled me to run the query and eliminate the error.

Its also a good idea to examine your query to find out why the query made this service stop

enter image description here

Detecting Windows or Linux?

apache commons lang has a class SystemUtils.java you can use :

SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Replacing column values in a pandas DataFrame

dic = {'female':1, 'male':0}
w['female'] = w['female'].replace(dic)

.replace has as argument a dictionary in which you may change and do whatever you want or need.

Add image to left of text via css

For adding background icon always before text when length of text is not known in advance.

.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}

Decorators with parameters?

define this "decoratorize function" to generate customized decorator function:

def decoratorize(FUN, **kw):
    def foo(*args, **kws):
        return FUN(*args, **kws, **kw)
    return foo

use it this way:

    @decoratorize(FUN, arg1 = , arg2 = , ...)
    def bar(...):
        ...

How can you use php in a javascript function

I think you're confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I'd recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

Can I animate absolute positioned element with CSS transition?

Please Try this code margin-left:60px instead of left:60px

please take a look: http://jsfiddle.net/hbirjand/2LtBh/2/

as @Shomz said,transition must be changed to transition:margin 1s linear; instead of transition:all 1s linear;

How to run single test method with phpunit?

for run phpunit test in laravel by many way ..

vendor/bin/phpunit --filter methodName className pathTofile.php

vendor/bin/phpunit --filter 'namespace\\directoryName\\className::methodName'

for test single class :

vendor/bin/phpunit --filter  tests/Feature/UserTest.php
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest'
vendor/bin/phpunit --filter 'UserTest' 

for test single method :

 vendor/bin/phpunit --filter testExample 
 vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest::testExample'
 vendor/bin/phpunit --filter testExample UserTest tests/Feature/UserTest.php

for run tests from all class within namespace :

vendor/bin/phpunit --filter 'Tests\\Feature'

for more way run test see more

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Case insensitive searching in Oracle

There are 3 main ways to perform a case-insensitive search in Oracle without using full-text indexes.

Ultimately what method you choose is dependent on your individual circumstances; the main thing to remember is that to improve performance you must index correctly for case-insensitive searching.

1. Case your column and your string identically.

You can force all your data to be the same case by using UPPER() or LOWER():

select * from my_table where upper(column_1) = upper('my_string');

or

select * from my_table where lower(column_1) = lower('my_string');

If column_1 is not indexed on upper(column_1) or lower(column_1), as appropriate, this may force a full table scan. In order to avoid this you can create a function-based index.

create index my_index on my_table ( lower(column_1) );

If you're using LIKE then you have to concatenate a % around the string you're searching for.

select * from my_table where lower(column_1) LIKE lower('my_string') || '%';

This SQL Fiddle demonstrates what happens in all these queries. Note the Explain Plans, which indicate when an index is being used and when it isn't.

2. Use regular expressions.

From Oracle 10g onwards REGEXP_LIKE() is available. You can specify the _match_parameter_ 'i', in order to perform case-insensitive searching.

In order to use this as an equality operator you must specify the start and end of the string, which is denoted by the carat and the dollar sign.

select * from my_table where regexp_like(column_1, '^my_string$', 'i');

In order to perform the equivalent of LIKE, these can be removed.

select * from my_table where regexp_like(column_1, 'my_string', 'i');

Be careful with this as your string may contain characters that will be interpreted differently by the regular expression engine.

This SQL Fiddle shows you the same example output except using REGEXP_LIKE().

3. Change it at the session level.

The NLS_SORT parameter governs the collation sequence for ordering and the various comparison operators, including = and LIKE. You can specify a binary, case-insensitive, sort by altering the session. This will mean that every query performed in that session will perform case-insensitive parameters.

alter session set nls_sort=BINARY_CI

There's plenty of additional information around linguistic sorting and string searching if you want to specify a different language, or do an accent-insensitive search using BINARY_AI.

You will also need to change the NLS_COMP parameter; to quote:

The exact operators and query clauses that obey the NLS_SORT parameter depend on the value of the NLS_COMP parameter. If an operator or clause does not obey the NLS_SORT value, as determined by NLS_COMP, the collation used is BINARY.

The default value of NLS_COMP is BINARY; but, LINGUISTIC specifies that Oracle should pay attention to the value of NLS_SORT:

Comparisons for all SQL operations in the WHERE clause and in PL/SQL blocks should use the linguistic sort specified in the NLS_SORT parameter. To improve the performance, you can also define a linguistic index on the column for which you want linguistic comparisons.

So, once again, you need to alter the session

alter session set nls_comp=LINGUISTIC

As noted in the documentation you may want to create a linguistic index to improve performance

create index my_linguistc_index on my_table 
   (NLSSORT(column_1, 'NLS_SORT = BINARY_CI'));

Converting from byte to int in java

Primitive data types (such as byte) don't have methods in java, but you can directly do:

int i=rno[0];

How to check if an element is off-screen

I know this is kind of late but this plugin should work. http://remysharp.com/2009/01/26/element-in-view-event-plugin/

$('p.inview').bind('inview', function (event, visible) {
if (visible) {
  $(this).text('You can see me!');
} else {
  $(this).text('Hidden again');
}

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

data.frame rows to a list

The best way for me was:

Example data:

Var1<-c("X1",X2","X3")
Var2<-c("X1",X2","X3")
Var3<-c("X1",X2","X3")

Data<-cbind(Var1,Var2,Var3)

ID    Var1   Var2  Var3 
1      X1     X2    X3
2      X4     X5    X6
3      X7     X8    X9

We call the BBmisc library

library(BBmisc)

data$lists<-convertRowsToList(data[,2:4])

And the result will be:

ID    Var1   Var2  Var3  lists
1      X1     X2    X3   list("X1", "X2", X3") 
2      X4     X5    X6   list("X4","X5", "X6") 
3      X7     X8    X9   list("X7,"X8,"X9) 

How to get the element clicked (for the whole document)?

$(document).click(function (e) {
    alert($(e.target).text());
});

python how to pad numpy array with zeros

I understand that your main problem is that you need to calculate d=b-a but your arrays have different sizes. There is no need for an intermediate padded c

You can solve this without padding:

import numpy as np

a = np.array([[ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.]])

b = np.array([[ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.]])

d = b.copy()
d[:a.shape[0],:a.shape[1]] -=  a

print d

Output:

[[ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 3.  3.  3.  3.  3.  3.]]

Reading in from System.in - Java

class myFileReaderThatStarts with arguments
{

 class MissingArgumentException extends Exception{      
      MissingArgumentException(String s)
  {
     super(s);
  }

   }    
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value 
if(args.length>0)
{
    // do something with args[0]
}
else
{
// default in a path 
// or 
   throw new MissingArgumentException("You need to start this program with a path");
}
}

How to get build time stamp from Jenkins build variables?

Generate environment variables from script (Unix script) :

echo "BUILD_DATE=$(date +%F-%T)"

Use Font Awesome icon as CSS content

Update for FontAwesome 5 Thanks to Aurelien

You need to change the font-family to Font Awesome 5 Brands OR Font Awesome 5 Free, based on the type of icon you are trying to render. Also, do not forget to declare font-weight: 900;

a:before {
   font-family: "Font Awesome 5 Free";
   content: "\f095";
   display: inline-block;
   padding-right: 3px;
   vertical-align: middle;
   font-weight: 900;
}

Demo

You can read the rest of the answer below to understand how it works and to know some workarounds for spacing between icon and the text.


FontAwesome 4 and below

That's the wrong way to use it. Open the font awesome style sheet, go to the class of the font you want to use say fa-phone, copy the content property under that class with the entity, and use it like:

a:before {
    font-family: FontAwesome;
    content: "\f095";
}

Demo

Just make sure that if you are looking to target a specific a tag, then consider using a class instead to make it more specific like:

a.class_name:before {
    font-family: FontAwesome;
    content: "\f095";
}

Using the way above will stick the icon with the remaining text of yours, so if you want to have a bit of space between the two of them, make it display: inline-block; and use some padding-right:

a:before {
    font-family: FontAwesome;
    content: "\f095";
    display: inline-block;
    padding-right: 3px;
    vertical-align: middle;
}

Extending this answer further, since many might be having a requirement to change an icon on hover, so for that, we can write a separate selector and rules for :hover action:

a:hover:before {
    content: "\f099"; /* Code of the icon you want to change on hover */
}

Demo

Now in the above example, icon nudges because of the different size and you surely don't want that, so you can set a fixed width on the base declaration like

a:before {
    /* Other properties here, look in the above code snippets */
    width: 12px; /* add some desired width here to prevent nudge */
}

Demo

How can I copy a conditional formatting from one document to another?

If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.

Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.

Getting the count of unique values in a column in bash

Perl

This code computes the occurrences of all columns, and prints a sorted report for each of them:

# columnvalues.pl
while (<>) {
    @Fields = split /\s+/;
    for $i ( 0 .. $#Fields ) {
        $result[$i]{$Fields[$i]}++
    };
}
for $j ( 0 .. $#result ) {
    print "column $j:\n";
    @values = keys %{$result[$j]};
    @sorted = sort { $result[$j]{$b} <=> $result[$j]{$a}  ||  $a cmp $b } @values;
    for $k ( @sorted ) {
        print " $k $result[$j]{$k}\n"
    }
}

Save the text as columnvalues.pl
Run it as: perl columnvalues.pl files*

Explanation

In the top-level while loop:
* Loop over each line of the combined input files
* Split the line into the @Fields array
* For every column, increment the result array-of-hashes data structure

In the top-level for loop:
* Loop over the result array
* Print the column number
* Get the values used in that column
* Sort the values by the number of occurrences
* Secondary sort based on the value (for example b vs g vs m vs z)
* Iterate through the result hash, using the sorted list
* Print the value and number of each occurrence

Results based on the sample input files provided by @Dennis

column 0:
 a 3
 z 3
 t 1
 v 1
 w 1
column 1:
 d 3
 r 2
 b 1
 g 1
 m 1
 z 1
column 2:
 c 4
 a 3
 e 2

.csv input

If your input files are .csv, change /\s+/ to /,/

Obfuscation

In an ugly contest, Perl is particularly well equipped.
This one-liner does the same:

perl -lane 'for $i (0..$#F){$g[$i]{$F[$i]}++};END{for $j (0..$#g){print "$j:";for $k (sort{$g[$j]{$b}<=>$g[$j]{$a}||$a cmp $b} keys %{$g[$j]}){print " $k $g[$j]{$k}"}}}' files*

Change the "From:" address in Unix "mail"

I don't know if it's the same with other OS, but in OpenBSD, the mail command has this syntax:

mail to-addr ... -sendmail-options ...

sendmail has -f option where you indicate the email address for the FROM: field. The following command works for me.

mail [email protected] -f [email protected]

List vs tuple, when to use each?

Must it be mutable? Use a list. Must it not be mutable? Use a tuple.

Otherwise, it's a question of choice.

For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.

Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.

Difference between Date(dateString) and new Date(dateString)

The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.

For More Information:

Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

What is the difference between String and StringBuffer in Java?

String is used to manipulate character strings that cannot be changed (read-only and immutable).

StringBuffer is used to represent characters that can be modified.

Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.

You can also use StringBuilder which is similar to StringBuffer except it is not synchronized. The maximum size for either of these is Integer.MAX_VALUE (231 - 1 = 2,147,483,647) or maximum heap size divided by 2 (see How many characters can a Java String have?). More information here.

How to do multiline shell script in Ansible

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

mentions YAML line continuations.

As an example (tried with ansible 2.0.0.2):

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

The shell command is collapsed into a single line, as in ls --color /home

Eclipse: How to install a plugin manually?

  1. Download your plugin
  2. Open Eclipse
  3. From the menu choose: Help / Install New Software...
  4. Click the Add button
  5. In the Add Repository dialog that appears, click the Archive button next to the Location field
  6. Select your plugin file, click OK

You could also just copy plugins to the eclipse/plugins directory, but it's not recommended.

Getting Class type from String

You can get the Class reference of any class during run time through the Java Reflection Concept.

Check the Below Code. Explanation is given below

Here is one example that uses returned Class to create an instance of AClass:

package com.xyzws;
class AClass {
    public AClass() {
        System.out.println("AClass's Constructor"); 
    }  
    static {   
        System.out.println("static block in AClass");  
    }
}
public class Program {   
    public static void main(String[] args) {
        try {       
            System.out.println("The first time calls forName:");   
            Class c = Class.forName("com.xyzws.AClass");      
            AClass a = (AClass)c.newInstance();    
            System.out.println("The second time calls forName:");  
            Class c1 = Class.forName("com.xyzws.AClass"); 
        } catch (ClassNotFoundException e) { 
            // ...
        } catch (InstantiationException e) {  
            // ...
        } catch (IllegalAccessException e) { 
            // ...
        }     
    }
}

The printed output is

    The first time calls forName:
    static block in AClass
    AClass's Constructor
    The second time calls forName:

The class has already been loaded so there is no second "static block in AClass"

The Explanation is below

Class.ForName is called to get a Class Object

By Using the Class Object we are creating the new instance of the Class.

Any doubts about this let me know

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Failed to find 'ANDROID_HOME' environment variable

Execute: sudo gedit ~/.bashrc add

JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export JAVA_HOME
PATH=$PATH:$JAVA_HOME
export PATH
export ANDROID_HOME=~/Android/Sdk 
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

and

source ~/.bashrc

How to round each item in a list of floats to 2 decimal places?

mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
myRoundedList =  [round(x,2) for x in mylist] 
# [0.3, 0.5, 0.2]

SQL variable to hold list of integers

I use this :

1-Declare a temp table variable in the script your building:

DECLARE @ShiftPeriodList TABLE(id INT NOT NULL);

2-Allocate to temp table:

IF (SOME CONDITION) 
BEGIN 
        INSERT INTO @ShiftPeriodList SELECT ShiftId FROM [hr].[tbl_WorkShift]
END
IF (SOME CONDITION2)
BEGIN
    INSERT INTO @ShiftPeriodList
        SELECT  ws.ShiftId
        FROM [hr].[tbl_WorkShift] ws
        WHERE ws.WorkShift = 'Weekend(VSD)' OR ws.WorkShift = 'Weekend(SDL)'

END

3-Reference the table when you need it in a WHERE statement :

INSERT INTO SomeTable WHERE ShiftPeriod IN (SELECT * FROM @ShiftPeriodList)

The static keyword and its various uses in C++

In order to clarify the question, I would rather categorize the usage of 'static' keyword in three different forms:

(A). variables

(B). functions

(C). member variables/functions of classes

the explanation follows below for each of the sub headings:

(A) 'static' keyword for variables

This one can be little tricky however if explained and understood properly, it's pretty straightforward.

To explain this, first it is really useful to know about the scope, duration and linkage of variables, without which things are always difficult to see through the murky concept of staic keyword

1. Scope : Determines where in the file, the variable is accessible. It can be of two types: (i) Local or Block Scope. (ii) Global Scope

2. Duration : Determines when a variable is created and destroyed. Again it's of two types: (i) Automatic Storage Duration (for variables having Local or Block scope). (ii) Static Storage Duration (for variables having Global Scope or local variables (in a function or a in a code block) with static specifier).

3. Linkage: Determines whether a variable can be accessed (or linked ) in another file. Again ( and luckily) it is of two types: (i) Internal Linkage (for variables having Block Scope and Global Scope/File Scope/Global Namespace scope) (ii) External Linkage (for variables having only for Global Scope/File Scope/Global Namespace Scope)

Let's refer an example below for better understanding of plain global and local variables (no local variables with static storage duration) :

//main file
#include <iostream>

int global_var1; //has global scope
const global_var2(1.618); //has global scope

int main()
{
//these variables are local to the block main.
//they have automatic duration, i.e, they are created when the main() is 
//  executed and destroyed, when main goes out of scope
 int local_var1(23);
 const double local_var2(3.14);

 {
/* this is yet another block, all variables declared within this block are 
 have local scope limited within this block. */
// all variables declared within this block too have automatic duration, i.e, 
/*they are created at the point of definition within this block,
 and destroyed as soon as this block ends */
   char block_char1;
   int local_var1(32) //NOTE: this has been re-declared within the block, 
//it shadows the local_var1 declared outside

 std::cout << local_var1 <<"\n"; //prints 32

  }//end of block
  //local_var1 declared inside goes out of scope

 std::cout << local_var1 << "\n"; //prints 23

 global_var1 = 29; //global_var1 has been declared outside main (global scope)
 std::cout << global_var1 << "\n"; //prints 29
 std::cout << global_var2 << "\n"; //prints 1.618

 return 0;
}  //local_var1, local_var2 go out of scope as main ends
//global_var1, global_var2 go out of scope as the program terminates 
//(in this case program ends with end of main, so both local and global
//variable go out of scope together

Now comes the concept of Linkage. When a global variable defined in one file is intended to be used in another file, the linkage of the variable plays an important role.

The Linkage of global variables is specified by the keywords: (i) static , and, (ii) extern

( Now you get the explanation )

static keyword can be applied to variables with local and global scope, and in both the cases, they mean different things. I will first explain the usage of 'static' keyword in variables with global scope ( where I also clarify the usage of keyword 'extern') and later the for those with local scope.

1. Static Keyword for variables with global scope

Global variables have static duration, meaning they don't go out of scope when a particular block of code (for e.g main() ) in which it is used ends . Depending upon the linkage, they can be either accessed only within the same file where they are declared (for static global variable), or outside the file even outside the file in which they are declared (extern type global variables)

In the case of a global variable having extern specifier, and if this variable is being accessed outside the file in which it has been initialized, it has to be forward declared in the file where it's being used, just like a function has to be forward declared if it's definition is in a file different from where it's being used.

In contrast, if the global variable has static keyword, it cannot be used in a file outside of which it has been declared.

(see example below for clarification)

eg:

//main2.cpp
 static int global_var3 = 23;  /*static global variable, cannot be                            
                                accessed in anyother file */
 extern double global_var4 = 71; /*can be accessed outside this file                  linked to main2.cpp */
 int main() { return 0; }

main3.cpp

//main3.cpp
#include <iostream>

int main()
{
   extern int gloabl_var4; /*this variable refers to the gloabal_var4
                            defined in the main2.cpp file */
  std::cout << global_var4 << "\n"; //prints 71;

  return 0;
}

now any variable in c++ can be either a const or a non-const and for each 'const-ness' we get two case of default c++ linkage, in case none is specified:

(i) If a global variable is non-const, its linkage is extern by default, i.e, the non-const global variable can be accessed in another .cpp file by forward declaration using the extern keyword (in other words, non const global variables have external linkage ( with static duration of course)). Also usage of extern keyword in the original file where it has been defined is redundant. In this case to make a non-const global variable inaccessible to external file, use the specifier 'static' before the type of the variable.

(ii) If a global variable is const, its linkage is static by default, i.e a const global variable cannot be accessed in a file other than where it is defined, (in other words, const global variables have internal linkage (with static duration of course)). Also usage of static keyword to prevent a const global variable from being accessed in another file is redundant. Here, to make a const global variable have an external linkage, use the specifier 'extern' before the type of the variable

Here's a summary for global scope variables with various linkages

//globalVariables1.cpp 

// defining uninitialized vairbles
int globalVar1; //  uninitialized global variable with external linkage 
static int globalVar2; // uninitialized global variable with internal linkage
const int globalVar3; // error, since const variables must be initialized upon declaration
const int globalVar4 = 23; //correct, but with static linkage (cannot be accessed outside the file where it has been declared*/
extern const double globalVar5 = 1.57; //this const variable ca be accessed outside the file where it has been declared

Next we investigate how the above global variables behave when accessed in a different file.

//using_globalVariables1.cpp (eg for the usage of global variables above)

// Forward declaration via extern keyword:
 extern int globalVar1; // correct since globalVar1 is not a const or static
 extern int globalVar2; //incorrect since globalVar2 has internal linkage
 extern const int globalVar4; /* incorrect since globalVar4 has no extern 
                         specifier, limited to internal linkage by
                         default (static specifier for const variables) */
 extern const double globalVar5; /*correct since in the previous file, it 
                           has extern specifier, no need to initialize the
                       const variable here, since it has already been
                       legitimately defined perviously */

2. Static Keyword for variables with Local Scope

Updates (August 2019) on static keyword for variables in local scope

This further can be subdivided in two categories :

(i) static keyword for variables within a function block, and (ii) static keyword for variables within a unnamed local block.

(i) static keyword for variables within a function block.

Earlier, I mentioned that variables with local scope have automatic duration, i.e they come to exist when the block is entered ( be it a normal block, be it a function block) and cease to exist when the block ends, long story short, variables with local scope have automatic duration and automatic duration variables (and objects) have no linkage meaning they are not visible outside the code block.

If static specifier is applied to a local variable within a function block, it changes the duration of the variable from automatic to static and its life time is the entire duration of the program which means it has a fixed memory location and its value is initialized only once prior to program start up as mentioned in cpp reference(initialization should not be confused with assignment)

lets take a look at an example.

//localVarDemo1.cpp    
 int localNextID()
{
  int tempID = 1;  //tempID created here
  return tempID++; //copy of tempID returned and tempID incremented to 2
} //tempID destroyed here, hence value of tempID lost

int newNextID()
{
  static int newID = 0;//newID has static duration, with internal linkage
  return newID++; //copy of newID returned and newID incremented by 1
}  //newID doesn't get destroyed here :-)


int main()
{
  int employeeID1 = localNextID();  //employeeID1 = 1
  int employeeID2 = localNextID();  // employeeID2 = 1 again (not desired)
  int employeeID3 = newNextID(); //employeeID3 = 0;
  int employeeID4 = newNextID(); //employeeID4 = 1;
  int employeeID5 = newNextID(); //employeeID5 = 2;
  return 0;
}

Looking at the above criterion for static local variables and static global variables, one might be tempted to ask, what the difference between them could be. While global variables are accessible at any point in within the code (in same as well as different translation unit depending upon the const-ness and extern-ness), a static variable defined within a function block is not directly accessible. The variable has to be returned by the function value or reference. Lets demonstrate this by an example:

//localVarDemo2.cpp 

//static storage duration with global scope 
//note this variable can be accessed from outside the file
//in a different compilation unit by using `extern` specifier
//which might not be desirable for certain use case.
static int globalId = 0;

int newNextID()
{
  static int newID = 0;//newID has static duration, with internal linkage
  return newID++; //copy of newID returned and newID incremented by 1
}  //newID doesn't get destroyed here


int main()
{
    //since globalId is accessible we use it directly
  const int globalEmployee1Id = globalId++; //globalEmployeeId1 = 0;
  const int globalEmployee2Id = globalId++; //globalEmployeeId1 = 1;

  //const int employeeID1 = newID++; //this will lead to compilation error since newID++ is not accessible direcly. 
  int employeeID2 = newNextID(); //employeeID3 = 0;
  int employeeID2 = newNextID(); //employeeID3 = 1;

  return 0;
}

More explaination about choice of static global and static local variable could be found on this stackoverflow thread

(ii) static keyword for variables within a unnamed local block.

static variables within a local block (not a function block) cannot be accessed outside the block once the local block goes out of scope. No caveats to this rule.

    //localVarDemo3.cpp 
    int main()
    {

      {
          const static int static_local_scoped_variable {99};
      }//static_local_scoped_variable goes out of scope

      //the line below causes compilation error
      //do_something is an arbitrary function
      do_something(static_local_scoped_variable);
      return 0;
    }

C++11 introduced the keyword constexpr which guarantees the evaluation of an expression at compile time and allows compiler to optimize the code. Now if the value of a static const variable within a scope is known at compile time, the code is optimized in a manner similar to the one with constexpr. Here's a small example

I recommend readers also to look up the difference between constexprand static const for variables in this stackoverflow thread. this concludes my explanation for the static keyword applied to variables.

B. 'static' keyword used for functions

in terms of functions, the static keyword has a straightforward meaning. Here, it refers to linkage of the function Normally all functions declared within a cpp file have external linkage by default, i.e a function defined in one file can be used in another cpp file by forward declaration.

using a static keyword before the function declaration limits its linkage to internal , i.e a static function cannot be used within a file outside of its definition.

C. Staitc Keyword used for member variables and functions of classes

1. 'static' keyword for member variables of classes

I start directly with an example here

#include <iostream>

class DesignNumber
{
  private:

      static int m_designNum;  //design number
      int m_iteration;     // number of iterations performed for the design

  public:
    DesignNumber() {     }  //default constructor

   int  getItrNum() //get the iteration number of design
   {
      m_iteration = m_designNum++;
      return m_iteration;
   }
     static int m_anyNumber;  //public static variable
};
int DesignNumber::m_designNum = 0; // starting with design id = 0
                     // note : no need of static keyword here
                     //causes compiler error if static keyword used
int DesignNumber::m_anyNumber = 99; /* initialization of inclass public 
                                    static member  */
enter code here

int main()
{
   DesignNumber firstDesign, secondDesign, thirdDesign;
   std::cout << firstDesign.getItrNum() << "\n";  //prints 0
   std::cout << secondDesign.getItrNum() << "\n"; //prints 1
   std::cout << thirdDesign.getItrNum() << "\n";  //prints 2

   std::cout << DesignNumber::m_anyNumber++ << "\n";  /* no object
                                        associated with m_anyNumber */
   std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 100
   std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 101

   return 0;
}

In this example, the static variable m_designNum retains its value and this single private member variable (because it's static) is shared b/w all the variables of the object type DesignNumber

Also like other member variables, static member variables of a class are not associated with any class object, which is demonstrated by the printing of anyNumber in the main function

const vs non-const static member variables in class

(i) non-const class static member variables In the previous example the static members (both public and private) were non constants. ISO standard forbids non-const static members to be initialized in the class. Hence as in previous example, they must be initalized after the class definition, with the caveat that the static keyword needs to be omitted

(ii) const-static member variables of class this is straightforward and goes with the convention of other const member variable initialization, i.e the const static member variables of a class can be initialized at the point of declaration and they can be initialized at the end of the class declaration with one caveat that the keyword const needs to be added to the static member when being initialized after the class definition.

I would however, recommend to initialize the const static member variables at the point of declaration. This goes with the standard C++ convention and makes the code look cleaner

for more examples on static member variables in a class look up the following link from learncpp.com http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

2. 'static' keyword for member function of classes

Just like member variables of classes can ,be static, so can member functions of classes. Normal member functions of classes are always associated with a object of the class type. In contrast, static member functions of a class are not associated with any object of the class, i.e they have no *this pointer.

Secondly since the static member functions of the class have no *this pointer, they can be called using the class name and scope resolution operator in the main function (ClassName::functionName(); )

Thirdly static member functions of a class can only access static member variables of a class, since non-static member variables of a class must belong to a class object.

for more examples on static member functions in a class look up the following link from learncpp.com

http://www.learncpp.com/cpp-tutorial/812-static-member-functions/

How to remove the arrow from a select element in Firefox

This works (tested on Firefox 23.0.1):

select {
    -moz-appearance: radio-container;
}

Removing MySQL 5.7 Completely

First of all, do a backup of your needed databases with mysqldump

Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).

In total, do this:

sudo service mysql stop  #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql

All above commands in single line (just copy and paste):

sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql

MS SQL compare dates?

I am always used DateDiff(day,date1,date2) to compare two date.

Checkout following example. Just copy that and run in Ms sql server. Also, try with change date by 31 dec to 30 dec and check result

BEGIN

declare @firstDate datetime
declare @secondDate datetime


declare @chkDay int

set @firstDate ='2010-12-31 15:13:48.593'
set @secondDate ='2010-12-31 00:00:00.000'

set @chkDay=Datediff(day,@firstDate ,@secondDate )

if @chkDay=0
    Begin
        Print 'Date is Same'
    end
else
    Begin
        Print 'Date is not Same'
    end
End

Android replace the current fragment with another fragment

If you have a handle to an existing fragment you can just replace it with the fragment's ID.

Example in Kotlin:

fun aTestFuction() {
   val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
   val newFragment = MyNewFragment()
   replaceFragment(existingFragment, newFragment, "myTag")
}

fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
    supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
}

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Go to: chrome://flags/

Enable: Allow invalid certificates for resources loaded from localhost.

You don't have the green security, but you are always allowed for https://localhost in chrome.

How to get the entire document HTML as a string?

You can also do:

document.getElementsByTagName('html')[0].innerHTML

You will not get the Doctype or html tag, but everything else...

How can I scale an entire web page with CSS?

With this code 1em or 100% will equal to 1% of the body height

document.body.style.fontSize = ((window.innerHeight/100)*6.25)+"%"

Determine the number of lines within a text file

You can launch the "wc.exe" executable (comes with UnixUtils and does not need installation) run as an external process. It supports different line count methods (like unix vs mac vs windows).

element not interactable exception in selenium web automation

Please try selecting the password field like this.

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#Passwd")));
    passwordElement.click();
  passwordElement.clear();
     passwordElement.sendKeys("123");

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

Since the user asked for more than one timezone option, then you can make it generic.

Generic Function

function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
 $date = new DateTime($date,new DateTimeZone($timezone));
 $date->setTimezone( new DateTimeZone($timezone_to) );
 return $date->format($format);
}

Usage:

echo  convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');

Output:

2011-04-21 09:14:00

how to hide keyboard after typing in EditText in android?

editText.setInputType(InputType.TYPE_NULL);

Open a selected file (image, pdf, ...) programmatically from my Android Application?

You can get any file mime type with getContentResolver().getType(uri):

protected static void openFile(Context context, Uri localUri){
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        i.setDataAndType(localUri, context.getContentResolver().getType(localUri));
        context.startActivity(i);
    }

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Try adding the following to your eclipse.ini file:

-vm
C:\Program Files\Java\jdk1.7.0_01\bin\java.exe

You might also have to change the Dosgi.requiredJavaVersion to 1.7 in the same file.

Is there a command to undo git init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

link_to image tag. how to add class to a tag

this is my solution:

<%= link_to root_path do %>
   <%= image_tag "image.jpg", class: "some class here" %>
<% end %>

Still Reachable Leak detected by Valgrind

Since there is some routine from the the pthread family on the bottom (but I don't know that particular one), my guess would be that you have launched some thread as joinable that has terminated execution.

The exit state information of that thread is kept available until you call pthread_join. Thus, the memory is kept in a loss record at program termination, but it is still reachable since you could use pthread_join to access it.

If this analysis is correct, either launch these threads detached, or join them before terminating your program.

Edit: I ran your sample program (after some obvious corrections) and I don't have errors but the following

==18933== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
--18933-- 
--18933-- used_suppression:      2 dl-hack3-cond-1
--18933-- used_suppression:      2 glibc-2.5.x-on-SUSE-10.2-(PPC)-2a

Since the dl- thing resembles much of what you see I guess that you see a known problem that has a solution in terms of a suppression file for valgrind. Perhaps your system is not up to date, or your distribution doesn't maintain these things. (Mine is ubuntu 10.4, 64bit)

How to display errors on laravel 4?

Go to app/config/app.php

and set 'debug' => true,

Python: Making a beep noise

On Windows, if you want to just make the computer make a beep sound:

import winsound
frequency = 2500  # Set Frequency To 2500 Hertz
duration = 1000  # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)

The winsound.Beep() can be used wherever you want the beep to occur.

How can I easily add storage to a VirtualBox machine with XP installed?

Step 1 : create new virtual disk as per @mhaller instruction

Step 2 : Open Run dialog box type diskmgmt.msc and enter

Step 3 : Select uninitialized partition, right click->initialize

Step 4 : Select the partition again, right click and create extended partition, again right click create logical drive (adjust the partition size if you need in wizard)

Thats all

Aggregate function in SQL WHERE-Clause

Another solution is to Move the aggregate fuction to Scalar User Defined Function

Create Your Function:

CREATE FUNCTION getTotalSalesByProduct(@ProductName VARCHAR(500))
RETURNS INT
AS
BEGIN

DECLARE @TotalAmount INT

SET @TotalAmount = (select SUM(SaleAmount) FROM Sales where Product=@ProductName)

RETURN @TotalAmount

END

Use Function in Where Clause

SELECT ProductName, SUM(SaleAmount) AS TotalSales
FROM Sales
WHERE dbo.getTotalSalesByProduct(ProductName)  > 1000
GROUP BY Product

References:

1. 2.

Hope helps someone.

pop/remove items out of a python tuple

Maybe you want dictionaries?

d = dict( (i,value) for i,value in enumerate(tple))
while d:
    bla bla bla
    del b[x]

how to change color of TextinputLayout's label and edittext underline android

Add this attribute in Edittext tag and enjoy:

 android:backgroundTint="@color/colorWhite"

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:

When I log in the user I save the access token:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$accessToken = $facebook->getAccessToken();
//save the access token for later

Now when I make requests to facebook I just do something like this:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)

Convert time span value to format "hh:mm Am/Pm" using C#

You can add the TimeSpan to a DateTime, for example:

TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");

Demo: http://ideone.com/veJ6tT

04:00 PM

Standard Date and Time Format Strings

Recursively list files in Java

FileUtils have iterateFiles and listFiles methods. Give them a try. (from commons-io)

Edit: You can check here for a benchmark of different approaches. It seems that the commons-io approach is slow, so pick some of the faster ones from here (if it matters)

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

TL;DR

You are missing the @Id entity property, and that's why Hibernate is throwing that exception.

Entity identifiers

Any JPA entity must have an identifier property, that is marked with the Id annotation.

There are two types of identifiers:

  • assigned
  • auto-generated

Assigned identifiers

An assigned identifier looks as follows:

@Id
private Long id;

Notice that we are using a wrapper (e.g., Long, Integer) instead of a primitive type (e.g., long, int). Using a wrapper type is a better choice when using Hibernate because, by checking if the id is null or not, Hibernate can better determine if an entity is transient (it does not have an associated table row) or detached (it has an associated table row, but it's not managed by the current Persistence Context).

The assigned identifier must be set manually by the application prior to calling persist:

Post post = new Post();
post.setId(1L);

entityManager.persist(post);

Auto-generated identifiers

An auto-generated identifier requires the @GeneratedValue annotation besides the @Id:

@Id
@GeneratedValue
private int id;

There are 3 strategies Hibernate can use to auto-generate the entity identifier:

  • IDENTITY
  • SEQUENCE
  • TABLE

The IDENTITY strategy is to be avoided if the underlying database supports sequences (e.g., Oracle, PostgreSQL, MariaDB since 10.3, SQL Server since 2012). The only major database that does not support sequences is MySQL.

The problem with IDENTITY is that automatic Hibernate batch inserts are disabled for this strategy.

The SEQUENCE strategy is the best choice unless you are using MySQL. For the SEQUENCE strategy, you also want to use the pooled optimizer to reduce the number of database roundtrips when persisting multiple entities in the same Persistence Context.

The TABLE generator is a terrible choice because it does not scale. For portability, you are better off using SEQUENCE by default and switch to IDENTITY for MySQL only.

What is the .idea folder?

There is no problem in deleting this. It's not only the WebStorm IDE creating this file, but also PhpStorm and all other of JetBrains' IDEs.

It is safe to delete it but if your project is from GitLab or GitHub then you will see a warning.

Make function wait until element exists

If you want a generic solution using MutationObserver you can use this function

// MIT Licensed
// Author: jwilson8767

/**
 * Waits for an element satisfying selector to exist, then resolves promise with the element.
 * Useful for resolving race conditions.
 *
 * @param selector
 * @returns {Promise}
 */
export function elementReady(selector) {
  return new Promise((resolve, reject) => {
    const el = document.querySelector(selector);
    if (el) {resolve(el);}
    new MutationObserver((mutationRecords, observer) => {
      // Query for elements matching the specified selector
      Array.from(document.querySelectorAll(selector)).forEach((element) => {
        resolve(element);
        //Once we have resolved we don't need the observer anymore.
        observer.disconnect();
      });
    })
      .observe(document.documentElement, {
        childList: true,
        subtree: true
      });
  });
}

Source: https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
Example how to use it

elementReady('#someWidget').then((someWidget)=>{someWidget.remove();});

Note: MutationObserver has a great browser support; https://caniuse.com/#feat=mutationobserver

Et voilà ! :)

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Encoding as Base64 in Java

You need to change the import of your class:

import org.apache.commons.codec.binary.Base64;

And then change your class to use the Base64 class.

Here's some example code:

byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));

Then read why you shouldn't use sun.* packages.


Update (2016-12-16)

You can now use java.util.Base64 with Java 8. First, import it as you normally do:

import java.util.Base64;

Then use the Base64 static methods as follows:

byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));

If you directly want to encode string and get the result as encoded string, you can use this:

String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());

See Java documentation for Base64 for more.

Purpose of "%matplotlib inline"

If you don't know what backend is , you can read this: https://matplotlib.org/tutorials/introductory/usage.html#backends

Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people run Jupyter notebooks and draw inline plots for quick data analysis. Others embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications. Some people use matplotlib in batch scripts to generate postscript images from numerical simulations, and still others run web application servers to dynamically serve up graphs. To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the "frontend" is the user facing code, i.e., the plotting code, whereas the "backend" does all the hard work behind-the-scenes to make the figure.

So when you type %matplotlib inline , it activates the inline backend. As discussed in the previous posts :

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

Is true == 1 and false == 0 in JavaScript?

From the ECMAScript specification, Section 11.9.3 The Abstract Equality Comparison Algorithm:

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  • If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

Thus, in, if (1 == true), true gets coerced to a Number, i.e. Number(true), which results in the value of 1, yielding the final if (1 == 1) which is true.

if (0 == false) is the exact same logic, since Number(false) == 0.

This doesn't happen when you use the strict equals operator === instead:

11.9.6 The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  • If Type(x) is different from Type(y), return false.

How to check empty DataTable

This is an old question, but because this might help a lot of c# coders out there, there is an easy way to solve this right now as follows:

if ((dataTableName?.Rows?.Count ?? 0) > 0)

Static array vs. dynamic array in C++

Static array :Efficiency. No dynamic allocation or deallocation is required.

Arrays declared in C, C++ in function including static modifier are static. Example: static int foo[5];

ExecutorService, how to wait for all tasks to finish

how about this?

Object lock = new Object();
CountDownLatch cdl = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
    executorService.execute(() -> {

        synchronized (lock) {
            cdl.countDown();
            try {
                lock.wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    });
}
cdl.await();
synchronized (lock) {
    lock.notifyAll();
}

if you do not add new tasks to ExecutorService , this may wait for all current tasks completed

DateTime and CultureInfo

You may try the following:

System.Globalization.CultureInfo cultureinfo =
        new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I had similar problem with IntelliJ when tried to run some Groovy scripts. Here is how I solved it.

Go to "Project Structure"-> "Project" -> "Project language level" and select "SDK default". This should use the same SDK for all project modules.

What's a concise way to check that environment variables are set in a Unix shell script?

Your question is dependent on the shell that you are using.

Bourne shell leaves very little in the way of what you're after.

BUT...

It does work, just about everywhere.

Just try and stay away from csh. It was good for the bells and whistles it added, compared the Bourne shell, but it is really creaking now. If you don't believe me, just try and separate out STDERR in csh! (-:

There are two possibilities here. The example above, namely using:

${MyVariable:=SomeDefault}

for the first time you need to refer to $MyVariable. This takes the env. var MyVariable and, if it is currently not set, assigns the value of SomeDefault to the variable for later use.

You also have the possibility of:

${MyVariable:-SomeDefault}

which just substitutes SomeDefault for the variable where you are using this construct. It doesn't assign the value SomeDefault to the variable, and the value of MyVariable will still be null after this statement is encountered.

MySQL timestamp select date range

Whenever possible, avoid applying functions to a column in the where clause:

SELECT *
  FROM table_name
 WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00') 
   AND timestamp <  UNIX_TIMESTAMP('2010-11-01 00:00:00');

Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.

Changing Java Date one hour back

It worked for me instead using format .To work with time just use parse and toString() methods

String localTime="6:11"; LocalTime localTime = LocalTime.parse(localtime)

LocalTime lt = 6:11; localTime = lt.toString()

Save range to variable

To save a range and then call it later, you were just missing the "Set"

Set Remember_Range = Selection    or    Range("A3")
Remember_Range.Activate

But for copying and pasting, this quicker. Cuts out the middle man and its one line

Sheets("Copy").Range("A3").Value = Sheets("Paste").Range("A3").Value

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

How to picture "for" loop in block representation of algorithm

What's a "block scheme"?

If I were drawing it, I might draw a box with "for each x in y" written in it.

If you're drawing a flowchart, there's always a loop with a decision box.

Nassi-Schneiderman diagrams have a loop construct you could use.

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

Nth max salary in Oracle

This will also work :

with data as 
(
select sal,rwid from (
select salary as sal,rowid as rwid from salary order by salary desc
)
where rownum < 5
)
select * from salary a 
where rowid = (select min(rwid) from data)

Getting next element while cycling through a list

After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break, which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that li be a list or tuple. It could be any iterator.

from itertools import cycle

li = [0, 1, 2, 3]

running = True
licycle = cycle(li)
# Prime the pump
nextelem = next(licycle)
while running:
    thiselem, nextelem = nextelem, next(licycle)

I'm leaving the other solutions here for posterity.

All of that fancy iterator stuff has its place, but not here. Use the % operator.

li = [0, 1, 2, 3]

running = True
while running:
    for idx, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(idx + 1) % len(li)]

Now, if you intend to infinitely cycle through a list, then just do this:

li = [0, 1, 2, 3]

running = True
idx = 0
while running:
    thiselem = li[idx]
    idx = (idx + 1) % len(li)
    nextelem = li[idx]

I think that's easier to understand than the other solution involving tee, and probably faster too. If you're sure the list won't change size, you can squirrel away a copy of len(li) and use that.

This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running in the middle of the for loop and then break.

Locate the nginx.conf file my nginx is actually using

Both nginx -t and nginx -V would print out the default nginx config file path.

$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

$ nginx -V
nginx version: nginx/1.11.1
built by gcc 4.9.2 (Debian 4.9.2-10)
built with OpenSSL 1.0.1k 8 Jan 2015
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf ...

If you want, you can get the config file by:

$ nginx -V 2>&1 | grep -o '\-\-conf-path=\(.*conf\)' | cut -d '=' -f2
/etc/nginx/nginx.conf

Even if you have loaded some other config file, they would still print out the default value.


ps aux would show you the current loaded nginx config file.

$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root        11  0.0  0.2  31720  2212 ?        Ss   Jul23   0:00 nginx: master process nginx -c /app/nginx.conf

So that you could actually get the config file by for example:

$ ps aux | grep "[c]onf" | awk '{print $(NF)}'
/app/nginx.conf

What are the differences between json and simplejson Python modules?

I came across this question as I was looking to install simplejson for Python 2.6. I needed to use the 'object_pairs_hook' of json.load() in order to load a json file as an OrderedDict. Being familiar with more recent versions of Python I didn't realize that the json module for Python 2.6 doesn't include the 'object_pairs_hook' so I had to install simplejson for this purpose. From personal experience this is why i use simplejson as opposed to the standard json module.

Add missing dates to pandas dataframe

A quicker workaround is to use .asfreq(). This doesn't require creation of a new index to call within .reindex().

# "broken" (staggered) dates
dates = pd.Index([pd.Timestamp('2012-05-01'), 
                  pd.Timestamp('2012-05-04'), 
                  pd.Timestamp('2012-05-06')])
s = pd.Series([1, 2, 3], dates)

print(s.asfreq('D'))
2012-05-01    1.0
2012-05-02    NaN
2012-05-03    NaN
2012-05-04    2.0
2012-05-05    NaN
2012-05-06    3.0
Freq: D, dtype: float64

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

How to calculate the sum of the datatable column in asp.net?

You Can use Linq by Name Grouping

  var allEntries = from r in dt.AsEnumerable()
                            select r["Amount"];

using name space using System.Linq;

You can find the sample total,subtotal,grand total in datatable using c# at Myblog

What is the equivalent to getch() & getche() in Linux?

You can use the curses.h library in linux as mentioned in the other answer.

You can install it in Ubuntu by:

sudo apt-get update

sudo apt-get install ncurses-dev

I took the installation part from here.

link_to method and click event in Rails

You can use link_to_function (removed in Rails 4.1):

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/javascript/is/broken',
        :id => 'my-link'

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function (event) {
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

Or if you're using jQuery:

$('#my-link').click(function (event) {
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

How to automatically add user account AND password with a Bash script?

You can use expect in your bash script.

From http://www.seanodonnell.com/code/?id=21

#!/usr/bin/expect 
######################################### 
#$ file: htpasswd.sh 
#$ desc: Automated htpasswd shell script 
######################################### 
#$ 
#$ usage example: 
#$ 
#$ ./htpasswd.sh passwdpath username userpass 
#$ 
###################################### 

set htpasswdpath [lindex $argv 0] 
set username [lindex $argv 1] 
set userpass [lindex $argv 2] 

# spawn the htpasswd command process 
spawn htpasswd $htpasswdpath $username 

# Automate the 'New password' Procedure 
expect "New password:" 
send "$userpass\r" 

expect "Re-type new password:" 
send "$userpass\r"

Iterate through Nested JavaScript Objects

Here is a solution using object-scan

_x000D_
_x000D_
// const objectScan = require('object-scan');

const cars = { label: 'Autos', subs: [ { label: 'SUVs', subs: [] }, { label: 'Trucks', subs: [ { label: '2 Wheel Drive', subs: [] }, { label: '4 Wheel Drive', subs: [ { label: 'Ford', subs: [] }, { label: 'Chevrolet', subs: [] } ] } ] }, { label: 'Sedan', subs: [] } ] };

const find = (haystack, label) => objectScan(['**.label'], {
  filterFn: ({ value }) => value === label,
  rtn: 'parent',
  abort: true
})(haystack);

console.log(find(cars, 'Sedan'));
// => { label: 'Sedan', subs: [] }
console.log(find(cars, 'SUVs'));
// => { label: 'SUVs', subs: [] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

Oracle 12c Installation failed to access the temporary location

The error is caused due to administrative shares are being disabled. If they cannot be enabled then perform the following workaround:

6.2.23 INS-30131 Error When Installing Oracle Database or Oracle Client

If the administrative shares are not enabled when performing a single instance Oracle Database or Oracle Client installation for 12c Release 1 (12.1) on Microsoft Windows 7, Microsoft Windows 8, and Microsoft Windows 10, then the installation fails with an INS-30131 error.

Workaround:

Execute the net share command to ensure that the administrative shares are enabled. If they are disabled, then enable them by following the instructions in the Microsoft Windows documentation. Alternatively, perform the client or server installation by specifying the following options:

  • For a client installation:

    -ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"

  • For a server installation:

    -ignorePrereq -J"-Doracle.install.db.validate.supportedOSCheck=false"

This issue is tracked with Oracle bug 21452473.

Source: Oracle Database Release Notes (Section 6.2.23)

Genymotion Android emulator - adb access?

Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.

More info: https://stackoverflow.com/a/26630862/4154438

CakePHP find method with JOIN

        $services = $this->Service->find('all', array(
            'limit' =>4,
            'fields' => array('Service.*','ServiceImage.*'),
            'joins' => array(
                array(
                        'table' => 'services_images',
                        'alias' => 'ServiceImage',
                        'type' => 'INNER',
                        'conditions' => array(
                        'ServiceImage.service_id' =>'Service.id'
                        )
                    ),
                ),
            )
        );

It goges to array is null.

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I think you can change the "Automatically detect settings" via the registry key name "AutoConfigURL". here is the code that I check in c#. Wish you luck.

    RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                    if(registry.GetValue("AutoConfigURL") != null)
                    {
                        //Proxy Server disabled (Untick Proxy Server)
                        registry.DeleteValue("AutoConfigURL");
                    }

Python: "Indentation Error: unindent does not match any outer indentation level"

I have this issue. This is because wrong space in my code. probably the next line.delete all space and tabs and use space.

What is best way to start and stop hadoop ecosystem, with command line?

start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.

start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh

hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.

Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,

bin/hadoop-daemon.sh start datanode

Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.

Hope this answers your query.

Clear form after submission with jQuery

try this in your post methods callback function

$(':input','#myform')
 .not(':button, :submit, :reset, :hidden')
 .val('')
 .removeAttr('checked')
 .removeAttr('selected');

for more info read this

WebService Client Generation Error with JDK8

Another alternative is to update wsimport.sh shell script by adding the following:

The wsimport.sh is located in this directory:

jaxws-ri.2.2.28/bin

exec "$JAVA" $WSIMPORT_OPTS -Djavax.xml.accessExternalSchema=all -jar "$JAXWS_HOME/lib/jaxws-tools.jar" "$@"

Javascript date.getYear() returns 111 in 2011?

In order to comply with boneheaded precedent, getYear() returns the number of years since 1900.

Instead, you should call getFullYear(), which returns the actual year.

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

They way I did it was by selecting all of the data

select * from myTable and then right-clicking on the result set and chose "Save results as..." a csv file.

Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.

How do I concatenate two strings in C?

C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

Use strcat to concatenate two strings. You could use the following function to do it:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

Call the function like this:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

Stacking DIVs on top of each other?

To add to Dave's answer:

div { position: relative; }
div div { position: absolute; top: 0; left: 0; }

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

How to convert 'binary string' to normal string in Python3?

If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8')
'a string'

SoapUI "failed to load url" error when loading WSDL

In my case the

 Error loading [https://.../token?wsdl]: java.lang.Exception: Failed to load url; https://.../token?wsdl, 0 

was caused by fake certificate. If you get the following in browser

"There is a problem with this website’s security certificate." 

this is the case.

The resolution was to import a certificate to

 C:\Program Files (x86)\SmartBear\SoapUI-5.0.0\jre\lib\security\cacerts 

Which is default java used by SOAPUI

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Which characters need to be escaped in HTML?

It depends upon the context. Some possible contexts in HTML:

  • document body
  • inside common attributes
  • inside script tags
  • inside style tags
  • several more!

See OWASP's Cross Site Scripting Prevention Cheat Sheet, especially the "Why Can't I Just HTML Entity Encode Untrusted Data?" and "XSS Prevention Rules" sections. However, it's best to read the whole document.

Unicode character in PHP string

Because JSON directly supports the \uxxxx syntax the first thing that comes into my mind is:

$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');

Another option would be to use mb_convert_encoding()

echo mb_convert_encoding('&#x1000;', 'UTF-8', 'HTML-ENTITIES');

or make use of the direct mapping between UTF-16BE (big endian) and the Unicode codepoint:

echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');

How to actually search all files in Visual Studio

I think you are talking about ctrl + shift + F, by default it should be on "look in: entire solution" and there you go.

How to select all checkboxes with jQuery?

Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle:

(function($) {
    // Checkbox toggle function for selecting all checkboxes on the page
    $.fn.toggleCheckboxes = function() {
        // Get all checkbox elements
        checkboxes = $(':checkbox').not(this);

        // Check if the checkboxes are checked/unchecked and if so uncheck/check them
        if(this.is(':checked')) {
            checkboxes.prop('checked', true);
        } else {
            checkboxes.prop('checked', false);
        }
    }
}(jQuery));

Then simply call the function on your checkbox or button element:

// Check all checkboxes
$('.check-all').change(function() {
    $(this).toggleCheckboxes();
});

Git credential helper - update password

None of these answers ended up working for my Git credential issue. Here is what did work if anyone needs it (I'm using Git 1.9 on Windows 8.1).

To update your credentials, go to Control PanelCredential ManagerGeneric Credentials. Find the credentials related to your Git account and edit them to use the updated password.

Reference: How to update your Git credentials on Windows

Note that to use the Windows Credential Manager for Git you need to configure the credential helper like so:

git config --global credential.helper wincred

If you have multiple GitHub accounts that you use for different repositories, then you should configure credentials to use the full repository path (rather than just the domain, which is the default):

git config --global credential.useHttpPath true

Twitter Bootstrap Button Text Word Wrap

FWIW, in Boostrap 4.4, you can add .text-wrap style to things like buttons:

   <a href="#" class="btn btn-primary text-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>

https://getbootstrap.com/docs/4.4/utilities/text/#text-wrapping-and-overflow

HashMap to return default value for non-found keys?

I found the LazyMap quite helpful.

When the get(Object) method is called with a key that does not exist in the map, the factory is used to create the object. The created object will be added to the map using the requested key.

This allows you to do something like this:

    Map<String, AtomicInteger> map = LazyMap.lazyMap(new HashMap<>(), ()->new AtomicInteger(0));
    map.get(notExistingKey).incrementAndGet();

The call to get creates a default value for the given key. You specify how to create the default value with the factory argument to LazyMap.lazyMap(map, factory). In the example above, the map is initialized to a new AtomicInteger with value 0.

Byte Array and Int conversion in Java

I took a long look at many questions like this, and found this post... I didn't like the fact that the conversion code is duplicated for each type, so I've made a generic method to perform the task:

public static byte[] toByteArray(long value, int n)
{
    byte[] ret = new byte[n];
    ret[n-1] = (byte) ((value >> (0*8) & 0xFF);   
    ret[n-2] = (byte) ((value >> (1*8) & 0xFF);   
    ...
    ret[1] = (byte) ((value >> ((n-2)*8) & 0xFF);   
    ret[0] = (byte) ((value >> ((n-1)*8) & 0xFF);   
    return ret;
}

See full post.

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

Dictionary<int,string> comboSource = new Dictionary<int,string>();
comboSource.Add(1, "Sunday");
comboSource.Add(2, "Monday");

Aftr adding values to Dictionary, use this as combobox datasource:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

Error: the entity type requires a primary key

Make sure you have the following condition:

  1. Use [key] if your primary key name is not Id or ID.
  2. Use the public keyword.
  3. Primary key should have getter and setter.

Example:

public class MyEntity {
   [key]
   public Guid Id {get; set;}
}

Python "extend" for a dictionary

a.update(b)

Will add keys and values from b to a, overwriting if there's already a value for a key.

How do I write a RGB color value in JavaScript?

Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:

function rgb(r, g, b){
  return "rgb("+r+","+g+","+b+")";
}

Alternatively (to create fewer string objects), you could use array join():

function rgb(r, g, b){
  return ["rgb(",r,",",g,",",b,")"].join("");
}

The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:

function rgb(r, g, b){
  r = Math.floor(r);
  g = Math.floor(g);
  b = Math.floor(b);
  return ["rgb(",r,",",g,",",b,")"].join("");
}

You could also use ES6 language features:

const rgb = (r, g, b) => 
  `rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;

Android: Cancel Async Task

From SDK:

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.

After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

So your code is right for dialog listener:

uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
    public void onCancel(DialogInterface dialog) {
        myTask.cancel(true);
        //finish();
    }
});

Now, as I have mentioned earlier from SDK, you have to check whether the task is cancelled or not, for that you have to check isCancelled() inside the onPreExecute() method.

For example:

if (isCancelled()) 
    break;
else
{
   // do your work here
}

How to check if a variable is a dictionary in Python?

The OP did not exclude the starting variable, so for completeness here is how to handle the generic case of processing a supposed dictionary that may include items as dictionaries.

Also following the pure Python(3.8) recommended way to test for dictionary in the above comments.

from collections.abc import Mapping

dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def parse_dict(in_dict): 
    if isinstance(in_dict, Mapping):
        for k_outer, v_outer in in_dict.items():
            if isinstance(v_outer, Mapping):
                for k_inner, v_inner in v_outer.items():
                    print(k_inner, v_inner)
            else:
                print(k_outer, v_outer)

parse_dict(dict)

GitLab remote: HTTP Basic: Access denied and fatal Authentication

So for me the problem was that I had created my GitLab account via linking my GitHub account to it. This meant that no password formally existed for the account as it was created via hotlink between GitHub and GitLab. I fixed it by going to GitLab Settings -> Password -> and writing the same password as my GitHub account had.

How do you format code on save in VS Code

For MAC user, add this line into your Default Settings

File path is: /Users/USER_NAME/Library/Application Support/Code/User/settings.json

"tslint.autoFixOnSave": true

Sample of the file would be:

{
    "window.zoomLevel": 0,
    "workbench.iconTheme": "vscode-icons",
    "typescript.check.tscVersion": false,
    "vsicons.projectDetection.disableDetect": true,
    "typescript.updateImportsOnFileMove.enabled": "always",
    "eslint.autoFixOnSave": true,
    "tslint.autoFixOnSave": true
}

Why there is no ConcurrentHashSet against ConcurrentHashMap

It looks like Java provides a concurrent Set implementation with its ConcurrentSkipListSet. A SkipList Set is just a special kind of set implementation. It still implements the Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet interfaces. This might work for you if you only need the Set interface.

How to get my project path?

This gives you the root folder:

System.AppDomain.CurrentDomain.BaseDirectory

You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found

For .NET framework (thanks to Adiono comment)

Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"..\\..\\"))

For .NET core here is a way to do it (thanks to nopara73 comment)

Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;

Using PUT method in HTML form

Unfortunately, modern browsers do not provide native support for HTTP PUT requests. To work around this limitation, ensure your HTML form’s method attribute is “post”, then add a method override parameter to your HTML form like this:

<input type="hidden" name="_METHOD" value="PUT"/>

To test your requests you can use "Postman" a google chrome extension

How to pass the id of an element that triggers an `onclick` event to the event handling function

I would suggest the use of jquery mate.

With jQuery you would then be able to get the id of this element by

$(this).attr('id');

without jquery, if I remember correctly we used to access the id with a

this.id

Hope that helps :)

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

To Add to AlexG's answer, a better and enhanced version of multi-select is found in this following link (which I tried and worked as expected):

https://gist.github.com/coinsandsteeldev/4c67dfa5411e8add913273fc5a30f5e7

For general guidance on setting up a script in Google Sheets, see this quickstart guide.

To use this script:

  1. In your Google Sheet, set up data validation for a cell (or cells), using data from a range. In cell validation, do not select 'Reject input'.
  2. Go to Tools > Script editor...
  3. In the script editor, go to File > New > Script file
  4. Name the file multi-select.gs and paste in the contents of multi-select.gs. File > Save.
  5. In the script editor, go to File > New > Html file Name the file dialog.html and paste in the contents of dialog.html. File > Save.
  6. Back in your spreadsheet, you should now have a new menu called 'Scripts'. Refresh the page if necessary.
  7. Select the cell you want to fill with multiple items from your validation range.
  8. Go to Scripts > Multi-select for this cell... and the sidebar should open, showing a checklist of valid items.
  9. Tick the items you want and click the 'Set' button to fill your cell with those selected items, comma separated.

You can leave the script sidebar open. When you select any cell that has validation, click 'Refresh validation' in the script sidebar to bring up that cell's checklist.

The above mentioned steps are taken from this link

How to check if a Docker image with a specific tag exist locally?

for specific tag name

$ docker images  --filter reference='<REPOSITORY>:TAG'

for "like clause" tagname:my_image_tag --> start my_ima*

$ docker images  --filter reference='<REPOSITORY>:my_ima*'

if you want to someting "the image" for example delete all images tag started "my_ima" try this

docker rmi -f $(docker images -q  --filter reference='myreponame:my_ima*')

SQL - Create view from multiple tables

Thanks for the help. This is what I ended up doing in order to make it work.

CREATE VIEW V AS
    SELECT *
    FROM ((POP NATURAL FULL OUTER JOIN FOOD)
    NATURAL FULL OUTER JOIN INCOME);

oracle - what statements need to be committed?

In mechanical terms a COMMIT makes a transaction. That is, a transaction is all the activity (one or more DML statements) which occurs between two COMMIT statements (or ROLLBACK).

In Oracle a DDL statement is a transaction in its own right simply because an implicit COMMIT is issued before the statement is executed and again afterwards. TRUNCATE is a DDL command so it doesn't need an explicit commit because calling it executes an implicit commit.

From a system design perspective a transaction is a business unit of work. It might consist of a single DML statement or several of them. It doesn't matter: only full transactions require COMMIT. It literally does not make sense to issue a COMMIT unless or until we have completed a whole business unit of work.

This is a key concept. COMMITs don't just release locks. In Oracle they also release latches, such as the Interested Transaction List. This has an impact because of Oracle's read consistency model. Exceptions such as ORA-01555: SNAPSHOT TOO OLD or ORA-01002: FETCH OUT OF SEQUENCE occur because of inappropriate commits. Consequently, it is crucial for our transactions to hang onto locks for as long as they need them.

Getting multiple selected checkbox values in a string in javascript and PHP

var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++) 
{
    if (checkboxes[i].checked) 
    {
        vals += ","+checkboxes[i].value;
    }
}
if (vals) vals = vals.substring(1);