Programs & Examples On #Advapi32

Anything related to MS Windows Advanced Services API for 32bit systems (part of Windows API), residing in the `advapi32.dll` library. This library provides functions to access Windows registry, to restart the system, to create Windows services and to manage user accounts.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

Problem solved! I'm using Ctrl + Alt + E to open Exception Window, and I checked all throw checkbox. So the debuger can stop at the exactly the error code.

installing JDK8 on Windows XP - advapi32.dll error

Oracle has announced fix for Windows XP installation error

Oracle has decided to fix Windows XP installation. As of the JRE 8u25 release in 10/15/2014 the code of the installer has been changes so that installation on Windows XP is again possible.

However, this does not mean that Oracle is continuing to support Windows XP. They make no guarantee about current and future releases of JRE8 being compatible with Windows XP. It looks like it's a run at your own risk kind of thing.

See the Oracle blog post here.

You can get the latest JRE8 right off the Oracle downloads site.

Error Message : Cannot find or open the PDB file

  1. Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.

  2. Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .

  3. You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"

Cannot find or open the PDB file in Visual Studio C++ 2010

Answer by Paul is right, I am just putting the visual to easily get there.

Go to Tools->Options->Debugging->Symbols

Set the checkbox marked in red and it will download the pdb files from microsoft. When you set the checkbox, it will also set a default path for the pdb files in the edit box under, you don't need to change that.

enter image description here

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

In VS2010 iterator debug level defaults to 2 in debug and is disabled in release. One of the dlls you are using probably has iterator debugging turned off in debug either because it was built in an older version of visual studio or they explicitly added the defines to the project.

Search for _ITERATOR_DEBUG_LEVEL and _SECURE_SCL remove them or set them appropriately in all projects and sources and rebuild everything.

_ITERATOR_DEBUG_LEVEL = 0 // disabled (for release builds)
_ITERATOR_DEBUG_LEVEL = 1 // enabled (if _SECURE_SCL is defined)
_ITERATOR_DEBUG_LEVEL = 2 // enabled (for debug builds)

In short you are probably mixing release and debug dlls. Don't linked release dlls in debug or vice versa!

pow (x,y) in Java

In Java x ^ y is an XOR operation.

Swift days between two NSDates

Nice handy one liner :

extension Date {
  var daysFromNow: Int {
    return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
  }
}

What's the best way to break from nested loops in JavaScript?

Wrap that up in a function and then just return.

How do I rotate the Android emulator display?

Ctrl + F12 did not work for me, nor did Home, PageUp etc.

So here's what finally came up with:

  • Enable NUMLOCK;
  • Open your emulator and press the 7 followed by 9 on the NUMPAD on the right side of your keyboard;
  • Now your emulator will be rotated in the opposite direction;

Remove empty array elements

$my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" ");   

foreach ($my as $key => $value) {
    if (is_null($value)) unset($my[$key]);
}

foreach ($my as $key => $value) {
    echo   $key . ':' . $value . '<br>';
} 

output

1:5

2:6

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());


  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);

      }

in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

Evaluate empty or null JSTL c tags

In this step I have Set the variable first:

<c:set var="structureId" value="<%=article.getStructureId()%>" scope="request"></c:set>

In this step I have checked the variable empty or not:

 <c:if test="${not empty structureId }">
    <a href="javascript:void(0);">Change Design</a>
 </c:if>

Add custom buttons on Slick Carousel

If you are using sass you can simply set below mentioned variables to use icons provided by other fonts,

$slick-font-family:FontAwesome;
$slick-prev-character: "\f053";
$slick-next-character: "\f054";

These will change the font family used by slick's theme css and also the unicode for prev and next button. This example will use FontAwesome's chevron-left and chevron-right icons.

Other sass variables which can be configured are given in Slick Github page

What is a magic number, and why is it bad?

@eed3si9n: I'd even suggest that '1' is a magic number. :-)

A principle that's related to magic numbers is that every fact your code deals with should be declared exactly once. If you use magic numbers in your code (such as the password length example that @marcio gave, you can easily end up duplicating that fact, and when your understand of that fact changes you've got a maintenance problem.

I am not able launch JNLP applications using "Java Web Start"?

Although this question is bit old, the issue was caused by corrupted ClearType registry setting and resolved by fixing it, as described in this ClearType, install4j and case of Java bug post.

ClearType, install4j and case of Java bug Java

Do you know what ClearType (font-smoothing technology in Windows) has in common with Java (programming language and one of the recommended frameworks)?

Nothing except that they were working together hard at making me miserable for few months. I had some Java software that I couldn’t install. I mean really couldn’t – not even figure out reason or reproduce it on another PC.

Recently I was approved for Woopra beta (site analytics service) and it uses desktop client written in Java… I couldn’t install. That got me really mad. :)

Story All of the software in question was similar :

setup based on install4j; setup crashing with bunch of errors. I was blaming install4j during early (hundred or so) attempts to solve issue. Later I slowly understood that if it was that bugged for that long time – solution would have been created and googled.

Tracing After shifting focus from install4j I decided to push Java framework. I was trying stable versions earlier so decided to go for non-stable 1.6 Update 10 Release Candidate.

This actually fixed error messages but not crashes. I had also noticed that there was new error log created in directory with setup files. Previously I had only seen logs in Windows temporary directory.

New error log was saying following :

Could not display the GUI. This application needs access to an X Server. If you have access there is probably an X library missing. ******************************************************************* You can also run this application in console mode without access to an X server by passing the argument -c Very weird to look for X-Server on non-Linux PC, isn’t it? So I decided to try that “-c” argument. And was actually able to install in console mode.

Happy ending? Nope. Now installed app was crashing. But it really got me thinking. If console works but graphical interface doesn’t – there must be problem with latter.

One more error log (in application folder) was now saying (among other things) :

Caused by: java.lang.IllegalArgumentException: -60397977 incompatible with Text-specific LCD contrast key Which successfully googled me description of bug with Java unable to read non-standard ClearType registry setting.

Solution I immediately launched ClearType Tuner from Control Panel and found setting showing gibberish number. After correcting it to proper one all problems with Java were instantly gone.

cleartypetuner_screenshot Lessons learned Don’t be fast to blame software problems on single application. Even minor and totally unrelated settings can launch deadly chain reactions. Links Jave Runtime Environment http://www.java.com/en/download/index.jsp

ClearType Tuner http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx

Woopra http://www.woopra.com/

install4j http://www.ej-technologies.com/products/install4j/overview.html

Hide particular div onload and then show div after click

This is an easier way to do it. Hope this helps...

<script type="text/javascript">
$(document).ready(function () {
    $("#preview").toggle(function() {
        $("#div1").hide();
        $("#div2").show();
    }, function() {
        $("#div1").show();
        $("#div2").hide();
    });
});

<div id="div1">
This is preview Div1. This is preview Div1.
</div>

<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>

<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
  • If you want the div to be hidden on load, make the style display:none
  • Use toggle rather than click function.


Links:

JQuery Tutorials

JQuery References

What is the difference between typeof and instanceof and when should one be used vs. the other?

According to MDN documentation about typeof, objects instantiated with the "new" keyword are of type 'object':

typeof 'bla' === 'string';

// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';

While documentation about instanceof points that:

const objectString = new String('String created with constructor');
objectString instanceOf String; // returns true
objectString instanceOf Object; // returns true

So if one wants to check e.g. that something is a string no matter how it was created, safest approach would be to use instanceof.

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

How can you test if an object has a specific property?

I ended up with the following function ...

function HasNoteProperty(
    [object]$testObject,
    [string]$propertyName
)
{
    $members = Get-Member -InputObject $testObject 
    if ($members -ne $null -and $members.count -gt 0) 
    { 
        foreach($member in $members) 
        { 
            if ( ($member.MemberType -eq "NoteProperty" )  -and `
                 ($member.Name       -eq $propertyName) ) 
            { 
                return $true 
            } 
        } 
        return $false 
    } 
    else 
    { 
        return $false; 
    }
}

Android Fragment onAttach() deprecated

Download newest Support library with the sdk manager and include

compile 'com.android.support:appcompat-v7:23.1.1'

in gradle.app and set compile version to api 23

How do I disable fail_on_empty_beans in Jackson?

You can also get the same issue if your class doesn't contain any public methods/properties. I normally have dedicated DTOs for API requests and responses, declared public, but forgot in one case to make the methods public as well - which caused the "empty" bean in the first place.

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

Live-stream video from one android phone to another over WiFi

I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

strange issue that i solved by comment this line

//$mail->IsSmtp();

whit the last phpmailer version (5.2)

test attribute in JSTL <c:if> tag

The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:

<c:if test="true">
    <li>user</li>
</c:if>

and then the c:if tag would be executed.

How to initialize a two-dimensional array in Python?

You can use a list comprehension:

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)

How can I remove specific rules from iptables?

Use -D command, this is how man page explains it:

-D, --delete chain rule-specification
-D, --delete chain rulenum
    Delete  one  or more rules from the selected chain.  
    There are two versions of this command: 
    the rule can be specified as a number in the chain (starting at 1 for the first rule) or a rule to match.

Do realize this command, like all other command(-A, -I) works on certain table. If you'are not working on the default table(filter table), use -t TABLENAME to specify that target table.

Delete a rule to match

iptables -D INPUT -i eth0 -p tcp --dport 443 -j ACCEPT

Note: This only deletes the first rule matched. If you have many rules matched(this can happen in iptables), run this several times.

Delete a rule specified as a number

iptables -D INPUT 2

Other than counting the number you can list the line-number with --line-number parameter, for example:

iptables -t nat -nL --line-number

SQL Select between dates

Special thanks to Jeff and vapcguy your interactivity is really encouraging.

Here is a more complex statement that is useful when the length between '/' is unknown::

SELECT * FROM tableName
WHERE julianday(
    substr(substr(date, instr(date, '/')+1), instr(substr(date, instr(date, '/')+1), '/')+1)
||'-'||
    case when length(
    substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1),'/')-1)
    )=2
    then
    substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1), '/')-1)
    else
    '0'||substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1), '/')-1)
    end
||'-'||
    case when length(substr(date,1, instr(date, '/')-1 )) =2
    then substr(date,1, instr(date, '/')-1 )
    else
    '0'||substr(date,1, instr(date, '/')-1 )
    end
) BETWEEN julianday('2015-03-14') AND julianday('2015-03-16') 

How to convert string into float in JavaScript?

Replace the comma with a dot.

This will only return 554:

var value = parseFloat("554,20")

This will return 554.20:

var value = parseFloat("554.20")

So in the end, you can simply use:

var fValue = parseFloat(document.getElementById("textfield").value.replace(",","."))

Don't forget that parseInt() should only be used to parse integers (no floating points). In your case it will only return 554. Additionally, calling parseInt() on a float will not round the number: it will take its floor (closest lower integer).


Extended example to answer Pedro Ferreira's question from the comments:

If the textfield contains thousands separator dots like in 1.234.567,99 those could be eliminated beforehand with another replace:

var fValue = parseFloat(document.getElementById("textfield").value.replace(/\./g,"").replace(",","."))

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

There are a few options:

  • Nest the AsyncTask class within your Activity class. Assuming you don't use the same task in multiple activities, this is the easiest way. All your code stays the same, you just move the existing task class to be a nested class inside your activity's class.

    public class MyActivity extends Activity {
        // existing Activity code
        ...
    
        private class MyAsyncTask extends AsyncTask<String, Void, String> {
            // existing AsyncTask code
            ...
        }
    }
    
  • Create a custom constructor for your AsyncTask that takes a reference to your Activity. You would instantiate the task with something like new MyAsyncTask(this).execute(param1, param2).

    public class MyAsyncTask extends AsyncTask<String, Void, String> {
        private Activity activity;
    
        public MyAsyncTask(Activity activity) {
            this.activity = activity;
        }
    
        // existing AsyncTask code
        ...
    }
    

Composer killed while updating

php -d memory_limit=5G composer.phar update

Change Twitter Bootstrap Tooltip content on click

for Bootstrap 4:

$(element).attr("title", "Copied!").tooltip("_fixTitle").tooltip("show").attr("title", "Copy to clipboard").tooltip("_fixTitle");

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

How do I setup a SSL certificate for an express.js server?

I was able to get SSL working with the following boilerplate code:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    express = require('express');

var port = 8000;

var options = {
    key: fs.readFileSync('./ssl/privatekey.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),
};

var app = express();

var server = https.createServer(options, app).listen(port, function(){
  console.log("Express server listening on port " + port);
});

app.get('/', function (req, res) {
    res.writeHead(200);
    res.end("hello world\n");
});

Where and why do I have to put the "template" and "typename" keywords?

(See here also for my C++11 answer)

In order to parse a C++ program, the compiler needs to know whether certain names are types or not. The following example demonstrates that:

t * f;

How should this be parsed? For many languages a compiler doesn't need to know the meaning of a name in order to parse and basically know what action a line of code does. In C++, the above however can yield vastly different interpretations depending on what t means. If it's a type, then it will be a declaration of a pointer f. However if it's not a type, it will be a multiplication. So the C++ Standard says at paragraph (3/7):

Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.

How will the compiler find out what a name t::x refers to, if t refers to a template type parameter? x could be a static int data member that could be multiplied or could equally well be a nested class or typedef that could yield to a declaration. If a name has this property - that it can't be looked up until the actual template arguments are known - then it's called a dependent name (it "depends" on the template parameters).

You might recommend to just wait till the user instantiates the template:

Let's wait until the user instantiates the template, and then later find out the real meaning of t::x * f;.

This will work and actually is allowed by the Standard as a possible implementation approach. These compilers basically copy the template's text into an internal buffer, and only when an instantiation is needed, they parse the template and possibly detect errors in the definition. But instead of bothering the template's users (poor colleagues!) with errors made by a template's author, other implementations choose to check templates early on and give errors in the definition as soon as possible, before an instantiation even takes place.

So there has to be a way to tell the compiler that certain names are types and that certain names aren't.

The "typename" keyword

The answer is: We decide how the compiler should parse this. If t::x is a dependent name, then we need to prefix it by typename to tell the compiler to parse it in a certain way. The Standard says at (14.6/2):

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

There are many names for which typename is not necessary, because the compiler can, with the applicable name lookup in the template definition, figure out how to parse a construct itself - for example with T *f;, when T is a type template parameter. But for t::x * f; to be a declaration, it must be written as typename t::x *f;. If you omit the keyword and the name is taken to be a non-type, but when instantiation finds it denotes a type, the usual error messages are emitted by the compiler. Sometimes, the error consequently is given at definition time:

// t::x is taken as non-type, but as an expression the following misses an
// operator between the two names or a semicolon separating them.
t::x f;

The syntax allows typename only before qualified names - it is therefor taken as granted that unqualified names are always known to refer to types if they do so.

A similar gotcha exists for names that denote templates, as hinted at by the introductory text.

The "template" keyword

Remember the initial quote above and how the Standard requires special handling for templates as well? Let's take the following innocent-looking example:

boost::function< int() > f;

It might look obvious to a human reader. Not so for the compiler. Imagine the following arbitrary definition of boost::function and f:

namespace boost { int function = 0; }
int main() { 
  int f = 0;
  boost::function< int() > f; 
}

That's actually a valid expression! It uses the less-than operator to compare boost::function against zero (int()), and then uses the greater-than operator to compare the resulting bool against f. However as you might well know, boost::function in real life is a template, so the compiler knows (14.2/3):

After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is always taken as the beginning of a template-argument-list and never as a name followed by the less-than operator.

Now we are back to the same problem as with typename. What if we can't know yet whether the name is a template when parsing the code? We will need to insert template immediately before the template name, as specified by 14.2/4. This looks like:

t::template f<int>(); // call a function template

Template names can not only occur after a :: but also after a -> or . in a class member access. You need to insert the keyword there too:

this->template f<int>(); // call a function template

Dependencies

For the people that have thick Standardese books on their shelf and that want to know what exactly I was talking about, I'll talk a bit about how this is specified in the Standard.

In template declarations some constructs have different meanings depending on what template arguments you use to instantiate the template: Expressions may have different types or values, variables may have different types or function calls might end up calling different functions. Such constructs are generally said to depend on template parameters.

The Standard defines precisely the rules by whether a construct is dependent or not. It separates them into logically different groups: One catches types, another catches expressions. Expressions may depend by their value and/or their type. So we have, with typical examples appended:

  • Dependent types (e.g: a type template parameter T)
  • Value-dependent expressions (e.g: a non-type template parameter N)
  • Type-dependent expressions (e.g: a cast to a type template parameter (T)0)

Most of the rules are intuitive and are built up recursively: For example, a type constructed as T[N] is a dependent type if N is a value-dependent expression or T is a dependent type. The details of this can be read in section (14.6.2/1) for dependent types, (14.6.2.2) for type-dependent expressions and (14.6.2.3) for value-dependent expressions.

Dependent names

The Standard is a bit unclear about what exactly is a dependent name. On a simple read (you know, the principle of least surprise), all it defines as a dependent name is the special case for function names below. But since clearly T::x also needs to be looked up in the instantiation context, it also needs to be a dependent name (fortunately, as of mid C++14 the committee has started to look into how to fix this confusing definition).

To avoid this problem, I have resorted to a simple interpretation of the Standard text. Of all the constructs that denote dependent types or expressions, a subset of them represent names. Those names are therefore "dependent names". A name can take different forms - the Standard says:

A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1)

An identifier is just a plain sequence of characters / digits, while the next two are the operator + and operator type form. The last form is template-name <argument list>. All these are names, and by conventional use in the Standard, a name can also include qualifiers that say what namespace or class a name should be looked up in.

A value dependent expression 1 + N is not a name, but N is. The subset of all dependent constructs that are names is called dependent name. Function names, however, may have different meaning in different instantiations of a template, but unfortunately are not caught by this general rule.

Dependent function names

Not primarily a concern of this article, but still worth mentioning: Function names are an exception that are handled separately. An identifier function name is dependent not by itself, but by the type dependent argument expressions used in a call. In the example f((T)0), f is a dependent name. In the Standard, this is specified at (14.6.2/1).

Additional notes and examples

In enough cases we need both of typename and template. Your code should look like the following

template <typename T, typename Tail>
struct UnionNode : public Tail {
    // ...
    template<typename U> struct inUnion {
        typedef typename Tail::template inUnion<U> dummy;
    };
    // ...
};

The keyword template doesn't always have to appear in the last part of a name. It can appear in the middle before a class name that's used as a scope, like in the following example

typename t::template iterator<int>::value_type v;

In some cases, the keywords are forbidden, as detailed below

  • On the name of a dependent base class you are not allowed to write typename. It's assumed that the name given is a class type name. This is true for both names in the base-class list and the constructor initializer list:

     template <typename T>
     struct derive_from_Has_type : /* typename */ SomeBase<T>::type 
     { };
    
  • In using-declarations it's not possible to use template after the last ::, and the C++ committee said not to work on a solution.

     template <typename T>
     struct derive_from_Has_type : SomeBase<T> {
        using SomeBase<T>::template type; // error
        using typename SomeBase<T>::type; // typename *is* allowed
     };
    

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I ran into this myself when I wanted to make a thor command under Windows.

To avoid having that message output everytime I ran my thor application I temporarily muted warnings while loading thor:

begin
  original_verbose = $VERBOSE
  $VERBOSE = nil
  require "thor"
ensure
  $VERBOSE = original_verbose
end

That saved me from having to edit third party source files.

c++ Read from .csv file

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
 ID=0   Name=Filipe Age=19  Gender=M
 ID=1   Name=Maria  Age=20  Gender=F
 ID=2   Name=Walter Age=60  Gender=M

Remove padding or margins from Google Charts

It's missing in the docs (I'm using version 43), but you can actually use the right and bottom property of the chart area:

var options = {
  chartArea:{
    left:10,
    right:10, // !!! works !!!
    bottom:20,  // !!! works !!!
    top:20,
    width:"100%",
    height:"100%"
  }
};

So it's possible to use full responsive width & height and prevent any axis labels or legends from being cropped.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

What is tempuri.org?

Unfortunately the tempuri.org URL now just redirects to Bing.

You can see what it used to render via archive.org:

https://web.archive.org/web/20090304024056/http://tempuri.org/

To quote:

Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.

Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.

For XML Web Services creating[sic] using ASP.NET, the default namespace can be changed using the WebService attribute's Namespace property. The WebService attribute is applied to the class that contains the XML Web Service methods. Below is a code example that sets the namespace to "http://microsoft.com/webservices/":

C#

[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}

Visual Basic.NET

<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class

Visual J#.NET

/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}

It's also worth reading section 'A 1.3 Generating URIs' at:

http://www.w3.org/TR/wsdl#_Toc492291092

Why rgb and not cmy?

There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).

With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.

On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.

Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.

P.D.: my father worked at graphic arts, this is why i know this... :-P

How to select the last record of a table in SQL?

You can also do something like this:

SELECT LAST (column_name) AS LAST_CUSTOMER FROM table_name;

Download image with JavaScript

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

I too faced the same problem, and I did a "Factory data reset", and it worked fine after that.

Parsing ISO 8601 date in Javascript

According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date methods and formatting to accomplish your goal:

function dateToString (date) {
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[date.getMonth()];
  var day = date.getDate();
  var year = date.getFullYear();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[date.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");

alert(dateToString(date));

You could even take it one step further and override the Date.toString() method:

function dateToString () { // No date argument this time
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[*this*.getMonth()];
  var day = *this*.getDate();
  var year = *this*.getFullYear();

  var hours = *this*.getHours();
  var minutes = *this*.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[*this*.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;

alert(date.toString());

Django CSRF check failing with an Ajax POST request

The accepted answer is most likely a red herring. The difference between Django 1.2.4 and 1.2.5 was the requirement for a CSRF token for AJAX requests.

I came across this problem on Django 1.3 and it was caused by the CSRF cookie not being set in the first place. Django will not set the cookie unless it has to. So an exclusively or heavily ajax site running on Django 1.2.4 would potentially never have sent a token to the client and then the upgrade requiring the token would cause the 403 errors.

The ideal fix is here: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#page-uses-ajax-without-any-html-form
but you'd have to wait for 1.4 unless this is just documentation catching up with the code

Edit

Note also that the later Django docs note a bug in jQuery 1.5 so ensure you are using 1.5.1 or later with the Django suggested code: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

How to get first character of string?

_x000D_
_x000D_
const x = 'some string';_x000D_
console.log(x.substring(0, 1));
_x000D_
_x000D_
_x000D_

How do I get the information from a meta tag with JavaScript?

If you use JQuery, you can use:

$("meta[property='video']").attr('content');

document.body.appendChild(i)

If your script is inside head tag in html file, try to put it inside body tag. CreateElement while script is inside head tag will give you a null warning

<head>
  <title></title>
</head>

<body>
  <h1>Game</h1>
  <script type="text/javascript" src="script.js"></script>
</body>

pandas: filter rows of DataFrame with operator chaining

This is unappealing as it requires I assign df to a variable before being able to filter on its values.

df[df["column_name"] != 5].groupby("other_column_name")

seems to work: you can nest the [] operator as well. Maybe they added it since you asked the question.

In android how to set navigation drawer header image and name programmatically in class file?

  nav = ( NavigationView ) findViewById( R.id.navigation );

    if( nav != null ){
        LinearLayout mParent = ( LinearLayout ) nav.getHeaderView( 0 );

        if( mParent != null ){
            // Set your values to the image and text view by declaring and setting as you need to here.

            SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
            String photoUrl = prefs.getString("photo_url", null);
            String user_name = prefs.getString("name", "User");

            if(photoUrl!=null) {
                Log.e("Photo Url: ", photoUrl);

                TextView userName = mParent.findViewById(R.id.user_name);
                userName.setText(user_name);

                ImageView user_imageView = mParent.findViewById(R.id.avatar);

                RequestOptions requestOptions = new RequestOptions();
                requestOptions.placeholder(R.drawable.ic_user_24dp);
                requestOptions.error(R.drawable.ic_user_24dp);

                Glide.with(this).load(photoUrl)
                        .apply(requestOptions).thumbnail(0.5f).into(user_imageView);

            }

        }
    }

Hope this helps.

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Suppose we have streaming in video tag and id is video - <video id="video"></video> then we should have following code -

var videoEl = document.getElementById('video');
// now get the steam 
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
   // stopping every track
   track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;

What is the difference between a heuristic and an algorithm?

I think Heuristic is more of a constraint used in Learning Based Model in Artificial Intelligent since the future solution states are difficult to predict.

But then my doubt after reading above answers is "How would Heuristic can be successfully applied using Stochastic Optimization Techniques? or can they function as full fledged algorithms when used with Stochastic Optimization?"

http://en.wikipedia.org/wiki/Stochastic_optimization

Remove duplicate rows in MySQL

You can easily delete the duplicate records from this code..

$qry = mysql_query("SELECT * from cities");
while($qry_row = mysql_fetch_array($qry))
{
$qry2 = mysql_query("SELECT * from cities2 where city = '".$qry_row['city']."'");

if(mysql_num_rows($qry2) > 1){
    while($row = mysql_fetch_array($qry2)){
        $city_arry[] = $row;

        }

    $total = sizeof($city_arry) - 1;
        for($i=1; $i<=$total; $i++){


            mysql_query( "delete from cities2 where town_id = '".$city_arry[$i][0]."'");

            }
    }
    //exit;
}

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

With HTML5, you can do this natively with: <input name="first_name" placeholder="First Name">

This is not supported with all browsers though (IE)

This may work:

<input type="first_name" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null">

Otherwise, if you are using jQuery, you can use .focus and .css to change the color.

"detached entity passed to persist error" with JPA/EJB code

I got the answer, I was using:

em.persist(user);

I used merge in place of persist:

em.merge(user);

But no idea, why persist didn't work. :(

MySQL convert date string to Unix timestamp

You will certainly have to use both STR_TO_DATE to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP to get the timestamp from it.

Given the format of your date, something like

UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))

Will gives you a valid timestamp. Look the STR_TO_DATE documentation to have more information on the format string.

How do I test if a variable does not equal either of two values?

I do that using jQuery

if ( 0 > $.inArray( test, [a,b] ) ) { ... }

@UniqueConstraint and @Column(unique = true) in hibernate annotation

As said before, @Column(unique = true) is a shortcut to UniqueConstraint when it is only a single field.

From the example you gave, there is a huge difference between both.

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;

This code implies that both mask and group have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.

On the other hand,

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)

Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.

If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:

@Table(
        name = "product_serial_group_mask",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "mask"),
                @UniqueConstraint(columnNames = "group")
        }
)

This has the same effect as the first code block.

Import pandas dataframe column as string not int

This probably isn't the most elegant way to do it, but it gets the job done.

In[1]: import numpy as np

In[2]: import pandas as pd

In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])

In[4]: df
Out[4]: 
                       ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

Just replace '/Users/spencerlyon2/Desktop/test.csv' with the path to your file

Convert from List into IEnumerable format

You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :

List<Book> list = new List<Book>();
return list.AsEnumerable();

This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).

How to disable Google Chrome auto update?

Have spent a long time trying to disable updates (literally hours, reading forums and testing various (some exotic) solutions), and this was driving me crazy. But there what seems an infallible solution (see further down).

Even using the official Google page with the templates did NOTHING: https://support.google.com/installer/answer/146164?hl=en

I followed scrupulously the instructions of that page, the keys in the registry are all correct, but still going to the "About Google Chrome" when the program is opened, I can see the wheel going around and a few seconds later the update is forced and done.

I have tried using the standalone installer of Google, on a Windows 8.1 machine 64Bits - and yes all the keys are set to :

Dword: AutoUpdateCheckPeriodMinutes Value: 0
Dword: DisableAutoUpdateChecksCheckboxValue Value: 1
Dword: UpdateDefault Value: 0
Dword: Update{8A69D345-D564-463C-AFF1-A69D9E530F96} Value: 0
(this last one requires the service(s) to not be disabled - gupdate/gupdatem)

... both in HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Update AND HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Policies\Google\Update since it is a 64-bit machine.

So the radical solution to prevent the auto-update, if that helps anyone, is to just purely sort the program responsible for the updates itself! (Just deleting it, OR saving a copy, OR renaming it OR even better just in case I one day need to do an update: Zip the content for future potential re-use).

Easy solution :
1- Go to "C:\Program Files (x86)\Google\ and find the folder "update".
2- There are a couple of options to choose from:

 A) first method: Rename the folder:

- Right click > Rename > from Update.bak to Update2.bak for example.
- Now launch Chrome: NO MORE UPDATES!! since it can not find the update program !! Finished.

 B) second method: Zip the folder:

- Zip the entire folder by making an archive. (Right click the "Update" folder > Send to Compressed (zip) folder)
- A window might ask you to backup/zip and place it on the desktop, click yes. (message: Windows cannot create the compressed folders here. Do you want to be placed on the desktop instead?)
- Move the newly created zip file to the original location. New window security might pop up > click continue. (message: You need administrator permission to copy this file). [This will be what to unzip if one day you decide to update Chrome - Just remember that when unzipped it will have the following structure: Update > Update > then all the content of the folder. Remember to move everything from inside the second update folder (copy paste) one level up so that is becoming: Update > then all the content of the folder].
- Now that you have a copy just delete the "Update" folder.
- Now launch Chrome: NO MORE UPDATES!! since it can not find the update program !! Finished.

Good luck and Enjoy.

How to convert a UTF-8 string into Unicode?

So the issue is that UTF-8 code unit values have been stored as a sequence of 16-bit code units in a C# string. You simply need to verify that each code unit is within the range of a byte, copy those values into bytes, and then convert the new UTF-8 byte sequence into UTF-16.

public static string DecodeFromUtf8(this string utf8String)
{
    // copy the string as UTF-8 bytes.
    byte[] utf8Bytes = new byte[utf8String.Length];
    for (int i=0;i<utf8String.Length;++i) {
        //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
        utf8Bytes[i] = (byte)utf8String[i];
    }

    return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}

DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà

This is easy, however it would be best to find the root cause; the location where someone is copying UTF-8 code units into 16 bit code units. The likely culprit is somebody converting bytes into a C# string using the wrong encoding. E.g. Encoding.Default.GetString(utf8Bytes, 0, utf8Bytes.Length).


Alternatively, if you're sure you know the incorrect encoding which was used to produce the string, and that incorrect encoding transformation was lossless (usually the case if the incorrect encoding is a single byte encoding), then you can simply do the inverse encoding step to get the original UTF-8 data, and then you can do the correct conversion from UTF-8 bytes:

public static string UndoEncodingMistake(string mangledString, Encoding mistake, Encoding correction)
{
    // the inverse of `mistake.GetString(originalBytes);`
    byte[] originalBytes = mistake.GetBytes(mangledString);
    return correction.GetString(originalBytes);
}

UndoEncodingMistake("d\u00C3\u00A9j\u00C3\u00A0", Encoding(1252), Encoding.UTF8);

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

How to use the 'main' parameter in package.json?

One important function of the main key is that it provides the path for your entry point. This is very helpful when working with nodemon. If you work with nodemon and you define the main key in your package.json as let say "main": "./src/server/app.js", then you can simply crank up the server with typing nodemon in the CLI with root as pwd instead of nodemon ./src/server/app.js.

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

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();

Are HTTPS URLs encrypted?

Linking to my answer on a duplicate question. Not only is the URL available in the browsers history, the server side logs but it's also sent as the HTTP Referer header which if you use third party content, exposes the URL to sources outside your control.

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

How to get a enum value from string in C#?

Alternate solution can be:

baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
uint value = (uint)hKeyLocalMachine;

Or just:

uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;

Fastest way to check if string contains only digits

Can be about 20% faster by using just one comparison per char and for instead of foreach:

bool isDigits(string s) 
{ 
    if (s == null || s == "") return false; 

    for (int i = 0; i < s.Length; i++) 
        if ((s[i] ^ '0') > 9) 
            return false; 

    return true; 
}

Code used for testing (always profile because the results depend on hardware, versions, order, etc.):

static bool isDigitsFr(string s) { if (s == null || s == "") return false; for (int i = 0; i < s.Length; i++) if (s[i] < '0' || s[i] > '9') return false; return true; }
static bool isDigitsFu(string s) { if (s == null || s == "") return false; for (int i = 0; i < s.Length; i++) if ((uint)(s[i] - '0') > 9) return false; return true; }
static bool isDigitsFx(string s) { if (s == null || s == "") return false; for (int i = 0; i < s.Length; i++) if ((s[i] ^ '0') > 9) return false; return true; }
static bool isDigitsEr(string s) { if (s == null || s == "") return false; foreach (char c in s) if (c < '0' || c > '9') return false; return true; }
static bool isDigitsEu(string s) { if (s == null || s == "") return false; foreach (char c in s) if ((uint)(c - '0') > 9) return false; return true; }
static bool isDigitsEx(string s) { if (s == null || s == "") return false; foreach (char c in s) if ((c ^ '0') > 9) return false; return true; }
static void test()
{
    var w = new Stopwatch(); bool b; var s = int.MaxValue + ""; int r = 12345678*2; var ss = new SortedSet<string>(); //s = string.Concat(Enumerable.Range(0, 127).Select(i => ((char)i ^ '0') < 10 ? 1 : 0));
    w.Restart(); for (int i = 0; i < r; i++) b = s.All(char.IsDigit); w.Stop(); ss.Add(w.Elapsed + ".All .IsDigit"); 
    w.Restart(); for (int i = 0; i < r; i++) b = s.All(c => c >= '0' && c <= '9'); w.Stop(); ss.Add(w.Elapsed + ".All <>"); 
    w.Restart(); for (int i = 0; i < r; i++) b = s.All(c => (c ^ '0') < 10); w.Stop(); ss.Add(w.Elapsed + " .All ^"); 
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsFr(s); w.Stop(); ss.Add(w.Elapsed + " for     <>");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsFu(s); w.Stop(); ss.Add(w.Elapsed + " for     -");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsFx(s); w.Stop(); ss.Add(w.Elapsed + " for     ^");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsEr(s); w.Stop(); ss.Add(w.Elapsed + " foreach <>");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsEu(s); w.Stop(); ss.Add(w.Elapsed + " foreach -");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsEx(s); w.Stop(); ss.Add(w.Elapsed + " foreach ^");
    MessageBox.Show(string.Join("\n", ss)); return;
}

Results on Intel i5-3470 @ 3.2GHz, VS 2015 .NET 4.6.1 Release mode and optimizations enabled:

time    method          ratio
0.7776  for     ^       1.0000 
0.7984  foreach -       1.0268 
0.8066  foreach ^       1.0372 
0.8940  for     -       1.1497 
0.8976  for     <>      1.1543 
0.9456  foreach <>      1.2160 
4.4559  .All <>         5.7303 
4.7791  .All ^          6.1458 
4.8539  .All. IsDigit   6.2421 

For anyone tempted to use the shorter methods, note that

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

iOS application: how to clear notifications?

Just to expand on pcperini's answer. As he mentions you will need to add the following code to your application:didFinishLaunchingWithOptions: method;

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

You Also need to increment then decrement the badge in your application:didReceiveRemoteNotification: method if you are trying to clear the message from the message centre so that when a user enters you app from pressing a notification the message centre will also clear, ie;

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Give full access of .composer to user.

sudo chown -R 'user-name' /home/'user-name'/.composer

or

sudo chmod 777 -R /home/'user-name'/.composer

user-name is your system user-name.

to get user-name type "whoami" in terminal:

enter image description here

How to disable a link using only CSS?

One way you could do this with CSS, would be to set a CSS on a wrapping div that you set to disappear and something else takes it's place.

E.g.:

<div class="disabled">
    <a class="toggleLink" href="wherever">blah</a>
    <span class="toggleLink">blah</span
</div>

With a CSS like

.disabled a.toggleLink { display: none; }
span.toggleLink { display: none; }
.disabled span.toggleLink { display: inline; }

To actually turn off the a you'll have to replace it's click event or href, as described by others.

PS: Just to clarify I'd consider this a fairly untidy solution, and for SEO it's not the best either, but I believe it's the best with purely CSS.

jQuery Selector: Id Ends With?

$('element[id$=txtTitle]')

It's not strictly necessary to quote the text fragment you are matching against

Call to undefined function curl_init().?

If you're on Windows:

Go to your php.ini file and remove the ; mark from the beginning of the following line:

;extension=php_curl.dll

After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.


For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.

sudo apt-get install php-curl

Or if you're using the old PHP5

sudo apt-get install php5-curl

or

sudo apt-get install php5.6-curl

Then restart apache to activate the package with

sudo service apache2 restart

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

As you can see here:

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Difference between @GetMapping & @RequestMapping

@GetMapping supports the consumes attribute like @RequestMapping.

Converting a char to uppercase

You can use Character#toUpperCase() for this.

char fUpper = Character.toUpperCase(f);
char lUpper = Character.toUpperCase(l);

It has however some limitations since the world is aware of many more characters than can ever fit in 16bit char range. See also the following excerpt of the javadoc:

Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the toUpperCase(int) method.

How to list all methods for an object in Ruby?

You can do

current_user.methods

For better listing

puts "\n\current_user.methods : "+ current_user.methods.sort.join("\n").to_s+"\n\n"

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

You should write something like that :

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

I have just removed UITableView from Interface Builder, created it once again and strange 35px gone away.

It seems that it there is a strange bug in Interface Builder.

Android textview outline text

It is quite an old question but still I don't see any complete answers. So I am posting this solution, hoping that someone struggling with this problem might find it useful. The simplest and most effective solution is to override TextView class' onDraw method. Most implementations I have seen use drawText method to draw the stroke but that approach doesn't account for all the formatting alignment and text wrapping that goes in. And as a result often the stroke and text end up at different places. Following approach uses super.onDraw to draw both the stroke and fill parts of the text so you don't have to bother about rest of the stuff. Here are the steps

  1. Extend TextView class
  2. Override onDraw method
  3. Set paint style to FILL
  4. call parent class on Draw to render text in fill mode.
  5. save current text color.
  6. Set current text color to your stroke color
  7. Set paint style to Stroke
  8. Set stroke width
  9. And call parent class onDraw again to draw the stroke over the previously rendered text.

    package com.example.widgets;
    
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.widget.Button;
    
    public class StrokedTextView extends Button {
    
        private static final int DEFAULT_STROKE_WIDTH = 0;
    
        // fields
        private int _strokeColor;
        private float _strokeWidth;
    
        // constructors
        public StrokedTextView(Context context) {
            this(context, null, 0);
        }
    
        public StrokedTextView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public StrokedTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
    
            if(attrs != null) {
                TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.StrokedTextAttrs);
                _strokeColor = a.getColor(R.styleable.StrokedTextAttrs_textStrokeColor,
                        getCurrentTextColor());         
                _strokeWidth = a.getFloat(R.styleable.StrokedTextAttrs_textStrokeWidth,
                        DEFAULT_STROKE_WIDTH);
    
                a.recycle();
            }
            else {          
                _strokeColor = getCurrentTextColor();
                _strokeWidth = DEFAULT_STROKE_WIDTH;
            } 
            //convert values specified in dp in XML layout to
            //px, otherwise stroke width would appear different
            //on different screens
            _strokeWidth = dpToPx(context, _strokeWidth);           
        }    
    
        // getters + setters
        public void setStrokeColor(int color) {
            _strokeColor = color;        
        }
    
        public void setStrokeWidth(int width) {
            _strokeWidth = width;
        }
    
        // overridden methods
        @Override
        protected void onDraw(Canvas canvas) {
            if(_strokeWidth > 0) {
                //set paint to fill mode
                Paint p = getPaint();
                p.setStyle(Paint.Style.FILL);        
                //draw the fill part of text
                super.onDraw(canvas);       
                //save the text color   
                int currentTextColor = getCurrentTextColor();    
                //set paint to stroke mode and specify 
                //stroke color and width        
                p.setStyle(Paint.Style.STROKE);
                p.setStrokeWidth(_strokeWidth);
                setTextColor(_strokeColor);
                //draw text stroke
                super.onDraw(canvas);      
               //revert the color back to the one 
               //initially specified
               setTextColor(currentTextColor);
           } else {
               super.onDraw(canvas);
           }
       }
    
       /**
        * Convenience method to convert density independent pixel(dp) value
        * into device display specific pixel value.
        * @param context Context to access device specific display metrics 
        * @param dp density independent pixel value
        * @return device specific pixel value.
        */
       public static int dpToPx(Context context, float dp)
       {
           final float scale= context.getResources().getDisplayMetrics().density;
           return (int) (dp * scale + 0.5f);
       }            
    }
    

That is all. This class uses custom XML attributes to enable specifying stroke color and width from the XML layout files. Therefore, you need to add these attributes in your attr.xml file in subfolder 'values' under folder 'res'. Copy and paste the following in your attr.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="StrokedTextAttrs">
        <attr name="textStrokeColor" format="color"/>    
        <attr name="textStrokeWidth" format="float"/>
    </declare-styleable>                

</resources>

Once you are done with that, you can use the custom StrokedTextView class in your XML layout files and specify stroke color and width as well. Here is an example

<com.example.widgets.StrokedTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Stroked text sample"
    android:textColor="@android:color/white"
    android:textSize="25sp"
    strokeAttrs:textStrokeColor="@android:color/black"
    strokeAttrs:textStrokeWidth="1.7" />

Remember to replace package name with your project's package name. Also add the xmlns namespace in the layout file in order to use custom XML attributes. You can add the following line in your layout file's root node.

xmlns:strokeAttrs="http://schemas.android.com/apk/res-auto"

Android: Share plain text using intent (to all messaging apps)

Images or binary data:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

or HTML:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Set active tab style with AngularJS

@rob-juurlink I improved a bit on your solution:

instead of each route needing an active tab; and needing to set the active tab in each controller I do this:

var App = angular.module('App',[]);
App.config(['$routeProvider', function($routeProvider){
  $routeProvider.
  when('/dashboard', {
    templateUrl: 'partials/dashboard.html',
    controller: Ctrl1
  }).
  when('/lab', {
    templateUrl: 'partials/lab.html',
    controller: Ctrl2
  });
}]).run(['$rootScope', '$location', function($rootScope, $location){
   var path = function() { return $location.path();};
   $rootScope.$watch(path, function(newVal, oldVal){
     $rootScope.activetab = newVal;
   });
}]);

And the HTML looks like this. The activetab is just the url that relates to that route. This just removes the need to add code in each controller (dragging in dependencies like $route and $rootScope if this is the only reason they're used)

<ul>
    <li ng-class="{active: activetab=='/dashboard'}">
       <a href="#/dashboard">dashboard</a>
    </li>
    <li ng-class="{active: activetab=='/lab'}">
       <a href="#/lab">lab</a>
    </li>
</ul>

How to restore the dump into your running mongodb

mongodump: To dump all the records:

mongodump --db databasename

To limit the amount of data included in the database dump, you can specify --db and --collection as options to mongodump. For example:

mongodump --collection myCollection --db test

This operation creates a dump of the collection named myCollection from the database 'test' in a dump/ subdirectory of the current working directory. NOTE: mongodump overwrites output files if they exist in the backup data folder.


mongorestore: To restore all data to the original database:

1) mongorestore --verbose \path\dump

or restore to a new database:

2) mongorestore --db databasename --verbose \path\dump\<dumpfolder>

Note: Both requires mongod instances.

How to create a JPA query with LEFT OUTER JOIN

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

How can I generate Unix timestamps?

In Haskell...

To get it back as a POSIXTime type:

import Data.Time.Clock.POSIX
getPOSIXTime

As an integer:

import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime

Response to preflight request doesn't pass access control check

If you're writing a chrome-extension

You have to add in the manifest.json the permissions for your domain(s).

"permissions": [
   "http://example.com/*",
   "https://example.com/*",
   "http://www.example.com/*",
   "https://www.example.com/*"
]

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

I know this answer is not directly related to this questions' issue but in some cases the "Uncaught ReferenceError: google is not defined" issue will occur if your js file is being called prior to the google maps api you're using...so DON'T DO this:

<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

How do I get a python program to do nothing?

You could use a pass statement:

if condition:
    pass

Python 2.x documentation

Python 3.x documentation

However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.

If you have something like this:

if condition:        # condition in your case being `num2 == num5`
    pass
else:
    do_something()

You can in general change it to this:

if not condition:
    do_something()

But in this specific case you could (and should) do this:

if num2 != num5:        # != is the not-equal-to operator
    do_something()

How do I check if a C++ string is an int?

If you're just checking if word is a number, that's not too hard:

#include <ctype.h>

...

string word;
bool isNumber = true;
for(string::const_iterator k = word.begin(); k != word.end(); ++k)
    isNumber &&= isdigit(*k);

Optimize as desired.

How to dynamically allocate memory space for a string and get that string from user?

You can also use a regular expression, for instance the following piece of code:

char *names
scanf("%m[^\n]", &names)

will get the whole line from stdin, allocating dynamically the amount of space that it takes. After that, of course, you have to free names.

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

What are the minimum margins most printers can handle?

You shouldn't need to let the users specify the margin on your website - Let them do it on their computer. Print dialogs usually (Adobe and Preview, at least) give you an option to scale and center the output on the printable area of the page:

Adobe
alt text

Preview
alt text

Of course, this assumes that you have computer literate users, which may or may not be the case.

How to select all checkboxes with jQuery?

$('.checkall').change(function() {
    var checkboxes = $(this).closest('table').find('td').find(':checkbox');
    if($(this).is(':checked')) {
        checkboxes.attr('checked', 'checked');
    } else {
        checkboxes.removeAttr('checked');
    }
});

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

If you used debian-based OS, you can simply run

apt-get install ca-certificates

How to clear exisiting dropdownlist items when its content changes?

just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:

Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()

ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub

and it worked just fine

How to hide the border for specified rows of a table?

You can simply add these lines of codes here to hide a row,

Either you can write border:0 or border-style:hidden; border: none or it will happen the same thing

_x000D_
_x000D_
<style type="text/css">_x000D_
              table, th, td {_x000D_
               border: 1px solid;_x000D_
              }_x000D_
              _x000D_
              tr.hide_all > td, td.hide_all{_x000D_
                 border: 0;_x000D_
                _x000D_
              }_x000D_
          }_x000D_
        </style>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th>Firstname</th>_x000D_
        <th>Lastname</th>_x000D_
        <th>Savings</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Peter</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$100</td>_x000D_
      </tr>_x000D_
      <tr class= hide_all>_x000D_
        <td>Lois</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$150</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Joe</td>_x000D_
        <td>Swanson</td>_x000D_
        <td>$300</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Cleveland</td>_x000D_
        <td>Brown</td>_x000D_
        <td>$250</td>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

running these lines of codes can solve the problem easily

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

Difference between web reference and service reference?

Another point to take in consideration is that the new UI for Service Interface will give you much more flexibility on how you want to create your proxy class. For example, it will allow you to map data contracts to existing dlls, if they match (actually this is the default behaviour).

Implicit function declarations in C

Because of historical reasons going back to the very first version of C, functions are assumed to have an implicit definition of int function(int arg1, int arg2, int arg3, etc).

Edit: no, I was wrong about int for the arguments. Instead it passes whatever type the argument is. So it could be an int or a double or a char*. Without a prototype the compiler will pass whatever size the argument is and the function being called had better use the correct argument type to receive it.

For more details look up K&R C.

How to inject a Map using the @Value Spring Annotation?

Here is how we did it. Two sample classes as follow:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {

    @Autowired
    protected KafkaConsumerProperties kafkaConsumerProperties;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
    }
...

@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
    protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();

    @ConfigurationProperties("kafkaConsumerConfig")
    public Map<String, Object> getKafkaConsumerConfig() {
        return (kafkaConsumerConfig);
    }
...

To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value

//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:

kafkaConsumerConfig:
  "[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
  "[group.id]": test-consumer-group-local
  "[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
  "[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer

React Error: Target Container is not a DOM Element

Also make sure id set in index.html is same as the one you referring to in index.js

index.html:

<body> 
    <div id="root"></div>
    <script src="/bundle.js"></script>
</body>

index.js:

ReactDOM.render(<App/>,document.getElementById('root'));

How to distinguish mouse "click" and "drag"

Cleaner ES2015

_x000D_
_x000D_
let drag = false;_x000D_
_x000D_
document.addEventListener('mousedown', () => drag = false);_x000D_
document.addEventListener('mousemove', () => drag = true);_x000D_
document.addEventListener('mouseup', () => console.log(drag ? 'drag' : 'click'));
_x000D_
_x000D_
_x000D_

Didn't experience any bugs, as others comment.

How do you execute SQL from within a bash script?

I've used the jdbcsql project on Sourceforge.

On *nix systems, this will create a csv stream of results to standard out:

java -Djava.security.egd=file///dev/urandom -jar jdbcsql.jar -d oracledb_SID -h $host -p 1521 -U some_username -m oracle -P "$PW" -f excel -s "," "$1"

Note that adding the -Djava.security.egd=file///dev/urandom increases performance greatly

Windows commands are similar: see http://jdbcsql.sourceforge.net/

How to configure a HTTP proxy for svn

There are two common approaches for this:

If you are on Windows, you can also write http-proxy- options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.

Adding a Time to a DateTime in C#

If you are using two DateTime objects, one to store the date the other the time, you could do the following:

var date = new DateTime(2016,6,28);

var time = new DateTime(1,1,1,13,13,13);

var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks);

An example of this can be found here

Get an image extension from an uploaded file in Laravel

Or can use the Extension Splitter Trickster::getExtention() function of https://github.com/secrethash/trickster

Trickster::getExtention('some-funny.image.jpg'); It returns jpg

keycloak Invalid parameter: redirect_uri

What worked for me was adding wildchar '*'. Although for production builds, I am going to be more specific with the value of this field. But for dev purposes you can do this.

enter image description here

Setting available under, keycloak admin console -> Realm_Name -> Cients -> Client_Name.

EDIT: DO NOT DO THIS IN PRODUCTION. Doing so creates a large security flaw.

Excel VBA Run-time error '13' Type mismatch

Diogo

Justin has given you some very fine tips :)

You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.

For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code

Sheets("Sheet1").Range("A1").Value - 1

I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.

Option Explicit

Sub Sample()
  Dim ws As Worksheet
  Dim x As Integer, i As Integer, a As Integer, y As Integer
  Dim name As String
  Dim lastRow As Long
10        On Error GoTo Whoa

20        Application.ScreenUpdating = False

30        name = InputBox("Please insert the name of the sheet")

40        If Len(Trim(name)) = 0 Then Exit Sub

50        Set ws = Sheets(name)

60        With ws
70            If Not IsError(.Range("BE4").Value) Then
80                x = Val(.Range("BE4").Value)
90            Else
100               MsgBox "Please check the value of cell BE4. It seems to have an error"
110               GoTo LetsContinue
120           End If

130           .Range("BF4").Value = x

140           lastRow = .Range("BE" & Rows.Count).End(xlUp).Row

150           For i = 5 To lastRow
160               If IsError(.Range("BE" & i)) Then
170                   MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180                   GoTo LetsContinue
190               End If

200               a = 0: y = Val(.Range("BE" & i))
210               If y <> x Then
220                   If y <> 0 Then
230                       If y = 3 Then
240                           a = x
250                           .Range("BF" & i) = Val(.Range("BE" & i)) - x

260                           x = Val(.Range("BE" & i)) - x
270                       End If
280                       .Range("BF" & i) = Val(.Range("BE" & i)) - a
290                       x = Val(.Range("BE" & i)) - a
300                   Else
310                       .Range("BF" & i).ClearContents
320                   End If
330               Else
340                   .Range("BF" & i).ClearContents
350               End If
360           Next i
370       End With

LetsContinue:
380       Application.ScreenUpdating = True
390       Exit Sub
Whoa:
400       MsgBox "Error Description :" & Err.Description & vbNewLine & _
         "Error at line     : " & Erl
410       Resume LetsContinue
End Sub

Where value in column containing comma delimited values

SELECT * FROM TABLE_NAME WHERE
        (
            LOCATE(',DOG,', CONCAT(',',COLUMN,','))>0 OR
            LOCATE(',CAT,', CONCAT(',',COLUMN,','))>0
        );

Easy login script without database

I would use a two file setup like this:

index.php

<?php 
session_start(); 

define('DS',  TRUE); // used to protect includes
define('USERNAME', $_SESSION['username']);
define('SELF',  $_SERVER['PHP_SELF'] );

if (!USERNAME or isset($_GET['logout']))
 include('login.php');

// everything below will show after correct login 
?>

login.php

<?php defined('DS') OR die('No direct access allowed.');

$users = array(
 "user" => "userpass"
);

if(isset($_GET['logout'])) {
    $_SESSION['username'] = '';
    header('Location:  ' . $_SERVER['PHP_SELF']);
}

if(isset($_POST['username'])) {
    if($users[$_POST['username']] !== NULL && $users[$_POST['username']] == $_POST['password']) {
  $_SESSION['username'] = $_POST['username'];
  header('Location:  ' . $_SERVER['PHP_SELF']);
    }else {
        //invalid login
  echo "<p>error logging in</p>";
    }
}

echo '<form method="post" action="'.SELF.'">
  <h2>Login</h2>
  <p><label for="username">Username</label> <input type="text" id="username" name="username" value="" /></p>
  <p><label for="password">Password</label> <input type="password" id="password" name="password" value="" /></p>
  <p><input type="submit" name="submit" value="Login" class="button"/></p>
  </form>';
exit; 
?>

How do I import a sql data file into SQL Server?

  1. Start SQL Server Management Studio
  2. Connect to your database
  3. File > Open > File and pick your file
  4. Execute it

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

Pass user defined environment variable to tomcat

Environment variables can be set, by creating a setenv.bat (windows) or setenv.sh (unix) file in the bin folder of your tomcat installation directory. However, environment variables will not be accessabile from within your code.

System properties are set by -D arguments of the java process. You can define java starting arguments in the environment variable JAVA_OPTS.

My suggestions is the combination of these two mechanisms. In your apache-tomcat-0.0.0\bin\setenv.bat write:

set JAVA_OPTS=-DAPP_MASTER_PASSWORD=password1

and in your Java code write:

System.getProperty("APP_MASTER_PASSWORD")

Why use a ReentrantLock if one can use synchronized(this)?

Synchronized locks does not offer any mechanism of waiting queue in which after the execution of one thread any thread running in parallel can acquire the lock. Due to which the thread which is there in the system and running for a longer period of time never gets chance to access the shared resource thus leading to starvation.

Reentrant locks are very much flexible and has a fairness policy in which if a thread is waiting for a longer time and after the completion of the currently executing thread we can make sure that the longer waiting thread gets the chance of accessing the shared resource hereby decreasing the throughput of the system and making it more time consuming.

Cannot GET / Nodejs Error

Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js

node_modules/
app/
  index.html
  server.js

After printing out the __dirname path, I realized that the __dirname path was where my server was running (app/).

So, the answer to your question is this:

If your server.js file is in the same folder as the files you are trying to render, then

app.use( express.static( path.join( application_root, 'site') ) );

should actually be

app.use(express.static(application_root));

The only time you would want to use the original syntax that you had would be if you had a folder tree like so:

app/
  index.html
node_modules
server.js

where index.html is in the app/ directory, whereas server.js is in the root directory (i.e. the same level as the app/ directory).

Side note: Intead of calling the path utility, you can use the syntax application_root + 'site' to join a path.

Overall, your code could look like:

// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration

//Create server
var app = express();

// Configure server
app.configure( function() {

    //Don't change anything here...

    //Where to serve static content
    app.use( express.static( application_root ) );

    //Nothing changes here either...
});

//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

PNG has 2 advantages: it has smaller size and it's more widely used and supported (except in case favicons). As mentioned before ICO, can have multiple size icons, which is useful for desktop applications, but not too much for websites. I would recommend you to put a favicon.ico in the root of your application. An if you have access to the Head of your website pages use the tag to point to a png file. So older browser will show the favicon.ico and newer ones the png.

To create Png and Icon files I would recommend The Gimp.

How do I find the location of Python module sources?

I realize this answer is 4 years late, but the existing answers are misleading people.

The right way to do this is never __file__, or trying to walk through sys.path and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).

It's the inspect module—in particular, getfile or getsourcefile.

Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping .pyc to .py files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to .so/.pyd files that don't support __file__; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it.

Meanwhile, every Python version's source from 2.0+ is available online at http://hg.python.org/cpython/file/X.Y/ (e.g., 2.7 or 3.3). So, once you discover that inspect.getfile(datetime) is a .so or .pyd file like /usr/local/lib/python2.7/lib-dynload/datetime.so, you can look it up inside the Modules directory. Strictly speaking, there's no way to be sure of which file defines which module, but nearly all of them are either foo.c or foomodule.c, so it shouldn't be hard to guess that datetimemodule.c is what you want.

Printing image with PrintDocument. how to adjust the image to fit paper size

all these answers has the problem, that's always stretching the image to pagesize and cuts off some content at trying this.
Found a little bit easier way.

My own solution only stretch(is this the right word?) if the image is to large, can use multiply copies and pageorientations.

                PrintDialog dlg = new PrintDialog();

            if (dlg.ShowDialog() == true)
            {
                BitmapImage bmi = new BitmapImage(new Uri(strPath));

                Image img = new Image();
                img.Source = bmi;

                if (bmi.PixelWidth < dlg.PrintableAreaWidth ||
                           bmi.PixelHeight < dlg.PrintableAreaHeight)
                {
                    img.Stretch = Stretch.None;
                    img.Width = bmi.PixelWidth;
                    img.Height = bmi.PixelHeight;
                }


                if (dlg.PrintTicket.PageBorderless == PageBorderless.Borderless)
                {
                    img.Margin = new Thickness(0);
                }
                else
                {
                    img.Margin = new Thickness(48);
                }
                img.VerticalAlignment = VerticalAlignment.Top;
                img.HorizontalAlignment = HorizontalAlignment.Left;

                for (int i = 0; i < dlg.PrintTicket.CopyCount; i++)
                {
                    dlg.PrintVisual(img, "Print a Image");
                }
            }

Removing padding gutter from grid columns in Bootstrap 4

You can use this css code to get gutterless grid in bootstrap.

.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
  margin-left: 0;
  margin-right: 0;
}

.no-gutter>[class^="col-"]{
  padding-left: 0;
  padding-right: 0;
}

Pentaho Data Integration SQL connection

Turns out I will missing a class called mysql-connector-java-5.1.2.jar, I added it this folder (C:\Program Files\pentaho\design-tools\data-integration\lib) and it worked with a MySQL connection and my data and tables appear.

Generate a random number in a certain range in MATLAB

If you are looking for Uniformly distributed pseudorandom integers use:

randi([13, 20])

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

You don't have a field named user_email in the members table ... as for why, I'm not sure as the code "looks" like it should try to join on different fields

Does the Auth::attempt method perform a join of the schema? Run grep -Rl 'class Auth' /path/to/framework and find where the attempt method is and what it does.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup

Edit: details you asked for. in Eclipse 3.4

  1. Run->Run Configurations...

  2. if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner

  3. on the right, "Main" tab make sure the project and the class are the right ones

  4. select the "Arguments" tab on the right. this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
    -Xmx2048m

    I think that 1024m should more than enough for what you need though!

  5. Click Apply, then Click Run

  6. Should work :)

Comparing two NumPy arrays for equality, element-wise

Now use np.array_equal. From documentation:

np.array_equal([1, 2], [1, 2])
True
np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
np.array_equal([1, 2], [1, 2, 3])
False
np.array_equal([1, 2], [1, 4])
False

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.

How to Apply Gradient to background view of iOS Swift App

Just modifying the above mentioned answer.

enter image description here

func setGradientBackground() {
    let colorTop =  UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
    let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).cgColor
                
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [colorTop, colorBottom]
    gradientLayer.locations = [0.0, 1.0]
    gradientLayer.frame = self.view.bounds
            
    self.view.layer.insertSublayer(gradientLayer, at:0)
}

Then call this method within viewWillAppear

override func viewWillAppear(_ animated: Bool) {
    setGradientBackground()
    super.viewWillAppear(animated)
}

enter image description here

User Authentication in ASP.NET Web API

If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.

void EnsureAuthenticated(string role)
{
    string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
    if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
    if (role != null && !Roles.IsUserInRole(parts[0], role))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}

From the client side, this helper creates a HttpClient with the authentication header in place:

static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
    return client;
}

Display image at 50% of its "native" size

The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:

<img src="..." onload="this.width/=2;this.onload=null;" />

The reason for the this.onload=null addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:

<img src="..." onload="this.width/=2;" />

Which is quite succinct.

mkdir's "-p" option

PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.

mkdir -p /usr/bin/comm/diff/er/fence

if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence

As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.

Linux : Search for a Particular word in a List of files under a directory

This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.

grep -rn '<word or regex>' <location>

do a

man grep 

for more options

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn

 List<AttributeHistory> findByValueIn(List<String> values);

Get random item from array

If you don't mind picking the same item again at some other time:

$items[rand(0, count($items) - 1)];

How to Add Date Picker To VBA UserForm

Just throw some light in to some issues related to this control.

Date picker is not a standard control that comes with office package. So developers encountered issues like missing date picker controls when application deployed in some other machiens/versions of office. In order to use it you have to activate the reference to the .dll, .ocx file that contains it.

In the event of a missing date picker, you have to replace MSCOMCT2.OCX file in System or System32 directory and register it properly. Try this link to do the proper replacement of the file.

In the VBA editor menu bar-> select tools-> references and then find the date picker reference and check it.

If you need the file, download MSCOMCT2.OCX from here.

SHA-256 or MD5 for file integrity

To 1): Yes, on most CPUs, SHA-256 is about only 40% as fast as MD5.

To 2): I would argue for a different algorithm than MD5 in such a case. I would definitely prefer an algorithm that is considered safe. However, this is more a feeling. Cases where this matters would be rather constructed than realistic, e.g. if your backup system encounters an example case of an attack on an MD5-based certificate, you are likely to have two files in such an example with different data, but identical MD5 checksums. For the rest of the cases, it doesn't matter, because MD5 checksums have a collision (= same checksums for different data) virtually only when provoked intentionally. I'm not an expert on the various hashing (checksum generating) algorithms, so I can not suggest another algorithm. Hence this part of the question is still open. Suggested further reading is Cryptographic Hash Function - File or Data Identifier on Wikipedia. Also further down on that page there is a list of cryptographic hash algorithms.

To 3): MD5 is an algorithm to calculate checksums. A checksum calculated using this algorithm is then called an MD5 checksum.

Editable 'Select' element

Thanks to @Arraxas's anwser, I customized the arrow and make the input element auto-adaptive to the select element, and it looks good on Chrome, Firefox of my Android mobile phone (set color:transparent for select and some color for option to hide text display of the select because the input and .combobox div:after cannot completely cover select).

_x000D_
_x000D_
/* https://stackoverflow.com/questions/13694271/modify-select-so-only-the-first-one-is-gray/41941056#41941056
select option:first-child, */
.combobox select, .combobox select option { color: #000000; }
.combobox select:invalid, .combobox select option[value=""] { color:grey; }

.combobox {position:absolute; left:80px; top:6px;}
.combobox>div { position:relative; font-size:1em; }
.combobox select {
    font-size:inherit; color:transparent;
    padding:0; -moz-appearance:none; -webkit-appearance:none; appearance:none;
    border:1px solid blueviolet;
}
.combobox input {
    position:absolute;top:1px;left:0px; text-overflow:ellipsis;
    box-sizing:border-box; padding:0px; margin:0px; height:calc(100% - 1px); width:calc(100% - 20px);
    border:1px solid blueviolet; border-right:none; border-top:none;
}
.combobox>div:after{
    position:absolute; top:0px; right:0px; height:100%; width:20px;
    box-sizing:border-box; content:"?"; border:1px solid blueviolet; pointer-events:none;
    display:flex; flex-direction:row; align-items:center; justify-content:center;
}
.combobox select:focus, .combobox input:focus {outline:none;}
_x000D_
<!-- mandatory benefits/social security/welfare -->
<div class="combobox"><div>
    <select id=MandatoryBenefits onchange="this.nextElementSibling.value=this.value" required>
        <option value="" selected>Select ...</option>
        <option value="Pension">Pension %</option>
        <option value="Medical">Medical %</option>
        <option value="Unemployment">Unemployment %</option>
        <option value="Injury">Injury %</option>
        <option value="Maternity">Maternity %</option>
        <option value="Serious Illness">Serious Illness %</option>
        <option value="Housing Fund">Housing Fund %</option>
    </select>
    <input type="text" value="" onchange="this.previousElementSibling.selectedIndex=0"
        oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" />
</div></div>
_x000D_
_x000D_
_x000D_

online demo (@jsbin)

Can a Windows batch file determine its own file name?

Yes.

Use the special %0 variable to get the path to the current file.

Write %~n0 to get just the filename without the extension.

Write %~n0%~x0 to get the filename and extension.

Also possible to write %~nx0 to get the filename and extension.

base64 encode in MySQL

SELECT `id`,`name`, TO_BASE64(content) FROM `db`.`upload`

this will convert the blob value from content column to base64 string. Then you can do with this string whatever you want even insert it into another table

How to filter input type="file" dialog by specific file type?

You can use the accept attribute along with the . It doesn't work in IE and Safari.

Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.

For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes

add Shadow on UIView using swift 3

    func shadow(Vw : UIView)
    {
        Vw.layer.masksToBounds = false
        Vw.layer.shadowColor =  colorLiteral(red: 0.5058823529, green: 0.5333333333, blue: 0.6117647059, alpha: 1)
        Vw.layer.shadowOffset = CGSize(width: 0, height: 1)
        Vw.layer.shadowRadius = 5.0
        Vw.layer.shadowOpacity = 15.0
        Vw.layer.cornerRadius = 5.0
    }

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I had the same issue when I changed the home directory of one use. In my case it was because of selinux. I used the below to fix the issue:

selinuxenabled 0
setenforce 0

Java, reading a file from current directory?

try using "." E.g.

File currentDirectory = new File(".");

This worked for me

ASP.NET Web Application Message Box

if you will include

System.Windows.forms

as namespace then it will conflict . Use

btn_click()
{

System.Windows.Forms.MessageBox.Show("Hello");

}

CSS3 Transparency + Gradient

Here is my code:

background: #e8e3e3; /* Old browsers */
  background: -moz-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%, rgba(246, 242, 242, 0.95) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(232, 227, 227, 0.95)), color-stop(100%,rgba(246, 242, 242, 0.95))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* IE10+ */
  background: linear-gradient(to bottom,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='rgba(232, 227, 227, 0.95)', endColorstr='rgba(246, 242, 242, 0.95)',GradientType=0 ); /* IE6-9 */

Angular ReactiveForms: Producing an array of checkbox values?

I don't see a solution here that completely answers the question using reactive forms to its fullest extent so here's my solution for the same.


Summary

Here's the pith of the detailed explanation along with a StackBlitz example.

  1. Use FormArray for the checkboxes and initialize the form.
  2. The valueChanges observable is perfect for when you want the form to display something but store something else in the component. Map the true/false values to the desired values here.
  3. Filter out the false values at the time of submission.
  4. Unsubscribe from valueChanges observable.

StackBlitz example


Detailed explanation

Use FormArray to define the form

As already mentioned in the answer marked as correct. FormArray is the way to go in such cases where you would prefer to get the data in an array. So the first thing you need to do is create the form.

checkboxGroup: FormGroup;
checkboxes = [{
    name: 'Value 1',
    value: 'value-1'
}, {
    name: 'Value 2',
    value: 'value-2'
}];

this.checkboxGroup = this.fb.group({
    checkboxes: this.fb.array(this.checkboxes.map(x => false))
});

This will just set the initial value of all the checkboxes to false.

Next, we need to register these form variables in the template and iterate over the checkboxes array (NOT the FormArray but the checkbox data) to display them in the template.

<form [formGroup]="checkboxGroup">
    <ng-container *ngFor="let checkbox of checkboxes; let i = index" formArrayName="checkboxes">
        <input type="checkbox" [formControlName]="i" />{{checkbox.name}}
    </ng-container>
</form>

Make use of the valueChanges observable

Here's the part I don't see mentioned in any answer given here. In situations such as this, where we would like to display said data but store it as something else, the valueChanges observable is very helpful. Using valueChanges, we can observe the changes in the checkboxes and then map the true/false values received from the FormArray to the desired data. Note that this will not change the selection of the checkboxes as any truthy value passed to the checkbox will mark it as checked and vice-versa.

subscription: Subscription;

const checkboxControl = (this.checkboxGroup.controls.checkboxes as FormArray);
this.subscription = checkboxControl.valueChanges.subscribe(checkbox => {
    checkboxControl.setValue(
        checkboxControl.value.map((value, i) => value ? this.checkboxes[i].value : false),
        { emitEvent: false }
    );
});

This basically maps the FormArray values to the original checkboxes array and returns the value in case the checkbox is marked as true, else it returns false. The emitEvent: false is important here since setting the FormArray value without it will cause valueChanges to emit an event creating an endless loop. By setting emitEvent to false, we are making sure the valueChanges observable does not emit when we set the value here.

Filter out the false values

We cannot directly filter the false values in the FormArray because doing so will mess up the template since they are bound to the checkboxes. So the best possible solution is to filter out the false values during submission. Use the spread operator to do this.

submit() {
    const checkboxControl = (this.checkboxGroup.controls.checkboxes as FormArray);
    const formValue = {
        ...this.checkboxGroup.value,
        checkboxes: checkboxControl.value.filter(value => !!value)
    }
    // Submit formValue here instead of this.checkboxGroup.value as it contains the filtered data
}

This basically filters out the falsy values from the checkboxes.

Unsubscribe from valueChanges

Lastly, don't forget to unsubscribe from valueChanges

ngOnDestroy() {
    this.subscription.unsubscribe();
}

Note: There is a special case where a value cannot be set to the FormArray in valueChanges, i.e if the checkbox value is set to the number 0. This will make it look like the checkbox cannot be selected since selecting the checkbox will set the FormControl as the number 0 (a falsy value) and hence keep it unchecked. It would be preferred not to use the number 0 as a value but if it is required, you have to conditionally set 0 to some truthy value, say string '0' or just plain true and then on submitting, convert it back to the number 0.

StackBlitz example

The StackBlitz also has code for when you want to pass default values to the checkboxes so they get marked as checked in the UI.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

JDBC API mostly consists of interfaces which work independently of any database. A database specific driver is required for each database which implements the JDBC API.

First download the MySQL connector jar from www.mysql.com, then:

Right Click the project -- > build path -- > configure build path

In the libraries tab press Add External Jar and select your jar.

Take a char input from the Scanner

You could take the first character from Scanner.next:

char c = reader.next().charAt(0);

To consume exactly one character you could use:

char c = reader.findInLine(".").charAt(0);

To consume strictly one character you could use:

char c = reader.next(".").charAt(0);

Real world use of JMS/message queues?

Use them all the time to process long-running operations asynchronously. A web user won't want to wait for more than 5 seconds for a request to process. If you have one that runs longer than that, one design is to submit the request to a queue and immediately send back a URL that the user can check to see when the job is finished.

Publish/subscribe is another good technique for decoupling senders from many receivers. It's a flexible architecture, because subscribers can come and go as needed.

In php, is 0 treated as empty?

proper example. just create int type field( example mobile number) in the database and submit an blank value for the following database through a form or just insert using SQL. what it will be saved in database 0 because it is int type and cannot be saved as blank or null. therefore it is empty but it will be saved as 0. so when you fetch data through PHP and check for the empty values. it is very useful and logically correct.

0.00, 0.000, 0.0000 .... 0.0...0 is also empty and the above example can also be used for storing different type of values in database like float, double, decimal( decimal have different variants like 0.000 and so on.

Convert UIImage to NSData and convert back to UIImage in Swift?

Details

  • Xcode 10.2.1 (10E1001), Swift 5

Solution 1

guard let image = UIImage(named: "img") else { return }
let jpegData = image.jpegData(compressionQuality: 1.0)
let pngData = image.pngData()

Solution 2.1

extension UIImage {
    func toData (options: NSDictionary, type: CFString) -> Data? {
        guard let cgImage = cgImage else { return nil }
        return autoreleasepool { () -> Data? in
            let data = NSMutableData()
            guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, type, 1, nil) else { return nil }
            CGImageDestinationAddImage(imageDestination, cgImage, options)
            CGImageDestinationFinalize(imageDestination)
            return data as Data
        }
    }
}

Usage of solution 2.1

// about properties: https://developer.apple.com/documentation/imageio/1464962-cgimagedestinationaddimage
let options: NSDictionary =     [
    kCGImagePropertyOrientation: 6,
    kCGImagePropertyHasAlpha: true,
    kCGImageDestinationLossyCompressionQuality: 0.5
]

// https://developer.apple.com/documentation/mobilecoreservices/uttype/uti_image_content_types
guard let data = image.toData(options: options, type: kUTTypeJPEG) else { return }
let size = CGFloat(data.count)/1000.0/1024.0
print("\(size) mb")

Solution 2.2

extension UIImage {

    func toJpegData (compressionQuality: CGFloat, hasAlpha: Bool = true, orientation: Int = 6) -> Data? {
        guard cgImage != nil else { return nil }
        let options: NSDictionary =     [
                                            kCGImagePropertyOrientation: orientation,
                                            kCGImagePropertyHasAlpha: hasAlpha,
                                            kCGImageDestinationLossyCompressionQuality: compressionQuality
                                        ]
        return toData(options: options, type: .jpeg)
    }

    func toData (options: NSDictionary, type: ImageType) -> Data? {
        guard cgImage != nil else { return nil }
        return toData(options: options, type: type.value)
    }
    // about properties: https://developer.apple.com/documentation/imageio/1464962-cgimagedestinationaddimage
    func toData (options: NSDictionary, type: CFString) -> Data? {
        guard let cgImage = cgImage else { return nil }
        return autoreleasepool { () -> Data? in
            let data = NSMutableData()
            guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, type, 1, nil) else { return nil }
            CGImageDestinationAddImage(imageDestination, cgImage, options)
            CGImageDestinationFinalize(imageDestination)
            return data as Data
        }
    }

    // https://developer.apple.com/documentation/mobilecoreservices/uttype/uti_image_content_types
    enum ImageType {
        case image // abstract image data
        case jpeg                       // JPEG image
        case jpeg2000                   // JPEG-2000 image
        case tiff                       // TIFF image
        case pict                       // Quickdraw PICT format
        case gif                        // GIF image
        case png                        // PNG image
        case quickTimeImage             // QuickTime image format (OSType 'qtif')
        case appleICNS                  // Apple icon data
        case bmp                        // Windows bitmap
        case ico                        // Windows icon data
        case rawImage                   // base type for raw image data (.raw)
        case scalableVectorGraphics     // SVG image
        case livePhoto                  // Live Photo

        var value: CFString {
            switch self {
            case .image: return kUTTypeImage
            case .jpeg: return kUTTypeJPEG
            case .jpeg2000: return kUTTypeJPEG2000
            case .tiff: return kUTTypeTIFF
            case .pict: return kUTTypePICT
            case .gif: return kUTTypeGIF
            case .png: return kUTTypePNG
            case .quickTimeImage: return kUTTypeQuickTimeImage
            case .appleICNS: return kUTTypeAppleICNS
            case .bmp: return kUTTypeBMP
            case .ico: return kUTTypeICO
            case .rawImage: return kUTTypeRawImage
            case .scalableVectorGraphics: return kUTTypeScalableVectorGraphics
            case .livePhoto: return kUTTypeLivePhoto
            }
        }
    }
}

Usage of solution 2.2

let compressionQuality: CGFloat = 0.4
guard let data = image.toJpegData(compressionQuality: compressionQuality) else { return }
printSize(of: data)

let options: NSDictionary =     [
                                    kCGImagePropertyHasAlpha: true,
                                    kCGImageDestinationLossyCompressionQuality: compressionQuality
                                ]
guard let data2 = image.toData(options: options, type: .png) else { return }
printSize(of: data2)

Problems

Image representing will take a lot of cpu and memory resources. So, in this case it is better to follow several rules:

- do not run jpegData(compressionQuality:) on main queue

- run only one jpegData(compressionQuality:) simultaneously

Wrong:

for i in 0...50 {
    DispatchQueue.global(qos: .utility).async {
        let quality = 0.02 * CGFloat(i)
        //let data = image.toJpegData(compressionQuality: quality)
        let data = image.jpegData(compressionQuality: quality)
        let size = CGFloat(data!.count)/1000.0/1024.0
        print("\(i), quality: \(quality), \(size.rounded()) mb")
    }
}

Right:

let serialQueue = DispatchQueue(label: "queue", qos: .utility, attributes: [], autoreleaseFrequency: .workItem, target: nil)

for i in 0...50 {
    serialQueue.async {
        let quality = 0.02 * CGFloat(i)
        //let data = image.toJpegData(compressionQuality: quality)
        let data = image.jpegData(compressionQuality: quality)
        let size = CGFloat(data!.count)/1000.0/1024.0
        print("\(i), quality: \(quality), \(size.rounded()) mb")
    }
}

Links

How to catch an Exception from a thread

Use a Thread.UncaughtExceptionHandler.

Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};
Thread t = new Thread() {
    @Override
    public void run() {
        System.out.println("Sleeping ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }
};
t.setUncaughtExceptionHandler(h);
t.start();

WCF Service Returning "Method Not Allowed"

Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract:

[ServiceContract]
public interface IUploadService
{
    [WebGet()]
    [OperationContract]
    string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.

    [OperationContract]
    void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.
 }

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

Removing All Items From A ComboBox?

Psuedo code ahead (updated with actual code):

Do While ComboBox1.ListCount > 0
    ComboBox1.RemoveItem (0)
Loop

Basically, while you have items, remove the first item from the combobox. Once all the items have been removed (count = 0), your box is blank.

Method 2: Even better

ComboBox1.Clear

How to set cursor position in EditText?

I have done this way to set cursor position to end of the text after updating the text of EditText programmatically here, etmsg is EditText

etmsg.setText("Updated Text From another Activity");
int position = etmsg.length();
Editable etext = etmsg.getText();
Selection.setSelection(etext, position);

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.

From Books Online, on MAXDOP:

Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.

See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.

Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.

Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.

Google Android USB Driver and ADB

Locate the following file

C:\Users\[your name]\.android\adb_usb.ini

And make the following changes:

# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207

I added 0x2207 to the file. This number is part of the hardware id, which can be found under the device's hardware information.

Mine was:

USB\VID_2207&PID_0010&MI_01

(I tried executing android update adb, but it did nothing.)

How do I connect to this localhost from another computer on the same network?

Provided both machines are in the same workgroup, open cmd.exe on the machine you want to connect to, type ipconfig and note the IP at the IPv4 Address line.

Then, on the machine you want to connect with, use http:// + the IP of the target machine.

That should do it.

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

This has been discussed in many posts but still I could not figure out a solution with:

android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"

Below solution will work with any of the ui components : Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout clicks inside a listview cell and also will respond to onItemClick:

Adapter class - getview():

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = lInflater.inflate(R.layout.my_ref_row, parent, false);
            }
            final Organization currentOrg = organizationlist.get(position).getOrganization();

            TextView name = (TextView) view.findViewById(R.id.name);
            Button btn = (Button) view.findViewById(R.id.btn_check);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    context.doSelection(currentOrg);

                }
            });

       if(currentOrg.isSelected()){
            btn.setBackgroundResource(R.drawable.sub_search_tick);
        }else{
            btn.setBackgroundResource(R.drawable.sub_search_tick_box);
        }

    }

In this was you can get the button clicked object to the activity. (Specially when you want the button to act as a check box with selected and non-selected states):

    public void doSelection(Organization currentOrg) {
        Log.e("Btn clicked ", currentOrg.getOrgName());
        if (currentOrg.isSelected() == false) {
            currentOrg.setSelected(true);
        } else {
            currentOrg.setSelected(false);
        }
        adapter.notifyDataSetChanged();

    }

SQL to find the number of distinct values in a column

**

Using following SQL we can get the distinct column value count in Oracle 11g.

**

Select count(distinct(Column_Name)) from TableName

Remote origin already exists on 'git push' to a new repository

You need to check the origin and add if not exists.

if ! git config remote.origin.url >/dev/null; then
    git remote add origin [email protected]:john/doe.git
fi

Create file check.sh, paste the script update your git repository URL and run ./check.sh.

What is the list of supported languages/locales on Android?

Arabic, Egypt (ar_EG)
Arabic, Israel (ar_IL)
Bulgarian, Bulgaria (bg_BG)
Catalan, Spain (ca_ES)
Czech, Czech Republic (cs_CZ)
Danish, Denmark(da_DK)
German, Austria (de_AT)
German, Switzerland (de_CH)
German, Germany (de_DE)
German, Liechtenstein (de_LI)
Greek, Greece (el_GR)
English, Australia (en_AU)
English, Canada (en_CA)
English, Britain (en_GB)
English, Ireland (en_IE)
English, India (en_IN)
English, New Zealand (en_NZ)
English, Singapore(en_SG)
English, US (en_US)
English, South Africa (en_ZA)
Spanish (es_ES)
Spanish, US (es_US)
Finnish, Finland (fi_FI)
French, Belgium (fr_BE)
French, Canada (fr_CA)
French, Switzerland (fr_CH)
French, France (fr_FR)
Hebrew, Israel (he_IL)
Hindi, India (hi_IN)
Croatian, Croatia (hr_HR)
Hungarian, Hungary (hu_HU)
Indonesian, Indonesia (id_ID)
Italian, Switzerland (it_CH)
Italian, Italy (it_IT)
Japanese (ja_JP)
Korean (ko_KR)
Lithuanian, Lithuania (lt_LT)
Latvian, Latvia (lv_LV)
Norwegian bokmål, Norway (nb_NO)
Dutch, Belgium (nl_BE)
Dutch, Netherlands (nl_NL)
Polish (pl_PL)
Portuguese, Brazil (pt_BR)
Portuguese, Portugal (pt_PT)
Romanian, Romania (ro_RO)
Russian (ru_RU)
Slovak, Slovakia (sk_SK)
Slovenian, Slovenia (sl_SI)
Serbian (sr_RS)
Swedish, Sweden (sv_SE)
Thai, Thailand (th_TH)
Tagalog, Philippines (tl_PH)
Turkish, Turkey (tr_TR)
Ukrainian, Ukraine (uk_UA)
Vietnamese, Vietnam (vi_VN)
Chinese, PRC (zh_CN)
Chinese, Taiwan (zh_TW)

What are all the common ways to read a file in Ruby?

content = `cat file`

I think this method is the most "uncommon" one. Maybe it is kind of tricky, but it works if cat is installed.

Better way to right align text in HTML Table

The current draft of CSS Selectors Level 4 specifies structural selectors for grids. If implemented, we will be able to do things like:

th.price,
th.price || td {
    text-align: right;
}

Of course, that doesn't help us today -- the other answers here offer enough practical advice for that.

gridview data export to excel in asp.net

may be problem in data binding in export excel . check that data properly bin to a gridview or not.

Use this code for export grid view in excel sheet and note that you must add iTextSharp dll in you project.

protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;

        // Re-Bind data to GridView 

        using (CompMSEntities1 CompObj = new CompMSEntities1())
        {
            Start = Convert.ToDateTime(txtStart.Text);
            End = Convert.ToDateTime(txtEnd.Text);

            GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
            SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
            GridView1.DataBind();
           GridView1.Visible = true;
            ExportTable.Visible = true;
        }

        //Change the Header Row back to white color

        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");


       GridView1.Style.Add(" font-size", "10px");




        //Apply style to Individual Cells

        GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
        GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");

        for (int i = 1; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];

            //Change Color back to white

            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row

        //    row.Attributes.Add("class", "textmode");

            //Apply style to Individual Cells of Alternating Row

            if (i % 2 != 0)
            {
                row.Cells[0].Style.Add("background-color", "#C2D69B");
                row.Cells[1].Style.Add("background-color", "#C2D69B");
                row.Cells[2].Style.Add("background-color", "#C2D69B");
                row.Cells[3].Style.Add("background-color", "#C2D69B");
                row.Cells[4].Style.Add("background-color", "#C2D69B");
            }
        }
        GridView1.RenderControl(hw);

        //style to format numbers to string

        string style = @"<style> .textmode { mso-number-format:\@; } </style>";

        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

Breaking to a new line with inline-block?

Remove all br tags and use display: table.

.text span {
   background: rgba(165, 220, 79, 0.8);
   display: table;
   padding: 7px 10px;
   color: white;
}
.fullscreen .large { font-size: 80px }

Explanation: The table wraps the width of its content by default without setting a width, but is still a block level element. You can get the same behavior by setting a width to other block-level elements:

<span style="display:block;border:1px solid red;width:100px;">Like a default table.</span>
<code>null</code>

Notice the <code> element doesn't flow inline with the <span> like it would normally. Check it out with the computed styles in your dev tools. You'll see pseudo margin to the right of the <span>. Anyway, this is the same as the table, but the table has the added benefit of always forming to the width of its content.

Send Outlook Email Via Python?

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional

# To attach a file to the email (optional):
attachment  = "Path to the attachment"
mail.Attachments.Add(attachment)

mail.Send()

Will use your local outlook account to send.

Note if you are trying to do something not mentioned above, look at the COM docs properties/methods: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. In the code above, mail is a MailItem Object.

How to scroll to specific item using jQuery?

You can use the the jQuery scrollTo plugin plugin:

$('div').scrollTo('#row_8');

ie8 var w= window.open() - "Message: Invalid argument."

I also meet this issue while I used the following code:

window.open('test.html','Window title','width=1200,height=800,scrollbars=yes');

but when I delete the blank space of the "Window title" the below code is working:

window.open('test.html','Windowtitle','width=1200,height=800,scrollbars=yes');

Reverse a string in Python

This is simple and meaningful reverse function, easy to understand and code

def reverse_sentence(text):
    words = text.split(" ")
    reverse =""
    for word in reversed(words):
        reverse += word+ " "
    return reverse

Which Eclipse version should I use for an Android app?

I would recommend at least Eclipse Indigo (v 3.7) for Android Development because even though a minimum of Helios (v 3.6) is required for ADT 22.0.1 as explained here...

http://developer.android.com/tools/sdk/eclipse-adt.html

... Indigo is required for Android NDK development using CDT, as explained here:

http://tools.android.com/recent/usingthendkplugin

Create component to specific module with Angular-CLI

1.- Create your feature module as usual.

ng generate module dirlevel1/module-name

2.- You can specify the ROOT PATH of your project in --module ( only in --module, (/) root points to your PROJECT ROOT and IS NOT THE SYSTEM ROOT!!!)

ng generate component dirlevel1/component-name --module /src/app/dirlevel1/module-name.module.ts

Real Example:

ng generate module stripe/payment-methods-list
ng generate component stripe/payment-methods-list --module=/src/app/stripe/payment-methods-list/payment-methods-list.module.ts 

Output:

CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.scss (0 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.html (39 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.spec.ts (768 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.ts (322 bytes)
UPDATE src/app/stripe/payment-methods-list/payment-methods-list.module.ts (311 bytes)
[OK] Generated component!

Tested with Angular CLI: 9.1.4

Compare two Timestamp in java

java.util.Date mytime = null;
if (mytime.after(now) && mytime.before(last_download_time) )

Worked for me

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Get started with Latex on Linux

I would recommend start using Lyx, with that you can use Latex just as easy as OOO-Writer. It gives you the possibility to step into Latex deeper by manually adding Latex-Code to your Document. PDF is just one klick away after installatioin. Lyx is cross-plattform.

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Truncate Two decimal places without rounding

This is an old question, but many anwsers don't perform well or overflow for big numbers. I think D. Nesterov answer is the best one: robust, simple and fast. I just want to add my two cents. I played around with decimals and also checked out the source code. From the public Decimal (int lo, int mid, int hi, bool isNegative, byte scale) constructor documentation.

The binary representation of a Decimal number consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the integer number and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10 raised to an exponent ranging from 0 to 28.

Knowing this, my first approach was to create another decimal whose scale corresponds to the decimals that I wanted to discard, then truncate it and finally create a decimal with the desired scale.

private const int ScaleMask = 0x00FF0000;
    public static Decimal Truncate(decimal target, byte decimalPlaces)
    {
        var bits = Decimal.GetBits(target);
        var scale = (byte)((bits[3] & (ScaleMask)) >> 16);

        if (scale <= decimalPlaces)
            return target;

        var temporalDecimal = new Decimal(bits[0], bits[1], bits[2], target < 0, (byte)(scale - decimalPlaces));
        temporalDecimal = Math.Truncate(temporalDecimal);

        bits = Decimal.GetBits(temporalDecimal);
        return new Decimal(bits[0], bits[1], bits[2], target < 0, decimalPlaces);
    }

This method is not faster than D. Nesterov's and it is more complex, so I played around a little bit more. My guess is that having to create an auxiliar decimal and retrieving the bits twice is making it slower. On my second attempt, I manipulated the components returned by Decimal.GetBits(Decimal d) method myself. The idea is to divide the components by 10 as many times as needed and reduce the scale. The code is based (heavily) on the Decimal.InternalRoundFromZero(ref Decimal d, int decimalCount) method.

private const Int32 MaxInt32Scale = 9;
private const int ScaleMask = 0x00FF0000;
    private const int SignMask = unchecked((int)0x80000000);
    // Fast access for 10^n where n is 0-9        
    private static UInt32[] Powers10 = new UInt32[] {
        1,
        10,
        100,
        1000,
        10000,
        100000,
        1000000,
        10000000,
        100000000,
        1000000000
    };

    public static Decimal Truncate(decimal target, byte decimalPlaces)
    {
        var bits = Decimal.GetBits(target);
        int lo = bits[0];
        int mid = bits[1];
        int hi = bits[2];
        int flags = bits[3];

        var scale = (byte)((flags & (ScaleMask)) >> 16);
        int scaleDifference = scale - decimalPlaces;
        if (scaleDifference <= 0)
            return target;

        // Divide the value by 10^scaleDifference
        UInt32 lastDivisor;
        do
        {
            Int32 diffChunk = (scaleDifference > MaxInt32Scale) ? MaxInt32Scale : scaleDifference;
            lastDivisor = Powers10[diffChunk];
            InternalDivRemUInt32(ref lo, ref mid, ref hi, lastDivisor);
            scaleDifference -= diffChunk;
        } while (scaleDifference > 0);


        return new Decimal(lo, mid, hi, (flags & SignMask)!=0, decimalPlaces);
    }
    private static UInt32 InternalDivRemUInt32(ref int lo, ref int mid, ref int hi, UInt32 divisor)
    {
        UInt32 remainder = 0;
        UInt64 n;
        if (hi != 0)
        {
            n = ((UInt32)hi);
            hi = (Int32)((UInt32)(n / divisor));
            remainder = (UInt32)(n % divisor);
        }
        if (mid != 0 || remainder != 0)
        {
            n = ((UInt64)remainder << 32) | (UInt32)mid;
            mid = (Int32)((UInt32)(n / divisor));
            remainder = (UInt32)(n % divisor);
        }
        if (lo != 0 || remainder != 0)
        {
            n = ((UInt64)remainder << 32) | (UInt32)lo;
            lo = (Int32)((UInt32)(n / divisor));
            remainder = (UInt32)(n % divisor);
        }
        return remainder;
    }

I haven't performed rigorous performance tests, but on a MacOS Sierra 10.12.6, 3,06 GHz Intel Core i3 processor and targeting .NetCore 2.1 this method seems to be much faster than D. Nesterov's (I won't give numbers since, as I have mentioned, my tests are not rigorous). It is up to whoever implements this to evaluate whether or not the performance gains pay off for the added code complexity.

Count multiple columns with group by in one query

You didn't say which database server you are using, but if temp tables are available they may be the best approach.

// table is a temp table
select ... into #table ....
SELECT COUNT(column1),column1 FROM #table GROUP BY column1  
SELECT COUNT(column2),column2 FROM #table GROUP BY column2  
SELECT COUNT(column3),column3 FROM #table GROUP BY column3  
// drop may not be required
drop table #table

java.math.BigInteger cannot be cast to java.lang.Long

It's a very old post, but if it benefits anyone, we can do something like this:

Long max=((BigInteger) Collections.max(dynamics)).longValue(); 

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

How do I get the path of a process in Unix / Linux

Find the path to a process name

#!/bin/bash
# @author Lukas Gottschall
PID=`ps aux | grep precessname | grep -v grep | awk '{ print $2 }'`
PATH=`ls -ald --color=never /proc/$PID/exe | awk '{ print $10 }'`
echo $PATH

How to store custom objects in NSUserDefaults

Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults to save and retrieve custom objects:

@interface NSUserDefaults (NSUserDefaultsExtensions)

- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;

@end


@implementation NSUserDefaults (NSUserDefaultsExtensions)


- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [self setObject:encodedObject forKey:key];
    [self synchronize];

}

- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
    NSData *encodedObject = [self objectForKey:key];
    id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

@end

Usage:

[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];

Regex to match 2 digits, optional decimal, two digits

To build on Lee's answer, you need to anchor the expression to satisfy the requirement of not having more than 2 numbers before the decimal.

If each number is a separate string, you can use the string anchors:

^\d{0,2}(\.\d{1,2})?$

If each number is within a string, you can use the word anchors:

\b\d{0,2}(\.\d{1,2})?\b

How can I display a messagebox in ASP.NET?

@freelancer If you are using ScriptManager then try this code for message..

string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(), 
                      "ServerControlScript", script, true);

How to get only time from date-time C#

You might want to look into the DateTime.ToShortTimeString() method.

Also, there many other methods and properties on the DateTime object that can help you in formating the date or time in any way you like. Just take a look at the documentation.

How to select a drop-down menu value with Selenium using Python?

from selenium.webdriver.support.ui import Select
driver = webdriver.Ie(".\\IEDriverServer.exe")
driver.get("https://test.com")
select = Select(driver.find_element_by_xpath("""//input[@name='n_name']"""))
select.select_by_index(2)

It will work fine

JUnit Eclipse Plugin?

You should be able to add the Java Development Tools by selecting 'Help' -> 'Install New Software', there you select the 'Juno' update site, then 'Programming Languages' -> 'Eclipse Java Development Tools'.

After that, you will be able to run your JUnit tests with 'Right Click' -> 'Run as' -> 'JUnit test'.

How can one change the timestamp of an old commit in Git?

After reading all the answers I came up with a more succinct and convenient way of editing the date of multiple commits at once without the need of rebasing interactively:

git rebase HEAD~4 --exec "git commit --amend --no-edit --date 'now'"

It changes both the committer and author dates.

Is it possible to declare a variable in Gradle usable in Java?

I'm using this code and working very fine.

def baseUrl = '\"http://patelwala.com/myapi/"'
def googleServerKey = '\"87171841097-opu71rk2ps35ibv96ud57g3ktto6ioio.apps.googleusercontent.com"'
android {
  buildTypes {
  release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
    releasedebug {
        initWith debug
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id' ,googleServerKey
    }
    debug {

        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
 }
}

}

How do I make this file.sh executable via double click?

Remove the extension altogether and then double-click it. Most system shell scripts are like this. As long as it has a shebang it will work.

What process is listening on a certain port on Solaris?

You might not want to, but your best bet is to grab the sunfreeware CD and install lsof.

Other than that, yes you can grovel around in /proc with a shell script.

How can I execute a PHP function in a form action?

It's better something like this...post the data to the self page and maybe do a check on user input.

   <?php
    require_once ( 'username.php' );

    if(isset($_POST)) {
      echo "form post"; // ex $_POST['textfield']
    }


    echo '
    <form name="form1" method="post" action="' . $_SERVER['PHP_SELF'] . '">
      <p>
        <label>
          <input type="text" name="textfield" id="textfield">
        </label>
      </p>
      <p>
        <label>
          <input type="submit" name="button" id="button" value="Submit">
        </label>
      </p>
    </form>';
    ?>

Error Installing Homebrew - Brew Command Not Found

try this

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/linuxbrew/go/install)"