Programs & Examples On #Rsa key fingerprint

ssh: The authenticity of host 'hostname' can't be established

Depending on your ssh client, you can set the StrictHostKeyChecking option to no on the command line, and/or send the key to a null known_hosts file. You can also set these options in your config file, either for all hosts or for a given set of IP addresses or host names.

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

EDIT

As @IanDunn notes, there are security risks to doing this. If the resource you're connecting to has been spoofed by an attacker, they could potentially replay the destination server's challenge back to you, fooling you into thinking that you're connecting to the remote resource while in fact they are connecting to that resource with your credentials. You should carefully consider whether that's an appropriate risk to take on before altering your connection mechanism to skip HostKeyChecking.

Reference.

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

Android Studio AVD - Emulator: Process finished with exit code 1

None of the solutions worked for me. I ended up downloading a different emulator image.

First I had arm64-v8a, which was giving this error. I download armeabi-v7a, which worked fine.

Unfortunately I was not able to install HAXM accelerator as organization's softwares were blocking the installation. Hence, had to go with arm.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Just to phrase things differently from the great answers above, as that has helped me get an intuitive understanding of negative margins:

A negative margin on an element allows it to eat up the space of its parent container.

Adding a (positive) margin on the bottom doesn't allow the element to do that - it only pushes back whatever element is below.

What exactly does stringstream do?

You entered an alphanumeric and int, blank delimited in mystr.

You then tried to convert the first token (blank delimited) into an int.

The first token was RS which failed to convert to int, leaving a zero for myprice, and we all know what zero times anything yields.

When you only entered int values the second time, everything worked as you expected.

It was the spurious RS that caused your code to fail.

fill an array in C#

You could try something like this:

I have initialzed the array for having value 5, you could put your number similarly.

int[] arr = new int[10]; // your initial array

arr = arr.Select(i => 5).ToArray(); // array initialized to 5.

How to send email to multiple recipients using python smtplib?

You need to understand the difference between the visible address of an email, and the delivery.

msg["To"] is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.

The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.

There are various reasons for this. For example forwarding. The To: header field doesn't change on forwarding, however the email is dropped into a different mailbox.

The smtp.sendmail command now takes care of the actual delivery. email.Message is the contents of the letter only, not the delivery.

In low-level SMTP, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.

For the header, it can also contain for example the name, e.g. To: First Last <[email protected]>, Other User <[email protected]>. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on , you still not not have the valid adresses!

Early exit from function?

This:

function myfunction()
{
     if (a == 'stop')  // How can I stop working of function here?
     {
         return;
     }
}

Python conversion from binary string to hexadecimal

format(int(bits, 2), '0' + str(len(bits) / 4) + 'x')

How do you make Git work with IntelliJ?

You need to specify the executable path of Git in the Git Settings, as mentionned in the per-requesites:

The Git integration plugin is enabled and the location of the Git executable file is correctly specified on the Git page of the Settings dialog box.

As long as you see "a message indicating that the Git execution path is not correct", the rest of the instructions won't work.

Path to Git executable

In this text box, specify the path to the Git executable file.
Type the path manually or click the Browse button to open the Select Path - Git Configuration dialog box and select the location of the Git executable file in the directories tree.

See "Where is git.exe located?" for the path of Git on Windows.

OR

    c:\path\to\PortableGit-2.6.2-64-bit\usr\bin

OR

    c:\path\to\PortableGit-2.x.\mingw64\bin
  • With GitHub Desktop:

      %USERPROFILE%\AppData\Local\GitHub\PORTAB~1\bin\git.exe
    

Update 2020, three years later:

As noted by Daniel Connelly in the comments

IntelliJ now lets people install it through the path specified in the help above (just look for the "Download Now" button on the Git menu).
If you download Git from the website, a version that IntelliJ does not support will be installed.

How to change folder with git bash?

The command is:

cd  /c/project/

Tip:
Use the pwd command to see which path you are currently in, handy when you did a right-click "Git Bash here..."

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I realize this is an old post, but it ranks high in Google, so I'm adding what I figured out for MY problem. If you have a mix of table types (e.g. MyISAM and InnoDB), you will get this error as well. In this case, InnoDB is the default table type, but one table needed fulltext searching so it was migrated to MyISAM. In this situation, you cannot create a foreign key in the InnoDB table that references the MyISAM table.

Listing only directories using ls in Bash?

A plain list of the current directory, it'd be:

ls -1d */

If you want it sorted and clean:

ls -1d */ | cut -c 1- | rev | cut -c 2- | rev | sort

Remember: capitalized characters have different behavior in the sort

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

C++ queue - simple example

std::queue<myclass*> that's it

Load CSV file with Spark

When using spark.read.csv, I find that using the options escape='"' and multiLine=True provide the most consistent solution to the CSV standard, and in my experience works the best with CSV files exported from Google Sheets.

That is,

#set inferSchema=False to read everything as string
df = spark.read.csv("myData.csv", escape='"', multiLine=True,
     inferSchema=False, header=True)

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

Find the process and terminate it. On Windows do a Control+Alt+Delete and then find the "Java(TM) Platform SE Binary" process under the Processes Tab. For example: enter image description here

On Ubuntu, you can use "ps aux | grep java" to find the process and "kill -9 PID_NUMBER" to kill the process.

OR

If you're using a Spring boot application, go to application.properties and add this:

server.port = 8081

Input text dialog Android

If you want some space at left and right of input view, you can add some padding like

private fun showAlertWithTextInputLayout(context: Context) {
    val textInputLayout = TextInputLayout(context)
    textInputLayout.setPadding(
        resources.getDimensionPixelOffset(R.dimen.dp_19), // if you look at android alert_dialog.xml, you will see the message textview have margin 14dp and padding 5dp. This is the reason why I use 19 here
        0,
        resources.getDimensionPixelOffset(R.dimen.dp_19),
        0
    )
    val input = EditText(context)
    textInputLayout.hint = "Email"
    textInputLayout.addView(input)

    val alert = AlertDialog.Builder(context)
        .setTitle("Reset Password")
        .setView(textInputLayout)
        .setMessage("Please enter your email address")
        .setPositiveButton("Submit") { dialog, _ ->
            // do some thing with input.text
            dialog.cancel()
        }
        .setNegativeButton("Cancel") { dialog, _ ->
            dialog.cancel()
        }.create()

    alert.show()
}

dimens.xml

<dimen name="dp_19">19dp</dimen>

Hope it help

How can I print a quotation mark in C?

you should use escape character like this:

printf("\"");

How to convert list to string

>>> L = [1,2,3]       
>>> " ".join(str(x) for x in L)
'1 2 3'

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

When do I use the PHP constant "PHP_EOL"?

I have a site where a logging-script writes a new line of text to a textfile after an action from the user, who can be using any OS.

Using PHP_EOL don't seem to be optimal in this case. If the user is on Mac OS and writes to the textfile it will put \n. When opening the textfile on a windows computer it doesn't show a line break. For this reason i use "\r\n" instead which works when opening the file on any OS.

What are the basic rules and idioms for operator overloading?

Overloading new and delete

Note: This only deals with the syntax of overloading new and delete, not with the implementation of such overloaded operators. I think that the semantics of overloading new and delete deserve their own FAQ, within the topic of operator overloading I can never do it justice.

Basics

In C++, when you write a new expression like new T(arg) two things happen when this expression is evaluated: First operator new is invoked to obtain raw memory, and then the appropriate constructor of T is invoked to turn this raw memory into a valid object. Likewise, when you delete an object, first its destructor is called, and then the memory is returned to operator delete.
C++ allows you to tune both of these operations: memory management and the construction/destruction of the object at the allocated memory. The latter is done by writing constructors and destructors for a class. Fine-tuning memory management is done by writing your own operator new and operator delete.

The first of the basic rules of operator overloading – don’t do it – applies especially to overloading new and delete. Almost the only reasons to overload these operators are performance problems and memory constraints, and in many cases, other actions, like changes to the algorithms used, will provide a much higher cost/gain ratio than attempting to tweak memory management.

The C++ standard library comes with a set of predefined new and delete operators. The most important ones are these:

void* operator new(std::size_t) throw(std::bad_alloc); 
void  operator delete(void*) throw(); 
void* operator new[](std::size_t) throw(std::bad_alloc); 
void  operator delete[](void*) throw(); 

The first two allocate/deallocate memory for an object, the latter two for an array of objects. If you provide your own versions of these, they will not overload, but replace the ones from the standard library.
If you overload operator new, you should always also overload the matching operator delete, even if you never intend to call it. The reason is that, if a constructor throws during the evaluation of a new expression, the run-time system will return the memory to the operator delete matching the operator new that was called to allocate the memory to create the object in. If you do not provide a matching operator delete, the default one is called, which is almost always wrong.
If you overload new and delete, you should consider overloading the array variants, too.

Placement new

C++ allows new and delete operators to take additional arguments.
So-called placement new allows you to create an object at a certain address which is passed to:

class X { /* ... */ };
char buffer[ sizeof(X) ];
void f()
{ 
  X* p = new(buffer) X(/*...*/);
  // ... 
  p->~X(); // call destructor 
} 

The standard library comes with the appropriate overloads of the new and delete operators for this:

void* operator new(std::size_t,void* p) throw(std::bad_alloc); 
void  operator delete(void* p,void*) throw(); 
void* operator new[](std::size_t,void* p) throw(std::bad_alloc); 
void  operator delete[](void* p,void*) throw(); 

Note that, in the example code for placement new given above, operator delete is never called, unless the constructor of X throws an exception.

You can also overload new and delete with other arguments. As with the additional argument for placement new, these arguments are also listed within parentheses after the keyword new. Merely for historical reasons, such variants are often also called placement new, even if their arguments are not for placing an object at a specific address.

Class-specific new and delete

Most commonly you will want to fine-tune memory management because measurement has shown that instances of a specific class, or of a group of related classes, are created and destroyed often and that the default memory management of the run-time system, tuned for general performance, deals inefficiently in this specific case. To improve this, you can overload new and delete for a specific class:

class my_class { 
  public: 
    // ... 
    void* operator new();
    void  operator delete(void*,std::size_t);
    void* operator new[](size_t);
    void  operator delete[](void*,std::size_t);
    // ... 
}; 

Overloaded thus, new and delete behave like static member functions. For objects of my_class, the std::size_t argument will always be sizeof(my_class). However, these operators are also called for dynamically allocated objects of derived classes, in which case it might be greater than that.

Global new and delete

To overload the global new and delete, simply replace the pre-defined operators of the standard library with our own. However, this rarely ever needs to be done.

Custom domain for GitHub project pages

Overview

The documentation is a little confusing when it comes to project pages, as opposed to user pages. It feels like you should have to do more, but actually the process is very easy.

It involves:

  1. Setting up 2 static A records for the naked (no www) domain.
  2. Creating one CNAME record for www which will point to a GitHub URL. This will handle www redirection for you.
  3. Creating a file called CNAME (capitalised) in your project root on the gh-pages branch. This will tell Github what URL to respond to.
  4. Wait for everything to propagate.

What you will get

Your content will be served from a URL of the form http://nicholasjohnson.com.

Visiting http://www.nicholasjohnson.com will return a 301 redirect to the naked domain.

The path will be respected by the redirect, so traffic to http://www.nicholasjohnson.com/angular will be redirected to http://nicholasjohnson.com/angular.

You can have one project page per repository, so if your repos are open you can have as many as you like.

Here's the process:

1. Create A records

For the A records, point @ to the following ip addresses:

@: 185.199.108.153
@: 185.199.109.153
@: 185.199.110.153
@: 185.199.111.153

These are the static Github IP addresses from which your content will be served.

2. Create a CNAME Record

For the CNAME record, point www to yourusername.github.io. Note the trailing full stop. Note also, this is the username, not the project name. You don't need to specify the project name yet. Github will use the CNAME file to determine which project to serve content from.

e.g.

www: forwardadvance.github.io.

The purpose of the CNAME is to redirect all www subdomain traffic to a GitHub page which will 301 redirect to the naked domain.

Here's a screenshot of the configuration I use for my own site http://nicholasjohnson.com:

A and CNAME records required for Github Static Pages

3. Create a CNAME file

Add a file called CNAME to your project root in the gh-pages branch. This should contain the domain you want to serve. Make sure you commit and push.

e.g.

nicholasjohnson.com

This file tells GitHub to use this repo to handle traffic to this domain.

4. Wait

Now wait 5 minutes, your project page should now be live.

How to do a subquery in LINQ?

Here's a subquery for you!

List<int> IdsToFind = new List<int>() {2, 3, 4};

db.Users
.Where(u => SqlMethods.Like(u.LastName, "%fra%"))
.Where(u =>
    db.CompanyRolesToUsers
    .Where(crtu => IdsToFind.Contains(crtu.CompanyRoleId))
    .Select(crtu =>  crtu.UserId)
    .Contains(u.Id)
)

Regarding this portion of the question:

predicateAnd = predicateAnd.And(c => c.LastName.Contains(
                                TextBoxLastName.Text.Trim()));

I strongly recommend extracting the string from the textbox before authoring the query.

string searchString = TextBoxLastName.Text.Trim();
predicateAnd = predicateAnd.And(c => c.LastName.Contains( searchString));

You want to maintain good control over what gets sent to the database. In the original code, one possible reading is that an untrimmed string gets sent into the database for trimming - which is not good work for the database to be doing.

Pandas index column title or name

Setting the index name can also be accomplished at creation:

pd.DataFrame(data={'age': [10,20,30], 'height': [100, 170, 175]}, index=pd.Series(['a', 'b', 'c'], name='Tag'))

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

Failed to load ApplicationContext for JUnit test of Spring controller

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class) at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than @WebMvcTest

Hash table runtime complexity (insert, search and delete)

Hash tables are O(1) average and amortized case complexity, however it suffers from O(n) worst case time complexity. [And I think this is where your confusion is]

Hash tables suffer from O(n) worst time complexity due to two reasons:

  1. If too many elements were hashed into the same key: looking inside this key may take O(n) time.
  2. Once a hash table has passed its load balance - it has to rehash [create a new bigger table, and re-insert each element to the table].

However, it is said to be O(1) average and amortized case because:

  1. It is very rare that many items will be hashed to the same key [if you chose a good hash function and you don't have too big load balance.
  2. The rehash operation, which is O(n), can at most happen after n/2 ops, which are all assumed O(1): Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)

Note because of the rehashing issue - a realtime applications and applications that need low latency - should not use a hash table as their data structure.

EDIT: Annother issue with hash tables: cache
Another issue where you might see a performance loss in large hash tables is due to cache performance. Hash Tables suffer from bad cache performance, and thus for large collection - the access time might take longer, since you need to reload the relevant part of the table from the memory back into the cache.

setup android on eclipse but don't know SDK directory

ADT Plugin (UNSUPPORTED)

The Eclipse ADT plugin is no longer supported, as per this announcement in June 2015.

The Eclipse ADT plugin has many known bugs and potential security bugs that will not be fixed.

You should immediately switch to use Android Studio, the official IDE for Android.

For help transitioning your projects, read Migrate to Android Studio.

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

For mac users: in new version there is no setting.xml, alternate way is to

navigate to SmartGit preferences folder using terminal

cd /Library/Preferences/SmartGit/

use ls command to see list of folders .. simply delete SmartGit version folder you find using command rm -r <main-smartgit-version> and reopen the SmartGit app. :)

How to check if string input is a number?

You can use the isdigit() method for strings. In this case, as you said the input is always a string:

    user_input = input("Enter something:")
    if user_input.isdigit():
        print("Is a number")
    else:
        print("Not a number")

TypeError: tuple indices must be integers, not str

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

How to NodeJS require inside TypeScript file?

The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require(). This was previously done using packages like typings, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:

npm install --save-dev @types/node

Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.

Using DataContractSerializer to serialize, but can't deserialize back

I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.


Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

In [1]: class HeavyDuty(object):
   ...:     def __init__(self):
   ...:         import time
   ...:         time.sleep(2)  # <- Spends a lot of time here
   ...:     
   ...:     def do_work(self, arg1, arg2):
   ...:         print("Called with %r and %r" % (arg1, arg2))
   ...:  

here is some code that uses two instances of the HeavyDuty class:

In [2]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(13, 17)
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(23, 29)
   ...:    


Now, here is a test case for the heavy_work function:

In [3]: from unittest.mock import patch, call
   ...: def test_heavy_work():
   ...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
   ...:     
   ...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
   ...:         heavy_work()
   ...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)
   ...:  

We are mocking the HeavyDuty class with MockHeavyDuty. To assert method calls coming from every HeavyDuty instance we have to refer to MockHeavyDuty.return_value.assert_has_calls, instead of MockHeavyDuty.assert_has_calls. In addition, in the list of expected_calls we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work, as opposed to simply call.

Exercising the test case shows us it is successful:

In [4]: print(test_heavy_work())
None


If we modify the heavy_work function, the test fails and produces a helpful error message:

In [5]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(113, 117)  # <- call args are different
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(123, 129)  # <- call args are different
   ...:     

In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)

AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]


Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

In [7]: def work_function(arg1, arg2):
   ...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
   ...: def test_work_function():
   ...:     expected_calls = [call(13, 17), call(23, 29)]    
   ...:     with patch('__main__.work_function') as mock_work_function:
   ...:         work_function(13, 17)
   ...:         work_function(23, 29)
   ...:         mock_work_function.assert_has_calls(expected_calls)
   ...:    

In [9]: print(test_work_function())
None


There are two main differences. The first one is that when mocking a function we setup our expected calls using call, instead of using call.some_method. The second one is that we call assert_has_calls on mock_work_function, instead of on mock_work_function.return_value.

Check if certain value is contained in a dataframe column in pandas

You can use any:

print any(df.column == 07311954)
True       #true if it contains the number, false otherwise

If you rather want to see how many times '07311954' occurs in a column you can use:

df.column[df.column == 07311954].count()

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

MySQL Database won't start in XAMPP Manager-osx

It might be the possibility that your voice recognition software has a installer of mysql internally and when u installed this software, it has installed mysql too and added it to the service and this mysql service starts once your system starts. So now u r having two mysql servers (one from voice recognition software and second is from XAMPP) that's why killing the previous process (mysql service) solved your problem. But this is not a permanent solution, you have to repeat it every time when ever you start your machine. So better is to find out that mysql server (service) and change its port no. OR change settings so that mysql service should not start when your machine start (but might be your voice recognition software won't work properly)

I hope it will help you.

Cheers

How do I send an HTML email?

If you are using Google app engine/Java, then use the following...

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SENDER_EMAIL_ADDRESS, "Admin"));
msg.addRecipient(Message.RecipientType.TO,
                 new InternetAddress(toAddress, "user");

msg.setSubject(subject,"UTF-8");

Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(message, "text/html");
mp.addBodyPart(htmlPart);
msg.setContent(mp);
Transport.send(msg);

Entity framework left join

For 2 and more left joins (left joining creatorUser and initiatorUser )

IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
                                             join candidateUser in authContext.AuthUsers
                                             on r.CandidateId equals candidateUser.Id
                                             join creatorUser in authContext.AuthUsers
                                             on r.CreatorId equals creatorUser.Id into gj
                                             from x in gj.DefaultIfEmpty()
                                             join initiatorUser in authContext.AuthUsers
                                             on r.InitiatorId equals initiatorUser.Id into init
                                             from x1 in init.DefaultIfEmpty()

                                             where candidateUser.UserName.Equals(candidateUsername)
                                             select new CreateRequestModel
                                             {
                                                 UserName = candidateUser.UserName,
                                                 CreatorId = (x == null ? String.Empty : x.UserName),
                                                 InitiatorId = (x1 == null ? String.Empty : x1.UserName),
                                                 CandidateId = candidateUser.UserName
                                             };

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

Do not use primitives in your Entity classes, use instead their respective wrappers. That will fix this problem.

Out of your Entity classes you can use the != null validation for the rest of your code flow.

How do I add a Font Awesome icon to input field?

to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution

in html:

   <span class="button1 search"></span>
<input name="username">

in css:

.button1 {
    background-color: #B9D5AD;
    border-radius: 0.2em 0 0 0.2em;
    box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5); 
    pointer-events: none;
    margin:1px 12px;    
    border-radius: 0.2em;    
    color: #333333;
    cursor: pointer;
    position: absolute;
    padding: 3px;
    text-decoration: none;   

}

Fastest way to get the first object from a queryset in django?

r = list(qs[:1])
if r:
  return r[0]
return None

How to revert the last migration?

I did this in 1.9.1 (to delete the last or latest migration created):

  1. rm <appname>/migrations/<migration #>*

    example: rm myapp/migrations/0011*

  2. logged into database and ran this SQL (postgres in this example)

    delete from django_migrations where name like '0011%';

I was then able to create new migrations that started with the migration number that I had just deleted (in this case, 11).

Type of expression is ambiguous without more context Swift

This can happen if any part of your highlighted method or property is attempting to access a property or method with the incorrect type.

Here is a troubleshooting checklist:

  • Make sure the type of arguments match in the call site and implementation.
  • Make sure the argument names match in the call site and implementation.
  • Make sure the method name matches in the call site and implementation.
  • Make sure the returned value of a property or method matches in the usage and implementation (ie: enumerated())
  • Make sure you don't have a duplicated method with potentially ambiguous types such as with protocols or generics.
  • Make sure the compiler can infer the correct type when using type inference.

A Strategy

  • Try breaking apart your method into a greater number of simpler method/implementations.

For example, lets say you are running compactMap on an array of custom Types. In the closure you are passing to the compactMap method, you initialize and return another custom struct. When you get this error, it is difficult to tell which part of your code is offending.

  • For debugging purposes, you can use a for loop instead of compactMap.
  • instead of passing the arguments, directly, you can assign them to constants in the for loop.

By this point, you may come to a realization, such as, instead of the property you thought you wanted to assign actually had a property on it that had the actual value you wanted to pass.

How to properly ignore exceptions

First I quote the answer of Jack o'Connor from this thread. The referenced thread got closed so I write here:

"There's a new way to do this coming in Python 3.4:

from contextlib import suppress

with suppress(Exception):
    # your code

Here's the commit that added it: http://hg.python.org/cpython/rev/406b47c64480

And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness: https://youtu.be/OSGv2VnC0go?t=43m23s

My addition to this is the Python 2.7 equivalent:

from contextlib import contextmanager

@contextmanager
def ignored(*exceptions):
    try:
        yield
    except exceptions:
        pass

Then you use it like in Python 3.4:

with ignored(Exception):
    # your code

Django 1.7 - makemigrations not detecting changes

python manage.py makemigrations accounts Migrations for 'accounts': accounts\migrations\0001_initial.py - Create model Customer - Create model Tag - Create model Product - Create model Order

Note: here "accounts" is my app name

How to replace comma (,) with a dot (.) using java

Use this:

String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12

hope help you.

Commenting code in Notepad++

This link was exactly what I was searching for .

Let me summarize the answers for others' benefit (for python and notepad++)

1) Ctrl+K on multiple lines (i.e. selected region) allows you to block comment.

Also note that pressing the combination multiple times allows you to add multiple "#"s (sometimes I use that while testing to differentiate from other comments)

2) Ctrl+Shift+K (on the commented region) allows you to perform block uncomment

3) Ctrl+Shift+K on an uncommented selected region does not comment it

4) Ctrl+Q allows you to block comment/uncomment in a toggled mode (meaning, you cannot add multiple '#'s like in 1) )

Hope this helps another wandering soul.

Question - how would you develop a hack of keyboard combinations to comment/uncomment if there were no shortcuts? Just curious. I've no clue hence asking.

Java Equivalent of C# async/await?

If you're just after clean code which simulates the same effect as async/await in java and don't mind blocking the thread it is called on until it is finished, such as in a test, you could use something like this code:

interface Async {
    void run(Runnable handler);
}

static void await(Async async) throws InterruptedException {

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    async.run(new Runnable() {

        @Override
        public void run() {
            countDownLatch.countDown();
        }
    });
    countDownLatch.await(YOUR_TIMEOUT_VALUE_IN_SECONDS, TimeUnit.SECONDS);
}

    await(new Async() {
        @Override
        public void run(final Runnable handler) {
            yourAsyncMethod(new CompletionHandler() {

                @Override
                public void completion() {
                    handler.run();
                }
            });
        }
    });

How do I determine file encoding in OS X?

Typing file myfile.tex in a terminal can sometimes tell you the encoding and type of file using a series of algorithms and magic numbers. It's fairly useful but don't rely on it providing concrete or reliable information.

A Localizable.strings file (found in localised Mac OS X applications) is typically reported to be a UTF-16 C source file.

Running Jupyter via command line on Windows

Problem for me was that I was running the jupyter command from the wrong directory.

Once I navigated to the path containing the script, everything worked.

Path- C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Scripts

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

I personally use Visual Leak Detector, though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block).

Installing PIL with pip

For CentOS:

yum install python-imaging

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had this issue when having a custom display in my terminal when creating a new git project (I have my branch display before the pathname e.g. :/current/path). All I needed to do was do my initial commit to my master branch to get this message to go away.

Python using enumerate inside list comprehension

Or, if you don't insist on using a list comprehension:

>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

How to use glyphicons in bootstrap 3.0

If you are using grunt to build your application, it's possible that during build the paths change. In this case you need to modify your grunt file like this:

copy: {
        main: {
            files: [{
                src: ['fonts/**'],
                dest: 'dist/fonts/',
                filter: 'isFile',
                expand: true,
                flatten: true
            }, {
                src: ['bower_components/font-awesome/fonts/**'],
                dest: 'dist/css/',
                filter: 'isFile',
                expand: true,
                flatten: false
            }]
        }
    },

Postgres Error: More than one row returned by a subquery used as an expression

USE LIMIT 1 - so It will return only 1 row. Example

customerId- (select id from enumeration where enumerations.name = 'Ready To Invoice' limit 1)

CSS: Center block, but align contents to the left

Normally you should use margin: 0 auto on the div as mentioned in the other answers, but you'll have to specify a width for the div. If you don't want to specify a width you could either (this is depending on what you're trying to do) use margins, something like margin: 0 200px; , this should make your content seems as if it's centered, you could also see the answer of Leyu to my question

PHP Warning: Module already loaded in Unknown on line 0

In Windows 10, I fix this by comment like this

;extension=php_sockets.dll

How can I use a local image as the base image with a dockerfile?

You can have - characters in your images. Assume you have a local image (not a local registry) named centos-base-image with tag 7.3.1611.

docker version 
      Client:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

      Server:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

docker images
 REPOSITORY            TAG
 centos-base-image     7.3.1611

Dockerfile

FROM centos-base-image:7.3.1611
RUN yum -y install epel-release libaio bc flex

Result

Sending build context to Docker daemon 315.9 MB
Step 1 : FROM centos-base-image:7.3.1611
  ---> c4d84e86782e
Step 2 : RUN yum -y install epel-release libaio bc flex
  ---> Running in 36d8abd0dad9
...

In the example above FROM is fetching your local image, you can provide additional instructions to fetch an image from your custom registry (e.g. FROM localhost:5000/my-image:with.tag). See https://docs.docker.com/engine/reference/commandline/pull/#pull-from-a-different-registry and https://docs.docker.com/registry/#tldr

Finally, if your image is not being resolved when providing a name, try adding a tag to the image when you create it

This GitHub thread describes a similar issue of not finding local images by name.

By omitting a specific tag, docker will look for an image tagged "latest", so either create an image with the :latest tag, or change your FROM

How to sort a list of lists by a specific index of the inner list?

I think lambda function can solve your problem.

old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]

#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])

#Resulst of new_list will be:

[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

How do I prompt a user for confirmation in bash script?

qnd: use

read VARNAME
echo $VARNAME

for a one line response without readline support. Then test $VARNAME however you want.

How to change the time format (12/24 hours) of an <input>?

you can try this for html side

<label for="appointment-time">Choose Time</label>
<input class="form-control" type="time" ng-model="time" ng-change="ChangeTime()" />
<label class="form-control" >{{displayTime}}</label>

JavaScript Side

function addMinutes(time/*"hh:mm"*/, minsToAdd/*"N"*/) 
{
        function z(n)
        {
           return (n<10? '0':'') + n;
        }
        var bits = time.split(':');
        var mins = bits[0]*60 + (+bits[1]) + (+minsToAdd);
        return z(mins%(24*60)/60 | 0) + ':' + z(mins%60); 
 }  

 $scope.ChangeTime=function()
 {
      var d = new Date($scope.time);
      var hours=d.getHours();
      var minutes=Math.round(d.getMinutes());
      var ampm = hours >= 12 ? 'PM' : 'AM';
      var Time=hours+':'+minutes;
      var DisplayTime=addMinutes(Time, duration);
      $scope.displayTime=Time+' - '+DisplayTime +' '+ampm;
 }

Python: For each list element apply a function across the list

If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc.

from __future__ import division

import numpy

data = numpy.asarray([1,2,3,4,5])
dists = data.reshape((1,5)) / data.reshape((5,1))

print dists

which = dists.argmin()
(r,c) = (which // 5, which % 5) # assumes C ordering

# pick whichever is most appropriate for you...
minval = dists[r,c]
minval = dists.min()
minval = dists.ravel()[which]

How to append a newline to StringBuilder

Another option is to use Apache Commons StrBuilder, which has the functionality that's lacking in StringBuilder.

StrBuilder.appendLn()

As of version 3.6 StrBuilder has been deprecated in favour of TextStringBuilder which has the same functionality

addEventListener in Internet Explorer

addEventListener is the proper DOM method to use for attaching event handlers.

Internet Explorer (up to version 8) used an alternate attachEvent method.

Internet Explorer 9 supports the proper addEventListener method.

The following should be an attempt to write a cross-browser addEvent function.

function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem["on"+evnt] = func;
   }
}

iconv - Detected an illegal character in input string

this bellow solution worked for me

$result_encr="##Sƒ";

iconv("cp1252", "utf-8//IGNORE", $result_encr);

adding .css file to ejs

Your problem is not actually specific to ejs.

2 things to note here

  1. style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.

  2. In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image

it can be done by

app.use(express.static(__dirname + '/public'));

assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like

<link href="/css/style.css" rel="stylesheet" type="text/css">

Here i assume you have put the css file in css folder inside your public folder.

So folder structure would be

.
./app.js
./public
    /css
        /style.css

Can I call a constructor from another constructor (do constructor chaining) in C++?

No, you can't call one constructor from another in C++03 (called a delegating constructor).

This changed in C++11 (aka C++0x), which added support for the following syntax:
(example taken from Wikipedia)

class SomeType
{
  int number;

public:
  SomeType(int newNumber) : number(newNumber) {}
  SomeType() : SomeType(42) {}
};

Add new value to an existing array in JavaScript

jQuery is an abstraction of JavaScript. Think of jQuery as a sub-set of JavaScript, aimed at working with the DOM. That being said; there are functions for adding item(s) to a collection. I would use basic JavaScript in your case though:

var array;

array[0] = "value1";
array[1] = "value2";
array[2] = "value3";

... Or:

var array = ["value1", "value2", "value3"];

... Or:

var array = [];

array.push("value1");
array.push("value2");
array.push("value3");

What is the best method of handling currency/money?

My underlying APIs were all using cents to represent money, and I didn't want to change that. Nor was I working with large amounts of money. So I just put this in a helper method:

sprintf("%03d", amount).insert(-3, ".")

That converts the integer to a string with at least three digits (adding leading zeroes if necessary), then inserts a decimal point before the last two digits, never using a Float. From there you can add whatever currency symbols are appropriate for your use case.

It's definitely quick and dirty, but sometimes that's just fine!

error: pathspec 'test-branch' did not match any file(s) known to git

Following worked for me

git pull

Then checkout the required branch

lodash: mapping array to object

This is probably more verbose than you want, but you're asking for a slightly complex operation so actual code might be involved (the horror).

My recommendation, with zipObject that's pretty logical:

_.zipObject(_.map(params, 'name'), _.map(params, 'input'));

Another option, more hacky, using fromPairs:

_.fromPairs(_.map(params, function(val) { return [val['name'], val['input']));

The anonymous function shows the hackiness -- I don't believe JS guarantees order of elements in object iteration, so callling .values() won't do.

Rotating videos with FFmpeg

For me it works like this

Rotate clockwise

 ffmpeg -i "path_source_video.mp4" -filter:v "transpose=1" "path_output_video.mp4"

Rotate counterclockwise

 ffmpeg -i "path_source_video.mp4" -filter:v "transpose=0,transpose=1,transpose=0" -acodec copy "path_output_video.mp4"

the package I use zeranoe

JavaScript closures vs. anonymous functions

Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.

A simple explanation for closures:

  1. Take a function. Let's call it F.
  2. List all the variables of F.
  3. The variables may be of two types:
    1. Local variables (bound variables)
    2. Non-local variables (free variables)
  4. If F has no free variables then it cannot be a closure.
  5. If F has any free variables (which are defined in a parent scope of F) then:
    1. There must be only one parent scope of F to which a free variable is bound.
    2. If F is referenced from outside that parent scope, then it becomes a closure for that free variable.
    3. That free variable is called an upvalue of the closure F.

Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):

Case 1: Your Friend's Program

for (var i = 0; i < 10; i++) {
    (function f() {
        var i2 = i;
        setTimeout(function g() {
            console.log(i2);
        }, 1000);
    })();
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. i is a free variable.
    3. setTimeout is a free variable.
    4. g is a local variable.
    5. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. i is bound to the global scope.
    2. setTimeout is bound to the global scope.
    3. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence i is not closed over by f.
    2. Hence setTimeout is not closed over by f.
    3. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Bad for you: Your friend is using a closure. The inner function is a closure.

Case 2: Your Program

for (var i = 0; i < 10; i++) {
    setTimeout((function f(i2) {
        return function g() {
            console.log(i2);
        };
    })(i), 1000);
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. g is a local variable.
    3. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Good for you: You are using a closure. The inner function is a closure.

So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.

Edit: A simple explanation as to why are all functions closures (credits @Peter):

First let's consider the following program (it's the control):

_x000D_
_x000D_
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
    regularFunction();_x000D_
_x000D_
    function regularFunction() {_x000D_
        alert(eval("message"));_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that both lexicalScope and regularFunction aren't closures from the above definition.
  2. When we execute the program we expect message to be alerted because regularFunction is not a closure (i.e. it has access to all the variables in its parent scope - including message).
  3. When we execute the program we observe that message is indeed alerted.

Next let's consider the following program (it's the alternative):

_x000D_
_x000D_
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
    return function closureFunction() {_x000D_
        alert(eval("message"));_x000D_
    };_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that only closureFunction is a closure from the above definition.
  2. When we execute the program we expect message not to be alerted because closureFunction is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message).
  3. When we execute the program we observe that message is actually being alerted.

What do we infer from this?

  1. JavaScript interpreters do not treat closures differently from the way they treat other functions.
  2. Every function carries its scope chain along with it. Closures don't have a separate referencing environment.
  3. A closure is just like every other function. We just call them closures when they are referenced in a scope outside the scope to which they belong because this is an interesting case.

Can we have multiple "WITH AS" in single sql - Oracle SQL

You can do this as:

WITH abc AS( select
             FROM ...)
, XYZ AS(select
         From abc ....) /*This one uses "abc" multiple times*/
  Select 
  From XYZ....   /*using abc, XYZ multiple times*/

Check if a value is in an array (C#)

I searched now over 2h to find a nicely way how to find duplicates in a list and how to remove them. Here is the simplest answer:

//Copy the string array with the filtered data of the analytics db into an list
// a list should be easier to use
List<string> list_filtered_data = new List<string>(analytics_db_filtered_data);

// Get distinct elements and convert into a list again.
List<string> distinct = list_filtered_data.Distinct().ToList();

The Output will look like this: Duplicated Elements will be removed in the new list called distinct!

Convert varchar to uniqueidentifier in SQL Server

SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

how to remove css property using javascript?

actually, if you already know the property, this will do it...

for example:

<a href="test.html" style="color:white;zoom:1.2" id="MyLink"></a>

    var txt = "";
    txt = getStyle(InterTabLink);
    setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");

    function setStyle(element, styleText){
        if(element.style.setAttribute)
            element.style.setAttribute("cssText", styleText );
        else
            element.setAttribute("style", styleText );
    }

    /* getStyle function */
    function getStyle(element){
        var styleText = element.getAttribute('style');
        if(styleText == null)
            return "";
        if (typeof styleText == 'string') // !IE
            return styleText;
        else  // IE
            return styleText.cssText;
    } 

Note that this only works for inline styles... not styles you've specified through a class or something like that...

Other note: you may have to escape some characters in that replace statement, but you get the idea.

How do I get countifs to select all non-blank cells in Excel?

You can try this :

=COUNTIF(Data!A2:A300,"<>"&"")

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

Where are the python modules stored?

On python command line, first import that module for which you need location.

import module_name

Then type:

print(module_name.__file__)

For example to find out "pygal" location:

import pygal
print(pygal.__file__)

Output:

/anaconda3/lib/python3.7/site-packages/pygal/__init__.py

How to convert Map keys to array?

myMap.map(([x,_]) => {x});

Above should also work

why windows 7 task scheduler task fails with error 2147942667

I had this same issue.

The solution for me was found in the Microsoft KB Article 2452723:

Windows Vista onwards scheduled tasks fail to run if the path in "Start in (Optional)" field has quotes

Basically, edit your scheduled task and take the Quotes out of the Start In field:

  1. Open your Scheduled Task
  2. Switch to "Actions" tab
  3. Open your Action
  4. Remove Quotes (") from the field "Start in (optional)"
  5. Save and close all open dialogs

Edit Action Dialog Box

To get the relevant error message:

1) Convert 2147942667 to hex: 8007010B
2) Take last 4 digits (010B) and convert to decimal: 267
3) Run: net helpmsg 267
4) Result: "The directory name is invalid."

Command Prompt Window

The performance impact of using instanceof in Java

You're focusing on the wrong thing. The difference between instanceof and any other method for checking the same thing would probably not even be measurable. If performance is critical then Java is probably the wrong language. The major reason being that you can't control when the VM decides it wants to go collect garbage, which can take the CPU to 100% for several seconds in a large program (MagicDraw 10 was great for that). Unless you are in control of every computer this program will run on you can't guarantee which version of JVM it will be on, and many of the older ones had major speed issues. If it's a small app you may be ok with Java, but if you are constantly reading and discarding data then you will notice when the GC kicks in.

How can we dynamically allocate and grow an array

You have to manually create a new bigger array and copy over the items.

this may help

Asp.net Validation of viewstate MAC failed

I am not sure how this happened but I started to get this error in my internal submit form pages. So when ever I submit something I'm getting this error. But the problem is this website is almost working 5-6 years. I don't remember I made an important change.

None of the solutions worked for me.

I have setup a machine key with the Microsoft script and copied into my web.config

I have executed asp.net regiis script.

aspnet_regiis -ga "IIS APPPOOL\My App Pool"

Also tried to add this code into the page:

enableViewStateMac="false"

still no luck.

Any other idea to solve this issue?

UPDATE:

Finally I solved the issue. I had integrated my angular 4 component into my asp.net website. So I had added base href into my master page. So I removed that code and it is working fine now.

<base href="/" />

how to detect search engine bots with php?

Check the $_SERVER['HTTP_USER_AGENT'] for some of the strings listed here:

http://www.useragentstring.com/pages/useragentstring.php

Or more specifically for crawlers:

http://www.useragentstring.com/pages/useragentstring.php?typ=Crawler

If you want to -say- log the number of visits of most common search engine crawlers, you could use

$interestingCrawlers = array( 'google', 'yahoo' );
$pattern = '/(' . implode('|', $interestingCrawlers) .')/';
$matches = array();
$numMatches = preg_match($pattern, strtolower($_SERVER['HTTP_USER_AGENT']), $matches, 'i');
if($numMatches > 0) // Found a match
{
  // $matches[1] contains an array of all text matches to either 'google' or 'yahoo'
}

Failed to resolve version for org.apache.maven.archetypes

If you are using eclipse, you can follow the steps here (maven in 5 min not working) for getting your proxy information. Once done follow the steps below:

  1. Go to Maven installation folder C:\apache-maven-3.1.0\conf\
  2. Copy settings.xml to C:\Users\[UserFolder]\.m2
  3. Modify the proxy in settings.xml based on the info that you get from the above link.

    <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>your proxy</host>
      <port>your port</port>
    </proxy>
    
  4. Open eclipse

  5. Go to: Windows > Preferences > Maven > User Settings

  6. Browse the settings.xml from .m2 folder

  7. Click Update Settings

  8. Click Reindex

  9. Apply the changes and Click OK

You can now try to create Maven Project in Eclipse

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

Regex - Does not contain certain Characters

Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

Restarting cron after changing crontab file?

1) If file /var/spool/cron/crontabs/root edit via SFTP client - need service cron restart. Reload service not work.

2) If edit file /var/spool/cron/crontabs/root via console linux (nano, mc) - restart NOT need.

3) If edit cron via crontab -e - restart NOT need.

How exactly does the python any() function work?

(x > 0 for x in list) in that function call creates a generator expression eg.

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

Which any uses, and shortcircuits on encountering the first object that evaluates True

BigDecimal equals() versus compareTo()

I believe that the correct answer would be to make the two numbers (BigDecimals), have the same scale, then we can decide about their equality. For example, are these two numbers equal?

1.00001 and 1.00002

Well, it depends on the scale. On the scale 5 (5 decimal points), no they are not the same. but on smaller decimal precisions (scale 4 and lower) they are considered equal. So I suggest make the scale of the two numbers equal and then compare them.

How to make space between LinearLayout children?

The sample below just does what you need programatically. I have used a fixed size of (140,398).

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(140, 398);
        layoutParams.setMargins(24, 0, 24, 0);
        layout.addView(button,layoutParams);

How to wait for async method to complete?

The most important thing to know about async and await is that await doesn't wait for the associated call to complete. What await does is to return the result of the operation immediately and synchronously if the operation has already completed or, if it hasn't, to schedule a continuation to execute the remainder of the async method and then to return control to the caller. When the asynchronous operation completes, the scheduled completion will then execute.

The answer to the specific question in your question's title is to block on an async method's return value (which should be of type Task or Task<T>) by calling an appropriate Wait method:

public static async Task<Foo> GetFooAsync()
{
    // Start asynchronous operation(s) and return associated task.
    ...
}

public static Foo CallGetFooAsyncAndWaitOnResult()
{
    var task = GetFooAsync();
    task.Wait(); // Blocks current thread until GetFooAsync task completes
                 // For pedagogical use only: in general, don't do this!
    var result = task.Result;
    return result;
}

In this code snippet, CallGetFooAsyncAndWaitOnResult is a synchronous wrapper around asynchronous method GetFooAsync. However, this pattern is to be avoided for the most part since it will block a whole thread pool thread for the duration of the asynchronous operation. This an inefficient use of the various asynchronous mechanisms exposed by APIs that go to great efforts to provide them.

The answer at "await" doesn't wait for the completion of call has several, more detailed, explanations of these keywords.

Meanwhile, @Stephen Cleary's guidance about async void holds. Other nice explanations for why can be found at http://www.tonicodes.net/blog/why-you-should-almost-never-write-void-asynchronous-methods/ and https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

What is the difference between a schema and a table and a database?

In oracle Schema is one user under one database,For example scott is one schema in database orcl. In one database we may have many schema's like scott

Calculating Page Table Size

My explanation uses elementary building blocks that helped me to understand. Note I am leveraging @Deepak Goyal's answer above since he provided clarity:

We were given a logical 32-bit address space (i.e. We have a 32 bit computer)

Consider a system with a 32-bit logical address space

We were also told that

each page size is 4 KB

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • 4 x 1024 bytes = 2^2 x 2^10 bytes => 4 KB (i.e. 2^12 bytes)
  • The size of each page is thus 4 KB (Kilobytes NOT kilobits).

As Depaak said, we calculate the number of pages in the page table with this formula:

Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^32                           /    2^12
Num_Pages_in_PgTable = 2^20 (i.e. 1 million) 

The authors go on to give the case where each entry in the page table takes 4 bytes. That means that the total size of the page table in physical memory will be 4MB:

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page =           4                 x     2^20
Memory_Required_Per_Page =     4 MB (Megabytes)

So yes, each process would require at least 4MB of memory to run, in increments of 4MB.

Example

Now if a professor wanted to make the question a bit more challenging than the explanation from the book, they might ask about a 64-bit computer. Let's say they want memory in bits. To solve the question, we'd follow the same process, only being sure to convert MB to Mbits.

Let's step through this example.

Givens:

  • Logical address space: 64-bit
  • Page Size: 4KB
  • Entry_Size_Per_Page: 4 bytes

Recall: A 64-bit entry can point to one of 2^64 physical page frames - Since Page size is 4 KB, then we still have 2^12 byte page sizes

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • Size of each page = 4 x 1024 bytes = 2^2 x 2^10 bytes = 2^12 bytes

How Many pages In Page Table?

`Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^64                            /    2^12
Num_Pages_in_PgTable =         2^52 
Num_Pages_in_PgTable =      2^2 x 2^50 
Num_Pages_in_PgTable =       4  x 2^50 `  

How Much Memory in BITS Per Page?

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable 
Memory_Required_Per_Page =   4 bytes x 8 bits/byte    x     2^52
Memory_Required_Per_Page =     32 bits                x   2^2 x 2^50
Memory_Required_Per_Page =     32 bits                x    4  x 2^50
Memory_Required_Per_Page =     128 Petabits

[2]: Operating System Concepts (9th Ed) - Gagne, Silberschatz, and Galvin

How to get pandas.DataFrame columns containing specific dtype

Someone will give you a better answe than this possibly, but one thing I tend to do is if all my numeric data are int64 or float64 objects, then you can create a dict of the column data types and then use the values to create your list of columns.

So for example, in a dataframe where I have columns of type float64, int64 and object firstly you can look at the data types as so:

DF.dtypes

and if they conform to the standard whereby the non-numeric columns of data are all object types (as they are in my dataframes), then you can do the following to get a list of the numeric columns:

[key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]

Its just a simple list comprehension. Nothing fancy. Again, though whether this works for you will depend upon how you set up you dataframe...

Share application "link" in Android

Thomas,

You would want to provide your users with a market:// link which will bring them directly to the details page of your app. The following is from developer.android.com:

Loading an application's Details page

In Android Market, every application has a Details page that provides an overview of the application for users. For example, the page includes a short description of the app and screen shots of it in use, if supplied by the developer, as well as feedback from users and information about the developer. The Details page also includes an "Install" button that lets the user trigger the download/purchase of the application.

If you want to refer the user to a specific application, your application can take the user directly to the application's Details page. To do so, your application sends an ACTION_VIEW Intent that includes a URI and query parameter in this format:

market://details?id=

In this case, the packagename parameter is target application's fully qualified package name, as declared in the package attribute of the manifest element in the application's manifest file. For example:

market://details?id=com.example.android.jetboy

Source: http://developer.android.com/guide/publishing/publishing.html

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

replace String with another in java

Replacing one string with another can be done in the below methods

Method 1: Using String replaceAll

 String myInput = "HelloBrother";
 String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
 ---OR---
 String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
 System.out.println("My Output is : " +myOutput);       

Method 2: Using Pattern.compile

 import java.util.regex.Pattern;
 String myInput = "JAVAISBEST";
 String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
 ---OR -----
 String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
 System.out.println("My Output is : " +myOutputWithRegEX);           

Method 3: Using Apache Commons as defined in the link below:

http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)

REFERENCE

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

How to set Android camera orientation properly?

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:

Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.

The method:

    protected void setDisplayOrientation(Camera camera, int angle){
    Method downPolymorphic;
    try
    {
        downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
        if (downPolymorphic != null)
            downPolymorphic.invoke(camera, new Object[] { angle });
    }
    catch (Exception e1)
    {
    }
}

And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :

    if (Integer.parseInt(Build.VERSION.SDK) >= 8)
        setDisplayOrientation(mCamera, 90);
    else
    {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation", 90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }
    }   

adding onclick event to dynamically added button?

Try this:

var inputTag = document.createElement("div");              
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
document.body.appendChild(inputTag);

This creates a button inside a DIV which works perfectly!

Insert, on duplicate update in PostgreSQL?

I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.

My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.

This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.

The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.

 #This is pseudo-code - within the application:
 BEGIN TRANSACTION - get transaction lock
 SELECT all current name value pairs where id = $id into a hash record
 create a merge record from the current and update record
  (set intersection where shared keys in new win, and empty values in new are deleted).
 DELETE all name value pairs where id = $id
 COPY/INSERT merged records 
 END TRANSACTION

Perform Button click event when user press Enter key in Textbox

in the html code only, add a panel that contains the page's controls. Inside the panel, add a line DefaultButton = "buttonNameThatClicksAtEnter". See the example below, there should be nothing else required.

<asp:Panel runat="server" DefaultButton="Button1"> //add this!
  //here goes all the page controls and the trigger button
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
</asp:Panel> //and this too!

Remove Safari/Chrome textinput/textarea glow

Edit (11 years later): Don't do this unless you're going to provide a fallback to indicate which element is active. Otherwise, this harms accessibility as it essentially removes the indication showing which element in a document has focus. Imagine being a keyboard user and not really knowing what element you can interact with. Let accessibility trump aesthetics here.

textarea, select, input, button { outline: none; }

Although, it's been argued that keeping the glow/outline is actually beneficial for accessibility as it can help users see which Element is currently focused.

You can also use the pseudo-element ':focus' to only target the inputs when the user has them selected.

Demo: https://jsfiddle.net/JohnnyWalkerDesign/xm3zu0cf/

How do you validate a URL with a regular expression in Python?

I'm using the one used by Django and it seems to work pretty well:

def is_valid_url(url):
    import re
    regex = re.compile(
        r'^https?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    return url is not None and regex.search(url)

You can always check the latest version here: https://github.com/django/django/blob/master/django/core/validators.py#L74

UINavigationBar custom back button without title

To add to Thomas C's answer above, sometimes putting a single space doesn't work and you have to keep adding spaces.

empty bar button

You'll know you succeeded when you see "Bar Button Item - " under the "Navigation Item". That's in the Document Outline (Editor->Show Document Outline). Once you see the above picture, you can delete a few spaces and see if it still works.

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

What does "make oldconfig" do exactly in the Linux kernel makefile?

From this page:

Make oldconfig takes the .config and runs it through the rules of the Kconfig files and produces a .config which is consistant with the Kconfig rules. If there are CONFIG values which are missing, the make oldconfig will ask for them.

If the .config is already consistant with the rules found in Kconfig, then make oldconfig is essentially a no-op.

If you were to run make oldconfig, and then run make oldconfig a second time, the second time won't cause any additional changes to be made.

How can I load webpage content into a div on page load?

With jQuery, it is possible, however not using ajax.

function LoadPage(){
  $.get('http://a_site.com/a_page.html', function(data) {
    $('#siteloader').html(data);
  });
}

And then place onload="LoadPage()" in the body tag.

Although if you follow this route, a php version might be better:

echo htmlspecialchars(file_get_contents("some URL"));

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

I've added the <%% literal tag delimiter as an answer to this because of its obscurity. This will tell erb not to interpret the <% part of the tag which is necessary for js apps like displaying chart.js tooltips etc.

Update (Fixed broken link)

Everything about ERB can now be found here: https://puppet.com/docs/puppet/5.3/lang_template_erb.html#tags

psql: FATAL: Peer authentication failed for user "dev"

For people in the future seeing this, postgres is in the /usr/lib/postgresql/10/bin on my Ubuntu server.

I added it to the PATH in my .bashrc file, and add this line at the end

PATH=$PATH:/usr/lib/postgresql/10/bin

then on the command line

$> source ./.bashrc

I refreshed my bash environment. Now I can use postgres -D /wherever from any directory

Smooth scrolling when clicking an anchor link

I suggest you to make this generic code :

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

    $('html, body').animate({
        scrollTop:$(the_id).offset().top
    }, 'slow');

return false;});

You can see a very good article here : jquery-effet-smooth-scroll-defilement-fluide

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

JQuery DatePicker ReadOnly

You can set the range allowed to some invalid range so the user can't select any date:

$("#datepicker").datepicker({minDate:-1,maxDate:-2}).attr('readonly','readonly');     

Logging best practices

We use Log4Net at work as the logging provider, with a singleton wrapper for the log instance (although the singleton is under review, questioning whether they are a good idea or not).

We chose it for the following reasons:

  • Simple configuration/ reconfiguration on various environments
  • Good number of pre-built appenders
  • One of the CMS's we use already had it built in
  • Nice number of log levels and configurations around them

I should mention, this is speaking from an ASP.NET development point of view

I can see some merits in using the Trace that is in the .NET framework but I'm not entirely sold on it, mainly because the components I work with don't really do any Trace calls. The only thing that I frequently use that does is System.Net.Mail from what I can tell.

So we have a library which wraps log4net and within our code we just need stuff like this:

Logger.Instance.Warn("Something to warn about");
Logger.Instance.Fatal("Something went bad!", new Exception());

try {
  var i = int.Parse("Hello World");
} catch(FormatException, ex) {
  Logger.Instance.Error(ex);
}

Within the methods we do a check to see if the logging level is enabled, so you don't have redundant calls to the log4net API (so if Debug isn't enabled, the debug statements are ignored), but when I get some time I'll be updating it to expose those so that you can do the checks yourself. This will prevent evaluations being undertaken when they shouldn't, eg:

Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);

This will become:

if(Logger.DebugEnabled) Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);

(Save a bit of execusion time)

By default we log at two locations:

  1. File system of the website (in a non-served file extension)
  2. Email sending for Error & Fatal

Files are done as rolling of each day or 10mb (IIRC). We don't use the EventLog as it can require higher security than we often want to give a site.

I find Notepad works just fine for reading logs.

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

Handlebars.js Else If

I usually use this form:

{{#if FriendStatus.IsFriend}}
  ...
{{else}} {{#if FriendStatus.FriendRequested}}
  ...
{{else}}
  ...
{{/if}}{{/if}}

Newline in markdown table?

Use <br/> . For example:

Change log, upgrade version

Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`

URL: https://github.com/donhuvy/lsb/wiki

Docker - Ubuntu - bash: ping: command not found

Every time you get this kind of error

bash: <command>: command not found
  • On a host with that command already working with this solution:

    dpkg -S $(which <command>)
    
  • Don't have a host with that package installed? Try this:

    apt-file search /bin/<command>
    

Flask at first run: Do not use the development server in a production environment

When running the python file, you would normally do this

python app.py
This will display these messages.

To avoid these messsages. Inside the CLI (Command Line Interface), run these commands.

export FLASK_APP=app.py
export FLASK_RUN_HOST=127.0.0.1
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run

This should work perfectlly. :) :)

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

I know its late to answer here, still if anybody want to know solution is below

conversationView.smoothScrollToPosition(conversationView.getAdapter().getItemCount() - 1);

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Align HTML input fields by :

I know that this approach has been taken before, But I believe that using tables, the layout can be generated easily, Though this may not be the best practice.

JSFiddle

HTML

<table>

    <tr><td>Name:</td><td><input type="text"/></td></tr>

    <tr><td>Age:</td><td><input type="text"/></td></tr>

</table>

<!--You can add the fields as you want-->

CSS

td{
    text-align:right;
}

100% width background image with an 'auto' height

Try this

html { 
  background: url(image.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
     -moz-background-size: cover;
       -o-background-size: cover;
          background-size: cover;
}

Simplified version

html {
  background: url(image.jpg) center center / cover no-repeat fixed;
}

R memory management / cannot allocate vector of size n Mb

I followed to the help page of memory.limit and found out that on my computer R by default can use up to ~ 1.5 GB of RAM and that the user can increase this limit. Using the following code,

>memory.limit()
[1] 1535.875
> memory.limit(size=1800)

helped me to solve my problem.

ComboBox: Adding Text and Value to an Item (no Binding Source)

This is one of the ways that just came to mind:

combo1.Items.Add(new ListItem("Text", "Value"))

And to change text of or value of an item, you can do it like this:

combo1.Items[0].Text = 'new Text';

combo1.Items[0].Value = 'new Value';

There is no class called ListItem in Windows Forms. It only exists in ASP.NET, so you will need to write your own class before using it, the same as @Adam Markowitz did in his answer.

Also check these pages, they may help:

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.

Blowfish();

How to check if a string contains an element from a list in Python

Use a generator together with any, which short-circuits on the first True:

if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)

EDIT: I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all that this solution does. It does not care WHERE the string is found e.g. in the ending of the string. If this is important, as is often the case with urls, you should look to the answer of @Wladimir Palant, or you risk getting false positives.

Why do you need to invoke an anonymous function on the same line?

The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,

function help() {return true;}

If you call result = help(); this is a call to a function and will return true.

If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.

What you did was declaring/instantiating an anonymous function by adding the semicolon,

(function (msg) { /* Code here */ });

and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:

('SO');

The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:

(function (msg){/*code here*/});('SO');

It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.

(function (msg){/*code here*/})        // This space is ignored by the interpreter
('SO');

Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".

How to check if a String contains only ASCII?

You can do it with java.nio.charset.Charset.

import java.nio.charset.Charset;

public class StringUtils {

  public static boolean isPureAscii(String v) {
    return Charset.forName("US-ASCII").newEncoder().canEncode(v);
    // or "ISO-8859-1" for ISO Latin 1
    // or StandardCharsets.US_ASCII with JDK1.7+
  }

  public static void main (String args[])
    throws Exception {

     String test = "Réal";
     System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
     test = "Real";
     System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));

     /*
      * output :
      *   Réal isPureAscii() : false
      *   Real isPureAscii() : true
      */
  }
}

Detect non-ASCII character in a String

Dynamically access object property using variable

You can achieve this in quite a few different ways.

let foo = {
    bar: 'Hello World'
};

foo.bar;
foo['bar'];

The bracket notation is specially powerful as it let's you access a property based on a variable:

let foo = {
    bar: 'Hello World'
};

let prop = 'bar';

foo[prop];

This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'
};

for (let prop in foo.getOwnPropertyNames()) {
    console.log(foo[prop]);
}

Both dot and bracket notation also work as expected for nested objects:

let foo = {
    bar: {
        baz: 'Hello World'
    }
};

foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;

Object destructuring

We could also consider object destructuring as a means to access a property in an object, but as follows:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'
};

let prop = 'last';
let { bar, baz, [prop]: customName } = foo;

// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'

Converting stream of int's to char's in java

Maybe you are asking for:

Character.toChars(65) // returns ['A']

More info: Character.toChars(int codePoint)

Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.

SQL Server: Cannot insert an explicit value into a timestamp column

According to MSDN, timestamp

Is a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type.

You're probably looking for the datetime data type instead.

ld cannot find an existing library

Unless I'm badly mistaken libmagic or -lmagic is not the same library as ImageMagick. You state that you want ImageMagick.

ImageMagick comes with a utility to supply all appropriate options to the compiler.

Ex:

g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o "prog"

How can I get the current page name in WordPress?

I have come up with a simpler solution.

Get the returned value of the page name from wp_title(). If empty, print homepage name, otherwise echo the wp_title() value.

<?php $title = wp_title('', false); ?>

Remember to remove the separation with the first argument and then set display to false to use as an input to the variable. Then just bung the code between your heading, etc. tags.

<?php if ( $title == "" ) : echo "Home"; else : echo $title; endif; ?>

It worked a treat for me and ensuring that the first is declared in the section where you wish to extract the $title, this can be tuned to return different variables.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was failing to send a body on a DELETE that required one and was getting this message as a result.

Get the latest record from mongodb collection

This will give you one last document for a collection

db.collectionName.findOne({}, {sort:{$natural:-1}})

$natural:-1 means order opposite of the one that records are inserted in.

Edit: For all the downvoters, above is a Mongoose syntax, mongo CLI syntax is: db.collectionName.find({}).sort({$natural:-1}).limit(1)

Way to run Excel macros from command line or batch file?

The simplest way to do it is to:

1) Start Excel from your batch file to open the workbook containing your macro:

EXCEL.EXE /e "c:\YourWorkbook.xls"

2) Call your macro from the workbook's Workbook_Open event, such as:

Private Sub Workbook_Open()
    Call MyMacro1          ' Call your macro
    ActiveWorkbook.Save    ' Save the current workbook, bypassing the prompt
    Application.Quit       ' Quit Excel
End Sub

This will now return the control to your batch file to do other processing.

How to fill a datatable with List<T>

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

Print raw string from variable? (not getting the answers)

I know i'm too late for the answer but for people reading this I found a much easier way for doing it

myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)

Declaring a custom android UI element using XML

You can include any layout file in other layout file as-

             <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="30dp" >

                <include
                    android:id="@+id/frnd_img_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_imagefile"/>

                <include
                    android:id="@+id/frnd_video_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_video_lay" />

                <ImageView
                    android:id="@+id/downloadbtn"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_centerInParent="true"
                    android:src="@drawable/plus"/>
            </RelativeLayout>

here the layout files in include tag are other .xml layout files in the same res folder.

What is the syntax to insert one list into another list in python?

If we just do x.append(y), y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:

x = [1,2,3] y = [4,5,6] x.append(y[:])

How to stop mongo DB in one command

I use this startup script on Ubuntu.

#!/bin/sh

### BEGIN INIT INFO
# Provides:     mongodb
# Required-Sart:
# Required-Stop:
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description: mongodb
# Description: mongo db server
### END INIT INFO

. /lib/lsb/init-functions

PROGRAM=/opt/mongo/bin/mongod
MONGOPID=`ps -ef | grep 'mongod' | grep -v grep | awk '{print $2}'`

test -x $PROGRAM || exit 0

case "$1" in
  start)
     log_begin_msg "Starting MongoDB server"
         ulimit -v unlimited.
         ulimit -n 100000
     /opt/mongo/bin/mongod --fork --quiet --dbpath /data/db --bind_ip 127.0.0.1 --rest   --config /etc/mongod.conf.
     log_end_msg 0
     ;;
  stop)
     log_begin_msg "Stopping MongoDB server"
     if [ ! -z "$MONGOPID" ]; then
kill -15 $MONGOPID
     fi
     log_end_msg 0
     ;;
  status)
     ;;
  *)
     log_success_msg "Usage: /etc/init.d/mongodb {start|stop|status}"
     exit 1
esac

exit 0

How do I use setsockopt(SO_REUSEADDR)?

After :

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
    error("ERROR opening socket");

You can add (with standard C99 compound literal support) :

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Or :

int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting JButton.setOpaque(true)?

JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

jQuery - passing value from one input to another

It's simpler if you modify your HTML a little bit:

<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />

<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />

<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />

then it's relatively simple

$(document).ready(function() { 
    $('#name').change(function() {
      $('#firstname').val($('#name').val());
    });
});

@Scope("prototype") bean scope not creating new bean

@Component

@Scope(value="prototype")

public class TennisCoach implements Coach {

// some code

}

How can I run a PHP script inside a HTML file?

Yes, you can run PHP in an HTML page.

I have successfully executed PHP code in my HTML files for many years. (For the curious, this is because I have over 8,000 static HTML files created by me and others over the last 20 years and I didn't want to lose search engine ranking by changing them and, more importantly, I have too many other things to work on).

I am not an expert -- below is what I've tried and what works for me. Please don't ask me to explain it.

Everything below involves adding a line or two to your .htaccess file.

Here is what one host ( http://simolyhosting.net ) support did for me in 2008 -- but it no longer works for me now.

AddHandler application/x-httpd-php5 .html .htm
AddType application/x-httpd-php5 .htm .html

That solution appears to be deprecated now, though it might work for you.

Here's what's working for me now:

AddType application/x-httpd-lsphp .htm .html

(This page has PHP code that executes properly with the above solution -- http://mykindred.com/bumstead/steeplehistory.htm )


Below are other solutions I found -- they are NOT MINE:


https://forums.cpanel.net/threads/cant-execute-php-in-html-since-ea4-upgrade.569531

I'm seeing this across many servers I've recently upgraded to EA4. Using cPanel Apache handlers or adding this directly in to .htaccess (same as cPanel does through gui add handlers):

AddHandler application/x-httpd-php5 .html

Sep 9, 2016

AddHandler application/x-httpd-ea-php56 .html

https://help.1and1.com/hosting-c37630/scripts-and-programming-languages-c85099/php-c37728/parsing-php-code-within-html-pages-a602364.html

Open a text editor such as wordpad, notepad, nano, etc. and add the following line:

AddHandler x-mapp-php5 .html .htm

If you want to use PHP 5.4 instead of PHP 5.2 then use the following line instead:

AddHandler x-mapp-php6 .html .htm

https://www.godaddy.com/community/Developer-Cloud-Portal/Running-php-in-html-files/td-p/2776

To run HTML using FastCGI/PHP, try adding this code to the .htaccess file for the directory the script is in:

Options +ExecCGI
AddHandler fcgid-script .html
FCGIWrapper /usr/local/cpanel/cgi-sys/php5 .html

You can add additional lines for other file extensions if needed.

Bash scripting, multiple conditions in while loop

Try:

while [ $stats -gt 300 -o $stats -eq 0 ]

[ is a call to test. It is not just for grouping, like parentheses in other languages. Check man [ or man test for more information.

C compiler for Windows?

Be careful to use a C compiler, not C++ if you're actually doing C. While most programs in C will work using a C++ compiler there are enough differences that there can be problems. I would agree with the people who suggest using gcc via cygwin.

EDIT:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B shows some of the major differences

How to get progress from XMLHttpRequest

One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.

Best way to check if an PowerShell Object exist?

You can also do

if ($ie) {
    # Do Something if $ie is not null
}

How do I monitor all incoming http requests?

I would install Microsoft Network Monitor, configure the tool so it would only see HTTP packets (filter the port) and start capturing packets.

You could download it here

How to convert R Markdown to PDF?

Only two steps:

  1. Install the latest release "pandoc" from here:

    https://github.com/jgm/pandoc/releases

  2. Call the function pandoc in the library(knitr)

    library(knitr)
    pandoc('input.md', format = 'latex')
    

Thus, you can convert your "input.md" into "input.pdf".

How to create war files

I've always just selected Export from Eclipse. It builds the war file and includes all necessary files. Providing you created the project as a web project that's all you'll need to do. Eclipse makes it very simple to do.

jQuery - selecting elements from inside a element

You can use find option to select an element inside another. For example, to find an element with id txtName in a particular div, you can use like

var name = $('#div1').find('#txtName').val();

Move the mouse pointer to a specific position?

You could detect position of the mouse pointer and then move the web page (with body position relative) so they hover over what you want them to click.

For an example you can paste this code on the current page in your browser console (and refresh afterwards)

var upvote_position = $('#answer-12878316').position();
$('body').mousemove(function (event) {
    $(this).css({
        position: 'relative',
        left: (event.pageX - upvote_position.left - 22) + 'px',
        top: (event.pageY - upvote_position.top - 35) + 'px'
    });        
});

Check if string ends with one of the strings from a list

There is two ways: regular expressions and string (str) methods.

String methods are usually faster ( ~2x ).

import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)

792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)

274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Waiting till the async task finish its work

Although optimally it would be nice if your code can run parallel, it can be the case you're simply using a thread so you do not block the UI thread, even if your app's usage flow will have to wait for it.

You've got pretty much 2 options here;

  1. You can execute the code you want waiting, in the AsyncTask itself. If it has to do with updating the UI(thread), you can use the onPostExecute method. This gets called automatically when your background work is done.

  2. If you for some reason are forced to do it in the Activity/Fragment/Whatever, you can also just make yourself a custom listener, which you broadcast from your AsyncTask. By using this, you can have a callback method in your Activity/Fragment/Whatever which only gets called when you want it: aka when your AsyncTask is done with whatever you had to wait for.

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

How to extract base URL from a string in JavaScript?

You can use below codes for get different parameters of Current URL

alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);

Replace Fragment inside a ViewPager

I doing something to similar to wize but in my answer yo can change between the two fragments whenever you want. And with the wize answer I have some problems when changing the orientation of the screen an things like that. This is the PagerAdapter looks like:

    public class MyAdapter extends FragmentPagerAdapter
{
    static final int NUM_ITEMS = 2;
    private final FragmentManager mFragmentManager;
    private Fragment mFragmentAtPos0;
     private Map<Integer, String> mFragmentTags;
     private boolean isNextFragment=false;

    public MyAdapter(FragmentManager fm)
    {
        super(fm);
        mFragmentManager = fm;
         mFragmentTags = new HashMap<Integer, String>();
    }

    @Override
    public Fragment getItem(int position)
    {
        if (position == 0)
        {


            if (isPager) {
                mFragmentAtPos0 = new FirstPageFragment();
            } else {
                mFragmentAtPos0 = new NextFragment();
            }
            return mFragmentAtPos0;
        }
        else
            return SecondPageFragment.newInstance();
    }

    @Override
    public int getCount()
    {
        return NUM_ITEMS;
    }


 @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Object obj = super.instantiateItem(container, position);
        if (obj instanceof Fragment) {
            // record the fragment tag here.
            Fragment f = (Fragment) obj;
            String tag = f.getTag();
            mFragmentTags.put(position, tag);
        }
        return obj;
    }


    public void onChange(boolean isNextFragment) {

        if (mFragmentAtPos0 == null)
            mFragmentAtPos0 = getFragment(0);
        if (mFragmentAtPos0 != null)
            mFragmentManager.beginTransaction().remove(mFragmentAtPos0).commit();


        if (!isNextFragment) {
            mFragmentAtFlashcards = new FirstPageFragment();
        } else {
            mFragmentAtFlashcards = new NextFragment();
        }

        notifyDataSetChanged();


    }


    @Override
    public int getItemPosition(Object object)
    {
        if (object instanceof FirstPageFragment && mFragmentAtPos0 instanceof NextFragment)
            return POSITION_NONE;
         if (object instanceof NextFragment && mFragmentAtPos0 instanceof FirstPageFragment)
            return POSITION_NONE;
        return POSITION_UNCHANGED;
    }


    public Fragment getFragment(int position) {
        String tag = mFragmentTags.get(position);
        if (tag == null)
            return null;
        return mFragmentManager.findFragmentByTag(tag);
    }
}

The listener I implemented in the adapter container activity to put it to the fragment when attaching it, this is the activity:

    public class PagerContainerActivity extends AppCompatActivity implements ChangeFragmentListener {

//...

  @Override
    public void onChange(boolean isNextFragment) {
        if (pagerAdapter != null)
            pagerAdapter.onChange(isNextFragment);


    }

//...
}

Then in the fragment putting the listener when attach an calling it:

public class FirstPageFragment extends Fragment{


private ChangeFragmentListener changeFragmentListener;


//...
 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        changeFragmentListener = ((PagerContainerActivity) activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        changeFragmentListener = null;
    }
//...
//in the on click to change the fragment
changeFragmentListener.onChange(true);
//...
}

And finally the listener:

public interface changeFragmentListener {

    void onChange(boolean isNextFragment);

}

ProgressDialog in AsyncTask

A couple of days ago I found a very nice solution of this problem. Read about it here. In two words Mike created a AsyncTaskManager that mediates ProgressDialog and AsyncTask. It's very easy to use this solution. You just need to include in your project several interfaces and several classes and in your activity write some simple code and nest your new AsyncTask from BaseTask. I also advice you to read comments because there are some useful tips.

What is the technology behind wechat, whatsapp and other messenger apps?

The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.

Here is the general explanation from the link

  • WhatsApp server is almost completely implemented in Erlang.

  • Server systems that do the backend message routing are done in Erlang.

  • Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.

  • Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.

  • WhatsApp server has started from ejabberd

  • Ejabberd is a famous open source Jabber server written in Erlang.

  • Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.

  • The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.

  • To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.

  • A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.

  • Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).

  • Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.

  • What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message

  • How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.

How can I rebuild indexes and update stats in MySQL innoDB?

Why? One almost never needs to update the statistics. Rebuilding an index is even more rarely needed.

OPTIMIZE TABLE tbl; will rebuild the indexes and do ANALYZE; it takes time.

ANALYZE TABLE tbl; is fast for InnoDB to rebuild the stats. With 5.6.6 it is even less needed.

How to set underline text on textview?

Need not to use HTML properties, let's focus on java xD I had the same problem, i found the way to do it in java:

String text="Hide post";
TextView tvHide=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(text);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
tvHide.setText(spanString );

css divide width 100% to 3 column

How about using the CSS3 flex model:

HTML Code:

<div id="wrapper">
    <div id="c1">c1</div>
    <div id="c2">c2</div>
    <div id="c3">c3</div>
</div>  

CSS Code:

*{
    margin:0;
    padding:0;
}

#wrapper{
    display:-webkit-flex;
    -webkit-justify-content:center;

    display:flex;
    justify-content:center;

}

#wrapper div{
    -webkit-flex:1;
    flex:1;
    border:thin solid #777;

}

Understanding the set() function

Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.

Here's an example of a set changing order after a lot of values are added and then removed:

>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
    s.remove(v)
>>> print(s)
{1, 6, 8}

This is implementation dependent though, and so you should not rely upon it.

Laravel 5.2 redirect back with success message

You can simply use back() function to redirect no need to use redirect()->back() make sure you are using 5.2 or greater than 5.2 version.

You can replace your code to below code.

return back()->with('message', 'WORKS!');

In the view file replace below code.

@if(session()->has('message'))
    <div class="alert alert-success">
        {{ session()->get('message') }}
    </div>
@endif

For more detail, you can read here

back() is just a helper function. It's doing the same thing as redirect()->back()

Compute elapsed time

var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;
};

StopWatch.prototype.currentTime = function () {
    return this.performance ? window.performance.now() : new Date().getTime();
};

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;
};

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;
};

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();
    }

    return this.stopTime - this.startTime;
};

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;
};

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};

Benchmark

var stopwatch = new StopWatch();
stopwatch.start();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');
}

stopwatch.stop();

stopwatch.printElapsed();

Output

Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]

performance.now() is optional - just pass false into StopWatch constructor function.

onclick="javascript:history.go(-1)" not working in Chrome

Try this dude,

<button onclick="goBack()">Go Back 2 Pages</button>
<script>
  function goBack() {
    window.history.go(-2);
  }
</script>

Convert unix time stamp to date in java

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)

How to determine if object is in array

I used underscore javascript library to tweak this issue.

function containsObject(obj, list) {
 var res = _.find(list, function(val){ return _.isEqual(obj, val)});
 return (_.isObject(res))? true:false;
}

please refer to underscore.js documentation for the underscore functions used in the above example.

note: This is not a pure javascript solution. Shared for educational purposes.

Kubernetes how to make Deployment to update image

UPDATE 2019-06-24

Based on the @Jodiug comment if you have a 1.15 version you can use the command:

kubectl rollout restart deployment/demo

Read more on the issue:

https://github.com/kubernetes/kubernetes/issues/13488


Well there is an interesting discussion about this subject on the kubernetes GitHub project. See the issue: https://github.com/kubernetes/kubernetes/issues/33664

From the solutions described there, I would suggest one of two.

First

1.Prepare deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: demo
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
      - name: demo
        image: registry.example.com/apps/demo:master
        imagePullPolicy: Always
        env:
        - name: FOR_GODS_SAKE_PLEASE_REDEPLOY
          value: 'THIS_STRING_IS_REPLACED_DURING_BUILD'

2.Deploy

sed -ie "s/THIS_STRING_IS_REPLACED_DURING_BUILD/$(date)/g" deployment.yml
kubectl apply -f deployment.yml

Second (one liner):

kubectl patch deployment web -p \
  "{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"

Of course the imagePullPolicy: Always is required on both cases.

React: Expected an assignment or function call and instead saw an expression

Expected an assignment or function call and instead saw an expression.

I had this similar error with this code:

const mapStateToProps = (state) => {
    players: state
}

To correct all I needed to do was add parenthesis around the curved brackets

const mapStateToProps = (state) => ({
    players: state
});

Checking if a field contains a string

ideal answer its use index i option for case-insensitive

db.users.findOne({"username" : new RegExp(search_value, 'i') });

Find integer index of rows with NaN in pandas dataframe

And just in case, if you want to find the coordinates of 'nan' for all the columns instead (supposing they are all numericals), here you go:

df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])

df
   0  1  2    3    4  5
0  0  1  3  4.0  NaN  2
1  3  5  6  NaN  3.0  3

np.where(np.asanyarray(np.isnan(df)))
(array([0, 1]), array([4, 3]))

Compare object instances for equality by their attributes

If you want to get an attribute-by-attribute comparison, and see if and where it fails, you can use the following list comprehension:

[i for i,j in 
 zip([getattr(obj_1, attr) for attr in dir(obj_1)],
     [getattr(obj_2, attr) for attr in dir(obj_2)]) 
 if not i==j]

The extra advantage here is that you can squeeze it one line and enter in the "Evaluate Expression" window when debugging in PyCharm.

How to indent HTML tags in Notepad++

On Notepadd++ v7.5.9 (32-bits), "Indent by fold" plugin is working fine with html content.

  1. Search and install in plugin manager
  2. Use "Plugins" > "Indent by fold" > "Reindent file"

https://www.fesevur.com/indentbyfold/

In Tkinter is there any way to make a widget not visible?

One option, as explained in another answer, is to use pack_forget or grid_forget. Another option is to use lift and lower. This changes the stacking order of widgets. The net effect is that you can hide widgets behind sibling widgets (or descendants of siblings). When you want them to be visible you lift them, and when you want them to be invisible you lower them.

The advantage (or disadvantage...) is that they still take up space in their master. If you "forget" a widget, the other widgets might readjust their size or orientation, but if you raise or lower them they will not.

Here is a simple example:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.frame = tk.Frame(self)
        self.frame.pack(side="top", fill="both", expand=True)
        self.label = tk.Label(self, text="Hello, world")
        button1 = tk.Button(self, text="Click to hide label",
                           command=self.hide_label)
        button2 = tk.Button(self, text="Click to show label",
                            command=self.show_label)
        self.label.pack(in_=self.frame)
        button1.pack(in_=self.frame)
        button2.pack(in_=self.frame)

    def show_label(self, event=None):
        self.label.lift(self.frame)

    def hide_label(self, event=None):
        self.label.lower(self.frame)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Changing the default icon in a Windows Forms application

The icons you are seeing on desktop is not a icon file. They are either executable files .exe or shortcuts of any application .lnk. So can only set icon which have .ico extension.

Go to Project Menu -> Your_Project_Name Properties -> Application TAB -> Resources -> Icon

browse for your Icon, remember it must have .ico extension

You can make your icon in Visual Studio

Go to Project Menu -> Add New Item -> Icon File

Really killing a process in Windows

When ntsd access is denied, try:

ZeroWave was designed to be a simple tool that will provide a multilevel termination of any kind of process.

ZeroWave is also a easy-to-use program due to its simple installation and its very friendly graphical interface.

ZeroWave has three termination modes and with the "INSANE" mode can terminate any kind of process that can run on Windows.

It seems that ZeroWave can't kill avp.exe

How to add minutes to current time in swift

You can use in swift 4 or 5

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let current_date_time = dateFormatter.string(from: date)
    print("before add time-->",current_date_time)

    //adding 5 miniuts
    let addminutes = date.addingTimeInterval(5*60)
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let after_add_time = dateFormatter.string(from: addminutes)
    print("after add time-->",after_add_time)

output:

before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15

URL.Action() including route values

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

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

If you are using PHP 5.6 with Guzzle, Guzzle has switched to using the PHP libraries autodetect for certificates rather than it's process (ref). PHP outlines the changes here.

Finding out Where PHP/Guzzle is Looking for Certificates

You can dump where PHP is looking using the following PHP command:

 var_dump(openssl_get_cert_locations());

Getting a Certificate Bundle

For OS X testing, you can use homebrew to install openssl brew install openssl and then use openssl.cafile=/usr/local/etc/openssl/cert.pem in your php.ini or Zend Server settings (under OpenSSL).

A certificate bundle is also available from curl/Mozilla on the curl website: https://curl.haxx.se/docs/caextract.html

Telling PHP Where the Certificates Are

Once you have a bundle, either place it where PHP is already looking (which you found out above) or update openssl.cafile in php.ini. (Generally, /etc/php.ini or /etc/php/7.0/cli/php.ini or /etc/php/php.ini on Unix.)

Create hyperlink to another sheet

This macro adds a hyperlink to the worksheet with the same name, I also modify the range to be more flexible, just change the first cell in the code. Works like a charm

Sub hyper()
 Dim cl As Range
 Dim nS As String

 Set MyRange = Sheets("Sheet1").Range("B16")
 Set MyRange = Range(MyRange, MyRange.End(xlDown))

 For Each cl In MyRange
  nS = cl.Value
  cl.Hyperlinks.Add Anchor:=cl, Address:="", SubAddress:="'" & nS & "'" & "!B16", TextToDisplay:=nS
 Next
End Sub

Extracting specific columns from a data frame

There are two obvious choices: Joshua Ulrich's df[,c("A","B","E")] or

df[,c(1,2,5)]

as in

> df <- data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,7),E=c(8,8),F=c(9,9)) 
> df
  A B C D E F
1 1 3 5 7 8 9
2 2 4 6 7 8 9
> df[,c(1,2,5)]
  A B E
1 1 3 8
2 2 4 8
> df[,c("A","B","E")]
  A B E
1 1 3 8
2 2 4 8

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

How do I change db schema to dbo

ALTER SCHEMA dbo TRANSFER jonathan.MovieData;

See ALTER SCHEMA.

Generalized Syntax:

ALTER SCHEMA TargetSchema TRANSFER SourceSchema.TableName; 

Remove background drawable programmatically in Android

Try this

RelativeLayout relative = (RelativeLayout) findViewById(R.id.widget29);
relative.setBackgroundResource(0);

Check the setBackground functions in the RelativeLayout documentation