Programs & Examples On #Map edit

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

the ON DUPLICATE KEY UPDATE clause is the best solution because: REPLACE does a DELETE followed by an INSERT so for an ever so slight period the record is removed creating the ever so slight possibility that a query could come back having skipped that if the page was viewed during the REPLACE query.

I prefer INSERT ... ON DUPLICATE UPDATE ... for that reason.

jmoz's solution is the best: though I prefer the SET syntax to the parentheses

INSERT INTO cache 
SET key = 'key', generation = 'generation'
ON DUPLICATE KEY 
UPDATE key = 'key', generation = (generation + 1)
;

How do I specify the JDK for a GlassFish domain?

Similar error with Glassfish 4.0 and several JDK installed:

SEVERE: GlassFish requires JDK 7, you are using JDK version 6.

There is no AS_JAVA reference in "C:\glassfish\config\asenv.bat" by default. After adding manually

set AS_JAVA=C:\Program Files\Java\jdk1.7.0_25 

it works.

How to get value from form field in django framework?

You can do this after you validate your data.

if myform.is_valid():
  data = myform.cleaned_data
  field = data['field']

Also, read the django docs. They are perfect.

Windows command to get service status?

Using pstools - in particular psservice and "query" - for example:

psservice query "serviceName"

jQuery how to find an element based on a data-attribute value?

I improved upon psycho brm's filterByData extension to jQuery.

Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.

(function ($) {

    $.fn.filterByData = function (prop, val) {
        var $self = this;
        if (typeof val === 'undefined') {
            return $self.filter(
                function () { return typeof $(this).data(prop) !== 'undefined'; }
            );
        }
        return $self.filter(
            function () { return $(this).data(prop) == val; }
        );
    };

})(window.jQuery);

Usage:

$('<b>').data('x', 1).filterByData('x', 1).length    // output: 1
$('<b>').data('x', 1).filterByData('x').length       // output: 1

_x000D_
_x000D_
// test data_x000D_
function extractData() {_x000D_
  log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);_x000D_
  log('data-prop .......... ' + $('div').filterByData('prop').length);_x000D_
  log('data-random ........ ' + $('div').filterByData('random').length);_x000D_
  log('data-test .......... ' + $('div').filterByData('test').length);_x000D_
  log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#b5').data('test', 'anyval');_x000D_
});_x000D_
_x000D_
// the actual extension_x000D_
(function($) {_x000D_
_x000D_
  $.fn.filterByData = function(prop, val) {_x000D_
    var $self = this;_x000D_
    if (typeof val === 'undefined') {_x000D_
      return $self.filter(_x000D_
_x000D_
        function() {_x000D_
          return typeof $(this).data(prop) !== 'undefined';_x000D_
        });_x000D_
    }_x000D_
    return $self.filter(_x000D_
_x000D_
      function() {_x000D_
        return $(this).data(prop) == val;_x000D_
      });_x000D_
  };_x000D_
_x000D_
})(window.jQuery);_x000D_
_x000D_
_x000D_
//just to quickly log_x000D_
function log(txt) {_x000D_
  if (window.console && console.log) {_x000D_
    console.log(txt);_x000D_
    //} else {_x000D_
    //  alert('You need a console to check the results');_x000D_
  }_x000D_
  $("#result").append(txt + "<br />");_x000D_
}
_x000D_
#bPratik {_x000D_
  font-family: monospace;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="bPratik">_x000D_
  <h2>Setup</h2>_x000D_
  <div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
  <div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
  <div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>_x000D_
  <div id="b4" data-test="val">Data added inline :: data-test="val"</div>_x000D_
  <div id="b5">Data will be added via jQuery</div>_x000D_
  <h2>Output</h2>_x000D_
  <div id="result"></div>_x000D_
_x000D_
  <hr />_x000D_
  <button onclick="extractData()">Reveal</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or the fiddle: http://jsfiddle.net/PTqmE/46/

Converting Integer to Long

Try to convertValue by Jackson

ObjectMapper mapper = new ObjectMapper()
Integer a = 1;
Long b = mapper.convertValue(a, Long.class)

How to adjust text font size to fit textview

I've been working on improving the excellent solution from speedplane, and came up with this. It manages the height, including setting the margin such that the text should be centered correctly vertically.

This uses the same function to get the width, as it seems to work the best, but it uses a different function to get the height, as the height isn't provided anywhere. There are some corrections that need to be made, but I figured out a way to do that, while looking pleasing to the eye.

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

public class FontFitTextView extends TextView {

    public FontFitTextView(Context context) {
        super(context);
        initialize();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    private void initialize() {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());

        //max size defaults to the initially specified text size unless it is too small
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth,int textHeight) 
    { 
        if (textWidth <= 0)
            return;
        int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
        int targetHeight = textHeight - this.getPaddingTop() - this.getPaddingBottom();
        float hi = Math.min(targetHeight,100);
        float lo = 2;
        final float threshold = 0.5f; // How close we have to be

        Rect bounds = new Rect();

        mTestPaint.set(this.getPaint());

        while((hi - lo) > threshold) {
            float size = (hi+lo)/2;
            mTestPaint.setTextSize(size);
            mTestPaint.getTextBounds(text, 0, text.length(), bounds);
            if((mTestPaint.measureText(text)) >= targetWidth || (1+(2*(size+(float)bounds.top)-bounds.bottom)) >=targetHeight) 
                hi = size; // too big
            else
                lo = size; // too small
        }
        // Use lo so that we undershoot rather than overshoot
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX,(float) lo);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
        int height = getMeasuredHeight();
        refitText(this.getText().toString(), parentWidth,height);
        this.setMeasuredDimension(parentWidth, height);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        refitText(text.toString(), this.getWidth(),this.getHeight());
    }

    @Override
    protected void onSizeChanged (int w, int h, int oldw, int oldh) {

        if (w != oldw) {
            refitText(this.getText().toString(), w,h);
        }
    }

    //Attributes
    private Paint mTestPaint;
}

?: operator (the 'Elvis operator') in PHP

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

What's the CMake syntax to set and use variables?

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or "What value does my variable have?"

First there are the "Normal Variables" and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory(), include(), macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the "Global Variables Cache". Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring. I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.

  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and "How to debug variable changes?"

To avoid pitfalls you should know the following about variables:

  • Local variables do hide cached variables if both have the same name
  • The find_... commands - if successful - do write their results as cached variables "so that no call will search again"
  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number.
    • False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if(MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1")
      • if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1")
      • So the best solution here would be - see above - to directly check for if(MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted."
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.

References

how to show calendar on text box click in html

You will need to use any javascript html calendar widget.

try this calendar view widget, just copy-paste some code shown in example there and thats it what you want.

Here is the link to Jquery Mobile date box - JQM datebox

How to convert an array to object in PHP?

You could also do this by adding (object) on left of variable to create a new object.

<?php
$a = Array
    ( 'status' => " text" );
var_dump($a);
$b = (object)$a;
var_dump($b);
var_dump($b->status);

http://codepad.org/9YmD1KsU

How to switch back to 'master' with git?

I'm trying to sort of get my head around what's going on over there. Is there anything IN your "example" folder? Git doesn't track empty folders.

If you branched and switched to your new branch then made a new folder and left it empty, and then did "git commit -a", you wouldn't get that new folder in the commit.

Which means it's untracked, which means checking out a different branch wouldn't remove it.

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

The same situation was with the previous versions. It's annoing that new versions com.google.android.gms libraries are always releasing before plugin, and it's impossible to use new version because is incompatible with old plugin. I don't know if plugin is now required (google docs sucks). I remember times when it wasn't. The only way is wait for new plugin version, or you can try to remove plugin dependencies, but as I said I'am not sure if gcm will work without it. What I know the main feature of 9.2.0 version is new Awareness API https://inthecheesefactory.com/blog/google-awareness-api-in-action/en, if you didn't need it, you can use 9.0.0 version without any trouble.

How to ensure that there is a delay before a service is started in systemd?

Instead of editing the bringup service, add a post-start delay to the service which it depends on. Edit cassandra.service like so:

ExecStartPost=/bin/sleep 30

This way the added sleep shouldn't slow down restarts of starting services that depend on it (though does slow down its own start, maybe that's desirable?).

What's the purpose of the LEA instruction?

Maybe just another thing about LEA instruction. You can also use LEA for fast multiplying registers by 3, 5 or 9.

LEA EAX, [EAX * 2 + EAX]   ;EAX = EAX * 3
LEA EAX, [EAX * 4 + EAX]   ;EAX = EAX * 5
LEA EAX, [EAX * 8 + EAX]   ;EAX = EAX * 9

Best way to define error codes/strings in Java?

As far as I am concerned, I prefer to externalize the error messages in a properties files. This will be really helpful in case of internationalization of your application (one properties file per language). It is also easier to modify an error message, and it won't need any re-compilation of the Java sources.

On my projects, generally I have an interface that contains errors codes (String or integer, it doesn't care much), which contains the key in the properties files for this error:

public interface ErrorCodes {
    String DATABASE_ERROR = "DATABASE_ERROR";
    String DUPLICATE_USER = "DUPLICATE_USER";
    ...
}

in the properties file:

DATABASE_ERROR=An error occurred in the database.
DUPLICATE_USER=The user already exists.
...

Another problem with your solution is the maintenability: you have only 2 errors, and already 12 lines of code. So imagine your Enumeration file when you will have hundreds of errors to manage!

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

This one also works

  1. Remove the "php.executablePath" line from the VS code settings.

  2. Then add the xampp php path to the System variables

enter image description here

enter image description here

After that restart the Visual Studio Code

Getting output of system() calls in Ruby

The straightforward way to do this correctly and securely is to use Open3.capture2(), Open3.capture2e(), or Open3.capture3().

Using ruby's backticks and its %x alias are NOT SECURE UNDER ANY CIRCUMSTANCES if used with untrusted data. It is DANGEROUS, plain and simple:

untrusted = "; date; echo"
out = `echo #{untrusted}`                              # BAD

untrusted = '"; date; echo"'
out = `echo "#{untrusted}"`                            # BAD

untrusted = "'; date; echo'"
out = `echo '#{untrusted}'`                            # BAD

The system function, in contrast, escapes arguments properly if used correctly:

ret = system "echo #{untrusted}"                       # BAD
ret = system 'echo', untrusted                         # good

Trouble is, it returns the exit code instead of the output, and capturing the latter is convoluted and messy.

The best answer in this thread so far mentions Open3, but not the functions that are best suited for the task. Open3.capture2, capture2e and capture3 work like system, but returns two or three arguments:

out, err, st = Open3.capture3("echo #{untrusted}")     # BAD
out, err, st = Open3.capture3('echo', untrusted)       # good
out_err, st  = Open3.capture2e('echo', untrusted)      # good
out, st      = Open3.capture2('echo', untrusted)       # good
p st.exitstatus

Another mentions IO.popen(). The syntax can be clumsy in the sense that it wants an array as input, but it works too:

out = IO.popen(['echo', untrusted]).read               # good

For convenience, you can wrap Open3.capture3() in a function, e.g.:

#
# Returns stdout on success, false on failure, nil on error
#
def syscall(*cmd)
  begin
    stdout, stderr, status = Open3.capture3(*cmd)
    status.success? && stdout.slice!(0..-(1 + $/.size)) # strip trailing eol
  rescue
  end
end

Example:

p system('foo')
p syscall('foo')
p system('which', 'foo')
p syscall('which', 'foo')
p system('which', 'which')
p syscall('which', 'which')

Yields the following:

nil
nil
false
false
/usr/bin/which         <— stdout from system('which', 'which')
true                   <- p system('which', 'which')
"/usr/bin/which"       <- p syscall('which', 'which')

How to Create a real one-to-one relationship in SQL Server

A 1 to 1 relationship is very much possible. Even if the relationship diagram doesn't show the 1 to 1 relationship explicitly. If you implement it as below, it will function as a one to one relationship.

I will use a basic example to explain the concept where a single person can only have a single passport. This example works perfectly in MS Access. For the SQL Server version follow this link.

Remember that in MS Access, SQL scripts can only be run one at a time and not as displayed here in sequence.

CREATE TABLE Person
(
Pk_Person_Id INT PRIMARY KEY,
Name VARCHAR(255),
EmailId VARCHAR(255),
);

CREATE TABLE PassportDetails
(
Pk_Passport_Id INT PRIMARY KEY,
Passport_Number VARCHAR(255),
Fk_Person_Id INT NOT NULL UNIQUE, 
FOREIGN KEY(Fk_Person_Id) REFERENCES Person(Pk_Person_Id)
);

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

You need to manually filter input to constructors and setters. Well... you could use reflection but I wouldn't advise it. Part of the job of constructors and setters is to validate input. That can include things like:

public void setPrice(double price) {
  if (price < 0.0d) {
    throw new IllegalArgumentException("price cannot be negative " + price);
  }
  this.price = price;
}

and

public void setName(String name) {
  if (name == null) {
    throw new NullPointerException("name cannot be null");
  }
  this.name = name;
}

You could use wrapper functions for the actual check and throwing the exception.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

Why is Thread.Sleep so harmful

I agree with many here, but I also think it depends.

Recently I did this code:

private void animate(FlowLayoutPanel element, int start, int end)
{
    bool asc = end > start;
    element.Show();
    while (start != end) {
        start += asc ? 1 : -1;
        element.Height = start;
        Thread.Sleep(1);
    }
    if (!asc)
    {
        element.Hide();
    }
    element.Focus();
}

It was a simple animate-function, and I used Thread.Sleep on it.

My conclusion, if it does the job, use it.

How to Update Multiple Array Elements in mongodb

$[] operator selects all nested array ..You can update all array items with '$[]'

.update({"events.profile":10},{$set:{"events.$[].handled":0}},false,true)

Reference

CREATE DATABASE permission denied in database 'master' (EF code-first)

I have resolved this problem in my way. Try connection string in this way:

<add name="MFCConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MFC.mdf;Initial Catalog=MFC;Integrated Security=false;User ID=sa;Password=123"
  providerName="System.Data.SqlClient" />

remember to set default db from master to MFC (in your case, aspnet-test-2012615153521).

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

How to get index of object by its property in JavaScript?

If you're fine with using ES6. Arrays now have the findIndex function. Which means you can do something like this:

const index = Data.findIndex(item => item.name === 'John');

How do I use floating-point division in bash?

You could use bc by the -l option (the L letter)

RESULT=$(echo "$IMG_WIDTH/$IMG2_WIDTH" | bc -l)

Laravel Eloquent compare date from datetime field

You can get the all record of the date '2016-07-14' by using it

 whereDate('date','=','2016-07-14')

Or use the another code for dynamic date

whereDate('date',$date)

MSVCP120d.dll missing

Alternate approach : without installation of Redistributable package.

Check out in some github for the relevant dll, some people upload the reference dll for their application dependency.

you can download and use them in your project , I have used and run them successfully.

example : https://github.com/Emotiv/community-sdk/find/master

Finish an activity from another activity

I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me

I overrode onPause and called finish() inside that method.

What's the @ in front of a string in C#?

Copied from MSDN:

At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string @"C:\files.txt" will appear in the watch window as "C:\\files.txt".

Detect the Enter key in a text input field

$(".input1").on('keyup', function (e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
        // Do something
    }
});

// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.

Clear and refresh jQuery Chosen dropdown list

$("#idofBtn").click(function(){
        $('#idofdropdown').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#idofdropdown').append(newOption);
        $('#idofdropdown').trigger("chosen:updated");
    });

adb remount permission denied, but able to access super user in shell -- android

Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.

What is the difference between DTR/DSR and RTS/CTS flow control?

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

Find out free space on tablespace

The following query will help to find out free space of tablespaces in MB:

select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;

YouTube API to fetch all videos on a channel

Since everyone answering this question has problems due to the 500 video limit here's an alternate solution using youtube_dl in Python 3. Also, no API key is needed.

  1. Install youtube_dl: sudo pip3 install youtube-dl
  2. Find out your target channel's channel id. The ID is going to start with UC. Replace the C for Channel with U for Upload (i.e. UU...), this is the upload playlist.
  3. Use the playlist downloader feature from youtube-dl. Ideally you do NOT want to download every video in the playlist which is the default, but only the metadata.

Example (warning -- takes tens of minutes):

import youtube_dl, pickle

             # UCVTyTA7-g9nopHeHbeuvpRA is the channel id (1517+ videos)
PLAYLIST_ID = 'UUVTyTA7-g9nopHeHbeuvpRA'  # Late Night with Seth Meyers

with youtube_dl.YoutubeDL({'ignoreerrors': True}) as ydl:

    playd = ydl.extract_info(PLAYLIST_ID, download=False)

    with open('playlist.pickle', 'wb') as f:
        pickle.dump(playd, f, pickle.HIGHEST_PROTOCOL)

    vids = [vid for vid in playd['entries'] if 'A Closer Look' in vid['title']]
    print(sum('Trump' in vid['title'] for vid in vids), '/', len(vids))

ant warning: "'includeantruntime' was not set"

If you like me work from commandline the quick answer is executing

export ANT_OPTS=-Dbuild.sysclasspath=ignore

And then run your ant script again.

Find OpenCV Version Installed on Ubuntu

1) Direct Answer: Try this:

   sudo updatedb
   locate OpenCVConfig.cmake

For me, I get:

   /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

To see the version, you can try:

   cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

giving

    ....
   SET(OpenCV_VERSION 2.3.1)
    ....

2) Better Answer:

"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).

Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.

fastest way to export blobs from table into individual files

I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.

Original Method:

SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand

CLR Method:

declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)

C# Code for the CLR function

using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace BlobExport
{
    public class Functions
    {
      [SqlFunction]
      public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
      {        
        try
        {
          if (!binary.IsNull && !path.IsNull && !append.IsNull)
          {         
            var dir = Path.GetDirectoryName(path.Value);           
            if (!Directory.Exists(dir))              
              Directory.CreateDirectory(dir);            
              using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
            {
                byte[] byteArr = binary.Value;
                for (int i = 0; i < byteArr.Length; i++)
                {
                    fs.WriteByte(byteArr[i]);
                };
            }
            return "SUCCESS";
          }
          else
             "NULL INPUT";
        }
        catch (Exception ex)
        {          
          return ex.Message;
        }
      }
    }
}

Youtube API Limitations

Apart from other answer There are calculator provided by Youtube to check your usage. It is good to identify your usage. https://developers.google.com/youtube/v3/determine_quota_cost

enter image description here

Android how to convert int to String?

Use Integer.toString(tmpInt) instead.

Check for file exists or not in sql server?

You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:

set nocount on
declare cur cursor local fast_forward for
    (select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;

fetch from cur into @fullpath
while @@FETCH_STATUS = 0
    begin
        exec xp_fileexist @fullpath, @isExists out
        if @isExists = 1            
            print @fullpath + char(9) + char(9) + 'file exists'
        else            
            print @fullpath + char(9) + char(9) + 'file does not exists'
        fetch from cur into @fullpath
    end
close cur
deallocate cur

or you can put it in a tempTable if you want to integrate it in your frontend..

create proc GetFileStatus as
begin
    set nocount on
    create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
    declare cur cursor local fast_forward for
        (select filepath from Directory)
    open cur;
    declare @fullpath varchar(250);
    declare @isExists int;

    fetch from cur into @fullpath
    while @@FETCH_STATUS = 0
        begin
            exec xp_fileexist @fullpath, @isExists out
            if @isExists = 1                
                insert into #tempFileStatus values(@fullpath,'File exist')
            else
                insert into #tempFileStatus values(@fullpath,'File does not exists')
            fetch from cur into @fullpath
        end
    close cur
    deallocate cur
    select * from #tempFileStatus
    drop table #tempFileStatus
end

then call it using:

exec GetFileStatus

Getting a map() to return a list in Python 3.x

Converting my old comment for better visibility: For a "better way to do this" without map entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes and decode, a la bytes(list_of_ordinals).decode('ascii'). That gets you a str of the values, but if you need a list for mutability or the like, you can just convert it (and it's still faster). For example, in ipython microbenchmarks converting 45 inputs:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

If you leave it as a str, it takes ~20% of the time of the fastest map solutions; even converting back to list it's still less than 40% of the fastest map solution. Bulk convert via bytes and bytes.decode then bulk converting back to list saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1).

indexOf method in an object array?

Using the ES6 findIndex method, without lodash or any other libraries, you can write:

function deepIndexOf(arr, obj) {
  return arr.findIndex(function (cur) {
    return Object.keys(obj).every(function (key) {
      return obj[key] === cur[key];
    });
  });
}

This will compare the immediate properties of the object, but not recurse into the properties.

If your implementation doesn't provide findIndex yet (most don't), you can add a light polyfill that supports this search:

function deepIndexOf(arr, obj) {
  function findIndex = Array.prototype.findIndex || function (pred) {
    for (let i = 0; i < this.length; ++i) {
      if (pred.call(this, this[i], i)) {
        return i;
      }
    }

    return -1;
  }

  return findIndex.call(arr, function (cur) {
    return Object.keys(obj).every(function (key) {
      return obj[key] === cur[key];
    });
  });
}

(from my answer on this dupe)

How to change DataTable columns order

Try to use the DataColumn.SetOrdinal method. For example:

dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1); 

UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:

Extension method:

public static class DataTableExtensions
{
    public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
    {
        int columnIndex = 0;
        foreach(var columnName in columnNames)
        {
            table.Columns[columnName].SetOrdinal(columnIndex);
            columnIndex++;
        }
    }
}

Usage:

table.SetColumnsOrder("Qty", "Unit", "Id");

or

table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});

Lining up labels with radio buttons in bootstrap

This is all nicely lined up including the field label. Lining up the field label was the tricky part.

enter image description here

HTML Code:

<div class="form-group">
    <label class="control-label col-md-5">Create a</label>
    <div class="col-md-7">
        <label class="radio-inline control-label">
            <input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
        </label>
        <label class="radio-inline control-label">
            <input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
        </label>
    </div>
</div>

CSHTML / Razor Code:

<div class="form-group">
    @Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
    <div class="col-md-7">
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
        </label>
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
        </label>
    </div>
</div>

SQLAlchemy create_all() does not create tables

This is probably not the main reason why the create_all() method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

def get_db():
  if 'db' not in g:
    g.db = SQLAlchemy(current_app)
  return g.db

I also have a separate cli command that also does the create_all:

# tasks/db.py
from lib.db import get_db

@current_app.cli.command('init-db')
def init_db():
  db = get_db()
  db.create_all()

I also am using a application factory.

When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).

The fix that I came around to was to make sure that the db was a single global reference:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

db = None
def get_db():
  global db
  if not db:
    db = SQLAlchemy(current_app)
  return db

I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

It works for me.....

I went to the settings on my phone and deleted my gmail account then re-added and synced the account and it worked for me.

settings>accounts>delete account settings>accounts>add account>sync and follow screen prompts

hope it works for you, i was receiving the df-dferh-01 error as well and couldnt buy in app purchases and this did the trick

How to "git clone" including submodules?

Submodules parallel fetch aims at reducing the time required to fetch a repositories and all of its related submodules by enabling the fetching of multiple repositories at once. This can be accomplished by using the new --jobs option, e.g.:

git fetch --recurse-submodules --jobs=4

According to Git team, this can substantially speed up updating repositories that contain many submodules. When using --recurse-submodules without the new --jobs option, Git will fetch submodules one by one.

Source: http://www.infoq.com/news/2016/03/git28-released

Math functions in AngularJS bindings

If you're looking to do a simple round in Angular you can easily set the filter inside your expression. For example:

{{ val | number:0 }}

See this CodePen example & for other number filter options.

Angular Docs on using Number Filters

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

delete vs delete[] operators in C++

The operators delete and delete [] are used respectively to destroy the objects created with new and new[], returning to the allocated memory left available to the compiler's memory manager.

Objects created with new must necessarily be destroyed with delete, and that the arrays created with new[] should be deleted with delete[].

vector vs. list in STL

vector:

  • Contiguous memory.
  • Pre-allocates space for future elements, so extra space required beyond what's necessary for the elements themselves.
  • Each element only requires the space for the element type itself (no extra pointers).
  • Can re-allocate memory for the entire vector any time that you add an element.
  • Insertions at the end are constant, amortized time, but insertions elsewhere are a costly O(n).
  • Erasures at the end of the vector are constant time, but for the rest it's O(n).
  • You can randomly access its elements.
  • Iterators are invalidated if you add or remove elements to or from the vector.
  • You can easily get at the underlying array if you need an array of the elements.

list:

  • Non-contiguous memory.
  • No pre-allocated memory. The memory overhead for the list itself is constant.
  • Each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.
  • Never has to re-allocate memory for the whole list just because you add an element.
  • Insertions and erasures are cheap no matter where in the list they occur.
  • It's cheap to combine lists with splicing.
  • You cannot randomly access elements, so getting at a particular element in the list can be expensive.
  • Iterators remain valid even when you add or remove elements from the list.
  • If you need an array of the elements, you'll have to create a new one and add them all to it, since there is no underlying array.

In general, use vector when you don't care what type of sequential container that you're using, but if you're doing many insertions or erasures to and from anywhere in the container other than the end, you're going to want to use list. Or if you need random access, then you're going to want vector, not list. Other than that, there are naturally instances where you're going to need one or the other based on your application, but in general, those are good guidelines.

Comment shortcut Android Studio

Comment method like pro developers:

Windows/linux:

Line Comment : Ctrl + /

Block Comment : Ctrl + Shift

Method Commenting:

Type `/**` and press `Enter Key`

it will add the comment snippet like we see in standard documentation, give it a try this once.

/**
 * 
 * @param addOpacity
 */
public void setOpacityOnUserImage(boolean addOpacity) {
// Your business logic. 
}

Better way to remove specific characters from a Perl string

You could use the tr instead:

       $p =~ tr/fo//d;

will delete every f and every o from $p. In your case it should be:

       $p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d

See Perl's tr documentation.

tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Transliterates all occurrences of the characters found (or not found if the /c modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.

[…]

If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.

Scanner vs. BufferedReader

In currently latest JDK6 release/build (b27), the Scanner has a smaller buffer (1024 chars) as opposed to the BufferedReader (8192 chars), but it's more than sufficient.

As to the choice, use the Scanner if you want to parse the file, use the BufferedReader if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.

  • Parsing = interpreting the given input as tokens (parts). It's able to give back you specific parts directly as int, string, decimal, etc. See also all those nextXxx() methods in Scanner class.
  • Reading = dumb streaming. It keeps giving back you all characters, which you in turn have to manually inspect if you'd like to match or compose something useful. But if you don't need to do that anyway, then reading is sufficient.

How can I get query parameters from a URL in Vue.js?

You can get By Using this function.

console.log(this.$route.query.test)

When should I use git pull --rebase?

I don't think there's ever a reason not to use pull --rebase -- I added code to Git specifically to allow my git pull command to always rebase against upstream commits.

When looking through history, it is just never interesting to know when the guy/gal working on the feature stopped to synchronise up. It might be useful for the guy/gal while he/she is doing it, but that's what reflog is for. It's just adding noise for everyone else.

ERROR 1067 (42000): Invalid default value for 'created_at'

For Mysql8.0.18:

CURRENT_TIMESTAMP([fsp])

Remove "([fsp])", resolved my problem.

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

None of these answers really work. As others noted the Cors package will only use the Access-Control-Allow-Origin header if the request had an Origin header. But you can't generally just add an Origin header to the request because browsers may try to regulate that too.

If you want a quick and dirty way to allow cross site requests to a web api, it's really a lot easier to just write a custom filter attribute:

public class AllowCors : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext == null)
        {
            throw new ArgumentNullException("actionExecutedContext");
        }
        else
        {
            actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin");
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        }
        base.OnActionExecuted(actionExecutedContext);
    }
}

Then just use it on your Controller action:

[AllowCors]
public IHttpActionResult Get()
{
    return Ok("value");
}

I won't vouch for the security of this in general, but it's probably a lot safer than setting the headers in the web.config since this way you can apply them only as specifically as you need them.

And of course it is simple to modify the above to allow only certain origins, methods etc.

JavaScript private methods

var TestClass = function( ) {

    var privateProperty = 42;

    function privateMethod( ) {
        alert( "privateMethod, " + privateProperty );
    }

    this.public = {
        constructor: TestClass,

        publicProperty: 88,
        publicMethod: function( ) {
            alert( "publicMethod" );
            privateMethod( );
        }
    };
};
TestClass.prototype = new TestClass( ).public;


var myTestClass = new TestClass( );

alert( myTestClass.publicProperty );
myTestClass.publicMethod( );

alert( myTestClass.privateMethod || "no privateMethod" );

Similar to georgebrock but a little less verbose (IMHO) Any problems with doing it this way? (I haven't seen it anywhere)

edit: I realised this is kinda useless since every independent instantiation has its own copy of the public methods, thus undermining the use of the prototype.

Changing date format in R

This is really easy using package lubridate. All you have to do is tell R what format your date is already in. It then converts it into the standard format

nzd$date <- dmy(nzd$date)

that's it.

How do I add slashes to a string in Javascript?

if (!String.prototype.hasOwnProperty('addSlashes')) {
    String.prototype.addSlashes = function() {
        return this.replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
             .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
             .replace(/"/g, '&quot;')
             .replace(/\\/g, '\\\\')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
        }
}

Usage: alert(str.addSlashes());

ref: https://stackoverflow.com/a/9756789/3584667

Gradient text color

I don't exactly know how the stop stuff works. But I've got a gradient text example. Maybe this will help you out!

_you can also add more colors to the gradient if you want or just select other colors from the color generator

_x000D_
_x000D_
.rainbow2 {_x000D_
    background-image: -webkit-linear-gradient(left, #E0F8F7, #585858, #fff); /* For Chrome and Safari */_x000D_
    background-image:    -moz-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Fx (3.6 to 15) */_x000D_
    background-image:     -ms-linear-gradient(left, #E0F8F7, #585858, #fff); /* For pre-releases of IE 10*/_x000D_
    background-image:      -o-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Opera (11.1 to 12.0) */_x000D_
    background-image:         linear-gradient(to right, #E0F8F7, #585858, #fff); /* Standard syntax; must be last */_x000D_
    color:transparent;_x000D_
    -webkit-background-clip: text;_x000D_
    background-clip: text;_x000D_
}_x000D_
.rainbow {_x000D_
_x000D_
  background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  color:transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>_x000D_
<br />_x000D_
<span class="rainbow2">No rainbow text</span>
_x000D_
_x000D_
_x000D_

Django: multiple models in one template using forms

The MultiModelForm from django-betterforms is a convenient wrapper to do what is described in Gnudiff's answer. It wraps regular ModelForms in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.

# forms.py
from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile

User = get_user_model()

class UserEditForm(forms.ModelForm):
    class Meta:
        fields = ('email',)

class UserProfileForm(forms.ModelForm):
    class Meta:
        fields = ('favorite_color',)

class UserEditMultiForm(MultiModelForm):
    form_classes = {
        'user': UserEditForm,
        'profile': UserProfileForm,
    }

# views.py
from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm

User = get_user_model()

class UserSignupView(UpdateView):
    model = User
    form_class = UserEditMultiForm
    success_url = reverse_lazy('home')

    def get_form_kwargs(self):
        kwargs = super(UserSignupView, self).get_form_kwargs()
        kwargs.update(instance={
            'user': self.object,
            'profile': self.object.profile,
        })
        return kwargs

Prevent jQuery UI dialog from setting focus to first textbox

I had a similar problem and solved it by focusing on the dialog after open:

var $dialog = $("#pnlFiltros")
    .dialog({
        autoOpen: false,
        hide: "puff",                   
        width: dWidth,
        height: 'auto',
        draggable: true,
        resizable: true,
        closeOnScape : true,
        position: [x,y]                    
    });
$dialog.dialog('open');
$("#pnlFiltros").focus(); //focus on the div being dialogued (is that a word?)

But in my case the first element is an anchor, so I don't know if in your case that will leave the datepicker opened.

EDIT: only works on IE

Custom sort function in ng-repeat

Actually the orderBy filter can take as a parameter not only a string but also a function. From the orderBy documentation: https://docs.angularjs.org/api/ng/filter/orderBy):

function: Getter function. The result of this function will be sorted using the <, =, > operator.

So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:

$scope.myValueFunction = function(card) {
   return card.values.opt1 + card.values.opt2;
};

and then, in your template:

ng-repeat="card in cards | orderBy:myValueFunction"

Here is the working jsFiddle

The other thing worth noting is that orderBy is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy should be enough for most uses cases).

Converting a String array into an int Array in java

public static int[] strArrayToIntArray(String[] a){
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        b[i] = Integer.parseInt(a[i]);
    }

    return b;
}

This is a simple function, that should help you. You can use him like this:

int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);

How to load up CSS files using Javascript?

Here's a one line example, that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:

document.head.innerHTML += '<link rel="stylesheet" href="css/style.css">';

Most browsers support it. See the browser compatibility.

Easier way to debug a Windows service

UPDATE

This approach is by far the easiest:

http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx

I leave my original answer below for posterity.


My services tend to have a class that encapsulates a Timer as I want the service to check at regular intervals whether there is any work for it to do.

We new up the class and call StartEventLoop() during the service start-up. (This class could easily be used from a console app too.)

The nice side-effect of this design is that the arguments with which you set up the Timer can be used to have a delay before the service actually starts working, so that you have time to attach a debugger manually.

p.s. How to attach the debugger manually to a running process...?

using System;
using System.Threading;
using System.Configuration;    

public class ServiceEventHandler
{
    Timer _timer;
    public ServiceEventHandler()
    {
        // get configuration etc.
        _timer = new Timer(
            new TimerCallback(EventTimerCallback)
            , null
            , Timeout.Infinite
            , Timeout.Infinite);
    }

    private void EventTimerCallback(object state)
    {
        // do something
    }

    public void StartEventLoop()
    {
        // wait a minute, then run every 30 minutes
        _timer.Change(TimeSpan.Parse("00:01:00"), TimeSpan.Parse("00:30:00");
    }
}

Also I used to do the following (already mentioned in previous answers but with the conditional compiler [#if] flags to help avoid it firing in a Release build).

I stopped doing it this way because sometimes we'd forget to build in Release and have a debugger break in an app running on a client demo (embarrasing!).

#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
{
    System.Diagnostics.Debugger.Break();
}
#endif

how to use font awesome in own css?

you can do so by using the :before or :after pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/

change your code to this

.lb-prev:hover {
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
   text-decoration: none;
}

.lb-prev:before {
    font-family: FontAwesome;
    content: "\f053";
    font-size: 30px;
}

do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.

Also, google sets in its response header an 'X-Frame-Options' of SAMEORIGIN.

Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.

So, the only option is to make the request from your server to see if you can display the site in your IFrame.

So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.

How do I trim whitespace from a string?

I wanted to remove the too-much spaces in a string (also in between the string, not only in the beginning or end). I made this, because I don't know how to do it otherwise:

string = "Name : David         Account: 1234             Another thing: something  " 

ready = False
while ready == False:
    pos = string.find("  ")
    if pos != -1:
       string = string.replace("  "," ")
    else:
       ready = True
print(string)

This replaces double spaces in one space until you have no double spaces any more

Alphabet range in Python

Print the Upper and Lower case alphabets in python using a built-in range function

def upperCaseAlphabets():
    print("Upper Case Alphabets")
    for i in range(65, 91):
        print(chr(i), end=" ")
    print()

def lowerCaseAlphabets():
    print("Lower Case Alphabets")
    for i in range(97, 123):
        print(chr(i), end=" ")

upperCaseAlphabets();
lowerCaseAlphabets();

Extract time from date String

let datestring = "2017-02-14 02:16:28"

let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full

formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

Add JVM options in Tomcat

if you want to set jvm args on eclipse you can use below:

see below two links to accomplish it:

  1. eclipse setting to pass jvm args to java
  2. eclipse setting to pass jvm args to java and adding to run config on eclipse

And for Tomcat you can create a setenv.bat file in bin folder of Tomcat and add below lines to it :

echo "hello im starting setenv"
set CATALINA_OPTS=-DNLP.home=${NLP.home} -Dhostname=${hostname}

Trim to remove white space

Why not try this?

html:

<p>
  a b c
</p>

js:

$("p").text().trim();

Get domain name from given url

I made a small treatment after the URI object creation

 if (url.startsWith("http:/")) {
        if (!url.contains("http://")) {
            url = url.replaceAll("http:/", "http://");
        }
    } else {
        url = "http://" + url;
    }
    URI uri = new URI(url);
    String domain = uri.getHost();
    return domain.startsWith("www.") ? domain.substring(4) : domain;

How to Lazy Load div background images

Lazy loading images using above mentioned plugins uses conventional way of attaching listener to scroll events or by making use of setInterval and is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.

Use Lozad.js (just 569 bytes with no dependencies), which uses InteractionObserver to lazy load images performantly.

'dependencies.dependency.version' is missing error, but version is managed in parent

You must build parent module before doing child module.

Change value of input placeholder via model?

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

Should I use Python 32bit or Python 64bit

64 bit version will allow a single process to use more RAM than 32 bit, however you may find that the memory footprint doubles depending on what you are storing in RAM (Integers in particular).

For example if your app requires > 2GB of RAM, so you switch from 32bit to 64bit you may find that your app is now requiring > 4GB of RAM.

Check whether all of your 3rd party modules are available in 64 bit, otherwise it may be easier to stick to 32bit in the meantime

Python: Random numbers into a list

xrange() will not work for 3.x.

numpy.random.randint().tolist() is a great alternative for integers in a specified interval:

 #[In]:
import numpy as np
np.random.seed(123) #option for reproducibility
np.random.randint(low=0, high=100, size=10).tolist()

#[Out:]

[66, 92, 98, 17, 83, 57, 86, 97, 96, 47]

You also have np.random.uniform() for floats:

#[In]:
np.random.uniform(low=0, high=100, size=10).tolist()

#[Out]:
[69.64691855978616,
28.613933495037948,
22.68514535642031,
55.13147690828912,
71.94689697855631,
42.3106460124461,
98.07641983846155,
68.48297385848633,
48.09319014843609,
39.211751819415056]

How can I open a website in my web browser using Python?

Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")

Postgresql query between date ranges

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'

Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.

How to set up file permissions for Laravel?

As posted already

All you need to do is to give ownership of the folders to Apache :

but I added -R for chown command: sudo chown -R www-data:www-data /path/to/your/project/vendor sudo chown -R www-data:www-data /path/to/your/project/storage

How to set the size of button in HTML

Do you mean something like this?

HTML

<button class="test"></button>

CSS

.test{
    height:200px;
    width:200px;
}

If you want to use inline CSS instead of an external stylesheet, see this:

<button style="height:200px;width:200px"></button>

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:

 byte -> short -> int -> long -> float -> double. 

The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

What is the use of the @Temporal annotation in Hibernate?

I use Hibernate 5.2 and @Temporal is not required anymore.
java.util.date, sql.date, time.LocalDate are stored into DB with appropriate datatype as Date/timestamp.

How to test if list element exists?

Here is a performance comparison of the proposed methods in other answers.

> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo), 
                                 is.null(foo[['k']]), 
                                 exists('k', where = foo))
Unit: nanoseconds
                     expr  min   lq    mean median   uq   max neval cld
      "k" %in% names(foo)  467  933 1064.31    934  934 10730   100  a 
      is.null(foo[["k"]])    0    0  168.50      1  467  3266   100  a 
 exists("k", where = foo) 6532 6998 7940.78   7232 7465 56917   100   b

If you are planing to use the list as a fast dictionary accessed many times, then the is.null approach might be the only viable option. I assume it is O(1), while the %in% approach is O(n)?

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

No. The HTML 5 spec mentions:

The method and formmethod content attributes are enumerated attributes with the following keywords and states:

The keyword get, mapping to the state GET, indicating the HTTP GET method. The GET method should only request and retrieve data and should have no other effect.

The keyword post, mapping to the state POST, indicating the HTTP POST method. The POST method requests that the server accept the submitted form's data to be processed, which may result in an item being added to a database, the creation of a new web page resource, the updating of the existing page, or all of the mentioned outcomes.

The keyword dialog, mapping to the state dialog, indicating that submitting the form is intended to close the dialog box in which the form finds itself, if any, and otherwise not submit.

The invalid value default for these attributes is the GET state

I.e. HTML forms only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly.

However, GET, POST, PUT and DELETE are supported by the implementations of XMLHttpRequest (i.e. AJAX calls) in all the major web browsers (IE, Firefox, Safari, Chrome, Opera).

Callback after all asynchronous forEach callbacks are completed

You shouldn't need a callback for iterating through a list. Just add the end() call after the loop.

posts.forEach(function(v, i){
   res.write(v + ". Index " + i);
});
res.end();

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my case, I had this javascript on the form submit:

$('form').submit(function () {
    $('input').prop('disabled', true);
});

This was removing the hidden RequestVerificationToken from the form being submitted. I changed that to:

$('form').submit(function () {
    $('input[type=submit]').prop('disabled', true);
    $('input[type=text]').prop('readonly', true);
    $('input[type=password]').prop('readonly', true);
});

... and it worked fine.

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

Any shortcut to initialize all array elements to zero?

The int values are already zero after initialization, as everyone has mentioned. If you have a situation where you actually do need to set array values to zero and want to optimize that, use System.arraycopy:

static private int[] zeros = new float[64];
...
int[] values = ...
if (zeros.length < values.length) zeros = new int[values.length];
System.arraycopy(zeros, 0, values, 0, values.length);

This uses memcpy under the covers in most or all JRE implementations. Note the use of a static like this is safe even with multiple threads, since the worst case is multiple threads reallocate zeros concurrently, which doesn't hurt anything.

You could also use Arrays.fill as some others have mentioned. Arrays.fill could use memcpy in a smart JVM, but is probably just a Java loop and the bounds checking that entails.

Benchmark your optimizations, of course.

How to get the current logged in user Id in ASP.NET Core

use can use

string userid = User.FindFirst("id").Value;

for some reason NameIdentifier now retrieve the username (.net core 2.2)

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

Cannot use a leading ../ to exit above the top directory

I got same problem... and I did it.

My code before:

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

And the problem solved after I changed my code into this:

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

So I think "href=../" is not allowed, because I don't have problem when I use "../" in "src=../"

Regex match everything after question mark?

str.replace(/^.+?\"|^.|\".+/, '');

This is sometimes bad to use when you wanna select what else to remove between "" and you cannot use it more than twice in one string. All it does is select whatever is not in between "" and replace it with nothing.

Even for me it is a bit confusing, but ill try to explain it. ^.+? (not anything OPTIONAL) till first " then | Or/stop (still researching what it really means) till/at ^. has selected nothing until before the 2nd " using (| stop/at). And select all that comes after with .+.

Is it possible to use JS to open an HTML select to show its option list?

I'm fairly certain the answer is: No. You can select options with JavaScript but not open the select. You'd have to use a custom solution.

Getting the .Text value from a TextBox

if(sender is TextBox) {
 var text = (sender as TextBox).Text;
}

Is there a /dev/null on Windows?

NUL works programmatically as well. E.g. the following:

freopen("NUL", "w", stderr);

works as expected without creating a file. (MSVC++ 12.0)

How different is Objective-C from C++?

Objective-C is a more perfect superset of C. In C and Objective-C implicit casting from void* to a struct pointer is allowed.

Foo* bar = malloc(sizeof(Foo));

C++ will not compile unless the void pointer is explicitly cast:

Foo* bar = (Foo*)malloc(sizeof(Foo));

The relevance of this to every day programming is zero, just a fun trivia fact.

How Do I Take a Screen Shot of a UIView?

iOS 7 has a new method that allows you to draw a view hierarchy into the current graphics context. This can be used to get an UIImage very fast.

I implemented a category method on UIView to get the view as an UIImage:

- (UIImage *)pb_takeSnapshot {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);

    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];

    // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

It is considerably faster then the existing renderInContext: method.

Reference: https://developer.apple.com/library/content/qa/qa1817/_index.html

UPDATE FOR SWIFT: An extension that does the same:

extension UIView {

    func pb_takeSnapshot() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

        // old style: layer.renderInContext(UIGraphicsGetCurrentContext())

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

UPDATE FOR SWIFT 3

    UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)

    drawHierarchy(in: self.bounds, afterScreenUpdates: true)

    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image

Creating Scheduled Tasks

You can use Task Scheduler Managed Wrapper:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}

Alternatively you can use native API or go for Quartz.NET. See this for details.

How to select all columns, except one column in pandas?

I think a nice solution is with the function filter of pandas and regex (match everything except "b"):

df.filter(regex="^(?!b$)")

What should a Multipart HTTP request with multiple files look like?

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to read the post request parameters using JavaScript

We can collect the form params submitted using POST with using serialize concept.

Try this:

$('form').serialize(); 

Just enclose it alert, it displays all the parameters including hidden.

How to write and save html file in python?

You can do it using write() :

#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()

How to add a ListView to a Column in Flutter?

You can check console output. It prints error:

The following assertion was thrown during performResize(): Horizontal viewport was given unbounded height. Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.

You need to add height constraint to your horizontal list. E.g. wrap in Container with height:

Container(
  height: 44.0,
  child: ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      RaisedButton(
        onPressed: null,
        child: Text("Facebook"),
      ),
      Padding(padding: EdgeInsets.all(5.00)),
      RaisedButton(
        onPressed: null,
        child: Text("Google"),
      )
    ],
  ),
)

Android : How to set onClick event for Button in List item of ListView

In getview method put listener outside checking the view..try to follow this..it worked in my case..How to Increase or decrease value of edittext in listview's each row?

Laravel 5 - How to access image uploaded in storage within View?

One option would be to create a symbolic link between a subfolder in your storage directory and public directory.

For example

ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars

This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.

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_

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

Initialize a byte array to a certain value, other than the default null?

var array = Encoding.ASCII.GetBytes(new string(' ', 100));

Java 8 Streams: multiple filters vs. complex condition

This test shows that your second option can perform significantly better. Findings first, then the code:

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=4142, min=29, average=41.420000, max=82}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=13315, min=117, average=133.150000, max=153}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10320, min=82, average=103.200000, max=127}

now the code:

enum Gender {
    FEMALE,
    MALE
}

static class User {
    Gender gender;
    int age;

    public User(Gender gender, int age){
        this.gender = gender;
        this.age = age;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

static long test1(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter((u) -> u.getGender() == Gender.FEMALE && u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test2(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(u -> u.getGender() == Gender.FEMALE)
            .filter(u -> u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test3(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(((Predicate<User>) u -> u.getGender() == Gender.FEMALE).and(u -> u.getAge() % 2 == 0))
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

public static void main(String... args) {
    int size = 10000000;
    List<User> users =
    IntStream.range(0,size)
            .mapToObj(i -> i % 2 == 0 ? new User(Gender.MALE, i % 100) : new User(Gender.FEMALE, i % 100))
            .collect(Collectors.toCollection(()->new ArrayList<>(size)));
    repeat("one filter with predicate of form u -> exp1 && exp2", users, Temp::test1, 100);
    repeat("two filters with predicates of form u -> exp1", users, Temp::test2, 100);
    repeat("one filter with predicate of form predOne.and(pred2)", users, Temp::test3, 100);
}

private static void repeat(String name, List<User> users, ToLongFunction<List<User>> test, int iterations) {
    System.out.println(name + ", list size " + users.size() + ", averaged over " + iterations + " runs: " + IntStream.range(0, iterations)
            .mapToLong(i -> test.applyAsLong(users))
            .summaryStatistics());
}

When use getOne and findOne methods Spring Data JPA

1. Why does the getOne(id) method fail?

See this section in the docs. You overriding the already in place transaction might be causing the issue. However, without more info this one is difficult to answer.

2. When I should use the getOne(id) method?

Without digging into the internals of Spring Data JPA, the difference seems to be in the mechanism used to retrieve the entity.

If you look at the JavaDoc for getOne(ID) under See Also:

See Also:
EntityManager.getReference(Class, Object)

it seems that this method just delegates to the JPA entity manager's implementation.

However, the docs for findOne(ID) do not mention this.

The clue is also in the names of the repositories. JpaRepository is JPA specific and therefore can delegate calls to the entity manager if so needed. CrudRepository is agnostic of the persistence technology used. Look here. It's used as a marker interface for multiple persistence technologies like JPA, Neo4J etc.

So there's not really a 'difference' in the two methods for your use cases, it's just that findOne(ID) is more generic than the more specialised getOne(ID). Which one you use is up to you and your project but I would personally stick to the findOne(ID) as it makes your code less implementation specific and opens the doors to move to things like MongoDB etc. in the future without too much refactoring :)

Replace "\\" with "\" in a string in C#

Regex.Unescape(string) method converts any escaped characters in the input string.

The Unescape method performs one of the following two transformations:

  1. It reverses the transformation performed by the Escape method by removing the escape character ("\") from each character escaped by the method. These include the \, *, +, ?, |, {, [, (,), ^, $, ., #, and white space characters. In addition, the Unescape method unescapes the closing bracket (]) and closing brace (}) characters.

  2. It replaces the hexadecimal values in verbatim string literals with the actual printable characters. For example, it replaces @"\x07" with "\a", or @"\x0A" with "\n". It converts to supported escape characters such as \a, \b, \e, \n, \r, \f, \t, \v, and alphanumeric characters.

string str = @"a\\b\\c";
var output = System.Text.RegularExpressions.Regex.Unescape(str);

Reference:

https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.unescape?view=netframework-4.8

How to get a list of installed android applications and pick one to run

If there are multiple launchers in a one package above code has a problem. Eg: on LG Optimus Facebook for LG, MySpace for LG, Twitter for LG contains in a one package name SNS and if you use above SNS will repeat. After hours of research I came with below code. Seems to work well.

private List<String> getInstalledComponentList()
            throws NameNotFoundException {
        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> ril = getPackageManager().queryIntentActivities(mainIntent, 0);
        List<String> componentList = new ArrayList<String>();
        String name = null;

        for (ResolveInfo ri : ril) {
            if (ri.activityInfo != null) {
                Resources res = getPackageManager().getResourcesForApplication(ri.activityInfo.applicationInfo);
                if (ri.activityInfo.labelRes != 0) {
                    name = res.getString(ri.activityInfo.labelRes);
                } else {
                    name = ri.activityInfo.applicationInfo.loadLabel(
                            getPackageManager()).toString();
                }
                componentList.add(name);
            }
        }
        return componentList;
    }

How to use SQL Select statement with IF EXISTS sub query?

You can also use ISNULL and a select statement to get this result

SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1

How to remove unused C/C++ symbols with GCC and ld?

You can use strip binary on object file(eg. executable) to strip all symbols from it.

Note: it changes file itself and don't create copy.

Asp.net 4.0 has not been registered

If ASP.NET 4.0 is not registered with IIS

*****Use this step if u cant access using run command*****

Go to

C Drive
-->>windows
-->>Microsoft.Net
-->>Framework
-->>v4.0.30319

(Choose whatever framework to register with IIS me selecting Framework 4)
-->>aspnet_regiis
(Double-click or right click & choose run as administrator)

AttributeError: 'module' object has no attribute 'urlopen'

This works in Python 2.x.

For Python 3 look in the docs:

import urllib.request

with urllib.request.urlopen("http://www.python.org") as url:
    s = url.read()
    # I'm guessing this would output the html source code ?
    print(s)

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

I use the following method in my project

-(NSArray*)networkErrorCodes
{
    static NSArray *codesArray;
    if (![codesArray count]){
        @synchronized(self){
            const int codes[] = {
                //kCFURLErrorUnknown,     //-998
                //kCFURLErrorCancelled,   //-999
                //kCFURLErrorBadURL,      //-1000
                //kCFURLErrorTimedOut,    //-1001
                //kCFURLErrorUnsupportedURL, //-1002
                //kCFURLErrorCannotFindHost, //-1003
                kCFURLErrorCannotConnectToHost,     //-1004
                kCFURLErrorNetworkConnectionLost,   //-1005
                kCFURLErrorDNSLookupFailed,         //-1006
                //kCFURLErrorHTTPTooManyRedirects,    //-1007
                kCFURLErrorResourceUnavailable,     //-1008
                kCFURLErrorNotConnectedToInternet,  //-1009
                //kCFURLErrorRedirectToNonExistentLocation,   //-1010
                kCFURLErrorBadServerResponse,               //-1011
                //kCFURLErrorUserCancelledAuthentication,     //-1012
                //kCFURLErrorUserAuthenticationRequired,      //-1013
                //kCFURLErrorZeroByteResource,        //-1014
                //kCFURLErrorCannotDecodeRawData,     //-1015
                //kCFURLErrorCannotDecodeContentData, //-1016
                //kCFURLErrorCannotParseResponse,     //-1017
                kCFURLErrorInternationalRoamingOff, //-1018
                kCFURLErrorCallIsActive,                //-1019
                //kCFURLErrorDataNotAllowed,              //-1020
                //kCFURLErrorRequestBodyStreamExhausted,  //-1021
                kCFURLErrorFileDoesNotExist,            //-1100
                //kCFURLErrorFileIsDirectory,             //-1101
                kCFURLErrorNoPermissionsToReadFile,     //-1102
                //kCFURLErrorDataLengthExceedsMaximum,     //-1103
            };
            int size = sizeof(codes)/sizeof(int);
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int i=0;i<size;++i){
                [array addObject:[NSNumber numberWithInt:codes[i]]];
            }
            codesArray = [array copy];
        }
    }
    return codesArray;
}

Then I just check the error code and show alert if it is in the list

if ([[self networkErrorCodes] containsObject:[NSNumber
numberWithInt:[error code]]]){ 
// Fire Alert View Here
}

But as you can see I commented out codes that I think does not fit to my definition of NO INTERNET. E.g the code of -1012 (Authentication fail.) You may edit the list as you like.

In my project I use it at username/password entering from user. And in my view (physical) network connection errors could be the only reason to show alert view in your network based app. In any other case (e.g. incorrect username/password pair) I prefer to do some custom user friendly animation, OR just repeat the failed attempt again without any attention of the user. Especially if the user didn't explicitly initiated a network call.

Regards to martinezdelariva for a link to documentation.

Multiple file upload in php

It's not that different from uploading one file - $_FILES is an array containing any and all uploaded files.

There's a chapter in the PHP manual: Uploading multiple files

If you want to enable multiple file uploads with easy selection on the user's end (selecting multiple files at once instead of filling in upload fields) take a look at SWFUpload. It works differently from a normal file upload form and requires Flash to work, though. SWFUpload was obsoleted along with Flash. Check the other, newer answers for the now-correct approach.

How to align 3 divs (left/center/right) inside another div?

Using Bootstrap 3 I create 3 divs of equal width (in 12 column layout 4 columns for each div). This way you can keep your central zone centered even if left/right sections have different widths (if they don't overflow their columns' space).

HTML:

<div id="container">
  <div id="left" class="col col-xs-4 text-left">Left</div>
  <div id="center" class="col col-xs-4 text-center">Center</div>
  <div id="right" class="col col-xs-4 text-right">Right</div>
</div>

CSS:

#container {
  border: 1px solid #aaa;
  margin: 10px;
  padding: 10px;
  height: 100px;
}
.col {
  border: 1px solid #07f;
  padding: 0;
}

CodePen

To create that structure without libraries I copied some rules from Bootstrap CSS.

HTML:

<div id="container">
  <div id="left" class="col">Left</div>
  <div id="center" class="col">Center</div>
  <div id="right" class="col">Right</div>
</div>

CSS:

* {
  box-sizing: border-box;
}
#container {
  border: 1px solid #aaa;
  margin: 10px;
  padding: 10px;
  height: 100px;
}
.col {
  float: left;
  width: 33.33333333%;
  border: 1px solid #07f;
  padding: 0;
}
#left {
  text-align: left;
}
#center {
  text-align: center;
}
#right {
  text-align: right;
}

CopePen

Hide all warnings in ipython

The accepted answer does not work in Jupyter (at least when using some libraries).

The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.

To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.

%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
    var s='Showing';  
    cssrules.empty()
    if(on) {
        s='Hiding';
        cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
    }
    e.text(s+' warnings (click to toggle)');
    on=!on;
}).click();
$(element).append(e);
})(true);

Style input element to fill remaining width of its container

Very easy trick is using a CSS calc formula. All modern browsers, IE9, wide range of mobile browsers should support this.

<div style='white-space:nowrap'>
  <span style='display:inline-block;width:80px;font-weight:bold'>
    <label for='field1'>Field1</label>
  </span>
  <input id='field1' name='field1' type='text' value='Some text' size='30' style='width:calc(100% - 80px)' />
</div>

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

undefined reference to `WinMain@16'

My situation was that I did not have a main function.

How to allow <input type="file"> to accept only image files?

Use the accept attribute of the input tag. So to accept only PNG's, JPEG's and GIF's you can use the following code:

_x000D_
_x000D_
<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
_x000D_
_x000D_
_x000D_

Or simply:

_x000D_
_x000D_
<input type="file" name="myImage" accept="image/*" />
_x000D_
_x000D_
_x000D_

Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.

It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports, this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.

For detailed browser support, see http://caniuse.com/#feat=input-file-accept

printf format specifiers for uint32_t and size_t

All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long is at least 32 bits, so %lu together with (unsigned long)k is always correct:

uint32_t k;
printf("%lu\n", (unsigned long)k);

size_t is trickier, which is why %zu was added in C99. If you can't use that, then treat it just like k (long is the biggest type in C89, size_t is very unlikely to be larger).

size_t sz;
printf("%zu\n", sz);  /* C99 version */
printf("%lu\n", (unsigned long)sz);  /* common C89 version */

If you don't get the format specifiers correct for the type you are passing, then printf will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Sort JavaScript object by key

The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.


See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:

All methods that iterate over property keys do so in the same order:

  1. First all Array indices, sorted numerically.
  2. Then all string keys (that are not indices), in the order in which they were created.
  3. Then all symbols, in the order in which they were created.

So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.

Here’s how you can sort an object by its keys/properties, alphabetically:

_x000D_
_x000D_
const unordered = {
  'b': 'foo',
  'c': 'bar',
  'a': 'baz'
};

console.log(JSON.stringify(unordered));
// ? '{"b":"foo","c":"bar","a":"baz"}'

const ordered = Object.keys(unordered).sort().reduce(
  (obj, key) => { 
    obj[key] = unordered[key]; 
    return obj;
  }, 
  {}
);

console.log(JSON.stringify(ordered));
// ? '{"a":"baz","b":"foo","c":"bar"}'
_x000D_
_x000D_
_x000D_

Use var instead of const for compatibility with ES5 engines.

Reverse ip, find domain names on ip address

You can use ping -a <ip> or nbtstat -A <ip>

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

#!/bin/bash

export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

bootstrap multiselect get selected values

In my case i was using jQuery validation rules with

submitHandler function and submitting the data as new FormData(form);

Select Option

<select class="selectpicker" id="branch" name="branch" multiple="multiple" title="Of Branch" data-size="6" required>
  <option disabled>Multiple Branch Select</option>
  <option value="Computer">Computer</option>
  <option value="Civil">Civil</option>
  <option value="EXTC">EXTC</option>
  <option value="ETRX">ETRX</option>
  <option value="Mechinical">Mechinical</option>
</select>

<input type="hidden" name="new_branch" id="new_branch">

Get the multiple selected value and set to new_branch input value & while submitting the form get value from new_branch

Just replace hidden with text to view on the output

<input type="text" name="new_branch" id="new_branch">

Script (jQuery / Ajax)

<script>
    $(document).ready(function() {

      $('#branch').on('change', function(){
          var selected = $(this).find("option:selected"); //get current selected value
          var arrSelected = []; //Array to store your multiple value in stack
          selected.each(function(){
            arrSelected.push($(this).val()); //Stack the value
          });
          $('#new_branch').val(arrSelected); //It will set the multiple selected value to input new_branch
      });

    });
</script>

How can I properly use a PDO object for a parameterized SELECT query

You can use the bindParam or bindValue methods to help prepare your statement. It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.

Check the clear, easy to read example below:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row_id = $check['id'];
    // do something
}

If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetchAll(PDO::FETCH_ASSOC);
    //$check will now hold an array of returned rows. 
    //let's say we need the second result, i.e. index of 1
    $row_id = $check[1]['id']; 
    // do something
}

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

Unicode character in PHP string

PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}

Or with an anonymous function expression instead of create_function:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
        return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
    }, $str);
}

Its usage:

$str = unicodeString("\u1000");

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

First create dir /var/run/mysqld

with command:

mkdir -p /var/run/mysqld

then add rigths to the dir

chown mysql:mysql /var/run/mysqld

after this try

mysql -u root

Select2 open dropdown on focus

For Version 3.5.4 (Aug 30, 2015 and earlier)

The current answer is only applicable to versions 3.5.4 and before, where select2 fired blur and focus events (select2-focus & select2-blur). It attaches a one-time use handler using $.one to catch the initial focus, and then reattaches it during blur for subsequent uses.

$('.select2').select2({})
  .one('select2-focus', OpenSelect2)
  .on("select2-blur", function (e) {
    $(this).one('select2-focus', OpenSelect2)
  })

function OpenSelect2() {
  var $select2 = $(this).data('select2');
  setTimeout(function() {
    if (!$select2.opened()) { $select2.open(); }
  }, 0);  
}

I tried both of @irvin-dominin-aka-edward's answers, but also ran into both problems (having to click the dropdown twice, and that Firefox throws 'event is not defined').

I did find a solution that seems to solve the two problems and haven't run into other issue yet. This is based on @irvin-dominin-aka-edward's answers by modifying the select2Focus function so that instead of executing the rest of the code right away, wrap it in setTimeout.

Demo in jsFiddle & Stack Snippets

_x000D_
_x000D_
$('.select2').select2({})_x000D_
  .one('select2-focus', OpenSelect2)_x000D_
  .on("select2-blur", function (e) {_x000D_
    $(this).one('select2-focus', OpenSelect2)_x000D_
  })_x000D_
_x000D_
function OpenSelect2() {_x000D_
  var $select2 = $(this).data('select2');_x000D_
  setTimeout(function() {_x000D_
    if (!$select2.opened()) { $select2.open(); }_x000D_
  }, 0);  _x000D_
}
_x000D_
body {_x000D_
  margin: 2em;_x000D_
}_x000D_
_x000D_
.form-control {_x000D_
  width: 200px;  _x000D_
  margin-bottom: 1em;_x000D_
  padding: 5px;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
select {_x000D_
  border: 1px solid #aaa;_x000D_
  border-radius: 4px;_x000D_
  height: 28px;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>_x000D_
_x000D_
  _x000D_
  <div class="form-control">_x000D_
    <label for="foods1" >Normal</label>_x000D_
    <select id="foods1" >_x000D_
      <option value=""></option>_x000D_
      <option value="1">Apple</option>_x000D_
      <option value="2">Banana</option>_x000D_
      <option value="3">Carrot</option>_x000D_
      <option value="4">Donut</option>_x000D_
    </select>_x000D_
</div>_x000D_
_x000D_
<div class="form-control">_x000D_
  <label for="foods2" >Select2</label>_x000D_
  <select id="foods2" class="select2" >_x000D_
    <option value=""></option>_x000D_
    <option value="1">Apple</option>_x000D_
    <option value="2">Banana</option>_x000D_
      <option value="3">Carrot</option>_x000D_
      <option value="4">Donut</option>_x000D_
    </select>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Invoking a PHP script from a MySQL trigger

That should be considered a very bad programming practice to call PHP code from a database trigger. If you will explain the task you are trying to solve using such "mad" tricks, we might provide a satisfying solution.

ADDED 19.03.2014:

I should have added some reasoning earlier, but only found time to do this now. Thanks to @cmc for an important remark. So, PHP triggers add the following complexities to your application:

  • Adds a certain degree of security problems to the application (external PHP script calls, permission setup, probably SELinux setup etc) as @Johan says.

  • Adds additional level of complexity to your application (to understand how database works you now need to know both SQL and PHP, not only SQL) and you will have to debug PHP also, not only SQL.

  • Adds additional point of failure to your application (PHP misconfiguration for example), which needs to be diagnosied also ( I think trigger needs to hold some debug code which will log somwewhere all insuccessful PHP interpreter calls and their reasons).

  • Adds additional point of performance analysis. Each PHP call is expensive, since you need to start interpreter, compile script to bytecode, execute it etc. So each query involving this trigger will execute slower. And sometimes it will be difficult to isolate query performance problems since EXPLAIN doesn't tell you anything about query being slower because of trigger routine performance. And I'm not sure how trigger time is dumped into slow query log.

  • Adds some problems to application testing. SQL can be tested pretty easily. But to test SQL + PHP triggers, you will have to apply some skill.

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

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

You can simply write:

<link rel="stylesheet" href="file.css">

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

java.lang.UnsupportedClassVersionError happens because of a higher JDK during compile time and lower JDK during runtime.

Here's the list of versions:

Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45

Change font size of UISegmentedControl

In swift 5,

let font = UIFont.systemFont(ofSize: 16)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

Flutter command not found

You can easily create a symbolic link as below,

sudo ln -s /opt/flutter/bin/flutter /usr/bin/flutter

I had moved flutter into /opt/ folder after downloading, so replace with the path you have flutter directory.

flutter command should work even after rebooting your machine.

Create an Excel file using vbscripts

This code creates the file temp.xls in the desktop but it uses the SpecialFolders property, which is very useful sometimes!

set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")

set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strDesktop & "\temp.xls")

Convert Java String to sql.Timestamp

You could use Timestamp.valueOf(String). The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...], so you might need to change the field separators in your incoming string.

Then again, if you're going to do that then you could just parse it yourself and use the setNanos method to store the microseconds.

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

Correct way to detach from a container without stopping it

If you do "docker attach "container id" you get into the container. To exit from the container without stopping the container you need to enter Ctrl+P+Q

Create an enum with string values

Why not just use the native way of accessing the strings of a enum.

enum e {
  WHY,
  NOT,
  USE,
  NATIVE
}

e[e.WHY] // this returns string 'WHY'

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

PHP: Limit foreach() statement?

you should use the break statement

usually it's use this way

$i = 0;
foreach($data as $key => $row){
    if(++$i > 2) break;
}

on the same fashion the continue statement exists if you need to skip some items.

Waiting for background processes to finish before exiting script

You can use kill -0 for checking whether a particular pid is running or not.

Assuming, you have list of pid numbers in a file called pid in pwd

while true;
do 
    if [ -s pid ] ; then
        for pid in `cat pid`
        do  
            echo "Checking the $pid"
            kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
        done
    else
        echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
        break
    fi
done

Bash foreach loop

Something like this would do:

xargs cat <filenames.txt

The xargs program reads its standard input, and for each line of input runs the cat program with the input lines as argument(s).

If you really want to do this in a loop, you can:

for fn in `cat filenames.txt`; do
    echo "the next file is $fn"
    cat $fn
done

python: restarting a loop

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

Rails :include vs. :joins

.joins will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again

:includes will eager load the included associations and add them in memory. :includes loads all the included tables attributes. If you call associations on include query result, it will not fire any queries

bootstrap 3 tabs not working properly

My problem was with extra </div> tag inside the first tab.

How to write to file in Ruby?

Zambri's answer found here is the best.

File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }

where your options for <OPTION> are:

r - Read only. The file must exist.

w - Create an empty file for writing.

a - Append to a file.The file is created if it does not exist.

r+ - Open a file for update both reading and writing. The file must exist.

w+ - Create an empty file for both reading and writing.

a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, w is preferable.

resize font to fit in a div (on one line)

Today I created a jQuery plugin called jQuery Responsive Headlines that does exactly what you want: it adjusts the font size of a headline to fit inside its containing element (a div, the body or whatever). There are some nice options that you can set to customize the behavior of the plugin and I have also taken the precaution to add support for Ben Altmans Throttle/Debounce functionality to increase performance and ease the load on the browser/computer when the user resizes the window. In it's most simple use case the code would look like this:

$('h1').responsiveHeadlines();

...which would turn all h1 on the page elements into responsive one-line headlines that adjust their sizes to the parent/container element.

You'll find the source code and a longer description of the plugin on this GitHub page.

Good luck!

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

Inspired by cyptus's answer I used

_dbContext.Database.CreateIfNotExists();

on EF6 before the first database contact (before DB seeding).

Insert variable values in the middle of a string

1 You can use string.Replace method

var sample = "testtesttesttest#replace#testtesttest";
var result = sample.Replace("#replace#", yourValue);

2 You can also use string.Format

var result = string.Format("your right part {0} Your left Part", yourValue);

3 You can use Regex class

Android Button click go to another xml page

There is more than one way to do this.

Here is a good resource straight from Google: http://developer.android.com/training/basics/firstapp/starting-activity.html

At developer.android.com, they have numerous tutorials explaining just about everything you need to know about android. They even provide detailed API for each class.

If that doesn't help, there are NUMEROUS different resources that can help you with this question and other android questions.

How can I alter a primary key constraint using SQL syntax?

In my case, I want to add a column to a Primary key (column4). I used this script to add column4

ALTER TABLE TableA
DROP CONSTRAINT [PK_TableA]

ALTER TABLE TableA
ADD CONSTRAINT [PK_TableA] PRIMARY KEY (
    [column1] ASC,
    [column2] ASC, 
    [column3] ASC,
    [column4] ASC
)

fatal error: Python.h: No such file or directory

If you're using Python 3.6 on Amazon Linux (based on RHEL, but the RHEL answers given here didn't work):

sudo yum install python36-devel

Java: How to convert a File object to a String object in java?

You can copy all contents of myhtml to String as follows:

Scanner myScanner = null;
try
{
    myScanner = new Scanner(myhtml);
    String contents = myScanner.useDelimiter("\\Z").next(); 
}
finally
{
    if(myScanner != null)
    {
        myScanner.close(); 
    }
}

Ofcourse, you can add a catch block to handle exceptions properly.

How do you Programmatically Download a Webpage in Java

On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.

How to match hyphens with Regular Expression?

It’s less confusing to always use an escaped hyphen, so that it doesn't have to be positionally dependent. That’s a \- inside the bracketed character class.

But there’s something else to consider. Some of those enumerated characters should possibly be written differently. In some circumstances, they definitely should.

This comparison of regex flavors says that C? can use some of the simpler Unicode properties. If you’re dealing with Unicode, you should probably use the general category \p{L} for all possible letters, and maybe \p{Nd} for decimal numbers. Also, if you want to accomodate all that dash punctuation, not just HYPHEN-MINUS, you should use the \p{Pd} property. You might also want to write that sequence of whitespace characters simply as \s, assuming that’s not too general for you.

All together, that works out to apattern of [\p{L}\p{Nd}\p{Pd}!$*] to match any one character from that set.

I’d likely use that anyway, even if I didn’t plan on dealing with the full Unicode set, because it’s a good habit to get into, and because these things often grow beyond their original parameters. Now when you lift it to use in other code, it will still work correctly. If you hard-code all the characters, it won’t.

Get all directories within directory nodejs

Alternatively, if you are able to use external libraries, you can use filehound. It supports callbacks, promises and sync calls.

Using promises:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory() // only search for directories
  .find()
  .then((subdirectories) => {
    console.log(subdirectories);
  });

Using callbacks:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory()
  .find((err, subdirectories) => {
    if (err) return console.error(err);

    console.log(subdirectories);
  });

Sync call:

const Filehound = require('filehound');

const subdirectories = Filehound.create()
  .path("MyFolder")
  .directory()
  .findSync();

console.log(subdirectories);

For further information (and examples), check out the docs: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

How do I add a margin between bootstrap columns without wrapping

Change the number of @grid-columns. Then use -offset. Changing the number of columns will allow you to control the amount of space between columns. E.g.

variables.less (approx line 294).

@grid-columns:              20;

someName.html

<div class="row">
  <div class="col-md-4 col-md-offset-1">First column</div>
  <div class="col-md-13 col-md-offset-1">Second column</div>
</div>

jQuery - prevent default, then continue default

"Validation injection without submit looping":

I just want to check reCaptcha and some other stuff before HTML5 validation, so I did something like that (the validation function returns true or false):

$(document).ready(function(){
   var application_form = $('form#application-form');

   application_form.on('submit',function(e){

        if(application_form_extra_validation()===true){
           return true;
        }

        e.preventDefault();

   });
});

SQL Server Case Statement when IS NULL

You can use IIF (I think from SQL Server 2012)

SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]

How to create a file in Android?

Write to a file test.txt:

String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
        fos = new FileOutputStream(filepath);
        byte[] buffer = "This will be writtent in test.txt".getBytes();
        fos.write(buffer, 0, buffer.length);
        fos.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fos != null)
            fos.close();
    }

Read from file test.txt:

String filepath ="/mnt/sdcard/test.txt";        
FileInputStream fis = null;
try {
       fis = new FileInputStream(filepath);
       int length = (int) new File(filepath).length();
       byte[] buffer = new byte[length];
       fis.read(buffer, 0, length);
       fis.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fis != null)
            fis.close();
   }

Note: don't forget to add these two permission in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How much faster is C++ than C#?

I suppose there are applications written in C# running fast, as well as there are more C++ written apps running fast (well C++ just older... and take UNIX too...)
- the question indeed is - what is that thing, users and developers are complaining about ...
Well, IMHO, in case of C# we have very comfort UI, very nice hierarchy of libraries, and whole interface system of CLI. In case of C++ we have templates, ATL, COM, MFC and whole shebang of alreadyc written and running code like OpenGL, DirectX and so on... Developers complains of indeterminably risen GC calls in case of C# (means program runs fast, and in one second - bang! it's stuck).
To write code in C# very simple and fast (not to forget that also increase chance of errors. In case of C++, developers complains of memory leaks, - means crushes, calls between DLLs, as well as of "DLL hell" - problem with support and replacement libraries by newer ones...
I think more skill you'll have in the programming language, the more quality (and speed) will characterize your software.

git - remote add origin vs remote set-url origin

1. git remote add origin [email protected]:User/UserRepo.git

  • This command is the second step in the command series after you initialize git into your current working repository using git init.
  • This command simply means "you are adding the location of your remote repository where you wish to push/pull your files to/from !!.."
  • Your remote repository could be anywhere on github, gitlab, bitbucket, etc.
  • Here origin is an alias/alternate name for your remote repository so that you don't have to type the entire path for remote every time and henceforth you are declaring that you will use this name(origin) to refer to your remote. This name could be anything.
  • To verify that the remote is set properly type : git remote -v

OR git remote get-url origin

2. git remote set-url origin [email protected]:User/UserRepo.git

This command means that if at any stage you wish to change the location of your repository(i.e if you made a mistake while adding the remote path using the git add command) the first time, you can easily go back & "reset(update) your current remote repository path" by using the above command.

3. git push -u remote master

This command simply pushes your files to the remote repository.Git has a concept of something known as a "branch", so by default everything is pushed to the master branch unless explicitly specified an alternate branch.

To know about the list of all branches you have in your repository type :git branch

Enter triggers button click

Where ever you use a <button> element by default it considers that button type="submit" so if you define the button type="button" then it won't consider that <button> as submit button.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

You could try a subquery:

SELECT DISTINCT TEST.* FROM (
    SELECT rsc.RadioServiceCodeId,
        rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
    FROM sbi_l_radioservicecodes rsc
       INNER JOIN sbi_l_radioservicecodegroups rscg ON  rsc.radioservicecodeid = rscg.radioservicecodeid
    WHERE rscg.radioservicegroupid IN 
       (select val from dbo.fnParseArray(@RadioServiceGroup,','))
        OR @RadioServiceGroup IS NULL  
    ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
) as TEST

Get name of object or class

Try this:

var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];

How to disable copy/paste from/to EditText

In addition to the setCustomSelectionActionModeCallback, and disabled long-click solutions, it's necessary to prevent the PASTE/REPLACE menus from appearing when the text selection handle is clicked, as per the image below:

Text selection handle with paste menu

The solution lies in preventing PASTE/REPLACE menu from appearing in the show() method of the (non-documented) android.widget.Editor class. Before the menu appears, a check is done to if (!canPaste && !canSuggest) return;. The two methods that are used as the basis to set these variables are both in the EditText class:

A more complete answer is available here.

How To: Execute command line in C#, get STD OUT results

Here's a quick sample:

//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = strCommand;

//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = strCommandParameters;

pProcess.StartInfo.UseShellExecute = false;

//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;   

//Optional
pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;

//Start the process
pProcess.Start();

//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();

//Wait for process to finish
pProcess.WaitForExit();

ReactJS: setTimeout() not working?

setTimeout(() => {
  this.setState({ position: 1 });
}, 3000);

The above would also work because the ES6 arrow function does not change the context of this.

How to remove duplicate values from an array in PHP

We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...

$array = array (1,3,4,2,1,7,4,9,7,5,9);
    $data=array();
    foreach($array as $value ){

        $data[$value]= $value;

    }

    array_keys($data);
    OR
    array_values($data);

How to urlencode a querystring in Python?

If the urllib.parse.urlencode( ) is giving you errors , then Try the urllib3 module .

The syntax is as follows :

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

What's an Aggregate Root?

In another world, in Event Sourcing, an Aggregate(Root) is a different concept. Event Sourcing might be encountered together with CQRS, DDD etc.

In Event Sourcing an Aggregate is an object for which the state (fields) is not mapped to a record in a database as we are used to think in SQL/JPA world.

Is not a group of related entities.

It is a group of related records like in a history table.

GiftCard.amount is one field in a GiftCard Aggregate, but this field is mapped to all the events, like card-redeemed (take money from the card) ever created.

So the source of data for your Aggregate is not a record in a database but the complete list of events ever created for that specific aggregate. We say we event sourced the aggregate.

Now we can ask ourselves how is it done? Who is aggregating these events so we are operating still with one field e.g GiftCard.amount? We might be expecting that amount to be a Collection and not a big-decimal type.

Is the event sourcing engine, doing the work, who might simply replay all the events in the creation order. But this is out of the scope for this thread.

Why is processing a sorted array faster than processing an unsorted array?

Bjarne Stroustrup's Answer to this question:

That sounds like an interview question. Is it true? How would you know? It is a bad idea to answer questions about efficiency without first doing some measurements, so it is important to know how to measure.

So, I tried with a vector of a million integers and got:

Already sorted    32995 milliseconds
Shuffled          125944 milliseconds

Already sorted    18610 milliseconds
Shuffled          133304 milliseconds

Already sorted    17942 milliseconds
Shuffled          107858 milliseconds

I ran that a few times to be sure. Yes, the phenomenon is real. My key code was:

void run(vector<int>& v, const string& label)
{
    auto t0 = system_clock::now();
    sort(v.begin(), v.end());
    auto t1 = system_clock::now();
    cout << label
         << duration_cast<microseconds>(t1 — t0).count()
         << " milliseconds\n";
}

void tst()
{
    vector<int> v(1'000'000);
    iota(v.begin(), v.end(), 0);
    run(v, "already sorted ");
    std::shuffle(v.begin(), v.end(), std::mt19937{ std::random_device{}() });
    run(v, "shuffled    ");
}

At least the phenomenon is real with this compiler, standard library, and optimizer settings. Different implementations can and do give different answers. In fact, someone did do a more systematic study (a quick web search will find it) and most implementations show that effect.

One reason is branch prediction: the key operation in the sort algorithm is “if(v[i] < pivot]) …” or equivalent. For a sorted sequence that test is always true whereas, for a random sequence, the branch chosen varies randomly.

Another reason is that when the vector is already sorted, we never need to move elements to their correct position. The effect of these little details is the factor of five or six that we saw.

Quicksort (and sorting in general) is a complex study that has attracted some of the greatest minds of computer science. A good sort function is a result of both choosing a good algorithm and paying attention to hardware performance in its implementation.

If you want to write efficient code, you need to know a bit about machine architecture.

What is a good alternative to using an image map generator?

Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.

This btw is Search Engine Optimised as well :)

Source code follows:

_x000D_
_x000D_
.image-map {
  background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  width: 272px;
  height: 92px;
  display: block;
  position: relative;
  margin-top:10px;
  float: left;
}

.image-map > a.map {
  position: absolute;
  display: block;
  border: 1px solid green;
}
_x000D_
<div class="image-map">
    <a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
    <a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
    <a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
_x000D_
_x000D_

EDIT:

After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.

Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)

However I guess the target audience for this question does not agree with me.

You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.