Programs & Examples On #Dynamic html

How do you remove all the options of a select box and then add one option and select it with jQuery?

How about just changing the html to new data.

$('#mySelect').html('<option value="whatever">text</option>');

Another example:

$('#mySelect').html('
    <option value="1" selected>text1</option>
    <option value="2">text2</option>
    <option value="3" disabled>text3</option>
');

Save a file in json format using Notepad++

enter image description hereSave the file as *.txt and then rename the file and change the file extension to json

How can I replace non-printable Unicode characters in Java?

my_string.replaceAll("\\p{C}", "?");

See more about Unicode regex. java.util.regexPattern/String.replaceAll supports them.

What causes javac to issue the "uses unchecked or unsafe operations" warning

You can keep it in the generic form and write it as:

// list 2 is made generic and can store any type of Object
        ArrayList<Object> list2 = new ArrayList<Object>();

Setting type of ArrayList as Object gives us the advantage to store any type of data. You don't need to use -Xlint or anything else.

Count indexes using "for" in Python

This?

for i in range(0,5): 
 print(i)

Are HTTP headers case-sensitive?

Header names are not case sensitive.

From RFC 2616 - "Hypertext Transfer Protocol -- HTTP/1.1", Section 4.2, "Message Headers":

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

The updating RFC 7230 does not list any changes from RFC 2616 at this part.

Is there a method to generate a UUID with go language

There is an official implementation by Google: https://github.com/google/uuid

Generating a version 4 UUID works like this:

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    id := uuid.New()
    fmt.Println(id.String())
}

Try it here: https://play.golang.org/p/6YPi1djUMj9

What's the difference between abstraction and encapsulation?

Abstraction has to do with separating interface from implementation. (We don't care what it is, we care that it works a certain way.)

Encapsulation has to do with disallowing access to or knowledge of internal structures of an implementation. (We don't care or need to see how it works, only that it does.)

Some people do use encapsulation as a synonym for abstraction, which is (IMO) incorrect. It's possible that your interviewer thought this. If that is the case then you were each talking about two different things when you referred to "encapsulation."


It's worth noting that these concepts are represented differently in different programming languages. A few examples:

  • In Java and C#, interfaces (and, to some degree, abstract classes) provide abstraction, while access modifiers provide encapsulation.
  • It's mostly the same deal in C++, except that we don't have interfaces, we only have abstract classes.
  • In JavaScript, duck typing provides abstraction, and closure provides encapsulation. (Naming convention can also provide encapsulation, but this only works if all parties agree to follow it.)

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

TRY THIS:

Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

SELECT DATEADD(dd, -30, 
       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

Laravel redirect back to original destination after login

For laravel 5.* try these.

return redirect()->intended('/');

or

return Redirect::intended('/');

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

scp files from local to remote machine error: no such file or directory

Be sure the folder from where you send the file does not contain space !

I was trying to send a file to a remote server from my windows machine from VS code terminal, and I got this error even if the file was here.

It's because the folder where the file was contained space in its name...

Is it possible to simulate key press events programmatically?

In some cases keypress event can't provide required funtionality. From mozilla docs we can see that the feature is deprecated:

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

So, since the keypress event is combined from the two consequently fired events keydown, and the following it keyup for the same key, just generate the events one-by-one:

element.dispatchEvent(new KeyboardEvent('keydown',{'key':'Shift'}));
element.dispatchEvent(new KeyboardEvent('keyup',{'key':'Shift'}));

Why functional languages?

Functional programming has been around for a long time, since LISP was one of the earliest languages to have a compiler, and since MIT's LISP machines. It's not a new paradigm (OO is much newer) but the dominant software platforms have tended to be written in languages that translate easily to assembly language, and their APIs heavily favor imperative code (UNIX with C, Windows with C, and Macintosh with Pascal and later C).

I think the new innovation in the last few years is for a diversity of APIs to catch on, particularly for things like web development where the platform APIs are irrelevant. Since you're not coding directly to the Win32 API or the POSIX API, that gives people the freedom to try out functional languages.

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

Excel: VLOOKUP that returns true or false?

Just use a COUNTIF ! Much faster to write and calculate than the other suggestions.


EDIT:

Say you cell A1 should be 1 if the value of B1 is found in column C and otherwise it should be 2. How would you do that?

I would say if the value of B1 is found in column C, then A1 will be positive, otherwise it will be 0. Thats easily done with formula: =COUNTIF($C$1:$C$15,B1), which means: count the cells in range C1:C15 which are equal to B1.

You can combine COUNTIF with VLOOKUP and IF, and that's MUCH faster than using 2 lookups + ISNA. IF(COUNTIF(..)>0,LOOKUP(..),"Not found")

A bit of Googling will bring you tons of examples.

WPF loading spinner

With Images

Visual summary of options for spinning icons. Recorded using Screen To Gif.


Font-Awesome-WPF

Documentation on GitHub.

Install via NuGet:

PM> Install-Package FontAwesome.WPF

Looks like this:

XAML:

<fa:ImageAwesome Icon="Spinner" Spin="True" SpinDuration="4" />

Icons pictured are Spinner, CircleOutlineNotch, Refresh and Cog. There are many others.


Method from @HAdes

XAML copy/paste.

open existing java project in eclipse

The typical pattern is to check out the root project folder (=the one containing a file called ".project") from SVN using eclipse's svn integration (SVN repository exploring perspective). The project is then recognized automatically.

CSS rounded corners in IE8

PIE.htc worked for me great (http://css3pie.com/), but with one issue:

You should write absolute path to PIE.htc. It hasn't worked for me when I used relative path.

How to generate auto increment field in select query

here's for SQL server, Oracle, PostgreSQL which support window functions.

SELECT  ROW_NUMBER() OVER (ORDER BY first_name, last_name)  Sequence_no,
        first_name,
        last_name
FROM    tableName

How to properly seed random number generator

OK why so complex!

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed( time.Now().UnixNano())
    var bytes int

    for i:= 0 ; i < 10 ; i++{ 
        bytes = rand.Intn(6)+1
        fmt.Println(bytes)
        }
    //fmt.Println(time.Now().UnixNano())
}

This is based off the dystroy's code but fitted for my needs.

It's die six (rands ints 1 =< i =< 6)

func randomInt (min int , max int  ) int {
    var bytes int
    bytes = min + rand.Intn(max)
    return int(bytes)
}

The function above is the exactly same thing.

I hope this information was of use.

How to call a Web Service Method?

The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService" as the service reference name, that will generate the type TestUploaderWebService.Service1. That class will have a method named GetFileListOnWebServer, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:

string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
    proxy = new TestUploaderWebService.Service1();
    files = proxy.GetFileListOnWebServer();
    proxy.Close();
    success = true;
}
finally
{
    if (!success)
    {
        proxy.Abort();
    }
}

P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.

Best design for a changelog / auditing database table?

In the project I'm working on, audit log also started from the very minimalistic design, like the one you described:

event ID
event date/time
event type
user ID
description

The idea was the same: to keep things simple.

However, it quickly became obvious that this minimalistic design was not sufficient. The typical audit was boiling down to questions like this:

Who the heck created/updated/deleted a record 
with ID=X in the table Foo and when?

So, in order to be able to answer such questions quickly (using SQL), we ended up having two additional columns in the audit table

object type (or table name)
object ID

That's when design of our audit log really stabilized (for a few years now).

Of course, the last "improvement" would work only for tables that had surrogate keys. But guess what? All our tables that are worth auditing do have such a key!

How to remove docker completely from ubuntu 14.04

@miyuru. As suggested by him run all the steps.

Ubuntu version 16.04

Still when I ran docker --version it was returning a version. So to uninstall it completely

Again run the dpkg -l | grep -i docker which will list package still there in system.

For example:

ii  docker-ce-cli      5:19.03.6~3-0~ubuntu-xenial               
amd64        Docker CLI: the open-source application container engine

Now remove them as show below :

sudo apt-get purge -y docker-ce-cli

sudo apt-get autoremove -y --purge docker-ce-cli

sudo apt-get autoclean

Hope this will resolve it, as it did in my case.

How can I scroll a web page using selenium webdriver in python?

element=find_element_by_xpath("xpath of the li you are trying to access")

element.location_once_scrolled_into_view

this helped when I was trying to access a 'li' that was not visible.

UnicodeDecodeError when reading CSV file in Pandas with Python

Try specifying the engine='python'. It worked for me but I'm still trying to figure out why.

df = pd.read_csv(input_file_path,...engine='python')

How to import a module given its name as string?

Note: imp is deprecated since Python 3.4 in favor of importlib

As mentioned the imp module provides you loading functions:

imp.load_source(name, path)
imp.load_compiled(name, path)

I've used these before to perform something similar.

In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:

import imp
import os

def load_from_file(filepath):
    class_inst = None
    expected_class = 'MyClass'

    mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])

    if file_ext.lower() == '.py':
        py_mod = imp.load_source(mod_name, filepath)

    elif file_ext.lower() == '.pyc':
        py_mod = imp.load_compiled(mod_name, filepath)

    if hasattr(py_mod, expected_class):
        class_inst = getattr(py_mod, expected_class)()

    return class_inst

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

Get the current language in device

Answers above don't distinguish between simple chinese and traditinal chinese. Locale.getDefault().toString() works which returns "zh_CN", "zh_TW", "en_US" and etc.

References to : https://developer.android.com/reference/java/util/Locale.html, ISO 639-1 is OLD.

What is the difference between SQL and MySQL?

SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.

MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.

How to extract numbers from a string in Python?

I was looking for a solution to remove strings' masks, specifically from Brazilian phones numbers, this post not answered but inspired me. This is my solution:

>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Add an image in a WPF button

Please try the below XAML snippet:

<Button Width="300" Height="50">
  <StackPanel Orientation="Horizontal">
    <Image Source="Pictures/img.jpg" Width="20" Height="20"/>
    <TextBlock Text="Blablabla" VerticalAlignment="Center" />
  </StackPanel>
</Button>

In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.

Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));

StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);

Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);

Determine distance from the top of a div to top of window with javascript

This can be achieved purely with JavaScript.

I see the answer I wanted to write has been answered by lynx in comments to the question.

But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.

So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:

// Fetch the element
var el = document.getElementById("someElement");  

use getBoundingClientRect()

// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top; 

Thats it!

Hope this helps someone :)

RecyclerView onClick

Step 1 ) Write the click interface

Create an interface named RecyclerViewClickListener.java and add below code. Here we declare two methods onClick and onLongClick to identify item click and long click respectively.

package com.androidtutorialshub.recyclerviewtutorial.Helper;

import android.view.View;

public interface RecyclerViewClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}

Step 2 ) Write the Item Touch Class

Create a class named RecyclerViewTouchListener.java and add below code . Here we write the logic to detect click and long press on recycler view item .

package com.androidtutorialshub.recyclerviewtutorial.Helper;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;


public class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener{

    private GestureDetector gestureDetector;
    private RecyclerViewClickListener clickListener;

    public RecyclerViewTouchListener(Context context, final RecyclerView recyclerView, final RecyclerViewClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

Step 3 ) Defining click listener

Open MainActivity.java and update the below changes. Here onClick() method will detect click on item and onLongClick will detect long click on item.

recyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(getApplicationContext(), recyclerView, new RecyclerViewClickListener() {
            @Override
            public void onClick(View view, int position) {
                Toast.makeText(getApplicationContext(), bookList.get(position).getTitle() + " is clicked!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(View view, int position) {
                Toast.makeText(getApplicationContext(), bookList.get(position).getTitle() + " is long pressed!", Toast.LENGTH_SHORT).show();

            }
        }));

For more info or Download source code :- http://www.androidtutorialshub.com/android-recyclerview-click-listener-tutorial/

How to check for empty array in vba macro

Another method would be to do it sooner. You can create a Boolean variable and set it to true once you load data to the array. so all you really need is a simple if statement of when you load data into the array.

What is the path that Django uses for locating and loading templates?

I also had issues with this part of the tutorial (used tutorial for version 1.7).

My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.

This is the line from django/contrib/admin/templates/admin/base_site.html:

<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>

But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).

Example manual:

<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>

How to delete SQLite database from Android programmatically

From Application Manager, you can delete whole application with data. Or just data by it self. This includes database.

  1. Navigate to Settings. You can get to the settings menu either in your apps menu or, on most phones, by pulling down the notification drawer and tapping a button there.

  2. Select the Apps submenu. On some phones this menu will have a slightly different name such as Application Manager.

  3. Swipe right to the All apps list. Ignore the lists of Running and Downloaded apps. You want the All apps list.

  4. Select the app you wish to disable. A properties screen appears with a button for Force Stop on the upper left and another for either Disable or Uninstall updates on the upper right side.

  5. Delete data.

XML Schema (XSD) validation tool?

http://www.xmlvalidation.com/

(Be sure to check the " Validate against external XML schema" Box)

Select row on click react-table

Another mechanism for dynamic styling is to define it in the JSX for your component. For example, the following could be used to selectively style the current step in the React tic-tac-toe tutorial (one of the suggested extra credit enhancements:

  return (
    <li key={move}>
      <button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
    </li>
  );

Granted, a cleaner approach would be to add/remove a 'selected' CSS class but this direct approach might be helpful in some cases.

Sequelize.js delete query?

I've searched deep into the code, step by step into the following files:

https://github.com/sdepold/sequelize/blob/master/test/Model/destroy.js

https://github.com/sdepold/sequelize/blob/master/lib/model.js#L140

https://github.com/sdepold/sequelize/blob/master/lib/query-interface.js#L207-217

https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js

What I found:

There isn't a deleteAll method, there's a destroy() method you can call on a record, for example:

Project.find(123).on('success', function(project) {
  project.destroy().on('success', function(u) {
    if (u && u.deletedAt) {
      // successfully deleted the project
    }
  })
})

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Both awk and sed are plenty fast, but if you think it matters feel free to use one of the following:

If the characters that you want to delete are always at the end of the string

echo '1234567890  *' | tr -d ' *'

If they can appear anywhere within the string and you only want to delete those at the end

echo '1234567890  *' | rev | cut -c 4- | rev

The man pages of all the commands will explain what's going on.

I think you should use sed, though.

Fatal error: Call to undefined function sqlsrv_connect()

i have same this because in httpd.conf in apache PHPIniDir D:/wamp/bin/php/php5.5.12 that was incorrect

Sieve of Eratosthenes - Finding Primes Python

I figured it must be possible to simply use the empty list as the terminating condition for the loop and came up with this:

limit = 100
ints = list(range(2, limit))   # Will end up empty

while len(ints) > 0:
    prime = ints[0]
    print prime
    ints.remove(prime)
    i = 2
    multiple = prime * i
    while multiple <= limit:
        if multiple in ints:
            ints.remove(multiple)
        i += 1
        multiple = prime * i

Sending string via socket (python)

This piece of code is incorrect.

while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    r='REceieve'
    clientsocket.send(r.encode())

The call on accept() on the serversocket blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.

That's the reason the recv works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.

Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.

window.location.reload with clear cache

i had this problem and i solved it using javascript

 location.reload(true);

you may also use

window.history.forward(1);

to stop the browser back button after user logs out of the application.

Docker error : no space left on device

The current best practice is:

docker system prune

Note the output from this command prior to accepting the consequences:

WARNING! This will remove:
  - all stopped containers
  - all networks not used by at least one container
  - all dangling images
  - all dangling build cache

Are you sure you want to continue? [y/N]

In other words, continuing with this command is permanent. Keep in mind that best practice is to treat stopped containers as ephemeral i.e. you should be designing your work with Docker to not keep these stopped containers around. You may want to consider using the --rm flag at runtime if you are not actively debugging your containers.

Make sure you read this answer, re: Volumes

You may also be interested in this answer, if docker system prune does not work for you.

Create multiple threads and wait all of them to complete

Most proposed answers don't take into account a time-out interval, which is very important to prevent a possible deadlock. Next is my sample code. (Note that I'm primarily a Win32 developer, and that's how I'd do it there.)

//'arrRunningThreads' = List<Thread>

//Wait for all threads
const int knmsMaxWait = 3 * 1000;           //3 sec timeout
int nmsBeginTicks = Environment.TickCount;
foreach(Thread thrd in arrRunningThreads)
{
    //See time left
    int nmsElapsed = Environment.TickCount - nmsBeginTicks;
    int nmsRemain = knmsMaxWait - nmsElapsed;
    if(nmsRemain < 0)
        nmsRemain = 0;

    //Then wait for thread to exit
    if(!thrd.Join(nmsRemain))
    {
        //It didn't exit in time, terminate it
        thrd.Abort();

        //Issue a debugger warning
        Debug.Assert(false, "Terminated thread");
    }
}

Git: See my last commit

Use git show:

git show --summary

This will show the names of created or removed files, but not the names of changed files. The git show command supports a wide variety of output formats that show various types of information about commits.

Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

Hope it helps:)

Checking if a list is empty with LINQ

This extension method works for me:

public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
    try
    {
        enumerable.First();
        return false;
    }
    catch (InvalidOperationException)
    {
        return true;
    }
}

MySQL ORDER BY multiple column ASC and DESC

Ok, I THINK I understand what you want now, and let me clarify to confirm before the query. You want 1 record for each user. For each user, you want their BEST POINTS score record. Of the best points per user, you want the one with the best average time. Once you have all users "best" values, you want the final results sorted with best points first... Almost like ranking of a competition.

So now the query. If the above statement is accurate, you need to start with getting the best point/average time per person and assigning a "Rank" to that entry. This is easily done using MySQL @ variables. Then, just include a HAVING clause to only keep those records ranked 1 for each person. Finally apply the order by of best points and shortest average time.

select
      U.UserName,
      PreSortedPerUser.Point,
      PreSortedPerUser.Avg_Time,
      @UserRank := if( @lastUserID = PreSortedPerUser.User_ID, @UserRank +1, 1 ) FinalRank,
      @lastUserID := PreSortedPerUser.User_ID
   from
      ( select
              S.user_id,
              S.point,
              S.avg_time
           from
              Scores S
           order by
              S.user_id,
              S.point DESC,
              S.Avg_Time ) PreSortedPerUser
         JOIN Users U
            on PreSortedPerUser.user_ID = U.ID,
      ( select @lastUserID := 0,
               @UserRank := 0 ) sqlvars 
   having
      FinalRank = 1
   order by
      Point Desc,
      Avg_Time

Results as handled by SQLFiddle

Note, due to the inline @variables needed to get the answer, there are the two extra columns at the end of each row. These are just "left-over" and can be ignored in any actual output presentation you are trying to do... OR, you can wrap the entire thing above one more level to just get the few columns you want like

select 
      PQ.UserName,
      PQ.Point,
      PQ.Avg_Time
   from
      ( entire query above pasted here ) as PQ

Scatter plots in Pandas/Pyplot: How to plot by category

With plt.scatter, I can only think of one: to use a proxy artist:

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)

ccm=x.get_cmap()
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)]
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1)

And the result is:

enter image description here

Eclipse internal error while initializing Java tooling

In my case even after deleting the workspace and reimport doesn't work. Because all the files are Corrupted. so have utilized my existing backup data, extracted it & reimported into workspace then it started working fine.

Timeout for python requests.get entire response

UPDATE: https://requests.readthedocs.io/en/master/user/advanced/#timeouts

In new version of requests:

If you specify a single value for the timeout, like this:

r = requests.get('https://github.com', timeout=5)

The timeout value will be applied to both the connect and the read timeouts. Specify a tuple if you would like to set the values separately:

r = requests.get('https://github.com', timeout=(3.05, 27))

If the remote server is very slow, you can tell Requests to wait forever for a response, by passing None as a timeout value and then retrieving a cup of coffee.

r = requests.get('https://github.com', timeout=None)

My old (probably outdated) answer (which was posted long time ago):

There are other ways to overcome this problem:

1. Use the TimeoutSauce internal class

From: https://github.com/kennethreitz/requests/issues/1928#issuecomment-35811896

import requests from requests.adapters import TimeoutSauce

class MyTimeout(TimeoutSauce):
    def __init__(self, *args, **kwargs):
        connect = kwargs.get('connect', 5)
        read = kwargs.get('read', connect)
        super(MyTimeout, self).__init__(connect=connect, read=read)

requests.adapters.TimeoutSauce = MyTimeout

This code should cause us to set the read timeout as equal to the connect timeout, which is the timeout value you pass on your Session.get() call. (Note that I haven't actually tested this code, so it may need some quick debugging, I just wrote it straight into the GitHub window.)

2. Use a fork of requests from kevinburke: https://github.com/kevinburke/requests/tree/connect-timeout

From its documentation: https://github.com/kevinburke/requests/blob/connect-timeout/docs/user/advanced.rst

If you specify a single value for the timeout, like this:

r = requests.get('https://github.com', timeout=5)

The timeout value will be applied to both the connect and the read timeouts. Specify a tuple if you would like to set the values separately:

r = requests.get('https://github.com', timeout=(3.05, 27))

kevinburke has requested it to be merged into the main requests project, but it hasn't been accepted yet.

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

Where do alpha testers download Google Play Android apps?

  1. Publish your alpha apk by pressing the submit button.

  2. Wait until it's published.
    (e.g.: CURRENT APK published on Apr 28, 2015, 2:20:13AM)

  3. Select Alpha testers - click Manage list of testers.

  4. Share the link with your testers (by email).
    (e.g.: https://play.google.com/apps/testing/uk.co.xxxxx.xxxxx)

Difference between a SOAP message and a WSDL?

A SOAP document is sent per request. Say we were a book store, and had a remote server we queried to learn the current price of a particular book. Say we needed to pass the Book's title, number of pages and ISBN number to the server.

Whenever we wanted to know the price, we'd send a unique SOAP message. It'd look something like this;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPrice xmlns:m="http://namespaces.my-example-book-info.com">
      <ISBN>978-0451524935</ISBN>
      <Title>1984</Title>
      <NumPages>328</NumPages>
    </m:GetBookPrice>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope> 

And we expect to get a SOAP response message back like;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPriceResponse xmlns:m="http://namespaces.my-example-book-info.com">
      <CurrentPrice>8.99</CurrentPrice>
      <Currency>USD</Currency>
    </m:GetBookPriceResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The WSDL then describes how to handle/process this message when a server receives it. In our case, it describes what types the Title, NumPages & ISBN would be, whether we should expect a response from the GetBookPrice message and what that response should look like.

The types would look like this;

<wsdl:types>

  <!-- all type declarations are in a chunk of xsd -->
  <xsd:schema targetNamespace="http://namespaces.my-example-book-info.com"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">

    <xsd:element name="GetBookPrice">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="ISBN" type="string"/>
          <xsd:element name="Title" type="string"/>
          <xsd:element name="NumPages" type="integer"/>
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

    <xsd:element name="GetBookPriceResponse">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="CurrentPrice" type="decimal" />
          <xsd:element name="Currency" type="string" />
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

  </xsd:schema>
</wsdl:types>

But the WSDL also contains more information, about which functions link together to make operations, and what operations are avaliable in the service, and whereabouts on a network you can access the service/operations.

See also W3 Annotated WSDL Examples

Stop node.js program from command line

I'm adding this answer because for many projects with production deployments, we have scripts that stop these processes so we don't have to.

A clean way to manage your Node Server processes is using the forever package (from NPM).

Example:

Install Forever

npm install forever -g

Run Node Server

forever start -al ./logs/forever.log -ao ./logs/out.log -ae ./logs/err.log server.js

Result:

info: Forever processing file: server.js

Shutdown Node Server

forever stop server.js

Result

info: Forever stopped process: uid command script forever pid id logfile uptime [0] sBSj "/usr/bin/nodejs/node" ~/path/to/your/project/server.js 23084 13176 ~/.forever/forever.log 0:0:0:0.247

This will cleanly shutdown your Server application.

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

see NSURLError.h Define

NSURLErrorUnknown =             -1,
NSURLErrorCancelled =           -999,
NSURLErrorBadURL =              -1000,
NSURLErrorTimedOut =            -1001,
NSURLErrorUnsupportedURL =          -1002,
NSURLErrorCannotFindHost =          -1003,
NSURLErrorCannotConnectToHost =         -1004,
NSURLErrorNetworkConnectionLost =       -1005,
NSURLErrorDNSLookupFailed =         -1006,
NSURLErrorHTTPTooManyRedirects =        -1007,
NSURLErrorResourceUnavailable =         -1008,
NSURLErrorNotConnectedToInternet =      -1009,
NSURLErrorRedirectToNonExistentLocation =   -1010,
NSURLErrorBadServerResponse =       -1011,
NSURLErrorUserCancelledAuthentication =     -1012,
NSURLErrorUserAuthenticationRequired =  -1013,
NSURLErrorZeroByteResource =        -1014,
NSURLErrorCannotDecodeRawData =             -1015,
NSURLErrorCannotDecodeContentData =         -1016,
NSURLErrorCannotParseResponse =             -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist =        -1100,
NSURLErrorFileIsDirectory =         -1101,
NSURLErrorNoPermissionsToReadFile =     -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

// SSL errors
NSURLErrorSecureConnectionFailed =      -1200,
NSURLErrorServerCertificateHasBadDate =     -1201,
NSURLErrorServerCertificateUntrusted =  -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid =    -1204,
NSURLErrorClientCertificateRejected =   -1205,
NSURLErrorClientCertificateRequired =   -1206,
NSURLErrorCannotLoadFromNetwork =       -2000,

// Download and file I/O errors
NSURLErrorCannotCreateFile =        -3000,
NSURLErrorCannotOpenFile =          -3001,
NSURLErrorCannotCloseFile =         -3002,
NSURLErrorCannotWriteToFile =       -3003,
NSURLErrorCannotRemoveFile =        -3004,
NSURLErrorCannotMoveFile =          -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,

NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,

Could not find any resources appropriate for the specified culture or the neutral culture

Just another case. I copied a solution with two projects and renamed them partially in the Windows explorer (folder names, .sln and .csproj file names) and partially with a massive Find & Replace action in Visual Studio (namespaces etc.). Nevertheless the exception stated by the OP still occurred. I found out that the Assembly and Namespace names were still old.

Although the project and everything else was already named OfficeStyle the Assembly name and Default namespace were still named Linckus.

Old situation

After this correction everything worked fine again, compile and run time :)

New situation

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

In my case problem was when i added com.fasterxml.jackson.dataformat i put the version 2.11.0.

While all other Jackson dependencies were 2.8.0 and one of them was 2.11.0 and changing all to be 2.8.0 fixed it.

FYI, 2.11 is the latest but due to my legacy code, i kept it as 2.8 as well.

Before Fix [ERROR]

com.fasterxml.jackson.dataformat version is 2.11.0    
com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.11.0
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

After Fix [WORKED] com.fasterxml.jackson.dataformat version is 2.8.0

com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.8.0
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

Spring Boot application as a Service

Are you using Maven? Then you should try the AppAssembler Plugin:

The Application Assembler Plugin is a Maven plugin for generating scripts for starting java applications. ... All artifacts (dependencies + the artifact from the project) are added to the classpath in the generated bin scripts.

Supported platforms:

Unix-variants

Windows NT (Windows 9x is NOT supported)

Java Service Wrapper (JSW)

See: http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/index.html

How to detect if a stored procedure already exists

I have a stored proc that allows the customer to extend validation, if it exists I do not want to change it, if it doesn't I want to create it, the best way I have found:

IF OBJECT_ID('ValidateRequestPost') IS NULL
BEGIN
    EXEC ('CREATE PROCEDURE ValidateRequestPost 
    @RequestNo VARCHAR(30),
    @ErrorStates VARCHAR(255) OUTPUT
AS
BEGIN
    SELECT @ErrorStates = @ErrorStates
END')
END

Microsoft.Office.Core Reference Missing

None of the above answer helped me, i was using Visual Studio 2017. What I did is, installed Office/SharePoint Development using Visual Studio Installer.

enter image description here

After that, I was able to see 'office', this assembly contains Microsoft.Office.Core.

enter image description here

Hope this helps you.

Print Currency Number Format in PHP

The easiest answer is number_format().

echo "$ ".number_format($value, 2);

If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00 for some of us Europeans for example), it becomes a bit more complex.

There is money_format() but it doesn't work on Windows and relies on setlocale(), which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.

If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.

Java Compare Two List's object values?

You can subtract one list from the other using CollectionUtils.subtract, if the result is an empty collection, it means both lists are the same. Another approach is using CollectionUtils.isSubCollection or CollectionUtils.isProperSubCollection.

For any case you should implement equals and hashCode methods for your object.

printf and long double

If you are using MinGW, the problem is that by default, MinGW uses the I/O resp. formatting functions from the Microsoft C runtime, which doesn't support 80 bit floating point numbers (long double == double in Microsoft land).

However, MinGW also comes with a set of alternative implementations that do properly support long doubles. To use them, prefix the function names with __mingw_ (e.g. __mingw_printf). Depending on the nature of your project, you might also want to globally #define printf __mingw_printf or use -D__USE_MINGW_ANSI_STDIO (which enables the MinGW versions of all the printf-family functions).

Relative Paths in Javascript in an external file

get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:

var jsFileLocation = $('script[src*=example]').attr('src');  // the js file path
jsFileLocation = jsFileLocation.replace('example.js', '');   // the js folder path

(assuming your javascript file is named 'example.js')

Excel function to make SQL-like queries on worksheet data?

You can use Get External Data (dispite its name), located in the 'Data' tab of Excel 2010, to set up a connection in a workbook to query data from itself. Use From Other Sources From Microsoft Query to connect to Excel

Once set up you can use VBA to manipulate the connection to, among other thing, view and modify the SQL command that drives the query. This query does reference the in memory workbook, so doen't require a save to refresh the latest data.

Here's a quick Sub to demonstrate accessing the connection objects

Sub DemoConnection()
    Dim c As Connections
    Dim wb As Workbook
    Dim i As Long
    Dim strSQL As String

    Set wb = ActiveWorkbook
    Set c = wb.Connections
    For i = 1 To c.Count
        ' Reresh the data
        c(i).Refresh 
        ' view the SQL query
        strSQL = c(i).ODBCConnection.CommandText
        MsgBox strSQL
    Next
End Sub

Linq to SQL .Sum() without group ... into

Try:

itemsCard.ToList().Select(c=>c.Price).Sum();

Actually this would perform better:

var itemsInCart = from o in db.OrderLineItems
              where o.OrderId == currentOrder.OrderId
              select new { o.WishListItem.Price };
var sum = itemsCard.ToList().Select(c=>c.Price).Sum();

Because you'll only be retrieving one column from the database.

How do I load a file from resource folder?

this.getClass().getClassLoader().getResource("filename").getPath()

Best way to check if column returns a null value (from database to .net application)

Just use DataRow.IsNull. It has overrides accepting a column index, a column name, or a DataColumn object as parameters.

Example using the column index:

if (table.rows[0].IsNull(0))
{
    //Whatever I want to do
}

And although the function is called IsNull it really compares with DbNull (which is exactly what you need).


What if I want to check for DbNull but I don't have a DataRow? Use Convert.IsDBNull.

Resize image proportionally with CSS?

We can resize image using CSS in the browser using media queries and the principle of responsive design.

    @media screen and (orientation: portrait) {
img.ri {
    max-width: 80%;
  }
}

_x000D_
_x000D_
@media screen and (orientation: landscape) {_x000D_
  img.ri { max-height: 80%; }_x000D_
}
_x000D_
_x000D_
_x000D_

ASP.NET MVC Razor render without encoding

As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.

For example, if your view model was:

public class SampleViewModel
{
  public string SampleString { get; set; }
  public MvcHtmlString SampleHtmlString { get; set; }
}

For Core 1.0+ (and MVC 5+) use HtmlString

public class SampleViewModel
{
  public string SampleString { get; set; }
  public HtmlString SampleHtmlString { get; set; }
}

then

<!-- this will be encoded -->
<div>@Model.SampleString</div>
<!-- this will not be encoded -->
<div>@Html.Raw(Model.SampleString)</div>
<!-- this will not be encoded either -->
<div>@Model.SampleHtmlString</div>

Angular 4 img src is not found

An important observation on how Angular 2, 2+ attribute bindings work.

The issue with [src]="imagePath" not working while the following do:

  • <img src="img/myimage.png">
  • <img src={{imagePath}}>

Is due your binding declaration, [src]="imagePath" is directly binded to Component's this.imagePath or if it's part of an ngFor loop, then *each.imagePath.

However, on the other two working options, you're either binding a string on HTML or allowing HTML to be binded to a variable that's yet to be defined.

HTML will not throw any error if you bind <img src=garbage*Th_i$.ngs>, however Angular will.

My recommendation is to use an inline-if in case the variable might not be defined, such as <img [src]="!!imagePath ? imagePath : 'urlString'">, which can be though of as node.src = imagePath ? imagePath : 'something'.

Avoid binding to possible missing variables or make good use of *ngIf in that element.

What is HEAD in Git?

Take a look at Creating and playing with branches

HEAD is actually a file whose contents determines where the HEAD variable refers:

$ cat .git/HEAD
ref: refs/heads/master
$ cat .git/refs/heads/master
35ede5c916f88d8ba5a9dd6afd69fcaf773f70ed

In this repository, the contents of the HEAD file refers to a second file named refs/heads/master. The file refs/heads/master contains the hash of the most recent commit on the master branch.

The result is HEAD points to the master branch commit from the .git/refs/heads/master file.

enter image description here

SQLAlchemy: What's the difference between flush() and commit()?

commit () records these changes in the database. flush () is always called as part of the commit () (1) call. When you use a Session object to query a database, the query returns results from both the database and the reddened parts of the unrecorded transaction it is performing.

What is the difference between .*? and .* regular expressions?

On greedy vs non-greedy

Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.

The ? as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.

References


Example 1: From A to Z

Let's compare these two patterns: A.*Z and A.*?Z.

Given the following input:

eeeAiiZuuuuAoooZeeee

The patterns yield the following matches:

Let's first focus on what A.*Z does. When it matched the first A, the .*, being greedy, first tries to match as many . as possible.

eeeAiiZuuuuAoooZeeee
   \_______________/
    A.* matched, Z can't match

Since the Z doesn't match, the engine backtracks, and .* must then match one fewer .:

eeeAiiZuuuuAoooZeeee
   \______________/
    A.* matched, Z still can't match

This happens a few more times, until finally we come to this:

eeeAiiZuuuuAoooZeeee
   \__________/
    A.* matched, Z can now match

Now Z can match, so the overall pattern matches:

eeeAiiZuuuuAoooZeeee
   \___________/
    A.*Z matched

By contrast, the reluctant repetition in A.*?Z first matches as few . as possible, and then taking more . as necessary. This explains why it finds two matches in the input.

Here's a visual representation of what the two patterns matched:

eeeAiiZuuuuAoooZeeee
   \__/r   \___/r      r = reluctant
    \____g____/        g = greedy

Example: An alternative

In many applications, the two matches in the above input is what is desired, thus a reluctant .*? is used instead of the greedy .* to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.

The pattern A[^Z]*Z also finds the same two matches as the A.*?Z pattern for the above input (as seen on ideone.com). [^Z] is what is called a negated character class: it matches anything but Z.

The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.

References


Example 2: From A to ZZ

This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.

eeAiiZooAuuZZeeeZZfff

These are the matches for the above input:

Here's a visual representation of what they matched:

         ___n
        /   \              n = negated character class
eeAiiZooAuuZZeeeZZfff      r = reluctant
  \_________/r   /         g = greedy
   \____________/g

Related topics

These are links to questions and answers on stackoverflow that cover some topics that may be of interest.

One greedy repetition can outgreed another

How to efficiently count the number of keys/properties of an object in JavaScript?

I'm not aware of any way to do this, however to keep the iterations to a minimum, you could try checking for the existance of __count__ and if it doesn't exist (ie not Firefox) then you could iterate over the object and define it for later use eg:

if (myobj.__count__ === undefined) {
  myobj.__count__ = ...
}

This way any browser supporting __count__ would use that, and iterations would only be carried out for those which don't. If the count changes and you can't do this, you could always make it a function:

if (myobj.__count__ === undefined) {
  myobj.__count__ = function() { return ... }
  myobj.__count__.toString = function() { return this(); }
}

This way anytime you reference myobj.__count__ the function will fire and recalculate.

What is the difference between a .cpp file and a .h file?

.h files, or header files, are used to list the publicly accessible instance variables and and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.

The reason they are separate is because .h files aren't compiled into binary code while .cpp files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.

Disable submit button ONLY after submit

I put this in my global code to work on all submit buttons:

$("input[type='submit']").on("click", function (e) {
    $(this).attr("disabled", true);
    $(this).closest("form").submit()
});

Use cases for the 'setdefault' dict method

The different use case for setdefault() is when you don't want to overwrite the value of an already set key. defaultdict overwrites, while setdefault() does not. For nested dictionaries it is more often the case that you want to set a default only if the key is not set yet, because you don't want to remove the present sub dictionary. This is when you use setdefault().

Example with defaultdict:

>>> from collection import defaultdict()
>>> foo = defaultdict()
>>> foo['a'] = 4
>>> foo['a'] = 2
>>> print(foo)
defaultdict(None, {'a': 2})

setdefault doesn't overwrite:

>>> bar = dict()
>>> bar.setdefault('a', 4)
>>> bar.setdefault('a', 2)
>>> print(bar)
{'a': 4}

ModuleNotFoundError: What does it mean __main__ is not a package?

The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue

Simple bubble sort c#

No, your algorithm works but your Write operation is misplaced within the outer loop.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();

How can I print the contents of an array horizontally?

namespace ReverseString
{
    class Program
    {
        static void Main(string[] args)
        {
            string stat = "This is an example of code" +
                          "This code has written in C#\n\n";

            Console.Write(stat);

            char[] myArrayofChar = stat.ToCharArray();

            Array.Reverse(myArrayofChar);

            foreach (char myNewChar in myArrayofChar)
                Console.Write(myNewChar); // You just need to write the function
                                          // Write instead of WriteLine
            Console.ReadKey();
        }
    }
}

This is the output:

#C ni nettirw sah edoc sihTedoc fo elpmaxe na si sihT

Get total size of file in bytes

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

Laravel Eloquent update just if changes have been made

I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id) function:

$post = Post::find($id);    
$post->fill($request->input())->save();

keep in mind that you have to name your inputs with the same column name. The fill() function will do all the work for you :)

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

Transfer data from one HTML file to another

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

Setting background colour of Android layout element

You can use android:background="#DC143C", or any other RGB values for your color. I have no problem using it this way, as stated here

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

A top-like utility for monitoring CUDA activity on a GPU

Another useful monitoring approach is to use ps filtered on processes that consume your GPUs. I use this one a lot:

ps f -o user,pgrp,pid,pcpu,pmem,start,time,command -p `lsof -n -w -t /dev/nvidia*`

That'll show all nvidia GPU-utilizing processes and some stats about them. lsof ... retrieves a list of all processes using an nvidia GPU owned by the current user, and ps -p ... shows ps results for those processes. ps f shows nice formatting for child/parent process relationships / hierarchies, and -o specifies a custom formatting. That one is similar to just doing ps u but adds the process group ID and removes some other fields.

One advantage of this over nvidia-smi is that it'll show process forks as well as main processes that use the GPU.

One disadvantage, though, is it's limited to processes owned by the user that executes the command. To open it up to all processes owned by any user, I add a sudo before the lsof.

Lastly, I combine it with watch to get a continuous update. So, in the end, it looks like:

watch -n 0.1 'ps f -o user,pgrp,pid,pcpu,pmem,start,time,command -p `sudo lsof -n -w -t /dev/nvidia*`'

Which has output like:

Every 0.1s: ps f -o user,pgrp,pid,pcpu,pmem,start,time,command -p `sudo lsof -n -w -t /dev/nvi...  Mon Jun  6 14:03:20 2016
USER      PGRP   PID %CPU %MEM  STARTED     TIME COMMAND
grisait+ 27294 50934  0.0  0.1   Jun 02 00:01:40 /opt/google/chrome/chrome --type=gpu-process --channel=50877.0.2015482623
grisait+ 27294 50941  0.0  0.0   Jun 02 00:00:00  \_ /opt/google/chrome/chrome --type=gpu-broker
grisait+ 53596 53596 36.6  1.1 13:47:06 00:05:57 python -u process_examples.py
grisait+ 53596 33428  6.9  0.5 14:02:09 00:00:04  \_ python -u process_examples.py
grisait+ 53596 33773  7.5  0.5 14:02:19 00:00:04  \_ python -u process_examples.py
grisait+ 53596 34174  5.0  0.5 14:02:30 00:00:02  \_ python -u process_examples.py
grisait+ 28205 28205  905  1.5 13:30:39 04:56:09 python -u train.py
grisait+ 28205 28387  5.8  0.4 13:30:49 00:01:53  \_ python -u train.py
grisait+ 28205 28388  5.3  0.4 13:30:49 00:01:45  \_ python -u train.py
grisait+ 28205 28389  4.5  0.4 13:30:49 00:01:29  \_ python -u train.py
grisait+ 28205 28390  4.5  0.4 13:30:49 00:01:28  \_ python -u train.py
grisait+ 28205 28391  4.8  0.4 13:30:49 00:01:34  \_ python -u train.py

How to un-commit last un-pushed git commit without losing the changes

With me mostly it happens when I push changes to the wrong branch and realize later. And following works in most of the time.

git revert commit-hash
git push

git checkout my-other-branch
git revert revert-commit-hash
git push
  1. revert the commit
  2. (create and) checkout other branch
  3. revert the revert

PHP - regex to allow letters and numbers only

  • Missing end anchor $
  • Missing multiplier
  • Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.

/^[a-z0-9]+$/i

How to enable core dump in my Linux C++ program

By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.

Try ulimit -c unlimited before running your program.

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Type of expression is ambiguous without more context Swift

The compiler can't figure out what type to make the Dictionary, because it's not homogenous. You have values of different types. The only way to get around this is to make it a [String: Any], which will make everything clunky as all hell.

return [
    "title": title,
    "is_draft": isDraft,
    "difficulty": difficulty,
    "duration": duration,
    "cost": cost,
    "user_id": userId,
    "description": description,
    "to_sell": toSell,
    "images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]

This is a job for a struct. It'll vastly simplify working with this data structure.

How do I initialize a TypeScript Object with a JSON-Object?

I personally prefer option #3 of @Ingo Bürk. And I improved his codes to support an array of complex data and Array of primitive data.

interface IDeserializable {
  getTypes(): Object;
}

class Utility {
  static deserializeJson<T>(jsonObj: object, classType: any): T {
    let instanceObj = new classType();
    let types: IDeserializable;
    if (instanceObj && instanceObj.getTypes) {
      types = instanceObj.getTypes();
    }

    for (var prop in jsonObj) {
      if (!(prop in instanceObj)) {
        continue;
      }

      let jsonProp = jsonObj[prop];
      if (this.isObject(jsonProp)) {
        instanceObj[prop] =
          types && types[prop]
            ? this.deserializeJson(jsonProp, types[prop])
            : jsonProp;
      } else if (this.isArray(jsonProp)) {
        instanceObj[prop] = [];
        for (let index = 0; index < jsonProp.length; index++) {
          const elem = jsonProp[index];
          if (this.isObject(elem) && types && types[prop]) {
            instanceObj[prop].push(this.deserializeJson(elem, types[prop]));
          } else {
            instanceObj[prop].push(elem);
          }
        }
      } else {
        instanceObj[prop] = jsonProp;
      }
    }

    return instanceObj;
  }

  //#region ### get types ###
  /**
   * check type of value be string
   * @param {*} value
   */
  static isString(value: any) {
    return typeof value === "string" || value instanceof String;
  }

  /**
   * check type of value be array
   * @param {*} value
   */
  static isNumber(value: any) {
    return typeof value === "number" && isFinite(value);
  }

  /**
   * check type of value be array
   * @param {*} value
   */
  static isArray(value: any) {
    return value && typeof value === "object" && value.constructor === Array;
  }

  /**
   * check type of value be object
   * @param {*} value
   */
  static isObject(value: any) {
    return value && typeof value === "object" && value.constructor === Object;
  }

  /**
   * check type of value be boolean
   * @param {*} value
   */
  static isBoolean(value: any) {
    return typeof value === "boolean";
  }
  //#endregion
}

// #region ### Models ###
class Hotel implements IDeserializable {
  id: number = 0;
  name: string = "";
  address: string = "";
  city: City = new City(); // complex data
  roomTypes: Array<RoomType> = []; // array of complex data
  facilities: Array<string> = []; // array of primitive data

  // getter example
  get nameAndAddress() {
    return `${this.name} ${this.address}`;
  }

  // function example
  checkRoom() {
    return true;
  }

  // this function will be use for getting run-time type information
  getTypes() {
    return {
      city: City,
      roomTypes: RoomType
    };
  }
}

class RoomType implements IDeserializable {
  id: number = 0;
  name: string = "";
  roomPrices: Array<RoomPrice> = [];

  // getter example
  get totalPrice() {
    return this.roomPrices.map(x => x.price).reduce((a, b) => a + b, 0);
  }

  getTypes() {
    return {
      roomPrices: RoomPrice
    };
  }
}

class RoomPrice {
  price: number = 0;
  date: string = "";
}

class City {
  id: number = 0;
  name: string = "";
}
// #endregion

// #region ### test code ###
var jsonObj = {
  id: 1,
  name: "hotel1",
  address: "address1",
  city: {
    id: 1,
    name: "city1"
  },
  roomTypes: [
    {
      id: 1,
      name: "single",
      roomPrices: [
        {
          price: 1000,
          date: "2020-02-20"
        },
        {
          price: 1500,
          date: "2020-02-21"
        }
      ]
    },
    {
      id: 2,
      name: "double",
      roomPrices: [
        {
          price: 2000,
          date: "2020-02-20"
        },
        {
          price: 2500,
          date: "2020-02-21"
        }
      ]
    }
  ],
  facilities: ["facility1", "facility2"]
};

var hotelInstance = Utility.deserializeJson<Hotel>(jsonObj, Hotel);

console.log(hotelInstance.city.name);
console.log(hotelInstance.nameAndAddress); // getter
console.log(hotelInstance.checkRoom()); // function
console.log(hotelInstance.roomTypes[0].totalPrice); // getter
// #endregion

How to develop Android app completely using python?

Android, Python !

When I saw these two keywords together in your question, Kivy is the one which came to my mind first.

Kivy logo

Before coming to native Android development in Java using Android Studio, I had tried Kivy. It just awesome. Here are a few advantage I could find out.


Simple to use

With a python basics, you won't have trouble learning it.


Good community

It's well documented and has a great, active community.


Cross platform.

You can develop thing for Android, iOS, Windows, Linux and even Raspberry Pi with this single framework. Open source.


It is a free software

At least few of it's (Cross platform) competitors want you to pay a fee if you want a commercial license.


Accelerated graphics support

Kivy's graphics engine build over OpenGL ES 2 makes it suitable for softwares which require fast graphics rendering such as games.



Now coming into the next part of question, you can't use Android Studio IDE for Kivy. Here is a detailed guide for setting up the development environment.

JavaScript Promises - reject vs. throw

There's one difference — which shouldn't matter — that the other answers haven't touched on, so:

There's no difference that's likely to matter, no. Yes, there is a very small difference.

If the fulfillment handler passed to then throws, the promise returned by that call to then is rejected with what was thrown.

If it returns a rejected promise, the promise returned by the call to then is resolved to that promise (and will ultimately be rejected, since the promise it's resolved to is rejected), which may introduce one extra async "tick" (one more loop in the microtask queue, to put it in browser terms).

Any code that relies on that difference is fundamentally broken, though. :-) It shouldn't be that sensitive to the timing of the promise settlement.

Here's an example:

_x000D_
_x000D_
function usingThrow(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                throw new Error(`${v} is not 42!`);
            }
            return v;
        });
}
function usingReject(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                return Promise.reject(new Error(`${v} is not 42!`));
            }
            return v;
        });
}

// The rejection handler on this chain may be called **after** the
// rejection handler on the following chain
usingReject(1)
.then(v => console.log(v))
.catch(e => console.error("Error from usingReject:", e.message));

// The rejection handler on this chain may be called **before** the
// rejection handler on the preceding chain
usingThrow(2)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));
_x000D_
_x000D_
_x000D_

If you run that, as of this writing you get:

Error from usingThrow: 2 is not 42!
Error from usingReject: 1 is not 42!

Note the order.

Compare that to the same chains but both using usingThrow:

_x000D_
_x000D_
function usingThrow(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                throw new Error(`${v} is not 42!`);
            }
            return v;
        });
}

usingThrow(1)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));

usingThrow(2)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));
_x000D_
_x000D_
_x000D_

which shows that the rejection handlers ran in the other order:

Error from usingThrow: 1 is not 42!
Error from usingThrow: 2 is not 42!

I said "may" above because there's been some work in other areas that removed this unnecessary extra tick in other similar situations if all of the promises involved are native promises (not just thenables). (Specifically: In an async function, return await x originally introduced an extra async tick vs. return x while being otherwise identical; ES2020 changed it so that if x is a native promise, the extra tick is removed.)

Again, any code that's that sensitive to the timing of the settlement of a promise is already broken. So really it doesn't/shouldn't matter.

In practical terms, as other answers have mentioned:

  • As Kevin B pointed out, throw won't work if you're in a callback to some other function you've used within your fulfillment handler — this is the biggie
  • As lukyer pointed out, throw abruptly terminates the function, which can be useful (but you're using return in your example, which does the same thing)
  • As Vencator pointed out, you can't use throw in a conditional expression (? :), at least not for now

Other than that, it's mostly a matter of style/preference, so as with most of those, agree with your team what you'll do (or that you don't care either way), and be consistent.

How to read a file in Groovy into a string?

String fileContents = new File('/path/to/file').text

If you need to specify the character encoding, use the following instead:

String fileContents = new File('/path/to/file').getText('UTF-8')

Remove scrollbars from textarea

Hide scroll bar, but while still being able to scroll using CSS

To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:

    -webkit- (Chrome, Safari, newer versions of Opera):
    .element::-webkit-scrollbar { width: 0 !important }
    -moz- (Firefox):
    .element { overflow: -moz-scrollbars-none; }
    -ms- (Internet Explorer +10):
    .element { -ms-overflow-style: none; }

ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/

Basic http file downloading and saving to disk in python?

import urllib
urllib.request.urlretrieve("https://raw.githubusercontent.com/dnishimoto/python-deep-learning/master/list%20iterators%20and%20generators.ipynb", "test.ipynb")

downloads a single raw juypter notebook to file.

Failed to find target with hash string 'android-25'

You don't need to update anything. Just download the SDK for API 25 from Android SDK Manager or by launching Android standalone SDK manager. The error is for missing platform and not for missing tool.Android SDK Manager Android Studio 2.2.2

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

Div Size Automatically size of content

As far as I know, display: inline-block is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.

Unfortunately MyApp has stopped. How can I solve this?

Use the LogCat and try to find what is causing the app to crash.

To see Logcat if you use Android Studio then Press ALT + 6 or

if you use Eclipse then Window -> Open Perspective -> Other - LogCat

Go to the LogCat, from the drop down menu select error. This will contain all the required information to help you debug. If that doesn't help, post the LogCat as an edit to your question and somebody will help you out.

How to make "if not true condition"?

I think it can be simplified into:

grep sysa /etc/passwd || {
    echo "ERROR - The user sysa could not be looked up"
    exit 2
}

or in a single command line

$ grep sysa /etc/passwd || { echo "ERROR - The user sysa could not be looked up"; exit 2; }

changing minDate option in JQuery DatePicker not working

How to dynamically alter the minDate (after init)

The above answers address how to set the default minDate at init, but the question was actually how to dynamically alter the minDate, below I also clarify How to set the default minDate.

All that was wrong with the original question was that the minDate value being set should have been a string (don't forget the quotes):

$('#datePickerId').datepicker('option', 'minDate', '3');

minDate also accepts a date object and a common use is to have an end date you are trying to calculate so something like this could be useful:

$('#datePickerId').datepicker(
    'option', 'minDate', new Date($(".datePop.start").val())
);

How to set the default minDate (at init)

Just answering this for best practice; the minDate option expects one of:

  1. a string in the current dateFormat OR
  2. number of days from today (e.g. +7) OR
  3. string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '-1y -1m')

@bogart setting the string to "0" is a solution as it satisfies option 2 above

$('#datePickerId').datepicker('minDate': '3');

jQuery UI docs for minDate

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

Running eclipse and also running Maven will require you to store two path variables, one in your jdk1.7_x_x_x location and also in your jdk1.7_x_x_\bin. If you are using Windows, when you are in your environment variables, do the following:

1) create a USER variable called JAVA_HOME. Point this to the location of your JAVA file. For example: "C:\Program Files\Java\jdk1.7.0_51" (remove the quotes)

2) under the PATH, append %JAVA_HOME% to the PATH. This will add the file location from step 1 to your PATH. This is good for MAVEN

3) if you are using eclipse you need to have the path point to "C:\Program Files\Java\jdk1.7.0_51\bin". Now append %JAVA_HOME%\bin to the end of your path.

4) your path should look something like this: C:\Program Files (x86)\Google\google_appengine\;C:\Users\username\AppData\Roaming\npm;%M2%;%JAVA_HOME%;%JAVA_HOME%\bin

Notes: the items that are enclosed in %'s like %M2% are assigned variables. It looks redundant but necessary. You can confirm that everything works by typing in:

java -version
javac -version
mvn -version

Each of those three statements typed in comman prompt should not return errors.

jquery-ui-dialog - How to hook into dialog close event

I believe you can also do it while creating the dialog (copied from a project I did):

dialog = $('#dialog').dialog({
    modal: true,
    autoOpen: false,
    width: 700,
    height: 500,
    minWidth: 700,
    minHeight: 500,
    position: ["center", 200],
    close: CloseFunction,
    overlay: {
        opacity: 0.5,
        background: "black"
    }
});

Note close: CloseFunction

How to iterate a loop with index and element in Swift

Starting with Swift 2, the enumerate function needs to be called on the collection like so:

for (index, element) in list.enumerate() {
    print("Item \(index): \(element)")
}

Hard reset of a single file

You can use the following command:

git reset -- my-file.txt

which will update both the working copy of my-file.txt when added.

Responsive Bootstrap Jumbotron Background Image

I found that this worked perfectly for me:

.jumbotron {
background-image: url(/img/Jumbotron.jpg);
background-size: cover;
height: 100%;}

You can resize your screen and it will always take up 100% of the window.

How to check the multiple permission at single request in Android M?

       // **For multiple permission you can use this code :**

       // **First:**
//Write down in onCreate method.

         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{
                                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                    android.Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST);

         }

        //**Second:**
    //Write down in a activity.
     @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST:

                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Intent i = new Intent(SplashActivity.this,
                                        HomeActivity.class);
                                startActivity(i);
                                finish();
                            }
                        }, SPLASH_DISPLAY_LENGTH);

                    } else {
                        finish();
                    }
                    return;
            }
        }

How to change Windows 10 interface language on Single Language version

You can download language pack and use "Install or Uninstall display languages" wizard. To do this:

  • Press Win+R, paste lpksetup and press Enter
  • Wizard will appear on the screen
  • Click the Install display languages button
  • In the next page of the wizard, click Browse and pick the *.cab file of the MUI language you downloaded
  • Click the Next button to install language

Fastest way to write huge data in text file Java

For those who want to improve the time for retrieval of records and dump into the file (i.e no processing on records), instead of putting them into an ArrayList, append those records into a StringBuffer. Apply toSring() function to get a single String and write it into the file at once.

For me, the retrieval time reduced from 22 seconds to 17 seconds.

Make REST API call in Swift

Swift 4 - GET request

var request = URLRequest(url: URL(string: "http://example.com/api/v1/example")!)
request.httpMethod = "GET"

URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
    do {
        let jsonDecoder = JSONDecoder()
        let responseModel = try jsonDecoder.decode(CustomDtoClass.self, from: data!)
        print(responseModel)
    } catch {
        print("JSON Serialization error")
    }
}).resume()

Don't forget to configure App Transport Security Settings to add your domain to the exceptions and allow insecure http requests if you're hitting endpoints without using HTTPS.

You can use a tool like http://www.json4swift.com/ to autogenerate your Codeable Mappings from your JSON responses.

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Google Spreadsheet, Count IF contains a string

Try using wildcards directly in the COUNTIF function :

=(COUNTIF(A2:A51,"=*iPad*")/COUNTA(A2:A51))*1

How to make clang compile to llvm IR

If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8 but you can use any other version):

  1. generate all .ll files

    clang-3.8 -S -emit-llvm *.c
    
  2. link them into a single one

    llvm-link-3.8 -S -v -o single.ll *.ll
    
  3. (Optional) Optimise your code (maybe some alias analysis)

    opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
    
  4. Generate assembly (generates a optimised.s file)

    llc-3.8 optimised.ll
    
  5. Create executable (named a.out)

    clang-3.8 optimised.s
    

Python list directory, subdirectory, and files

Just in case... Getting all files in the directory and subdirectories matching some pattern (*.py for example):

import os
from fnmatch import fnmatch

root = '/some/directory'
pattern = "*.py"

for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name, pattern):
            print os.path.join(path, name)

Possible heap pollution via varargs parameter

The reason is because varargs give the option of being called with a non-parametrized object array. So if your type was List < A > ... , it can also be called with List[] non-varargs type.

Here is an example:

public static void testCode(){
    List[] b = new List[1];
    test(b);
}

@SafeVarargs
public static void test(List<A>... a){
}

As you can see List[] b can contain any type of consumer, and yet this code compiles. If you use varargs, then you are fine, but if you use the method definition after type-erasure - void test(List[]) - then the compiler will not check the template parameter types. @SafeVarargs will suppress this warning.

How to get current date in jquery?

This will give you current date string

var today = new Date().toISOString().split('T')[0];

How to make 'submit' button disabled?

This worked for me.

.ts

newForm : FormGroup;

.html

<input type="button" [disabled]="newForm.invalid" />

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In addition to @chanafdo answer, you can use route name

when working with laravel blade

<a href="{{route('login')}}">login here</a> with parameter in route name

when go to url like URI: profile/{id} <a href="{{route('profile', ['id' => 1])}}">login here</a>

without blade

<a href="<?php echo route('login')?>">login here</a>

with parameter in route name

when go to url like URI: profile/{id} <a href="<?php echo route('profile', ['id' => 1])?>">login here</a>

As of laravel 5.2 you can use @php @endphp to create as <?php ?> in laravel blade. Using blade your personal opinion but I suggest to use it. Learn it. It has many wonderful features as template inheritance, Components & Slots,subviews etc...

How to make/get a multi size .ico file?

ImageMagick, the free and open source image manipulation toolkit, can easily do this:

Note: Since ImageMagick 7, the CLI has changed slightly, you need to add magick in front of any commands.

magick convert icon-16.png icon-32.png icon-64.png icon-128.png icon.ico

See also http://www.imagemagick.org/Usage/thumbnails/#favicon, that has the example:

magick convert image.png -bordercolor white -border 0 \
          \( -clone 0 -resize 16x16 \) \
          \( -clone 0 -resize 32x32 \) \
          \( -clone 0 -resize 48x48 \) \
          \( -clone 0 -resize 64x64 \) \
          -delete 0 -alpha off -colors 256 favicon.ico

There is also now the shorter:

magick convert image.png -define icon:auto-resize="256,128,96,64,48,32,16" favicon.ico

How to set a default value with Html.TextBoxFor?

Here's how I solved it. This works if you also use this for editing.

@Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })

Double quotes within php script echo

use a HEREDOC, which eliminates any need to swap quote types and/or escape them:

echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

POST request via RestTemplate in JSON

I ran across this problem when attempting to debug a REST endpoint. Here is a basic example using Spring's RestTemplate class to make a POST request that I used. It took me quite a bit of a long time to piece together code from different places to get a working version.

RestTemplate restTemplate = new RestTemplate();

String url = "endpoint url";
String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);

The particular JSON parser my rest endpoint was using needed double quotes around field names so that's why I've escaped the double quotes in my requestJson String.

How to use: while not in

The expression ('AND' and 'OR' and 'NOT') evaluates to 'NOT', so you are testing whether the list has NOT or not.

Git fetch remote branch

I want to give you one-liner command for fetching all the remote branches to your local and switch to your desired newly created local branch:

git fetch && git checkout discover

After running the above command you will get the below message:

Switched to a new branch 'discover'
Branch discover set up to track remote branch discover from origin.

The first line states that switched to a new branch - why new? It is already there in remote!

But actually you have to create it locally too. The branch is taken from the remote index and created locally for you.

Here discover is a new branch which were created from your repository's remote branch discover.

But the second line gives more information than the first one which tell us that:

Our branch is set up to track remote branch with the same name.

Although git fetch fetches all branches to local. But if you run git branch after it, you will see only master branch in local. Why?

Because for every branch you have in remote you have to create it locally too, for tracking it as git checkout <branchname> as we have done in the above example.

After running git checkout command you can run git branch, and now you can see both the branch:

  1. master and 2. discover in your local listing.

join list of lists in python

What you're describing is known as flattening a list, and with this new knowledge you'll be able to find many solutions to this on Google (there is no built-in flatten method). Here is one of them, from http://www.daniel-lemire.com/blog/archives/2006/05/10/flattening-lists-in-python/:

def flatten(x):
    flat = True
    ans = []
    for i in x:
        if ( i.__class__ is list):
            ans = flatten(i)
        else:
            ans.append(i)
    return ans

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

The solution is to add your variable to /etc/profile. Then everything works as expected! Of course you MUST do it as a root user with sudo nano /etc/profile. If you edit it with any other way the system will complain with a damaged /etc/profile, even if you change the permissions to root.

How To Convert A Number To an ASCII Character?

Edit: By request, I added a check to make sure the value entered was within the ASCII range of 0 to 127. Whether you want to limit this is up to you. In C# (and I believe .NET in general), chars are represented using UTF-16, so any valid UTF-16 character value could be cast into it. However, it is possible a system does not know what every Unicode character should look like so it may show up incorrectly.

// Read a line of input
string input = Console.ReadLine();

int value;
// Try to parse the input into an Int32
if (Int32.TryParse(input, out value)) {
    // Parse was successful
    if (value >= 0 and value < 128) {
        //value entered was within the valid ASCII range
        //cast value to a char and print it
        char c = (char)value;
        Console.WriteLine(c);
    }
}

How to add scroll bar to the Relative Layout?

I used the

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<RelativeLayout

and works perfectly

How to generate XML file dynamically using PHP?

I see examples with both DOM and SimpleXML, but none with the XMLWriter.

Please keep in mind that from the tests I've done, both DOM and SimpleXML are almost twice slower then the XMLWriter and for larger files you should consider using the later one.

Here's a full working example, clear and simple that meets the requirements, written with XMLWriter (I'm sure it will help other users):

// array with the key / value pairs of the information to be added (can be an array with the data fetched from db as well)
$songs = [
    'song1.mp3' => 'Track 1 - Track Title',
    'song2.mp3' => 'Track 2 - Track Title',
    'song3.mp3' => 'Track 3 - Track Title',
    'song4.mp3' => 'Track 4 - Track Title',
    'song5.mp3' => 'Track 5 - Track Title',
    'song6.mp3' => 'Track 6 - Track Title',
    'song7.mp3' => 'Track 7 - Track Title',
    'song8.mp3' => 'Track 8 - Track Title',
];

$xml = new XMLWriter();
$xml->openURI('songs.xml');
$xml->setIndent(true);
$xml->setIndentString('    ');
$xml->startDocument('1.0', 'UTF-8');
    $xml->startElement('xml');
            foreach($songs as $song => $track){
                $xml->startElement('track');
                    $xml->writeElement('path', $song);
                    $xml->writeElement('title', $track);
                $xml->endElement();
            }
    $xml->endElement();
$xml->endDocument();
$xml->flush();
unset($xml);

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

I had similar issue, I resolved by changing the requestlimits maxAllowedContentLength ="40000000" section of applicationhost.config file, located in "C:\Windows\System32\inetsrv\config" directory

Look for security Section and add the sectionGroup.

<sectionGroup name="requestfiltering">
    <section name="requestlimits" maxAllowedContentLength ="40000000" />
</sectionGroup>

*NOTE delete;

<section name="requestfiltering" overrideModeDefault="Deny" />

No server in Eclipse; trying to install Tomcat

Try to install JST Server Adapters and JST Server Adapters Extentions. I am running Eclipse 4.4.2 Luna and it worked.

Here are the steps I followed:

  1. Help -> Install New Software

  2. Choose "Luna - http://download.eclipse.org/releases/luna" site

  3. Expand "Web, XML, and Java EE Development"

  4. Check JST Server Adapters and JST Server Adapters Extentions

React Native fixed footer

Here's the actual code based on Colin's Ramsay answer:

<View style={{flex: 1}}>
  <ScrollView>main</ScrollView>
  <View><Text>footer</Text></View>
</View>

How to handle AccessViolationException

Microsoft: "Corrupted process state exceptions are exceptions that indicate that the state of a process has been corrupted. We do not recommend executing your application in this state.....If you are absolutely sure that you want to maintain your handling of these exceptions, you must apply the HandleProcessCorruptedStateExceptionsAttribute attribute"

Microsoft: "Use application domains to isolate tasks that might bring down a process."

The program below will protect your main application/thread from unrecoverable failures without risks associated with use of HandleProcessCorruptedStateExceptions and <legacyCorruptedStateExceptionsPolicy>

public class BoundaryLessExecHelper : MarshalByRefObject
{
    public void DoSomething(MethodParams parms, Action action)
    {
        if (action != null)
            action();
        parms.BeenThere = true; // example of return value
    }
}

public struct MethodParams
{
    public bool BeenThere { get; set; }
}

class Program
{
    static void InvokeCse()
    {
        IntPtr ptr = new IntPtr(123);
        System.Runtime.InteropServices.Marshal.StructureToPtr(123, ptr, true);
    }

    private static void ExecInThisDomain()
    {
        try
        {
            var o = new BoundaryLessExecHelper();
            var p = new MethodParams() { BeenThere = false };
            Console.WriteLine("Before call");

            o.DoSomething(p, CausesAccessViolation);
            Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); //never stops here
        }
        catch (Exception exc)
        {
            Console.WriteLine($"CSE: {exc.ToString()}");
        }
        Console.ReadLine();
    }


    private static void ExecInAnotherDomain()
    {
        AppDomain dom = null;

        try
        {
            dom = AppDomain.CreateDomain("newDomain");
            var p = new MethodParams() { BeenThere = false };
            var o = (BoundaryLessExecHelper)dom.CreateInstanceAndUnwrap(typeof(BoundaryLessExecHelper).Assembly.FullName, typeof(BoundaryLessExecHelper).FullName);         
            Console.WriteLine("Before call");

            o.DoSomething(p, CausesAccessViolation);
            Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); // never gets to here
        }
        catch (Exception exc)
        {
            Console.WriteLine($"CSE: {exc.ToString()}");
        }
        finally
        {
            AppDomain.Unload(dom);
        }

        Console.ReadLine();
    }


    static void Main(string[] args)
    {
        ExecInAnotherDomain(); // this will not break app
        ExecInThisDomain();  // this will
    }
}

Differences between unique_ptr and shared_ptr

unique_ptr is the light-weight smart pointer of choice if you just have a dynamic object somewhere for which one consumer has sole (hence "unique") responsibility -- maybe a wrapper class that needs to maintain some dynamically allocated object. unique_ptr has very little overhead. It is not copyable, but movable. Its type is template <typename D, typename Deleter> class unique_ptr;, so it depends on two template parameters.

unique_ptr is also what auto_ptr wanted to be in the old C++ but couldn't because of that language's limitations.

shared_ptr on the other hand is a very different animal. The obvious difference is that you can have many consumers sharing responsibility for a dynamic object (hence "shared"), and the object will only be destroyed when all shared pointers have gone away. Additionally you can have observing weak pointers which will intelligently be informed if the shared pointer they're following has disappeared.

Internally, shared_ptr has a lot more going on: There is a reference count, which is updated atomically to allow the use in concurrent code. Also, there's plenty of allocation going on, one for an internal bookkeeping "reference control block", and another (often) for the actual member object.

But there's another big difference: The shared pointers type is always template <typename T> class shared_ptr;, and this is despite the fact that you can initialize it with custom deleters and with custom allocators. The deleter and allocator are tracked using type erasure and virtual function dispatch, which adds to the internal weight of the class, but has the enormous advantage that different sorts of shared pointers of type T are all compatible, no matter the deletion and allocation details. Thus they truly express the concept of "shared responsibility for T" without burdening the consumer with the details!

Both shared_ptr and unique_ptr are designed to be passed by value (with the obvious movability requirement for the unique pointer). Neither should make you worried about the overhead, since their power is truly astounding, but if you have a choice, prefer unique_ptr, and only use shared_ptr if you really need shared responsibility.

Rounding integer division (instead of truncating)

The standard idiom for integer rounding up is:

int a = (59 + (4 - 1)) / 4;

You add the divisor minus one to the dividend.

What are the proper permissions for an upload folder with PHP/Apache?

I would go with Ryan's answer if you really want to do this.

In general on a *nix environment, you always want to err on giving away as little permissions as possible.

9 times out of 10, 755 is the ideal permission for this - as the only user with the ability to modify the files will be the webserver. Change this to 775 with your ftp user in a group if you REALLY need to change this.

Since you're new to php by your own admission, here's a helpful link for improving the security of your upload service: move_uploaded_file

Difference between a class and a module

The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

What is the command to exit a Console application in C#?

Several options, by order of most appropriate way:

  1. Return an int from the Program.Main method
  2. Throw an exception and don't handle it anywhere (use for unexpected error situations)
  3. To force termination elsewhere, System.Environment.Exit (not portable! see below)

Edited 9/2013 to improve readability

Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.

Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.

split string only on first instance of specified character

With help of destructuring assignment it can be more readable:

let [first, ...rest] = "good_luck_buddy".split('_')
rest = rest.join('_')

How do I replace NA values with zeros in an R dataframe?

Another dplyr pipe compatible option with tidyrmethod replace_na that works for several columns:

require(dplyr)
require(tidyr)

m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
d <- as.data.frame(m)

myList <- setNames(lapply(vector("list", ncol(d)), function(x) x <- 0), names(d))

df <- d %>% replace_na(myList)

You can easily restrict to e.g. numeric columns:

d$str <- c("string", NA)

myList <- myList[sapply(d, is.numeric)]

df <- d %>% replace_na(myList)

Wordpress plugin install: Could not create directory

CentOS7 or Ubuntu 16


1.

WordPress uses ftp to install themes and plugins.
So the ftpd should have been configured to create-directory

vim /etc/pure-ftpd.confg

and if it is no then should be yes

# Are anonymous users allowed to create new directories?
AnonymousCanCreateDirs       yes

lastly

sudo systemctl restart pure-ftpd

2.

Maybe there is an ownership issue with the parent directories. Find the Web Server user name and group name if it is Apache Web Server

apachectl -S

it will print

...
...
User: name="apache" id=997
Group: name="apache" id=1000

on Ubuntu it is

User: name="www-data" id=33 not_used
Group: name="www-data" id=33 not_used

then

sudo chown -R apache:apache directory-name

3.

Sometimes it is because of directories permissions. So try

sudo chmod -R 755 directory-name

in some cases 755 does not work. (It should & I do not no why) so try

sudo chmod -R 777 directory-name

4.

Maybe it is because of php safe mode. So turn it off in the root of your domain

vim php.ini

then add

safe_mode = Off

NOTE:
For not entering FTP username and password each time installing a theme we can configure WordPress to use it directly by adding

define('FS_METHOD','direct');

to the wp-config.php file.

remote rejected master -> master (pre-receive hook declined)

I was getting the same error, and running the following code in the command line solved it:

$ heroku config:set BUNDLE_WITHOUT="development:test"

TypeError: 'builtin_function_or_method' object is not subscriptable

Looks like you typed brackets instead of parenthesis by mistake.

How to update attributes without validation

You can do something like:

object.attribute = value
object.save(:validate => false)

Difference between Pragma and Cache-Control headers?

Pragma is the HTTP/1.0 implementation and cache-control is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.

How to change Label Value using javascript

very simple

$('#label-ID').text("label value which you want to set");

How to install Visual Studio 2015 on a different drive

Run the installer from command line with argument /CustomInstallPath InstallationDirectory

See more command-line parameters and other installation information.

Note: this won't change location of all files, but only of those which can be (by design) installed onto different location. Be warned that there is many shared components which will be installed into shared repositories on drive C: without any possibility to change their path (unless you do some hacking using mklink /j (directory junction, i.e."hard link for folder"), but it is questionable whether it is worth it, because any Visual Studio updates will break those hard links. This is confirmed by people who tried that, although on Visual Studio 2012.)


Update: per recent comment, uninstallation of Visual Studio might be required before the above applies. Uninstallation command is like this: vs_community_ENU.exe /uninstall /force

Resizing an Image without losing any quality

See if you like the image resizing quality of this open source ASP.NET module. There's a live demo, so you can mess around with it yourself. It yields results that are (to me) impossible to distinguish from Photoshop output. It also has similar file sizes - MS did a good job on their JPEG encoder.

Difference between volatile and synchronized in Java

It's important to understand that there are two aspects to thread safety.

  1. execution control, and
  2. memory visibility

The first has to do with controlling when code executes (including the order in which instructions are executed) and whether it can execute concurrently, and the second to do with when the effects in memory of what has been done are visible to other threads. Because each CPU has several levels of cache between it and main memory, threads running on different CPUs or cores can see "memory" differently at any given moment in time because threads are permitted to obtain and work on private copies of main memory.

Using synchronized prevents any other thread from obtaining the monitor (or lock) for the same object, thereby preventing all code blocks protected by synchronization on the same object from executing concurrently. Synchronization also creates a "happens-before" memory barrier, causing a memory visibility constraint such that anything done up to the point some thread releases a lock appears to another thread subsequently acquiring the same lock to have happened before it acquired the lock. In practical terms, on current hardware, this typically causes flushing of the CPU caches when a monitor is acquired and writes to main memory when it is released, both of which are (relatively) expensive.

Using volatile, on the other hand, forces all accesses (read or write) to the volatile variable to occur to main memory, effectively keeping the volatile variable out of CPU caches. This can be useful for some actions where it is simply required that visibility of the variable be correct and order of accesses is not important. Using volatile also changes treatment of long and double to require accesses to them to be atomic; on some (older) hardware this might require locks, though not on modern 64 bit hardware. Under the new (JSR-133) memory model for Java 5+, the semantics of volatile have been strengthened to be almost as strong as synchronized with respect to memory visibility and instruction ordering (see http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#volatile). For the purposes of visibility, each access to a volatile field acts like half a synchronization.

Under the new memory model, it is still true that volatile variables cannot be reordered with each other. The difference is that it is now no longer so easy to reorder normal field accesses around them. Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire. In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.

-- JSR 133 (Java Memory Model) FAQ

So, now both forms of memory barrier (under the current JMM) cause an instruction re-ordering barrier which prevents the compiler or run-time from re-ordering instructions across the barrier. In the old JMM, volatile did not prevent re-ordering. This can be important, because apart from memory barriers the only limitation imposed is that, for any particular thread, the net effect of the code is the same as it would be if the instructions were executed in precisely the order in which they appear in the source.

One use of volatile is for a shared but immutable object is recreated on the fly, with many other threads taking a reference to the object at a particular point in their execution cycle. One needs the other threads to begin using the recreated object once it is published, but does not need the additional overhead of full synchronization and it's attendant contention and cache flushing.

// Declaration
public class SharedLocation {
    static public SomeObject someObject=new SomeObject(); // default object
    }

// Publishing code
// Note: do not simply use SharedLocation.someObject.xxx(), since although
//       someObject will be internally consistent for xxx(), a subsequent 
//       call to yyy() might be inconsistent with xxx() if the object was 
//       replaced in between calls.
SharedLocation.someObject=new SomeObject(...); // new object is published

// Using code
private String getError() {
    SomeObject myCopy=SharedLocation.someObject; // gets current copy
    ...
    int cod=myCopy.getErrorCode();
    String txt=myCopy.getErrorText();
    return (cod+" - "+txt);
    }
// And so on, with myCopy always in a consistent state within and across calls
// Eventually we will return to the code that gets the current SomeObject.

Speaking to your read-update-write question, specifically. Consider the following unsafe code:

public void updateCounter() {
    if(counter==1000) { counter=0; }
    else              { counter++; }
    }

Now, with the updateCounter() method unsynchronized, two threads may enter it at the same time. Among the many permutations of what could happen, one is that thread-1 does the test for counter==1000 and finds it true and is then suspended. Then thread-2 does the same test and also sees it true and is suspended. Then thread-1 resumes and sets counter to 0. Then thread-2 resumes and again sets counter to 0 because it missed the update from thread-1. This can also happen even if thread switching does not occur as I have described, but simply because two different cached copies of counter were present in two different CPU cores and the threads each ran on a separate core. For that matter, one thread could have counter at one value and the other could have counter at some entirely different value just because of caching.

What's important in this example is that the variable counter was read from main memory into cache, updated in cache and only written back to main memory at some indeterminate point later when a memory barrier occurred or when the cache memory was needed for something else. Making the counter volatile is insufficient for thread-safety of this code, because the test for the maximum and the assignments are discrete operations, including the increment which is a set of non-atomic read+increment+write machine instructions, something like:

MOV EAX,counter
INC EAX
MOV counter,EAX

Volatile variables are useful only when all operations performed on them are "atomic", such as my example where a reference to a fully formed object is only read or written (and, indeed, typically it's only written from a single point). Another example would be a volatile array reference backing a copy-on-write list, provided the array was only read by first taking a local copy of the reference to it.

Can I configure a subdomain to point to a specific port on my server

I... don't think so. You can redirect the subdomain (such as blah.something.com) to point to something.com:25566, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

How to tell if UIViewController's view is visible

There are a couple of issues with the above solutions. If you are using, for example, a UISplitViewController, the master view will always return true for

if(viewController.isViewLoaded && viewController.view.window) {
    //Always true for master view in split view controller
}

Instead, take this simple approach which seems to work well in most, if not all cases:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    //We are now invisible
    self.visible = false;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //We are now visible
    self.visible = true;
}

How to restart VScode after editing extension's config?

  1. Open the Command Palette

    Ctrl + Shift + P

  2. Then type:

    Reload Window
    

Recommended date format for REST GET API

Always use UTC:

For example I have a schedule component that takes in one parameter DATETIME. When I call this using a GET verb I use the following format where my incoming parameter name is scheduleDate.

Example:
https://localhost/api/getScheduleForDate?scheduleDate=2003-11-21T01:11:11Z

Share data between AngularJS controllers

As pointed out by @MaNn in one of the comments of the accepted answers, the solution wont work if the page is refreshed.

The Solution for this is to use localStorage or sessionStorage for temporary persistence of the data you want to share across controllers.

  1. Either you make a sessionService whose GET and SET method, encrypts and decrypts the data and reads the data from either localStorage or sessionStorage. So now you use this service directly to read and write the data in the storage via any controller or service you want. This is a open approach and easy one
  2. Else you make a DataSharing Service and use localStorage inside it - so that if the page is refreshed the service will try and check the storage and reply back via the Getters and Setters you have made public or private in this service file.

Printing to the console in Google Apps Script?

In a google script project you can create html files (example: index.html) or gs files (example:code.gs). The .gs files are executed on the server and you can use Logger.log as @Peter Herrman describes. However if the function is created in a .html file it is being executed on the user's browser and you can use console.log. The Chrome browser console can be viewed by Ctrl Shift J on Windows/Linux or Cmd Opt J on Mac

If you want to use Logger.log on an html file you can use a scriptlet to call the Logger.log function from the html file. To do so you would insert <? Logger.log(something) ?> replacing something with whatever you want to log. Standard scriptlets, which use the syntax <? ... ?>, execute code without explicitly outputting content to the page.

How to manage startActivityForResult on Android?

From your FirstActivity call the SecondActivity using startActivityForResult() method

For example:

int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);

In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

For example: In SecondActivity if you want to send back data:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don't want to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

Now in your FirstActivity class write following code for the onActivityResult() method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult

To implement passing data between two activities in much better way in Kotlin please go through this link 'A better way to pass data between Activities'

How do I configure git to ignore some files locally?

Add the following lines to the [alias] section of your .gitconfig file

ignore = update-index --assume-unchanged
unignore = update-index --no-assume-unchanged
ignored = !git ls-files -v | grep "^[[:lower:]]"

Now you can use git ignore my_file to ignore changes to the local file, and git unignore my_file to stop ignoring the changes. git ignored lists the ignored files.

This answer was gleaned from http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html.

How to set Java environment path in Ubuntu

Step1:

sudo gedit ~/.bash_profile

Step2:

JAVA_HOME=/home/user/tool/jdk-8u201-linux-x64/jdk1.8.0_201
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

Step3:

source ~/.bash_profile

Ping all addresses in network, windows

Some things seem appeared to have changed in batch scripts on Windows 8, and the solution above by DGG now causes the Command Prompt to crash.

The following solution worked for me:

@echo off
set /a n=0
:repeat
set /a n+=1
echo 192.168.1.%n%
ping -n 1 -w 500 192.168.1.%n% | FIND /i "Reply">>ipaddresses.txt
if %n% lss 254 goto repeat
type ipaddresses.txt

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

As it is a multi-class problem, you have to use the categorical_crossentropy, the binary cross entropy will produce bogus results, most likely will only evaluate the first two classes only.

50% for a multi-class problem can be quite good, depending on the number of classes. If you have n classes, then 100/n is the minimum performance you can get by outputting a random class.

What are my options for storing data when using React Native? (iOS and Android)

Folks above hit the right notes for storage, though if you also need to consider any PII data that needs to be stored then you can also stash into the keychain using something like https://github.com/oblador/react-native-keychain since ASyncStorage is unencrypted. It can be applied as part of the persist configuration in something like redux-persist.

How to get the difference between two arrays of objects in JavaScript

I take a slightly more general-purpose approach, although similar in ideas to the approaches of both @Cerbrus and @Kasper Moerch. I create a function that accepts a predicate to determine if two objects are equal (here we ignore the $$hashKey property, but it could be anything) and return a function which calculates the symmetric difference of two lists based on that predicate:

a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]
b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]

var makeSymmDiffFunc = (function() {
    var contains = function(pred, a, list) {
        var idx = -1, len = list.length;
        while (++idx < len) {if (pred(a, list[idx])) {return true;}}
        return false;
    };
    var complement = function(pred, a, b) {
        return a.filter(function(elem) {return !contains(pred, elem, b);});
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

var myDiff = makeSymmDiffFunc(function(x, y) {
    return x.value === y.value && x.display === y.display;
});

var result = myDiff(a, b); //=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

It has one minor advantage over Cerebrus's approach (as does Kasper Moerch's approach) in that it escapes early; if it finds a match, it doesn't bother checking the rest of the list. If I had a curry function handy, I would do this a little differently, but this works fine.

Explanation

A comment asked for a more detailed explanation for beginners. Here's an attempt.

We pass the following function to makeSymmDiffFunc:

function(x, y) {
    return x.value === y.value && x.display === y.display;
}

This function is how we decide that two objects are equal. Like all functions that return true or false, it can be called a "predicate function", but that's just terminology. The main point is that makeSymmDiffFunc is configured with a function that accepts two objects and returns true if we consider them equal, false if we don't.

Using that, makeSymmDiffFunc (read "make symmetric difference function") returns us a new function:

        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };

This is the function we will actually use. We pass it two lists and it finds the elements in the first not in the second, then those in the second not in the first and combine these two lists.

Looking over it again, though, I could definitely have taken a cue from your code and simplified the main function quite a bit by using some:

var makeSymmDiffFunc = (function() {
    var complement = function(pred, a, b) {
        return a.filter(function(x) {
            return !b.some(function(y) {return pred(x, y);});
        });
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

complement uses the predicate and returns the elements of its first list not in its second. This is simpler than my first pass with a separate contains function.

Finally, the main function is wrapped in an immediately invoked function expression (IIFE) to keep the internal complement function out of the global scope.


Update, a few years later

Now that ES2015 has become pretty well ubiquitous, I would suggest the same technique, with a lot less boilerplate:

const diffBy = (pred) => (a, b) => a.filter(x => !b.some(y => pred(x, y)))
const makeSymmDiffFunc = (pred) => (a, b) => diffBy(pred)(a, b).concat(diffBy(pred)(b, a))

const myDiff = makeSymmDiffFunc((x, y) => x.value === y.value && x.display === y.display)

const result = myDiff(a, b)
//=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

How to get english language word database?

You can find what you need on infochimps.org.

They have a list of 350,000 simple (ie non-compound) words available for free download.

Word List - 350,000+ Simple English Words

Regarding other languages, you might want to poke around on Wiktionary. Here is a link to all the database backups - the information isnt organized so likely but if they have a language, you can download the data in SQL format.

Run parallel multiple commands at once in the same terminal

To run multiple commands just add && between two commands like this: command1 && command2

And if you want to run them in two different terminals then you do it like this:

gnome-terminal -e "command1" && gnome-terminal -e "command2"

This will open 2 terminals with command1 and command2 executing in them.

Hope this helps you.

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

What would be the Unicode character for big bullet in the middle of the character?

Here's full list of black dotlikes from unicode

● - &#9679; - Black Circle
⏺ - &#9210; - Black Circle for Record
⚫ - &#9899; - Medium Black Circle
⬤ - &#11044; - Black Large Circle
⧭ - &#10733; - Black Circle with Down Arrow
🞄 - &#128900; - Black Slightly Small Circle
• - &#8226; - Bullet (also • - &#149; - Message Waiting)
∙ - &#8729; - Bullet Operator
⋅ - &#8901; - Dot Operator (also · - &#183; - Middle Dot)
🌑 - &#127761; - New Moon Symbol

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

How to grant remote access permissions to mysql server for user?

In my case I was trying to connect to a remote mysql server on cent OS. After going through a lot of solutions (granting all privileges, removing ip bindings,enabling networking) problem was still not getting solved.

As it turned out, while looking into various solutions,I came across iptables, which made me realize mysql port 3306 was not accepting connections.

Here is a small note on how I checked and resolved this issue.

  • Checking if port is accepting connections:
telnet (mysql server ip) [portNo]

-Adding ip table rule to allow connections on the port:

iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT

-Would not recommend this for production environment, but if your iptables are not configured properly, adding the rules might not still solve the issue. In that case following should be done:

service iptables stop

Hope this helps.

How to use both onclick and target="_blank"

The window.open method is prone to cause popup blockers to complain

A better approach is:

Put a form in the webpage with an id

<form action="theUrlToGoTo" method="post" target="yourTarget" id="yourFormName"> </form>

Then use:

function openYourRequiredPage() {
var theForm = document.getElementById("yourFormName");
theForm.submit();

}

and

onclick="Javascript: openYourRequiredPage()"

You can use

method="post"

or

method="get"

As you wish

QComboBox - set selected item based on the item's data

You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.

Here is a little example :

/* Create the comboBox */
QComboBox   *_comboBox = new QComboBox;

/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");

/* Populate the comboBox */
_comboBox->addItems(stringsList);

/* Create the label */
QLabel *label = new QLabel;

/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
    label->setText("Text2 not found !");
else
    label->setText(QString("Text2's index is ")
                   .append(QString::number(_comboBox->findText("Text2"))));

/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);

What is "Advanced" SQL?

Some "Advanced" features

  • recursive queries
  • windowing/ranking functions
  • pivot and unpivot
  • performance tuning

How to determine when Fragment becomes visible in ViewPager

How to determine when Fragment becomes visible in ViewPager

You can do the following by overriding setUserVisibleHint in your Fragment:

public class MyFragment extends Fragment {
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
        }
        else {
        }
    }
}

jQuery, get html of a whole element

Differences might not be meaningful in a typical use case, but using the standard DOM functionality

$("#el")[0].outerHTML

is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

/* 
 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
 */
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  
};

What's a .sh file?

sh files are unix (linux) shell executables files, they are the equivalent (but much more powerful) of bat files on windows.

So you need to run it from a linux console, just typing its name the same you do with bat files on windows.

Caching a jquery ajax response in javascript/browser

I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache.

I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage which will help others who may want to use localStorage instead of localCache for caching.

Ajax Call:

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    url: url,
    data: '{"Id":"' + Id + '"}',
    cache: true, //It must "true" if you want to cache else "false"
    //async: false,
    success: function (data) {
        var resData = JSON.parse(data);
        var Info = resData.Info;
        if (Info) {
            customerName = Info.FirstName;
        }
    },
    error: function (xhr, textStatus, error) {
        alert("Error Happened!");
    }
});

To store data into localStorage:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
    var success = originalOptions.success || $.noop,
        url = originalOptions.url;

    options.cache = false; //remove jQuery cache as we have our own localStorage
    options.beforeSend = function () {
        if (localStorage.getItem(url)) {
            success(localStorage.getItem(url));
            return false;
        }
        return true;
    };
    options.success = function (data, textStatus) {
        var responseData = JSON.stringify(data.responseJSON);
        localStorage.setItem(url, responseData);
        if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
    };
}
});

If you want to remove localStorage, use following statement wherever you want:

localStorage.removeItem("Info");

Hope it helps others!

Angularjs autocomplete from $http

Use angular-ui-bootstrap's typehead.

It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.

(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)

What's the difference between ISO 8601 and RFC 3339 Date Formats?

You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:

http://tools.ietf.org/html/rfc3339

How to check for empty value in Javascript?

First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).

Also, for your if-condition, this should suffice:

if (!timetemp[0].value) {
    // The value is empty.
}
else {
    // The value is not empty.
}

The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.

Select from where field not equal to Mysql Php

Or can also insert the statement inside bracket.

SELECT * FROM tablename WHERE NOT (columnA = 'x')

python: SyntaxError: EOL while scanning string literal

In this case, three single quotations or three double quotations both will work! For example:

    """Parameters:
    ...Type something.....
    .....finishing statement"""

OR

    '''Parameters:
    ...Type something.....
    .....finishing statement'''

MSVCP140.dll missing

That usually means that your friend does not have the Microsoft redistributable for Visual C++. I am of course assuming you are using VC++ and not MingW or another compiler. Since your friend does not have VS installed as well there is no guarantee he has the redist installed.

VC++ Distro

Read text from response

If you http request is Post and request.Accept = "application/x-www-form-urlencoded"; then i think you can to get text of respone by code bellow:

var contentEncoding = response.Headers["content-encoding"];
                        if (contentEncoding != null && contentEncoding.Contains("gzip")) // cause httphandler only request gzip
                        {
                            // using gzip stream reader
                            using (var responseStreamReader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)))
                            {
                                strResponse = responseStreamReader.ReadToEnd();
                            }
                        }
                        else
                        {
                            // using ordinary stream reader
                            using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
                            {
                                strResponse = responseStreamReader.ReadToEnd();
                            }
                        }

How to change Jquery UI Slider handle

If you should need to replace the handle with something else entirely, rather than just restyling it:

You can specify custom handle elements by creating and appending the elements and adding the ui-slider-handle class before initialization.

Working Example

_x000D_
_x000D_
$('.slider').append('<div class="my-handle ui-slider-handle"><svg height="18" width="14"><path d="M13,9 5,1 A 10,10 0, 0, 0, 5,17z"/></svg></div>');_x000D_
_x000D_
$('.slider').slider({_x000D_
  range: "min",_x000D_
  value: 10_x000D_
});
_x000D_
.slider .ui-state-default {_x000D_
  background: none;_x000D_
}_x000D_
.slider.ui-slider .ui-slider-handle {_x000D_
  width: 14px;_x000D_
  height: 18px;_x000D_
  margin-left: -5px;_x000D_
  top: -4px;_x000D_
  border: none;_x000D_
  background: none;_x000D_
}_x000D_
.slider {_x000D_
  height: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />_x000D_
<div class="slider"></div>
_x000D_
_x000D_
_x000D_

Unix: How to delete files listed in a file

xargs -I{} sh -c 'rm {}' < 1.txt should do what you want. Be careful with this command as one incorrect entry in that file could cause a lot of trouble.

This answer was edited after @tdavies pointed out that the original did not do shell expansion.